From 74080d1f344e6dd256df03bdf79a0f159d70c066 Mon Sep 17 00:00:00 2001
From: PureCloud Jenkins
Date: Tue, 11 May 2021 08:46:37 +0000
Subject: [PATCH] 7.1.0
---
README.md | 84 +-
build/README.md | 84 +-
.../dist/node/purecloud-guest-chat-client.js | 444 +-
.../web-amd/purecloud-guest-chat-client.js | 444 +-
.../purecloud-guest-chat-client.min.js | 2 +-
build/dist/web-cjs/bundle.js | 444 +-
.../web-cjs/purecloud-guest-chat-client.js | 36022 ++--------------
.../purecloud-guest-chat-client.min.js | 2 +-
build/docs/index.md | 84 +-
build/docs/releaseNotes.md | 2 +-
build/index.d.ts | 3 +-
.../@dabh/diagnostics/CHANGELOG.md | 26 -
build/node_modules/@dabh/diagnostics/LICENSE | 20 -
.../node_modules/@dabh/diagnostics/README.md | 473 -
.../@dabh/diagnostics/adapters/hash.js | 11 -
.../@dabh/diagnostics/adapters/index.js | 18 -
.../diagnostics/adapters/localstorage.js | 11 -
.../@dabh/diagnostics/adapters/process.env.js | 11 -
.../@dabh/diagnostics/browser/development.js | 35 -
.../@dabh/diagnostics/browser/index.js | 8 -
.../@dabh/diagnostics/browser/override.js | 6 -
.../@dabh/diagnostics/browser/production.js | 24 -
.../@dabh/diagnostics/diagnostics.js | 212 -
.../@dabh/diagnostics/example.png | Bin 310926 -> 0 bytes
.../@dabh/diagnostics/logger/console.js | 19 -
.../diagnostics/modifiers/namespace-ansi.js | 20 -
.../@dabh/diagnostics/modifiers/namespace.js | 32 -
.../@dabh/diagnostics/node/development.js | 36 -
.../@dabh/diagnostics/node/index.js | 8 -
.../@dabh/diagnostics/node/override.js | 21 -
.../@dabh/diagnostics/node/production.js | 24 -
.../@dabh/diagnostics/package.json | 101 -
.../node_modules/xtend/package.json | 2 +-
.../abstract-leveldown/package.json | 2 +-
build/node_modules/acorn/package.json | 4 +-
build/node_modules/array-filter/package.json | 2 +-
.../asn1.js/node_modules/bn.js/package.json | 4 +-
build/node_modules/asn1.js/package.json | 4 +-
build/node_modules/async/CHANGELOG.md | 331 -
build/node_modules/async/LICENSE | 19 -
build/node_modules/async/README.md | 60 -
build/node_modules/async/all.js | 54 -
build/node_modules/async/allLimit.js | 46 -
build/node_modules/async/allSeries.js | 45 -
build/node_modules/async/any.js | 56 -
build/node_modules/async/anyLimit.js | 47 -
build/node_modules/async/anySeries.js | 46 -
build/node_modules/async/apply.js | 55 -
build/node_modules/async/applyEach.js | 57 -
build/node_modules/async/applyEachSeries.js | 37 -
build/node_modules/async/asyncify.js | 118 -
build/node_modules/async/auto.js | 267 -
build/node_modules/async/autoInject.js | 156 -
build/node_modules/async/bower.json | 17 -
build/node_modules/async/cargo.js | 63 -
build/node_modules/async/cargoQueue.js | 71 -
build/node_modules/async/compose.js | 55 -
build/node_modules/async/concat.js | 47 -
build/node_modules/async/concatLimit.js | 60 -
build/node_modules/async/concatSeries.js | 41 -
build/node_modules/async/constant.js | 55 -
build/node_modules/async/detect.js | 61 -
build/node_modules/async/detectLimit.js | 48 -
build/node_modules/async/detectSeries.js | 47 -
build/node_modules/async/dir.js | 43 -
build/node_modules/async/dist/async.js | 4846 ---
build/node_modules/async/dist/async.min.js | 1 -
build/node_modules/async/dist/async.mjs | 4734 --
build/node_modules/async/doDuring.js | 68 -
build/node_modules/async/doUntil.js | 46 -
build/node_modules/async/doWhilst.js | 68 -
build/node_modules/async/during.js | 78 -
build/node_modules/async/each.js | 88 -
build/node_modules/async/eachLimit.js | 50 -
build/node_modules/async/eachOf.js | 116 -
build/node_modules/async/eachOfLimit.js | 47 -
build/node_modules/async/eachOfSeries.js | 39 -
build/node_modules/async/eachSeries.js | 44 -
build/node_modules/async/ensureAsync.js | 67 -
build/node_modules/async/every.js | 54 -
build/node_modules/async/everyLimit.js | 46 -
build/node_modules/async/everySeries.js | 45 -
build/node_modules/async/filter.js | 53 -
build/node_modules/async/filterLimit.js | 45 -
build/node_modules/async/filterSeries.js | 43 -
build/node_modules/async/find.js | 61 -
build/node_modules/async/findLimit.js | 48 -
build/node_modules/async/findSeries.js | 47 -
build/node_modules/async/flatMap.js | 47 -
build/node_modules/async/flatMapLimit.js | 60 -
build/node_modules/async/flatMapSeries.js | 41 -
build/node_modules/async/foldl.js | 77 -
build/node_modules/async/foldr.js | 41 -
build/node_modules/async/forEach.js | 88 -
build/node_modules/async/forEachLimit.js | 50 -
build/node_modules/async/forEachOf.js | 116 -
build/node_modules/async/forEachOfLimit.js | 47 -
build/node_modules/async/forEachOfSeries.js | 39 -
build/node_modules/async/forEachSeries.js | 44 -
build/node_modules/async/forever.js | 68 -
build/node_modules/async/groupBy.js | 54 -
build/node_modules/async/groupByLimit.js | 71 -
build/node_modules/async/groupBySeries.js | 36 -
build/node_modules/async/index.js | 588 -
build/node_modules/async/inject.js | 77 -
.../async/internal/DoublyLinkedList.js | 92 -
build/node_modules/async/internal/Heap.js | 120 -
.../node_modules/async/internal/applyEach.js | 29 -
.../async/internal/asyncEachOfLimit.js | 75 -
build/node_modules/async/internal/awaitify.js | 27 -
.../node_modules/async/internal/breakLoop.js | 10 -
.../async/internal/consoleFunc.js | 27 -
.../async/internal/createTester.js | 40 -
.../async/internal/eachOfLimit.js | 90 -
build/node_modules/async/internal/filter.js | 55 -
.../async/internal/getIterator.js | 11 -
.../async/internal/initialParams.js | 14 -
.../async/internal/isArrayLike.js | 10 -
build/node_modules/async/internal/iterator.js | 54 -
build/node_modules/async/internal/map.js | 30 -
build/node_modules/async/internal/once.js | 17 -
build/node_modules/async/internal/onlyOnce.js | 15 -
build/node_modules/async/internal/parallel.js | 34 -
.../async/internal/promiseCallback.js | 23 -
build/node_modules/async/internal/queue.js | 291 -
build/node_modules/async/internal/range.js | 14 -
build/node_modules/async/internal/reject.js | 26 -
.../async/internal/setImmediate.js | 30 -
.../async/internal/withoutIndex.js | 10 -
.../node_modules/async/internal/wrapAsync.js | 34 -
build/node_modules/async/log.js | 41 -
build/node_modules/async/map.js | 62 -
build/node_modules/async/mapLimit.js | 45 -
build/node_modules/async/mapSeries.js | 44 -
build/node_modules/async/mapValues.js | 62 -
build/node_modules/async/mapValuesLimit.js | 61 -
build/node_modules/async/mapValuesSeries.js | 37 -
build/node_modules/async/memoize.js | 91 -
build/node_modules/async/nextTick.js | 52 -
build/node_modules/async/package.json | 109 -
build/node_modules/async/parallel.js | 91 -
build/node_modules/async/parallelLimit.js | 41 -
build/node_modules/async/priorityQueue.js | 84 -
build/node_modules/async/queue.js | 167 -
build/node_modules/async/race.js | 67 -
build/node_modules/async/reduce.js | 77 -
build/node_modules/async/reduceRight.js | 41 -
build/node_modules/async/reflect.js | 78 -
build/node_modules/async/reflectAll.js | 93 -
build/node_modules/async/reject.js | 53 -
build/node_modules/async/rejectLimit.js | 45 -
build/node_modules/async/rejectSeries.js | 43 -
build/node_modules/async/retry.js | 159 -
build/node_modules/async/retryable.js | 77 -
build/node_modules/async/select.js | 53 -
build/node_modules/async/selectLimit.js | 45 -
build/node_modules/async/selectSeries.js | 43 -
build/node_modules/async/seq.js | 79 -
build/node_modules/async/series.js | 86 -
build/node_modules/async/setImmediate.js | 45 -
build/node_modules/async/some.js | 56 -
build/node_modules/async/someLimit.js | 47 -
build/node_modules/async/someSeries.js | 46 -
build/node_modules/async/sortBy.js | 88 -
build/node_modules/async/timeout.js | 89 -
build/node_modules/async/times.js | 50 -
build/node_modules/async/timesLimit.js | 43 -
build/node_modules/async/timesSeries.js | 32 -
build/node_modules/async/transform.js | 81 -
build/node_modules/async/tryEach.js | 78 -
build/node_modules/async/unmemoize.js | 25 -
build/node_modules/async/until.js | 61 -
build/node_modules/async/waterfall.js | 105 -
build/node_modules/async/whilst.js | 78 -
build/node_modules/async/wrapSync.js | 118 -
build/node_modules/asynckit/package.json | 2 +-
.../available-typed-arrays/package.json | 4 +-
.../bl/node_modules/isarray/package.json | 2 +-
.../node_modules/readable-stream/package.json | 2 +-
.../node_modules/string_decoder/package.json | 2 +-
build/node_modules/bl/package.json | 2 +-
build/node_modules/bn.js/package.json | 4 +-
build/node_modules/brorand/package.json | 2 +-
.../node_modules/browserify-aes/package.json | 4 +-
.../browserify-cipher/package.json | 4 +-
.../node_modules/browserify-des/package.json | 4 +-
build/node_modules/browserify-fs/package.json | 2 +-
.../node_modules/browserify-rsa/package.json | 4 +-
.../node_modules/readable-stream/package.json | 4 +-
.../node_modules/safe-buffer/package.json | 4 +-
.../node_modules/browserify-sign/package.json | 4 +-
build/node_modules/buffer-es6/package.json | 2 +-
build/node_modules/buffer-from/package.json | 4 +-
build/node_modules/buffer-xor/package.json | 2 +-
.../node_modules/builtin-modules/package.json | 4 +-
build/node_modules/call-bind/package.json | 4 +-
build/node_modules/cipher-base/package.json | 4 +-
build/node_modules/clone/package.json | 2 +-
build/node_modules/color-convert/CHANGELOG.md | 54 -
build/node_modules/color-convert/LICENSE | 21 -
build/node_modules/color-convert/README.md | 68 -
.../node_modules/color-convert/conversions.js | 868 -
build/node_modules/color-convert/index.js | 78 -
build/node_modules/color-convert/package.json | 81 -
build/node_modules/color-convert/route.js | 97 -
build/node_modules/color-name/.eslintrc.json | 43 -
build/node_modules/color-name/.npmignore | 107 -
build/node_modules/color-name/LICENSE | 8 -
build/node_modules/color-name/README.md | 11 -
build/node_modules/color-name/index.js | 152 -
build/node_modules/color-name/package.json | 54 -
build/node_modules/color-name/test.js | 7 -
build/node_modules/color-string/CHANGELOG.md | 18 -
build/node_modules/color-string/LICENSE | 21 -
build/node_modules/color-string/README.md | 58 -
build/node_modules/color-string/index.js | 234 -
build/node_modules/color-string/package.json | 81 -
build/node_modules/color/LICENSE | 21 -
build/node_modules/color/README.md | 114 -
build/node_modules/color/index.js | 479 -
build/node_modules/color/package.json | 72 -
build/node_modules/colors/LICENSE | 25 -
build/node_modules/colors/README.md | 221 -
.../colors/examples/normal-usage.js | 82 -
.../colors/examples/safe-string.js | 79 -
build/node_modules/colors/index.d.ts | 136 -
build/node_modules/colors/lib/colors.js | 211 -
build/node_modules/colors/lib/custom/trap.js | 46 -
build/node_modules/colors/lib/custom/zalgo.js | 110 -
.../colors/lib/extendStringPrototype.js | 110 -
build/node_modules/colors/lib/index.js | 13 -
build/node_modules/colors/lib/maps/america.js | 10 -
build/node_modules/colors/lib/maps/rainbow.js | 12 -
build/node_modules/colors/lib/maps/random.js | 11 -
build/node_modules/colors/lib/maps/zebra.js | 5 -
build/node_modules/colors/lib/styles.js | 95 -
.../colors/lib/system/has-flag.js | 35 -
.../colors/lib/system/supports-colors.js | 151 -
build/node_modules/colors/package.json | 74 -
build/node_modules/colors/safe.d.ts | 48 -
build/node_modules/colors/safe.js | 10 -
.../colors/themes/generic-logging.js | 12 -
build/node_modules/colorspace/LICENSE.md | 20 -
build/node_modules/colorspace/README.md | 43 -
build/node_modules/colorspace/index.js | 29 -
build/node_modules/colorspace/package.json | 64 -
build/node_modules/colorspace/test.js | 14 -
.../node_modules/combined-stream/package.json | 4 +-
build/node_modules/commander/package.json | 2 +-
.../component-emitter/package.json | 4 +-
build/node_modules/concat-stream/package.json | 4 +-
.../configparser/.circleci/config.yml | 85 -
build/node_modules/configparser/package.json | 62 -
build/node_modules/configparser/readme.md | 59 -
.../configparser/src/configparser.js | 289 -
build/node_modules/configparser/src/errors.js | 76 -
.../configparser/src/interpolation.js | 56 -
.../configparser/test/configparser.js | 83 -
.../configparser/test/data/file.ini | 38 -
.../configparser/typings/configparser.d.ts | 24 -
build/node_modules/cookiejar/package.json | 4 +-
build/node_modules/core-util-is/package.json | 2 +-
.../node_modules/bn.js/package.json | 4 +-
build/node_modules/create-ecdh/package.json | 4 +-
build/node_modules/create-hash/package.json | 4 +-
build/node_modules/create-hmac/package.json | 4 +-
.../crypto-browserify/package.json | 4 +-
build/node_modules/debug/package.json | 4 +-
.../deferred-leveldown/package.json | 2 +-
.../node_modules/object-keys/package.json | 4 +-
.../define-properties/package.json | 4 +-
.../node_modules/delayed-stream/package.json | 2 +-
build/node_modules/des.js/package.json | 4 +-
build/node_modules/diff/package.json | 2 +-
.../node_modules/bn.js/package.json | 4 +-
.../node_modules/diffie-hellman/package.json | 4 +-
.../elliptic/node_modules/bn.js/package.json | 4 +-
build/node_modules/elliptic/package.json | 4 +-
build/node_modules/enabled/.travis.yml | 9 -
build/node_modules/enabled/LICENSE | 20 -
build/node_modules/enabled/README.md | 68 -
build/node_modules/enabled/index.js | 34 -
build/node_modules/enabled/package.json | 64 -
build/node_modules/enabled/test.js | 39 -
build/node_modules/errno/package.json | 4 +-
.../node_modules/object-keys/package.json | 4 +-
build/node_modules/es-abstract/package.json | 4 +-
.../node_modules/es-to-primitive/package.json | 4 +-
.../escape-string-regexp/package.json | 2 +-
build/node_modules/estree-walker/package.json | 4 +-
.../node_modules/evp_bytestokey/package.json | 4 +-
build/node_modules/expect.js/package.json | 2 +-
build/node_modules/extend/package.json | 4 +-
.../fast-safe-stringify/.travis.yml | 8 -
.../fast-safe-stringify/CHANGELOG.md | 17 -
.../node_modules/fast-safe-stringify/LICENSE | 23 -
.../fast-safe-stringify/benchmark.js | 137 -
.../fast-safe-stringify/index.d.ts | 8 -
.../node_modules/fast-safe-stringify/index.js | 161 -
.../fast-safe-stringify/package.json | 87 -
.../fast-safe-stringify/readme.md | 154 -
.../fast-safe-stringify/test-stable.js | 311 -
.../node_modules/fast-safe-stringify/test.js | 304 -
build/node_modules/fecha/CHANGELOG.md | 71 -
build/node_modules/fecha/LICENSE | 22 -
build/node_modules/fecha/README.md | 320 -
build/node_modules/fecha/dist/fecha.min.js | 2 -
.../node_modules/fecha/dist/fecha.min.js.map | 1 -
build/node_modules/fecha/lib/fecha.d.ts | 52 -
build/node_modules/fecha/lib/fecha.js | 386 -
build/node_modules/fecha/lib/fecha.js.map | 1 -
build/node_modules/fecha/lib/fecha.umd.js | 401 -
build/node_modules/fecha/lib/fecha.umd.js.map | 1 -
build/node_modules/fecha/package.json | 82 -
build/node_modules/fecha/src/fecha.ts | 506 -
build/node_modules/fn.name/.gitattributes | 1 -
build/node_modules/fn.name/.travis.yml | 10 -
build/node_modules/fn.name/LICENSE | 22 -
build/node_modules/fn.name/README.md | 42 -
build/node_modules/fn.name/index.js | 42 -
build/node_modules/fn.name/package.json | 64 -
build/node_modules/fn.name/test.js | 73 -
build/node_modules/foreach/package.json | 2 +-
build/node_modules/form-data/package.json | 4 +-
build/node_modules/formatio/package.json | 2 +-
build/node_modules/formidable/package.json | 4 +-
build/node_modules/function-bind/package.json | 4 +-
.../node_modules/isarray/package.json | 2 +-
.../node_modules/readable-stream/package.json | 2 +-
.../node_modules/string_decoder/package.json | 2 +-
build/node_modules/fwd-stream/package.json | 2 +-
build/node_modules/get-intrinsic/package.json | 4 +-
build/node_modules/glob/package.json | 2 +-
build/node_modules/graceful-fs/package.json | 2 +-
build/node_modules/growl/package.json | 2 +-
build/node_modules/has-bigints/package.json | 4 +-
build/node_modules/has-symbols/package.json | 4 +-
build/node_modules/has/package.json | 4 +-
.../node_modules/readable-stream/package.json | 4 +-
.../node_modules/safe-buffer/package.json | 4 +-
build/node_modules/hash-base/package.json | 4 +-
build/node_modules/hash.js/package.json | 4 +-
build/node_modules/hmac-drbg/package.json | 2 +-
build/node_modules/idb-wrapper/package.json | 4 +-
build/node_modules/indexof/package.json | 2 +-
build/node_modules/inherits/package.json | 7 +-
build/node_modules/is-arguments/package.json | 4 +-
build/node_modules/is-arrayish/LICENSE | 21 -
build/node_modules/is-arrayish/README.md | 16 -
build/node_modules/is-arrayish/index.js | 9 -
build/node_modules/is-arrayish/package.json | 77 -
build/node_modules/is-arrayish/yarn-error.log | 1443 -
build/node_modules/is-bigint/package.json | 4 +-
.../is-boolean-object/package.json | 4 +-
build/node_modules/is-callable/package.json | 4 +-
.../node_modules/is-core-module/package.json | 4 +-
.../node_modules/is-date-object/package.json | 4 +-
.../is-generator-function/package.json | 4 +-
build/node_modules/is-module/package.json | 2 +-
.../is-negative-zero/package.json | 4 +-
.../is-number-object/package.json | 4 +-
build/node_modules/is-object/package.json | 2 +-
build/node_modules/is-regex/package.json | 4 +-
build/node_modules/is-stream/index.d.ts | 80 -
build/node_modules/is-stream/index.js | 29 -
build/node_modules/is-stream/license | 9 -
build/node_modules/is-stream/package.json | 73 -
build/node_modules/is-stream/readme.md | 57 -
build/node_modules/is-string/package.json | 4 +-
build/node_modules/is-symbol/package.json | 4 +-
.../node_modules/is-typed-array/package.json | 4 +-
build/node_modules/is/package.json | 2 +-
build/node_modules/isarray/package.json | 2 +-
build/node_modules/isbuffer/package.json | 2 +-
.../jade/node_modules/commander/package.json | 2 +-
.../jade/node_modules/mkdirp/package.json | 2 +-
build/node_modules/jade/package.json | 2 +-
build/node_modules/kuler/.travis.yml | 5 -
build/node_modules/kuler/LICENSE | 7 -
build/node_modules/kuler/README.md | 40 -
build/node_modules/kuler/index.js | 118 -
build/node_modules/kuler/package.json | 61 -
build/node_modules/kuler/test.js | 23 -
.../node_modules/isarray/package.json | 2 +-
.../node_modules/readable-stream/package.json | 2 +-
.../node_modules/string_decoder/package.json | 2 +-
build/node_modules/level-blobs/package.json | 2 +-
.../level-filesystem/package.json | 2 +-
.../node_modules/level-fix-range/package.json | 2 +-
build/node_modules/level-hooks/package.json | 2 +-
.../node_modules/object-keys/package.json | 2 +-
.../level-js/node_modules/xtend/package.json | 2 +-
build/node_modules/level-js/package.json | 2 +-
build/node_modules/level-peek/package.json | 2 +-
.../node_modules/level-fix-range/package.json | 2 +-
.../node_modules/xtend/package.json | 2 +-
.../node_modules/level-sublevel/package.json | 2 +-
.../levelup/node_modules/isarray/package.json | 2 +-
.../levelup/node_modules/prr/package.json | 2 +-
.../node_modules/readable-stream/package.json | 2 +-
.../node_modules/string_decoder/package.json | 2 +-
.../levelup/node_modules/xtend/package.json | 2 +-
build/node_modules/levelup/package.json | 2 +-
build/node_modules/logform/.babelrc | 3 -
build/node_modules/logform/.eslintrc | 7 -
build/node_modules/logform/.gitattributes | 1 -
build/node_modules/logform/.travis.yml | 17 -
build/node_modules/logform/CHANGELOG.md | 232 -
build/node_modules/logform/LICENSE | 21 -
build/node_modules/logform/README.md | 655 -
build/node_modules/logform/align.js | 14 -
build/node_modules/logform/browser.js | 36 -
build/node_modules/logform/cli.js | 52 -
build/node_modules/logform/colorize.js | 122 -
build/node_modules/logform/combine.js | 66 -
build/node_modules/logform/dist/align.js | 15 -
build/node_modules/logform/dist/browser.js | 66 -
build/node_modules/logform/dist/cli.js | 73 -
build/node_modules/logform/dist/colorize.js | 144 -
build/node_modules/logform/dist/combine.js | 71 -
build/node_modules/logform/dist/errors.js | 43 -
build/node_modules/logform/dist/format.js | 87 -
build/node_modules/logform/dist/index.js | 54 -
build/node_modules/logform/dist/json.js | 33 -
build/node_modules/logform/dist/label.js | 20 -
build/node_modules/logform/dist/levels.js | 14 -
build/node_modules/logform/dist/logstash.js | 34 -
build/node_modules/logform/dist/metadata.js | 64 -
build/node_modules/logform/dist/ms.js | 21 -
build/node_modules/logform/dist/pad-levels.js | 127 -
.../node_modules/logform/dist/pretty-print.js | 34 -
build/node_modules/logform/dist/printf.js | 41 -
build/node_modules/logform/dist/simple.js | 37 -
build/node_modules/logform/dist/splat.js | 159 -
build/node_modules/logform/dist/timestamp.js | 32 -
build/node_modules/logform/dist/uncolorize.js | 31 -
build/node_modules/logform/errors.js | 39 -
.../node_modules/logform/examples/combine.js | 14 -
build/node_modules/logform/examples/filter.js | 30 -
.../node_modules/logform/examples/invalid.js | 6 -
.../node_modules/logform/examples/metadata.js | 78 -
.../logform/examples/padLevels.js | 39 -
build/node_modules/logform/examples/volume.js | 25 -
build/node_modules/logform/format.js | 52 -
build/node_modules/logform/index.d.ts | 161 -
build/node_modules/logform/index.js | 53 -
build/node_modules/logform/json.js | 30 -
build/node_modules/logform/label.js | 19 -
build/node_modules/logform/levels.js | 12 -
build/node_modules/logform/logstash.js | 29 -
build/node_modules/logform/metadata.js | 61 -
build/node_modules/logform/ms.js | 18 -
build/node_modules/logform/package.json | 76 -
build/node_modules/logform/pad-levels.js | 83 -
build/node_modules/logform/pretty-print.js | 29 -
build/node_modules/logform/printf.js | 26 -
build/node_modules/logform/simple.js | 33 -
build/node_modules/logform/splat.js | 132 -
build/node_modules/logform/timestamp.js | 30 -
build/node_modules/logform/tsconfig.json | 22 -
build/node_modules/logform/uncolorize.js | 27 -
build/node_modules/lolex/package.json | 2 +-
build/node_modules/lru-cache/package.json | 2 +-
build/node_modules/ltgt/package.json | 2 +-
build/node_modules/magic-string/package.json | 4 +-
build/node_modules/md5.js/package.json | 4 +-
build/node_modules/methods/package.json | 2 +-
.../node_modules/bn.js/package.json | 4 +-
build/node_modules/miller-rabin/package.json | 4 +-
build/node_modules/mime-db/package.json | 4 +-
build/node_modules/mime-types/package.json | 4 +-
build/node_modules/mime/package.json | 4 +-
.../minimalistic-assert/package.json | 4 +-
.../minimalistic-crypto-utils/package.json | 2 +-
build/node_modules/minimatch/package.json | 2 +-
build/node_modules/minimist/.travis.yml | 4 -
build/node_modules/minimist/example/parse.js | 2 +-
build/node_modules/minimist/index.js | 166 +-
build/node_modules/minimist/package.json | 26 +-
build/node_modules/minimist/readme.markdown | 34 +-
build/node_modules/minimist/test/all_bool.js | 32 -
build/node_modules/minimist/test/bool.js | 178 -
build/node_modules/minimist/test/dash.js | 7 -
.../minimist/test/default_bool.js | 15 -
build/node_modules/minimist/test/dotted.js | 6 -
build/node_modules/minimist/test/kv_short.js | 16 -
build/node_modules/minimist/test/num.js | 36 -
build/node_modules/minimist/test/parse.js | 167 +-
.../minimist/test/parse_modified.js | 2 +-
build/node_modules/minimist/test/proto.js | 44 -
.../node_modules/minimist/test/stop_early.js | 15 -
build/node_modules/minimist/test/unknown.js | 102 -
.../node_modules => }/mkdirp/.npmignore | 0
.../node_modules => }/mkdirp/.travis.yml | 0
.../node_modules => }/mkdirp/examples/pow.js | 0
build/node_modules/mkdirp/index.js | 6 +-
build/node_modules/mkdirp/package.json | 43 +-
build/node_modules/mkdirp/readme.markdown | 4 +-
.../node_modules => }/mkdirp/test/chmod.js | 0
.../node_modules => }/mkdirp/test/clobber.js | 0
.../node_modules => }/mkdirp/test/mkdirp.js | 0
.../node_modules => }/mkdirp/test/opts_fs.js | 0
.../mkdirp/test/opts_fs_sync.js | 0
.../node_modules => }/mkdirp/test/perm.js | 0
.../mkdirp/test/perm_sync.js | 0
.../node_modules => }/mkdirp/test/race.js | 0
.../node_modules => }/mkdirp/test/rel.js | 0
.../node_modules => }/mkdirp/test/return.js | 0
.../mkdirp/test/return_sync.js | 0
.../node_modules => }/mkdirp/test/root.js | 0
.../node_modules => }/mkdirp/test/sync.js | 0
.../node_modules => }/mkdirp/test/umask.js | 0
.../mkdirp/test/umask_sync.js | 0
.../mocha/node_modules/.bin/mkdirp | 1 -
.../mocha/node_modules/debug/package.json | 2 +-
.../mocha/node_modules/minimist/.travis.yml | 4 -
.../mocha/node_modules/minimist/LICENSE | 18 -
.../node_modules/minimist/example/parse.js | 2 -
.../mocha/node_modules/minimist/index.js | 187 -
.../mocha/node_modules/minimist/package.json | 71 -
.../node_modules/minimist/readme.markdown | 73 -
.../mocha/node_modules/minimist/test/dash.js | 24 -
.../minimist/test/default_bool.js | 20 -
.../node_modules/minimist/test/dotted.js | 16 -
.../mocha/node_modules/minimist/test/long.js | 31 -
.../mocha/node_modules/minimist/test/parse.js | 318 -
.../minimist/test/parse_modified.js | 9 -
.../mocha/node_modules/minimist/test/short.js | 67 -
.../node_modules/minimist/test/whitespace.js | 8 -
.../mocha/node_modules/mkdirp/LICENSE | 21 -
.../mocha/node_modules/mkdirp/bin/cmd.js | 33 -
.../mocha/node_modules/mkdirp/bin/usage.txt | 12 -
.../mocha/node_modules/mkdirp/index.js | 97 -
.../mocha/node_modules/mkdirp/package.json | 62 -
.../mocha/node_modules/mkdirp/readme.markdown | 100 -
.../mocha/node_modules/ms/package.json | 2 +-
build/node_modules/mocha/package.json | 2 +-
build/node_modules/ms/package.json | 7 +-
.../node_modules/object-inspect/package.json | 4 +-
build/node_modules/object-keys/package.json | 2 +-
.../node_modules/object-keys/package.json | 4 +-
build/node_modules/object.assign/package.json | 4 +-
build/node_modules/octal/package.json | 2 +-
build/node_modules/once/package.json | 2 +-
build/node_modules/one-time/LICENSE | 22 -
build/node_modules/one-time/README.md | 88 -
build/node_modules/one-time/async.js | 43 -
build/node_modules/one-time/index.js | 42 -
build/node_modules/one-time/package.json | 65 -
build/node_modules/parse-asn1/package.json | 4 +-
build/node_modules/path-parse/package.json | 4 +-
build/node_modules/pbkdf2/package.json | 4 +-
build/node_modules/process-es6/package.json | 2 +-
.../process-nextick-args/package.json | 4 +-
build/node_modules/prr/package.json | 2 +-
.../node_modules/bn.js/package.json | 4 +-
.../node_modules/public-encrypt/package.json | 4 +-
build/node_modules/qs/package.json | 4 +-
build/node_modules/randombytes/package.json | 4 +-
build/node_modules/randomfill/package.json | 4 +-
.../node_modules/readable-stream/package.json | 7 +-
build/node_modules/resolve/package.json | 4 +-
build/node_modules/ripemd160/package.json | 4 +-
.../rollup-plugin-commonjs/package.json | 4 +-
.../rollup-plugin-json/package.json | 4 +-
.../rollup-plugin-node-builtins/package.json | 2 +-
.../node_modules/estree-walker/package.json | 4 +-
.../node_modules/magic-string/package.json | 4 +-
.../rollup-plugin-node-globals/package.json | 4 +-
.../rollup-plugin-node-resolve/package.json | 4 +-
.../node_modules/magic-string/package.json | 2 +-
.../rollup-plugin-re/package.json | 2 +-
.../rollup-pluginutils/package.json | 4 +-
build/node_modules/safe-buffer/package.json | 4 +-
build/node_modules/safer-buffer/package.json | 4 +-
build/node_modules/samsam/package.json | 2 +-
build/node_modules/semver/package.json | 2 +-
build/node_modules/sha.js/package.json | 4 +-
build/node_modules/side-channel/package.json | 4 +-
build/node_modules/sigmund/package.json | 2 +-
build/node_modules/simple-swizzle/LICENSE | 21 -
build/node_modules/simple-swizzle/README.md | 39 -
build/node_modules/simple-swizzle/index.js | 29 -
.../node_modules/simple-swizzle/package.json | 71 -
build/node_modules/sinon/package.json | 2 +-
.../node_modules/sourcemap-codec/package.json | 4 +-
build/node_modules/stack-trace/.npmignore | 1 -
build/node_modules/stack-trace/License | 19 -
build/node_modules/stack-trace/Makefile | 11 -
build/node_modules/stack-trace/Readme.md | 98 -
.../stack-trace/lib/stack-trace.js | 136 -
build/node_modules/stack-trace/package.json | 53 -
build/node_modules/string-range/package.json | 2 +-
.../string.prototype.trimend/package.json | 4 +-
.../string.prototype.trimstart/package.json | 4 +-
.../node_modules/string_decoder/package.json | 7 +-
build/node_modules/superagent/package.json | 4 +-
.../node_modules/supports-color/package.json | 2 +-
build/node_modules/text-hex/LICENSE | 21 -
build/node_modules/text-hex/README.md | 20 -
build/node_modules/text-hex/index.js | 24 -
build/node_modules/text-hex/package.json | 57 -
build/node_modules/text-hex/test.js | 11 -
build/node_modules/triple-beam/.eslintrc | 7 -
build/node_modules/triple-beam/.gitattributes | 1 -
build/node_modules/triple-beam/.travis.yml | 17 -
build/node_modules/triple-beam/CHANGELOG.md | 22 -
build/node_modules/triple-beam/LICENSE | 21 -
build/node_modules/triple-beam/README.md | 34 -
build/node_modules/triple-beam/config/cli.js | 42 -
.../node_modules/triple-beam/config/index.js | 32 -
build/node_modules/triple-beam/config/npm.js | 36 -
.../node_modules/triple-beam/config/syslog.js | 38 -
build/node_modules/triple-beam/index.js | 46 -
build/node_modules/triple-beam/package.json | 66 -
build/node_modules/triple-beam/test.js | 98 -
.../typedarray-to-buffer/package.json | 2 +-
build/node_modules/typedarray/package.json | 2 +-
.../node_modules/unbox-primitive/package.json | 4 +-
.../node_modules/util-deprecate/package.json | 5 +-
build/node_modules/util/package.json | 4 +-
build/node_modules/vlq/package.json | 4 +-
.../which-boxed-primitive/package.json | 4 +-
.../which-typed-array/package.json | 4 +-
build/node_modules/winston-transport/.babelrc | 3 -
.../node_modules/winston-transport/.eslintrc | 7 -
.../winston-transport/.gitattributes | 1 -
.../1c69f3e4-4c25-457d-9df5-dfa761729528.json | 1 -
.../1c69f3e4-4c25-457d-9df5-dfa761729528.json | 1 -
.../.nyc_output/processinfo/index.json | 1 -
.../winston-transport/.travis.yml | 17 -
.../winston-transport/CHANGELOG.md | 115 -
build/node_modules/winston-transport/LICENSE | 22 -
.../node_modules/winston-transport/README.md | 50 -
.../winston-transport/dist/index.js | 215 -
.../winston-transport/dist/legacy.js | 116 -
.../node_modules/winston-transport/index.d.ts | 37 -
build/node_modules/winston-transport/index.js | 215 -
.../node_modules/winston-transport/legacy.js | 119 -
.../winston-transport/package.json | 78 -
.../winston-transport/tsconfig.json | 22 -
build/node_modules/winston/CHANGELOG.md | 560 -
build/node_modules/winston/LICENSE | 19 -
build/node_modules/winston/README.md | 1230 -
build/node_modules/winston/dist/winston.js | 172 -
.../winston/dist/winston/common.js | 56 -
.../winston/dist/winston/config/index.js | 37 -
.../winston/dist/winston/container.js | 147 -
.../winston/dist/winston/create-logger.js | 141 -
.../winston/dist/winston/exception-handler.js | 288 -
.../winston/dist/winston/exception-stream.js | 94 -
.../winston/dist/winston/logger.js | 752 -
.../winston/dist/winston/profiler.js | 69 -
.../winston/dist/winston/rejection-handler.js | 288 -
.../winston/dist/winston/tail-file.js | 135 -
.../dist/winston/transports/console.js | 166 -
.../winston/dist/winston/transports/file.js | 817 -
.../winston/dist/winston/transports/http.js | 264 -
.../winston/dist/winston/transports/index.js | 55 -
.../winston/dist/winston/transports/stream.js | 117 -
build/node_modules/winston/index.d.ts | 193 -
build/node_modules/winston/lib/winston.js | 182 -
.../winston/lib/winston/common.js | 61 -
.../winston/lib/winston/config/index.d.ts | 98 -
.../winston/lib/winston/config/index.js | 35 -
.../winston/lib/winston/container.js | 114 -
.../winston/lib/winston/create-logger.js | 104 -
.../winston/lib/winston/exception-handler.js | 245 -
.../winston/lib/winston/exception-stream.js | 54 -
.../winston/lib/winston/logger.js | 667 -
.../winston/lib/winston/profiler.js | 51 -
.../winston/lib/winston/rejection-handler.js | 251 -
.../winston/lib/winston/tail-file.js | 124 -
.../winston/lib/winston/transports/console.js | 117 -
.../winston/lib/winston/transports/file.js | 695 -
.../winston/lib/winston/transports/http.js | 202 -
.../winston/lib/winston/transports/index.d.ts | 100 -
.../winston/lib/winston/transports/index.js | 56 -
.../winston/lib/winston/transports/stream.js | 63 -
.../readable-stream/CONTRIBUTING.md | 38 -
.../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 | 97 -
.../readable-stream/readable-browser.js | 9 -
.../node_modules/readable-stream/readable.js | 16 -
build/node_modules/winston/package.json | 118 -
build/node_modules/wrappy/package.json | 2 +-
build/node_modules/xtend/package.json | 2 +-
build/package-lock.json | 834 +-
build/package.json | 6 +-
.../purecloud-guest-chat-client/ApiClient.js | 124 +-
.../api/WebChatApi.js | 2 +-
.../configuration.js | 150 -
.../src/purecloud-guest-chat-client/index.js | 2 +-
.../src/purecloud-guest-chat-client/logger.js | 171 -
releaseNotes.md | 2 +-
version.json | 6 +-
716 files changed, 4758 insertions(+), 85870 deletions(-)
delete mode 100644 build/node_modules/@dabh/diagnostics/CHANGELOG.md
delete mode 100644 build/node_modules/@dabh/diagnostics/LICENSE
delete mode 100644 build/node_modules/@dabh/diagnostics/README.md
delete mode 100644 build/node_modules/@dabh/diagnostics/adapters/hash.js
delete mode 100644 build/node_modules/@dabh/diagnostics/adapters/index.js
delete mode 100644 build/node_modules/@dabh/diagnostics/adapters/localstorage.js
delete mode 100644 build/node_modules/@dabh/diagnostics/adapters/process.env.js
delete mode 100644 build/node_modules/@dabh/diagnostics/browser/development.js
delete mode 100644 build/node_modules/@dabh/diagnostics/browser/index.js
delete mode 100644 build/node_modules/@dabh/diagnostics/browser/override.js
delete mode 100644 build/node_modules/@dabh/diagnostics/browser/production.js
delete mode 100644 build/node_modules/@dabh/diagnostics/diagnostics.js
delete mode 100644 build/node_modules/@dabh/diagnostics/example.png
delete mode 100644 build/node_modules/@dabh/diagnostics/logger/console.js
delete mode 100644 build/node_modules/@dabh/diagnostics/modifiers/namespace-ansi.js
delete mode 100644 build/node_modules/@dabh/diagnostics/modifiers/namespace.js
delete mode 100644 build/node_modules/@dabh/diagnostics/node/development.js
delete mode 100644 build/node_modules/@dabh/diagnostics/node/index.js
delete mode 100644 build/node_modules/@dabh/diagnostics/node/override.js
delete mode 100644 build/node_modules/@dabh/diagnostics/node/production.js
delete mode 100644 build/node_modules/@dabh/diagnostics/package.json
delete mode 100644 build/node_modules/async/CHANGELOG.md
delete mode 100644 build/node_modules/async/LICENSE
delete mode 100644 build/node_modules/async/README.md
delete mode 100644 build/node_modules/async/all.js
delete mode 100644 build/node_modules/async/allLimit.js
delete mode 100644 build/node_modules/async/allSeries.js
delete mode 100644 build/node_modules/async/any.js
delete mode 100644 build/node_modules/async/anyLimit.js
delete mode 100644 build/node_modules/async/anySeries.js
delete mode 100644 build/node_modules/async/apply.js
delete mode 100644 build/node_modules/async/applyEach.js
delete mode 100644 build/node_modules/async/applyEachSeries.js
delete mode 100644 build/node_modules/async/asyncify.js
delete mode 100644 build/node_modules/async/auto.js
delete mode 100644 build/node_modules/async/autoInject.js
delete mode 100644 build/node_modules/async/bower.json
delete mode 100644 build/node_modules/async/cargo.js
delete mode 100644 build/node_modules/async/cargoQueue.js
delete mode 100644 build/node_modules/async/compose.js
delete mode 100644 build/node_modules/async/concat.js
delete mode 100644 build/node_modules/async/concatLimit.js
delete mode 100644 build/node_modules/async/concatSeries.js
delete mode 100644 build/node_modules/async/constant.js
delete mode 100644 build/node_modules/async/detect.js
delete mode 100644 build/node_modules/async/detectLimit.js
delete mode 100644 build/node_modules/async/detectSeries.js
delete mode 100644 build/node_modules/async/dir.js
delete mode 100644 build/node_modules/async/dist/async.js
delete mode 100644 build/node_modules/async/dist/async.min.js
delete mode 100644 build/node_modules/async/dist/async.mjs
delete mode 100644 build/node_modules/async/doDuring.js
delete mode 100644 build/node_modules/async/doUntil.js
delete mode 100644 build/node_modules/async/doWhilst.js
delete mode 100644 build/node_modules/async/during.js
delete mode 100644 build/node_modules/async/each.js
delete mode 100644 build/node_modules/async/eachLimit.js
delete mode 100644 build/node_modules/async/eachOf.js
delete mode 100644 build/node_modules/async/eachOfLimit.js
delete mode 100644 build/node_modules/async/eachOfSeries.js
delete mode 100644 build/node_modules/async/eachSeries.js
delete mode 100644 build/node_modules/async/ensureAsync.js
delete mode 100644 build/node_modules/async/every.js
delete mode 100644 build/node_modules/async/everyLimit.js
delete mode 100644 build/node_modules/async/everySeries.js
delete mode 100644 build/node_modules/async/filter.js
delete mode 100644 build/node_modules/async/filterLimit.js
delete mode 100644 build/node_modules/async/filterSeries.js
delete mode 100644 build/node_modules/async/find.js
delete mode 100644 build/node_modules/async/findLimit.js
delete mode 100644 build/node_modules/async/findSeries.js
delete mode 100644 build/node_modules/async/flatMap.js
delete mode 100644 build/node_modules/async/flatMapLimit.js
delete mode 100644 build/node_modules/async/flatMapSeries.js
delete mode 100644 build/node_modules/async/foldl.js
delete mode 100644 build/node_modules/async/foldr.js
delete mode 100644 build/node_modules/async/forEach.js
delete mode 100644 build/node_modules/async/forEachLimit.js
delete mode 100644 build/node_modules/async/forEachOf.js
delete mode 100644 build/node_modules/async/forEachOfLimit.js
delete mode 100644 build/node_modules/async/forEachOfSeries.js
delete mode 100644 build/node_modules/async/forEachSeries.js
delete mode 100644 build/node_modules/async/forever.js
delete mode 100644 build/node_modules/async/groupBy.js
delete mode 100644 build/node_modules/async/groupByLimit.js
delete mode 100644 build/node_modules/async/groupBySeries.js
delete mode 100644 build/node_modules/async/index.js
delete mode 100644 build/node_modules/async/inject.js
delete mode 100644 build/node_modules/async/internal/DoublyLinkedList.js
delete mode 100644 build/node_modules/async/internal/Heap.js
delete mode 100644 build/node_modules/async/internal/applyEach.js
delete mode 100644 build/node_modules/async/internal/asyncEachOfLimit.js
delete mode 100644 build/node_modules/async/internal/awaitify.js
delete mode 100644 build/node_modules/async/internal/breakLoop.js
delete mode 100644 build/node_modules/async/internal/consoleFunc.js
delete mode 100644 build/node_modules/async/internal/createTester.js
delete mode 100644 build/node_modules/async/internal/eachOfLimit.js
delete mode 100644 build/node_modules/async/internal/filter.js
delete mode 100644 build/node_modules/async/internal/getIterator.js
delete mode 100644 build/node_modules/async/internal/initialParams.js
delete mode 100644 build/node_modules/async/internal/isArrayLike.js
delete mode 100644 build/node_modules/async/internal/iterator.js
delete mode 100644 build/node_modules/async/internal/map.js
delete mode 100644 build/node_modules/async/internal/once.js
delete mode 100644 build/node_modules/async/internal/onlyOnce.js
delete mode 100644 build/node_modules/async/internal/parallel.js
delete mode 100644 build/node_modules/async/internal/promiseCallback.js
delete mode 100644 build/node_modules/async/internal/queue.js
delete mode 100644 build/node_modules/async/internal/range.js
delete mode 100644 build/node_modules/async/internal/reject.js
delete mode 100644 build/node_modules/async/internal/setImmediate.js
delete mode 100644 build/node_modules/async/internal/withoutIndex.js
delete mode 100644 build/node_modules/async/internal/wrapAsync.js
delete mode 100644 build/node_modules/async/log.js
delete mode 100644 build/node_modules/async/map.js
delete mode 100644 build/node_modules/async/mapLimit.js
delete mode 100644 build/node_modules/async/mapSeries.js
delete mode 100644 build/node_modules/async/mapValues.js
delete mode 100644 build/node_modules/async/mapValuesLimit.js
delete mode 100644 build/node_modules/async/mapValuesSeries.js
delete mode 100644 build/node_modules/async/memoize.js
delete mode 100644 build/node_modules/async/nextTick.js
delete mode 100644 build/node_modules/async/package.json
delete mode 100644 build/node_modules/async/parallel.js
delete mode 100644 build/node_modules/async/parallelLimit.js
delete mode 100644 build/node_modules/async/priorityQueue.js
delete mode 100644 build/node_modules/async/queue.js
delete mode 100644 build/node_modules/async/race.js
delete mode 100644 build/node_modules/async/reduce.js
delete mode 100644 build/node_modules/async/reduceRight.js
delete mode 100644 build/node_modules/async/reflect.js
delete mode 100644 build/node_modules/async/reflectAll.js
delete mode 100644 build/node_modules/async/reject.js
delete mode 100644 build/node_modules/async/rejectLimit.js
delete mode 100644 build/node_modules/async/rejectSeries.js
delete mode 100644 build/node_modules/async/retry.js
delete mode 100644 build/node_modules/async/retryable.js
delete mode 100644 build/node_modules/async/select.js
delete mode 100644 build/node_modules/async/selectLimit.js
delete mode 100644 build/node_modules/async/selectSeries.js
delete mode 100644 build/node_modules/async/seq.js
delete mode 100644 build/node_modules/async/series.js
delete mode 100644 build/node_modules/async/setImmediate.js
delete mode 100644 build/node_modules/async/some.js
delete mode 100644 build/node_modules/async/someLimit.js
delete mode 100644 build/node_modules/async/someSeries.js
delete mode 100644 build/node_modules/async/sortBy.js
delete mode 100644 build/node_modules/async/timeout.js
delete mode 100644 build/node_modules/async/times.js
delete mode 100644 build/node_modules/async/timesLimit.js
delete mode 100644 build/node_modules/async/timesSeries.js
delete mode 100644 build/node_modules/async/transform.js
delete mode 100644 build/node_modules/async/tryEach.js
delete mode 100644 build/node_modules/async/unmemoize.js
delete mode 100644 build/node_modules/async/until.js
delete mode 100644 build/node_modules/async/waterfall.js
delete mode 100644 build/node_modules/async/whilst.js
delete mode 100644 build/node_modules/async/wrapSync.js
delete mode 100644 build/node_modules/color-convert/CHANGELOG.md
delete mode 100644 build/node_modules/color-convert/LICENSE
delete mode 100644 build/node_modules/color-convert/README.md
delete mode 100644 build/node_modules/color-convert/conversions.js
delete mode 100644 build/node_modules/color-convert/index.js
delete mode 100644 build/node_modules/color-convert/package.json
delete mode 100644 build/node_modules/color-convert/route.js
delete mode 100644 build/node_modules/color-name/.eslintrc.json
delete mode 100644 build/node_modules/color-name/.npmignore
delete mode 100644 build/node_modules/color-name/LICENSE
delete mode 100644 build/node_modules/color-name/README.md
delete mode 100644 build/node_modules/color-name/index.js
delete mode 100644 build/node_modules/color-name/package.json
delete mode 100644 build/node_modules/color-name/test.js
delete mode 100644 build/node_modules/color-string/CHANGELOG.md
delete mode 100644 build/node_modules/color-string/LICENSE
delete mode 100644 build/node_modules/color-string/README.md
delete mode 100644 build/node_modules/color-string/index.js
delete mode 100644 build/node_modules/color-string/package.json
delete mode 100644 build/node_modules/color/LICENSE
delete mode 100644 build/node_modules/color/README.md
delete mode 100644 build/node_modules/color/index.js
delete mode 100644 build/node_modules/color/package.json
delete mode 100644 build/node_modules/colors/LICENSE
delete mode 100644 build/node_modules/colors/README.md
delete mode 100644 build/node_modules/colors/examples/normal-usage.js
delete mode 100644 build/node_modules/colors/examples/safe-string.js
delete mode 100644 build/node_modules/colors/index.d.ts
delete mode 100644 build/node_modules/colors/lib/colors.js
delete mode 100644 build/node_modules/colors/lib/custom/trap.js
delete mode 100644 build/node_modules/colors/lib/custom/zalgo.js
delete mode 100644 build/node_modules/colors/lib/extendStringPrototype.js
delete mode 100644 build/node_modules/colors/lib/index.js
delete mode 100644 build/node_modules/colors/lib/maps/america.js
delete mode 100644 build/node_modules/colors/lib/maps/rainbow.js
delete mode 100644 build/node_modules/colors/lib/maps/random.js
delete mode 100644 build/node_modules/colors/lib/maps/zebra.js
delete mode 100644 build/node_modules/colors/lib/styles.js
delete mode 100644 build/node_modules/colors/lib/system/has-flag.js
delete mode 100644 build/node_modules/colors/lib/system/supports-colors.js
delete mode 100644 build/node_modules/colors/package.json
delete mode 100644 build/node_modules/colors/safe.d.ts
delete mode 100644 build/node_modules/colors/safe.js
delete mode 100644 build/node_modules/colors/themes/generic-logging.js
delete mode 100644 build/node_modules/colorspace/LICENSE.md
delete mode 100644 build/node_modules/colorspace/README.md
delete mode 100644 build/node_modules/colorspace/index.js
delete mode 100644 build/node_modules/colorspace/package.json
delete mode 100644 build/node_modules/colorspace/test.js
delete mode 100644 build/node_modules/configparser/.circleci/config.yml
delete mode 100644 build/node_modules/configparser/package.json
delete mode 100644 build/node_modules/configparser/readme.md
delete mode 100644 build/node_modules/configparser/src/configparser.js
delete mode 100644 build/node_modules/configparser/src/errors.js
delete mode 100644 build/node_modules/configparser/src/interpolation.js
delete mode 100644 build/node_modules/configparser/test/configparser.js
delete mode 100644 build/node_modules/configparser/test/data/file.ini
delete mode 100644 build/node_modules/configparser/typings/configparser.d.ts
delete mode 100644 build/node_modules/enabled/.travis.yml
delete mode 100644 build/node_modules/enabled/LICENSE
delete mode 100644 build/node_modules/enabled/README.md
delete mode 100644 build/node_modules/enabled/index.js
delete mode 100644 build/node_modules/enabled/package.json
delete mode 100644 build/node_modules/enabled/test.js
delete mode 100644 build/node_modules/fast-safe-stringify/.travis.yml
delete mode 100644 build/node_modules/fast-safe-stringify/CHANGELOG.md
delete mode 100644 build/node_modules/fast-safe-stringify/LICENSE
delete mode 100644 build/node_modules/fast-safe-stringify/benchmark.js
delete mode 100644 build/node_modules/fast-safe-stringify/index.d.ts
delete mode 100644 build/node_modules/fast-safe-stringify/index.js
delete mode 100644 build/node_modules/fast-safe-stringify/package.json
delete mode 100644 build/node_modules/fast-safe-stringify/readme.md
delete mode 100644 build/node_modules/fast-safe-stringify/test-stable.js
delete mode 100644 build/node_modules/fast-safe-stringify/test.js
delete mode 100644 build/node_modules/fecha/CHANGELOG.md
delete mode 100644 build/node_modules/fecha/LICENSE
delete mode 100644 build/node_modules/fecha/README.md
delete mode 100644 build/node_modules/fecha/dist/fecha.min.js
delete mode 100644 build/node_modules/fecha/dist/fecha.min.js.map
delete mode 100644 build/node_modules/fecha/lib/fecha.d.ts
delete mode 100644 build/node_modules/fecha/lib/fecha.js
delete mode 100644 build/node_modules/fecha/lib/fecha.js.map
delete mode 100644 build/node_modules/fecha/lib/fecha.umd.js
delete mode 100644 build/node_modules/fecha/lib/fecha.umd.js.map
delete mode 100644 build/node_modules/fecha/package.json
delete mode 100644 build/node_modules/fecha/src/fecha.ts
delete mode 100644 build/node_modules/fn.name/.gitattributes
delete mode 100644 build/node_modules/fn.name/.travis.yml
delete mode 100644 build/node_modules/fn.name/LICENSE
delete mode 100644 build/node_modules/fn.name/README.md
delete mode 100644 build/node_modules/fn.name/index.js
delete mode 100644 build/node_modules/fn.name/package.json
delete mode 100644 build/node_modules/fn.name/test.js
delete mode 100644 build/node_modules/is-arrayish/LICENSE
delete mode 100644 build/node_modules/is-arrayish/README.md
delete mode 100644 build/node_modules/is-arrayish/index.js
delete mode 100644 build/node_modules/is-arrayish/package.json
delete mode 100644 build/node_modules/is-arrayish/yarn-error.log
delete mode 100644 build/node_modules/is-stream/index.d.ts
delete mode 100644 build/node_modules/is-stream/index.js
delete mode 100644 build/node_modules/is-stream/license
delete mode 100644 build/node_modules/is-stream/package.json
delete mode 100644 build/node_modules/is-stream/readme.md
delete mode 100644 build/node_modules/kuler/.travis.yml
delete mode 100644 build/node_modules/kuler/LICENSE
delete mode 100644 build/node_modules/kuler/README.md
delete mode 100644 build/node_modules/kuler/index.js
delete mode 100644 build/node_modules/kuler/package.json
delete mode 100644 build/node_modules/kuler/test.js
delete mode 100644 build/node_modules/logform/.babelrc
delete mode 100644 build/node_modules/logform/.eslintrc
delete mode 100644 build/node_modules/logform/.gitattributes
delete mode 100644 build/node_modules/logform/.travis.yml
delete mode 100644 build/node_modules/logform/CHANGELOG.md
delete mode 100644 build/node_modules/logform/LICENSE
delete mode 100644 build/node_modules/logform/README.md
delete mode 100644 build/node_modules/logform/align.js
delete mode 100644 build/node_modules/logform/browser.js
delete mode 100644 build/node_modules/logform/cli.js
delete mode 100644 build/node_modules/logform/colorize.js
delete mode 100644 build/node_modules/logform/combine.js
delete mode 100644 build/node_modules/logform/dist/align.js
delete mode 100644 build/node_modules/logform/dist/browser.js
delete mode 100644 build/node_modules/logform/dist/cli.js
delete mode 100644 build/node_modules/logform/dist/colorize.js
delete mode 100644 build/node_modules/logform/dist/combine.js
delete mode 100644 build/node_modules/logform/dist/errors.js
delete mode 100644 build/node_modules/logform/dist/format.js
delete mode 100644 build/node_modules/logform/dist/index.js
delete mode 100644 build/node_modules/logform/dist/json.js
delete mode 100644 build/node_modules/logform/dist/label.js
delete mode 100644 build/node_modules/logform/dist/levels.js
delete mode 100644 build/node_modules/logform/dist/logstash.js
delete mode 100644 build/node_modules/logform/dist/metadata.js
delete mode 100644 build/node_modules/logform/dist/ms.js
delete mode 100644 build/node_modules/logform/dist/pad-levels.js
delete mode 100644 build/node_modules/logform/dist/pretty-print.js
delete mode 100644 build/node_modules/logform/dist/printf.js
delete mode 100644 build/node_modules/logform/dist/simple.js
delete mode 100644 build/node_modules/logform/dist/splat.js
delete mode 100644 build/node_modules/logform/dist/timestamp.js
delete mode 100644 build/node_modules/logform/dist/uncolorize.js
delete mode 100644 build/node_modules/logform/errors.js
delete mode 100644 build/node_modules/logform/examples/combine.js
delete mode 100644 build/node_modules/logform/examples/filter.js
delete mode 100644 build/node_modules/logform/examples/invalid.js
delete mode 100644 build/node_modules/logform/examples/metadata.js
delete mode 100644 build/node_modules/logform/examples/padLevels.js
delete mode 100644 build/node_modules/logform/examples/volume.js
delete mode 100644 build/node_modules/logform/format.js
delete mode 100644 build/node_modules/logform/index.d.ts
delete mode 100644 build/node_modules/logform/index.js
delete mode 100644 build/node_modules/logform/json.js
delete mode 100644 build/node_modules/logform/label.js
delete mode 100644 build/node_modules/logform/levels.js
delete mode 100644 build/node_modules/logform/logstash.js
delete mode 100644 build/node_modules/logform/metadata.js
delete mode 100644 build/node_modules/logform/ms.js
delete mode 100644 build/node_modules/logform/package.json
delete mode 100644 build/node_modules/logform/pad-levels.js
delete mode 100644 build/node_modules/logform/pretty-print.js
delete mode 100644 build/node_modules/logform/printf.js
delete mode 100644 build/node_modules/logform/simple.js
delete mode 100644 build/node_modules/logform/splat.js
delete mode 100644 build/node_modules/logform/timestamp.js
delete mode 100644 build/node_modules/logform/tsconfig.json
delete mode 100644 build/node_modules/logform/uncolorize.js
delete mode 100644 build/node_modules/minimist/test/all_bool.js
delete mode 100644 build/node_modules/minimist/test/bool.js
delete mode 100644 build/node_modules/minimist/test/kv_short.js
delete mode 100644 build/node_modules/minimist/test/num.js
delete mode 100644 build/node_modules/minimist/test/proto.js
delete mode 100644 build/node_modules/minimist/test/stop_early.js
delete mode 100644 build/node_modules/minimist/test/unknown.js
rename build/node_modules/{mocha/node_modules => }/mkdirp/.npmignore (100%)
rename build/node_modules/{mocha/node_modules => }/mkdirp/.travis.yml (100%)
rename build/node_modules/{mocha/node_modules => }/mkdirp/examples/pow.js (100%)
rename build/node_modules/{mocha/node_modules => }/mkdirp/test/chmod.js (100%)
rename build/node_modules/{mocha/node_modules => }/mkdirp/test/clobber.js (100%)
rename build/node_modules/{mocha/node_modules => }/mkdirp/test/mkdirp.js (100%)
rename build/node_modules/{mocha/node_modules => }/mkdirp/test/opts_fs.js (100%)
rename build/node_modules/{mocha/node_modules => }/mkdirp/test/opts_fs_sync.js (100%)
rename build/node_modules/{mocha/node_modules => }/mkdirp/test/perm.js (100%)
rename build/node_modules/{mocha/node_modules => }/mkdirp/test/perm_sync.js (100%)
rename build/node_modules/{mocha/node_modules => }/mkdirp/test/race.js (100%)
rename build/node_modules/{mocha/node_modules => }/mkdirp/test/rel.js (100%)
rename build/node_modules/{mocha/node_modules => }/mkdirp/test/return.js (100%)
rename build/node_modules/{mocha/node_modules => }/mkdirp/test/return_sync.js (100%)
rename build/node_modules/{mocha/node_modules => }/mkdirp/test/root.js (100%)
rename build/node_modules/{mocha/node_modules => }/mkdirp/test/sync.js (100%)
rename build/node_modules/{mocha/node_modules => }/mkdirp/test/umask.js (100%)
rename build/node_modules/{mocha/node_modules => }/mkdirp/test/umask_sync.js (100%)
delete mode 120000 build/node_modules/mocha/node_modules/.bin/mkdirp
delete mode 100644 build/node_modules/mocha/node_modules/minimist/.travis.yml
delete mode 100644 build/node_modules/mocha/node_modules/minimist/LICENSE
delete mode 100644 build/node_modules/mocha/node_modules/minimist/example/parse.js
delete mode 100644 build/node_modules/mocha/node_modules/minimist/index.js
delete mode 100644 build/node_modules/mocha/node_modules/minimist/package.json
delete mode 100644 build/node_modules/mocha/node_modules/minimist/readme.markdown
delete mode 100644 build/node_modules/mocha/node_modules/minimist/test/dash.js
delete mode 100644 build/node_modules/mocha/node_modules/minimist/test/default_bool.js
delete mode 100644 build/node_modules/mocha/node_modules/minimist/test/dotted.js
delete mode 100644 build/node_modules/mocha/node_modules/minimist/test/long.js
delete mode 100644 build/node_modules/mocha/node_modules/minimist/test/parse.js
delete mode 100644 build/node_modules/mocha/node_modules/minimist/test/parse_modified.js
delete mode 100644 build/node_modules/mocha/node_modules/minimist/test/short.js
delete mode 100644 build/node_modules/mocha/node_modules/minimist/test/whitespace.js
delete mode 100644 build/node_modules/mocha/node_modules/mkdirp/LICENSE
delete mode 100755 build/node_modules/mocha/node_modules/mkdirp/bin/cmd.js
delete mode 100644 build/node_modules/mocha/node_modules/mkdirp/bin/usage.txt
delete mode 100644 build/node_modules/mocha/node_modules/mkdirp/index.js
delete mode 100644 build/node_modules/mocha/node_modules/mkdirp/package.json
delete mode 100644 build/node_modules/mocha/node_modules/mkdirp/readme.markdown
delete mode 100644 build/node_modules/one-time/LICENSE
delete mode 100644 build/node_modules/one-time/README.md
delete mode 100644 build/node_modules/one-time/async.js
delete mode 100644 build/node_modules/one-time/index.js
delete mode 100644 build/node_modules/one-time/package.json
delete mode 100644 build/node_modules/simple-swizzle/LICENSE
delete mode 100644 build/node_modules/simple-swizzle/README.md
delete mode 100644 build/node_modules/simple-swizzle/index.js
delete mode 100644 build/node_modules/simple-swizzle/package.json
delete mode 100644 build/node_modules/stack-trace/.npmignore
delete mode 100644 build/node_modules/stack-trace/License
delete mode 100644 build/node_modules/stack-trace/Makefile
delete mode 100644 build/node_modules/stack-trace/Readme.md
delete mode 100644 build/node_modules/stack-trace/lib/stack-trace.js
delete mode 100644 build/node_modules/stack-trace/package.json
delete mode 100644 build/node_modules/text-hex/LICENSE
delete mode 100644 build/node_modules/text-hex/README.md
delete mode 100644 build/node_modules/text-hex/index.js
delete mode 100644 build/node_modules/text-hex/package.json
delete mode 100644 build/node_modules/text-hex/test.js
delete mode 100644 build/node_modules/triple-beam/.eslintrc
delete mode 100644 build/node_modules/triple-beam/.gitattributes
delete mode 100644 build/node_modules/triple-beam/.travis.yml
delete mode 100644 build/node_modules/triple-beam/CHANGELOG.md
delete mode 100644 build/node_modules/triple-beam/LICENSE
delete mode 100644 build/node_modules/triple-beam/README.md
delete mode 100644 build/node_modules/triple-beam/config/cli.js
delete mode 100644 build/node_modules/triple-beam/config/index.js
delete mode 100644 build/node_modules/triple-beam/config/npm.js
delete mode 100644 build/node_modules/triple-beam/config/syslog.js
delete mode 100644 build/node_modules/triple-beam/index.js
delete mode 100644 build/node_modules/triple-beam/package.json
delete mode 100644 build/node_modules/triple-beam/test.js
delete mode 100644 build/node_modules/winston-transport/.babelrc
delete mode 100644 build/node_modules/winston-transport/.eslintrc
delete mode 100644 build/node_modules/winston-transport/.gitattributes
delete mode 100644 build/node_modules/winston-transport/.nyc_output/1c69f3e4-4c25-457d-9df5-dfa761729528.json
delete mode 100644 build/node_modules/winston-transport/.nyc_output/processinfo/1c69f3e4-4c25-457d-9df5-dfa761729528.json
delete mode 100644 build/node_modules/winston-transport/.nyc_output/processinfo/index.json
delete mode 100644 build/node_modules/winston-transport/.travis.yml
delete mode 100644 build/node_modules/winston-transport/CHANGELOG.md
delete mode 100644 build/node_modules/winston-transport/LICENSE
delete mode 100644 build/node_modules/winston-transport/README.md
delete mode 100644 build/node_modules/winston-transport/dist/index.js
delete mode 100644 build/node_modules/winston-transport/dist/legacy.js
delete mode 100644 build/node_modules/winston-transport/index.d.ts
delete mode 100644 build/node_modules/winston-transport/index.js
delete mode 100644 build/node_modules/winston-transport/legacy.js
delete mode 100644 build/node_modules/winston-transport/package.json
delete mode 100644 build/node_modules/winston-transport/tsconfig.json
delete mode 100644 build/node_modules/winston/CHANGELOG.md
delete mode 100644 build/node_modules/winston/LICENSE
delete mode 100644 build/node_modules/winston/README.md
delete mode 100644 build/node_modules/winston/dist/winston.js
delete mode 100644 build/node_modules/winston/dist/winston/common.js
delete mode 100644 build/node_modules/winston/dist/winston/config/index.js
delete mode 100644 build/node_modules/winston/dist/winston/container.js
delete mode 100644 build/node_modules/winston/dist/winston/create-logger.js
delete mode 100644 build/node_modules/winston/dist/winston/exception-handler.js
delete mode 100644 build/node_modules/winston/dist/winston/exception-stream.js
delete mode 100644 build/node_modules/winston/dist/winston/logger.js
delete mode 100644 build/node_modules/winston/dist/winston/profiler.js
delete mode 100644 build/node_modules/winston/dist/winston/rejection-handler.js
delete mode 100644 build/node_modules/winston/dist/winston/tail-file.js
delete mode 100644 build/node_modules/winston/dist/winston/transports/console.js
delete mode 100644 build/node_modules/winston/dist/winston/transports/file.js
delete mode 100644 build/node_modules/winston/dist/winston/transports/http.js
delete mode 100644 build/node_modules/winston/dist/winston/transports/index.js
delete mode 100644 build/node_modules/winston/dist/winston/transports/stream.js
delete mode 100644 build/node_modules/winston/index.d.ts
delete mode 100644 build/node_modules/winston/lib/winston.js
delete mode 100644 build/node_modules/winston/lib/winston/common.js
delete mode 100644 build/node_modules/winston/lib/winston/config/index.d.ts
delete mode 100644 build/node_modules/winston/lib/winston/config/index.js
delete mode 100644 build/node_modules/winston/lib/winston/container.js
delete mode 100644 build/node_modules/winston/lib/winston/create-logger.js
delete mode 100644 build/node_modules/winston/lib/winston/exception-handler.js
delete mode 100644 build/node_modules/winston/lib/winston/exception-stream.js
delete mode 100644 build/node_modules/winston/lib/winston/logger.js
delete mode 100644 build/node_modules/winston/lib/winston/profiler.js
delete mode 100644 build/node_modules/winston/lib/winston/rejection-handler.js
delete mode 100644 build/node_modules/winston/lib/winston/tail-file.js
delete mode 100644 build/node_modules/winston/lib/winston/transports/console.js
delete mode 100644 build/node_modules/winston/lib/winston/transports/file.js
delete mode 100644 build/node_modules/winston/lib/winston/transports/http.js
delete mode 100644 build/node_modules/winston/lib/winston/transports/index.d.ts
delete mode 100644 build/node_modules/winston/lib/winston/transports/index.js
delete mode 100644 build/node_modules/winston/lib/winston/transports/stream.js
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/CONTRIBUTING.md
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/GOVERNANCE.md
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/LICENSE
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/README.md
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/errors-browser.js
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/errors.js
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/experimentalWarning.js
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/lib/_stream_duplex.js
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/lib/_stream_passthrough.js
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/lib/_stream_readable.js
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/lib/_stream_transform.js
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/lib/_stream_writable.js
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/async_iterator.js
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/buffer_list.js
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/destroy.js
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/end-of-stream.js
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/from-browser.js
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/from.js
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/pipeline.js
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/state.js
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/stream-browser.js
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/lib/internal/streams/stream.js
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/package.json
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/readable-browser.js
delete mode 100644 build/node_modules/winston/node_modules/readable-stream/readable.js
delete mode 100644 build/node_modules/winston/package.json
delete mode 100644 build/src/purecloud-guest-chat-client/configuration.js
delete mode 100644 build/src/purecloud-guest-chat-client/logger.js
diff --git a/README.md b/README.md
index c6247a20..f190d97f 100644
--- a/README.md
+++ b/README.md
@@ -31,7 +31,7 @@ For direct use in a browser script:
```{"language":"html"}
-
+
@@ -149,76 +149,6 @@ webChatApi.postWebchatGuestConversations(createChatBody)
.catch(console.error);
```
-## SDK Logging
-
-Logging of API requests and responses can be controlled by a number of parameters on the `Configuration`'s `Logger` instance.
-
-`log_level` values:
-1. LTrace (HTTP Method, URL, Request Body, HTTP Status Code, Request Headers, Response Headers)
-2. LDebug (HTTP Method, URL, Request Body, HTTP Status Code, Request Headers)
-3. LError (HTTP Method, URL, Request Body, Response Body, HTTP Status Code, Request Headers, Response Headers)
-4. LNone - default
-
-`log_format` values:
-1. JSON
-2. TEXT - default
-
-By default, the request and response bodies are not logged because these can contain PII. Be mindful of this data if choosing to log it.
-To log to a file, provide a `log_file_path` value. SDK users are responsible for the rotation of the log file.
-
-Example logging configuration:
-```{"language":"javascript"}
-client.config.logger.log_level = client.config.logger.logLevelEnum.level.LTrace;
-client.config.logger.log_format = client.config.logger.logFormatEnum.formats.JSON;
-client.config.logger.log_request_body = true;
-client.config.logger.log_response_body = true;
-client.config.logger.log_to_console = true;
-client.config.logger.log_file_path = "/var/log/javascriptguestsdk.log";
-
-client.config.logger.setLogger(); // To apply above changes
-```
-
-#### Configuration file
-
-A number of configuration parameters can be applied using a configuration file. There are two sources for this file:
-
-1. The SDK will look for `%USERPROFILE%\.genesyscloudjavascript-guest\config` on Windows if the environment variable USERPROFILE is defined, otherwise uses the path to the profile directory of the current user as home, or `$HOME/.genesyscloudjavascript-guest/config` on Unix.
-2. Provide a valid file path to `client.config.setConfigPath()`
-
-The SDK will constantly check to see if the config file has been updated, regardless of whether a config file was present at start-up. To disable this behaviour, set `client.config.live_reload_config` to false.
-INI and JSON formats are supported. See below for examples of configuration values in both formats:
-
-INI:
-```{"language":"ini"}
-[logging]
-log_level = trace
-log_format = text
-log_to_console = false
-log_file_path = /var/log/javascriptguestsdk.log
-log_response_body = false
-log_request_body = false
-[general]
-live_reload_config = true
-host = https://api.mypurecloud.com
-```
-
-JSON:
-```{"language":"json"}
-{
- "logging": {
- "log_level": "trace",
- "log_format": "text",
- "log_to_console": false,
- "log_file_path": "/var/log/javascriptguestsdk.log",
- "log_response_body": false,
- "log_request_body": false
- },
- "general": {
- "live_reload_config": true,
- "host": "https://api.mypurecloud.com"
- }
-}
-```
## Environments
@@ -351,6 +281,16 @@ Example error response object:
```
+## Debug Logging
+
+There are hooks to trace requests and responses. To enable debug tracing, provide a log object. Optionally, specify a maximum number of lines. If specified, the response body trace will be truncated. If not specified, the entire response body will be traced out.
+
+```{"language":"javascript"}
+const client = platformClient.ApiClient.instance;
+client.setDebugLog(console.log, 25);
+```
+
+
## Versioning
The SDK's version is incremented according to the [Semantic Versioning Specification](https://semver.org/). The decision to increment version numbers is determined by [diffing the Platform API's swagger](https://github.com/purecloudlabs/platform-client-sdk-common/blob/master/modules/swaggerDiff.js) for automated builds, and optionally forcing a version bump when a build is triggered manually (e.g. releasing a bugfix).
diff --git a/build/README.md b/build/README.md
index c6247a20..f190d97f 100644
--- a/build/README.md
+++ b/build/README.md
@@ -31,7 +31,7 @@ For direct use in a browser script:
```{"language":"html"}
-
+
@@ -149,76 +149,6 @@ webChatApi.postWebchatGuestConversations(createChatBody)
.catch(console.error);
```
-## SDK Logging
-
-Logging of API requests and responses can be controlled by a number of parameters on the `Configuration`'s `Logger` instance.
-
-`log_level` values:
-1. LTrace (HTTP Method, URL, Request Body, HTTP Status Code, Request Headers, Response Headers)
-2. LDebug (HTTP Method, URL, Request Body, HTTP Status Code, Request Headers)
-3. LError (HTTP Method, URL, Request Body, Response Body, HTTP Status Code, Request Headers, Response Headers)
-4. LNone - default
-
-`log_format` values:
-1. JSON
-2. TEXT - default
-
-By default, the request and response bodies are not logged because these can contain PII. Be mindful of this data if choosing to log it.
-To log to a file, provide a `log_file_path` value. SDK users are responsible for the rotation of the log file.
-
-Example logging configuration:
-```{"language":"javascript"}
-client.config.logger.log_level = client.config.logger.logLevelEnum.level.LTrace;
-client.config.logger.log_format = client.config.logger.logFormatEnum.formats.JSON;
-client.config.logger.log_request_body = true;
-client.config.logger.log_response_body = true;
-client.config.logger.log_to_console = true;
-client.config.logger.log_file_path = "/var/log/javascriptguestsdk.log";
-
-client.config.logger.setLogger(); // To apply above changes
-```
-
-#### Configuration file
-
-A number of configuration parameters can be applied using a configuration file. There are two sources for this file:
-
-1. The SDK will look for `%USERPROFILE%\.genesyscloudjavascript-guest\config` on Windows if the environment variable USERPROFILE is defined, otherwise uses the path to the profile directory of the current user as home, or `$HOME/.genesyscloudjavascript-guest/config` on Unix.
-2. Provide a valid file path to `client.config.setConfigPath()`
-
-The SDK will constantly check to see if the config file has been updated, regardless of whether a config file was present at start-up. To disable this behaviour, set `client.config.live_reload_config` to false.
-INI and JSON formats are supported. See below for examples of configuration values in both formats:
-
-INI:
-```{"language":"ini"}
-[logging]
-log_level = trace
-log_format = text
-log_to_console = false
-log_file_path = /var/log/javascriptguestsdk.log
-log_response_body = false
-log_request_body = false
-[general]
-live_reload_config = true
-host = https://api.mypurecloud.com
-```
-
-JSON:
-```{"language":"json"}
-{
- "logging": {
- "log_level": "trace",
- "log_format": "text",
- "log_to_console": false,
- "log_file_path": "/var/log/javascriptguestsdk.log",
- "log_response_body": false,
- "log_request_body": false
- },
- "general": {
- "live_reload_config": true,
- "host": "https://api.mypurecloud.com"
- }
-}
-```
## Environments
@@ -351,6 +281,16 @@ Example error response object:
```
+## Debug Logging
+
+There are hooks to trace requests and responses. To enable debug tracing, provide a log object. Optionally, specify a maximum number of lines. If specified, the response body trace will be truncated. If not specified, the entire response body will be traced out.
+
+```{"language":"javascript"}
+const client = platformClient.ApiClient.instance;
+client.setDebugLog(console.log, 25);
+```
+
+
## Versioning
The SDK's version is incremented according to the [Semantic Versioning Specification](https://semver.org/). The decision to increment version numbers is determined by [diffing the Platform API's swagger](https://github.com/purecloudlabs/platform-client-sdk-common/blob/master/modules/swaggerDiff.js) for automated builds, and optionally forcing a version bump when a build is triggered manually (e.g. releasing a bugfix).
diff --git a/build/dist/node/purecloud-guest-chat-client.js b/build/dist/node/purecloud-guest-chat-client.js
index 6e7b9672..7111affb 100644
--- a/build/dist/node/purecloud-guest-chat-client.js
+++ b/build/dist/node/purecloud-guest-chat-client.js
@@ -16,326 +16,9 @@ var PureCloudRegionHosts = {
eu_west_2: "euw2.pure.cloud"
}
-const winston = require('winston');
-
-const logLevels = {
- levels: {
- none: 0,
- error: 1,
- debug: 2,
- trace: 3,
- },
-};
-
-const logLevelEnum = {
- level: {
- LNone: 'none',
- LError: 'error',
- LDebug: 'debug',
- LTrace: 'trace',
- },
-};
-
-const logFormatEnum = {
- formats: {
- JSON: 'json',
- TEXT: 'text',
- },
-};
-
-class Logger {
- get logLevelEnum() {
- return logLevelEnum;
- }
-
- get logFormatEnum() {
- return logFormatEnum;
- }
-
- constructor() {
- this.log_level = logLevelEnum.level.LNone;
- this.log_format = logFormatEnum.formats.TEXT;
- this.log_to_console = true;
- this.log_file_path;
- this.log_response_body = false;
- this.log_request_body = false;
-
- this.setLogger();
- }
-
- createNewLogger() {
- this.logger = winston.createLogger({
- levels: logLevels.levels,
- level: this.log_level,
- });
- }
-
- setLogger() {
- this.createNewLogger();
- if (this.log_file_path && this.log_file_path !== '') {
- if (this.log_format === logFormatEnum.formats.JSON) {
- this.logger.add(new winston.transports.File({ format: winston.format.json(), filename: this.log_file_path }));
- } else {
- this.logger.add(
- new winston.transports.File({
- format: winston.format.combine(
- winston.format((info) => {
- info.level = info.level.toUpperCase();
- return info;
- })(),
- winston.format.simple()
- ),
- filename: this.log_file_path,
- })
- );
- }
- }
- if (this.log_to_console) {
- if (this.log_format === logFormatEnum.formats.JSON) {
- this.logger.add(new winston.transports.Console({ format: winston.format.json() }));
- } else {
- this.logger.add(
- new winston.transports.Console({
- format: winston.format.combine(
- winston.format((info) => {
- info.level = info.level.toUpperCase();
- return info;
- })(),
- winston.format.simple()
- ),
- })
- );
- }
- }
- }
-
- log(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody) {
- var content = this.formatLog(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody);
- if (this.logger.transports.length > 0) this.logger.log(level, content);
- }
-
- formatLog(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody) {
- var result;
- if (requestHeaders) requestHeaders['Authorization'] = '[REDACTED]';
- if (!this.log_request_body) requestBody = undefined;
- if (!this.log_response_body) responseBody = undefined;
- if (this.log_format && this.log_format === logFormatEnum.formats.JSON) {
- result = {
- level: level,
- date: new Date().toISOString(),
- method: method,
- url: decodeURIComponent(url),
- correlationId: responseHeaders ? (responseHeaders['inin-correlation-id'] ? responseHeaders['inin-correlation-id'] : '') : '',
- statusCode: statusCode,
- };
- if (requestHeaders) result.requestHeaders = requestHeaders;
- if (responseHeaders) result.responseHeaders = responseHeaders;
- if (requestBody) result.requestBody = requestBody;
- if (responseBody) result.responseBody = responseBody;
- } else {
- result = `${new Date().toISOString()}
-=== REQUEST ===
-${this.formatValue('URL', decodeURIComponent(url))}${this.formatValue('Method', method)}${this.formatValue(
- 'Headers',
- this.formatHeaderString(requestHeaders)
- )}${this.formatValue('Body', requestBody ? JSON.stringify(requestBody, null, 2) : '')}
-=== RESPONSE ===
-${this.formatValue('Status', statusCode)}${this.formatValue('Headers', this.formatHeaderString(responseHeaders))}${this.formatValue(
- 'CorrelationId',
- responseHeaders ? (responseHeaders['inin-correlation-id'] ? responseHeaders['inin-correlation-id'] : '') : ''
- )}${this.formatValue('Body', responseBody ? JSON.stringify(responseBody, null, 2) : '')}`;
- }
-
- return result;
- }
-
- formatHeaderString(headers) {
- var headerString = '';
- if (!headers) return headerString;
- for (const [key, value] of Object.entries(headers)) {
- headerString += `\n\t${key}: ${value}`;
- }
- return headerString;
- }
-
- formatValue(key, value) {
- if (!value || value === '' || value === '{}') return '';
- return `${key}: ${value}\n`;
- }
-
- getLogLevel(level) {
- switch (level) {
- case 'error':
- return logLevelEnum.level.LError;
- case 'debug':
- return logLevelEnum.level.LDebug;
- case 'trace':
- return logLevelEnum.level.LTrace;
- default:
- return logLevelEnum.level.LNone;
- }
- }
-
- getLogFormat(format) {
- switch (format) {
- case 'json':
- return logFormatEnum.formats.JSON;
- default:
- return logFormatEnum.formats.TEXT;
- }
- }
-}
-
-const ConfigParser = require('configparser');
-const os = require('os');
-const path = require('path');
-const fs = require('fs');
-
-class Configuration {
- /**
- * Singleton getter
- */
- get instance() {
- return Configuration.instance;
- }
-
- /**
- * Singleton setter
- */
- set instance(value) {
- Configuration.instance = value;
- }
-
- constructor() {
- if (!Configuration.instance) {
- Configuration.instance = this;
- }
-
- this.configPath = typeof window !== 'undefined' ? '' : path.join(os.homedir(), '.genesyscloudjavascript-guest', 'config');
- this.live_reload_config = true;
- this.host;
- this.environment;
- this.basePath;
- this.authUrl;
- this.config;
- this.logger = new Logger();
- this.setEnvironment();
- this.liveLoadConfig();
- }
-
- liveLoadConfig() {
- // If in browser, don't read config file, use default values
- if (typeof window !== 'undefined') {
- this.configPath = '';
- return;
- }
-
- this.updateConfigFromFile();
-
- if (this.live_reload_config && this.live_reload_config === true) {
- try {
- fs.watchFile(this.configPath, { persistent: false }, (eventType, filename) => {
- this.updateConfigFromFile();
- if (!this.live_reload_config) {
- fs.unwatchFile(this.configPath);
- }
- });
- } catch (err) {
- // do nothing
- }
- }
- }
-
- setConfigPath(path) {
- if (path && path !== this.configPath) {
- this.configPath = path;
- this.liveLoadConfig();
- }
- }
-
- updateConfigFromFile() {
- var configparser = new ConfigParser();
-
- try {
- configparser.read(this.configPath); // If no error catched, indicates it's INI format
- this.config = configparser;
- } catch (error) {
- if (error.name && error.name === 'MissingSectionHeaderError') {
- // Not INI format, see if it's JSON format
- var configData = fs.readFileSync(this.configPath, 'utf8');
- this.config = {
- _sections: JSON.parse(configData), // To match INI data format
- };
- }
- }
-
- if (this.config) this.updateConfigValues();
- }
-
- updateConfigValues() {
- this.logger.log_level = this.logger.getLogLevel(this.getConfigString('logging', 'log_level'));
- this.logger.log_format = this.logger.getLogFormat(this.getConfigString('logging', 'log_format'));
- this.logger.log_to_console =
- this.getConfigBoolean('logging', 'log_to_console') !== undefined
- ? this.getConfigBoolean('logging', 'log_to_console')
- : this.logger.log_to_console;
- this.logger.log_file_path =
- this.getConfigString('logging', 'log_file_path') !== undefined
- ? this.getConfigString('logging', 'log_file_path')
- : this.logger.log_file_path;
- this.logger.log_response_body =
- this.getConfigBoolean('logging', 'log_response_body') !== undefined
- ? this.getConfigBoolean('logging', 'log_response_body')
- : this.logger.log_response_body;
- this.logger.log_request_body =
- this.getConfigBoolean('logging', 'log_request_body') !== undefined
- ? this.getConfigBoolean('logging', 'log_request_body')
- : this.logger.log_request_body;
- this.live_reload_config =
- this.getConfigBoolean('general', 'live_reload_config') !== undefined
- ? this.getConfigBoolean('general', 'live_reload_config')
- : this.live_reload_config;
- this.host = this.getConfigString('general', 'host') !== undefined ? this.getConfigString('general', 'host') : this.host;
-
- this.setEnvironment();
-
- // Update logging configs
- this.logger.setLogger();
- }
-
- setEnvironment(env) {
- // Default value
- if (env) this.environment = env;
- else this.environment = this.host ? this.host : 'mypurecloud.com';
-
- // Strip trailing slash
- this.environment = this.environment.replace(/\/+$/, '');
-
- // Strip protocol and subdomain
- if (this.environment.startsWith('https://')) this.environment = this.environment.substring(8);
- if (this.environment.startsWith('http://')) this.environment = this.environment.substring(7);
- if (this.environment.startsWith('api.')) this.environment = this.environment.substring(4);
-
- this.basePath = `https://api.${this.environment}`;
- this.authUrl = `https://login.${this.environment}`;
- }
-
- getConfigString(section, key) {
- if (this.config._sections[section]) return this.config._sections[section][key];
- }
-
- getConfigBoolean(section, key) {
- if (this.config._sections[section] && this.config._sections[section][key] !== undefined) {
- if (typeof this.config._sections[section][key] === 'string') {
- return this.config._sections[section][key] === 'true';
- } else return this.config._sections[section][key];
- }
- }
-}
-
/**
* @module purecloud-guest-chat-client/ApiClient
- * @version 7.0.0
+ * @version 7.1.0
*/
class ApiClient {
/**
@@ -412,11 +95,6 @@ class ApiClient {
this.hasLocalStorage = false;
}
- /**
- * Create configuration instance for ApiClient and prepare logger.
- */
- this.config = new Configuration();
-
/**
* The base URL against which to resolve every API call's (relative) path.
* @type {String}
@@ -456,6 +134,16 @@ class ApiClient {
if (typeof(window) !== 'undefined') window.ApiClient = this;
}
+ /**
+ * @description Sets the debug log to enable debug logging
+ * @param {log} debugLog - In most cases use `console.log`
+ * @param {integer} maxLines - (optional) The max number of lines to write to the log. Must be > 0.
+ */
+ setDebugLog(debugLog, maxLines) {
+ this.debugLog = debugLog;
+ this.debugLogMaxLines = (maxLines && maxLines > 0) ? maxLines : undefined;
+ }
+
/**
* @description If set to `true`, the response object will contain additional information about the HTTP response. When `false` (default) only the body object will be returned.
* @param {boolean} returnExtended - `true` to return extended responses
@@ -472,6 +160,7 @@ class ApiClient {
setPersistSettings(doPersist, prefix) {
this.persistSettings = doPersist;
this.settingsPrefix = prefix ? prefix.replace(/\W+/g, '_') : 'purecloud';
+ this._debugTrace(`this.settingsPrefix=${this.settingsPrefix}`);
}
/**
@@ -496,6 +185,7 @@ class ApiClient {
// Ensure we can access local storage
if (!this.hasLocalStorage) {
+ this._debugTrace('Warning: Cannot access local storage. Settings will not be saved.');
return;
}
@@ -505,6 +195,7 @@ class ApiClient {
// Save updated auth data
localStorage.setItem(`${this.settingsPrefix}_auth_data`, JSON.stringify(tempData));
+ this._debugTrace('Auth data saved to local storage');
} catch (e) {
console.error(e);
}
@@ -519,6 +210,7 @@ class ApiClient {
// Ensure we can access local storage
if (!this.hasLocalStorage) {
+ this._debugTrace('Warning: Cannot access local storage. Settings will not be loaded.');
return;
}
@@ -538,7 +230,24 @@ class ApiClient {
* @param {string} environment - (Optional, default "mypurecloud.com") Environment the session use, e.g. mypurecloud.ie, mypurecloud.com.au, etc.
*/
setEnvironment(environment) {
- this.config.setEnvironment(environment);
+ if (!environment)
+ environment = 'mypurecloud.com';
+
+ // Strip trailing slash
+ environment = environment.replace(/\/+$/, '');
+
+ // Strip protocol and subdomain
+ if (environment.startsWith('https://'))
+ environment = environment.substring(8);
+ if (environment.startsWith('http://'))
+ environment = environment.substring(7);
+ if (environment.startsWith('api.'))
+ environment = environment.substring(4);
+
+ // Set vars
+ this.environment = environment;
+ this.basePath = `https://api.${environment}`;
+ this.authUrl = `https://login.${environment}`;
}
/**
@@ -595,7 +304,7 @@ class ApiClient {
*/
_buildAuthUrl(path, query) {
if (!query) query = {};
- return Object.keys(query).reduce((url, key) => !query[key] ? url : `${url}&${key}=${query[key]}`, `${this.config.authUrl}/${path}?`);
+ return Object.keys(query).reduce((url, key) => !query[key] ? url : `${url}&${key}=${query[key]}`, `${this.authUrl}/${path}?`);
}
/**
@@ -624,7 +333,7 @@ class ApiClient {
if (!path.match(/^\//)) {
path = `/${path}`;
}
- var url = this.config.basePath + path;
+ var url = this.basePath + path;
url = url.replace(/\{([\w-]+)\}/g, (fullMatch, key) => {
var value;
if (pathParams.hasOwnProperty(key)) {
@@ -809,6 +518,23 @@ class ApiClient {
request.proxy(this.proxy);
}
+ if(this.debugLog){
+ var trace = `[REQUEST] ${httpMethod} ${url}`;
+ if(pathParams && Object.keys(pathParams).count > 0 && pathParams[Object.keys(pathParams)[0]]){
+ trace += `\nPath Params: ${JSON.stringify(pathParams)}`;
+ }
+
+ if(queryParams && Object.keys(queryParams).count > 0 && queryParams[Object.keys(queryParams)[0]]){
+ trace += `\nQuery Params: ${JSON.stringify(queryParams)}`;
+ }
+
+ if(bodyParam){
+ trace += `\nnBody: ${JSON.stringify(bodyParam)}`;
+ }
+
+ this._debugTrace(trace);
+ }
+
// apply authentications
this.applyAuthToRequest(request, authNames);
@@ -817,7 +543,7 @@ class ApiClient {
// set header parameters
request.set(this.defaultHeaders).set(this.normalizeParams(headerParams));
- //request.set({ 'purecloud-sdk': '7.0.0' });
+ //request.set({ 'purecloud-sdk': '7.1.0' });
// set request timeout
request.timeout(this.timeout);
@@ -879,22 +605,23 @@ class ApiClient {
} : response.body ? response.body : response.text;
// Debug logging
- this.config.logger.log('trace', response.statusCode, httpMethod, url, request.header, response.headers, bodyParam, undefined);
- this.config.logger.log('debug', response.statusCode, httpMethod, url, request.header, undefined, bodyParam, undefined);
+ if (this.debugLog) {
+ var trace = `[RESPONSE] ${response.status}: ${httpMethod} ${url}`;
+ if (response.headers)
+ trace += `\ninin-correlation-id: ${response.headers['inin-correlation-id']}`;
+ if (response.body)
+ trace += `\nBody: ${JSON.stringify(response.body,null,2)}`;
+
+ // Log trace message
+ this._debugTrace(trace);
+
+ // Log stack trace
+ if (error)
+ this._debugTrace(error);
+ }
// Resolve promise
if (error) {
- // Log error
- this.config.logger.log(
- 'error',
- response.statusCode,
- httpMethod,
- url,
- request.header,
- response.headers,
- bodyParam,
- response.body
- );
reject(data);
} else {
resolve(data);
@@ -902,13 +629,46 @@ class ApiClient {
});
});
}
+
+ /**
+ * @description Parses an ISO-8601 string representation of a date value.
+ * @param {String} str The date value as a string.
+ * @returns {Date} The parsed date object.
+ */
+ parseDate(str) {
+ return new Date(str.replace(/T/i, ' '));
+ }
+
+ /**
+ * @description Logs to the debug log
+ * @param {String} str The date value as a string.
+ * @returns {Date} The parsed date object.
+ */
+ _debugTrace(trace) {
+ if (!this.debugLog) return;
+
+ if (typeof(trace) === 'string') {
+ // Truncate
+ var truncTrace = '';
+ var lines = trace.split('\n');
+ if (this.debugLogMaxLines && lines.length > this.debugLogMaxLines) {
+ for (var i = 0; i < this.debugLogMaxLines; i++) {
+ truncTrace += `${lines[i]}\n`;
+ }
+ truncTrace += '...response truncated...';
+ trace = truncTrace;
+ }
+ }
+
+ this.debugLog(trace);
+ }
}
class WebChatApi {
/**
* WebChat service.
* @module purecloud-guest-chat-client/api/WebChatApi
- * @version 7.0.0
+ * @version 7.1.0
*/
/**
@@ -1287,7 +1047,7 @@ class WebChatApi {
*
*
* @module purecloud-guest-chat-client/index
- * @version 7.0.0
+ * @version 7.1.0
*/
class platformClient {
constructor() {
diff --git a/build/dist/web-amd/purecloud-guest-chat-client.js b/build/dist/web-amd/purecloud-guest-chat-client.js
index d5484c35..57c34a09 100644
--- a/build/dist/web-amd/purecloud-guest-chat-client.js
+++ b/build/dist/web-amd/purecloud-guest-chat-client.js
@@ -14,326 +14,9 @@ define(['superagent'], function (superagent) { 'use strict';
eu_west_2: "euw2.pure.cloud"
}
- const winston = require('winston');
-
- const logLevels = {
- levels: {
- none: 0,
- error: 1,
- debug: 2,
- trace: 3,
- },
- };
-
- const logLevelEnum = {
- level: {
- LNone: 'none',
- LError: 'error',
- LDebug: 'debug',
- LTrace: 'trace',
- },
- };
-
- const logFormatEnum = {
- formats: {
- JSON: 'json',
- TEXT: 'text',
- },
- };
-
- class Logger {
- get logLevelEnum() {
- return logLevelEnum;
- }
-
- get logFormatEnum() {
- return logFormatEnum;
- }
-
- constructor() {
- this.log_level = logLevelEnum.level.LNone;
- this.log_format = logFormatEnum.formats.TEXT;
- this.log_to_console = true;
- this.log_file_path;
- this.log_response_body = false;
- this.log_request_body = false;
-
- this.setLogger();
- }
-
- createNewLogger() {
- this.logger = winston.createLogger({
- levels: logLevels.levels,
- level: this.log_level,
- });
- }
-
- setLogger() {
- this.createNewLogger();
- if (this.log_file_path && this.log_file_path !== '') {
- if (this.log_format === logFormatEnum.formats.JSON) {
- this.logger.add(new winston.transports.File({ format: winston.format.json(), filename: this.log_file_path }));
- } else {
- this.logger.add(
- new winston.transports.File({
- format: winston.format.combine(
- winston.format((info) => {
- info.level = info.level.toUpperCase();
- return info;
- })(),
- winston.format.simple()
- ),
- filename: this.log_file_path,
- })
- );
- }
- }
- if (this.log_to_console) {
- if (this.log_format === logFormatEnum.formats.JSON) {
- this.logger.add(new winston.transports.Console({ format: winston.format.json() }));
- } else {
- this.logger.add(
- new winston.transports.Console({
- format: winston.format.combine(
- winston.format((info) => {
- info.level = info.level.toUpperCase();
- return info;
- })(),
- winston.format.simple()
- ),
- })
- );
- }
- }
- }
-
- log(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody) {
- var content = this.formatLog(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody);
- if (this.logger.transports.length > 0) this.logger.log(level, content);
- }
-
- formatLog(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody) {
- var result;
- if (requestHeaders) requestHeaders['Authorization'] = '[REDACTED]';
- if (!this.log_request_body) requestBody = undefined;
- if (!this.log_response_body) responseBody = undefined;
- if (this.log_format && this.log_format === logFormatEnum.formats.JSON) {
- result = {
- level: level,
- date: new Date().toISOString(),
- method: method,
- url: decodeURIComponent(url),
- correlationId: responseHeaders ? (responseHeaders['inin-correlation-id'] ? responseHeaders['inin-correlation-id'] : '') : '',
- statusCode: statusCode,
- };
- if (requestHeaders) result.requestHeaders = requestHeaders;
- if (responseHeaders) result.responseHeaders = responseHeaders;
- if (requestBody) result.requestBody = requestBody;
- if (responseBody) result.responseBody = responseBody;
- } else {
- result = `${new Date().toISOString()}
-=== REQUEST ===
-${this.formatValue('URL', decodeURIComponent(url))}${this.formatValue('Method', method)}${this.formatValue(
- 'Headers',
- this.formatHeaderString(requestHeaders)
- )}${this.formatValue('Body', requestBody ? JSON.stringify(requestBody, null, 2) : '')}
-=== RESPONSE ===
-${this.formatValue('Status', statusCode)}${this.formatValue('Headers', this.formatHeaderString(responseHeaders))}${this.formatValue(
- 'CorrelationId',
- responseHeaders ? (responseHeaders['inin-correlation-id'] ? responseHeaders['inin-correlation-id'] : '') : ''
- )}${this.formatValue('Body', responseBody ? JSON.stringify(responseBody, null, 2) : '')}`;
- }
-
- return result;
- }
-
- formatHeaderString(headers) {
- var headerString = '';
- if (!headers) return headerString;
- for (const [key, value] of Object.entries(headers)) {
- headerString += `\n\t${key}: ${value}`;
- }
- return headerString;
- }
-
- formatValue(key, value) {
- if (!value || value === '' || value === '{}') return '';
- return `${key}: ${value}\n`;
- }
-
- getLogLevel(level) {
- switch (level) {
- case 'error':
- return logLevelEnum.level.LError;
- case 'debug':
- return logLevelEnum.level.LDebug;
- case 'trace':
- return logLevelEnum.level.LTrace;
- default:
- return logLevelEnum.level.LNone;
- }
- }
-
- getLogFormat(format) {
- switch (format) {
- case 'json':
- return logFormatEnum.formats.JSON;
- default:
- return logFormatEnum.formats.TEXT;
- }
- }
- }
-
- const ConfigParser = require('configparser');
- const os = require('os');
- const path = require('path');
- const fs = require('fs');
-
- class Configuration {
- /**
- * Singleton getter
- */
- get instance() {
- return Configuration.instance;
- }
-
- /**
- * Singleton setter
- */
- set instance(value) {
- Configuration.instance = value;
- }
-
- constructor() {
- if (!Configuration.instance) {
- Configuration.instance = this;
- }
-
- this.configPath = typeof window !== 'undefined' ? '' : path.join(os.homedir(), '.genesyscloudjavascript-guest', 'config');
- this.live_reload_config = true;
- this.host;
- this.environment;
- this.basePath;
- this.authUrl;
- this.config;
- this.logger = new Logger();
- this.setEnvironment();
- this.liveLoadConfig();
- }
-
- liveLoadConfig() {
- // If in browser, don't read config file, use default values
- if (typeof window !== 'undefined') {
- this.configPath = '';
- return;
- }
-
- this.updateConfigFromFile();
-
- if (this.live_reload_config && this.live_reload_config === true) {
- try {
- fs.watchFile(this.configPath, { persistent: false }, (eventType, filename) => {
- this.updateConfigFromFile();
- if (!this.live_reload_config) {
- fs.unwatchFile(this.configPath);
- }
- });
- } catch (err) {
- // do nothing
- }
- }
- }
-
- setConfigPath(path) {
- if (path && path !== this.configPath) {
- this.configPath = path;
- this.liveLoadConfig();
- }
- }
-
- updateConfigFromFile() {
- var configparser = new ConfigParser();
-
- try {
- configparser.read(this.configPath); // If no error catched, indicates it's INI format
- this.config = configparser;
- } catch (error) {
- if (error.name && error.name === 'MissingSectionHeaderError') {
- // Not INI format, see if it's JSON format
- var configData = fs.readFileSync(this.configPath, 'utf8');
- this.config = {
- _sections: JSON.parse(configData), // To match INI data format
- };
- }
- }
-
- if (this.config) this.updateConfigValues();
- }
-
- updateConfigValues() {
- this.logger.log_level = this.logger.getLogLevel(this.getConfigString('logging', 'log_level'));
- this.logger.log_format = this.logger.getLogFormat(this.getConfigString('logging', 'log_format'));
- this.logger.log_to_console =
- this.getConfigBoolean('logging', 'log_to_console') !== undefined
- ? this.getConfigBoolean('logging', 'log_to_console')
- : this.logger.log_to_console;
- this.logger.log_file_path =
- this.getConfigString('logging', 'log_file_path') !== undefined
- ? this.getConfigString('logging', 'log_file_path')
- : this.logger.log_file_path;
- this.logger.log_response_body =
- this.getConfigBoolean('logging', 'log_response_body') !== undefined
- ? this.getConfigBoolean('logging', 'log_response_body')
- : this.logger.log_response_body;
- this.logger.log_request_body =
- this.getConfigBoolean('logging', 'log_request_body') !== undefined
- ? this.getConfigBoolean('logging', 'log_request_body')
- : this.logger.log_request_body;
- this.live_reload_config =
- this.getConfigBoolean('general', 'live_reload_config') !== undefined
- ? this.getConfigBoolean('general', 'live_reload_config')
- : this.live_reload_config;
- this.host = this.getConfigString('general', 'host') !== undefined ? this.getConfigString('general', 'host') : this.host;
-
- this.setEnvironment();
-
- // Update logging configs
- this.logger.setLogger();
- }
-
- setEnvironment(env) {
- // Default value
- if (env) this.environment = env;
- else this.environment = this.host ? this.host : 'mypurecloud.com';
-
- // Strip trailing slash
- this.environment = this.environment.replace(/\/+$/, '');
-
- // Strip protocol and subdomain
- if (this.environment.startsWith('https://')) this.environment = this.environment.substring(8);
- if (this.environment.startsWith('http://')) this.environment = this.environment.substring(7);
- if (this.environment.startsWith('api.')) this.environment = this.environment.substring(4);
-
- this.basePath = `https://api.${this.environment}`;
- this.authUrl = `https://login.${this.environment}`;
- }
-
- getConfigString(section, key) {
- if (this.config._sections[section]) return this.config._sections[section][key];
- }
-
- getConfigBoolean(section, key) {
- if (this.config._sections[section] && this.config._sections[section][key] !== undefined) {
- if (typeof this.config._sections[section][key] === 'string') {
- return this.config._sections[section][key] === 'true';
- } else return this.config._sections[section][key];
- }
- }
- }
-
/**
* @module purecloud-guest-chat-client/ApiClient
- * @version 7.0.0
+ * @version 7.1.0
*/
class ApiClient {
/**
@@ -410,11 +93,6 @@ ${this.formatValue('Status', statusCode)}${this.formatValue('Headers', this.form
this.hasLocalStorage = false;
}
- /**
- * Create configuration instance for ApiClient and prepare logger.
- */
- this.config = new Configuration();
-
/**
* The base URL against which to resolve every API call's (relative) path.
* @type {String}
@@ -454,6 +132,16 @@ ${this.formatValue('Status', statusCode)}${this.formatValue('Headers', this.form
if (typeof(window) !== 'undefined') window.ApiClient = this;
}
+ /**
+ * @description Sets the debug log to enable debug logging
+ * @param {log} debugLog - In most cases use `console.log`
+ * @param {integer} maxLines - (optional) The max number of lines to write to the log. Must be > 0.
+ */
+ setDebugLog(debugLog, maxLines) {
+ this.debugLog = debugLog;
+ this.debugLogMaxLines = (maxLines && maxLines > 0) ? maxLines : undefined;
+ }
+
/**
* @description If set to `true`, the response object will contain additional information about the HTTP response. When `false` (default) only the body object will be returned.
* @param {boolean} returnExtended - `true` to return extended responses
@@ -470,6 +158,7 @@ ${this.formatValue('Status', statusCode)}${this.formatValue('Headers', this.form
setPersistSettings(doPersist, prefix) {
this.persistSettings = doPersist;
this.settingsPrefix = prefix ? prefix.replace(/\W+/g, '_') : 'purecloud';
+ this._debugTrace(`this.settingsPrefix=${this.settingsPrefix}`);
}
/**
@@ -494,6 +183,7 @@ ${this.formatValue('Status', statusCode)}${this.formatValue('Headers', this.form
// Ensure we can access local storage
if (!this.hasLocalStorage) {
+ this._debugTrace('Warning: Cannot access local storage. Settings will not be saved.');
return;
}
@@ -503,6 +193,7 @@ ${this.formatValue('Status', statusCode)}${this.formatValue('Headers', this.form
// Save updated auth data
localStorage.setItem(`${this.settingsPrefix}_auth_data`, JSON.stringify(tempData));
+ this._debugTrace('Auth data saved to local storage');
} catch (e) {
console.error(e);
}
@@ -517,6 +208,7 @@ ${this.formatValue('Status', statusCode)}${this.formatValue('Headers', this.form
// Ensure we can access local storage
if (!this.hasLocalStorage) {
+ this._debugTrace('Warning: Cannot access local storage. Settings will not be loaded.');
return;
}
@@ -536,7 +228,24 @@ ${this.formatValue('Status', statusCode)}${this.formatValue('Headers', this.form
* @param {string} environment - (Optional, default "mypurecloud.com") Environment the session use, e.g. mypurecloud.ie, mypurecloud.com.au, etc.
*/
setEnvironment(environment) {
- this.config.setEnvironment(environment);
+ if (!environment)
+ environment = 'mypurecloud.com';
+
+ // Strip trailing slash
+ environment = environment.replace(/\/+$/, '');
+
+ // Strip protocol and subdomain
+ if (environment.startsWith('https://'))
+ environment = environment.substring(8);
+ if (environment.startsWith('http://'))
+ environment = environment.substring(7);
+ if (environment.startsWith('api.'))
+ environment = environment.substring(4);
+
+ // Set vars
+ this.environment = environment;
+ this.basePath = `https://api.${environment}`;
+ this.authUrl = `https://login.${environment}`;
}
/**
@@ -593,7 +302,7 @@ ${this.formatValue('Status', statusCode)}${this.formatValue('Headers', this.form
*/
_buildAuthUrl(path, query) {
if (!query) query = {};
- return Object.keys(query).reduce((url, key) => !query[key] ? url : `${url}&${key}=${query[key]}`, `${this.config.authUrl}/${path}?`);
+ return Object.keys(query).reduce((url, key) => !query[key] ? url : `${url}&${key}=${query[key]}`, `${this.authUrl}/${path}?`);
}
/**
@@ -622,7 +331,7 @@ ${this.formatValue('Status', statusCode)}${this.formatValue('Headers', this.form
if (!path.match(/^\//)) {
path = `/${path}`;
}
- var url = this.config.basePath + path;
+ var url = this.basePath + path;
url = url.replace(/\{([\w-]+)\}/g, (fullMatch, key) => {
var value;
if (pathParams.hasOwnProperty(key)) {
@@ -807,6 +516,23 @@ ${this.formatValue('Status', statusCode)}${this.formatValue('Headers', this.form
request.proxy(this.proxy);
}
+ if(this.debugLog){
+ var trace = `[REQUEST] ${httpMethod} ${url}`;
+ if(pathParams && Object.keys(pathParams).count > 0 && pathParams[Object.keys(pathParams)[0]]){
+ trace += `\nPath Params: ${JSON.stringify(pathParams)}`;
+ }
+
+ if(queryParams && Object.keys(queryParams).count > 0 && queryParams[Object.keys(queryParams)[0]]){
+ trace += `\nQuery Params: ${JSON.stringify(queryParams)}`;
+ }
+
+ if(bodyParam){
+ trace += `\nnBody: ${JSON.stringify(bodyParam)}`;
+ }
+
+ this._debugTrace(trace);
+ }
+
// apply authentications
this.applyAuthToRequest(request, authNames);
@@ -815,7 +541,7 @@ ${this.formatValue('Status', statusCode)}${this.formatValue('Headers', this.form
// set header parameters
request.set(this.defaultHeaders).set(this.normalizeParams(headerParams));
- //request.set({ 'purecloud-sdk': '7.0.0' });
+ //request.set({ 'purecloud-sdk': '7.1.0' });
// set request timeout
request.timeout(this.timeout);
@@ -877,22 +603,23 @@ ${this.formatValue('Status', statusCode)}${this.formatValue('Headers', this.form
} : response.body ? response.body : response.text;
// Debug logging
- this.config.logger.log('trace', response.statusCode, httpMethod, url, request.header, response.headers, bodyParam, undefined);
- this.config.logger.log('debug', response.statusCode, httpMethod, url, request.header, undefined, bodyParam, undefined);
+ if (this.debugLog) {
+ var trace = `[RESPONSE] ${response.status}: ${httpMethod} ${url}`;
+ if (response.headers)
+ trace += `\ninin-correlation-id: ${response.headers['inin-correlation-id']}`;
+ if (response.body)
+ trace += `\nBody: ${JSON.stringify(response.body,null,2)}`;
+
+ // Log trace message
+ this._debugTrace(trace);
+
+ // Log stack trace
+ if (error)
+ this._debugTrace(error);
+ }
// Resolve promise
if (error) {
- // Log error
- this.config.logger.log(
- 'error',
- response.statusCode,
- httpMethod,
- url,
- request.header,
- response.headers,
- bodyParam,
- response.body
- );
reject(data);
} else {
resolve(data);
@@ -900,13 +627,46 @@ ${this.formatValue('Status', statusCode)}${this.formatValue('Headers', this.form
});
});
}
+
+ /**
+ * @description Parses an ISO-8601 string representation of a date value.
+ * @param {String} str The date value as a string.
+ * @returns {Date} The parsed date object.
+ */
+ parseDate(str) {
+ return new Date(str.replace(/T/i, ' '));
+ }
+
+ /**
+ * @description Logs to the debug log
+ * @param {String} str The date value as a string.
+ * @returns {Date} The parsed date object.
+ */
+ _debugTrace(trace) {
+ if (!this.debugLog) return;
+
+ if (typeof(trace) === 'string') {
+ // Truncate
+ var truncTrace = '';
+ var lines = trace.split('\n');
+ if (this.debugLogMaxLines && lines.length > this.debugLogMaxLines) {
+ for (var i = 0; i < this.debugLogMaxLines; i++) {
+ truncTrace += `${lines[i]}\n`;
+ }
+ truncTrace += '...response truncated...';
+ trace = truncTrace;
+ }
+ }
+
+ this.debugLog(trace);
+ }
}
class WebChatApi {
/**
* WebChat service.
* @module purecloud-guest-chat-client/api/WebChatApi
- * @version 7.0.0
+ * @version 7.1.0
*/
/**
@@ -1285,7 +1045,7 @@ ${this.formatValue('Status', statusCode)}${this.formatValue('Headers', this.form
*
*
* @module purecloud-guest-chat-client/index
- * @version 7.0.0
+ * @version 7.1.0
*/
class platformClient {
constructor() {
diff --git a/build/dist/web-amd/purecloud-guest-chat-client.min.js b/build/dist/web-amd/purecloud-guest-chat-client.min.js
index 35cb7275..e1806a51 100644
--- a/build/dist/web-amd/purecloud-guest-chat-client.min.js
+++ b/build/dist/web-amd/purecloud-guest-chat-client.min.js
@@ -1 +1 @@
-define(["superagent"],function(e){"use strict";e=e&&e.hasOwnProperty("default")?e.default:e;var t={us_east_1:"mypurecloud.com",eu_west_1:"mypurecloud.ie",ap_southeast_2:"mypurecloud.com.au",ap_northeast_1:"mypurecloud.jp",eu_central_1:"mypurecloud.de",us_west_2:"usw2.pure.cloud",ca_central_1:"cac1.pure.cloud",ap_northeast_2:"apne2.pure.cloud",eu_west_2:"euw2.pure.cloud"};const i=require("winston"),s={levels:{none:0,error:1,debug:2,trace:3}},o={level:{LNone:"none",LError:"error",LDebug:"debug",LTrace:"trace"}},a={formats:{JSON:"json",TEXT:"text"}};class n{get logLevelEnum(){return o}get logFormatEnum(){return a}constructor(){this.log_level=o.level.LNone,this.log_format=a.formats.TEXT,this.log_to_console=!0,this.log_file_path,this.log_response_body=!1,this.log_request_body=!1,this.setLogger()}createNewLogger(){this.logger=i.createLogger({levels:s.levels,level:this.log_level})}setLogger(){this.createNewLogger(),this.log_file_path&&""!==this.log_file_path&&(this.log_format===a.formats.JSON?this.logger.add(new i.transports.File({format:i.format.json(),filename:this.log_file_path})):this.logger.add(new i.transports.File({format:i.format.combine(i.format(e=>(e.level=e.level.toUpperCase(),e))(),i.format.simple()),filename:this.log_file_path}))),this.log_to_console&&(this.log_format===a.formats.JSON?this.logger.add(new i.transports.Console({format:i.format.json()})):this.logger.add(new i.transports.Console({format:i.format.combine(i.format(e=>(e.level=e.level.toUpperCase(),e))(),i.format.simple())})))}log(e,t,i,s,o,a,n,r){var l=this.formatLog(e,t,i,s,o,a,n,r);this.logger.transports.length>0&&this.logger.log(e,l)}formatLog(e,t,i,s,o,n,r,l){var h;return o&&(o.Authorization="[REDACTED]"),this.log_request_body||(r=void 0),this.log_response_body||(l=void 0),this.log_format&&this.log_format===a.formats.JSON?(h={level:e,date:(new Date).toISOString(),method:i,url:decodeURIComponent(s),correlationId:n&&n["inin-correlation-id"]?n["inin-correlation-id"]:"",statusCode:t},o&&(h.requestHeaders=o),n&&(h.responseHeaders=n),r&&(h.requestBody=r),l&&(h.responseBody=l)):h=`${(new Date).toISOString()}\n=== REQUEST === \n${this.formatValue("URL",decodeURIComponent(s))}${this.formatValue("Method",i)}${this.formatValue("Headers",this.formatHeaderString(o))}${this.formatValue("Body",r?JSON.stringify(r,null,2):"")}\n=== RESPONSE ===\n${this.formatValue("Status",t)}${this.formatValue("Headers",this.formatHeaderString(n))}${this.formatValue("CorrelationId",n&&n["inin-correlation-id"]?n["inin-correlation-id"]:"")}${this.formatValue("Body",l?JSON.stringify(l,null,2):"")}`,h}formatHeaderString(e){var t="";if(!e)return t;for(const[i,s]of Object.entries(e))t+=`\n\t${i}: ${s}`;return t}formatValue(e,t){return t&&""!==t&&"{}"!==t?`${e}: ${t}\n`:""}getLogLevel(e){switch(e){case"error":return o.level.LError;case"debug":return o.level.LDebug;case"trace":return o.level.LTrace;default:return o.level.LNone}}getLogFormat(e){switch(e){case"json":return a.formats.JSON;default:return a.formats.TEXT}}}const r=require("configparser"),l=require("os"),h=require("path"),g=require("fs");class u{get instance(){return u.instance}set instance(e){u.instance=e}constructor(){u.instance||(u.instance=this),this.configPath="undefined"!=typeof window?"":h.join(l.homedir(),".genesyscloudjavascript-guest","config"),this.live_reload_config=!0,this.host,this.environment,this.basePath,this.authUrl,this.config,this.logger=new n,this.setEnvironment(),this.liveLoadConfig()}liveLoadConfig(){if("undefined"==typeof window){if(this.updateConfigFromFile(),this.live_reload_config&&!0===this.live_reload_config)try{g.watchFile(this.configPath,{persistent:!1},(e,t)=>{this.updateConfigFromFile(),this.live_reload_config||g.unwatchFile(this.configPath)})}catch(e){}}else this.configPath=""}setConfigPath(e){e&&e!==this.configPath&&(this.configPath=e,this.liveLoadConfig())}updateConfigFromFile(){var e=new r;try{e.read(this.configPath),this.config=e}catch(e){if(e.name&&"MissingSectionHeaderError"===e.name){var t=g.readFileSync(this.configPath,"utf8");this.config={_sections:JSON.parse(t)}}}this.config&&this.updateConfigValues()}updateConfigValues(){this.logger.log_level=this.logger.getLogLevel(this.getConfigString("logging","log_level")),this.logger.log_format=this.logger.getLogFormat(this.getConfigString("logging","log_format")),this.logger.log_to_console=void 0!==this.getConfigBoolean("logging","log_to_console")?this.getConfigBoolean("logging","log_to_console"):this.logger.log_to_console,this.logger.log_file_path=void 0!==this.getConfigString("logging","log_file_path")?this.getConfigString("logging","log_file_path"):this.logger.log_file_path,this.logger.log_response_body=void 0!==this.getConfigBoolean("logging","log_response_body")?this.getConfigBoolean("logging","log_response_body"):this.logger.log_response_body,this.logger.log_request_body=void 0!==this.getConfigBoolean("logging","log_request_body")?this.getConfigBoolean("logging","log_request_body"):this.logger.log_request_body,this.live_reload_config=void 0!==this.getConfigBoolean("general","live_reload_config")?this.getConfigBoolean("general","live_reload_config"):this.live_reload_config,this.host=void 0!==this.getConfigString("general","host")?this.getConfigString("general","host"):this.host,this.setEnvironment(),this.logger.setLogger()}setEnvironment(e){this.environment=e||(this.host?this.host:"mypurecloud.com"),this.environment=this.environment.replace(/\/+$/,""),this.environment.startsWith("https://")&&(this.environment=this.environment.substring(8)),this.environment.startsWith("http://")&&(this.environment=this.environment.substring(7)),this.environment.startsWith("api.")&&(this.environment=this.environment.substring(4)),this.basePath=`https://api.${this.environment}`,this.authUrl=`https://login.${this.environment}`}getConfigString(e,t){if(this.config._sections[e])return this.config._sections[e][t]}getConfigBoolean(e,t){if(this.config._sections[e]&&void 0!==this.config._sections[e][t])return"string"==typeof this.config._sections[e][t]?"true"===this.config._sections[e][t]:this.config._sections[e][t]}}class c{get instance(){return c.instance}set instance(e){c.instance=e}constructor(){c.instance||(c.instance=this),this.CollectionFormatEnum={CSV:",",SSV:" ",TSV:"\t",PIPES:"|",MULTI:"multi"};try{localStorage.setItem("purecloud_local_storage_test","purecloud_local_storage_test"),localStorage.removeItem("purecloud_local_storage_test"),this.hasLocalStorage=!0}catch(e){this.hasLocalStorage=!1}this.config=new u,this.setEnvironment("https://api.mypurecloud.com"),this.authentications={"PureCloud OAuth":{type:"oauth2"},"Guest Chat JWT":{type:"apiKey",in:"header",name:"Authorization",apiKeyPrefix:"Bearer"}},this.defaultHeaders={},this.timeout=16e3,this.authData={},this.settingsPrefix="purecloud",this.superagent=e,"undefined"!=typeof window&&(window.ApiClient=this)}setReturnExtendedResponses(e){this.returnExtended=e}setPersistSettings(e,t){this.persistSettings=e,this.settingsPrefix=t?t.replace(/\W+/g,"_"):"purecloud"}_saveSettings(e){try{if(this.authData.apiKey=e.apiKey,this.authentications["Guest Chat JWT"].apiKey=e.apiKey,e.state&&(this.authData.state=e.state),e.tokenExpiryTime&&(this.authData.tokenExpiryTime=e.tokenExpiryTime,this.authData.tokenExpiryTimeString=e.tokenExpiryTimeString),!0!==this.persistSettings)return;if(!this.hasLocalStorage)return;let t=JSON.parse(JSON.stringify(this.authData));delete t.state,localStorage.setItem(`${this.settingsPrefix}_auth_data`,JSON.stringify(t))}catch(e){console.error(e)}}_loadSettings(){if(!0!==this.persistSettings)return;if(!this.hasLocalStorage)return;const e=this.authData.state;this.authData=localStorage.getItem(`${this.settingsPrefix}_auth_data`),this.authData?this.authData=JSON.parse(this.authData):this.authData={},this.authData.apiKey&&this.setJwt(this.authData.apiKey),this.authData.state=e}setEnvironment(e){this.config.setEnvironment(e)}_testTokenAccess(){return new Promise((e,t)=>{this._loadSettings(),this.authentications["Guest Chat JWT"].apiKey?this.callApi("/api/v2/authorization/permissions","GET",null,null,null,null,null,["Guest Chat JWT"],["application/json"],["application/json"]).then(()=>{e()}).catch(e=>{this._saveSettings({apiKey:void 0}),t(e)}):t(new Error("Token is not set"))})}setJwt(e){this._saveSettings({apiKey:e})}setStorageKey(e){this.storageKey=e,this.setJwt(this.authentications["Guest Chat JWT"].apiKey)}_buildAuthUrl(e,t){return t||(t={}),Object.keys(t).reduce((e,i)=>t[i]?`${e}&${i}=${t[i]}`:e,`${this.config.authUrl}/${e}?`)}paramToString(e){return e?e instanceof Date?e.toJSON():e.toString():""}buildUrl(e,t){e.match(/^\//)||(e=`/${e}`);var i=this.config.basePath+e;return i=i.replace(/\{([\w-]+)\}/g,(e,i)=>{var s;return s=t.hasOwnProperty(i)?this.paramToString(t[i]):e,encodeURIComponent(s)})}isJsonMime(e){return Boolean(e&&e.match(/^application\/json(;.*)?$/i))}jsonPreferredMime(e){for(var t=0;t{var i=this.authentications[t];switch(i.type){case"basic":(i.username||i.password)&&e.auth(i.username||"",i.password||"");break;case"apiKey":if(i.apiKey){var s={};i.apiKeyPrefix?s[i.name]=`${i.apiKeyPrefix} ${i.apiKey}`:s[i.name]=i.apiKey,"header"===i.in?e.set(s):e.query(s)}break;case"oauth2":i.accessToken&&e.set({Authorization:`Bearer ${i.accessToken}`});break;default:throw new Error(`Unknown authentication type: ${i.type}`)}})}callApi(t,i,s,o,a,n,r,l,h,g){var u=this.buildUrl(t,s),c=e(i,u);this.proxy&&c.proxy&&c.proxy(this.proxy),this.applyAuthToRequest(c,l),c.query(this.normalizeParams(o)),c.set(this.defaultHeaders).set(this.normalizeParams(a)),c.timeout(this.timeout);var d=this.jsonPreferredMime(h);if(d?c.type(d):c.header["Content-Type"]||c.type("application/json"),"application/x-www-form-urlencoded"===d)c.send(this.normalizeParams(n));else if("multipart/form-data"==d){var p=this.normalizeParams(n);for(var m in p)p.hasOwnProperty(m)&&(this.isFileParam(p[m])?c.attach(m,p[m]):c.field(m,p[m]))}else r&&c.send(r);var f=this.jsonPreferredMime(g);return f&&c.accept(f),new Promise((e,t)=>{c.end((s,o)=>{if(!s||o){var a=!0===this.returnExtended||s?{status:o.status,statusText:o.statusText,headers:o.headers,body:o.body,text:o.text,error:s}:o.body?o.body:o.text;this.config.logger.log("trace",o.statusCode,i,u,c.header,o.headers,r,void 0),this.config.logger.log("debug",o.statusCode,i,u,c.header,void 0,r,void 0),s?(this.config.logger.log("error",o.statusCode,i,u,c.header,o.headers,r,o.body),t(a)):e(a)}else t({status:0,statusText:"error",headers:[],body:{},text:"error",error:s})})})}}class d{constructor(e){this.apiClient=e||c.instance}deleteWebchatGuestConversationMember(e,t){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling deleteWebchatGuestConversationMember';if(void 0===t||null===t)throw'Missing the required parameter "memberId" when calling deleteWebchatGuestConversationMember';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/members/{memberId}","DELETE",{conversationId:e,memberId:t},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMediarequest(e,t){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMediarequest';if(void 0===t||null===t)throw'Missing the required parameter "mediaRequestId" when calling getWebchatGuestConversationMediarequest';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/mediarequests/{mediaRequestId}","GET",{conversationId:e,mediaRequestId:t},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMediarequests(e){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMediarequests';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/mediarequests","GET",{conversationId:e},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMember(e,t){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMember';if(void 0===t||null===t)throw'Missing the required parameter "memberId" when calling getWebchatGuestConversationMember';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/members/{memberId}","GET",{conversationId:e,memberId:t},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMembers(e,t){if(t=t||{},void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMembers';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/members","GET",{conversationId:e},{pageSize:t.pageSize,pageNumber:t.pageNumber,excludeDisconnectedMembers:t.excludeDisconnectedMembers},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMessage(e,t){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMessage';if(void 0===t||null===t)throw'Missing the required parameter "messageId" when calling getWebchatGuestConversationMessage';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/messages/{messageId}","GET",{conversationId:e,messageId:t},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMessages(e,t){if(t=t||{},void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMessages';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/messages","GET",{conversationId:e},{after:t.after,before:t.before,sortOrder:t.sortOrder,maxResults:t.maxResults},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}patchWebchatGuestConversationMediarequest(e,t,i){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling patchWebchatGuestConversationMediarequest';if(void 0===t||null===t)throw'Missing the required parameter "mediaRequestId" when calling patchWebchatGuestConversationMediarequest';if(void 0===i||null===i)throw'Missing the required parameter "body" when calling patchWebchatGuestConversationMediarequest';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/mediarequests/{mediaRequestId}","PATCH",{conversationId:e,mediaRequestId:t},{},{},{},i,["Guest Chat JWT"],["application/json"],["application/json"])}postWebchatGuestConversationMemberMessages(e,t,i){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling postWebchatGuestConversationMemberMessages';if(void 0===t||null===t)throw'Missing the required parameter "memberId" when calling postWebchatGuestConversationMemberMessages';if(void 0===i||null===i)throw'Missing the required parameter "body" when calling postWebchatGuestConversationMemberMessages';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/members/{memberId}/messages","POST",{conversationId:e,memberId:t},{},{},{},i,["Guest Chat JWT"],["application/json"],["application/json"])}postWebchatGuestConversationMemberTyping(e,t){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling postWebchatGuestConversationMemberTyping';if(void 0===t||null===t)throw'Missing the required parameter "memberId" when calling postWebchatGuestConversationMemberTyping';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/members/{memberId}/typing","POST",{conversationId:e,memberId:t},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}postWebchatGuestConversations(e){if(void 0===e||null===e)throw'Missing the required parameter "body" when calling postWebchatGuestConversations';return this.apiClient.callApi("/api/v2/webchat/guest/conversations","POST",{},{},{},{},e,[],["application/json"],["application/json"])}}return new class{constructor(){this.ApiClient=new c,this.WebChatApi=d,this.PureCloudRegionHosts=t}}});
\ No newline at end of file
+define(["superagent"],function(e){"use strict";e=e&&e.hasOwnProperty("default")?e.default:e;var t={us_east_1:"mypurecloud.com",eu_west_1:"mypurecloud.ie",ap_southeast_2:"mypurecloud.com.au",ap_northeast_1:"mypurecloud.jp",eu_central_1:"mypurecloud.de",us_west_2:"usw2.pure.cloud",ca_central_1:"cac1.pure.cloud",ap_northeast_2:"apne2.pure.cloud",eu_west_2:"euw2.pure.cloud"};class a{get instance(){return a.instance}set instance(e){a.instance=e}constructor(){a.instance||(a.instance=this),this.CollectionFormatEnum={CSV:",",SSV:" ",TSV:"\t",PIPES:"|",MULTI:"multi"};try{localStorage.setItem("purecloud_local_storage_test","purecloud_local_storage_test"),localStorage.removeItem("purecloud_local_storage_test"),this.hasLocalStorage=!0}catch(e){this.hasLocalStorage=!1}this.setEnvironment("https://api.mypurecloud.com"),this.authentications={"PureCloud OAuth":{type:"oauth2"},"Guest Chat JWT":{type:"apiKey",in:"header",name:"Authorization",apiKeyPrefix:"Bearer"}},this.defaultHeaders={},this.timeout=16e3,this.authData={},this.settingsPrefix="purecloud",this.superagent=e,"undefined"!=typeof window&&(window.ApiClient=this)}setDebugLog(e,t){this.debugLog=e,this.debugLogMaxLines=t&&t>0?t:void 0}setReturnExtendedResponses(e){this.returnExtended=e}setPersistSettings(e,t){this.persistSettings=e,this.settingsPrefix=t?t.replace(/\W+/g,"_"):"purecloud",this._debugTrace(`this.settingsPrefix=${this.settingsPrefix}`)}_saveSettings(e){try{if(this.authData.apiKey=e.apiKey,this.authentications["Guest Chat JWT"].apiKey=e.apiKey,e.state&&(this.authData.state=e.state),e.tokenExpiryTime&&(this.authData.tokenExpiryTime=e.tokenExpiryTime,this.authData.tokenExpiryTimeString=e.tokenExpiryTimeString),!0!==this.persistSettings)return;if(!this.hasLocalStorage)return void this._debugTrace("Warning: Cannot access local storage. Settings will not be saved.");let t=JSON.parse(JSON.stringify(this.authData));delete t.state,localStorage.setItem(`${this.settingsPrefix}_auth_data`,JSON.stringify(t)),this._debugTrace("Auth data saved to local storage")}catch(e){console.error(e)}}_loadSettings(){if(!0!==this.persistSettings)return;if(!this.hasLocalStorage)return void this._debugTrace("Warning: Cannot access local storage. Settings will not be loaded.");const e=this.authData.state;this.authData=localStorage.getItem(`${this.settingsPrefix}_auth_data`),this.authData?this.authData=JSON.parse(this.authData):this.authData={},this.authData.apiKey&&this.setJwt(this.authData.apiKey),this.authData.state=e}setEnvironment(e){e||(e="mypurecloud.com"),(e=e.replace(/\/+$/,"")).startsWith("https://")&&(e=e.substring(8)),e.startsWith("http://")&&(e=e.substring(7)),e.startsWith("api.")&&(e=e.substring(4)),this.environment=e,this.basePath=`https://api.${e}`,this.authUrl=`https://login.${e}`}_testTokenAccess(){return new Promise((e,t)=>{this._loadSettings(),this.authentications["Guest Chat JWT"].apiKey?this.callApi("/api/v2/authorization/permissions","GET",null,null,null,null,null,["Guest Chat JWT"],["application/json"],["application/json"]).then(()=>{e()}).catch(e=>{this._saveSettings({apiKey:void 0}),t(e)}):t(new Error("Token is not set"))})}setJwt(e){this._saveSettings({apiKey:e})}setStorageKey(e){this.storageKey=e,this.setJwt(this.authentications["Guest Chat JWT"].apiKey)}_buildAuthUrl(e,t){return t||(t={}),Object.keys(t).reduce((e,a)=>t[a]?`${e}&${a}=${t[a]}`:e,`${this.authUrl}/${e}?`)}paramToString(e){return e?e instanceof Date?e.toJSON():e.toString():""}buildUrl(e,t){e.match(/^\//)||(e=`/${e}`);var a=this.basePath+e;return a=a.replace(/\{([\w-]+)\}/g,(e,a)=>{var i;return i=t.hasOwnProperty(a)?this.paramToString(t[a]):e,encodeURIComponent(i)})}isJsonMime(e){return Boolean(e&&e.match(/^application\/json(;.*)?$/i))}jsonPreferredMime(e){for(var t=0;t{var a=this.authentications[t];switch(a.type){case"basic":(a.username||a.password)&&e.auth(a.username||"",a.password||"");break;case"apiKey":if(a.apiKey){var i={};a.apiKeyPrefix?i[a.name]=`${a.apiKeyPrefix} ${a.apiKey}`:i[a.name]=a.apiKey,"header"===a.in?e.set(i):e.query(i)}break;case"oauth2":a.accessToken&&e.set({Authorization:`Bearer ${a.accessToken}`});break;default:throw new Error(`Unknown authentication type: ${a.type}`)}})}callApi(t,a,i,s,n,r,o,u,h,l){var c=this.buildUrl(t,i),p=e(a,c);if(this.proxy&&p.proxy&&p.proxy(this.proxy),this.debugLog){var d=`[REQUEST] ${a} ${c}`;i&&Object.keys(i).count>0&&i[Object.keys(i)[0]]&&(d+=`\nPath Params: ${JSON.stringify(i)}`),s&&Object.keys(s).count>0&&s[Object.keys(s)[0]]&&(d+=`\nQuery Params: ${JSON.stringify(s)}`),o&&(d+=`\nnBody: ${JSON.stringify(o)}`),this._debugTrace(d)}this.applyAuthToRequest(p,u),p.query(this.normalizeParams(s)),p.set(this.defaultHeaders).set(this.normalizeParams(n)),p.timeout(this.timeout);var g=this.jsonPreferredMime(h);if(g?p.type(g):p.header["Content-Type"]||p.type("application/json"),"application/x-www-form-urlencoded"===g)p.send(this.normalizeParams(r));else if("multipart/form-data"==g){var m=this.normalizeParams(r);for(var v in m)m.hasOwnProperty(v)&&(this.isFileParam(m[v])?p.attach(v,m[v]):p.field(v,m[v]))}else o&&p.send(o);var b=this.jsonPreferredMime(l);return b&&p.accept(b),new Promise((e,t)=>{p.end((i,s)=>{if(!i||s){var n=!0===this.returnExtended||i?{status:s.status,statusText:s.statusText,headers:s.headers,body:s.body,text:s.text,error:i}:s.body?s.body:s.text;if(this.debugLog){var r=`[RESPONSE] ${s.status}: ${a} ${c}`;s.headers&&(r+=`\ninin-correlation-id: ${s.headers["inin-correlation-id"]}`),s.body&&(r+=`\nBody: ${JSON.stringify(s.body,null,2)}`),this._debugTrace(r),i&&this._debugTrace(i)}i?t(n):e(n)}else t({status:0,statusText:"error",headers:[],body:{},text:"error",error:i})})})}parseDate(e){return new Date(e.replace(/T/i," "))}_debugTrace(e){if(this.debugLog){if("string"==typeof e){var t="",a=e.split("\n");if(this.debugLogMaxLines&&a.length>this.debugLogMaxLines){for(var i=0;i {
- info.level = info.level.toUpperCase();
- return info;
- })(),
- winston.format.simple()
- ),
- filename: this.log_file_path,
- })
- );
- }
- }
- if (this.log_to_console) {
- if (this.log_format === logFormatEnum.formats.JSON) {
- this.logger.add(new winston.transports.Console({ format: winston.format.json() }));
- } else {
- this.logger.add(
- new winston.transports.Console({
- format: winston.format.combine(
- winston.format((info) => {
- info.level = info.level.toUpperCase();
- return info;
- })(),
- winston.format.simple()
- ),
- })
- );
- }
- }
- }
-
- log(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody) {
- var content = this.formatLog(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody);
- if (this.logger.transports.length > 0) this.logger.log(level, content);
- }
-
- formatLog(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody) {
- var result;
- if (requestHeaders) requestHeaders['Authorization'] = '[REDACTED]';
- if (!this.log_request_body) requestBody = undefined;
- if (!this.log_response_body) responseBody = undefined;
- if (this.log_format && this.log_format === logFormatEnum.formats.JSON) {
- result = {
- level: level,
- date: new Date().toISOString(),
- method: method,
- url: decodeURIComponent(url),
- correlationId: responseHeaders ? (responseHeaders['inin-correlation-id'] ? responseHeaders['inin-correlation-id'] : '') : '',
- statusCode: statusCode,
- };
- if (requestHeaders) result.requestHeaders = requestHeaders;
- if (responseHeaders) result.responseHeaders = responseHeaders;
- if (requestBody) result.requestBody = requestBody;
- if (responseBody) result.responseBody = responseBody;
- } else {
- result = `${new Date().toISOString()}
-=== REQUEST ===
-${this.formatValue('URL', decodeURIComponent(url))}${this.formatValue('Method', method)}${this.formatValue(
- 'Headers',
- this.formatHeaderString(requestHeaders)
- )}${this.formatValue('Body', requestBody ? JSON.stringify(requestBody, null, 2) : '')}
-=== RESPONSE ===
-${this.formatValue('Status', statusCode)}${this.formatValue('Headers', this.formatHeaderString(responseHeaders))}${this.formatValue(
- 'CorrelationId',
- responseHeaders ? (responseHeaders['inin-correlation-id'] ? responseHeaders['inin-correlation-id'] : '') : ''
- )}${this.formatValue('Body', responseBody ? JSON.stringify(responseBody, null, 2) : '')}`;
- }
-
- return result;
- }
-
- formatHeaderString(headers) {
- var headerString = '';
- if (!headers) return headerString;
- for (const [key, value] of Object.entries(headers)) {
- headerString += `\n\t${key}: ${value}`;
- }
- return headerString;
- }
-
- formatValue(key, value) {
- if (!value || value === '' || value === '{}') return '';
- return `${key}: ${value}\n`;
- }
-
- getLogLevel(level) {
- switch (level) {
- case 'error':
- return logLevelEnum.level.LError;
- case 'debug':
- return logLevelEnum.level.LDebug;
- case 'trace':
- return logLevelEnum.level.LTrace;
- default:
- return logLevelEnum.level.LNone;
- }
- }
-
- getLogFormat(format) {
- switch (format) {
- case 'json':
- return logFormatEnum.formats.JSON;
- default:
- return logFormatEnum.formats.TEXT;
- }
- }
-}
-
-const ConfigParser = require('configparser');
-const os = require('os');
-const path = require('path');
-const fs = require('fs');
-
-class Configuration {
- /**
- * Singleton getter
- */
- get instance() {
- return Configuration.instance;
- }
-
- /**
- * Singleton setter
- */
- set instance(value) {
- Configuration.instance = value;
- }
-
- constructor() {
- if (!Configuration.instance) {
- Configuration.instance = this;
- }
-
- this.configPath = typeof window !== 'undefined' ? '' : path.join(os.homedir(), '.genesyscloudjavascript-guest', 'config');
- this.live_reload_config = true;
- this.host;
- this.environment;
- this.basePath;
- this.authUrl;
- this.config;
- this.logger = new Logger();
- this.setEnvironment();
- this.liveLoadConfig();
- }
-
- liveLoadConfig() {
- // If in browser, don't read config file, use default values
- if (typeof window !== 'undefined') {
- this.configPath = '';
- return;
- }
-
- this.updateConfigFromFile();
-
- if (this.live_reload_config && this.live_reload_config === true) {
- try {
- fs.watchFile(this.configPath, { persistent: false }, (eventType, filename) => {
- this.updateConfigFromFile();
- if (!this.live_reload_config) {
- fs.unwatchFile(this.configPath);
- }
- });
- } catch (err) {
- // do nothing
- }
- }
- }
-
- setConfigPath(path) {
- if (path && path !== this.configPath) {
- this.configPath = path;
- this.liveLoadConfig();
- }
- }
-
- updateConfigFromFile() {
- var configparser = new ConfigParser();
-
- try {
- configparser.read(this.configPath); // If no error catched, indicates it's INI format
- this.config = configparser;
- } catch (error) {
- if (error.name && error.name === 'MissingSectionHeaderError') {
- // Not INI format, see if it's JSON format
- var configData = fs.readFileSync(this.configPath, 'utf8');
- this.config = {
- _sections: JSON.parse(configData), // To match INI data format
- };
- }
- }
-
- if (this.config) this.updateConfigValues();
- }
-
- updateConfigValues() {
- this.logger.log_level = this.logger.getLogLevel(this.getConfigString('logging', 'log_level'));
- this.logger.log_format = this.logger.getLogFormat(this.getConfigString('logging', 'log_format'));
- this.logger.log_to_console =
- this.getConfigBoolean('logging', 'log_to_console') !== undefined
- ? this.getConfigBoolean('logging', 'log_to_console')
- : this.logger.log_to_console;
- this.logger.log_file_path =
- this.getConfigString('logging', 'log_file_path') !== undefined
- ? this.getConfigString('logging', 'log_file_path')
- : this.logger.log_file_path;
- this.logger.log_response_body =
- this.getConfigBoolean('logging', 'log_response_body') !== undefined
- ? this.getConfigBoolean('logging', 'log_response_body')
- : this.logger.log_response_body;
- this.logger.log_request_body =
- this.getConfigBoolean('logging', 'log_request_body') !== undefined
- ? this.getConfigBoolean('logging', 'log_request_body')
- : this.logger.log_request_body;
- this.live_reload_config =
- this.getConfigBoolean('general', 'live_reload_config') !== undefined
- ? this.getConfigBoolean('general', 'live_reload_config')
- : this.live_reload_config;
- this.host = this.getConfigString('general', 'host') !== undefined ? this.getConfigString('general', 'host') : this.host;
-
- this.setEnvironment();
-
- // Update logging configs
- this.logger.setLogger();
- }
-
- setEnvironment(env) {
- // Default value
- if (env) this.environment = env;
- else this.environment = this.host ? this.host : 'mypurecloud.com';
-
- // Strip trailing slash
- this.environment = this.environment.replace(/\/+$/, '');
-
- // Strip protocol and subdomain
- if (this.environment.startsWith('https://')) this.environment = this.environment.substring(8);
- if (this.environment.startsWith('http://')) this.environment = this.environment.substring(7);
- if (this.environment.startsWith('api.')) this.environment = this.environment.substring(4);
-
- this.basePath = `https://api.${this.environment}`;
- this.authUrl = `https://login.${this.environment}`;
- }
-
- getConfigString(section, key) {
- if (this.config._sections[section]) return this.config._sections[section][key];
- }
-
- getConfigBoolean(section, key) {
- if (this.config._sections[section] && this.config._sections[section][key] !== undefined) {
- if (typeof this.config._sections[section][key] === 'string') {
- return this.config._sections[section][key] === 'true';
- } else return this.config._sections[section][key];
- }
- }
-}
-
/**
* @module purecloud-guest-chat-client/ApiClient
- * @version 7.0.0
+ * @version 7.1.0
*/
class ApiClient {
/**
@@ -2377,11 +2060,6 @@ class ApiClient {
this.hasLocalStorage = false;
}
- /**
- * Create configuration instance for ApiClient and prepare logger.
- */
- this.config = new Configuration();
-
/**
* The base URL against which to resolve every API call's (relative) path.
* @type {String}
@@ -2421,6 +2099,16 @@ class ApiClient {
if (typeof(window) !== 'undefined') window.ApiClient = this;
}
+ /**
+ * @description Sets the debug log to enable debug logging
+ * @param {log} debugLog - In most cases use `console.log`
+ * @param {integer} maxLines - (optional) The max number of lines to write to the log. Must be > 0.
+ */
+ setDebugLog(debugLog, maxLines) {
+ this.debugLog = debugLog;
+ this.debugLogMaxLines = (maxLines && maxLines > 0) ? maxLines : undefined;
+ }
+
/**
* @description If set to `true`, the response object will contain additional information about the HTTP response. When `false` (default) only the body object will be returned.
* @param {boolean} returnExtended - `true` to return extended responses
@@ -2437,6 +2125,7 @@ class ApiClient {
setPersistSettings(doPersist, prefix) {
this.persistSettings = doPersist;
this.settingsPrefix = prefix ? prefix.replace(/\W+/g, '_') : 'purecloud';
+ this._debugTrace(`this.settingsPrefix=${this.settingsPrefix}`);
}
/**
@@ -2461,6 +2150,7 @@ class ApiClient {
// Ensure we can access local storage
if (!this.hasLocalStorage) {
+ this._debugTrace('Warning: Cannot access local storage. Settings will not be saved.');
return;
}
@@ -2470,6 +2160,7 @@ class ApiClient {
// Save updated auth data
localStorage.setItem(`${this.settingsPrefix}_auth_data`, JSON.stringify(tempData));
+ this._debugTrace('Auth data saved to local storage');
} catch (e) {
console.error(e);
}
@@ -2484,6 +2175,7 @@ class ApiClient {
// Ensure we can access local storage
if (!this.hasLocalStorage) {
+ this._debugTrace('Warning: Cannot access local storage. Settings will not be loaded.');
return;
}
@@ -2503,7 +2195,24 @@ class ApiClient {
* @param {string} environment - (Optional, default "mypurecloud.com") Environment the session use, e.g. mypurecloud.ie, mypurecloud.com.au, etc.
*/
setEnvironment(environment) {
- this.config.setEnvironment(environment);
+ if (!environment)
+ environment = 'mypurecloud.com';
+
+ // Strip trailing slash
+ environment = environment.replace(/\/+$/, '');
+
+ // Strip protocol and subdomain
+ if (environment.startsWith('https://'))
+ environment = environment.substring(8);
+ if (environment.startsWith('http://'))
+ environment = environment.substring(7);
+ if (environment.startsWith('api.'))
+ environment = environment.substring(4);
+
+ // Set vars
+ this.environment = environment;
+ this.basePath = `https://api.${environment}`;
+ this.authUrl = `https://login.${environment}`;
}
/**
@@ -2560,7 +2269,7 @@ class ApiClient {
*/
_buildAuthUrl(path, query) {
if (!query) query = {};
- return Object.keys(query).reduce((url, key) => !query[key] ? url : `${url}&${key}=${query[key]}`, `${this.config.authUrl}/${path}?`);
+ return Object.keys(query).reduce((url, key) => !query[key] ? url : `${url}&${key}=${query[key]}`, `${this.authUrl}/${path}?`);
}
/**
@@ -2589,7 +2298,7 @@ class ApiClient {
if (!path.match(/^\//)) {
path = `/${path}`;
}
- var url = this.config.basePath + path;
+ var url = this.basePath + path;
url = url.replace(/\{([\w-]+)\}/g, (fullMatch, key) => {
var value;
if (pathParams.hasOwnProperty(key)) {
@@ -2767,6 +2476,23 @@ class ApiClient {
request.proxy(this.proxy);
}
+ if(this.debugLog){
+ var trace = `[REQUEST] ${httpMethod} ${url}`;
+ if(pathParams && Object.keys(pathParams).count > 0 && pathParams[Object.keys(pathParams)[0]]){
+ trace += `\nPath Params: ${JSON.stringify(pathParams)}`;
+ }
+
+ if(queryParams && Object.keys(queryParams).count > 0 && queryParams[Object.keys(queryParams)[0]]){
+ trace += `\nQuery Params: ${JSON.stringify(queryParams)}`;
+ }
+
+ if(bodyParam){
+ trace += `\nnBody: ${JSON.stringify(bodyParam)}`;
+ }
+
+ this._debugTrace(trace);
+ }
+
// apply authentications
this.applyAuthToRequest(request, authNames);
@@ -2775,7 +2501,7 @@ class ApiClient {
// set header parameters
request.set(this.defaultHeaders).set(this.normalizeParams(headerParams));
- //request.set({ 'purecloud-sdk': '7.0.0' });
+ //request.set({ 'purecloud-sdk': '7.1.0' });
// set request timeout
request.timeout(this.timeout);
@@ -2837,22 +2563,23 @@ class ApiClient {
} : response.body ? response.body : response.text;
// Debug logging
- this.config.logger.log('trace', response.statusCode, httpMethod, url, request.header, response.headers, bodyParam, undefined);
- this.config.logger.log('debug', response.statusCode, httpMethod, url, request.header, undefined, bodyParam, undefined);
+ if (this.debugLog) {
+ var trace = `[RESPONSE] ${response.status}: ${httpMethod} ${url}`;
+ if (response.headers)
+ trace += `\ninin-correlation-id: ${response.headers['inin-correlation-id']}`;
+ if (response.body)
+ trace += `\nBody: ${JSON.stringify(response.body,null,2)}`;
+
+ // Log trace message
+ this._debugTrace(trace);
+
+ // Log stack trace
+ if (error)
+ this._debugTrace(error);
+ }
// Resolve promise
if (error) {
- // Log error
- this.config.logger.log(
- 'error',
- response.statusCode,
- httpMethod,
- url,
- request.header,
- response.headers,
- bodyParam,
- response.body
- );
reject(data);
} else {
resolve(data);
@@ -2860,13 +2587,46 @@ class ApiClient {
});
});
}
+
+ /**
+ * @description Parses an ISO-8601 string representation of a date value.
+ * @param {String} str The date value as a string.
+ * @returns {Date} The parsed date object.
+ */
+ parseDate(str) {
+ return new Date(str.replace(/T/i, ' '));
+ }
+
+ /**
+ * @description Logs to the debug log
+ * @param {String} str The date value as a string.
+ * @returns {Date} The parsed date object.
+ */
+ _debugTrace(trace) {
+ if (!this.debugLog) return;
+
+ if (typeof(trace) === 'string') {
+ // Truncate
+ var truncTrace = '';
+ var lines = trace.split('\n');
+ if (this.debugLogMaxLines && lines.length > this.debugLogMaxLines) {
+ for (var i = 0; i < this.debugLogMaxLines; i++) {
+ truncTrace += `${lines[i]}\n`;
+ }
+ truncTrace += '...response truncated...';
+ trace = truncTrace;
+ }
+ }
+
+ this.debugLog(trace);
+ }
}
class WebChatApi {
/**
* WebChat service.
* @module purecloud-guest-chat-client/api/WebChatApi
- * @version 7.0.0
+ * @version 7.1.0
*/
/**
@@ -3245,7 +3005,7 @@ class WebChatApi {
*
*
* @module purecloud-guest-chat-client/index
- * @version 7.0.0
+ * @version 7.1.0
*/
class platformClient {
constructor() {
diff --git a/build/dist/web-cjs/purecloud-guest-chat-client.js b/build/dist/web-cjs/purecloud-guest-chat-client.js
index 7b15edff..bae3fffd 100644
--- a/build/dist/web-cjs/purecloud-guest-chat-client.js
+++ b/build/dist/web-cjs/purecloud-guest-chat-client.js
@@ -1,32987 +1,4067 @@
require=(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
- * @license MIT
- */
-function compare(a, b) {
- 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;
-}
-function isBuffer(b) {
- if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
- return global.Buffer.isBuffer(b);
- }
- return !!(b != null && b._isBuffer);
-}
+exports.byteLength = byteLength
+exports.toByteArray = toByteArray
+exports.fromByteArray = fromByteArray
-// based on node assert, original notice:
-// NB: The URL to the CommonJS spec is kept just for tradition.
-// node-assert has evolved a lot since then, both in API and behavior.
+var lookup = []
+var revLookup = []
+var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
-// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
-//
-// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
-//
-// Originally from narwhal.js (http://narwhaljs.org)
-// Copyright (c) 2009 Thomas Robinson <280north.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 BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
-// ACTION 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 util = require('util/');
-var hasOwn = Object.prototype.hasOwnProperty;
-var pSlice = Array.prototype.slice;
-var functionsHaveNames = (function () {
- return function foo() {}.name === 'foo';
-}());
-function pToString (obj) {
- return Object.prototype.toString.call(obj);
-}
-function isView(arrbuf) {
- if (isBuffer(arrbuf)) {
- return false;
- }
- if (typeof global.ArrayBuffer !== 'function') {
- return false;
- }
- if (typeof ArrayBuffer.isView === 'function') {
- return ArrayBuffer.isView(arrbuf);
- }
- if (!arrbuf) {
- return false;
- }
- if (arrbuf instanceof DataView) {
- return true;
- }
- if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
- return true;
- }
- return false;
+var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
+for (var i = 0, len = code.length; i < len; ++i) {
+ lookup[i] = code[i]
+ revLookup[code.charCodeAt(i)] = i
}
-// 1. The assert module provides functions that throw
-// AssertionError's when particular conditions are not met. The
-// assert module must conform to the following interface.
-var assert = module.exports = ok;
+// 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
-// 2. The AssertionError is defined in assert.
-// new assert.AssertionError({ message: message,
-// actual: actual,
-// expected: expected })
+function getLens (b64) {
+ var len = b64.length
-var regex = /\s*function\s+([^\(\s]*)\s*/;
-// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
-function getName(func) {
- if (!util.isFunction(func)) {
- return;
- }
- if (functionsHaveNames) {
- return func.name;
- }
- var str = func.toString();
- var match = str.match(regex);
- return match && match[1];
-}
-assert.AssertionError = function AssertionError(options) {
- this.name = 'AssertionError';
- this.actual = options.actual;
- this.expected = options.expected;
- this.operator = options.operator;
- if (options.message) {
- this.message = options.message;
- this.generatedMessage = false;
- } else {
- this.message = getMessage(this);
- this.generatedMessage = true;
+ if (len % 4 > 0) {
+ throw new Error('Invalid string. Length must be a multiple of 4')
}
- var stackStartFunction = options.stackStartFunction || fail;
- if (Error.captureStackTrace) {
- Error.captureStackTrace(this, stackStartFunction);
- } else {
- // non v8 browsers so we can have a stacktrace
- var err = new Error();
- if (err.stack) {
- var out = err.stack;
-
- // try to strip useless frames
- var fn_name = getName(stackStartFunction);
- var idx = out.indexOf('\n' + fn_name);
- if (idx >= 0) {
- // once we have located the function frame
- // we need to strip out everything before it (and its line)
- var next_line = out.indexOf('\n', idx + 1);
- out = out.substring(next_line + 1);
- }
- this.stack = out;
- }
- }
-};
+ // 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
-// assert.AssertionError instanceof Error
-util.inherits(assert.AssertionError, Error);
+ var placeHoldersLen = validLen === len
+ ? 0
+ : 4 - (validLen % 4)
-function truncate(s, n) {
- if (typeof s === 'string') {
- return s.length < n ? s : s.slice(0, n);
- } else {
- return s;
- }
-}
-function inspect(something) {
- if (functionsHaveNames || !util.isFunction(something)) {
- return util.inspect(something);
- }
- var rawname = getName(something);
- var name = rawname ? ': ' + rawname : '';
- return '[Function' + name + ']';
-}
-function getMessage(self) {
- return truncate(inspect(self.actual), 128) + ' ' +
- self.operator + ' ' +
- truncate(inspect(self.expected), 128);
+ return [validLen, placeHoldersLen]
}
-// At present only the three keys mentioned above are used and
-// understood by the spec. Implementations or sub modules can pass
-// other keys to the AssertionError's constructor - they will be
-// ignored.
-
-// 3. All of the following functions must throw an AssertionError
-// when a corresponding condition is not met, with a message that
-// may be undefined if not provided. All assertion methods provide
-// both the actual and expected values to the assertion error for
-// display purposes.
-
-function fail(actual, expected, message, operator, stackStartFunction) {
- throw new assert.AssertionError({
- message: message,
- actual: actual,
- expected: expected,
- operator: operator,
- stackStartFunction: stackStartFunction
- });
+// 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
}
-// EXTENSION! allows for well behaved errors defined elsewhere.
-assert.fail = fail;
-
-// 4. Pure assertion tests whether a value is truthy, as determined
-// by !!guard.
-// assert.ok(guard, message_opt);
-// This statement is equivalent to assert.equal(true, !!guard,
-// message_opt);. To test strictly for the value true, use
-// assert.strictEqual(true, guard, message_opt);.
-
-function ok(value, message) {
- if (!value) fail(value, true, message, '==', assert.ok);
+function _byteLength (b64, validLen, placeHoldersLen) {
+ return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
-assert.ok = ok;
-
-// 5. The equality assertion tests shallow, coercive equality with
-// ==.
-// assert.equal(actual, expected, message_opt);
-assert.equal = function equal(actual, expected, message) {
- if (actual != expected) fail(actual, expected, message, '==', assert.equal);
-};
+function toByteArray (b64) {
+ var tmp
+ var lens = getLens(b64)
+ var validLen = lens[0]
+ var placeHoldersLen = lens[1]
-// 6. The non-equality assertion tests for whether two objects are not equal
-// with != assert.notEqual(actual, expected, message_opt);
+ var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
-assert.notEqual = function notEqual(actual, expected, message) {
- if (actual == expected) {
- fail(actual, expected, message, '!=', assert.notEqual);
- }
-};
+ var curByte = 0
-// 7. The equivalence assertion tests a deep equality relation.
-// assert.deepEqual(actual, expected, message_opt);
+ // if there are placeholders, only get up to the last complete 4 chars
+ var len = placeHoldersLen > 0
+ ? validLen - 4
+ : validLen
-assert.deepEqual = function deepEqual(actual, expected, message) {
- if (!_deepEqual(actual, expected, false)) {
- fail(actual, expected, message, 'deepEqual', assert.deepEqual);
+ 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
}
-};
-assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
- if (!_deepEqual(actual, expected, true)) {
- fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
+ if (placeHoldersLen === 2) {
+ tmp =
+ (revLookup[b64.charCodeAt(i)] << 2) |
+ (revLookup[b64.charCodeAt(i + 1)] >> 4)
+ arr[curByte++] = tmp & 0xFF
}
-};
-
-function _deepEqual(actual, expected, strict, memos) {
- // 7.1. All identical values are equivalent, as determined by ===.
- if (actual === expected) {
- return true;
- } else if (isBuffer(actual) && isBuffer(expected)) {
- return compare(actual, expected) === 0;
-
- // 7.2. If the expected value is a Date object, the actual value is
- // equivalent if it is also a Date object that refers to the same time.
- } else if (util.isDate(actual) && util.isDate(expected)) {
- return actual.getTime() === expected.getTime();
-
- // 7.3 If the expected value is a RegExp object, the actual value is
- // equivalent if it is also a RegExp object with the same source and
- // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
- } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
- return actual.source === expected.source &&
- actual.global === expected.global &&
- actual.multiline === expected.multiline &&
- actual.lastIndex === expected.lastIndex &&
- actual.ignoreCase === expected.ignoreCase;
-
- // 7.4. Other pairs that do not both pass typeof value == 'object',
- // equivalence is determined by ==.
- } else if ((actual === null || typeof actual !== 'object') &&
- (expected === null || typeof expected !== 'object')) {
- return strict ? actual === expected : actual == expected;
-
- // If both values are instances of typed arrays, wrap their underlying
- // ArrayBuffers in a Buffer each to increase performance
- // This optimization requires the arrays to have the same type as checked by
- // Object.prototype.toString (aka pToString). Never perform binary
- // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
- // bit patterns are not identical.
- } else if (isView(actual) && isView(expected) &&
- pToString(actual) === pToString(expected) &&
- !(actual instanceof Float32Array ||
- actual instanceof Float64Array)) {
- return compare(new Uint8Array(actual.buffer),
- new Uint8Array(expected.buffer)) === 0;
-
- // 7.5 For all other Object pairs, including Array objects, equivalence is
- // determined by having the same number of owned properties (as verified
- // with Object.prototype.hasOwnProperty.call), the same set of keys
- // (although not necessarily the same order), equivalent values for every
- // corresponding key, and an identical 'prototype' property. Note: this
- // accounts for both named and indexed properties on Arrays.
- } else if (isBuffer(actual) !== isBuffer(expected)) {
- return false;
- } else {
- memos = memos || {actual: [], expected: []};
-
- var actualIndex = memos.actual.indexOf(actual);
- if (actualIndex !== -1) {
- if (actualIndex === memos.expected.indexOf(expected)) {
- return true;
- }
- }
-
- memos.actual.push(actual);
- memos.expected.push(expected);
- return objEquiv(actual, expected, strict, memos);
+ 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
}
-}
-function isArguments(object) {
- return Object.prototype.toString.call(object) == '[object Arguments]';
+ return arr
}
-function objEquiv(a, b, strict, actualVisitedObjects) {
- if (a === null || a === undefined || b === null || b === undefined)
- return false;
- // if one is a primitive, the other must be same
- if (util.isPrimitive(a) || util.isPrimitive(b))
- return a === b;
- if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
- return false;
- var aIsArgs = isArguments(a);
- var bIsArgs = isArguments(b);
- if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
- return false;
- if (aIsArgs) {
- a = pSlice.call(a);
- b = pSlice.call(b);
- return _deepEqual(a, b, strict);
- }
- var ka = objectKeys(a);
- var kb = objectKeys(b);
- var key, i;
- // having the same number of owned properties (keys incorporates
- // hasOwnProperty)
- if (ka.length !== kb.length)
- return false;
- //the same set of keys (although not necessarily the same order),
- ka.sort();
- kb.sort();
- //~~~cheap key test
- for (i = ka.length - 1; i >= 0; i--) {
- if (ka[i] !== kb[i])
- return false;
- }
- //equivalent values for every corresponding key, and
- //~~~possibly expensive deep test
- for (i = ka.length - 1; i >= 0; i--) {
- key = ka[i];
- if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
- return false;
- }
- return true;
+function tripletToBase64 (num) {
+ return lookup[num >> 18 & 0x3F] +
+ lookup[num >> 12 & 0x3F] +
+ lookup[num >> 6 & 0x3F] +
+ lookup[num & 0x3F]
}
-// 8. The non-equivalence assertion tests for any deep inequality.
-// assert.notDeepEqual(actual, expected, message_opt);
-
-assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
- if (_deepEqual(actual, expected, false)) {
- fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
- }
-};
-
-assert.notDeepStrictEqual = notDeepStrictEqual;
-function notDeepStrictEqual(actual, expected, message) {
- if (_deepEqual(actual, expected, true)) {
- fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
+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
-// 9. The strict equality assertion tests strict equality, as determined by ===.
-// assert.strictEqual(actual, expected, message_opt);
+ // 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)))
+ }
-assert.strictEqual = function strictEqual(actual, expected, message) {
- if (actual !== expected) {
- fail(actual, expected, message, '===', assert.strictEqual);
+ // 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] +
+ '='
+ )
}
-};
-// 10. The strict non-equality assertion tests for strict inequality, as
-// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
+ return parts.join('')
+}
-assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
- if (actual === expected) {
- fail(actual, expected, message, '!==', assert.notStrictEqual);
- }
-};
+},{}],2:[function(require,module,exports){
+(function (Buffer){(function (){
+/*!
+ * The buffer module from node.js, for the browser.
+ *
+ * @author Feross Aboukhadijeh
+ * @license MIT
+ */
+/* eslint-disable no-proto */
-function expectedException(actual, expected) {
- if (!actual || !expected) {
- return false;
- }
+'use strict'
- if (Object.prototype.toString.call(expected) == '[object RegExp]') {
- return expected.test(actual);
- }
+var base64 = require('base64-js')
+var ieee754 = require('ieee754')
- try {
- if (actual instanceof expected) {
- return true;
- }
- } catch (e) {
- // Ignore. The instanceof check doesn't work for arrow functions.
- }
+exports.Buffer = Buffer
+exports.SlowBuffer = SlowBuffer
+exports.INSPECT_MAX_BYTES = 50
- if (Error.isPrototypeOf(expected)) {
- return false;
- }
+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()
- return expected.call({}, actual) === true;
+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 _tryBlock(block) {
- var error;
+function typedArraySupport () {
+ // Can typed array instances can be augmented?
try {
- block();
+ var arr = new Uint8Array(1)
+ arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
+ return arr.foo() === 42
} catch (e) {
- error = e;
+ return false
}
- return error;
}
-function _throws(shouldThrow, block, expected, message) {
- var actual;
-
- if (typeof block !== 'function') {
- throw new TypeError('"block" argument must be a function');
- }
-
- if (typeof expected === 'string') {
- message = expected;
- expected = null;
- }
-
- actual = _tryBlock(block);
-
- message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
- (message ? ' ' + message : '.');
-
- if (shouldThrow && !actual) {
- fail(actual, expected, 'Missing expected exception' + message);
+Object.defineProperty(Buffer.prototype, 'parent', {
+ enumerable: true,
+ get: function () {
+ if (!Buffer.isBuffer(this)) return undefined
+ return this.buffer
}
+})
- var userProvidedMessage = typeof message === 'string';
- var isUnwantedException = !shouldThrow && util.isError(actual);
- var isUnexpectedException = !shouldThrow && actual && !expected;
-
- if ((isUnwantedException &&
- userProvidedMessage &&
- expectedException(actual, expected)) ||
- isUnexpectedException) {
- fail(actual, expected, 'Got unwanted exception' + message);
+Object.defineProperty(Buffer.prototype, 'offset', {
+ enumerable: true,
+ get: function () {
+ if (!Buffer.isBuffer(this)) return undefined
+ return this.byteOffset
}
+})
- if ((shouldThrow && actual && expected &&
- !expectedException(actual, expected)) || (!shouldThrow && actual)) {
- throw actual;
+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)
+ buf.__proto__ = Buffer.prototype
+ return buf
}
-// 11. Expected to throw an error:
-// assert.throws(block, Error_opt, message_opt);
-
-assert.throws = function(block, /*optional*/error, /*optional*/message) {
- _throws(true, block, error, message);
-};
-
-// EXTENSION! This is annoying to write outside this module.
-assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
- _throws(false, block, error, message);
-};
+/**
+ * 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.
+ */
-assert.ifError = function(err) { if (err) throw err; };
+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)
+}
-// Expose a strict only variant of assert
-function strict(value, message) {
- if (!value) fail(value, true, message, '==', strict);
+// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
+if (typeof Symbol !== 'undefined' && Symbol.species != null &&
+ Buffer[Symbol.species] === Buffer) {
+ Object.defineProperty(Buffer, Symbol.species, {
+ value: null,
+ configurable: true,
+ enumerable: false,
+ writable: false
+ })
}
-assert.strict = objectAssign(strict, assert, {
- equal: assert.strictEqual,
- deepEqual: assert.deepStrictEqual,
- notEqual: assert.notStrictEqual,
- notDeepEqual: assert.notDeepStrictEqual
-});
-assert.strict.strict = assert.strict;
-var objectKeys = Object.keys || function (obj) {
- var keys = [];
- for (var key in obj) {
- if (hasOwn.call(obj, key)) keys.push(key);
- }
- return keys;
-};
+Buffer.poolSize = 8192 // not used by this implementation
-}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"object-assign":19,"util/":5}],3:[function(require,module,exports){
-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
+function from (value, encodingOrOffset, length) {
+ if (typeof value === 'string') {
+ return fromString(value, encodingOrOffset)
}
-}
-},{}],4:[function(require,module,exports){
-module.exports = function isBuffer(arg) {
- return arg && typeof arg === 'object'
- && typeof arg.copy === 'function'
- && typeof arg.fill === 'function'
- && typeof arg.readUInt8 === 'function';
-}
-},{}],5:[function(require,module,exports){
-(function (process,global){(function (){
-// 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 formatRegExp = /%[sdj%]/g;
-exports.format = function(f) {
- if (!isString(f)) {
- var objects = [];
- for (var i = 0; i < arguments.length; i++) {
- objects.push(inspect(arguments[i]));
- }
- return objects.join(' ');
- }
-
- var i = 1;
- var args = arguments;
- var len = args.length;
- var str = String(f).replace(formatRegExp, function(x) {
- if (x === '%%') return '%';
- if (i >= len) return x;
- switch (x) {
- case '%s': return String(args[i++]);
- case '%d': return Number(args[i++]);
- case '%j':
- try {
- return JSON.stringify(args[i++]);
- } catch (_) {
- return '[Circular]';
- }
- default:
- return x;
- }
- });
- for (var x = args[i]; i < len; x = args[++i]) {
- if (isNull(x) || !isObject(x)) {
- str += ' ' + x;
- } else {
- str += ' ' + inspect(x);
- }
+ if (ArrayBuffer.isView(value)) {
+ return fromArrayLike(value)
}
- return str;
-};
-
-// Mark that a method should not be used.
-// Returns a modified function which warns once by default.
-// If --no-deprecation is set, then it is a no-op.
-exports.deprecate = function(fn, msg) {
- // Allow for deprecating things in the process of starting up.
- if (isUndefined(global.process)) {
- return function() {
- return exports.deprecate(fn, msg).apply(this, arguments);
- };
+ if (value == null) {
+ throw TypeError(
+ 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
+ 'or Array-like Object. Received type ' + (typeof value)
+ )
}
- if (process.noDeprecation === true) {
- return fn;
+ if (isInstance(value, ArrayBuffer) ||
+ (value && isInstance(value.buffer, ArrayBuffer))) {
+ return fromArrayBuffer(value, encodingOrOffset, length)
}
- var warned = false;
- function deprecated() {
- if (!warned) {
- if (process.throwDeprecation) {
- throw new Error(msg);
- } else if (process.traceDeprecation) {
- console.trace(msg);
- } else {
- console.error(msg);
- }
- warned = true;
- }
- return fn.apply(this, arguments);
+ if (typeof value === 'number') {
+ throw new TypeError(
+ 'The "value" argument must not be of type number. Received type number'
+ )
}
- return deprecated;
-};
+ 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
-var debugs = {};
-var debugEnviron;
-exports.debuglog = function(set) {
- if (isUndefined(debugEnviron))
- debugEnviron = process.env.NODE_DEBUG || '';
- set = set.toUpperCase();
- if (!debugs[set]) {
- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
- var pid = process.pid;
- debugs[set] = function() {
- var msg = exports.format.apply(exports, arguments);
- console.error('%s %d: %s', set, pid, msg);
- };
- } else {
- debugs[set] = function() {};
- }
+ if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
+ typeof value[Symbol.toPrimitive] === 'function') {
+ return Buffer.from(
+ value[Symbol.toPrimitive]('string'), encodingOrOffset, length
+ )
}
- return debugs[set];
-};
+ throw new TypeError(
+ 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
+ 'or Array-like Object. Received type ' + (typeof value)
+ )
+}
/**
- * Echos the value of a value. Trys to print the value out
- * in the best way possible given the different types.
- *
- * @param {Object} obj The object to print out.
- * @param {Object} opts Optional options object that alters the output.
- */
-/* legacy: obj, showHidden, depth, colors*/
-function inspect(obj, opts) {
- // default options
- var ctx = {
- seen: [],
- stylize: stylizeNoColor
- };
- // legacy...
- if (arguments.length >= 3) ctx.depth = arguments[2];
- if (arguments.length >= 4) ctx.colors = arguments[3];
- if (isBoolean(opts)) {
- // legacy...
- ctx.showHidden = opts;
- } else if (opts) {
- // got an "options" object
- exports._extend(ctx, opts);
- }
- // set default options
- if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
- if (isUndefined(ctx.depth)) ctx.depth = 2;
- if (isUndefined(ctx.colors)) ctx.colors = false;
- if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
- if (ctx.colors) ctx.stylize = stylizeWithColor;
- return formatValue(ctx, obj, ctx.depth);
+ * 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)
}
-exports.inspect = inspect;
-
-
-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
-inspect.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]
-};
-// Don't use 'blue' not visible on cmd.exe
-inspect.styles = {
- 'special': 'cyan',
- 'number': 'yellow',
- 'boolean': 'yellow',
- 'undefined': 'grey',
- 'null': 'bold',
- 'string': 'green',
- 'date': 'magenta',
- // "name": intentionally not styling
- 'regexp': 'red'
-};
-
-
-function stylizeWithColor(str, styleType) {
- var style = inspect.styles[styleType];
+// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
+// https://github.com/feross/buffer/pull/148
+Buffer.prototype.__proto__ = Uint8Array.prototype
+Buffer.__proto__ = Uint8Array
- if (style) {
- return '\u001b[' + inspect.colors[style][0] + 'm' + str +
- '\u001b[' + inspect.colors[style][1] + 'm';
- } else {
- return str;
+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 stylizeNoColor(str, styleType) {
- return str;
+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 interpretted 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 arrayToHash(array) {
- var hash = {};
-
- array.forEach(function(val, idx) {
- hash[val] = true;
- });
-
- return hash;
+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 formatValue(ctx, value, recurseTimes) {
- // Provide a hook for user-specified inspect functions.
- // Check that value is an object with an inspect function on it
- if (ctx.customInspect &&
- value &&
- isFunction(value.inspect) &&
- // Filter out the util module, it's inspect function is special
- value.inspect !== exports.inspect &&
- // Also filter out any prototype objects using the circular check.
- !(value.constructor && value.constructor.prototype === value)) {
- var ret = value.inspect(recurseTimes, ctx);
- if (!isString(ret)) {
- ret = formatValue(ctx, ret, recurseTimes);
- }
- return ret;
+function fromString (string, encoding) {
+ if (typeof encoding !== 'string' || encoding === '') {
+ encoding = 'utf8'
}
- // Primitive types cannot have properties
- var primitive = formatPrimitive(ctx, value);
- if (primitive) {
- return primitive;
+ if (!Buffer.isEncoding(encoding)) {
+ throw new TypeError('Unknown encoding: ' + encoding)
}
- // Look up the keys of the object.
- var keys = Object.keys(value);
- var visibleKeys = arrayToHash(keys);
-
- if (ctx.showHidden) {
- keys = Object.getOwnPropertyNames(value);
- }
+ var length = byteLength(string, encoding) | 0
+ var buf = createBuffer(length)
- // IE doesn't make error fields non-enumerable
- // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
- if (isError(value)
- && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
- return formatError(value);
- }
+ var actual = buf.write(string, encoding)
- // Some type of object without properties can be shortcutted.
- if (keys.length === 0) {
- if (isFunction(value)) {
- var name = value.name ? ': ' + value.name : '';
- return ctx.stylize('[Function' + name + ']', 'special');
- }
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- }
- if (isDate(value)) {
- return ctx.stylize(Date.prototype.toString.call(value), 'date');
- }
- if (isError(value)) {
- return formatError(value);
- }
+ 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)
}
- var base = '', array = false, braces = ['{', '}'];
+ return buf
+}
- // Make Array say that they are Array
- if (isArray(value)) {
- array = true;
- braces = ['[', ']'];
+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
+}
- // Make functions say that they are functions
- if (isFunction(value)) {
- var n = value.name ? ': ' + value.name : '';
- base = ' [Function' + n + ']';
+function fromArrayBuffer (array, byteOffset, length) {
+ if (byteOffset < 0 || array.byteLength < byteOffset) {
+ throw new RangeError('"offset" is outside of buffer bounds')
}
- // Make RegExps say that they are RegExps
- if (isRegExp(value)) {
- base = ' ' + RegExp.prototype.toString.call(value);
+ if (array.byteLength < byteOffset + (length || 0)) {
+ throw new RangeError('"length" is outside of buffer bounds')
}
- // Make dates with properties first say the date
- if (isDate(value)) {
- base = ' ' + Date.prototype.toUTCString.call(value);
+ 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)
}
- // Make error with message first say the error
- if (isError(value)) {
- base = ' ' + formatError(value);
- }
+ // Return an augmented `Uint8Array` instance
+ buf.__proto__ = Buffer.prototype
+ return buf
+}
- if (keys.length === 0 && (!array || value.length == 0)) {
- return braces[0] + base + braces[1];
- }
+function fromObject (obj) {
+ if (Buffer.isBuffer(obj)) {
+ var len = checked(obj.length) | 0
+ var buf = createBuffer(len)
- if (recurseTimes < 0) {
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- } else {
- return ctx.stylize('[Object]', 'special');
+ if (buf.length === 0) {
+ return buf
}
- }
-
- ctx.seen.push(value);
- var output;
- if (array) {
- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
- } else {
- output = keys.map(function(key) {
- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
- });
+ obj.copy(buf, 0, 0, len)
+ return buf
}
- ctx.seen.pop();
+ if (obj.length !== undefined) {
+ if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
+ return createBuffer(0)
+ }
+ return fromArrayLike(obj)
+ }
- return reduceToSingleString(output, base, braces);
+ if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
+ return fromArrayLike(obj.data)
+ }
}
-
-function formatPrimitive(ctx, value) {
- if (isUndefined(value))
- return ctx.stylize('undefined', 'undefined');
- if (isString(value)) {
- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
- .replace(/'/g, "\\'")
- .replace(/\\"/g, '"') + '\'';
- return ctx.stylize(simple, 'string');
- }
- if (isNumber(value))
- return ctx.stylize('' + value, 'number');
- if (isBoolean(value))
- return ctx.stylize('' + value, 'boolean');
- // For some reason typeof null is "object", so special case here.
- if (isNull(value))
- return ctx.stylize('null', 'null');
+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)
+}
-function formatError(value) {
- return '[' + Error.prototype.toString.call(value) + ']';
+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'
+ )
+ }
-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
- var output = [];
- for (var i = 0, l = value.length; i < l; ++i) {
- if (hasOwnProperty(value, String(i))) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- String(i), true));
- } else {
- output.push('');
+ 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
}
}
- keys.forEach(function(key) {
- if (!key.match(/^\d+$/)) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- key, true));
- }
- });
- return output;
+
+ 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
+ }
+}
-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
- var name, str, desc;
- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
- if (desc.get) {
- if (desc.set) {
- str = ctx.stylize('[Getter/Setter]', 'special');
- } else {
- str = ctx.stylize('[Getter]', 'special');
- }
- } else {
- if (desc.set) {
- str = ctx.stylize('[Setter]', 'special');
- }
+Buffer.concat = function concat (list, length) {
+ if (!Array.isArray(list)) {
+ throw new TypeError('"list" argument must be an Array of Buffers')
}
- if (!hasOwnProperty(visibleKeys, key)) {
- name = '[' + key + ']';
+
+ if (list.length === 0) {
+ return Buffer.alloc(0)
}
- if (!str) {
- if (ctx.seen.indexOf(desc.value) < 0) {
- if (isNull(recurseTimes)) {
- str = formatValue(ctx, desc.value, null);
- } else {
- str = formatValue(ctx, desc.value, recurseTimes - 1);
- }
- if (str.indexOf('\n') > -1) {
- if (array) {
- str = str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n').substr(2);
- } else {
- str = '\n' + str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n');
- }
- }
- } else {
- str = ctx.stylize('[Circular]', 'special');
+
+ var i
+ if (length === undefined) {
+ length = 0
+ for (i = 0; i < list.length; ++i) {
+ length += list[i].length
}
}
- if (isUndefined(name)) {
- if (array && key.match(/^\d+$/)) {
- return str;
+
+ var buffer = Buffer.allocUnsafe(length)
+ var pos = 0
+ for (i = 0; i < list.length; ++i) {
+ var buf = list[i]
+ if (isInstance(buf, Uint8Array)) {
+ buf = Buffer.from(buf)
}
- name = JSON.stringify('' + key);
- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
- name = name.substr(1, name.length - 2);
- name = ctx.stylize(name, 'name');
- } else {
- name = name.replace(/'/g, "\\'")
- .replace(/\\"/g, '"')
- .replace(/(^"|"$)/g, "'");
- name = ctx.stylize(name, 'string');
+ if (!Buffer.isBuffer(buf)) {
+ throw new TypeError('"list" argument must be an Array of Buffers')
}
+ buf.copy(buffer, pos)
+ pos += buf.length
}
-
- return name + ': ' + str;
+ return buffer
}
-
-function reduceToSingleString(output, base, braces) {
- var numLinesEst = 0;
- var length = output.reduce(function(prev, cur) {
- numLinesEst++;
- if (cur.indexOf('\n') >= 0) numLinesEst++;
- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
- }, 0);
-
- if (length > 60) {
- return braces[0] +
- (base === '' ? '' : base + '\n ') +
- ' ' +
- output.join(',\n ') +
- ' ' +
- braces[1];
+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
+ )
}
- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
-}
-
-
-// NOTE: These type checking functions intentionally don't use `instanceof`
-// because it is fragile and can be easily faked with `Object.create()`.
-function isArray(ar) {
- return Array.isArray(ar);
-}
-exports.isArray = isArray;
+ var len = string.length
+ var mustMatch = (arguments.length > 2 && arguments[2] === true)
+ if (!mustMatch && len === 0) return 0
-function isBoolean(arg) {
- return typeof arg === 'boolean';
+ // 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
+ }
+ }
}
-exports.isBoolean = isBoolean;
+Buffer.byteLength = byteLength
-function isNull(arg) {
- return arg === null;
-}
-exports.isNull = isNull;
+function slowToString (encoding, start, end) {
+ var loweredCase = false
-function isNullOrUndefined(arg) {
- return arg == null;
-}
-exports.isNullOrUndefined = isNullOrUndefined;
+ // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
+ // property of a typed array.
-function isNumber(arg) {
- return typeof arg === 'number';
-}
-exports.isNumber = isNumber;
+ // 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 ''
+ }
-function isString(arg) {
- return typeof arg === 'string';
-}
-exports.isString = isString;
+ if (end === undefined || end > this.length) {
+ end = this.length
+ }
-function isSymbol(arg) {
- return typeof arg === 'symbol';
-}
-exports.isSymbol = isSymbol;
+ if (end <= 0) {
+ return ''
+ }
-function isUndefined(arg) {
- return arg === void 0;
-}
-exports.isUndefined = isUndefined;
+ // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
+ end >>>= 0
+ start >>>= 0
-function isRegExp(re) {
- return isObject(re) && objectToString(re) === '[object RegExp]';
-}
-exports.isRegExp = isRegExp;
+ if (end <= start) {
+ return ''
+ }
-function isObject(arg) {
- return typeof arg === 'object' && arg !== null;
-}
-exports.isObject = isObject;
+ if (!encoding) encoding = 'utf8'
-function isDate(d) {
- return isObject(d) && objectToString(d) === '[object Date]';
-}
-exports.isDate = isDate;
+ while (true) {
+ switch (encoding) {
+ case 'hex':
+ return hexSlice(this, start, end)
-function isError(e) {
- return isObject(e) &&
- (objectToString(e) === '[object Error]' || e instanceof Error);
-}
-exports.isError = isError;
+ case 'utf8':
+ case 'utf-8':
+ return utf8Slice(this, start, end)
-function isFunction(arg) {
- return typeof arg === 'function';
-}
-exports.isFunction = isFunction;
-
-function isPrimitive(arg) {
- return arg === null ||
- typeof arg === 'boolean' ||
- typeof arg === 'number' ||
- typeof arg === 'string' ||
- typeof arg === 'symbol' || // ES6 symbol
- typeof arg === 'undefined';
-}
-exports.isPrimitive = isPrimitive;
+ case 'ascii':
+ return asciiSlice(this, start, end)
-exports.isBuffer = require('./support/isBuffer');
+ case 'latin1':
+ case 'binary':
+ return latin1Slice(this, start, end)
-function objectToString(o) {
- return Object.prototype.toString.call(o);
-}
+ case 'base64':
+ return base64Slice(this, start, end)
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return utf16leSlice(this, start, end)
-function pad(n) {
- return n < 10 ? '0' + n.toString(10) : n.toString(10);
+ 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
-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
- 'Oct', 'Nov', 'Dec'];
-
-// 26 Feb 16:19:34
-function timestamp() {
- var d = new Date();
- var time = [pad(d.getHours()),
- pad(d.getMinutes()),
- pad(d.getSeconds())].join(':');
- return [d.getDate(), months[d.getMonth()], time].join(' ');
+function swap (b, n, m) {
+ var i = b[n]
+ b[n] = b[m]
+ b[m] = i
}
-
-// log is just a thin wrapper to console.log that prepends a timestamp
-exports.log = function() {
- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
-};
-
-
-/**
- * Inherit the prototype methods from one constructor into another.
- *
- * The Function.prototype.inherits from lang.js rewritten as a standalone
- * function (not on Function.prototype). NOTE: If this file is to be loaded
- * during bootstrapping this function needs to be rewritten using some native
- * functions as prototype setup using normal JavaScript does not work as
- * expected during bootstrapping (see mirror.js in r114903).
- *
- * @param {function} ctor Constructor function which needs to inherit the
- * prototype.
- * @param {function} superCtor Constructor function to inherit prototype from.
- */
-exports.inherits = require('inherits');
-
-exports._extend = function(origin, add) {
- // Don't do anything if add isn't an object
- if (!add || !isObject(add)) return origin;
-
- var keys = Object.keys(add);
- var i = keys.length;
- while (i--) {
- origin[keys[i]] = add[keys[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')
}
- return origin;
-};
-
-function hasOwnProperty(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
+ for (var i = 0; i < len; i += 2) {
+ swap(this, i, i + 1)
+ }
+ return this
}
-}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"./support/isBuffer":4,"_process":34,"inherits":3}],6:[function(require,module,exports){
-'use strict'
-
-exports.byteLength = byteLength
-exports.toByteArray = toByteArray
-exports.fromByteArray = 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')
+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')
}
-
- // 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]
+ for (var i = 0; i < len; i += 4) {
+ swap(this, i, i + 3)
+ swap(this, i + 1, i + 2)
+ }
+ return this
}
-// 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
+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
}
-function _byteLength (b64, validLen, placeHoldersLen) {
- return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
+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)
}
-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))
+Buffer.prototype.toLocaleString = Buffer.prototype.toString
- var curByte = 0
+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
+}
- // if there are placeholders, only get up to the last complete 4 chars
- var len = placeHoldersLen > 0
- ? validLen - 4
- : validLen
+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 ''
+}
- 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
+Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
+ if (isInstance(target, Uint8Array)) {
+ target = Buffer.from(target, target.offset, target.byteLength)
}
-
- if (placeHoldersLen === 2) {
- tmp =
- (revLookup[b64.charCodeAt(i)] << 2) |
- (revLookup[b64.charCodeAt(i + 1)] >> 4)
- arr[curByte++] = tmp & 0xFF
+ if (!Buffer.isBuffer(target)) {
+ throw new TypeError(
+ 'The "target" argument must be one of type Buffer or Uint8Array. ' +
+ 'Received type ' + (typeof target)
+ )
}
- 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
+ if (start === undefined) {
+ start = 0
}
-
- 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))
+ if (end === undefined) {
+ end = target ? target.length : 0
}
- 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)))
+ if (thisStart === undefined) {
+ thisStart = 0
}
-
- // 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] +
- '='
- )
+ if (thisEnd === undefined) {
+ thisEnd = this.length
}
- return parts.join('')
-}
+ if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
+ throw new RangeError('out of range index')
+ }
-},{}],7:[function(require,module,exports){
-arguments[4][1][0].apply(exports,arguments)
-},{"dup":1}],8:[function(require,module,exports){
-(function (process,Buffer){(function (){
-'use strict';
-/* eslint camelcase: "off" */
+ if (thisStart >= thisEnd && start >= end) {
+ return 0
+ }
+ if (thisStart >= thisEnd) {
+ return -1
+ }
+ if (start >= end) {
+ return 1
+ }
-var assert = require('assert');
+ start >>>= 0
+ end >>>= 0
+ thisStart >>>= 0
+ thisEnd >>>= 0
-var Zstream = require('pako/lib/zlib/zstream');
-var zlib_deflate = require('pako/lib/zlib/deflate.js');
-var zlib_inflate = require('pako/lib/zlib/inflate.js');
-var constants = require('pako/lib/zlib/constants');
+ if (this === target) return 0
-for (var key in constants) {
- exports[key] = constants[key];
-}
+ var x = thisEnd - thisStart
+ var y = end - start
+ var len = Math.min(x, y)
-// zlib modes
-exports.NONE = 0;
-exports.DEFLATE = 1;
-exports.INFLATE = 2;
-exports.GZIP = 3;
-exports.GUNZIP = 4;
-exports.DEFLATERAW = 5;
-exports.INFLATERAW = 6;
-exports.UNZIP = 7;
+ var thisCopy = this.slice(thisStart, thisEnd)
+ var targetCopy = target.slice(start, end)
-var GZIP_HEADER_ID1 = 0x1f;
-var GZIP_HEADER_ID2 = 0x8b;
+ for (var i = 0; i < len; ++i) {
+ if (thisCopy[i] !== targetCopy[i]) {
+ x = thisCopy[i]
+ y = targetCopy[i]
+ break
+ }
+ }
-/**
- * Emulate Node's zlib C++ layer for use by the JS layer in index.js
- */
-function Zlib(mode) {
- if (typeof mode !== 'number' || mode < exports.DEFLATE || mode > exports.UNZIP) {
- throw new TypeError('Bad argument');
- }
-
- this.dictionary = null;
- this.err = 0;
- this.flush = 0;
- this.init_done = false;
- this.level = 0;
- this.memLevel = 0;
- this.mode = mode;
- this.strategy = 0;
- this.windowBits = 0;
- this.write_in_progress = false;
- this.pending_close = false;
- this.gzip_id_bytes_read = 0;
+ if (x < y) return -1
+ if (y < x) return 1
+ return 0
}
-Zlib.prototype.close = function () {
- if (this.write_in_progress) {
- this.pending_close = true;
- return;
- }
+// 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
- this.pending_close = false;
+ // 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)
+ }
- assert(this.init_done, 'close before init');
- assert(this.mode <= exports.UNZIP);
+ // 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
+ }
- if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) {
- zlib_deflate.deflateEnd(this.strm);
- } else if (this.mode === exports.INFLATE || this.mode === exports.GUNZIP || this.mode === exports.INFLATERAW || this.mode === exports.UNZIP) {
- zlib_inflate.inflateEnd(this.strm);
+ // Normalize val
+ if (typeof val === 'string') {
+ val = Buffer.from(val, encoding)
}
- this.mode = exports.NONE;
-
- this.dictionary = null;
-};
-
-Zlib.prototype.write = function (flush, input, in_off, in_len, out, out_off, out_len) {
- return this._write(true, flush, input, in_off, in_len, out, out_off, out_len);
-};
-
-Zlib.prototype.writeSync = function (flush, input, in_off, in_len, out, out_off, out_len) {
- return this._write(false, flush, input, in_off, in_len, out, out_off, out_len);
-};
-
-Zlib.prototype._write = function (async, flush, input, in_off, in_len, out, out_off, out_len) {
- assert.equal(arguments.length, 8);
-
- assert(this.init_done, 'write before init');
- assert(this.mode !== exports.NONE, 'already finalized');
- assert.equal(false, this.write_in_progress, 'write already in progress');
- assert.equal(false, this.pending_close, 'close is pending');
-
- this.write_in_progress = true;
-
- assert.equal(false, flush === undefined, 'must provide flush value');
-
- this.write_in_progress = true;
-
- if (flush !== exports.Z_NO_FLUSH && flush !== exports.Z_PARTIAL_FLUSH && flush !== exports.Z_SYNC_FLUSH && flush !== exports.Z_FULL_FLUSH && flush !== exports.Z_FINISH && flush !== exports.Z_BLOCK) {
- throw new Error('Invalid flush value');
- }
-
- if (input == null) {
- input = Buffer.alloc(0);
- in_len = 0;
- in_off = 0;
+ // 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)
}
- this.strm.avail_in = in_len;
- this.strm.input = input;
- this.strm.next_in = in_off;
- this.strm.avail_out = out_len;
- this.strm.output = out;
- this.strm.next_out = out_off;
- this.flush = flush;
+ throw new TypeError('val must be string, number or Buffer')
+}
- if (!async) {
- // sync version
- this._process();
+function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
+ var indexSize = 1
+ var arrLength = arr.length
+ var valLength = val.length
- if (this._checkError()) {
- return this._afterSync();
+ 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
}
- return;
}
- // async version
- var self = this;
- process.nextTick(function () {
- self._process();
- self._after();
- });
-
- return this;
-};
-
-Zlib.prototype._afterSync = function () {
- var avail_out = this.strm.avail_out;
- var avail_in = this.strm.avail_in;
-
- this.write_in_progress = false;
-
- return [avail_in, avail_out];
-};
+ function read (buf, i) {
+ if (indexSize === 1) {
+ return buf[i]
+ } else {
+ return buf.readUInt16BE(i * indexSize)
+ }
+ }
-Zlib.prototype._process = function () {
- var next_expected_header_byte = null;
-
- // If the avail_out is left at 0, then it means that it ran out
- // of room. If there was avail_out left over, then it means
- // that all of the input was consumed.
- switch (this.mode) {
- case exports.DEFLATE:
- case exports.GZIP:
- case exports.DEFLATERAW:
- this.err = zlib_deflate.deflate(this.strm, this.flush);
- break;
- case exports.UNZIP:
- if (this.strm.avail_in > 0) {
- next_expected_header_byte = this.strm.next_in;
+ 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
+ }
+ }
- switch (this.gzip_id_bytes_read) {
- case 0:
- if (next_expected_header_byte === null) {
- break;
- }
+ return -1
+}
- if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) {
- this.gzip_id_bytes_read = 1;
- next_expected_header_byte++;
+Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
+ return this.indexOf(val, byteOffset, encoding) !== -1
+}
- if (this.strm.avail_in === 1) {
- // The only available byte was already read.
- break;
- }
- } else {
- this.mode = exports.INFLATE;
- break;
- }
+Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
+}
- // fallthrough
- case 1:
- if (next_expected_header_byte === null) {
- break;
- }
+Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
+}
- if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID2) {
- this.gzip_id_bytes_read = 2;
- this.mode = exports.GUNZIP;
- } else {
- // There is no actual difference between INFLATE and INFLATERAW
- // (after initialization).
- this.mode = exports.INFLATE;
- }
+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
+ }
+ }
- break;
- default:
- throw new Error('invalid number of gzip magic number bytes read');
- }
+ var strLen = string.length
- // fallthrough
- case exports.INFLATE:
- case exports.GUNZIP:
- case exports.INFLATERAW:
- this.err = zlib_inflate.inflate(this.strm, this.flush
-
- // If data was encoded with dictionary
- );if (this.err === exports.Z_NEED_DICT && this.dictionary) {
- // Load it
- this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary);
- if (this.err === exports.Z_OK) {
- // And try to decode again
- this.err = zlib_inflate.inflate(this.strm, this.flush);
- } else if (this.err === exports.Z_DATA_ERROR) {
- // Both inflateSetDictionary() and inflate() return Z_DATA_ERROR.
- // Make it possible for After() to tell a bad dictionary from bad
- // input.
- this.err = exports.Z_NEED_DICT;
- }
- }
- while (this.strm.avail_in > 0 && this.mode === exports.GUNZIP && this.err === exports.Z_STREAM_END && this.strm.next_in[0] !== 0x00) {
- // Bytes remain in input buffer. Perhaps this is another compressed
- // member in the same archive, or just trailing garbage.
- // Trailing zero bytes are okay, though, since they are frequently
- // used for padding.
-
- this.reset();
- this.err = zlib_inflate.inflate(this.strm, this.flush);
- }
- break;
- default:
- throw new Error('Unknown mode ' + this.mode);
+ if (length > strLen / 2) {
+ length = strLen / 2
}
-};
-
-Zlib.prototype._checkError = function () {
- // Acceptable error states depend on the type of zlib stream.
- switch (this.err) {
- case exports.Z_OK:
- case exports.Z_BUF_ERROR:
- if (this.strm.avail_out !== 0 && this.flush === exports.Z_FINISH) {
- this._error('unexpected end of file');
- return false;
- }
- break;
- case exports.Z_STREAM_END:
- // normal statuses, not fatal
- break;
- case exports.Z_NEED_DICT:
- if (this.dictionary == null) {
- this._error('Missing dictionary');
- } else {
- this._error('Bad dictionary');
- }
- return false;
- default:
- // something else.
- this._error('Zlib error');
- return false;
+ 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
+}
- return true;
-};
+function utf8Write (buf, string, offset, length) {
+ return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
+}
-Zlib.prototype._after = function () {
- if (!this._checkError()) {
- return;
- }
+function asciiWrite (buf, string, offset, length) {
+ return blitBuffer(asciiToBytes(string), buf, offset, length)
+}
- var avail_out = this.strm.avail_out;
- var avail_in = this.strm.avail_in;
+function latin1Write (buf, string, offset, length) {
+ return asciiWrite(buf, string, offset, length)
+}
- this.write_in_progress = false;
+function base64Write (buf, string, offset, length) {
+ return blitBuffer(base64ToBytes(string), buf, offset, length)
+}
- // call the write() cb
- this.callback(avail_in, avail_out);
+function ucs2Write (buf, string, offset, length) {
+ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
+}
- if (this.pending_close) {
- this.close();
+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'
+ )
}
-};
-Zlib.prototype._error = function (message) {
- if (this.strm.msg) {
- message = this.strm.msg;
- }
- this.onerror(message, this.err
+ var remaining = this.length - offset
+ if (length === undefined || length > remaining) length = remaining
- // no hope of rescue.
- );this.write_in_progress = false;
- if (this.pending_close) {
- this.close();
+ if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
+ throw new RangeError('Attempt to write outside buffer bounds')
}
-};
-
-Zlib.prototype.init = function (windowBits, level, memLevel, strategy, dictionary) {
- assert(arguments.length === 4 || arguments.length === 5, 'init(windowBits, level, memLevel, strategy, [dictionary])');
- assert(windowBits >= 8 && windowBits <= 15, 'invalid windowBits');
- assert(level >= -1 && level <= 9, 'invalid compression level');
-
- assert(memLevel >= 1 && memLevel <= 9, 'invalid memlevel');
-
- assert(strategy === exports.Z_FILTERED || strategy === exports.Z_HUFFMAN_ONLY || strategy === exports.Z_RLE || strategy === exports.Z_FIXED || strategy === exports.Z_DEFAULT_STRATEGY, 'invalid strategy');
+ if (!encoding) encoding = 'utf8'
- this._init(level, windowBits, memLevel, strategy, dictionary);
- this._setDictionary();
-};
+ var loweredCase = false
+ for (;;) {
+ switch (encoding) {
+ case 'hex':
+ return hexWrite(this, string, offset, length)
-Zlib.prototype.params = function () {
- throw new Error('deflateParams Not supported');
-};
+ case 'utf8':
+ case 'utf-8':
+ return utf8Write(this, string, offset, length)
-Zlib.prototype.reset = function () {
- this._reset();
- this._setDictionary();
-};
+ case 'ascii':
+ return asciiWrite(this, string, offset, length)
-Zlib.prototype._init = function (level, windowBits, memLevel, strategy, dictionary) {
- this.level = level;
- this.windowBits = windowBits;
- this.memLevel = memLevel;
- this.strategy = strategy;
+ case 'latin1':
+ case 'binary':
+ return latin1Write(this, string, offset, length)
- this.flush = exports.Z_NO_FLUSH;
+ case 'base64':
+ // Warning: maxLength not taken into account in base64Write
+ return base64Write(this, string, offset, length)
- this.err = exports.Z_OK;
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return ucs2Write(this, string, offset, length)
- if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) {
- this.windowBits += 16;
+ default:
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
+ encoding = ('' + encoding).toLowerCase()
+ loweredCase = true
+ }
}
+}
- if (this.mode === exports.UNZIP) {
- this.windowBits += 32;
+Buffer.prototype.toJSON = function toJSON () {
+ return {
+ type: 'Buffer',
+ data: Array.prototype.slice.call(this._arr || this, 0)
}
+}
- if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) {
- this.windowBits = -1 * this.windowBits;
+function base64Slice (buf, start, end) {
+ if (start === 0 && end === buf.length) {
+ return base64.fromByteArray(buf)
+ } else {
+ return base64.fromByteArray(buf.slice(start, end))
}
+}
- this.strm = new Zstream();
-
- switch (this.mode) {
- case exports.DEFLATE:
- case exports.GZIP:
- case exports.DEFLATERAW:
- this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy);
- break;
- case exports.INFLATE:
- case exports.GUNZIP:
- case exports.INFLATERAW:
- case exports.UNZIP:
- this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits);
- break;
- default:
- throw new Error('Unknown mode ' + this.mode);
- }
+function utf8Slice (buf, start, end) {
+ end = Math.min(buf.length, end)
+ var res = []
- if (this.err !== exports.Z_OK) {
- this._error('Init error');
- }
+ 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
- this.dictionary = dictionary;
+ if (i + bytesPerSequence <= end) {
+ var secondByte, thirdByte, fourthByte, tempCodePoint
- this.write_in_progress = false;
- this.init_done = true;
-};
-
-Zlib.prototype._setDictionary = function () {
- if (this.dictionary == null) {
- return;
- }
+ 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
+ }
+ }
+ }
+ }
- this.err = exports.Z_OK;
+ 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
+ }
- switch (this.mode) {
- case exports.DEFLATE:
- case exports.DEFLATERAW:
- this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary);
- break;
- default:
- break;
+ res.push(codePoint)
+ i += bytesPerSequence
}
- if (this.err !== exports.Z_OK) {
- this._error('Failed to set dictionary');
- }
-};
+ return decodeCodePointsArray(res)
+}
-Zlib.prototype._reset = function () {
- this.err = exports.Z_OK;
+// 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
- switch (this.mode) {
- case exports.DEFLATE:
- case exports.DEFLATERAW:
- case exports.GZIP:
- this.err = zlib_deflate.deflateReset(this.strm);
- break;
- case exports.INFLATE:
- case exports.INFLATERAW:
- case exports.GUNZIP:
- this.err = zlib_inflate.inflateReset(this.strm);
- break;
- default:
- break;
+function decodeCodePointsArray (codePoints) {
+ var len = codePoints.length
+ if (len <= MAX_ARGUMENTS_LENGTH) {
+ return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
- if (this.err !== exports.Z_OK) {
- this._error('Failed to reset stream');
+ // 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
+}
-exports.Zlib = Zlib;
-}).call(this)}).call(this,require('_process'),require("buffer").Buffer)
-},{"_process":34,"assert":2,"buffer":10,"pako/lib/zlib/constants":23,"pako/lib/zlib/deflate.js":25,"pako/lib/zlib/inflate.js":27,"pako/lib/zlib/zstream":31}],9:[function(require,module,exports){
-(function (process){(function (){
-'use strict';
+function asciiSlice (buf, start, end) {
+ var ret = ''
+ end = Math.min(buf.length, end)
-var Buffer = require('buffer').Buffer;
-var Transform = require('stream').Transform;
-var binding = require('./binding');
-var util = require('util');
-var assert = require('assert').ok;
-var kMaxLength = require('buffer').kMaxLength;
-var kRangeErrorMessage = 'Cannot create final Buffer. It would be larger ' + 'than 0x' + kMaxLength.toString(16) + ' bytes';
-
-// zlib doesn't provide these, so kludge them in following the same
-// const naming scheme zlib uses.
-binding.Z_MIN_WINDOWBITS = 8;
-binding.Z_MAX_WINDOWBITS = 15;
-binding.Z_DEFAULT_WINDOWBITS = 15;
-
-// fewer than 64 bytes per chunk is stupid.
-// technically it could work with as few as 8, but even 64 bytes
-// is absurdly low. Usually a MB or more is best.
-binding.Z_MIN_CHUNK = 64;
-binding.Z_MAX_CHUNK = Infinity;
-binding.Z_DEFAULT_CHUNK = 16 * 1024;
-
-binding.Z_MIN_MEMLEVEL = 1;
-binding.Z_MAX_MEMLEVEL = 9;
-binding.Z_DEFAULT_MEMLEVEL = 8;
-
-binding.Z_MIN_LEVEL = -1;
-binding.Z_MAX_LEVEL = 9;
-binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
-
-// expose all the zlib constants
-var bkeys = Object.keys(binding);
-for (var bk = 0; bk < bkeys.length; bk++) {
- var bkey = bkeys[bk];
- if (bkey.match(/^Z/)) {
- Object.defineProperty(exports, bkey, {
- enumerable: true, value: binding[bkey], writable: false
- });
+ for (var i = start; i < end; ++i) {
+ ret += String.fromCharCode(buf[i] & 0x7F)
}
+ return ret
}
-// translation table for return codes.
-var codes = {
- Z_OK: binding.Z_OK,
- Z_STREAM_END: binding.Z_STREAM_END,
- Z_NEED_DICT: binding.Z_NEED_DICT,
- Z_ERRNO: binding.Z_ERRNO,
- Z_STREAM_ERROR: binding.Z_STREAM_ERROR,
- Z_DATA_ERROR: binding.Z_DATA_ERROR,
- Z_MEM_ERROR: binding.Z_MEM_ERROR,
- Z_BUF_ERROR: binding.Z_BUF_ERROR,
- Z_VERSION_ERROR: binding.Z_VERSION_ERROR
-};
+function latin1Slice (buf, start, end) {
+ var ret = ''
+ end = Math.min(buf.length, end)
-var ckeys = Object.keys(codes);
-for (var ck = 0; ck < ckeys.length; ck++) {
- var ckey = ckeys[ck];
- codes[codes[ckey]] = ckey;
+ for (var i = start; i < end; ++i) {
+ ret += String.fromCharCode(buf[i])
+ }
+ return ret
}
-Object.defineProperty(exports, 'codes', {
- enumerable: true, value: Object.freeze(codes), writable: false
-});
-
-exports.Deflate = Deflate;
-exports.Inflate = Inflate;
-exports.Gzip = Gzip;
-exports.Gunzip = Gunzip;
-exports.DeflateRaw = DeflateRaw;
-exports.InflateRaw = InflateRaw;
-exports.Unzip = Unzip;
-
-exports.createDeflate = function (o) {
- return new Deflate(o);
-};
-
-exports.createInflate = function (o) {
- return new Inflate(o);
-};
-
-exports.createDeflateRaw = function (o) {
- return new DeflateRaw(o);
-};
-
-exports.createInflateRaw = function (o) {
- return new InflateRaw(o);
-};
-
-exports.createGzip = function (o) {
- return new Gzip(o);
-};
-
-exports.createGunzip = function (o) {
- return new Gunzip(o);
-};
+function hexSlice (buf, start, end) {
+ var len = buf.length
-exports.createUnzip = function (o) {
- return new Unzip(o);
-};
+ if (!start || start < 0) start = 0
+ if (!end || end < 0 || end > len) end = len
-// Convenience methods.
-// compress/decompress a string or buffer in one step.
-exports.deflate = function (buffer, opts, callback) {
- if (typeof opts === 'function') {
- callback = opts;
- opts = {};
+ var out = ''
+ for (var i = start; i < end; ++i) {
+ out += toHex(buf[i])
}
- return zlibBuffer(new Deflate(opts), buffer, callback);
-};
-
-exports.deflateSync = function (buffer, opts) {
- return zlibBufferSync(new Deflate(opts), buffer);
-};
+ return out
+}
-exports.gzip = function (buffer, opts, callback) {
- if (typeof opts === 'function') {
- callback = opts;
- opts = {};
+function utf16leSlice (buf, start, end) {
+ var bytes = buf.slice(start, end)
+ var res = ''
+ for (var i = 0; i < bytes.length; i += 2) {
+ res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
}
- return zlibBuffer(new Gzip(opts), buffer, callback);
-};
+ return res
+}
-exports.gzipSync = function (buffer, opts) {
- return zlibBufferSync(new Gzip(opts), buffer);
-};
+Buffer.prototype.slice = function slice (start, end) {
+ var len = this.length
+ start = ~~start
+ end = end === undefined ? len : ~~end
-exports.deflateRaw = function (buffer, opts, callback) {
- if (typeof opts === 'function') {
- callback = opts;
- opts = {};
+ if (start < 0) {
+ start += len
+ if (start < 0) start = 0
+ } else if (start > len) {
+ start = len
}
- return zlibBuffer(new DeflateRaw(opts), buffer, callback);
-};
-
-exports.deflateRawSync = function (buffer, opts) {
- return zlibBufferSync(new DeflateRaw(opts), buffer);
-};
-exports.unzip = function (buffer, opts, callback) {
- if (typeof opts === 'function') {
- callback = opts;
- opts = {};
+ if (end < 0) {
+ end += len
+ if (end < 0) end = 0
+ } else if (end > len) {
+ end = len
}
- return zlibBuffer(new Unzip(opts), buffer, callback);
-};
-
-exports.unzipSync = function (buffer, opts) {
- return zlibBufferSync(new Unzip(opts), buffer);
-};
-exports.inflate = function (buffer, opts, callback) {
- if (typeof opts === 'function') {
- callback = opts;
- opts = {};
- }
- return zlibBuffer(new Inflate(opts), buffer, callback);
-};
+ if (end < start) end = start
-exports.inflateSync = function (buffer, opts) {
- return zlibBufferSync(new Inflate(opts), buffer);
-};
+ var newBuf = this.subarray(start, end)
+ // Return an augmented `Uint8Array` instance
+ newBuf.__proto__ = Buffer.prototype
+ return newBuf
+}
-exports.gunzip = function (buffer, opts, callback) {
- if (typeof opts === 'function') {
- callback = opts;
- opts = {};
- }
- return zlibBuffer(new Gunzip(opts), buffer, callback);
-};
+/*
+ * 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')
+}
-exports.gunzipSync = function (buffer, opts) {
- return zlibBufferSync(new Gunzip(opts), buffer);
-};
+Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
+ if (!noAssert) checkOffset(offset, byteLength, this.length)
-exports.inflateRaw = function (buffer, opts, callback) {
- if (typeof opts === 'function') {
- callback = opts;
- opts = {};
+ var val = this[offset]
+ var mul = 1
+ var i = 0
+ while (++i < byteLength && (mul *= 0x100)) {
+ val += this[offset + i] * mul
}
- return zlibBuffer(new InflateRaw(opts), buffer, callback);
-};
-exports.inflateRawSync = function (buffer, opts) {
- return zlibBufferSync(new InflateRaw(opts), buffer);
-};
-
-function zlibBuffer(engine, buffer, callback) {
- var buffers = [];
- var nread = 0;
-
- engine.on('error', onError);
- engine.on('end', onEnd);
-
- engine.end(buffer);
- flow();
-
- function flow() {
- var chunk;
- while (null !== (chunk = engine.read())) {
- buffers.push(chunk);
- nread += chunk.length;
- }
- engine.once('readable', flow);
- }
+ return val
+}
- function onError(err) {
- engine.removeListener('end', onEnd);
- engine.removeListener('readable', flow);
- callback(err);
+Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
+ if (!noAssert) {
+ checkOffset(offset, byteLength, this.length)
}
- function onEnd() {
- var buf;
- var err = null;
-
- if (nread >= kMaxLength) {
- err = new RangeError(kRangeErrorMessage);
- } else {
- buf = Buffer.concat(buffers, nread);
- }
-
- buffers = [];
- engine.close();
- callback(err, buf);
+ var val = this[offset + --byteLength]
+ var mul = 1
+ while (byteLength > 0 && (mul *= 0x100)) {
+ val += this[offset + --byteLength] * mul
}
-}
-function zlibBufferSync(engine, buffer) {
- if (typeof buffer === 'string') buffer = Buffer.from(buffer);
-
- if (!Buffer.isBuffer(buffer)) throw new TypeError('Not a string or buffer');
-
- var flushFlag = engine._finishFlushFlag;
-
- return engine._processChunk(buffer, flushFlag);
-}
-
-// generic zlib
-// minimal 2-byte header
-function Deflate(opts) {
- if (!(this instanceof Deflate)) return new Deflate(opts);
- Zlib.call(this, opts, binding.DEFLATE);
+ return val
}
-function Inflate(opts) {
- if (!(this instanceof Inflate)) return new Inflate(opts);
- Zlib.call(this, opts, binding.INFLATE);
+Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 1, this.length)
+ return this[offset]
}
-// gzip - bigger header, same deflate compression
-function Gzip(opts) {
- if (!(this instanceof Gzip)) return new Gzip(opts);
- Zlib.call(this, opts, binding.GZIP);
+Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 2, this.length)
+ return this[offset] | (this[offset + 1] << 8)
}
-function Gunzip(opts) {
- if (!(this instanceof Gunzip)) return new Gunzip(opts);
- Zlib.call(this, opts, binding.GUNZIP);
+Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 2, this.length)
+ return (this[offset] << 8) | this[offset + 1]
}
-// raw - no header
-function DeflateRaw(opts) {
- if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
- Zlib.call(this, opts, binding.DEFLATERAW);
-}
+Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 4, this.length)
-function InflateRaw(opts) {
- if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
- Zlib.call(this, opts, binding.INFLATERAW);
+ return ((this[offset]) |
+ (this[offset + 1] << 8) |
+ (this[offset + 2] << 16)) +
+ (this[offset + 3] * 0x1000000)
}
-// auto-detect header.
-function Unzip(opts) {
- if (!(this instanceof Unzip)) return new Unzip(opts);
- Zlib.call(this, opts, binding.UNZIP);
-}
+Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 4, this.length)
-function isValidFlushFlag(flag) {
- return flag === binding.Z_NO_FLUSH || flag === binding.Z_PARTIAL_FLUSH || flag === binding.Z_SYNC_FLUSH || flag === binding.Z_FULL_FLUSH || flag === binding.Z_FINISH || flag === binding.Z_BLOCK;
+ return (this[offset] * 0x1000000) +
+ ((this[offset + 1] << 16) |
+ (this[offset + 2] << 8) |
+ this[offset + 3])
}
-// 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.
+Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
+ if (!noAssert) checkOffset(offset, byteLength, this.length)
-function Zlib(opts, mode) {
- var _this = this;
+ var val = this[offset]
+ var mul = 1
+ var i = 0
+ while (++i < byteLength && (mul *= 0x100)) {
+ val += this[offset + i] * mul
+ }
+ mul *= 0x80
- this._opts = opts = opts || {};
- this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength)
- Transform.call(this, opts);
+ return val
+}
- if (opts.flush && !isValidFlushFlag(opts.flush)) {
- throw new Error('Invalid flush flag: ' + opts.flush);
- }
- if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) {
- throw new Error('Invalid flush flag: ' + opts.finishFlush);
- }
-
- this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
- this._finishFlushFlag = typeof opts.finishFlush !== 'undefined' ? opts.finishFlush : binding.Z_FINISH;
+Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
+ offset = offset >>> 0
+ byteLength = byteLength >>> 0
+ if (!noAssert) checkOffset(offset, byteLength, this.length)
- if (opts.chunkSize) {
- if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) {
- throw new Error('Invalid chunk size: ' + opts.chunkSize);
- }
+ var i = byteLength
+ var mul = 1
+ var val = this[offset + --i]
+ while (i > 0 && (mul *= 0x100)) {
+ val += this[offset + --i] * mul
}
+ mul *= 0x80
- if (opts.windowBits) {
- if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) {
- throw new Error('Invalid windowBits: ' + opts.windowBits);
- }
- }
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength)
- if (opts.level) {
- if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) {
- throw new Error('Invalid compression level: ' + opts.level);
- }
- }
+ return val
+}
- if (opts.memLevel) {
- if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) {
- throw new Error('Invalid memLevel: ' + opts.memLevel);
- }
- }
+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)
+}
- if (opts.strategy) {
- if (opts.strategy != exports.Z_FILTERED && opts.strategy != exports.Z_HUFFMAN_ONLY && opts.strategy != exports.Z_RLE && opts.strategy != exports.Z_FIXED && opts.strategy != exports.Z_DEFAULT_STRATEGY) {
- throw new Error('Invalid strategy: ' + opts.strategy);
- }
- }
+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
+}
- if (opts.dictionary) {
- if (!Buffer.isBuffer(opts.dictionary)) {
- throw new Error('Invalid dictionary: it should be a Buffer instance');
- }
- }
+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
+}
- this._handle = new binding.Zlib(mode);
+Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 4, this.length)
- var self = this;
- this._hadError = false;
- this._handle.onerror = function (message, errno) {
- // there is no way to cleanly recover.
- // continuing only obscures problems.
- _close(self);
- self._hadError = true;
-
- var error = new Error(message);
- error.errno = errno;
- error.code = exports.codes[errno];
- self.emit('error', error);
- };
+ return (this[offset]) |
+ (this[offset + 1] << 8) |
+ (this[offset + 2] << 16) |
+ (this[offset + 3] << 24)
+}
- var level = exports.Z_DEFAULT_COMPRESSION;
- if (typeof opts.level === 'number') level = opts.level;
+Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
+ offset = offset >>> 0
+ if (!noAssert) checkOffset(offset, 4, this.length)
- var strategy = exports.Z_DEFAULT_STRATEGY;
- if (typeof opts.strategy === 'number') strategy = opts.strategy;
+ return (this[offset] << 24) |
+ (this[offset + 1] << 16) |
+ (this[offset + 2] << 8) |
+ (this[offset + 3])
+}
- this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary);
+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)
+}
- this._buffer = Buffer.allocUnsafe(this._chunkSize);
- this._offset = 0;
- this._level = level;
- this._strategy = strategy;
+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)
+}
- this.once('end', this.close);
+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)
+}
- Object.defineProperty(this, '_closed', {
- get: function () {
- return !_this._handle;
- },
- configurable: true,
- enumerable: true
- });
+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)
}
-util.inherits(Zlib, Transform);
+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')
+}
-Zlib.prototype.params = function (level, strategy, callback) {
- if (level < exports.Z_MIN_LEVEL || level > exports.Z_MAX_LEVEL) {
- throw new RangeError('Invalid compression level: ' + level);
- }
- if (strategy != exports.Z_FILTERED && strategy != exports.Z_HUFFMAN_ONLY && strategy != exports.Z_RLE && strategy != exports.Z_FIXED && strategy != exports.Z_DEFAULT_STRATEGY) {
- throw new TypeError('Invalid strategy: ' + strategy);
+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)
}
- if (this._level !== level || this._strategy !== strategy) {
- var self = this;
- this.flush(binding.Z_SYNC_FLUSH, function () {
- assert(self._handle, 'zlib binding closed');
- self._handle.params(level, strategy);
- if (!self._hadError) {
- self._level = level;
- self._strategy = strategy;
- if (callback) callback();
- }
- });
- } else {
- process.nextTick(callback);
+ var mul = 1
+ var i = 0
+ this[offset] = value & 0xFF
+ while (++i < byteLength && (mul *= 0x100)) {
+ this[offset + i] = (value / mul) & 0xFF
}
-};
-
-Zlib.prototype.reset = function () {
- assert(this._handle, 'zlib binding closed');
- return this._handle.reset();
-};
-
-// This is the _flush function called by the transform class,
-// internally, when the last chunk has been written.
-Zlib.prototype._flush = function (callback) {
- this._transform(Buffer.alloc(0), '', callback);
-};
-
-Zlib.prototype.flush = function (kind, callback) {
- var _this2 = this;
- var ws = this._writableState;
+ return offset + byteLength
+}
- if (typeof kind === 'function' || kind === undefined && !callback) {
- callback = kind;
- kind = binding.Z_FULL_FLUSH;
+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)
}
- if (ws.ended) {
- if (callback) process.nextTick(callback);
- } else if (ws.ending) {
- if (callback) this.once('end', callback);
- } else if (ws.needDrain) {
- if (callback) {
- this.once('drain', function () {
- return _this2.flush(kind, callback);
- });
- }
- } else {
- this._flushFlag = kind;
- this.write(Buffer.alloc(0), '', callback);
+ var i = byteLength - 1
+ var mul = 1
+ this[offset + i] = value & 0xFF
+ while (--i >= 0 && (mul *= 0x100)) {
+ this[offset + i] = (value / mul) & 0xFF
}
-};
-
-Zlib.prototype.close = function (callback) {
- _close(this, callback);
- process.nextTick(emitCloseNT, this);
-};
-function _close(engine, callback) {
- if (callback) process.nextTick(callback);
-
- // Caller may invoke .close after a zlib error (which will null _handle).
- if (!engine._handle) return;
-
- engine._handle.close();
- engine._handle = null;
+ return offset + byteLength
}
-function emitCloseNT(self) {
- self.emit('close');
+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
}
-Zlib.prototype._transform = function (chunk, encoding, cb) {
- var flushFlag;
- var ws = this._writableState;
- var ending = ws.ending || ws.ended;
- var last = ending && (!chunk || ws.length === chunk.length);
-
- if (chunk !== null && !Buffer.isBuffer(chunk)) return cb(new Error('invalid input'));
-
- if (!this._handle) return cb(new Error('zlib binding closed'));
-
- // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag
- // (or whatever flag was provided using opts.finishFlush).
- // If it's explicitly flushing at some other time, then we use
- // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
- // goodness.
- if (last) flushFlag = this._finishFlushFlag;else {
- flushFlag = this._flushFlag;
- // once we've flushed the last of the queue, stop flushing and
- // go back to the normal behavior.
- if (chunk.length >= ws.length) {
- this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
- }
- }
-
- this._processChunk(chunk, flushFlag, cb);
-};
-
-Zlib.prototype._processChunk = function (chunk, flushFlag, cb) {
- var availInBefore = chunk && chunk.length;
- var availOutBefore = this._chunkSize - this._offset;
- var inOff = 0;
-
- var self = this;
-
- var async = typeof cb === 'function';
-
- if (!async) {
- var buffers = [];
- var nread = 0;
+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
+}
- var error;
- this.on('error', function (er) {
- error = er;
- });
+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
+}
- assert(this._handle, 'zlib binding closed');
- do {
- var res = this._handle.writeSync(flushFlag, chunk, // in
- inOff, // in_off
- availInBefore, // in_len
- this._buffer, // out
- this._offset, //out_off
- availOutBefore); // out_len
- } while (!this._hadError && callback(res[0], res[1]));
-
- if (this._hadError) {
- throw error;
- }
+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
+}
- if (nread >= kMaxLength) {
- _close(this);
- throw new RangeError(kRangeErrorMessage);
- }
+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
+}
- var buf = Buffer.concat(buffers, nread);
- _close(this);
+Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) {
+ var limit = Math.pow(2, (8 * byteLength) - 1)
- return buf;
+ checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
- assert(this._handle, 'zlib binding closed');
- var req = this._handle.write(flushFlag, chunk, // in
- inOff, // in_off
- availInBefore, // in_len
- this._buffer, // out
- this._offset, //out_off
- availOutBefore); // out_len
-
- req.buffer = chunk;
- req.callback = callback;
-
- function callback(availInAfter, availOutAfter) {
- // When the callback is used in an async write, the callback's
- // context is the `req` object that was created. The req object
- // is === this._handle, and that's why it's important to null
- // out the values after they are done being used. `this._handle`
- // can stay in memory longer than the callback and buffer are needed.
- if (this) {
- this.buffer = null;
- this.callback = null;
+ 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
+ }
- if (self._hadError) return;
+ return offset + byteLength
+}
- var have = availOutBefore - availOutAfter;
- assert(have >= 0, 'have should not go down');
+Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
+ value = +value
+ offset = offset >>> 0
+ if (!noAssert) {
+ var limit = Math.pow(2, (8 * byteLength) - 1)
- if (have > 0) {
- var out = self._buffer.slice(self._offset, self._offset + have);
- self._offset += have;
- // serve some output to the consumer.
- if (async) {
- self.push(out);
- } else {
- buffers.push(out);
- nread += out.length;
- }
- }
+ checkInt(this, value, offset, byteLength, limit - 1, -limit)
+ }
- // exhausted the output buffer, or used all the input create a new one.
- if (availOutAfter === 0 || self._offset >= self._chunkSize) {
- availOutBefore = self._chunkSize;
- self._offset = 0;
- self._buffer = Buffer.allocUnsafe(self._chunkSize);
+ 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
+ }
- if (availOutAfter === 0) {
- // Not actually done. Need to reprocess.
- // Also, update the availInBefore to the availInAfter value,
- // so that if we have to hit it a third (fourth, etc.) time,
- // it'll have the correct byte counts.
- inOff += availInBefore - availInAfter;
- availInBefore = availInAfter;
+ return offset + byteLength
+}
- if (!async) return true;
+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
+}
- var newReq = self._handle.write(flushFlag, chunk, inOff, availInBefore, self._buffer, self._offset, self._chunkSize);
- newReq.callback = callback; // this same function
- newReq.buffer = chunk;
- return;
- }
+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
+}
- if (!async) return false;
+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
+}
- // finished with the chunk.
- cb();
- }
-};
-
-util.inherits(Deflate, Zlib);
-util.inherits(Inflate, Zlib);
-util.inherits(Gzip, Zlib);
-util.inherits(Gunzip, Zlib);
-util.inherits(DeflateRaw, Zlib);
-util.inherits(InflateRaw, Zlib);
-util.inherits(Unzip, Zlib);
-}).call(this)}).call(this,require('_process'))
-},{"./binding":8,"_process":34,"assert":2,"buffer":10,"stream":55,"util":82}],10:[function(require,module,exports){
-(function (Buffer){(function (){
-/*!
- * 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')
-
-exports.Buffer = Buffer
-exports.SlowBuffer = SlowBuffer
-exports.INSPECT_MAX_BYTES = 50
-
-var K_MAX_LENGTH = 0x7fffffff
-exports.kMaxLength = K_MAX_LENGTH
+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
+}
-/**
- * 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()
+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
+}
-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 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 typedArraySupport () {
- // Can typed array instances can be augmented?
- try {
- var arr = new Uint8Array(1)
- arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
- return arr.foo() === 42
- } catch (e) {
- return false
+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
}
-Object.defineProperty(Buffer.prototype, 'parent', {
- enumerable: true,
- get: function () {
- if (!Buffer.isBuffer(this)) return undefined
- return this.buffer
- }
-})
+Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
+ return writeFloat(this, value, offset, true, noAssert)
+}
-Object.defineProperty(Buffer.prototype, 'offset', {
- enumerable: true,
- get: function () {
- if (!Buffer.isBuffer(this)) return undefined
- return this.byteOffset
- }
-})
+Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
+ return writeFloat(this, value, offset, false, noAssert)
+}
-function createBuffer (length) {
- if (length > K_MAX_LENGTH) {
- throw new RangeError('The value "' + length + '" is invalid for option "size"')
+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)
}
- // Return an augmented `Uint8Array` instance
- var buf = new Uint8Array(length)
- buf.__proto__ = Buffer.prototype
- return buf
+ ieee754.write(buf, value, offset, littleEndian, 52, 8)
+ return offset + 8
}
-/**
- * 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.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
+ return writeDouble(this, value, offset, true, noAssert)
}
-// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
-if (typeof Symbol !== 'undefined' && Symbol.species != null &&
- Buffer[Symbol.species] === Buffer) {
- Object.defineProperty(Buffer, Symbol.species, {
- value: null,
- configurable: true,
- enumerable: false,
- writable: false
- })
+Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
+ return writeDouble(this, value, offset, false, noAssert)
}
-Buffer.poolSize = 8192 // not used by this implementation
+// 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
-function from (value, encodingOrOffset, length) {
- if (typeof value === 'string') {
- return fromString(value, encodingOrOffset)
+ // 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')
- if (ArrayBuffer.isView(value)) {
- return fromArrayLike(value)
+ // Are we oob?
+ if (end > this.length) end = this.length
+ if (target.length - targetStart < end - start) {
+ end = target.length - targetStart + start
}
- if (value == null) {
- throw TypeError(
- 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
- 'or Array-like Object. Received type ' + (typeof value)
+ 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 if (this === target && start < targetStart && targetStart < end) {
+ // descending copy from end
+ for (var i = len - 1; i >= 0; --i) {
+ target[i + targetStart] = this[i + start]
+ }
+ } else {
+ Uint8Array.prototype.set.call(
+ target,
+ this.subarray(start, end),
+ targetStart
)
}
- if (isInstance(value, ArrayBuffer) ||
- (value && isInstance(value.buffer, ArrayBuffer))) {
- return fromArrayBuffer(value, encodingOrOffset, length)
+ 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
}
- if (typeof value === 'number') {
- throw new TypeError(
- 'The "value" argument must not be of type number. Received type number'
- )
+ // 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')
}
- var valueOf = value.valueOf && value.valueOf()
- if (valueOf != null && valueOf !== value) {
- return Buffer.from(valueOf, encodingOrOffset, length)
+ if (end <= start) {
+ return this
}
- var b = fromObject(value)
- if (b) return b
+ start = start >>> 0
+ end = end === undefined ? this.length : end >>> 0
- if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
- typeof value[Symbol.toPrimitive] === 'function') {
- return Buffer.from(
- value[Symbol.toPrimitive]('string'), encodingOrOffset, length
- )
- }
+ if (!val) val = 0
- throw new TypeError(
- 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
- 'or Array-like Object. Received type ' + (typeof value)
- )
-}
+ 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]
+ }
+ }
-/**
- * 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)
+ return this
}
-// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
-// https://github.com/feross/buffer/pull/148
-Buffer.prototype.__proto__ = Uint8Array.prototype
-Buffer.__proto__ = Uint8Array
+// HELPER FUNCTIONS
+// ================
-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"')
- }
-}
+var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
-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 interpretted as a start offset.
- return typeof encoding === 'string'
- ? createBuffer(size).fill(fill, encoding)
- : createBuffer(size).fill(fill)
+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 createBuffer(size)
+ return str
}
-/**
- * Creates a new filled Buffer instance.
- * alloc(size[, fill[, encoding]])
- **/
-Buffer.alloc = function (size, fill, encoding) {
- return alloc(size, fill, encoding)
+function toHex (n) {
+ if (n < 16) return '0' + n.toString(16)
+ return n.toString(16)
}
-function allocUnsafe (size) {
- assertSize(size)
- return createBuffer(size < 0 ? 0 : checked(size) | 0)
-}
+function utf8ToBytes (string, units) {
+ units = units || Infinity
+ var codePoint
+ var length = string.length
+ var leadSurrogate = null
+ var bytes = []
-/**
- * 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)
-}
+ for (var i = 0; i < length; ++i) {
+ codePoint = string.charCodeAt(i)
-function fromString (string, encoding) {
- if (typeof encoding !== 'string' || encoding === '') {
- encoding = 'utf8'
- }
+ // 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
+ }
- if (!Buffer.isEncoding(encoding)) {
- throw new TypeError('Unknown encoding: ' + encoding)
- }
+ // valid lead
+ leadSurrogate = codePoint
- var length = byteLength(string, encoding) | 0
- var buf = createBuffer(length)
+ continue
+ }
- var actual = buf.write(string, encoding)
+ // 2 leads in a row
+ if (codePoint < 0xDC00) {
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
+ leadSurrogate = codePoint
+ continue
+ }
- 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)
- }
+ // 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)
+ }
- return buf
-}
+ leadSurrogate = null
-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
+ // 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 buf
+
+ return bytes
}
-function fromArrayBuffer (array, byteOffset, length) {
- if (byteOffset < 0 || array.byteLength < byteOffset) {
- throw new RangeError('"offset" is outside of buffer bounds')
+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
+}
- if (array.byteLength < byteOffset + (length || 0)) {
- throw new RangeError('"length" is outside of buffer bounds')
- }
+function utf16leToBytes (str, units) {
+ var c, hi, lo
+ var byteArray = []
+ for (var i = 0; i < str.length; ++i) {
+ if ((units -= 2) < 0) break
- 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)
+ c = str.charCodeAt(i)
+ hi = c >> 8
+ lo = c % 256
+ byteArray.push(lo)
+ byteArray.push(hi)
}
- // Return an augmented `Uint8Array` instance
- buf.__proto__ = Buffer.prototype
- return buf
+ return byteArray
}
-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)
- }
+function base64ToBytes (str) {
+ return base64.toByteArray(base64clean(str))
+}
- if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
- return fromArrayLike(obj.data)
+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
}
-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)
+// 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)
}
-
-Buffer.isBuffer = function isBuffer (b) {
- return b != null && b._isBuffer === true &&
- b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
+function numberIsNaN (obj) {
+ // For IE11 support
+ return obj !== obj // eslint-disable-line no-self-compare
}
-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
+}).call(this)}).call(this,require("buffer").Buffer)
+},{"base64-js":1,"buffer":2,"ieee754":3}],3:[function(require,module,exports){
+/*! 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]
- var x = a.length
- var y = b.length
+ i += d
- for (var i = 0, len = Math.min(x, y); i < len; ++i) {
- if (a[i] !== b[i]) {
- x = a[i]
- y = b[i]
- break
- }
- }
+ e = s & ((1 << (-nBits)) - 1)
+ s >>= (-nBits)
+ nBits += eLen
+ for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
- if (x < y) return -1
- if (y < x) return 1
- return 0
-}
+ m = e & ((1 << (-nBits)) - 1)
+ e >>= (-nBits)
+ nBits += mLen
+ for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
-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
+ 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)
}
-Buffer.concat = function concat (list, length) {
- if (!Array.isArray(list)) {
- throw new TypeError('"list" argument must be an Array of Buffers')
- }
+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
- if (list.length === 0) {
- return Buffer.alloc(0)
- }
+ value = Math.abs(value)
- var i
- if (length === undefined) {
- length = 0
- for (i = 0; i < list.length; ++i) {
- length += list[i].length
+ 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
}
- }
-
- var buffer = Buffer.allocUnsafe(length)
- var pos = 0
- for (i = 0; i < list.length; ++i) {
- var buf = list[i]
- if (isInstance(buf, Uint8Array)) {
- buf = Buffer.from(buf)
+ if (e + eBias >= 1) {
+ value += rt / c
+ } else {
+ value += rt * Math.pow(2, 1 - eBias)
}
- if (!Buffer.isBuffer(buf)) {
- throw new TypeError('"list" argument must be an Array of Buffers')
+ if (value * c >= 2) {
+ e++
+ c /= 2
}
- 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
+ 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
}
}
-}
-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 coersion 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)
+ for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
- case 'ascii':
- return asciiSlice(this, start, end)
+ e = (e << mLen) | m
+ eLen += mLen
+ for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
- case 'latin1':
- case 'binary':
- return latin1Slice(this, start, end)
+ buffer[offset + i - d] |= s * 128
+}
- 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 ''
-}
-
-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 latin1Write (buf, string, offset, length) {
- return asciiWrite(buf, string, 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':
- return asciiWrite(this, string, offset, length)
-
- case 'latin1':
- case 'binary':
- return latin1Write(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 += toHex(buf[i])
- }
- return out
-}
-
-function utf16leSlice (buf, start, end) {
- var bytes = buf.slice(start, end)
- var res = ''
- for (var i = 0; i < bytes.length; 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
- newBuf.__proto__ = 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 = 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 = 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 = function readUInt8 (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 1, this.length)
- return this[offset]
-}
-
-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 = function readUInt16BE (offset, noAssert) {
- offset = offset >>> 0
- if (!noAssert) checkOffset(offset, 2, this.length)
- return (this[offset] << 8) | this[offset + 1]
-}
-
-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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 if (this === target && start < targetStart && targetStart < end) {
- // descending copy from end
- for (var i = len - 1; i >= 0; --i) {
- target[i + targetStart] = this[i + start]
- }
- } 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
- }
-
- // 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 toHex (n) {
- if (n < 16) return '0' + n.toString(16)
- return n.toString(16)
-}
-
-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
-}
-
-}).call(this)}).call(this,require("buffer").Buffer)
-},{"base64-js":6,"buffer":10,"ieee754":15}],11:[function(require,module,exports){
-module.exports = {
- "100": "Continue",
- "101": "Switching Protocols",
- "102": "Processing",
- "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",
- "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"
-}
-
-},{}],12:[function(require,module,exports){
-(function (Buffer){(function (){
-// 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.
-
-// NOTE: These type checking functions intentionally don't use `instanceof`
-// because it is fragile and can be easily faked with `Object.create()`.
-
-function isArray(arg) {
- if (Array.isArray) {
- return Array.isArray(arg);
- }
- return objectToString(arg) === '[object Array]';
-}
-exports.isArray = isArray;
-
-function isBoolean(arg) {
- return typeof arg === 'boolean';
-}
-exports.isBoolean = isBoolean;
-
-function isNull(arg) {
- return arg === null;
-}
-exports.isNull = isNull;
-
-function isNullOrUndefined(arg) {
- return arg == null;
-}
-exports.isNullOrUndefined = isNullOrUndefined;
-
-function isNumber(arg) {
- return typeof arg === 'number';
-}
-exports.isNumber = isNumber;
-
-function isString(arg) {
- return typeof arg === 'string';
-}
-exports.isString = isString;
-
-function isSymbol(arg) {
- return typeof arg === 'symbol';
-}
-exports.isSymbol = isSymbol;
-
-function isUndefined(arg) {
- return arg === void 0;
-}
-exports.isUndefined = isUndefined;
-
-function isRegExp(re) {
- return objectToString(re) === '[object RegExp]';
-}
-exports.isRegExp = isRegExp;
-
-function isObject(arg) {
- return typeof arg === 'object' && arg !== null;
-}
-exports.isObject = isObject;
-
-function isDate(d) {
- return objectToString(d) === '[object Date]';
-}
-exports.isDate = isDate;
-
-function isError(e) {
- return (objectToString(e) === '[object Error]' || e instanceof Error);
-}
-exports.isError = isError;
-
-function isFunction(arg) {
- return typeof arg === 'function';
-}
-exports.isFunction = isFunction;
-
-function isPrimitive(arg) {
- return arg === null ||
- typeof arg === 'boolean' ||
- typeof arg === 'number' ||
- typeof arg === 'string' ||
- typeof arg === 'symbol' || // ES6 symbol
- typeof arg === 'undefined';
-}
-exports.isPrimitive = isPrimitive;
-
-exports.isBuffer = Buffer.isBuffer;
-
-function objectToString(o) {
- return Object.prototype.toString.call(o);
-}
-
-}).call(this)}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
-},{"../../is-buffer/index.js":17}],13:[function(require,module,exports){
-// 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 objectCreate = Object.create || objectCreatePolyfill
-var objectKeys = Object.keys || objectKeysPolyfill
-var bind = Function.prototype.bind || functionBindPolyfill
-
-function EventEmitter() {
- if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
- this._events = objectCreate(null);
- this._eventsCount = 0;
- }
-
- this._maxListeners = this._maxListeners || undefined;
-}
-module.exports = EventEmitter;
-
-// Backwards-compat with node 0.10.x
-EventEmitter.EventEmitter = EventEmitter;
-
-EventEmitter.prototype._events = undefined;
-EventEmitter.prototype._maxListeners = undefined;
-
-// By default EventEmitters will print a warning if more than 10 listeners are
-// added to it. This is a useful default which helps finding memory leaks.
-var defaultMaxListeners = 10;
-
-var hasDefineProperty;
-try {
- var o = {};
- if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
- hasDefineProperty = o.x === 0;
-} catch (err) { hasDefineProperty = false }
-if (hasDefineProperty) {
- Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
- enumerable: true,
- get: function() {
- return defaultMaxListeners;
- },
- set: function(arg) {
- // check whether the input is a positive number (whose value is zero or
- // greater and not a NaN).
- if (typeof arg !== 'number' || arg < 0 || arg !== arg)
- throw new TypeError('"defaultMaxListeners" must be a positive number');
- defaultMaxListeners = arg;
- }
- });
-} else {
- EventEmitter.defaultMaxListeners = defaultMaxListeners;
-}
-
-// Obviously not all Emitters should be limited to 10. This function allows
-// that to be increased. Set to zero for unlimited.
-EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
- if (typeof n !== 'number' || n < 0 || isNaN(n))
- throw new TypeError('"n" argument must be a positive number');
- this._maxListeners = n;
- return this;
-};
-
-function $getMaxListeners(that) {
- if (that._maxListeners === undefined)
- return EventEmitter.defaultMaxListeners;
- return that._maxListeners;
-}
-
-EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
- return $getMaxListeners(this);
-};
-
-// These standalone emit* functions are used to optimize calling of event
-// handlers for fast cases because emit() itself often has a variable number of
-// arguments and can be deoptimized because of that. These functions always have
-// the same number of arguments and thus do not get deoptimized, so the code
-// inside them can execute faster.
-function emitNone(handler, isFn, self) {
- if (isFn)
- handler.call(self);
- else {
- var len = handler.length;
- var listeners = arrayClone(handler, len);
- for (var i = 0; i < len; ++i)
- listeners[i].call(self);
- }
-}
-function emitOne(handler, isFn, self, arg1) {
- if (isFn)
- handler.call(self, arg1);
- else {
- var len = handler.length;
- var listeners = arrayClone(handler, len);
- for (var i = 0; i < len; ++i)
- listeners[i].call(self, arg1);
- }
-}
-function emitTwo(handler, isFn, self, arg1, arg2) {
- if (isFn)
- handler.call(self, arg1, arg2);
- else {
- var len = handler.length;
- var listeners = arrayClone(handler, len);
- for (var i = 0; i < len; ++i)
- listeners[i].call(self, arg1, arg2);
- }
-}
-function emitThree(handler, isFn, self, arg1, arg2, arg3) {
- if (isFn)
- handler.call(self, arg1, arg2, arg3);
- else {
- var len = handler.length;
- var listeners = arrayClone(handler, len);
- for (var i = 0; i < len; ++i)
- listeners[i].call(self, arg1, arg2, arg3);
- }
-}
-
-function emitMany(handler, isFn, self, args) {
- if (isFn)
- handler.apply(self, args);
- else {
- var len = handler.length;
- var listeners = arrayClone(handler, len);
- for (var i = 0; i < len; ++i)
- listeners[i].apply(self, args);
- }
-}
-
-EventEmitter.prototype.emit = function emit(type) {
- var er, handler, len, args, i, events;
- var doError = (type === 'error');
-
- events = this._events;
- if (events)
- doError = (doError && events.error == null);
- else if (!doError)
- return false;
-
- // If there is no 'error' event listener then throw.
- if (doError) {
- if (arguments.length > 1)
- er = arguments[1];
- if (er instanceof Error) {
- throw er; // Unhandled 'error' event
- } else {
- // At least give some kind of context to the user
- var err = new Error('Unhandled "error" event. (' + er + ')');
- err.context = er;
- throw err;
- }
- return false;
- }
-
- handler = events[type];
-
- if (!handler)
- return false;
-
- var isFn = typeof handler === 'function';
- len = arguments.length;
- switch (len) {
- // fast cases
- case 1:
- emitNone(handler, isFn, this);
- break;
- case 2:
- emitOne(handler, isFn, this, arguments[1]);
- break;
- case 3:
- emitTwo(handler, isFn, this, arguments[1], arguments[2]);
- break;
- case 4:
- emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
- break;
- // slower
- default:
- args = new Array(len - 1);
- for (i = 1; i < len; i++)
- args[i - 1] = arguments[i];
- emitMany(handler, isFn, this, args);
- }
-
- return true;
-};
-
-function _addListener(target, type, listener, prepend) {
- var m;
- var events;
- var existing;
-
- if (typeof listener !== 'function')
- throw new TypeError('"listener" argument must be a function');
-
- events = target._events;
- if (!events) {
- events = target._events = objectCreate(null);
- target._eventsCount = 0;
- } else {
- // To avoid recursion in the case that type === "newListener"! Before
- // adding it to the listeners, first emit "newListener".
- if (events.newListener) {
- target.emit('newListener', type,
- listener.listener ? listener.listener : listener);
-
- // Re-assign `events` because a newListener handler could have caused the
- // this._events to be assigned to a new object
- events = target._events;
- }
- existing = events[type];
- }
-
- if (!existing) {
- // Optimize the case of one listener. Don't need the extra array object.
- existing = events[type] = listener;
- ++target._eventsCount;
- } else {
- if (typeof existing === 'function') {
- // Adding the second element, need to change to array.
- existing = events[type] =
- prepend ? [listener, existing] : [existing, listener];
- } else {
- // If we've already got an array, just append.
- if (prepend) {
- existing.unshift(listener);
- } else {
- existing.push(listener);
- }
- }
-
- // Check for listener leak
- if (!existing.warned) {
- m = $getMaxListeners(target);
- if (m && m > 0 && existing.length > m) {
- existing.warned = true;
- var w = new Error('Possible EventEmitter memory leak detected. ' +
- existing.length + ' "' + String(type) + '" listeners ' +
- 'added. Use emitter.setMaxListeners() to ' +
- 'increase limit.');
- w.name = 'MaxListenersExceededWarning';
- w.emitter = target;
- w.type = type;
- w.count = existing.length;
- if (typeof console === 'object' && console.warn) {
- console.warn('%s: %s', w.name, w.message);
- }
- }
- }
- }
-
- return target;
-}
-
-EventEmitter.prototype.addListener = function addListener(type, listener) {
- return _addListener(this, type, listener, false);
-};
-
-EventEmitter.prototype.on = EventEmitter.prototype.addListener;
-
-EventEmitter.prototype.prependListener =
- function prependListener(type, listener) {
- return _addListener(this, type, listener, true);
- };
-
-function onceWrapper() {
- if (!this.fired) {
- this.target.removeListener(this.type, this.wrapFn);
- this.fired = true;
- switch (arguments.length) {
- case 0:
- return this.listener.call(this.target);
- case 1:
- return this.listener.call(this.target, arguments[0]);
- case 2:
- return this.listener.call(this.target, arguments[0], arguments[1]);
- case 3:
- return this.listener.call(this.target, arguments[0], arguments[1],
- arguments[2]);
- default:
- var args = new Array(arguments.length);
- for (var i = 0; i < args.length; ++i)
- args[i] = arguments[i];
- this.listener.apply(this.target, args);
- }
- }
-}
-
-function _onceWrap(target, type, listener) {
- var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
- var wrapped = bind.call(onceWrapper, state);
- wrapped.listener = listener;
- state.wrapFn = wrapped;
- return wrapped;
-}
-
-EventEmitter.prototype.once = function once(type, listener) {
- if (typeof listener !== 'function')
- throw new TypeError('"listener" argument must be a function');
- this.on(type, _onceWrap(this, type, listener));
- return this;
-};
-
-EventEmitter.prototype.prependOnceListener =
- function prependOnceListener(type, listener) {
- if (typeof listener !== 'function')
- throw new TypeError('"listener" argument must be a function');
- this.prependListener(type, _onceWrap(this, type, listener));
- return this;
- };
-
-// Emits a 'removeListener' event if and only if the listener was removed.
-EventEmitter.prototype.removeListener =
- function removeListener(type, listener) {
- var list, events, position, i, originalListener;
-
- if (typeof listener !== 'function')
- throw new TypeError('"listener" argument must be a function');
-
- events = this._events;
- if (!events)
- return this;
-
- list = events[type];
- if (!list)
- return this;
-
- if (list === listener || list.listener === listener) {
- if (--this._eventsCount === 0)
- this._events = objectCreate(null);
- else {
- delete events[type];
- if (events.removeListener)
- this.emit('removeListener', type, list.listener || listener);
- }
- } else if (typeof list !== 'function') {
- position = -1;
-
- for (i = list.length - 1; i >= 0; i--) {
- if (list[i] === listener || list[i].listener === listener) {
- originalListener = list[i].listener;
- position = i;
- break;
- }
- }
-
- if (position < 0)
- return this;
-
- if (position === 0)
- list.shift();
- else
- spliceOne(list, position);
-
- if (list.length === 1)
- events[type] = list[0];
-
- if (events.removeListener)
- this.emit('removeListener', type, originalListener || listener);
- }
-
- return this;
- };
-
-EventEmitter.prototype.removeAllListeners =
- function removeAllListeners(type) {
- var listeners, events, i;
-
- events = this._events;
- if (!events)
- return this;
-
- // not listening for removeListener, no need to emit
- if (!events.removeListener) {
- if (arguments.length === 0) {
- this._events = objectCreate(null);
- this._eventsCount = 0;
- } else if (events[type]) {
- if (--this._eventsCount === 0)
- this._events = objectCreate(null);
- else
- delete events[type];
- }
- return this;
- }
-
- // emit removeListener for all listeners on all events
- if (arguments.length === 0) {
- var keys = objectKeys(events);
- var key;
- for (i = 0; i < keys.length; ++i) {
- key = keys[i];
- if (key === 'removeListener') continue;
- this.removeAllListeners(key);
- }
- this.removeAllListeners('removeListener');
- this._events = objectCreate(null);
- this._eventsCount = 0;
- return this;
- }
-
- listeners = events[type];
-
- if (typeof listeners === 'function') {
- this.removeListener(type, listeners);
- } else if (listeners) {
- // LIFO order
- for (i = listeners.length - 1; i >= 0; i--) {
- this.removeListener(type, listeners[i]);
- }
- }
-
- return this;
- };
-
-function _listeners(target, type, unwrap) {
- var events = target._events;
-
- if (!events)
- return [];
-
- var evlistener = events[type];
- if (!evlistener)
- return [];
-
- if (typeof evlistener === 'function')
- return unwrap ? [evlistener.listener || evlistener] : [evlistener];
-
- return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
-}
-
-EventEmitter.prototype.listeners = function listeners(type) {
- return _listeners(this, type, true);
-};
-
-EventEmitter.prototype.rawListeners = function rawListeners(type) {
- return _listeners(this, type, false);
-};
-
-EventEmitter.listenerCount = function(emitter, type) {
- if (typeof emitter.listenerCount === 'function') {
- return emitter.listenerCount(type);
- } else {
- return listenerCount.call(emitter, type);
- }
-};
-
-EventEmitter.prototype.listenerCount = listenerCount;
-function listenerCount(type) {
- var events = this._events;
-
- if (events) {
- var evlistener = events[type];
-
- if (typeof evlistener === 'function') {
- return 1;
- } else if (evlistener) {
- return evlistener.length;
- }
- }
-
- return 0;
-}
-
-EventEmitter.prototype.eventNames = function eventNames() {
- return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
-};
-
-// About 1.5x faster than the two-arg version of Array#splice().
-function spliceOne(list, index) {
- for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
- list[i] = list[k];
- list.pop();
-}
-
-function arrayClone(arr, n) {
- var copy = new Array(n);
- for (var i = 0; i < n; ++i)
- copy[i] = arr[i];
- return copy;
-}
-
-function unwrapListeners(arr) {
- var ret = new Array(arr.length);
- for (var i = 0; i < ret.length; ++i) {
- ret[i] = arr[i].listener || arr[i];
- }
- return ret;
-}
-
-function objectCreatePolyfill(proto) {
- var F = function() {};
- F.prototype = proto;
- return new F;
-}
-function objectKeysPolyfill(obj) {
- var keys = [];
- for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
- keys.push(k);
- }
- return k;
-}
-function functionBindPolyfill(context) {
- var fn = this;
- return function () {
- return fn.apply(context, arguments);
- };
-}
-
-},{}],14:[function(require,module,exports){
-var http = require('http')
-var url = require('url')
-
-var https = module.exports
-
-for (var key in http) {
- if (http.hasOwnProperty(key)) https[key] = http[key]
-}
-
-https.request = function (params, cb) {
- params = validateParams(params)
- return http.request.call(this, params, cb)
-}
-
-https.get = function (params, cb) {
- params = validateParams(params)
- return http.get.call(this, params, cb)
-}
-
-function validateParams (params) {
- if (typeof params === 'string') {
- params = url.parse(params)
- }
- if (!params.protocol) {
- params.protocol = 'https:'
- }
- if (params.protocol !== 'https:') {
- throw new Error('Protocol "' + params.protocol + '" not supported. Expected "https:"')
- }
- return params
-}
-
-},{"http":56,"url":77}],15:[function(require,module,exports){
-/*! 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
-}
-
-},{}],16:[function(require,module,exports){
-if (typeof Object.create === 'function') {
- // implementation from standard node.js 'util' module
- module.exports = function inherits(ctor, superCtor) {
- if (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) {
- if (superCtor) {
- ctor.super_ = superCtor
- var TempCtor = function () {}
- TempCtor.prototype = superCtor.prototype
- ctor.prototype = new TempCtor()
- ctor.prototype.constructor = ctor
- }
- }
-}
-
-},{}],17:[function(require,module,exports){
-/*!
- * Determine if an object is a Buffer
- *
- * @author Feross Aboukhadijeh
- * @license MIT
- */
-
-// The _isBuffer check is for Safari 5-7 support, because it's missing
-// Object.prototype.constructor. Remove this eventually
-module.exports = function (obj) {
- return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
-}
-
-function isBuffer (obj) {
- return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
-}
-
-// For Node v0.10 support. Remove this eventually.
-function isSlowBuffer (obj) {
- return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
-}
-
-},{}],18:[function(require,module,exports){
-var toString = {}.toString;
-
-module.exports = Array.isArray || function (arr) {
- return toString.call(arr) == '[object Array]';
-};
-
-},{}],19:[function(require,module,exports){
-/*
-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;
-};
-
-},{}],20:[function(require,module,exports){
-exports.endianness = function () { return 'LE' };
-
-exports.hostname = function () {
- if (typeof location !== 'undefined') {
- return location.hostname
- }
- else return '';
-};
-
-exports.loadavg = function () { return [] };
-
-exports.uptime = function () { return 0 };
-
-exports.freemem = function () {
- return Number.MAX_VALUE;
-};
-
-exports.totalmem = function () {
- return Number.MAX_VALUE;
-};
-
-exports.cpus = function () { return [] };
-
-exports.type = function () { return 'Browser' };
-
-exports.release = function () {
- if (typeof navigator !== 'undefined') {
- return navigator.appVersion;
- }
- return '';
-};
-
-exports.networkInterfaces
-= exports.getNetworkInterfaces
-= function () { return {} };
-
-exports.arch = function () { return 'javascript' };
-
-exports.platform = function () { return 'browser' };
-
-exports.tmpdir = exports.tmpDir = function () {
- return '/tmp';
-};
-
-exports.EOL = '\n';
-
-exports.homedir = function () {
- return '/'
-};
-
-},{}],21:[function(require,module,exports){
-'use strict';
-
-
-var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
- (typeof Uint16Array !== 'undefined') &&
- (typeof Int32Array !== 'undefined');
-
-function _has(obj, key) {
- return Object.prototype.hasOwnProperty.call(obj, key);
-}
-
-exports.assign = function (obj /*from1, from2, from3, ...*/) {
- var sources = Array.prototype.slice.call(arguments, 1);
- while (sources.length) {
- var source = sources.shift();
- if (!source) { continue; }
-
- if (typeof source !== 'object') {
- throw new TypeError(source + 'must be non-object');
- }
-
- for (var p in source) {
- if (_has(source, p)) {
- obj[p] = source[p];
- }
- }
- }
-
- return obj;
-};
-
-
-// reduce buffer size, avoiding mem copy
-exports.shrinkBuf = function (buf, size) {
- if (buf.length === size) { return buf; }
- if (buf.subarray) { return buf.subarray(0, size); }
- buf.length = size;
- return buf;
-};
-
-
-var fnTyped = {
- arraySet: function (dest, src, src_offs, len, dest_offs) {
- if (src.subarray && dest.subarray) {
- dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
- return;
- }
- // Fallback to ordinary array
- for (var i = 0; i < len; i++) {
- dest[dest_offs + i] = src[src_offs + i];
- }
- },
- // Join array of chunks to single array.
- flattenChunks: function (chunks) {
- var i, l, len, pos, chunk, result;
-
- // calculate data length
- len = 0;
- for (i = 0, l = chunks.length; i < l; i++) {
- len += chunks[i].length;
- }
-
- // join chunks
- result = new Uint8Array(len);
- pos = 0;
- for (i = 0, l = chunks.length; i < l; i++) {
- chunk = chunks[i];
- result.set(chunk, pos);
- pos += chunk.length;
- }
-
- return result;
- }
-};
-
-var fnUntyped = {
- arraySet: function (dest, src, src_offs, len, dest_offs) {
- for (var i = 0; i < len; i++) {
- dest[dest_offs + i] = src[src_offs + i];
- }
- },
- // Join array of chunks to single array.
- flattenChunks: function (chunks) {
- return [].concat.apply([], chunks);
- }
-};
-
-
-// Enable/Disable typed arrays use, for testing
-//
-exports.setTyped = function (on) {
- if (on) {
- exports.Buf8 = Uint8Array;
- exports.Buf16 = Uint16Array;
- exports.Buf32 = Int32Array;
- exports.assign(exports, fnTyped);
- } else {
- exports.Buf8 = Array;
- exports.Buf16 = Array;
- exports.Buf32 = Array;
- exports.assign(exports, fnUntyped);
- }
-};
-
-exports.setTyped(TYPED_OK);
-
-},{}],22:[function(require,module,exports){
-'use strict';
-
-// Note: adler32 takes 12% for level 0 and 2% for level 6.
-// It isn't worth it to make additional optimizations as in original.
-// Small size is preferable.
-
-// (C) 1995-2013 Jean-loup Gailly and Mark Adler
-// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
-//
-// This software is provided 'as-is', without any express or implied
-// warranty. In no event will the authors be held liable for any damages
-// arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it
-// freely, subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented; you must not
-// claim that you wrote the original software. If you use this software
-// in a product, an acknowledgment in the product documentation would be
-// appreciated but is not required.
-// 2. Altered source versions must be plainly marked as such, and must not be
-// misrepresented as being the original software.
-// 3. This notice may not be removed or altered from any source distribution.
-
-function adler32(adler, buf, len, pos) {
- var s1 = (adler & 0xffff) |0,
- s2 = ((adler >>> 16) & 0xffff) |0,
- n = 0;
-
- while (len !== 0) {
- // Set limit ~ twice less than 5552, to keep
- // s2 in 31-bits, because we force signed ints.
- // in other case %= will fail.
- n = len > 2000 ? 2000 : len;
- len -= n;
-
- do {
- s1 = (s1 + buf[pos++]) |0;
- s2 = (s2 + s1) |0;
- } while (--n);
-
- s1 %= 65521;
- s2 %= 65521;
- }
-
- return (s1 | (s2 << 16)) |0;
-}
-
-
-module.exports = adler32;
-
-},{}],23:[function(require,module,exports){
-'use strict';
-
-// (C) 1995-2013 Jean-loup Gailly and Mark Adler
-// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
-//
-// This software is provided 'as-is', without any express or implied
-// warranty. In no event will the authors be held liable for any damages
-// arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it
-// freely, subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented; you must not
-// claim that you wrote the original software. If you use this software
-// in a product, an acknowledgment in the product documentation would be
-// appreciated but is not required.
-// 2. Altered source versions must be plainly marked as such, and must not be
-// misrepresented as being the original software.
-// 3. This notice may not be removed or altered from any source distribution.
-
-module.exports = {
-
- /* Allowed flush values; see deflate() and inflate() below for details */
- Z_NO_FLUSH: 0,
- Z_PARTIAL_FLUSH: 1,
- Z_SYNC_FLUSH: 2,
- Z_FULL_FLUSH: 3,
- Z_FINISH: 4,
- Z_BLOCK: 5,
- Z_TREES: 6,
-
- /* Return codes for the compression/decompression functions. Negative values
- * are errors, positive values are used for special but normal events.
- */
- 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,
-
- /* compression levels */
- 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,
-
- /* Possible values of the data_type field (though see inflate()) */
- Z_BINARY: 0,
- Z_TEXT: 1,
- //Z_ASCII: 1, // = Z_TEXT (deprecated)
- Z_UNKNOWN: 2,
-
- /* The deflate compression method */
- Z_DEFLATED: 8
- //Z_NULL: null // Use -1 or null inline, depending on var type
-};
-
-},{}],24:[function(require,module,exports){
-'use strict';
-
-// Note: we can't get significant speed boost here.
-// So write code to minimize size - no pregenerated tables
-// and array tools dependencies.
-
-// (C) 1995-2013 Jean-loup Gailly and Mark Adler
-// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
-//
-// This software is provided 'as-is', without any express or implied
-// warranty. In no event will the authors be held liable for any damages
-// arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it
-// freely, subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented; you must not
-// claim that you wrote the original software. If you use this software
-// in a product, an acknowledgment in the product documentation would be
-// appreciated but is not required.
-// 2. Altered source versions must be plainly marked as such, and must not be
-// misrepresented as being the original software.
-// 3. This notice may not be removed or altered from any source distribution.
-
-// Use ordinary array, since untyped makes no boost here
-function makeTable() {
- var c, table = [];
-
- for (var n = 0; n < 256; n++) {
- c = n;
- for (var k = 0; k < 8; k++) {
- c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
- }
- table[n] = c;
- }
-
- return table;
-}
-
-// Create table on load. Just 255 signed longs. Not a problem.
-var crcTable = makeTable();
-
-
-function crc32(crc, buf, len, pos) {
- var t = crcTable,
- end = pos + len;
-
- crc ^= -1;
-
- for (var i = pos; i < end; i++) {
- crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
- }
-
- return (crc ^ (-1)); // >>> 0;
-}
-
-
-module.exports = crc32;
-
-},{}],25:[function(require,module,exports){
-'use strict';
-
-// (C) 1995-2013 Jean-loup Gailly and Mark Adler
-// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
-//
-// This software is provided 'as-is', without any express or implied
-// warranty. In no event will the authors be held liable for any damages
-// arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it
-// freely, subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented; you must not
-// claim that you wrote the original software. If you use this software
-// in a product, an acknowledgment in the product documentation would be
-// appreciated but is not required.
-// 2. Altered source versions must be plainly marked as such, and must not be
-// misrepresented as being the original software.
-// 3. This notice may not be removed or altered from any source distribution.
-
-var utils = require('../utils/common');
-var trees = require('./trees');
-var adler32 = require('./adler32');
-var crc32 = require('./crc32');
-var msg = require('./messages');
-
-/* Public constants ==========================================================*/
-/* ===========================================================================*/
-
-
-/* Allowed flush values; see deflate() and inflate() below for details */
-var Z_NO_FLUSH = 0;
-var Z_PARTIAL_FLUSH = 1;
-//var Z_SYNC_FLUSH = 2;
-var Z_FULL_FLUSH = 3;
-var Z_FINISH = 4;
-var Z_BLOCK = 5;
-//var Z_TREES = 6;
-
-
-/* Return codes for the compression/decompression functions. Negative values
- * are errors, positive values are used for special but normal events.
- */
-var Z_OK = 0;
-var Z_STREAM_END = 1;
-//var Z_NEED_DICT = 2;
-//var Z_ERRNO = -1;
-var Z_STREAM_ERROR = -2;
-var Z_DATA_ERROR = -3;
-//var Z_MEM_ERROR = -4;
-var Z_BUF_ERROR = -5;
-//var Z_VERSION_ERROR = -6;
-
-
-/* compression levels */
-//var Z_NO_COMPRESSION = 0;
-//var Z_BEST_SPEED = 1;
-//var Z_BEST_COMPRESSION = 9;
-var Z_DEFAULT_COMPRESSION = -1;
-
-
-var Z_FILTERED = 1;
-var Z_HUFFMAN_ONLY = 2;
-var Z_RLE = 3;
-var Z_FIXED = 4;
-var Z_DEFAULT_STRATEGY = 0;
-
-/* Possible values of the data_type field (though see inflate()) */
-//var Z_BINARY = 0;
-//var Z_TEXT = 1;
-//var Z_ASCII = 1; // = Z_TEXT
-var Z_UNKNOWN = 2;
-
-
-/* The deflate compression method */
-var Z_DEFLATED = 8;
-
-/*============================================================================*/
-
-
-var MAX_MEM_LEVEL = 9;
-/* Maximum value for memLevel in deflateInit2 */
-var MAX_WBITS = 15;
-/* 32K LZ77 window */
-var DEF_MEM_LEVEL = 8;
-
-
-var LENGTH_CODES = 29;
-/* number of length codes, not counting the special END_BLOCK code */
-var LITERALS = 256;
-/* number of literal bytes 0..255 */
-var L_CODES = LITERALS + 1 + LENGTH_CODES;
-/* number of Literal or Length codes, including the END_BLOCK code */
-var D_CODES = 30;
-/* number of distance codes */
-var BL_CODES = 19;
-/* number of codes used to transfer the bit lengths */
-var HEAP_SIZE = 2 * L_CODES + 1;
-/* maximum heap size */
-var MAX_BITS = 15;
-/* All codes must not exceed MAX_BITS bits */
-
-var MIN_MATCH = 3;
-var MAX_MATCH = 258;
-var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
-
-var PRESET_DICT = 0x20;
-
-var INIT_STATE = 42;
-var EXTRA_STATE = 69;
-var NAME_STATE = 73;
-var COMMENT_STATE = 91;
-var HCRC_STATE = 103;
-var BUSY_STATE = 113;
-var FINISH_STATE = 666;
-
-var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
-var BS_BLOCK_DONE = 2; /* block flush performed */
-var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
-var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
-
-var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
-
-function err(strm, errorCode) {
- strm.msg = msg[errorCode];
- return errorCode;
-}
-
-function rank(f) {
- return ((f) << 1) - ((f) > 4 ? 9 : 0);
-}
-
-function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
-
-
-/* =========================================================================
- * Flush as much pending output as possible. All deflate() output goes
- * through this function so some applications may wish to modify it
- * to avoid allocating a large strm->output buffer and copying into it.
- * (See also read_buf()).
- */
-function flush_pending(strm) {
- var s = strm.state;
-
- //_tr_flush_bits(s);
- var len = s.pending;
- if (len > strm.avail_out) {
- len = strm.avail_out;
- }
- if (len === 0) { return; }
-
- utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
- strm.next_out += len;
- s.pending_out += len;
- strm.total_out += len;
- strm.avail_out -= len;
- s.pending -= len;
- if (s.pending === 0) {
- s.pending_out = 0;
- }
-}
-
-
-function flush_block_only(s, last) {
- trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
- s.block_start = s.strstart;
- flush_pending(s.strm);
-}
-
-
-function put_byte(s, b) {
- s.pending_buf[s.pending++] = b;
-}
-
-
-/* =========================================================================
- * Put a short in the pending buffer. The 16-bit value is put in MSB order.
- * IN assertion: the stream state is correct and there is enough room in
- * pending_buf.
- */
-function putShortMSB(s, b) {
-// put_byte(s, (Byte)(b >> 8));
-// put_byte(s, (Byte)(b & 0xff));
- s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
- s.pending_buf[s.pending++] = b & 0xff;
-}
-
-
-/* ===========================================================================
- * Read a new buffer from the current input stream, update the adler32
- * and total number of bytes read. All deflate() input goes through
- * this function so some applications may wish to modify it to avoid
- * allocating a large strm->input buffer and copying from it.
- * (See also flush_pending()).
- */
-function read_buf(strm, buf, start, size) {
- var len = strm.avail_in;
-
- if (len > size) { len = size; }
- if (len === 0) { return 0; }
-
- strm.avail_in -= len;
-
- // zmemcpy(buf, strm->next_in, len);
- utils.arraySet(buf, strm.input, strm.next_in, len, start);
- if (strm.state.wrap === 1) {
- strm.adler = adler32(strm.adler, buf, len, start);
- }
-
- else if (strm.state.wrap === 2) {
- strm.adler = crc32(strm.adler, buf, len, start);
- }
-
- strm.next_in += len;
- strm.total_in += len;
-
- return len;
-}
-
-
-/* ===========================================================================
- * Set match_start to the longest match starting at the given string and
- * return its length. Matches shorter or equal to prev_length are discarded,
- * in which case the result is equal to prev_length and match_start is
- * garbage.
- * IN assertions: cur_match is the head of the hash chain for the current
- * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
- * OUT assertion: the match length is not greater than s->lookahead.
- */
-function longest_match(s, cur_match) {
- var chain_length = s.max_chain_length; /* max hash chain length */
- var scan = s.strstart; /* current string */
- var match; /* matched string */
- var len; /* length of current match */
- var best_len = s.prev_length; /* best match length so far */
- var nice_match = s.nice_match; /* stop if match long enough */
- var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
- s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
-
- var _win = s.window; // shortcut
-
- var wmask = s.w_mask;
- var prev = s.prev;
-
- /* Stop when cur_match becomes <= limit. To simplify the code,
- * we prevent matches with the string of window index 0.
- */
-
- var strend = s.strstart + MAX_MATCH;
- var scan_end1 = _win[scan + best_len - 1];
- var scan_end = _win[scan + best_len];
-
- /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
- * It is easy to get rid of this optimization if necessary.
- */
- // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
-
- /* Do not waste too much time if we already have a good match: */
- if (s.prev_length >= s.good_match) {
- chain_length >>= 2;
- }
- /* Do not look for matches beyond the end of the input. This is necessary
- * to make deflate deterministic.
- */
- if (nice_match > s.lookahead) { nice_match = s.lookahead; }
-
- // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
-
- do {
- // Assert(cur_match < s->strstart, "no future");
- match = cur_match;
-
- /* Skip to next match if the match length cannot increase
- * or if the match length is less than 2. Note that the checks below
- * for insufficient lookahead only occur occasionally for performance
- * reasons. Therefore uninitialized memory will be accessed, and
- * conditional jumps will be made that depend on those values.
- * However the length of the match is limited to the lookahead, so
- * the output of deflate is not affected by the uninitialized values.
- */
-
- if (_win[match + best_len] !== scan_end ||
- _win[match + best_len - 1] !== scan_end1 ||
- _win[match] !== _win[scan] ||
- _win[++match] !== _win[scan + 1]) {
- continue;
- }
-
- /* The check at best_len-1 can be removed because it will be made
- * again later. (This heuristic is not always a win.)
- * It is not necessary to compare scan[2] and match[2] since they
- * are always equal when the other bytes match, given that
- * the hash keys are equal and that HASH_BITS >= 8.
- */
- scan += 2;
- match++;
- // Assert(*scan == *match, "match[2]?");
-
- /* We check for insufficient lookahead only every 8th comparison;
- * the 256th check will be made at strstart+258.
- */
- do {
- /*jshint noempty:false*/
- } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
- _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
- _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
- _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
- scan < strend);
-
- // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
-
- len = MAX_MATCH - (strend - scan);
- scan = strend - MAX_MATCH;
-
- if (len > best_len) {
- s.match_start = cur_match;
- best_len = len;
- if (len >= nice_match) {
- break;
- }
- scan_end1 = _win[scan + best_len - 1];
- scan_end = _win[scan + best_len];
- }
- } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
-
- if (best_len <= s.lookahead) {
- return best_len;
- }
- return s.lookahead;
-}
-
-
-/* ===========================================================================
- * Fill the window when the lookahead becomes insufficient.
- * Updates strstart and lookahead.
- *
- * IN assertion: lookahead < MIN_LOOKAHEAD
- * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
- * At least one byte has been read, or avail_in == 0; reads are
- * performed for at least two bytes (required for the zip translate_eol
- * option -- not supported here).
- */
-function fill_window(s) {
- var _w_size = s.w_size;
- var p, n, m, more, str;
-
- //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
-
- do {
- more = s.window_size - s.lookahead - s.strstart;
-
- // JS ints have 32 bit, block below not needed
- /* Deal with !@#$% 64K limit: */
- //if (sizeof(int) <= 2) {
- // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
- // more = wsize;
- //
- // } else if (more == (unsigned)(-1)) {
- // /* Very unlikely, but possible on 16 bit machine if
- // * strstart == 0 && lookahead == 1 (input done a byte at time)
- // */
- // more--;
- // }
- //}
-
-
- /* If the window is almost full and there is insufficient lookahead,
- * move the upper half to the lower one to make room in the upper half.
- */
- if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
-
- utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
- s.match_start -= _w_size;
- s.strstart -= _w_size;
- /* we now have strstart >= MAX_DIST */
- s.block_start -= _w_size;
-
- /* Slide the hash table (could be avoided with 32 bit values
- at the expense of memory usage). We slide even when level == 0
- to keep the hash table consistent if we switch back to level > 0
- later. (Using level 0 permanently is not an optimal usage of
- zlib, so we don't care about this pathological case.)
- */
-
- n = s.hash_size;
- p = n;
- do {
- m = s.head[--p];
- s.head[p] = (m >= _w_size ? m - _w_size : 0);
- } while (--n);
-
- n = _w_size;
- p = n;
- do {
- m = s.prev[--p];
- s.prev[p] = (m >= _w_size ? m - _w_size : 0);
- /* If n is not on any hash chain, prev[n] is garbage but
- * its value will never be used.
- */
- } while (--n);
-
- more += _w_size;
- }
- if (s.strm.avail_in === 0) {
- break;
- }
-
- /* If there was no sliding:
- * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
- * more == window_size - lookahead - strstart
- * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
- * => more >= window_size - 2*WSIZE + 2
- * In the BIG_MEM or MMAP case (not yet supported),
- * window_size == input_size + MIN_LOOKAHEAD &&
- * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
- * Otherwise, window_size == 2*WSIZE so more >= 2.
- * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
- */
- //Assert(more >= 2, "more < 2");
- n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
- s.lookahead += n;
-
- /* Initialize the hash value now that we have some input: */
- if (s.lookahead + s.insert >= MIN_MATCH) {
- str = s.strstart - s.insert;
- s.ins_h = s.window[str];
-
- /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
-//#if MIN_MATCH != 3
-// Call update_hash() MIN_MATCH-3 more times
-//#endif
- while (s.insert) {
- /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
-
- s.prev[str & s.w_mask] = s.head[s.ins_h];
- s.head[s.ins_h] = str;
- str++;
- s.insert--;
- if (s.lookahead + s.insert < MIN_MATCH) {
- break;
- }
- }
- }
- /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
- * but this is not important since only literal bytes will be emitted.
- */
-
- } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
-
- /* If the WIN_INIT bytes after the end of the current data have never been
- * written, then zero those bytes in order to avoid memory check reports of
- * the use of uninitialized (or uninitialised as Julian writes) bytes by
- * the longest match routines. Update the high water mark for the next
- * time through here. WIN_INIT is set to MAX_MATCH since the longest match
- * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
- */
-// if (s.high_water < s.window_size) {
-// var curr = s.strstart + s.lookahead;
-// var init = 0;
-//
-// if (s.high_water < curr) {
-// /* Previous high water mark below current data -- zero WIN_INIT
-// * bytes or up to end of window, whichever is less.
-// */
-// init = s.window_size - curr;
-// if (init > WIN_INIT)
-// init = WIN_INIT;
-// zmemzero(s->window + curr, (unsigned)init);
-// s->high_water = curr + init;
-// }
-// else if (s->high_water < (ulg)curr + WIN_INIT) {
-// /* High water mark at or above current data, but below current data
-// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
-// * to end of window, whichever is less.
-// */
-// init = (ulg)curr + WIN_INIT - s->high_water;
-// if (init > s->window_size - s->high_water)
-// init = s->window_size - s->high_water;
-// zmemzero(s->window + s->high_water, (unsigned)init);
-// s->high_water += init;
-// }
-// }
-//
-// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
-// "not enough room for search");
-}
-
-/* ===========================================================================
- * Copy without compression as much as possible from the input stream, return
- * the current block state.
- * This function does not insert new strings in the dictionary since
- * uncompressible data is probably not useful. This function is used
- * only for the level=0 compression option.
- * NOTE: this function should be optimized to avoid extra copying from
- * window to pending_buf.
- */
-function deflate_stored(s, flush) {
- /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
- * to pending_buf_size, and each stored block has a 5 byte header:
- */
- var max_block_size = 0xffff;
-
- if (max_block_size > s.pending_buf_size - 5) {
- max_block_size = s.pending_buf_size - 5;
- }
-
- /* Copy as much as possible from input to output: */
- for (;;) {
- /* Fill the window as much as possible: */
- if (s.lookahead <= 1) {
-
- //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
- // s->block_start >= (long)s->w_size, "slide too late");
-// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
-// s.block_start >= s.w_size)) {
-// throw new Error("slide too late");
-// }
-
- fill_window(s);
- if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
- return BS_NEED_MORE;
- }
-
- if (s.lookahead === 0) {
- break;
- }
- /* flush the current block */
- }
- //Assert(s->block_start >= 0L, "block gone");
-// if (s.block_start < 0) throw new Error("block gone");
-
- s.strstart += s.lookahead;
- s.lookahead = 0;
-
- /* Emit a stored block if pending_buf will be full: */
- var max_start = s.block_start + max_block_size;
-
- if (s.strstart === 0 || s.strstart >= max_start) {
- /* strstart == 0 is possible when wraparound on 16-bit machine */
- s.lookahead = s.strstart - max_start;
- s.strstart = max_start;
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
-
-
- }
- /* Flush if we may have to slide, otherwise block_start may become
- * negative and the data will be gone:
- */
- if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- }
-
- s.insert = 0;
-
- if (flush === Z_FINISH) {
- /*** FLUSH_BLOCK(s, 1); ***/
- flush_block_only(s, true);
- if (s.strm.avail_out === 0) {
- return BS_FINISH_STARTED;
- }
- /***/
- return BS_FINISH_DONE;
- }
-
- if (s.strstart > s.block_start) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
-
- return BS_NEED_MORE;
-}
-
-/* ===========================================================================
- * Compress as much as possible from the input stream, return the current
- * block state.
- * This function does not perform lazy evaluation of matches and inserts
- * new strings in the dictionary only for unmatched strings or for short
- * matches. It is used only for the fast compression options.
- */
-function deflate_fast(s, flush) {
- var hash_head; /* head of the hash chain */
- var bflush; /* set if current block must be flushed */
-
- for (;;) {
- /* Make sure that we always have enough lookahead, except
- * at the end of the input file. We need MAX_MATCH bytes
- * for the next match, plus MIN_MATCH bytes to insert the
- * string following the next match.
- */
- if (s.lookahead < MIN_LOOKAHEAD) {
- fill_window(s);
- if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
- return BS_NEED_MORE;
- }
- if (s.lookahead === 0) {
- break; /* flush the current block */
- }
- }
-
- /* Insert the string window[strstart .. strstart+2] in the
- * dictionary, and set hash_head to the head of the hash chain:
- */
- hash_head = 0/*NIL*/;
- if (s.lookahead >= MIN_MATCH) {
- /*** INSERT_STRING(s, s.strstart, hash_head); ***/
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
- hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
- s.head[s.ins_h] = s.strstart;
- /***/
- }
-
- /* Find the longest match, discarding those <= prev_length.
- * At this point we have always match_length < MIN_MATCH
- */
- if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
- /* To simplify the code, we prevent matches with the string
- * of window index 0 (in particular we have to avoid a match
- * of the string with itself at the start of the input file).
- */
- s.match_length = longest_match(s, hash_head);
- /* longest_match() sets match_start */
- }
- if (s.match_length >= MIN_MATCH) {
- // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
-
- /*** _tr_tally_dist(s, s.strstart - s.match_start,
- s.match_length - MIN_MATCH, bflush); ***/
- bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
-
- s.lookahead -= s.match_length;
-
- /* Insert new strings in the hash table only if the match length
- * is not too large. This saves time but degrades compression.
- */
- if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
- s.match_length--; /* string at strstart already in table */
- do {
- s.strstart++;
- /*** INSERT_STRING(s, s.strstart, hash_head); ***/
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
- hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
- s.head[s.ins_h] = s.strstart;
- /***/
- /* strstart never exceeds WSIZE-MAX_MATCH, so there are
- * always MIN_MATCH bytes ahead.
- */
- } while (--s.match_length !== 0);
- s.strstart++;
- } else
- {
- s.strstart += s.match_length;
- s.match_length = 0;
- s.ins_h = s.window[s.strstart];
- /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
-
-//#if MIN_MATCH != 3
-// Call UPDATE_HASH() MIN_MATCH-3 more times
-//#endif
- /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
- * matter since it will be recomputed at next deflate call.
- */
- }
- } else {
- /* No match, output a literal byte */
- //Tracevv((stderr,"%c", s.window[s.strstart]));
- /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
- bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
-
- s.lookahead--;
- s.strstart++;
- }
- if (bflush) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- }
- s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
- if (flush === Z_FINISH) {
- /*** FLUSH_BLOCK(s, 1); ***/
- flush_block_only(s, true);
- if (s.strm.avail_out === 0) {
- return BS_FINISH_STARTED;
- }
- /***/
- return BS_FINISH_DONE;
- }
- if (s.last_lit) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- return BS_BLOCK_DONE;
-}
-
-/* ===========================================================================
- * Same as above, but achieves better compression. We use a lazy
- * evaluation for matches: a match is finally adopted only if there is
- * no better match at the next window position.
- */
-function deflate_slow(s, flush) {
- var hash_head; /* head of hash chain */
- var bflush; /* set if current block must be flushed */
-
- var max_insert;
-
- /* Process the input block. */
- for (;;) {
- /* Make sure that we always have enough lookahead, except
- * at the end of the input file. We need MAX_MATCH bytes
- * for the next match, plus MIN_MATCH bytes to insert the
- * string following the next match.
- */
- if (s.lookahead < MIN_LOOKAHEAD) {
- fill_window(s);
- if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
- return BS_NEED_MORE;
- }
- if (s.lookahead === 0) { break; } /* flush the current block */
- }
-
- /* Insert the string window[strstart .. strstart+2] in the
- * dictionary, and set hash_head to the head of the hash chain:
- */
- hash_head = 0/*NIL*/;
- if (s.lookahead >= MIN_MATCH) {
- /*** INSERT_STRING(s, s.strstart, hash_head); ***/
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
- hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
- s.head[s.ins_h] = s.strstart;
- /***/
- }
-
- /* Find the longest match, discarding those <= prev_length.
- */
- s.prev_length = s.match_length;
- s.prev_match = s.match_start;
- s.match_length = MIN_MATCH - 1;
-
- if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
- s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
- /* To simplify the code, we prevent matches with the string
- * of window index 0 (in particular we have to avoid a match
- * of the string with itself at the start of the input file).
- */
- s.match_length = longest_match(s, hash_head);
- /* longest_match() sets match_start */
-
- if (s.match_length <= 5 &&
- (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
-
- /* If prev_match is also MIN_MATCH, match_start is garbage
- * but we will ignore the current match anyway.
- */
- s.match_length = MIN_MATCH - 1;
- }
- }
- /* If there was a match at the previous step and the current
- * match is not better, output the previous match:
- */
- if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
- max_insert = s.strstart + s.lookahead - MIN_MATCH;
- /* Do not insert strings in hash table beyond this. */
-
- //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
-
- /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
- s.prev_length - MIN_MATCH, bflush);***/
- bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
- /* Insert in hash table all strings up to the end of the match.
- * strstart-1 and strstart are already inserted. If there is not
- * enough lookahead, the last two strings are not inserted in
- * the hash table.
- */
- s.lookahead -= s.prev_length - 1;
- s.prev_length -= 2;
- do {
- if (++s.strstart <= max_insert) {
- /*** INSERT_STRING(s, s.strstart, hash_head); ***/
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
- hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
- s.head[s.ins_h] = s.strstart;
- /***/
- }
- } while (--s.prev_length !== 0);
- s.match_available = 0;
- s.match_length = MIN_MATCH - 1;
- s.strstart++;
-
- if (bflush) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
-
- } else if (s.match_available) {
- /* If there was no match at the previous position, output a
- * single literal. If there was a match but the current match
- * is longer, truncate the previous match to a single literal.
- */
- //Tracevv((stderr,"%c", s->window[s->strstart-1]));
- /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
- bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
-
- if (bflush) {
- /*** FLUSH_BLOCK_ONLY(s, 0) ***/
- flush_block_only(s, false);
- /***/
- }
- s.strstart++;
- s.lookahead--;
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- } else {
- /* There is no previous match to compare with, wait for
- * the next step to decide.
- */
- s.match_available = 1;
- s.strstart++;
- s.lookahead--;
- }
- }
- //Assert (flush != Z_NO_FLUSH, "no flush?");
- if (s.match_available) {
- //Tracevv((stderr,"%c", s->window[s->strstart-1]));
- /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
- bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
-
- s.match_available = 0;
- }
- s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
- if (flush === Z_FINISH) {
- /*** FLUSH_BLOCK(s, 1); ***/
- flush_block_only(s, true);
- if (s.strm.avail_out === 0) {
- return BS_FINISH_STARTED;
- }
- /***/
- return BS_FINISH_DONE;
- }
- if (s.last_lit) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
-
- return BS_BLOCK_DONE;
-}
-
-
-/* ===========================================================================
- * For Z_RLE, simply look for runs of bytes, generate matches only of distance
- * one. Do not maintain a hash table. (It will be regenerated if this run of
- * deflate switches away from Z_RLE.)
- */
-function deflate_rle(s, flush) {
- var bflush; /* set if current block must be flushed */
- var prev; /* byte at distance one to match */
- var scan, strend; /* scan goes up to strend for length of run */
-
- var _win = s.window;
-
- for (;;) {
- /* Make sure that we always have enough lookahead, except
- * at the end of the input file. We need MAX_MATCH bytes
- * for the longest run, plus one for the unrolled loop.
- */
- if (s.lookahead <= MAX_MATCH) {
- fill_window(s);
- if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
- return BS_NEED_MORE;
- }
- if (s.lookahead === 0) { break; } /* flush the current block */
- }
-
- /* See how many times the previous byte repeats */
- s.match_length = 0;
- if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
- scan = s.strstart - 1;
- prev = _win[scan];
- if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
- strend = s.strstart + MAX_MATCH;
- do {
- /*jshint noempty:false*/
- } while (prev === _win[++scan] && prev === _win[++scan] &&
- prev === _win[++scan] && prev === _win[++scan] &&
- prev === _win[++scan] && prev === _win[++scan] &&
- prev === _win[++scan] && prev === _win[++scan] &&
- scan < strend);
- s.match_length = MAX_MATCH - (strend - scan);
- if (s.match_length > s.lookahead) {
- s.match_length = s.lookahead;
- }
- }
- //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
- }
-
- /* Emit match if have run of MIN_MATCH or longer, else emit literal */
- if (s.match_length >= MIN_MATCH) {
- //check_match(s, s.strstart, s.strstart - 1, s.match_length);
-
- /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
- bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
-
- s.lookahead -= s.match_length;
- s.strstart += s.match_length;
- s.match_length = 0;
- } else {
- /* No match, output a literal byte */
- //Tracevv((stderr,"%c", s->window[s->strstart]));
- /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
- bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
-
- s.lookahead--;
- s.strstart++;
- }
- if (bflush) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- }
- s.insert = 0;
- if (flush === Z_FINISH) {
- /*** FLUSH_BLOCK(s, 1); ***/
- flush_block_only(s, true);
- if (s.strm.avail_out === 0) {
- return BS_FINISH_STARTED;
- }
- /***/
- return BS_FINISH_DONE;
- }
- if (s.last_lit) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- return BS_BLOCK_DONE;
-}
-
-/* ===========================================================================
- * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
- * (It will be regenerated if this run of deflate switches away from Huffman.)
- */
-function deflate_huff(s, flush) {
- var bflush; /* set if current block must be flushed */
-
- for (;;) {
- /* Make sure that we have a literal to write. */
- if (s.lookahead === 0) {
- fill_window(s);
- if (s.lookahead === 0) {
- if (flush === Z_NO_FLUSH) {
- return BS_NEED_MORE;
- }
- break; /* flush the current block */
- }
- }
-
- /* Output a literal byte */
- s.match_length = 0;
- //Tracevv((stderr,"%c", s->window[s->strstart]));
- /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
- bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
- s.lookahead--;
- s.strstart++;
- if (bflush) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- }
- s.insert = 0;
- if (flush === Z_FINISH) {
- /*** FLUSH_BLOCK(s, 1); ***/
- flush_block_only(s, true);
- if (s.strm.avail_out === 0) {
- return BS_FINISH_STARTED;
- }
- /***/
- return BS_FINISH_DONE;
- }
- if (s.last_lit) {
- /*** FLUSH_BLOCK(s, 0); ***/
- flush_block_only(s, false);
- if (s.strm.avail_out === 0) {
- return BS_NEED_MORE;
- }
- /***/
- }
- return BS_BLOCK_DONE;
-}
-
-/* Values for max_lazy_match, good_match and max_chain_length, depending on
- * the desired pack level (0..9). The values given below have been tuned to
- * exclude worst case performance for pathological files. Better values may be
- * found for specific files.
- */
-function Config(good_length, max_lazy, nice_length, max_chain, func) {
- this.good_length = good_length;
- this.max_lazy = max_lazy;
- this.nice_length = nice_length;
- this.max_chain = max_chain;
- this.func = func;
-}
-
-var configuration_table;
-
-configuration_table = [
- /* good lazy nice chain */
- new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
- new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
- new Config(4, 5, 16, 8, deflate_fast), /* 2 */
- new Config(4, 6, 32, 32, deflate_fast), /* 3 */
-
- new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
- new Config(8, 16, 32, 32, deflate_slow), /* 5 */
- new Config(8, 16, 128, 128, deflate_slow), /* 6 */
- new Config(8, 32, 128, 256, deflate_slow), /* 7 */
- new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
- new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
-];
-
-
-/* ===========================================================================
- * Initialize the "longest match" routines for a new zlib stream
- */
-function lm_init(s) {
- s.window_size = 2 * s.w_size;
-
- /*** CLEAR_HASH(s); ***/
- zero(s.head); // Fill with NIL (= 0);
-
- /* Set the default configuration parameters:
- */
- s.max_lazy_match = configuration_table[s.level].max_lazy;
- s.good_match = configuration_table[s.level].good_length;
- s.nice_match = configuration_table[s.level].nice_length;
- s.max_chain_length = configuration_table[s.level].max_chain;
-
- s.strstart = 0;
- s.block_start = 0;
- s.lookahead = 0;
- s.insert = 0;
- s.match_length = s.prev_length = MIN_MATCH - 1;
- s.match_available = 0;
- s.ins_h = 0;
-}
-
-
-function DeflateState() {
- this.strm = null; /* pointer back to this zlib stream */
- this.status = 0; /* as the name implies */
- this.pending_buf = null; /* output still pending */
- this.pending_buf_size = 0; /* size of pending_buf */
- this.pending_out = 0; /* next pending byte to output to the stream */
- this.pending = 0; /* nb of bytes in the pending buffer */
- this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
- this.gzhead = null; /* gzip header information to write */
- this.gzindex = 0; /* where in extra, name, or comment */
- this.method = Z_DEFLATED; /* can only be DEFLATED */
- this.last_flush = -1; /* value of flush param for previous deflate call */
-
- this.w_size = 0; /* LZ77 window size (32K by default) */
- this.w_bits = 0; /* log2(w_size) (8..16) */
- this.w_mask = 0; /* w_size - 1 */
-
- this.window = null;
- /* Sliding window. Input bytes are read into the second half of the window,
- * and move to the first half later to keep a dictionary of at least wSize
- * bytes. With this organization, matches are limited to a distance of
- * wSize-MAX_MATCH bytes, but this ensures that IO is always
- * performed with a length multiple of the block size.
- */
-
- this.window_size = 0;
- /* Actual size of window: 2*wSize, except when the user input buffer
- * is directly used as sliding window.
- */
-
- this.prev = null;
- /* Link to older string with same hash index. To limit the size of this
- * array to 64K, this link is maintained only for the last 32K strings.
- * An index in this array is thus a window index modulo 32K.
- */
-
- this.head = null; /* Heads of the hash chains or NIL. */
-
- this.ins_h = 0; /* hash index of string to be inserted */
- this.hash_size = 0; /* number of elements in hash table */
- this.hash_bits = 0; /* log2(hash_size) */
- this.hash_mask = 0; /* hash_size-1 */
-
- this.hash_shift = 0;
- /* Number of bits by which ins_h must be shifted at each input
- * step. It must be such that after MIN_MATCH steps, the oldest
- * byte no longer takes part in the hash key, that is:
- * hash_shift * MIN_MATCH >= hash_bits
- */
-
- this.block_start = 0;
- /* Window position at the beginning of the current output block. Gets
- * negative when the window is moved backwards.
- */
-
- this.match_length = 0; /* length of best match */
- this.prev_match = 0; /* previous match */
- this.match_available = 0; /* set if previous match exists */
- this.strstart = 0; /* start of string to insert */
- this.match_start = 0; /* start of matching string */
- this.lookahead = 0; /* number of valid bytes ahead in window */
-
- this.prev_length = 0;
- /* Length of the best match at previous step. Matches not greater than this
- * are discarded. This is used in the lazy match evaluation.
- */
-
- this.max_chain_length = 0;
- /* To speed up deflation, hash chains are never searched beyond this
- * length. A higher limit improves compression ratio but degrades the
- * speed.
- */
-
- this.max_lazy_match = 0;
- /* Attempt to find a better match only when the current match is strictly
- * smaller than this value. This mechanism is used only for compression
- * levels >= 4.
- */
- // That's alias to max_lazy_match, don't use directly
- //this.max_insert_length = 0;
- /* Insert new strings in the hash table only if the match length is not
- * greater than this length. This saves time but degrades compression.
- * max_insert_length is used only for compression levels <= 3.
- */
-
- this.level = 0; /* compression level (1..9) */
- this.strategy = 0; /* favor or force Huffman coding*/
-
- this.good_match = 0;
- /* Use a faster search when the previous match is longer than this */
-
- this.nice_match = 0; /* Stop searching when current match exceeds this */
-
- /* used by trees.c: */
-
- /* Didn't use ct_data typedef below to suppress compiler warning */
-
- // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
- // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
- // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
-
- // Use flat array of DOUBLE size, with interleaved fata,
- // because JS does not support effective
- this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
- this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
- this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
- zero(this.dyn_ltree);
- zero(this.dyn_dtree);
- zero(this.bl_tree);
-
- this.l_desc = null; /* desc. for literal tree */
- this.d_desc = null; /* desc. for distance tree */
- this.bl_desc = null; /* desc. for bit length tree */
-
- //ush bl_count[MAX_BITS+1];
- this.bl_count = new utils.Buf16(MAX_BITS + 1);
- /* number of codes at each bit length for an optimal tree */
-
- //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
- this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
- zero(this.heap);
-
- this.heap_len = 0; /* number of elements in the heap */
- this.heap_max = 0; /* element of largest frequency */
- /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
- * The same heap array is used to build all trees.
- */
-
- this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
- zero(this.depth);
- /* Depth of each subtree used as tie breaker for trees of equal frequency
- */
-
- this.l_buf = 0; /* buffer index for literals or lengths */
-
- this.lit_bufsize = 0;
- /* Size of match buffer for literals/lengths. There are 4 reasons for
- * limiting lit_bufsize to 64K:
- * - frequencies can be kept in 16 bit counters
- * - if compression is not successful for the first block, all input
- * data is still in the window so we can still emit a stored block even
- * when input comes from standard input. (This can also be done for
- * all blocks if lit_bufsize is not greater than 32K.)
- * - if compression is not successful for a file smaller than 64K, we can
- * even emit a stored file instead of a stored block (saving 5 bytes).
- * This is applicable only for zip (not gzip or zlib).
- * - creating new Huffman trees less frequently may not provide fast
- * adaptation to changes in the input data statistics. (Take for
- * example a binary file with poorly compressible code followed by
- * a highly compressible string table.) Smaller buffer sizes give
- * fast adaptation but have of course the overhead of transmitting
- * trees more frequently.
- * - I can't count above 4
- */
-
- this.last_lit = 0; /* running index in l_buf */
-
- this.d_buf = 0;
- /* Buffer index for distances. To simplify the code, d_buf and l_buf have
- * the same number of elements. To use different lengths, an extra flag
- * array would be necessary.
- */
-
- this.opt_len = 0; /* bit length of current block with optimal trees */
- this.static_len = 0; /* bit length of current block with static trees */
- this.matches = 0; /* number of string matches in current block */
- this.insert = 0; /* bytes at end of window left to insert */
-
-
- this.bi_buf = 0;
- /* Output buffer. bits are inserted starting at the bottom (least
- * significant bits).
- */
- this.bi_valid = 0;
- /* Number of valid bits in bi_buf. All bits above the last valid bit
- * are always zero.
- */
-
- // Used for window memory init. We safely ignore it for JS. That makes
- // sense only for pointers and memory check tools.
- //this.high_water = 0;
- /* High water mark offset in window for initialized bytes -- bytes above
- * this are set to zero in order to avoid memory check warnings when
- * longest match routines access bytes past the input. This is then
- * updated to the new high water mark.
- */
-}
-
-
-function deflateResetKeep(strm) {
- var s;
-
- if (!strm || !strm.state) {
- return err(strm, Z_STREAM_ERROR);
- }
-
- strm.total_in = strm.total_out = 0;
- strm.data_type = Z_UNKNOWN;
-
- s = strm.state;
- s.pending = 0;
- s.pending_out = 0;
-
- if (s.wrap < 0) {
- s.wrap = -s.wrap;
- /* was made negative by deflate(..., Z_FINISH); */
- }
- s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
- strm.adler = (s.wrap === 2) ?
- 0 // crc32(0, Z_NULL, 0)
- :
- 1; // adler32(0, Z_NULL, 0)
- s.last_flush = Z_NO_FLUSH;
- trees._tr_init(s);
- return Z_OK;
-}
-
-
-function deflateReset(strm) {
- var ret = deflateResetKeep(strm);
- if (ret === Z_OK) {
- lm_init(strm.state);
- }
- return ret;
-}
-
-
-function deflateSetHeader(strm, head) {
- if (!strm || !strm.state) { return Z_STREAM_ERROR; }
- if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
- strm.state.gzhead = head;
- return Z_OK;
-}
-
-
-function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
- if (!strm) { // === Z_NULL
- return Z_STREAM_ERROR;
- }
- var wrap = 1;
-
- if (level === Z_DEFAULT_COMPRESSION) {
- level = 6;
- }
-
- if (windowBits < 0) { /* suppress zlib wrapper */
- wrap = 0;
- windowBits = -windowBits;
- }
-
- else if (windowBits > 15) {
- wrap = 2; /* write gzip wrapper instead */
- windowBits -= 16;
- }
-
-
- if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
- windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
- strategy < 0 || strategy > Z_FIXED) {
- return err(strm, Z_STREAM_ERROR);
- }
-
-
- if (windowBits === 8) {
- windowBits = 9;
- }
- /* until 256-byte window bug fixed */
-
- var s = new DeflateState();
-
- strm.state = s;
- s.strm = strm;
-
- s.wrap = wrap;
- s.gzhead = null;
- s.w_bits = windowBits;
- s.w_size = 1 << s.w_bits;
- s.w_mask = s.w_size - 1;
-
- s.hash_bits = memLevel + 7;
- s.hash_size = 1 << s.hash_bits;
- s.hash_mask = s.hash_size - 1;
- s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
-
- s.window = new utils.Buf8(s.w_size * 2);
- s.head = new utils.Buf16(s.hash_size);
- s.prev = new utils.Buf16(s.w_size);
-
- // Don't need mem init magic for JS.
- //s.high_water = 0; /* nothing written to s->window yet */
-
- s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
-
- s.pending_buf_size = s.lit_bufsize * 4;
-
- //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
- //s->pending_buf = (uchf *) overlay;
- s.pending_buf = new utils.Buf8(s.pending_buf_size);
-
- // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
- //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
- s.d_buf = 1 * s.lit_bufsize;
-
- //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
- s.l_buf = (1 + 2) * s.lit_bufsize;
-
- s.level = level;
- s.strategy = strategy;
- s.method = method;
-
- return deflateReset(strm);
-}
-
-function deflateInit(strm, level) {
- return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
-}
-
-
-function deflate(strm, flush) {
- var old_flush, s;
- var beg, val; // for gzip header write only
-
- if (!strm || !strm.state ||
- flush > Z_BLOCK || flush < 0) {
- return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
- }
-
- s = strm.state;
-
- if (!strm.output ||
- (!strm.input && strm.avail_in !== 0) ||
- (s.status === FINISH_STATE && flush !== Z_FINISH)) {
- return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
- }
-
- s.strm = strm; /* just in case */
- old_flush = s.last_flush;
- s.last_flush = flush;
-
- /* Write the header */
- if (s.status === INIT_STATE) {
-
- if (s.wrap === 2) { // GZIP header
- strm.adler = 0; //crc32(0L, Z_NULL, 0);
- put_byte(s, 31);
- put_byte(s, 139);
- put_byte(s, 8);
- if (!s.gzhead) { // s->gzhead == Z_NULL
- put_byte(s, 0);
- put_byte(s, 0);
- put_byte(s, 0);
- put_byte(s, 0);
- put_byte(s, 0);
- put_byte(s, s.level === 9 ? 2 :
- (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
- 4 : 0));
- put_byte(s, OS_CODE);
- s.status = BUSY_STATE;
- }
- else {
- put_byte(s, (s.gzhead.text ? 1 : 0) +
- (s.gzhead.hcrc ? 2 : 0) +
- (!s.gzhead.extra ? 0 : 4) +
- (!s.gzhead.name ? 0 : 8) +
- (!s.gzhead.comment ? 0 : 16)
- );
- put_byte(s, s.gzhead.time & 0xff);
- put_byte(s, (s.gzhead.time >> 8) & 0xff);
- put_byte(s, (s.gzhead.time >> 16) & 0xff);
- put_byte(s, (s.gzhead.time >> 24) & 0xff);
- put_byte(s, s.level === 9 ? 2 :
- (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
- 4 : 0));
- put_byte(s, s.gzhead.os & 0xff);
- if (s.gzhead.extra && s.gzhead.extra.length) {
- put_byte(s, s.gzhead.extra.length & 0xff);
- put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
- }
- if (s.gzhead.hcrc) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
- }
- s.gzindex = 0;
- s.status = EXTRA_STATE;
- }
- }
- else // DEFLATE header
- {
- var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
- var level_flags = -1;
-
- if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
- level_flags = 0;
- } else if (s.level < 6) {
- level_flags = 1;
- } else if (s.level === 6) {
- level_flags = 2;
- } else {
- level_flags = 3;
- }
- header |= (level_flags << 6);
- if (s.strstart !== 0) { header |= PRESET_DICT; }
- header += 31 - (header % 31);
-
- s.status = BUSY_STATE;
- putShortMSB(s, header);
-
- /* Save the adler32 of the preset dictionary: */
- if (s.strstart !== 0) {
- putShortMSB(s, strm.adler >>> 16);
- putShortMSB(s, strm.adler & 0xffff);
- }
- strm.adler = 1; // adler32(0L, Z_NULL, 0);
- }
- }
-
-//#ifdef GZIP
- if (s.status === EXTRA_STATE) {
- if (s.gzhead.extra/* != Z_NULL*/) {
- beg = s.pending; /* start of bytes to update crc */
-
- while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
- if (s.pending === s.pending_buf_size) {
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- flush_pending(strm);
- beg = s.pending;
- if (s.pending === s.pending_buf_size) {
- break;
- }
- }
- put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
- s.gzindex++;
- }
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- if (s.gzindex === s.gzhead.extra.length) {
- s.gzindex = 0;
- s.status = NAME_STATE;
- }
- }
- else {
- s.status = NAME_STATE;
- }
- }
- if (s.status === NAME_STATE) {
- if (s.gzhead.name/* != Z_NULL*/) {
- beg = s.pending; /* start of bytes to update crc */
- //int val;
-
- do {
- if (s.pending === s.pending_buf_size) {
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- flush_pending(strm);
- beg = s.pending;
- if (s.pending === s.pending_buf_size) {
- val = 1;
- break;
- }
- }
- // JS specific: little magic to add zero terminator to end of string
- if (s.gzindex < s.gzhead.name.length) {
- val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
- } else {
- val = 0;
- }
- put_byte(s, val);
- } while (val !== 0);
-
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- if (val === 0) {
- s.gzindex = 0;
- s.status = COMMENT_STATE;
- }
- }
- else {
- s.status = COMMENT_STATE;
- }
- }
- if (s.status === COMMENT_STATE) {
- if (s.gzhead.comment/* != Z_NULL*/) {
- beg = s.pending; /* start of bytes to update crc */
- //int val;
-
- do {
- if (s.pending === s.pending_buf_size) {
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- flush_pending(strm);
- beg = s.pending;
- if (s.pending === s.pending_buf_size) {
- val = 1;
- break;
- }
- }
- // JS specific: little magic to add zero terminator to end of string
- if (s.gzindex < s.gzhead.comment.length) {
- val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
- } else {
- val = 0;
- }
- put_byte(s, val);
- } while (val !== 0);
-
- if (s.gzhead.hcrc && s.pending > beg) {
- strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
- }
- if (val === 0) {
- s.status = HCRC_STATE;
- }
- }
- else {
- s.status = HCRC_STATE;
- }
- }
- if (s.status === HCRC_STATE) {
- if (s.gzhead.hcrc) {
- if (s.pending + 2 > s.pending_buf_size) {
- flush_pending(strm);
- }
- if (s.pending + 2 <= s.pending_buf_size) {
- put_byte(s, strm.adler & 0xff);
- put_byte(s, (strm.adler >> 8) & 0xff);
- strm.adler = 0; //crc32(0L, Z_NULL, 0);
- s.status = BUSY_STATE;
- }
- }
- else {
- s.status = BUSY_STATE;
- }
- }
-//#endif
-
- /* Flush as much pending output as possible */
- if (s.pending !== 0) {
- flush_pending(strm);
- if (strm.avail_out === 0) {
- /* Since avail_out is 0, deflate will be called again with
- * more output space, but possibly with both pending and
- * avail_in equal to zero. There won't be anything to do,
- * but this is not an error situation so make sure we
- * return OK instead of BUF_ERROR at next call of deflate:
- */
- s.last_flush = -1;
- return Z_OK;
- }
-
- /* Make sure there is something to do and avoid duplicate consecutive
- * flushes. For repeated and useless calls with Z_FINISH, we keep
- * returning Z_STREAM_END instead of Z_BUF_ERROR.
- */
- } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
- flush !== Z_FINISH) {
- return err(strm, Z_BUF_ERROR);
- }
-
- /* User must not provide more input after the first FINISH: */
- if (s.status === FINISH_STATE && strm.avail_in !== 0) {
- return err(strm, Z_BUF_ERROR);
- }
-
- /* Start a new block or continue the current one.
- */
- if (strm.avail_in !== 0 || s.lookahead !== 0 ||
- (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
- var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
- (s.strategy === Z_RLE ? deflate_rle(s, flush) :
- configuration_table[s.level].func(s, flush));
-
- if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
- s.status = FINISH_STATE;
- }
- if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
- if (strm.avail_out === 0) {
- s.last_flush = -1;
- /* avoid BUF_ERROR next call, see above */
- }
- return Z_OK;
- /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
- * of deflate should use the same flush parameter to make sure
- * that the flush is complete. So we don't have to output an
- * empty block here, this will be done at next call. This also
- * ensures that for a very small output buffer, we emit at most
- * one empty block.
- */
- }
- if (bstate === BS_BLOCK_DONE) {
- if (flush === Z_PARTIAL_FLUSH) {
- trees._tr_align(s);
- }
- else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
-
- trees._tr_stored_block(s, 0, 0, false);
- /* For a full flush, this empty block will be recognized
- * as a special marker by inflate_sync().
- */
- if (flush === Z_FULL_FLUSH) {
- /*** CLEAR_HASH(s); ***/ /* forget history */
- zero(s.head); // Fill with NIL (= 0);
-
- if (s.lookahead === 0) {
- s.strstart = 0;
- s.block_start = 0;
- s.insert = 0;
- }
- }
- }
- flush_pending(strm);
- if (strm.avail_out === 0) {
- s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
- return Z_OK;
- }
- }
- }
- //Assert(strm->avail_out > 0, "bug2");
- //if (strm.avail_out <= 0) { throw new Error("bug2");}
-
- if (flush !== Z_FINISH) { return Z_OK; }
- if (s.wrap <= 0) { return Z_STREAM_END; }
-
- /* Write the trailer */
- if (s.wrap === 2) {
- put_byte(s, strm.adler & 0xff);
- put_byte(s, (strm.adler >> 8) & 0xff);
- put_byte(s, (strm.adler >> 16) & 0xff);
- put_byte(s, (strm.adler >> 24) & 0xff);
- put_byte(s, strm.total_in & 0xff);
- put_byte(s, (strm.total_in >> 8) & 0xff);
- put_byte(s, (strm.total_in >> 16) & 0xff);
- put_byte(s, (strm.total_in >> 24) & 0xff);
- }
- else
- {
- putShortMSB(s, strm.adler >>> 16);
- putShortMSB(s, strm.adler & 0xffff);
- }
-
- flush_pending(strm);
- /* If avail_out is zero, the application will call deflate again
- * to flush the rest.
- */
- if (s.wrap > 0) { s.wrap = -s.wrap; }
- /* write the trailer only once! */
- return s.pending !== 0 ? Z_OK : Z_STREAM_END;
-}
-
-function deflateEnd(strm) {
- var status;
-
- if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
- return Z_STREAM_ERROR;
- }
-
- status = strm.state.status;
- if (status !== INIT_STATE &&
- status !== EXTRA_STATE &&
- status !== NAME_STATE &&
- status !== COMMENT_STATE &&
- status !== HCRC_STATE &&
- status !== BUSY_STATE &&
- status !== FINISH_STATE
- ) {
- return err(strm, Z_STREAM_ERROR);
- }
-
- strm.state = null;
-
- return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
-}
-
-
-/* =========================================================================
- * Initializes the compression dictionary from the given byte
- * sequence without producing any compressed output.
- */
-function deflateSetDictionary(strm, dictionary) {
- var dictLength = dictionary.length;
-
- var s;
- var str, n;
- var wrap;
- var avail;
- var next;
- var input;
- var tmpDict;
-
- if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
- return Z_STREAM_ERROR;
- }
-
- s = strm.state;
- wrap = s.wrap;
-
- if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
- return Z_STREAM_ERROR;
- }
-
- /* when using zlib wrappers, compute Adler-32 for provided dictionary */
- if (wrap === 1) {
- /* adler32(strm->adler, dictionary, dictLength); */
- strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
- }
-
- s.wrap = 0; /* avoid computing Adler-32 in read_buf */
-
- /* if dictionary would fill window, just replace the history */
- if (dictLength >= s.w_size) {
- if (wrap === 0) { /* already empty otherwise */
- /*** CLEAR_HASH(s); ***/
- zero(s.head); // Fill with NIL (= 0);
- s.strstart = 0;
- s.block_start = 0;
- s.insert = 0;
- }
- /* use the tail */
- // dictionary = dictionary.slice(dictLength - s.w_size);
- tmpDict = new utils.Buf8(s.w_size);
- utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
- dictionary = tmpDict;
- dictLength = s.w_size;
- }
- /* insert dictionary into window and hash */
- avail = strm.avail_in;
- next = strm.next_in;
- input = strm.input;
- strm.avail_in = dictLength;
- strm.next_in = 0;
- strm.input = dictionary;
- fill_window(s);
- while (s.lookahead >= MIN_MATCH) {
- str = s.strstart;
- n = s.lookahead - (MIN_MATCH - 1);
- do {
- /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
- s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
-
- s.prev[str & s.w_mask] = s.head[s.ins_h];
-
- s.head[s.ins_h] = str;
- str++;
- } while (--n);
- s.strstart = str;
- s.lookahead = MIN_MATCH - 1;
- fill_window(s);
- }
- s.strstart += s.lookahead;
- s.block_start = s.strstart;
- s.insert = s.lookahead;
- s.lookahead = 0;
- s.match_length = s.prev_length = MIN_MATCH - 1;
- s.match_available = 0;
- strm.next_in = next;
- strm.input = input;
- strm.avail_in = avail;
- s.wrap = wrap;
- return Z_OK;
-}
-
-
-exports.deflateInit = deflateInit;
-exports.deflateInit2 = deflateInit2;
-exports.deflateReset = deflateReset;
-exports.deflateResetKeep = deflateResetKeep;
-exports.deflateSetHeader = deflateSetHeader;
-exports.deflate = deflate;
-exports.deflateEnd = deflateEnd;
-exports.deflateSetDictionary = deflateSetDictionary;
-exports.deflateInfo = 'pako deflate (from Nodeca project)';
-
-/* Not implemented
-exports.deflateBound = deflateBound;
-exports.deflateCopy = deflateCopy;
-exports.deflateParams = deflateParams;
-exports.deflatePending = deflatePending;
-exports.deflatePrime = deflatePrime;
-exports.deflateTune = deflateTune;
-*/
-
-},{"../utils/common":21,"./adler32":22,"./crc32":24,"./messages":29,"./trees":30}],26:[function(require,module,exports){
-'use strict';
-
-// (C) 1995-2013 Jean-loup Gailly and Mark Adler
-// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
-//
-// This software is provided 'as-is', without any express or implied
-// warranty. In no event will the authors be held liable for any damages
-// arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it
-// freely, subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented; you must not
-// claim that you wrote the original software. If you use this software
-// in a product, an acknowledgment in the product documentation would be
-// appreciated but is not required.
-// 2. Altered source versions must be plainly marked as such, and must not be
-// misrepresented as being the original software.
-// 3. This notice may not be removed or altered from any source distribution.
-
-// See state defs from inflate.js
-var BAD = 30; /* got a data error -- remain here until reset */
-var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
-
-/*
- Decode literal, length, and distance codes and write out the resulting
- literal and match bytes until either not enough input or output is
- available, an end-of-block is encountered, or a data error is encountered.
- When large enough input and output buffers are supplied to inflate(), for
- example, a 16K input buffer and a 64K output buffer, more than 95% of the
- inflate execution time is spent in this routine.
-
- Entry assumptions:
-
- state.mode === LEN
- strm.avail_in >= 6
- strm.avail_out >= 258
- start >= strm.avail_out
- state.bits < 8
-
- On return, state.mode is one of:
-
- LEN -- ran out of enough output space or enough available input
- TYPE -- reached end of block code, inflate() to interpret next block
- BAD -- error in block data
-
- Notes:
-
- - The maximum input bits used by a length/distance pair is 15 bits for the
- length code, 5 bits for the length extra, 15 bits for the distance code,
- and 13 bits for the distance extra. This totals 48 bits, or six bytes.
- Therefore if strm.avail_in >= 6, then there is enough input to avoid
- checking for available input while decoding.
-
- - The maximum bytes that a single length/distance pair can output is 258
- bytes, which is the maximum length that can be coded. inflate_fast()
- requires strm.avail_out >= 258 for each loop to avoid checking for
- output space.
- */
-module.exports = function inflate_fast(strm, start) {
- var state;
- var _in; /* local strm.input */
- var last; /* have enough input while in < last */
- var _out; /* local strm.output */
- var beg; /* inflate()'s initial strm.output */
- var end; /* while out < end, enough space available */
-//#ifdef INFLATE_STRICT
- var dmax; /* maximum distance from zlib header */
-//#endif
- var wsize; /* window size or zero if not using window */
- var whave; /* valid bytes in the window */
- var wnext; /* window write index */
- // Use `s_window` instead `window`, avoid conflict with instrumentation tools
- var s_window; /* allocated sliding window, if wsize != 0 */
- var hold; /* local strm.hold */
- var bits; /* local strm.bits */
- var lcode; /* local strm.lencode */
- var dcode; /* local strm.distcode */
- var lmask; /* mask for first level of length codes */
- var dmask; /* mask for first level of distance codes */
- var here; /* retrieved table entry */
- var op; /* code bits, operation, extra bits, or */
- /* window position, window bytes to copy */
- var len; /* match length, unused bytes */
- var dist; /* match distance */
- var from; /* where to copy match from */
- var from_source;
-
-
- var input, output; // JS specific, because we have no pointers
-
- /* copy state to local variables */
- state = strm.state;
- //here = state.here;
- _in = strm.next_in;
- input = strm.input;
- last = _in + (strm.avail_in - 5);
- _out = strm.next_out;
- output = strm.output;
- beg = _out - (start - strm.avail_out);
- end = _out + (strm.avail_out - 257);
-//#ifdef INFLATE_STRICT
- dmax = state.dmax;
-//#endif
- wsize = state.wsize;
- whave = state.whave;
- wnext = state.wnext;
- s_window = state.window;
- hold = state.hold;
- bits = state.bits;
- lcode = state.lencode;
- dcode = state.distcode;
- lmask = (1 << state.lenbits) - 1;
- dmask = (1 << state.distbits) - 1;
-
-
- /* decode literals and length/distances until end-of-block or not enough
- input data or output space */
-
- top:
- do {
- if (bits < 15) {
- hold += input[_in++] << bits;
- bits += 8;
- hold += input[_in++] << bits;
- bits += 8;
- }
-
- here = lcode[hold & lmask];
-
- dolen:
- for (;;) { // Goto emulation
- op = here >>> 24/*here.bits*/;
- hold >>>= op;
- bits -= op;
- op = (here >>> 16) & 0xff/*here.op*/;
- if (op === 0) { /* literal */
- //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
- // "inflate: literal '%c'\n" :
- // "inflate: literal 0x%02x\n", here.val));
- output[_out++] = here & 0xffff/*here.val*/;
- }
- else if (op & 16) { /* length base */
- len = here & 0xffff/*here.val*/;
- op &= 15; /* number of extra bits */
- if (op) {
- if (bits < op) {
- hold += input[_in++] << bits;
- bits += 8;
- }
- len += hold & ((1 << op) - 1);
- hold >>>= op;
- bits -= op;
- }
- //Tracevv((stderr, "inflate: length %u\n", len));
- if (bits < 15) {
- hold += input[_in++] << bits;
- bits += 8;
- hold += input[_in++] << bits;
- bits += 8;
- }
- here = dcode[hold & dmask];
-
- dodist:
- for (;;) { // goto emulation
- op = here >>> 24/*here.bits*/;
- hold >>>= op;
- bits -= op;
- op = (here >>> 16) & 0xff/*here.op*/;
-
- if (op & 16) { /* distance base */
- dist = here & 0xffff/*here.val*/;
- op &= 15; /* number of extra bits */
- if (bits < op) {
- hold += input[_in++] << bits;
- bits += 8;
- if (bits < op) {
- hold += input[_in++] << bits;
- bits += 8;
- }
- }
- dist += hold & ((1 << op) - 1);
-//#ifdef INFLATE_STRICT
- if (dist > dmax) {
- strm.msg = 'invalid distance too far back';
- state.mode = BAD;
- break top;
- }
-//#endif
- hold >>>= op;
- bits -= op;
- //Tracevv((stderr, "inflate: distance %u\n", dist));
- op = _out - beg; /* max distance in output */
- if (dist > op) { /* see if copy from window */
- op = dist - op; /* distance back in window */
- if (op > whave) {
- if (state.sane) {
- strm.msg = 'invalid distance too far back';
- state.mode = BAD;
- break top;
- }
-
-// (!) This block is disabled in zlib defaults,
-// don't enable it for binary compatibility
-//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
-// if (len <= op - whave) {
-// do {
-// output[_out++] = 0;
-// } while (--len);
-// continue top;
-// }
-// len -= op - whave;
-// do {
-// output[_out++] = 0;
-// } while (--op > whave);
-// if (op === 0) {
-// from = _out - dist;
-// do {
-// output[_out++] = output[from++];
-// } while (--len);
-// continue top;
-// }
-//#endif
- }
- from = 0; // window index
- from_source = s_window;
- if (wnext === 0) { /* very common case */
- from += wsize - op;
- if (op < len) { /* some from window */
- len -= op;
- do {
- output[_out++] = s_window[from++];
- } while (--op);
- from = _out - dist; /* rest from output */
- from_source = output;
- }
- }
- else if (wnext < op) { /* wrap around window */
- from += wsize + wnext - op;
- op -= wnext;
- if (op < len) { /* some from end of window */
- len -= op;
- do {
- output[_out++] = s_window[from++];
- } while (--op);
- from = 0;
- if (wnext < len) { /* some from start of window */
- op = wnext;
- len -= op;
- do {
- output[_out++] = s_window[from++];
- } while (--op);
- from = _out - dist; /* rest from output */
- from_source = output;
- }
- }
- }
- else { /* contiguous in window */
- from += wnext - op;
- if (op < len) { /* some from window */
- len -= op;
- do {
- output[_out++] = s_window[from++];
- } while (--op);
- from = _out - dist; /* rest from output */
- from_source = output;
- }
- }
- while (len > 2) {
- output[_out++] = from_source[from++];
- output[_out++] = from_source[from++];
- output[_out++] = from_source[from++];
- len -= 3;
- }
- if (len) {
- output[_out++] = from_source[from++];
- if (len > 1) {
- output[_out++] = from_source[from++];
- }
- }
- }
- else {
- from = _out - dist; /* copy direct from output */
- do { /* minimum length is three */
- output[_out++] = output[from++];
- output[_out++] = output[from++];
- output[_out++] = output[from++];
- len -= 3;
- } while (len > 2);
- if (len) {
- output[_out++] = output[from++];
- if (len > 1) {
- output[_out++] = output[from++];
- }
- }
- }
- }
- else if ((op & 64) === 0) { /* 2nd level distance code */
- here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
- continue dodist;
- }
- else {
- strm.msg = 'invalid distance code';
- state.mode = BAD;
- break top;
- }
-
- break; // need to emulate goto via "continue"
- }
- }
- else if ((op & 64) === 0) { /* 2nd level length code */
- here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
- continue dolen;
- }
- else if (op & 32) { /* end-of-block */
- //Tracevv((stderr, "inflate: end of block\n"));
- state.mode = TYPE;
- break top;
- }
- else {
- strm.msg = 'invalid literal/length code';
- state.mode = BAD;
- break top;
- }
-
- break; // need to emulate goto via "continue"
- }
- } while (_in < last && _out < end);
-
- /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
- len = bits >> 3;
- _in -= len;
- bits -= len << 3;
- hold &= (1 << bits) - 1;
-
- /* update state and return */
- strm.next_in = _in;
- strm.next_out = _out;
- strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
- strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
- state.hold = hold;
- state.bits = bits;
- return;
-};
-
-},{}],27:[function(require,module,exports){
-'use strict';
-
-// (C) 1995-2013 Jean-loup Gailly and Mark Adler
-// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
-//
-// This software is provided 'as-is', without any express or implied
-// warranty. In no event will the authors be held liable for any damages
-// arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it
-// freely, subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented; you must not
-// claim that you wrote the original software. If you use this software
-// in a product, an acknowledgment in the product documentation would be
-// appreciated but is not required.
-// 2. Altered source versions must be plainly marked as such, and must not be
-// misrepresented as being the original software.
-// 3. This notice may not be removed or altered from any source distribution.
-
-var utils = require('../utils/common');
-var adler32 = require('./adler32');
-var crc32 = require('./crc32');
-var inflate_fast = require('./inffast');
-var inflate_table = require('./inftrees');
-
-var CODES = 0;
-var LENS = 1;
-var DISTS = 2;
-
-/* Public constants ==========================================================*/
-/* ===========================================================================*/
-
-
-/* Allowed flush values; see deflate() and inflate() below for details */
-//var Z_NO_FLUSH = 0;
-//var Z_PARTIAL_FLUSH = 1;
-//var Z_SYNC_FLUSH = 2;
-//var Z_FULL_FLUSH = 3;
-var Z_FINISH = 4;
-var Z_BLOCK = 5;
-var Z_TREES = 6;
-
-
-/* Return codes for the compression/decompression functions. Negative values
- * are errors, positive values are used for special but normal events.
- */
-var Z_OK = 0;
-var Z_STREAM_END = 1;
-var Z_NEED_DICT = 2;
-//var Z_ERRNO = -1;
-var Z_STREAM_ERROR = -2;
-var Z_DATA_ERROR = -3;
-var Z_MEM_ERROR = -4;
-var Z_BUF_ERROR = -5;
-//var Z_VERSION_ERROR = -6;
-
-/* The deflate compression method */
-var Z_DEFLATED = 8;
-
-
-/* STATES ====================================================================*/
-/* ===========================================================================*/
-
-
-var HEAD = 1; /* i: waiting for magic header */
-var FLAGS = 2; /* i: waiting for method and flags (gzip) */
-var TIME = 3; /* i: waiting for modification time (gzip) */
-var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
-var EXLEN = 5; /* i: waiting for extra length (gzip) */
-var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
-var NAME = 7; /* i: waiting for end of file name (gzip) */
-var COMMENT = 8; /* i: waiting for end of comment (gzip) */
-var HCRC = 9; /* i: waiting for header crc (gzip) */
-var DICTID = 10; /* i: waiting for dictionary check value */
-var DICT = 11; /* waiting for inflateSetDictionary() call */
-var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
-var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
-var STORED = 14; /* i: waiting for stored size (length and complement) */
-var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
-var COPY = 16; /* i/o: waiting for input or output to copy stored block */
-var TABLE = 17; /* i: waiting for dynamic block table lengths */
-var LENLENS = 18; /* i: waiting for code length code lengths */
-var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
-var LEN_ = 20; /* i: same as LEN below, but only first time in */
-var LEN = 21; /* i: waiting for length/lit/eob code */
-var LENEXT = 22; /* i: waiting for length extra bits */
-var DIST = 23; /* i: waiting for distance code */
-var DISTEXT = 24; /* i: waiting for distance extra bits */
-var MATCH = 25; /* o: waiting for output space to copy string */
-var LIT = 26; /* o: waiting for output space to write literal */
-var CHECK = 27; /* i: waiting for 32-bit check value */
-var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
-var DONE = 29; /* finished check, done -- remain here until reset */
-var BAD = 30; /* got a data error -- remain here until reset */
-var MEM = 31; /* got an inflate() memory error -- remain here until reset */
-var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
-
-/* ===========================================================================*/
-
-
-
-var ENOUGH_LENS = 852;
-var ENOUGH_DISTS = 592;
-//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
-
-var MAX_WBITS = 15;
-/* 32K LZ77 window */
-var DEF_WBITS = MAX_WBITS;
-
-
-function zswap32(q) {
- return (((q >>> 24) & 0xff) +
- ((q >>> 8) & 0xff00) +
- ((q & 0xff00) << 8) +
- ((q & 0xff) << 24));
-}
-
-
-function InflateState() {
- this.mode = 0; /* current inflate mode */
- this.last = false; /* true if processing last block */
- this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
- this.havedict = false; /* true if dictionary provided */
- this.flags = 0; /* gzip header method and flags (0 if zlib) */
- this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
- this.check = 0; /* protected copy of check value */
- this.total = 0; /* protected copy of output count */
- // TODO: may be {}
- this.head = null; /* where to save gzip header information */
-
- /* sliding window */
- this.wbits = 0; /* log base 2 of requested window size */
- this.wsize = 0; /* window size or zero if not using window */
- this.whave = 0; /* valid bytes in the window */
- this.wnext = 0; /* window write index */
- this.window = null; /* allocated sliding window, if needed */
-
- /* bit accumulator */
- this.hold = 0; /* input bit accumulator */
- this.bits = 0; /* number of bits in "in" */
-
- /* for string and stored block copying */
- this.length = 0; /* literal or length of data to copy */
- this.offset = 0; /* distance back to copy string from */
-
- /* for table and code decoding */
- this.extra = 0; /* extra bits needed */
-
- /* fixed and dynamic code tables */
- this.lencode = null; /* starting table for length/literal codes */
- this.distcode = null; /* starting table for distance codes */
- this.lenbits = 0; /* index bits for lencode */
- this.distbits = 0; /* index bits for distcode */
-
- /* dynamic table building */
- this.ncode = 0; /* number of code length code lengths */
- this.nlen = 0; /* number of length code lengths */
- this.ndist = 0; /* number of distance code lengths */
- this.have = 0; /* number of code lengths in lens[] */
- this.next = null; /* next available space in codes[] */
-
- this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
- this.work = new utils.Buf16(288); /* work area for code table building */
-
- /*
- because we don't have pointers in js, we use lencode and distcode directly
- as buffers so we don't need codes
- */
- //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
- this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
- this.distdyn = null; /* dynamic table for distance codes (JS specific) */
- this.sane = 0; /* if false, allow invalid distance too far */
- this.back = 0; /* bits back of last unprocessed length/lit */
- this.was = 0; /* initial length of match */
-}
-
-function inflateResetKeep(strm) {
- var state;
-
- if (!strm || !strm.state) { return Z_STREAM_ERROR; }
- state = strm.state;
- strm.total_in = strm.total_out = state.total = 0;
- strm.msg = ''; /*Z_NULL*/
- if (state.wrap) { /* to support ill-conceived Java test suite */
- strm.adler = state.wrap & 1;
- }
- state.mode = HEAD;
- state.last = 0;
- state.havedict = 0;
- state.dmax = 32768;
- state.head = null/*Z_NULL*/;
- state.hold = 0;
- state.bits = 0;
- //state.lencode = state.distcode = state.next = state.codes;
- state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
- state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
-
- state.sane = 1;
- state.back = -1;
- //Tracev((stderr, "inflate: reset\n"));
- return Z_OK;
-}
-
-function inflateReset(strm) {
- var state;
-
- if (!strm || !strm.state) { return Z_STREAM_ERROR; }
- state = strm.state;
- state.wsize = 0;
- state.whave = 0;
- state.wnext = 0;
- return inflateResetKeep(strm);
-
-}
-
-function inflateReset2(strm, windowBits) {
- var wrap;
- var state;
-
- /* get the state */
- if (!strm || !strm.state) { return Z_STREAM_ERROR; }
- state = strm.state;
-
- /* extract wrap request from windowBits parameter */
- if (windowBits < 0) {
- wrap = 0;
- windowBits = -windowBits;
- }
- else {
- wrap = (windowBits >> 4) + 1;
- if (windowBits < 48) {
- windowBits &= 15;
- }
- }
-
- /* set number of window bits, free window if different */
- if (windowBits && (windowBits < 8 || windowBits > 15)) {
- return Z_STREAM_ERROR;
- }
- if (state.window !== null && state.wbits !== windowBits) {
- state.window = null;
- }
-
- /* update state and reset the rest of it */
- state.wrap = wrap;
- state.wbits = windowBits;
- return inflateReset(strm);
-}
-
-function inflateInit2(strm, windowBits) {
- var ret;
- var state;
-
- if (!strm) { return Z_STREAM_ERROR; }
- //strm.msg = Z_NULL; /* in case we return an error */
-
- state = new InflateState();
-
- //if (state === Z_NULL) return Z_MEM_ERROR;
- //Tracev((stderr, "inflate: allocated\n"));
- strm.state = state;
- state.window = null/*Z_NULL*/;
- ret = inflateReset2(strm, windowBits);
- if (ret !== Z_OK) {
- strm.state = null/*Z_NULL*/;
- }
- return ret;
-}
-
-function inflateInit(strm) {
- return inflateInit2(strm, DEF_WBITS);
-}
-
-
-/*
- Return state with length and distance decoding tables and index sizes set to
- fixed code decoding. Normally this returns fixed tables from inffixed.h.
- If BUILDFIXED is defined, then instead this routine builds the tables the
- first time it's called, and returns those tables the first time and
- thereafter. This reduces the size of the code by about 2K bytes, in
- exchange for a little execution time. However, BUILDFIXED should not be
- used for threaded applications, since the rewriting of the tables and virgin
- may not be thread-safe.
- */
-var virgin = true;
-
-var lenfix, distfix; // We have no pointers in JS, so keep tables separate
-
-function fixedtables(state) {
- /* build fixed huffman tables if first call (may not be thread safe) */
- if (virgin) {
- var sym;
-
- lenfix = new utils.Buf32(512);
- distfix = new utils.Buf32(32);
-
- /* literal/length table */
- sym = 0;
- while (sym < 144) { state.lens[sym++] = 8; }
- while (sym < 256) { state.lens[sym++] = 9; }
- while (sym < 280) { state.lens[sym++] = 7; }
- while (sym < 288) { state.lens[sym++] = 8; }
-
- inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
-
- /* distance table */
- sym = 0;
- while (sym < 32) { state.lens[sym++] = 5; }
-
- inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
-
- /* do this just once */
- virgin = false;
- }
-
- state.lencode = lenfix;
- state.lenbits = 9;
- state.distcode = distfix;
- state.distbits = 5;
-}
-
-
-/*
- Update the window with the last wsize (normally 32K) bytes written before
- returning. If window does not exist yet, create it. This is only called
- when a window is already in use, or when output has been written during this
- inflate call, but the end of the deflate stream has not been reached yet.
- It is also called to create a window for dictionary data when a dictionary
- is loaded.
-
- Providing output buffers larger than 32K to inflate() should provide a speed
- advantage, since only the last 32K of output is copied to the sliding window
- upon return from inflate(), and since all distances after the first 32K of
- output will fall in the output data, making match copies simpler and faster.
- The advantage may be dependent on the size of the processor's data caches.
- */
-function updatewindow(strm, src, end, copy) {
- var dist;
- var state = strm.state;
-
- /* if it hasn't been done already, allocate space for the window */
- if (state.window === null) {
- state.wsize = 1 << state.wbits;
- state.wnext = 0;
- state.whave = 0;
-
- state.window = new utils.Buf8(state.wsize);
- }
-
- /* copy state->wsize or less output bytes into the circular window */
- if (copy >= state.wsize) {
- utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
- state.wnext = 0;
- state.whave = state.wsize;
- }
- else {
- dist = state.wsize - state.wnext;
- if (dist > copy) {
- dist = copy;
- }
- //zmemcpy(state->window + state->wnext, end - copy, dist);
- utils.arraySet(state.window, src, end - copy, dist, state.wnext);
- copy -= dist;
- if (copy) {
- //zmemcpy(state->window, end - copy, copy);
- utils.arraySet(state.window, src, end - copy, copy, 0);
- state.wnext = copy;
- state.whave = state.wsize;
- }
- else {
- state.wnext += dist;
- if (state.wnext === state.wsize) { state.wnext = 0; }
- if (state.whave < state.wsize) { state.whave += dist; }
- }
- }
- return 0;
-}
-
-function inflate(strm, flush) {
- var state;
- var input, output; // input/output buffers
- var next; /* next input INDEX */
- var put; /* next output INDEX */
- var have, left; /* available input and output */
- var hold; /* bit buffer */
- var bits; /* bits in bit buffer */
- var _in, _out; /* save starting available input and output */
- var copy; /* number of stored or match bytes to copy */
- var from; /* where to copy match bytes from */
- var from_source;
- var here = 0; /* current decoding table entry */
- var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
- //var last; /* parent table entry */
- var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
- var len; /* length to copy for repeats, bits to drop */
- var ret; /* return code */
- var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
- var opts;
-
- var n; // temporary var for NEED_BITS
-
- var order = /* permutation of code lengths */
- [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
-
-
- if (!strm || !strm.state || !strm.output ||
- (!strm.input && strm.avail_in !== 0)) {
- return Z_STREAM_ERROR;
- }
-
- state = strm.state;
- if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
-
-
- //--- LOAD() ---
- put = strm.next_out;
- output = strm.output;
- left = strm.avail_out;
- next = strm.next_in;
- input = strm.input;
- have = strm.avail_in;
- hold = state.hold;
- bits = state.bits;
- //---
-
- _in = have;
- _out = left;
- ret = Z_OK;
-
- inf_leave: // goto emulation
- for (;;) {
- switch (state.mode) {
- case HEAD:
- if (state.wrap === 0) {
- state.mode = TYPEDO;
- break;
- }
- //=== NEEDBITS(16);
- while (bits < 16) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
- state.check = 0/*crc32(0L, Z_NULL, 0)*/;
- //=== CRC2(state.check, hold);
- hbuf[0] = hold & 0xff;
- hbuf[1] = (hold >>> 8) & 0xff;
- state.check = crc32(state.check, hbuf, 2, 0);
- //===//
-
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- state.mode = FLAGS;
- break;
- }
- state.flags = 0; /* expect zlib header */
- if (state.head) {
- state.head.done = false;
- }
- if (!(state.wrap & 1) || /* check if zlib header allowed */
- (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
- strm.msg = 'incorrect header check';
- state.mode = BAD;
- break;
- }
- if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
- strm.msg = 'unknown compression method';
- state.mode = BAD;
- break;
- }
- //--- DROPBITS(4) ---//
- hold >>>= 4;
- bits -= 4;
- //---//
- len = (hold & 0x0f)/*BITS(4)*/ + 8;
- if (state.wbits === 0) {
- state.wbits = len;
- }
- else if (len > state.wbits) {
- strm.msg = 'invalid window size';
- state.mode = BAD;
- break;
- }
- state.dmax = 1 << len;
- //Tracev((stderr, "inflate: zlib header ok\n"));
- strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
- state.mode = hold & 0x200 ? DICTID : TYPE;
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- break;
- case FLAGS:
- //=== NEEDBITS(16); */
- while (bits < 16) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- state.flags = hold;
- if ((state.flags & 0xff) !== Z_DEFLATED) {
- strm.msg = 'unknown compression method';
- state.mode = BAD;
- break;
- }
- if (state.flags & 0xe000) {
- strm.msg = 'unknown header flags set';
- state.mode = BAD;
- break;
- }
- if (state.head) {
- state.head.text = ((hold >> 8) & 1);
- }
- if (state.flags & 0x0200) {
- //=== CRC2(state.check, hold);
- hbuf[0] = hold & 0xff;
- hbuf[1] = (hold >>> 8) & 0xff;
- state.check = crc32(state.check, hbuf, 2, 0);
- //===//
- }
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- state.mode = TIME;
- /* falls through */
- case TIME:
- //=== NEEDBITS(32); */
- while (bits < 32) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- if (state.head) {
- state.head.time = hold;
- }
- if (state.flags & 0x0200) {
- //=== CRC4(state.check, hold)
- hbuf[0] = hold & 0xff;
- hbuf[1] = (hold >>> 8) & 0xff;
- hbuf[2] = (hold >>> 16) & 0xff;
- hbuf[3] = (hold >>> 24) & 0xff;
- state.check = crc32(state.check, hbuf, 4, 0);
- //===
- }
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- state.mode = OS;
- /* falls through */
- case OS:
- //=== NEEDBITS(16); */
- while (bits < 16) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- if (state.head) {
- state.head.xflags = (hold & 0xff);
- state.head.os = (hold >> 8);
- }
- if (state.flags & 0x0200) {
- //=== CRC2(state.check, hold);
- hbuf[0] = hold & 0xff;
- hbuf[1] = (hold >>> 8) & 0xff;
- state.check = crc32(state.check, hbuf, 2, 0);
- //===//
- }
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- state.mode = EXLEN;
- /* falls through */
- case EXLEN:
- if (state.flags & 0x0400) {
- //=== NEEDBITS(16); */
- while (bits < 16) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- state.length = hold;
- if (state.head) {
- state.head.extra_len = hold;
- }
- if (state.flags & 0x0200) {
- //=== CRC2(state.check, hold);
- hbuf[0] = hold & 0xff;
- hbuf[1] = (hold >>> 8) & 0xff;
- state.check = crc32(state.check, hbuf, 2, 0);
- //===//
- }
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- }
- else if (state.head) {
- state.head.extra = null/*Z_NULL*/;
- }
- state.mode = EXTRA;
- /* falls through */
- case EXTRA:
- if (state.flags & 0x0400) {
- copy = state.length;
- if (copy > have) { copy = have; }
- if (copy) {
- if (state.head) {
- len = state.head.extra_len - state.length;
- if (!state.head.extra) {
- // Use untyped array for more convenient processing later
- state.head.extra = new Array(state.head.extra_len);
- }
- utils.arraySet(
- state.head.extra,
- input,
- next,
- // extra field is limited to 65536 bytes
- // - no need for additional size check
- copy,
- /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
- len
- );
- //zmemcpy(state.head.extra + len, next,
- // len + copy > state.head.extra_max ?
- // state.head.extra_max - len : copy);
- }
- if (state.flags & 0x0200) {
- state.check = crc32(state.check, input, copy, next);
- }
- have -= copy;
- next += copy;
- state.length -= copy;
- }
- if (state.length) { break inf_leave; }
- }
- state.length = 0;
- state.mode = NAME;
- /* falls through */
- case NAME:
- if (state.flags & 0x0800) {
- if (have === 0) { break inf_leave; }
- copy = 0;
- do {
- // TODO: 2 or 1 bytes?
- len = input[next + copy++];
- /* use constant limit because in js we should not preallocate memory */
- if (state.head && len &&
- (state.length < 65536 /*state.head.name_max*/)) {
- state.head.name += String.fromCharCode(len);
- }
- } while (len && copy < have);
-
- if (state.flags & 0x0200) {
- state.check = crc32(state.check, input, copy, next);
- }
- have -= copy;
- next += copy;
- if (len) { break inf_leave; }
- }
- else if (state.head) {
- state.head.name = null;
- }
- state.length = 0;
- state.mode = COMMENT;
- /* falls through */
- case COMMENT:
- if (state.flags & 0x1000) {
- if (have === 0) { break inf_leave; }
- copy = 0;
- do {
- len = input[next + copy++];
- /* use constant limit because in js we should not preallocate memory */
- if (state.head && len &&
- (state.length < 65536 /*state.head.comm_max*/)) {
- state.head.comment += String.fromCharCode(len);
- }
- } while (len && copy < have);
- if (state.flags & 0x0200) {
- state.check = crc32(state.check, input, copy, next);
- }
- have -= copy;
- next += copy;
- if (len) { break inf_leave; }
- }
- else if (state.head) {
- state.head.comment = null;
- }
- state.mode = HCRC;
- /* falls through */
- case HCRC:
- if (state.flags & 0x0200) {
- //=== NEEDBITS(16); */
- while (bits < 16) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- if (hold !== (state.check & 0xffff)) {
- strm.msg = 'header crc mismatch';
- state.mode = BAD;
- break;
- }
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- }
- if (state.head) {
- state.head.hcrc = ((state.flags >> 9) & 1);
- state.head.done = true;
- }
- strm.adler = state.check = 0;
- state.mode = TYPE;
- break;
- case DICTID:
- //=== NEEDBITS(32); */
- while (bits < 32) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- strm.adler = state.check = zswap32(hold);
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- state.mode = DICT;
- /* falls through */
- case DICT:
- if (state.havedict === 0) {
- //--- RESTORE() ---
- strm.next_out = put;
- strm.avail_out = left;
- strm.next_in = next;
- strm.avail_in = have;
- state.hold = hold;
- state.bits = bits;
- //---
- return Z_NEED_DICT;
- }
- strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
- state.mode = TYPE;
- /* falls through */
- case TYPE:
- if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
- /* falls through */
- case TYPEDO:
- if (state.last) {
- //--- BYTEBITS() ---//
- hold >>>= bits & 7;
- bits -= bits & 7;
- //---//
- state.mode = CHECK;
- break;
- }
- //=== NEEDBITS(3); */
- while (bits < 3) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- state.last = (hold & 0x01)/*BITS(1)*/;
- //--- DROPBITS(1) ---//
- hold >>>= 1;
- bits -= 1;
- //---//
-
- switch ((hold & 0x03)/*BITS(2)*/) {
- case 0: /* stored block */
- //Tracev((stderr, "inflate: stored block%s\n",
- // state.last ? " (last)" : ""));
- state.mode = STORED;
- break;
- case 1: /* fixed block */
- fixedtables(state);
- //Tracev((stderr, "inflate: fixed codes block%s\n",
- // state.last ? " (last)" : ""));
- state.mode = LEN_; /* decode codes */
- if (flush === Z_TREES) {
- //--- DROPBITS(2) ---//
- hold >>>= 2;
- bits -= 2;
- //---//
- break inf_leave;
- }
- break;
- case 2: /* dynamic block */
- //Tracev((stderr, "inflate: dynamic codes block%s\n",
- // state.last ? " (last)" : ""));
- state.mode = TABLE;
- break;
- case 3:
- strm.msg = 'invalid block type';
- state.mode = BAD;
- }
- //--- DROPBITS(2) ---//
- hold >>>= 2;
- bits -= 2;
- //---//
- break;
- case STORED:
- //--- BYTEBITS() ---// /* go to byte boundary */
- hold >>>= bits & 7;
- bits -= bits & 7;
- //---//
- //=== NEEDBITS(32); */
- while (bits < 32) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
- strm.msg = 'invalid stored block lengths';
- state.mode = BAD;
- break;
- }
- state.length = hold & 0xffff;
- //Tracev((stderr, "inflate: stored length %u\n",
- // state.length));
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- state.mode = COPY_;
- if (flush === Z_TREES) { break inf_leave; }
- /* falls through */
- case COPY_:
- state.mode = COPY;
- /* falls through */
- case COPY:
- copy = state.length;
- if (copy) {
- if (copy > have) { copy = have; }
- if (copy > left) { copy = left; }
- if (copy === 0) { break inf_leave; }
- //--- zmemcpy(put, next, copy); ---
- utils.arraySet(output, input, next, copy, put);
- //---//
- have -= copy;
- next += copy;
- left -= copy;
- put += copy;
- state.length -= copy;
- break;
- }
- //Tracev((stderr, "inflate: stored end\n"));
- state.mode = TYPE;
- break;
- case TABLE:
- //=== NEEDBITS(14); */
- while (bits < 14) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
- //--- DROPBITS(5) ---//
- hold >>>= 5;
- bits -= 5;
- //---//
- state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
- //--- DROPBITS(5) ---//
- hold >>>= 5;
- bits -= 5;
- //---//
- state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
- //--- DROPBITS(4) ---//
- hold >>>= 4;
- bits -= 4;
- //---//
-//#ifndef PKZIP_BUG_WORKAROUND
- if (state.nlen > 286 || state.ndist > 30) {
- strm.msg = 'too many length or distance symbols';
- state.mode = BAD;
- break;
- }
-//#endif
- //Tracev((stderr, "inflate: table sizes ok\n"));
- state.have = 0;
- state.mode = LENLENS;
- /* falls through */
- case LENLENS:
- while (state.have < state.ncode) {
- //=== NEEDBITS(3);
- while (bits < 3) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
- //--- DROPBITS(3) ---//
- hold >>>= 3;
- bits -= 3;
- //---//
- }
- while (state.have < 19) {
- state.lens[order[state.have++]] = 0;
- }
- // We have separate tables & no pointers. 2 commented lines below not needed.
- //state.next = state.codes;
- //state.lencode = state.next;
- // Switch to use dynamic table
- state.lencode = state.lendyn;
- state.lenbits = 7;
-
- opts = { bits: state.lenbits };
- ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
- state.lenbits = opts.bits;
-
- if (ret) {
- strm.msg = 'invalid code lengths set';
- state.mode = BAD;
- break;
- }
- //Tracev((stderr, "inflate: code lengths ok\n"));
- state.have = 0;
- state.mode = CODELENS;
- /* falls through */
- case CODELENS:
- while (state.have < state.nlen + state.ndist) {
- for (;;) {
- here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
- here_bits = here >>> 24;
- here_op = (here >>> 16) & 0xff;
- here_val = here & 0xffff;
-
- if ((here_bits) <= bits) { break; }
- //--- PULLBYTE() ---//
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- //---//
- }
- if (here_val < 16) {
- //--- DROPBITS(here.bits) ---//
- hold >>>= here_bits;
- bits -= here_bits;
- //---//
- state.lens[state.have++] = here_val;
- }
- else {
- if (here_val === 16) {
- //=== NEEDBITS(here.bits + 2);
- n = here_bits + 2;
- while (bits < n) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- //--- DROPBITS(here.bits) ---//
- hold >>>= here_bits;
- bits -= here_bits;
- //---//
- if (state.have === 0) {
- strm.msg = 'invalid bit length repeat';
- state.mode = BAD;
- break;
- }
- len = state.lens[state.have - 1];
- copy = 3 + (hold & 0x03);//BITS(2);
- //--- DROPBITS(2) ---//
- hold >>>= 2;
- bits -= 2;
- //---//
- }
- else if (here_val === 17) {
- //=== NEEDBITS(here.bits + 3);
- n = here_bits + 3;
- while (bits < n) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- //--- DROPBITS(here.bits) ---//
- hold >>>= here_bits;
- bits -= here_bits;
- //---//
- len = 0;
- copy = 3 + (hold & 0x07);//BITS(3);
- //--- DROPBITS(3) ---//
- hold >>>= 3;
- bits -= 3;
- //---//
- }
- else {
- //=== NEEDBITS(here.bits + 7);
- n = here_bits + 7;
- while (bits < n) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- //--- DROPBITS(here.bits) ---//
- hold >>>= here_bits;
- bits -= here_bits;
- //---//
- len = 0;
- copy = 11 + (hold & 0x7f);//BITS(7);
- //--- DROPBITS(7) ---//
- hold >>>= 7;
- bits -= 7;
- //---//
- }
- if (state.have + copy > state.nlen + state.ndist) {
- strm.msg = 'invalid bit length repeat';
- state.mode = BAD;
- break;
- }
- while (copy--) {
- state.lens[state.have++] = len;
- }
- }
- }
-
- /* handle error breaks in while */
- if (state.mode === BAD) { break; }
-
- /* check for end-of-block code (better have one) */
- if (state.lens[256] === 0) {
- strm.msg = 'invalid code -- missing end-of-block';
- state.mode = BAD;
- break;
- }
-
- /* build code tables -- note: do not change the lenbits or distbits
- values here (9 and 6) without reading the comments in inftrees.h
- concerning the ENOUGH constants, which depend on those values */
- state.lenbits = 9;
-
- opts = { bits: state.lenbits };
- ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
- // We have separate tables & no pointers. 2 commented lines below not needed.
- // state.next_index = opts.table_index;
- state.lenbits = opts.bits;
- // state.lencode = state.next;
-
- if (ret) {
- strm.msg = 'invalid literal/lengths set';
- state.mode = BAD;
- break;
- }
-
- state.distbits = 6;
- //state.distcode.copy(state.codes);
- // Switch to use dynamic table
- state.distcode = state.distdyn;
- opts = { bits: state.distbits };
- ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
- // We have separate tables & no pointers. 2 commented lines below not needed.
- // state.next_index = opts.table_index;
- state.distbits = opts.bits;
- // state.distcode = state.next;
-
- if (ret) {
- strm.msg = 'invalid distances set';
- state.mode = BAD;
- break;
- }
- //Tracev((stderr, 'inflate: codes ok\n'));
- state.mode = LEN_;
- if (flush === Z_TREES) { break inf_leave; }
- /* falls through */
- case LEN_:
- state.mode = LEN;
- /* falls through */
- case LEN:
- if (have >= 6 && left >= 258) {
- //--- RESTORE() ---
- strm.next_out = put;
- strm.avail_out = left;
- strm.next_in = next;
- strm.avail_in = have;
- state.hold = hold;
- state.bits = bits;
- //---
- inflate_fast(strm, _out);
- //--- LOAD() ---
- put = strm.next_out;
- output = strm.output;
- left = strm.avail_out;
- next = strm.next_in;
- input = strm.input;
- have = strm.avail_in;
- hold = state.hold;
- bits = state.bits;
- //---
-
- if (state.mode === TYPE) {
- state.back = -1;
- }
- break;
- }
- state.back = 0;
- for (;;) {
- here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
- here_bits = here >>> 24;
- here_op = (here >>> 16) & 0xff;
- here_val = here & 0xffff;
-
- if (here_bits <= bits) { break; }
- //--- PULLBYTE() ---//
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- //---//
- }
- if (here_op && (here_op & 0xf0) === 0) {
- last_bits = here_bits;
- last_op = here_op;
- last_val = here_val;
- for (;;) {
- here = state.lencode[last_val +
- ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
- here_bits = here >>> 24;
- here_op = (here >>> 16) & 0xff;
- here_val = here & 0xffff;
-
- if ((last_bits + here_bits) <= bits) { break; }
- //--- PULLBYTE() ---//
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- //---//
- }
- //--- DROPBITS(last.bits) ---//
- hold >>>= last_bits;
- bits -= last_bits;
- //---//
- state.back += last_bits;
- }
- //--- DROPBITS(here.bits) ---//
- hold >>>= here_bits;
- bits -= here_bits;
- //---//
- state.back += here_bits;
- state.length = here_val;
- if (here_op === 0) {
- //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
- // "inflate: literal '%c'\n" :
- // "inflate: literal 0x%02x\n", here.val));
- state.mode = LIT;
- break;
- }
- if (here_op & 32) {
- //Tracevv((stderr, "inflate: end of block\n"));
- state.back = -1;
- state.mode = TYPE;
- break;
- }
- if (here_op & 64) {
- strm.msg = 'invalid literal/length code';
- state.mode = BAD;
- break;
- }
- state.extra = here_op & 15;
- state.mode = LENEXT;
- /* falls through */
- case LENEXT:
- if (state.extra) {
- //=== NEEDBITS(state.extra);
- n = state.extra;
- while (bits < n) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
- //--- DROPBITS(state.extra) ---//
- hold >>>= state.extra;
- bits -= state.extra;
- //---//
- state.back += state.extra;
- }
- //Tracevv((stderr, "inflate: length %u\n", state.length));
- state.was = state.length;
- state.mode = DIST;
- /* falls through */
- case DIST:
- for (;;) {
- here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
- here_bits = here >>> 24;
- here_op = (here >>> 16) & 0xff;
- here_val = here & 0xffff;
-
- if ((here_bits) <= bits) { break; }
- //--- PULLBYTE() ---//
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- //---//
- }
- if ((here_op & 0xf0) === 0) {
- last_bits = here_bits;
- last_op = here_op;
- last_val = here_val;
- for (;;) {
- here = state.distcode[last_val +
- ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
- here_bits = here >>> 24;
- here_op = (here >>> 16) & 0xff;
- here_val = here & 0xffff;
-
- if ((last_bits + here_bits) <= bits) { break; }
- //--- PULLBYTE() ---//
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- //---//
- }
- //--- DROPBITS(last.bits) ---//
- hold >>>= last_bits;
- bits -= last_bits;
- //---//
- state.back += last_bits;
- }
- //--- DROPBITS(here.bits) ---//
- hold >>>= here_bits;
- bits -= here_bits;
- //---//
- state.back += here_bits;
- if (here_op & 64) {
- strm.msg = 'invalid distance code';
- state.mode = BAD;
- break;
- }
- state.offset = here_val;
- state.extra = (here_op) & 15;
- state.mode = DISTEXT;
- /* falls through */
- case DISTEXT:
- if (state.extra) {
- //=== NEEDBITS(state.extra);
- n = state.extra;
- while (bits < n) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
- //--- DROPBITS(state.extra) ---//
- hold >>>= state.extra;
- bits -= state.extra;
- //---//
- state.back += state.extra;
- }
-//#ifdef INFLATE_STRICT
- if (state.offset > state.dmax) {
- strm.msg = 'invalid distance too far back';
- state.mode = BAD;
- break;
- }
-//#endif
- //Tracevv((stderr, "inflate: distance %u\n", state.offset));
- state.mode = MATCH;
- /* falls through */
- case MATCH:
- if (left === 0) { break inf_leave; }
- copy = _out - left;
- if (state.offset > copy) { /* copy from window */
- copy = state.offset - copy;
- if (copy > state.whave) {
- if (state.sane) {
- strm.msg = 'invalid distance too far back';
- state.mode = BAD;
- break;
- }
-// (!) This block is disabled in zlib defaults,
-// don't enable it for binary compatibility
-//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
-// Trace((stderr, "inflate.c too far\n"));
-// copy -= state.whave;
-// if (copy > state.length) { copy = state.length; }
-// if (copy > left) { copy = left; }
-// left -= copy;
-// state.length -= copy;
-// do {
-// output[put++] = 0;
-// } while (--copy);
-// if (state.length === 0) { state.mode = LEN; }
-// break;
-//#endif
- }
- if (copy > state.wnext) {
- copy -= state.wnext;
- from = state.wsize - copy;
- }
- else {
- from = state.wnext - copy;
- }
- if (copy > state.length) { copy = state.length; }
- from_source = state.window;
- }
- else { /* copy from output */
- from_source = output;
- from = put - state.offset;
- copy = state.length;
- }
- if (copy > left) { copy = left; }
- left -= copy;
- state.length -= copy;
- do {
- output[put++] = from_source[from++];
- } while (--copy);
- if (state.length === 0) { state.mode = LEN; }
- break;
- case LIT:
- if (left === 0) { break inf_leave; }
- output[put++] = state.length;
- left--;
- state.mode = LEN;
- break;
- case CHECK:
- if (state.wrap) {
- //=== NEEDBITS(32);
- while (bits < 32) {
- if (have === 0) { break inf_leave; }
- have--;
- // Use '|' instead of '+' to make sure that result is signed
- hold |= input[next++] << bits;
- bits += 8;
- }
- //===//
- _out -= left;
- strm.total_out += _out;
- state.total += _out;
- if (_out) {
- strm.adler = state.check =
- /*UPDATE(state.check, put - _out, _out);*/
- (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
-
- }
- _out = left;
- // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
- if ((state.flags ? hold : zswap32(hold)) !== state.check) {
- strm.msg = 'incorrect data check';
- state.mode = BAD;
- break;
- }
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- //Tracev((stderr, "inflate: check matches trailer\n"));
- }
- state.mode = LENGTH;
- /* falls through */
- case LENGTH:
- if (state.wrap && state.flags) {
- //=== NEEDBITS(32);
- while (bits < 32) {
- if (have === 0) { break inf_leave; }
- have--;
- hold += input[next++] << bits;
- bits += 8;
- }
- //===//
- if (hold !== (state.total & 0xffffffff)) {
- strm.msg = 'incorrect length check';
- state.mode = BAD;
- break;
- }
- //=== INITBITS();
- hold = 0;
- bits = 0;
- //===//
- //Tracev((stderr, "inflate: length matches trailer\n"));
- }
- state.mode = DONE;
- /* falls through */
- case DONE:
- ret = Z_STREAM_END;
- break inf_leave;
- case BAD:
- ret = Z_DATA_ERROR;
- break inf_leave;
- case MEM:
- return Z_MEM_ERROR;
- case SYNC:
- /* falls through */
- default:
- return Z_STREAM_ERROR;
- }
- }
-
- // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
-
- /*
- Return from inflate(), updating the total counts and the check value.
- If there was no progress during the inflate() call, return a buffer
- error. Call updatewindow() to create and/or update the window state.
- Note: a memory error from inflate() is non-recoverable.
- */
-
- //--- RESTORE() ---
- strm.next_out = put;
- strm.avail_out = left;
- strm.next_in = next;
- strm.avail_in = have;
- state.hold = hold;
- state.bits = bits;
- //---
-
- if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
- (state.mode < CHECK || flush !== Z_FINISH))) {
- if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
- state.mode = MEM;
- return Z_MEM_ERROR;
- }
- }
- _in -= strm.avail_in;
- _out -= strm.avail_out;
- strm.total_in += _in;
- strm.total_out += _out;
- state.total += _out;
- if (state.wrap && _out) {
- strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
- (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
- }
- strm.data_type = state.bits + (state.last ? 64 : 0) +
- (state.mode === TYPE ? 128 : 0) +
- (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
- if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
- ret = Z_BUF_ERROR;
- }
- return ret;
-}
-
-function inflateEnd(strm) {
-
- if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
- return Z_STREAM_ERROR;
- }
-
- var state = strm.state;
- if (state.window) {
- state.window = null;
- }
- strm.state = null;
- return Z_OK;
-}
-
-function inflateGetHeader(strm, head) {
- var state;
-
- /* check state */
- if (!strm || !strm.state) { return Z_STREAM_ERROR; }
- state = strm.state;
- if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
-
- /* save header structure */
- state.head = head;
- head.done = false;
- return Z_OK;
-}
-
-function inflateSetDictionary(strm, dictionary) {
- var dictLength = dictionary.length;
-
- var state;
- var dictid;
- var ret;
-
- /* check state */
- if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
- state = strm.state;
-
- if (state.wrap !== 0 && state.mode !== DICT) {
- return Z_STREAM_ERROR;
- }
-
- /* check for correct dictionary identifier */
- if (state.mode === DICT) {
- dictid = 1; /* adler32(0, null, 0)*/
- /* dictid = adler32(dictid, dictionary, dictLength); */
- dictid = adler32(dictid, dictionary, dictLength, 0);
- if (dictid !== state.check) {
- return Z_DATA_ERROR;
- }
- }
- /* copy dictionary to window using updatewindow(), which will amend the
- existing dictionary if appropriate */
- ret = updatewindow(strm, dictionary, dictLength, dictLength);
- if (ret) {
- state.mode = MEM;
- return Z_MEM_ERROR;
- }
- state.havedict = 1;
- // Tracev((stderr, "inflate: dictionary set\n"));
- return Z_OK;
-}
-
-exports.inflateReset = inflateReset;
-exports.inflateReset2 = inflateReset2;
-exports.inflateResetKeep = inflateResetKeep;
-exports.inflateInit = inflateInit;
-exports.inflateInit2 = inflateInit2;
-exports.inflate = inflate;
-exports.inflateEnd = inflateEnd;
-exports.inflateGetHeader = inflateGetHeader;
-exports.inflateSetDictionary = inflateSetDictionary;
-exports.inflateInfo = 'pako inflate (from Nodeca project)';
-
-/* Not implemented
-exports.inflateCopy = inflateCopy;
-exports.inflateGetDictionary = inflateGetDictionary;
-exports.inflateMark = inflateMark;
-exports.inflatePrime = inflatePrime;
-exports.inflateSync = inflateSync;
-exports.inflateSyncPoint = inflateSyncPoint;
-exports.inflateUndermine = inflateUndermine;
-*/
-
-},{"../utils/common":21,"./adler32":22,"./crc32":24,"./inffast":26,"./inftrees":28}],28:[function(require,module,exports){
-'use strict';
-
-// (C) 1995-2013 Jean-loup Gailly and Mark Adler
-// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
-//
-// This software is provided 'as-is', without any express or implied
-// warranty. In no event will the authors be held liable for any damages
-// arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it
-// freely, subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented; you must not
-// claim that you wrote the original software. If you use this software
-// in a product, an acknowledgment in the product documentation would be
-// appreciated but is not required.
-// 2. Altered source versions must be plainly marked as such, and must not be
-// misrepresented as being the original software.
-// 3. This notice may not be removed or altered from any source distribution.
-
-var utils = require('../utils/common');
-
-var MAXBITS = 15;
-var ENOUGH_LENS = 852;
-var ENOUGH_DISTS = 592;
-//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
-
-var CODES = 0;
-var LENS = 1;
-var DISTS = 2;
-
-var lbase = [ /* Length codes 257..285 base */
- 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
- 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
-];
-
-var lext = [ /* Length codes 257..285 extra */
- 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
- 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
-];
-
-var dbase = [ /* Distance codes 0..29 base */
- 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
- 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
- 8193, 12289, 16385, 24577, 0, 0
-];
-
-var dext = [ /* Distance codes 0..29 extra */
- 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
- 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
- 28, 28, 29, 29, 64, 64
-];
-
-module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
-{
- var bits = opts.bits;
- //here = opts.here; /* table entry for duplication */
-
- var len = 0; /* a code's length in bits */
- var sym = 0; /* index of code symbols */
- var min = 0, max = 0; /* minimum and maximum code lengths */
- var root = 0; /* number of index bits for root table */
- var curr = 0; /* number of index bits for current table */
- var drop = 0; /* code bits to drop for sub-table */
- var left = 0; /* number of prefix codes available */
- var used = 0; /* code entries in table used */
- var huff = 0; /* Huffman code */
- var incr; /* for incrementing code, index */
- var fill; /* index for replicating entries */
- var low; /* low bits for current root entry */
- var mask; /* mask for low root bits */
- var next; /* next available space in table */
- var base = null; /* base value table to use */
- var base_index = 0;
-// var shoextra; /* extra bits table to use */
- var end; /* use base and extra for symbol > end */
- var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
- var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
- var extra = null;
- var extra_index = 0;
-
- var here_bits, here_op, here_val;
-
- /*
- Process a set of code lengths to create a canonical Huffman code. The
- code lengths are lens[0..codes-1]. Each length corresponds to the
- symbols 0..codes-1. The Huffman code is generated by first sorting the
- symbols by length from short to long, and retaining the symbol order
- for codes with equal lengths. Then the code starts with all zero bits
- for the first code of the shortest length, and the codes are integer
- increments for the same length, and zeros are appended as the length
- increases. For the deflate format, these bits are stored backwards
- from their more natural integer increment ordering, and so when the
- decoding tables are built in the large loop below, the integer codes
- are incremented backwards.
-
- This routine assumes, but does not check, that all of the entries in
- lens[] are in the range 0..MAXBITS. The caller must assure this.
- 1..MAXBITS is interpreted as that code length. zero means that that
- symbol does not occur in this code.
-
- The codes are sorted by computing a count of codes for each length,
- creating from that a table of starting indices for each length in the
- sorted table, and then entering the symbols in order in the sorted
- table. The sorted table is work[], with that space being provided by
- the caller.
-
- The length counts are used for other purposes as well, i.e. finding
- the minimum and maximum length codes, determining if there are any
- codes at all, checking for a valid set of lengths, and looking ahead
- at length counts to determine sub-table sizes when building the
- decoding tables.
- */
-
- /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
- for (len = 0; len <= MAXBITS; len++) {
- count[len] = 0;
- }
- for (sym = 0; sym < codes; sym++) {
- count[lens[lens_index + sym]]++;
- }
-
- /* bound code lengths, force root to be within code lengths */
- root = bits;
- for (max = MAXBITS; max >= 1; max--) {
- if (count[max] !== 0) { break; }
- }
- if (root > max) {
- root = max;
- }
- if (max === 0) { /* no symbols to code at all */
- //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
- //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
- //table.val[opts.table_index++] = 0; //here.val = (var short)0;
- table[table_index++] = (1 << 24) | (64 << 16) | 0;
-
-
- //table.op[opts.table_index] = 64;
- //table.bits[opts.table_index] = 1;
- //table.val[opts.table_index++] = 0;
- table[table_index++] = (1 << 24) | (64 << 16) | 0;
-
- opts.bits = 1;
- return 0; /* no symbols, but wait for decoding to report error */
- }
- for (min = 1; min < max; min++) {
- if (count[min] !== 0) { break; }
- }
- if (root < min) {
- root = min;
- }
-
- /* check for an over-subscribed or incomplete set of lengths */
- left = 1;
- for (len = 1; len <= MAXBITS; len++) {
- left <<= 1;
- left -= count[len];
- if (left < 0) {
- return -1;
- } /* over-subscribed */
- }
- if (left > 0 && (type === CODES || max !== 1)) {
- return -1; /* incomplete set */
- }
-
- /* generate offsets into symbol table for each length for sorting */
- offs[1] = 0;
- for (len = 1; len < MAXBITS; len++) {
- offs[len + 1] = offs[len] + count[len];
- }
-
- /* sort symbols by length, by symbol order within each length */
- for (sym = 0; sym < codes; sym++) {
- if (lens[lens_index + sym] !== 0) {
- work[offs[lens[lens_index + sym]]++] = sym;
- }
- }
-
- /*
- Create and fill in decoding tables. In this loop, the table being
- filled is at next and has curr index bits. The code being used is huff
- with length len. That code is converted to an index by dropping drop
- bits off of the bottom. For codes where len is less than drop + curr,
- those top drop + curr - len bits are incremented through all values to
- fill the table with replicated entries.
-
- root is the number of index bits for the root table. When len exceeds
- root, sub-tables are created pointed to by the root entry with an index
- of the low root bits of huff. This is saved in low to check for when a
- new sub-table should be started. drop is zero when the root table is
- being filled, and drop is root when sub-tables are being filled.
-
- When a new sub-table is needed, it is necessary to look ahead in the
- code lengths to determine what size sub-table is needed. The length
- counts are used for this, and so count[] is decremented as codes are
- entered in the tables.
-
- used keeps track of how many table entries have been allocated from the
- provided *table space. It is checked for LENS and DIST tables against
- the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
- the initial root table size constants. See the comments in inftrees.h
- for more information.
-
- sym increments through all symbols, and the loop terminates when
- all codes of length max, i.e. all codes, have been processed. This
- routine permits incomplete codes, so another loop after this one fills
- in the rest of the decoding tables with invalid code markers.
- */
-
- /* set up for code type */
- // poor man optimization - use if-else instead of switch,
- // to avoid deopts in old v8
- if (type === CODES) {
- base = extra = work; /* dummy value--not used */
- end = 19;
-
- } else if (type === LENS) {
- base = lbase;
- base_index -= 257;
- extra = lext;
- extra_index -= 257;
- end = 256;
-
- } else { /* DISTS */
- base = dbase;
- extra = dext;
- end = -1;
- }
-
- /* initialize opts for loop */
- huff = 0; /* starting code */
- sym = 0; /* starting code symbol */
- len = min; /* starting code length */
- next = table_index; /* current table to fill in */
- curr = root; /* current table index bits */
- drop = 0; /* current bits to drop from code for index */
- low = -1; /* trigger new sub-table when len > root */
- used = 1 << root; /* use root table entries */
- mask = used - 1; /* mask for comparing low */
-
- /* check available table space */
- if ((type === LENS && used > ENOUGH_LENS) ||
- (type === DISTS && used > ENOUGH_DISTS)) {
- return 1;
- }
-
- /* process all codes and make table entries */
- for (;;) {
- /* create table entry */
- here_bits = len - drop;
- if (work[sym] < end) {
- here_op = 0;
- here_val = work[sym];
- }
- else if (work[sym] > end) {
- here_op = extra[extra_index + work[sym]];
- here_val = base[base_index + work[sym]];
- }
- else {
- here_op = 32 + 64; /* end of block */
- here_val = 0;
- }
-
- /* replicate for those indices with low len bits equal to huff */
- incr = 1 << (len - drop);
- fill = 1 << curr;
- min = fill; /* save offset to next table */
- do {
- fill -= incr;
- table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
- } while (fill !== 0);
-
- /* backwards increment the len-bit code huff */
- incr = 1 << (len - 1);
- while (huff & incr) {
- incr >>= 1;
- }
- if (incr !== 0) {
- huff &= incr - 1;
- huff += incr;
- } else {
- huff = 0;
- }
-
- /* go to next symbol, update count, len */
- sym++;
- if (--count[len] === 0) {
- if (len === max) { break; }
- len = lens[lens_index + work[sym]];
- }
-
- /* create new sub-table if needed */
- if (len > root && (huff & mask) !== low) {
- /* if first time, transition to sub-tables */
- if (drop === 0) {
- drop = root;
- }
-
- /* increment past last table */
- next += min; /* here min is 1 << curr */
-
- /* determine length of next table */
- curr = len - drop;
- left = 1 << curr;
- while (curr + drop < max) {
- left -= count[curr + drop];
- if (left <= 0) { break; }
- curr++;
- left <<= 1;
- }
-
- /* check for enough space */
- used += 1 << curr;
- if ((type === LENS && used > ENOUGH_LENS) ||
- (type === DISTS && used > ENOUGH_DISTS)) {
- return 1;
- }
-
- /* point entry in root table to sub-table */
- low = huff & mask;
- /*table.op[low] = curr;
- table.bits[low] = root;
- table.val[low] = next - opts.table_index;*/
- table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
- }
- }
-
- /* fill in remaining table entry if code is incomplete (guaranteed to have
- at most one remaining entry, since if the code is incomplete, the
- maximum code length that was allowed to get this far is one bit) */
- if (huff !== 0) {
- //table.op[next + huff] = 64; /* invalid code marker */
- //table.bits[next + huff] = len - drop;
- //table.val[next + huff] = 0;
- table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
- }
-
- /* set return parameters */
- //opts.table_index += used;
- opts.bits = root;
- return 0;
-};
-
-},{"../utils/common":21}],29:[function(require,module,exports){
-'use strict';
-
-// (C) 1995-2013 Jean-loup Gailly and Mark Adler
-// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
-//
-// This software is provided 'as-is', without any express or implied
-// warranty. In no event will the authors be held liable for any damages
-// arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it
-// freely, subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented; you must not
-// claim that you wrote the original software. If you use this software
-// in a product, an acknowledgment in the product documentation would be
-// appreciated but is not required.
-// 2. Altered source versions must be plainly marked as such, and must not be
-// misrepresented as being the original software.
-// 3. This notice may not be removed or altered from any source distribution.
-
-module.exports = {
- 2: 'need dictionary', /* Z_NEED_DICT 2 */
- 1: 'stream end', /* Z_STREAM_END 1 */
- 0: '', /* Z_OK 0 */
- '-1': 'file error', /* Z_ERRNO (-1) */
- '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
- '-3': 'data error', /* Z_DATA_ERROR (-3) */
- '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
- '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
- '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
-};
-
-},{}],30:[function(require,module,exports){
-'use strict';
-
-// (C) 1995-2013 Jean-loup Gailly and Mark Adler
-// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
-//
-// This software is provided 'as-is', without any express or implied
-// warranty. In no event will the authors be held liable for any damages
-// arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it
-// freely, subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented; you must not
-// claim that you wrote the original software. If you use this software
-// in a product, an acknowledgment in the product documentation would be
-// appreciated but is not required.
-// 2. Altered source versions must be plainly marked as such, and must not be
-// misrepresented as being the original software.
-// 3. This notice may not be removed or altered from any source distribution.
-
-/* eslint-disable space-unary-ops */
-
-var utils = require('../utils/common');
-
-/* Public constants ==========================================================*/
-/* ===========================================================================*/
-
-
-//var Z_FILTERED = 1;
-//var Z_HUFFMAN_ONLY = 2;
-//var Z_RLE = 3;
-var Z_FIXED = 4;
-//var Z_DEFAULT_STRATEGY = 0;
-
-/* Possible values of the data_type field (though see inflate()) */
-var Z_BINARY = 0;
-var Z_TEXT = 1;
-//var Z_ASCII = 1; // = Z_TEXT
-var Z_UNKNOWN = 2;
-
-/*============================================================================*/
-
-
-function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
-
-// From zutil.h
-
-var STORED_BLOCK = 0;
-var STATIC_TREES = 1;
-var DYN_TREES = 2;
-/* The three kinds of block type */
-
-var MIN_MATCH = 3;
-var MAX_MATCH = 258;
-/* The minimum and maximum match lengths */
-
-// From deflate.h
-/* ===========================================================================
- * Internal compression state.
- */
-
-var LENGTH_CODES = 29;
-/* number of length codes, not counting the special END_BLOCK code */
-
-var LITERALS = 256;
-/* number of literal bytes 0..255 */
-
-var L_CODES = LITERALS + 1 + LENGTH_CODES;
-/* number of Literal or Length codes, including the END_BLOCK code */
-
-var D_CODES = 30;
-/* number of distance codes */
-
-var BL_CODES = 19;
-/* number of codes used to transfer the bit lengths */
-
-var HEAP_SIZE = 2 * L_CODES + 1;
-/* maximum heap size */
-
-var MAX_BITS = 15;
-/* All codes must not exceed MAX_BITS bits */
-
-var Buf_size = 16;
-/* size of bit buffer in bi_buf */
-
-
-/* ===========================================================================
- * Constants
- */
-
-var MAX_BL_BITS = 7;
-/* Bit length codes must not exceed MAX_BL_BITS bits */
-
-var END_BLOCK = 256;
-/* end of block literal code */
-
-var REP_3_6 = 16;
-/* repeat previous bit length 3-6 times (2 bits of repeat count) */
-
-var REPZ_3_10 = 17;
-/* repeat a zero length 3-10 times (3 bits of repeat count) */
-
-var REPZ_11_138 = 18;
-/* repeat a zero length 11-138 times (7 bits of repeat count) */
-
-/* eslint-disable comma-spacing,array-bracket-spacing */
-var extra_lbits = /* extra bits for each length code */
- [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
-
-var extra_dbits = /* extra bits for each distance code */
- [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
-
-var extra_blbits = /* extra bits for each bit length code */
- [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
-
-var bl_order =
- [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
-/* eslint-enable comma-spacing,array-bracket-spacing */
-
-/* The lengths of the bit length codes are sent in order of decreasing
- * probability, to avoid transmitting the lengths for unused bit length codes.
- */
-
-/* ===========================================================================
- * Local data. These are initialized only once.
- */
-
-// We pre-fill arrays with 0 to avoid uninitialized gaps
-
-var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
-
-// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
-var static_ltree = new Array((L_CODES + 2) * 2);
-zero(static_ltree);
-/* The static literal tree. Since the bit lengths are imposed, there is no
- * need for the L_CODES extra codes used during heap construction. However
- * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
- * below).
- */
-
-var static_dtree = new Array(D_CODES * 2);
-zero(static_dtree);
-/* The static distance tree. (Actually a trivial tree since all codes use
- * 5 bits.)
- */
-
-var _dist_code = new Array(DIST_CODE_LEN);
-zero(_dist_code);
-/* Distance codes. The first 256 values correspond to the distances
- * 3 .. 258, the last 256 values correspond to the top 8 bits of
- * the 15 bit distances.
- */
-
-var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
-zero(_length_code);
-/* length code for each normalized match length (0 == MIN_MATCH) */
-
-var base_length = new Array(LENGTH_CODES);
-zero(base_length);
-/* First normalized length for each code (0 = MIN_MATCH) */
-
-var base_dist = new Array(D_CODES);
-zero(base_dist);
-/* First normalized distance for each code (0 = distance of 1) */
-
-
-function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
-
- this.static_tree = static_tree; /* static tree or NULL */
- this.extra_bits = extra_bits; /* extra bits for each code or NULL */
- this.extra_base = extra_base; /* base index for extra_bits */
- this.elems = elems; /* max number of elements in the tree */
- this.max_length = max_length; /* max bit length for the codes */
-
- // show if `static_tree` has data or dummy - needed for monomorphic objects
- this.has_stree = static_tree && static_tree.length;
-}
-
-
-var static_l_desc;
-var static_d_desc;
-var static_bl_desc;
-
-
-function TreeDesc(dyn_tree, stat_desc) {
- this.dyn_tree = dyn_tree; /* the dynamic tree */
- this.max_code = 0; /* largest code with non zero frequency */
- this.stat_desc = stat_desc; /* the corresponding static tree */
-}
-
-
-
-function d_code(dist) {
- return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
-}
-
-
-/* ===========================================================================
- * Output a short LSB first on the stream.
- * IN assertion: there is enough room in pendingBuf.
- */
-function put_short(s, w) {
-// put_byte(s, (uch)((w) & 0xff));
-// put_byte(s, (uch)((ush)(w) >> 8));
- s.pending_buf[s.pending++] = (w) & 0xff;
- s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
-}
-
-
-/* ===========================================================================
- * Send a value on a given number of bits.
- * IN assertion: length <= 16 and value fits in length bits.
- */
-function send_bits(s, value, length) {
- if (s.bi_valid > (Buf_size - length)) {
- s.bi_buf |= (value << s.bi_valid) & 0xffff;
- put_short(s, s.bi_buf);
- s.bi_buf = value >> (Buf_size - s.bi_valid);
- s.bi_valid += length - Buf_size;
- } else {
- s.bi_buf |= (value << s.bi_valid) & 0xffff;
- s.bi_valid += length;
- }
-}
-
-
-function send_code(s, c, tree) {
- send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
-}
-
-
-/* ===========================================================================
- * Reverse the first len bits of a code, using straightforward code (a faster
- * method would use a table)
- * IN assertion: 1 <= len <= 15
- */
-function bi_reverse(code, len) {
- var res = 0;
- do {
- res |= code & 1;
- code >>>= 1;
- res <<= 1;
- } while (--len > 0);
- return res >>> 1;
-}
-
-
-/* ===========================================================================
- * Flush the bit buffer, keeping at most 7 bits in it.
- */
-function bi_flush(s) {
- if (s.bi_valid === 16) {
- put_short(s, s.bi_buf);
- s.bi_buf = 0;
- s.bi_valid = 0;
-
- } else if (s.bi_valid >= 8) {
- s.pending_buf[s.pending++] = s.bi_buf & 0xff;
- s.bi_buf >>= 8;
- s.bi_valid -= 8;
- }
-}
-
-
-/* ===========================================================================
- * Compute the optimal bit lengths for a tree and update the total bit length
- * for the current block.
- * IN assertion: the fields freq and dad are set, heap[heap_max] and
- * above are the tree nodes sorted by increasing frequency.
- * OUT assertions: the field len is set to the optimal bit length, the
- * array bl_count contains the frequencies for each bit length.
- * The length opt_len is updated; static_len is also updated if stree is
- * not null.
- */
-function gen_bitlen(s, desc)
-// deflate_state *s;
-// tree_desc *desc; /* the tree descriptor */
-{
- var tree = desc.dyn_tree;
- var max_code = desc.max_code;
- var stree = desc.stat_desc.static_tree;
- var has_stree = desc.stat_desc.has_stree;
- var extra = desc.stat_desc.extra_bits;
- var base = desc.stat_desc.extra_base;
- var max_length = desc.stat_desc.max_length;
- var h; /* heap index */
- var n, m; /* iterate over the tree elements */
- var bits; /* bit length */
- var xbits; /* extra bits */
- var f; /* frequency */
- var overflow = 0; /* number of elements with bit length too large */
-
- for (bits = 0; bits <= MAX_BITS; bits++) {
- s.bl_count[bits] = 0;
- }
-
- /* In a first pass, compute the optimal bit lengths (which may
- * overflow in the case of the bit length tree).
- */
- tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
-
- for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
- n = s.heap[h];
- bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
- if (bits > max_length) {
- bits = max_length;
- overflow++;
- }
- tree[n * 2 + 1]/*.Len*/ = bits;
- /* We overwrite tree[n].Dad which is no longer needed */
-
- if (n > max_code) { continue; } /* not a leaf node */
-
- s.bl_count[bits]++;
- xbits = 0;
- if (n >= base) {
- xbits = extra[n - base];
- }
- f = tree[n * 2]/*.Freq*/;
- s.opt_len += f * (bits + xbits);
- if (has_stree) {
- s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
- }
- }
- if (overflow === 0) { return; }
-
- // Trace((stderr,"\nbit length overflow\n"));
- /* This happens for example on obj2 and pic of the Calgary corpus */
-
- /* Find the first bit length which could increase: */
- do {
- bits = max_length - 1;
- while (s.bl_count[bits] === 0) { bits--; }
- s.bl_count[bits]--; /* move one leaf down the tree */
- s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
- s.bl_count[max_length]--;
- /* The brother of the overflow item also moves one step up,
- * but this does not affect bl_count[max_length]
- */
- overflow -= 2;
- } while (overflow > 0);
-
- /* Now recompute all bit lengths, scanning in increasing frequency.
- * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
- * lengths instead of fixing only the wrong ones. This idea is taken
- * from 'ar' written by Haruhiko Okumura.)
- */
- for (bits = max_length; bits !== 0; bits--) {
- n = s.bl_count[bits];
- while (n !== 0) {
- m = s.heap[--h];
- if (m > max_code) { continue; }
- if (tree[m * 2 + 1]/*.Len*/ !== bits) {
- // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
- s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
- tree[m * 2 + 1]/*.Len*/ = bits;
- }
- n--;
- }
- }
-}
-
-
-/* ===========================================================================
- * Generate the codes for a given tree and bit counts (which need not be
- * optimal).
- * IN assertion: the array bl_count contains the bit length statistics for
- * the given tree and the field len is set for all tree elements.
- * OUT assertion: the field code is set for all tree elements of non
- * zero code length.
- */
-function gen_codes(tree, max_code, bl_count)
-// ct_data *tree; /* the tree to decorate */
-// int max_code; /* largest code with non zero frequency */
-// ushf *bl_count; /* number of codes at each bit length */
-{
- var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
- var code = 0; /* running code value */
- var bits; /* bit index */
- var n; /* code index */
-
- /* The distribution counts are first used to generate the code values
- * without bit reversal.
- */
- for (bits = 1; bits <= MAX_BITS; bits++) {
- next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
- }
- /* Check that the bit counts in bl_count are consistent. The last code
- * must be all ones.
- */
- //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */
- length = 0;
- for (code = 0; code < LENGTH_CODES - 1; code++) {
- base_length[code] = length;
- for (n = 0; n < (1 << extra_lbits[code]); n++) {
- _length_code[length++] = code;
- }
- }
- //Assert (length == 256, "tr_static_init: length != 256");
- /* Note that the length 255 (match length 258) can be represented
- * in two different ways: code 284 + 5 bits or code 285, so we
- * overwrite length_code[255] to use the best encoding:
- */
- _length_code[length - 1] = code;
-
- /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
- dist = 0;
- for (code = 0; code < 16; code++) {
- base_dist[code] = dist;
- for (n = 0; n < (1 << extra_dbits[code]); n++) {
- _dist_code[dist++] = code;
- }
- }
- //Assert (dist == 256, "tr_static_init: dist != 256");
- dist >>= 7; /* from now on, all distances are divided by 128 */
- for (; code < D_CODES; code++) {
- base_dist[code] = dist << 7;
- for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
- _dist_code[256 + dist++] = code;
- }
- }
- //Assert (dist == 256, "tr_static_init: 256+dist != 512");
-
- /* Construct the codes of the static literal tree */
- for (bits = 0; bits <= MAX_BITS; bits++) {
- bl_count[bits] = 0;
- }
-
- n = 0;
- while (n <= 143) {
- static_ltree[n * 2 + 1]/*.Len*/ = 8;
- n++;
- bl_count[8]++;
- }
- while (n <= 255) {
- static_ltree[n * 2 + 1]/*.Len*/ = 9;
- n++;
- bl_count[9]++;
- }
- while (n <= 279) {
- static_ltree[n * 2 + 1]/*.Len*/ = 7;
- n++;
- bl_count[7]++;
- }
- while (n <= 287) {
- static_ltree[n * 2 + 1]/*.Len*/ = 8;
- n++;
- bl_count[8]++;
- }
- /* Codes 286 and 287 do not exist, but we must include them in the
- * tree construction to get a canonical Huffman tree (longest code
- * all ones)
- */
- gen_codes(static_ltree, L_CODES + 1, bl_count);
-
- /* The static distance tree is trivial: */
- for (n = 0; n < D_CODES; n++) {
- static_dtree[n * 2 + 1]/*.Len*/ = 5;
- static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
- }
-
- // Now data ready and we can init static trees
- static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
- static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
- static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
-
- //static_init_done = true;
-}
-
-
-/* ===========================================================================
- * Initialize a new block.
- */
-function init_block(s) {
- var n; /* iterates over tree elements */
-
- /* Initialize the trees. */
- for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
- for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
- for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
-
- s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
- s.opt_len = s.static_len = 0;
- s.last_lit = s.matches = 0;
-}
-
-
-/* ===========================================================================
- * Flush the bit buffer and align the output on a byte boundary
- */
-function bi_windup(s)
-{
- if (s.bi_valid > 8) {
- put_short(s, s.bi_buf);
- } else if (s.bi_valid > 0) {
- //put_byte(s, (Byte)s->bi_buf);
- s.pending_buf[s.pending++] = s.bi_buf;
- }
- s.bi_buf = 0;
- s.bi_valid = 0;
-}
-
-/* ===========================================================================
- * Copy a stored block, storing first the length and its
- * one's complement if requested.
- */
-function copy_block(s, buf, len, header)
-//DeflateState *s;
-//charf *buf; /* the input data */
-//unsigned len; /* its length */
-//int header; /* true if block header must be written */
-{
- bi_windup(s); /* align on byte boundary */
-
- if (header) {
- put_short(s, len);
- put_short(s, ~len);
- }
-// while (len--) {
-// put_byte(s, *buf++);
-// }
- utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
- s.pending += len;
-}
-
-/* ===========================================================================
- * Compares to subtrees, using the tree depth as tie breaker when
- * the subtrees have equal frequency. This minimizes the worst case length.
- */
-function smaller(tree, n, m, depth) {
- var _n2 = n * 2;
- var _m2 = m * 2;
- return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
- (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
-}
-
-/* ===========================================================================
- * Restore the heap property by moving down the tree starting at node k,
- * exchanging a node with the smallest of its two sons if necessary, stopping
- * when the heap property is re-established (each father smaller than its
- * two sons).
- */
-function pqdownheap(s, tree, k)
-// deflate_state *s;
-// ct_data *tree; /* the tree to restore */
-// int k; /* node to move down */
-{
- var v = s.heap[k];
- var j = k << 1; /* left son of k */
- while (j <= s.heap_len) {
- /* Set j to the smallest of the two sons: */
- if (j < s.heap_len &&
- smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
- j++;
- }
- /* Exit if v is smaller than both sons */
- if (smaller(tree, v, s.heap[j], s.depth)) { break; }
-
- /* Exchange v with the smallest son */
- s.heap[k] = s.heap[j];
- k = j;
-
- /* And continue down the tree, setting j to the left son of k */
- j <<= 1;
- }
- s.heap[k] = v;
-}
-
-
-// inlined manually
-// var SMALLEST = 1;
-
-/* ===========================================================================
- * Send the block data compressed using the given Huffman trees
- */
-function compress_block(s, ltree, dtree)
-// deflate_state *s;
-// const ct_data *ltree; /* literal tree */
-// const ct_data *dtree; /* distance tree */
-{
- var dist; /* distance of matched string */
- var lc; /* match length or unmatched char (if dist == 0) */
- var lx = 0; /* running index in l_buf */
- var code; /* the code to send */
- var extra; /* number of extra bits to send */
-
- if (s.last_lit !== 0) {
- do {
- dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
- lc = s.pending_buf[s.l_buf + lx];
- lx++;
-
- if (dist === 0) {
- send_code(s, lc, ltree); /* send a literal byte */
- //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
- } else {
- /* Here, lc is the match length - MIN_MATCH */
- code = _length_code[lc];
- send_code(s, code + LITERALS + 1, ltree); /* send the length code */
- extra = extra_lbits[code];
- if (extra !== 0) {
- lc -= base_length[code];
- send_bits(s, lc, extra); /* send the extra length bits */
- }
- dist--; /* dist is now the match distance - 1 */
- code = d_code(dist);
- //Assert (code < D_CODES, "bad d_code");
-
- send_code(s, code, dtree); /* send the distance code */
- extra = extra_dbits[code];
- if (extra !== 0) {
- dist -= base_dist[code];
- send_bits(s, dist, extra); /* send the extra distance bits */
- }
- } /* literal or match pair ? */
-
- /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
- //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
- // "pendingBuf overflow");
-
- } while (lx < s.last_lit);
- }
-
- send_code(s, END_BLOCK, ltree);
-}
-
-
-/* ===========================================================================
- * Construct one Huffman tree and assigns the code bit strings and lengths.
- * Update the total bit length for the current block.
- * IN assertion: the field freq is set for all tree elements.
- * OUT assertions: the fields len and code are set to the optimal bit length
- * and corresponding code. The length opt_len is updated; static_len is
- * also updated if stree is not null. The field max_code is set.
- */
-function build_tree(s, desc)
-// deflate_state *s;
-// tree_desc *desc; /* the tree descriptor */
-{
- var tree = desc.dyn_tree;
- var stree = desc.stat_desc.static_tree;
- var has_stree = desc.stat_desc.has_stree;
- var elems = desc.stat_desc.elems;
- var n, m; /* iterate over heap elements */
- var max_code = -1; /* largest code with non zero frequency */
- var node; /* new node being created */
-
- /* Construct the initial heap, with least frequent element in
- * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
- * heap[0] is not used.
- */
- s.heap_len = 0;
- s.heap_max = HEAP_SIZE;
-
- for (n = 0; n < elems; n++) {
- if (tree[n * 2]/*.Freq*/ !== 0) {
- s.heap[++s.heap_len] = max_code = n;
- s.depth[n] = 0;
-
- } else {
- tree[n * 2 + 1]/*.Len*/ = 0;
- }
- }
-
- /* The pkzip format requires that at least one distance code exists,
- * and that at least one bit should be sent even if there is only one
- * possible code. So to avoid special checks later on we force at least
- * two codes of non zero frequency.
- */
- while (s.heap_len < 2) {
- node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
- tree[node * 2]/*.Freq*/ = 1;
- s.depth[node] = 0;
- s.opt_len--;
-
- if (has_stree) {
- s.static_len -= stree[node * 2 + 1]/*.Len*/;
- }
- /* node is 0 or 1 so it does not have extra bits */
- }
- desc.max_code = max_code;
-
- /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
- * establish sub-heaps of increasing lengths:
- */
- for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
-
- /* Construct the Huffman tree by repeatedly combining the least two
- * frequent nodes.
- */
- node = elems; /* next internal node of the tree */
- do {
- //pqremove(s, tree, n); /* n = node of least frequency */
- /*** pqremove ***/
- n = s.heap[1/*SMALLEST*/];
- s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
- pqdownheap(s, tree, 1/*SMALLEST*/);
- /***/
-
- m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
-
- s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
- s.heap[--s.heap_max] = m;
-
- /* Create a new node father of n and m */
- tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
- s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
- tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
-
- /* and insert the new node in the heap */
- s.heap[1/*SMALLEST*/] = node++;
- pqdownheap(s, tree, 1/*SMALLEST*/);
-
- } while (s.heap_len >= 2);
-
- s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
-
- /* At this point, the fields freq and dad are set. We can now
- * generate the bit lengths.
- */
- gen_bitlen(s, desc);
-
- /* The field len is now set, we can generate the bit codes */
- gen_codes(tree, max_code, s.bl_count);
-}
-
-
-/* ===========================================================================
- * Scan a literal or distance tree to determine the frequencies of the codes
- * in the bit length tree.
- */
-function scan_tree(s, tree, max_code)
-// deflate_state *s;
-// ct_data *tree; /* the tree to be scanned */
-// int max_code; /* and its largest code of non zero frequency */
-{
- var n; /* iterates over all tree elements */
- var prevlen = -1; /* last emitted length */
- var curlen; /* length of current code */
-
- var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
-
- var count = 0; /* repeat count of the current code */
- var max_count = 7; /* max repeat count */
- var min_count = 4; /* min repeat count */
-
- if (nextlen === 0) {
- max_count = 138;
- min_count = 3;
- }
- tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
-
- for (n = 0; n <= max_code; n++) {
- curlen = nextlen;
- nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
-
- if (++count < max_count && curlen === nextlen) {
- continue;
-
- } else if (count < min_count) {
- s.bl_tree[curlen * 2]/*.Freq*/ += count;
-
- } else if (curlen !== 0) {
-
- if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
- s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
-
- } else if (count <= 10) {
- s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
-
- } else {
- s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
- }
-
- count = 0;
- prevlen = curlen;
-
- if (nextlen === 0) {
- max_count = 138;
- min_count = 3;
-
- } else if (curlen === nextlen) {
- max_count = 6;
- min_count = 3;
-
- } else {
- max_count = 7;
- min_count = 4;
- }
- }
-}
-
-
-/* ===========================================================================
- * Send a literal or distance tree in compressed form, using the codes in
- * bl_tree.
- */
-function send_tree(s, tree, max_code)
-// deflate_state *s;
-// ct_data *tree; /* the tree to be scanned */
-// int max_code; /* and its largest code of non zero frequency */
-{
- var n; /* iterates over all tree elements */
- var prevlen = -1; /* last emitted length */
- var curlen; /* length of current code */
-
- var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
-
- var count = 0; /* repeat count of the current code */
- var max_count = 7; /* max repeat count */
- var min_count = 4; /* min repeat count */
-
- /* tree[max_code+1].Len = -1; */ /* guard already set */
- if (nextlen === 0) {
- max_count = 138;
- min_count = 3;
- }
-
- for (n = 0; n <= max_code; n++) {
- curlen = nextlen;
- nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
-
- if (++count < max_count && curlen === nextlen) {
- continue;
-
- } else if (count < min_count) {
- do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
-
- } else if (curlen !== 0) {
- if (curlen !== prevlen) {
- send_code(s, curlen, s.bl_tree);
- count--;
- }
- //Assert(count >= 3 && count <= 6, " 3_6?");
- send_code(s, REP_3_6, s.bl_tree);
- send_bits(s, count - 3, 2);
-
- } else if (count <= 10) {
- send_code(s, REPZ_3_10, s.bl_tree);
- send_bits(s, count - 3, 3);
-
- } else {
- send_code(s, REPZ_11_138, s.bl_tree);
- send_bits(s, count - 11, 7);
- }
-
- count = 0;
- prevlen = curlen;
- if (nextlen === 0) {
- max_count = 138;
- min_count = 3;
-
- } else if (curlen === nextlen) {
- max_count = 6;
- min_count = 3;
-
- } else {
- max_count = 7;
- min_count = 4;
- }
- }
-}
-
-
-/* ===========================================================================
- * Construct the Huffman tree for the bit lengths and return the index in
- * bl_order of the last bit length code to send.
- */
-function build_bl_tree(s) {
- var max_blindex; /* index of last bit length code of non zero freq */
-
- /* Determine the bit length frequencies for literal and distance trees */
- scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
- scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
-
- /* Build the bit length tree: */
- build_tree(s, s.bl_desc);
- /* opt_len now includes the length of the tree representations, except
- * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
- */
-
- /* Determine the number of bit length codes to send. The pkzip format
- * requires that at least 4 bit length codes be sent. (appnote.txt says
- * 3 but the actual value used is 4.)
- */
- for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
- if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
- break;
- }
- }
- /* Update opt_len to include the bit length tree and counts */
- s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
- //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
- // s->opt_len, s->static_len));
-
- return max_blindex;
-}
-
-
-/* ===========================================================================
- * Send the header for a block using dynamic Huffman trees: the counts, the
- * lengths of the bit length codes, the literal tree and the distance tree.
- * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
- */
-function send_all_trees(s, lcodes, dcodes, blcodes)
-// deflate_state *s;
-// int lcodes, dcodes, blcodes; /* number of codes for each tree */
-{
- var rank; /* index in bl_order */
-
- //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
- //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
- // "too many codes");
- //Tracev((stderr, "\nbl counts: "));
- send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
- send_bits(s, dcodes - 1, 5);
- send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
- for (rank = 0; rank < blcodes; rank++) {
- //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
- send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
- }
- //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
-
- send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
- //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
-
- send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
- //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
-}
-
-
-/* ===========================================================================
- * Check if the data type is TEXT or BINARY, using the following algorithm:
- * - TEXT if the two conditions below are satisfied:
- * a) There are no non-portable control characters belonging to the
- * "black list" (0..6, 14..25, 28..31).
- * b) There is at least one printable character belonging to the
- * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
- * - BINARY otherwise.
- * - The following partially-portable control characters form a
- * "gray list" that is ignored in this detection algorithm:
- * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
- * IN assertion: the fields Freq of dyn_ltree are set.
- */
-function detect_data_type(s) {
- /* black_mask is the bit mask of black-listed bytes
- * set bits 0..6, 14..25, and 28..31
- * 0xf3ffc07f = binary 11110011111111111100000001111111
- */
- var black_mask = 0xf3ffc07f;
- var n;
-
- /* Check for non-textual ("black-listed") bytes. */
- for (n = 0; n <= 31; n++, black_mask >>>= 1) {
- if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
- return Z_BINARY;
- }
- }
-
- /* Check for textual ("white-listed") bytes. */
- if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
- s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
- return Z_TEXT;
- }
- for (n = 32; n < LITERALS; n++) {
- if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
- return Z_TEXT;
- }
- }
-
- /* There are no "black-listed" or "white-listed" bytes:
- * this stream either is empty or has tolerated ("gray-listed") bytes only.
- */
- return Z_BINARY;
-}
-
-
-var static_init_done = false;
-
-/* ===========================================================================
- * Initialize the tree data structures for a new zlib stream.
- */
-function _tr_init(s)
-{
-
- if (!static_init_done) {
- tr_static_init();
- static_init_done = true;
- }
-
- s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
- s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
- s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
-
- s.bi_buf = 0;
- s.bi_valid = 0;
-
- /* Initialize the first block of the first file: */
- init_block(s);
-}
-
-
-/* ===========================================================================
- * Send a stored block
- */
-function _tr_stored_block(s, buf, stored_len, last)
-//DeflateState *s;
-//charf *buf; /* input block */
-//ulg stored_len; /* length of input block */
-//int last; /* one if this is the last block for a file */
-{
- send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
- copy_block(s, buf, stored_len, true); /* with header */
-}
-
-
-/* ===========================================================================
- * Send one empty static block to give enough lookahead for inflate.
- * This takes 10 bits, of which 7 may remain in the bit buffer.
- */
-function _tr_align(s) {
- send_bits(s, STATIC_TREES << 1, 3);
- send_code(s, END_BLOCK, static_ltree);
- bi_flush(s);
-}
-
-
-/* ===========================================================================
- * Determine the best encoding for the current block: dynamic trees, static
- * trees or store, and output the encoded block to the zip file.
- */
-function _tr_flush_block(s, buf, stored_len, last)
-//DeflateState *s;
-//charf *buf; /* input block, or NULL if too old */
-//ulg stored_len; /* length of input block */
-//int last; /* one if this is the last block for a file */
-{
- var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
- var max_blindex = 0; /* index of last bit length code of non zero freq */
-
- /* Build the Huffman trees unless a stored block is forced */
- if (s.level > 0) {
-
- /* Check if the file is binary or text */
- if (s.strm.data_type === Z_UNKNOWN) {
- s.strm.data_type = detect_data_type(s);
- }
-
- /* Construct the literal and distance trees */
- build_tree(s, s.l_desc);
- // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
- // s->static_len));
-
- build_tree(s, s.d_desc);
- // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
- // s->static_len));
- /* At this point, opt_len and static_len are the total bit lengths of
- * the compressed block data, excluding the tree representations.
- */
-
- /* Build the bit length tree for the above two trees, and get the index
- * in bl_order of the last bit length code to send.
- */
- max_blindex = build_bl_tree(s);
-
- /* Determine the best encoding. Compute the block lengths in bytes. */
- opt_lenb = (s.opt_len + 3 + 7) >>> 3;
- static_lenb = (s.static_len + 3 + 7) >>> 3;
-
- // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
- // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
- // s->last_lit));
-
- if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
-
- } else {
- // Assert(buf != (char*)0, "lost buf");
- opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
- }
-
- if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
- /* 4: two words for the lengths */
-
- /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
- * Otherwise we can't have processed more than WSIZE input bytes since
- * the last block flush, because compression would have been
- * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
- * transform a block into a stored block.
- */
- _tr_stored_block(s, buf, stored_len, last);
-
- } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
-
- send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
- compress_block(s, static_ltree, static_dtree);
-
- } else {
- send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
- send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
- compress_block(s, s.dyn_ltree, s.dyn_dtree);
- }
- // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
- /* The above check is made mod 2^32, for files larger than 512 MB
- * and uLong implemented on 32 bits.
- */
- init_block(s);
-
- if (last) {
- bi_windup(s);
- }
- // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
- // s->compressed_len-7*last));
-}
-
-/* ===========================================================================
- * Save the match info and tally the frequency counts. Return true if
- * the current block must be flushed.
- */
-function _tr_tally(s, dist, lc)
-// deflate_state *s;
-// unsigned dist; /* distance of matched string */
-// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
-{
- //var out_length, in_length, dcode;
-
- s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
- s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
-
- s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
- s.last_lit++;
-
- if (dist === 0) {
- /* lc is the unmatched char */
- s.dyn_ltree[lc * 2]/*.Freq*/++;
- } else {
- s.matches++;
- /* Here, lc is the match length - MIN_MATCH */
- dist--; /* dist = match distance - 1 */
- //Assert((ush)dist < (ush)MAX_DIST(s) &&
- // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
- // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
-
- s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
- s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
- }
-
-// (!) This block is disabled in zlib defaults,
-// don't enable it for binary compatibility
-
-//#ifdef TRUNCATE_BLOCK
-// /* Try to guess if it is profitable to stop the current block here */
-// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
-// /* Compute an upper bound for the compressed length */
-// out_length = s.last_lit*8;
-// in_length = s.strstart - s.block_start;
-//
-// for (dcode = 0; dcode < D_CODES; dcode++) {
-// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
-// }
-// out_length >>>= 3;
-// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
-// // s->last_lit, in_length, out_length,
-// // 100L - out_length*100L/in_length));
-// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
-// return true;
-// }
-// }
-//#endif
-
- return (s.last_lit === s.lit_bufsize - 1);
- /* We avoid equality with lit_bufsize because of wraparound at 64K
- * on 16 bit machines and because stored blocks are restricted to
- * 64K-1 bytes.
- */
-}
-
-exports._tr_init = _tr_init;
-exports._tr_stored_block = _tr_stored_block;
-exports._tr_flush_block = _tr_flush_block;
-exports._tr_tally = _tr_tally;
-exports._tr_align = _tr_align;
-
-},{"../utils/common":21}],31:[function(require,module,exports){
-'use strict';
-
-// (C) 1995-2013 Jean-loup Gailly and Mark Adler
-// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
-//
-// This software is provided 'as-is', without any express or implied
-// warranty. In no event will the authors be held liable for any damages
-// arising from the use of this software.
-//
-// Permission is granted to anyone to use this software for any purpose,
-// including commercial applications, and to alter it and redistribute it
-// freely, subject to the following restrictions:
-//
-// 1. The origin of this software must not be misrepresented; you must not
-// claim that you wrote the original software. If you use this software
-// in a product, an acknowledgment in the product documentation would be
-// appreciated but is not required.
-// 2. Altered source versions must be plainly marked as such, and must not be
-// misrepresented as being the original software.
-// 3. This notice may not be removed or altered from any source distribution.
-
-function ZStream() {
- /* next input byte */
- this.input = null; // JS specific, because we have no pointers
- this.next_in = 0;
- /* number of bytes available at input */
- this.avail_in = 0;
- /* total number of input bytes read so far */
- this.total_in = 0;
- /* next output byte should be put there */
- this.output = null; // JS specific, because we have no pointers
- this.next_out = 0;
- /* remaining free space at output */
- this.avail_out = 0;
- /* total number of bytes output so far */
- this.total_out = 0;
- /* last error message, NULL if no error */
- this.msg = ''/*Z_NULL*/;
- /* not visible by applications */
- this.state = null;
- /* best guess about the data type: binary or text */
- this.data_type = 2/*Z_UNKNOWN*/;
- /* adler32 value of the uncompressed data */
- this.adler = 0;
-}
-
-module.exports = ZStream;
-
-},{}],32:[function(require,module,exports){
-(function (process){(function (){
-// .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
-// backported and transplited with Babel, with backwards-compat fixes
-
-// 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.
-
-// resolves . and .. elements in a path array with directory names there
-// must be no slashes, empty elements, or device names (c:\) in the array
-// (so also no leading and trailing slashes - it does not distinguish
-// relative and absolute paths)
-function normalizeArray(parts, allowAboveRoot) {
- // if the path tries to go above the root, `up` ends up > 0
- var up = 0;
- for (var i = parts.length - 1; i >= 0; i--) {
- var last = parts[i];
- if (last === '.') {
- parts.splice(i, 1);
- } else if (last === '..') {
- parts.splice(i, 1);
- up++;
- } else if (up) {
- parts.splice(i, 1);
- up--;
- }
- }
-
- // if the path is allowed to go above the root, restore leading ..s
- if (allowAboveRoot) {
- for (; up--; up) {
- parts.unshift('..');
- }
- }
-
- return parts;
-}
-
-// path.resolve([from ...], to)
-// posix version
-exports.resolve = function() {
- var resolvedPath = '',
- resolvedAbsolute = false;
-
- for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
- var path = (i >= 0) ? arguments[i] : process.cwd();
-
- // Skip empty and invalid entries
- if (typeof path !== 'string') {
- throw new TypeError('Arguments to path.resolve must be strings');
- } else if (!path) {
- continue;
- }
-
- resolvedPath = path + '/' + resolvedPath;
- resolvedAbsolute = path.charAt(0) === '/';
- }
-
- // At this point the path should be resolved to a full absolute path, but
- // handle relative paths to be safe (might happen when process.cwd() fails)
-
- // Normalize the path
- resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
- return !!p;
- }), !resolvedAbsolute).join('/');
-
- return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
-};
-
-// path.normalize(path)
-// posix version
-exports.normalize = function(path) {
- var isAbsolute = exports.isAbsolute(path),
- trailingSlash = substr(path, -1) === '/';
-
- // Normalize the path
- path = normalizeArray(filter(path.split('/'), function(p) {
- return !!p;
- }), !isAbsolute).join('/');
-
- if (!path && !isAbsolute) {
- path = '.';
- }
- if (path && trailingSlash) {
- path += '/';
- }
-
- return (isAbsolute ? '/' : '') + path;
-};
-
-// posix version
-exports.isAbsolute = function(path) {
- return path.charAt(0) === '/';
-};
-
-// posix version
-exports.join = function() {
- var paths = Array.prototype.slice.call(arguments, 0);
- return exports.normalize(filter(paths, function(p, index) {
- if (typeof p !== 'string') {
- throw new TypeError('Arguments to path.join must be strings');
- }
- return p;
- }).join('/'));
-};
-
-
-// path.relative(from, to)
-// posix version
-exports.relative = function(from, to) {
- from = exports.resolve(from).substr(1);
- to = exports.resolve(to).substr(1);
-
- function trim(arr) {
- var start = 0;
- for (; start < arr.length; start++) {
- if (arr[start] !== '') break;
- }
-
- var end = arr.length - 1;
- for (; end >= 0; end--) {
- if (arr[end] !== '') break;
- }
-
- if (start > end) return [];
- return arr.slice(start, end - start + 1);
- }
-
- var fromParts = trim(from.split('/'));
- var toParts = trim(to.split('/'));
-
- var length = Math.min(fromParts.length, toParts.length);
- var samePartsLength = length;
- for (var i = 0; i < length; i++) {
- if (fromParts[i] !== toParts[i]) {
- samePartsLength = i;
- break;
- }
- }
-
- var outputParts = [];
- for (var i = samePartsLength; i < fromParts.length; i++) {
- outputParts.push('..');
- }
-
- outputParts = outputParts.concat(toParts.slice(samePartsLength));
-
- return outputParts.join('/');
-};
-
-exports.sep = '/';
-exports.delimiter = ':';
-
-exports.dirname = function (path) {
- if (typeof path !== 'string') path = path + '';
- if (path.length === 0) return '.';
- var code = path.charCodeAt(0);
- var hasRoot = code === 47 /*/*/;
- var end = -1;
- var matchedSlash = true;
- for (var i = path.length - 1; i >= 1; --i) {
- code = path.charCodeAt(i);
- if (code === 47 /*/*/) {
- if (!matchedSlash) {
- end = i;
- break;
- }
- } else {
- // We saw the first non-path separator
- matchedSlash = false;
- }
- }
-
- if (end === -1) return hasRoot ? '/' : '.';
- if (hasRoot && end === 1) {
- // return '//';
- // Backwards-compat fix:
- return '/';
- }
- return path.slice(0, end);
-};
-
-function basename(path) {
- if (typeof path !== 'string') path = path + '';
-
- var start = 0;
- var end = -1;
- var matchedSlash = true;
- var i;
-
- for (i = path.length - 1; i >= 0; --i) {
- if (path.charCodeAt(i) === 47 /*/*/) {
- // If we reached a path separator that was not part of a set of path
- // separators at the end of the string, stop now
- if (!matchedSlash) {
- start = i + 1;
- break;
- }
- } else if (end === -1) {
- // We saw the first non-path separator, mark this as the end of our
- // path component
- matchedSlash = false;
- end = i + 1;
- }
- }
-
- if (end === -1) return '';
- return path.slice(start, end);
-}
-
-// Uses a mixed approach for backwards-compatibility, as ext behavior changed
-// in new Node.js versions, so only basename() above is backported here
-exports.basename = function (path, ext) {
- var f = basename(path);
- if (ext && f.substr(-1 * ext.length) === ext) {
- f = f.substr(0, f.length - ext.length);
- }
- return f;
-};
-
-exports.extname = function (path) {
- if (typeof path !== 'string') path = path + '';
- var startDot = -1;
- var startPart = 0;
- var end = -1;
- var matchedSlash = true;
- // Track the state of characters (if any) we see before our first dot and
- // after any path separator we find
- var preDotState = 0;
- for (var i = path.length - 1; i >= 0; --i) {
- var code = path.charCodeAt(i);
- if (code === 47 /*/*/) {
- // If we reached a path separator that was not part of a set of path
- // separators at the end of the string, stop now
- if (!matchedSlash) {
- startPart = i + 1;
- break;
- }
- continue;
- }
- if (end === -1) {
- // We saw the first non-path separator, mark this as the end of our
- // extension
- matchedSlash = false;
- end = i + 1;
- }
- if (code === 46 /*.*/) {
- // If this is our first dot, mark it as the start of our extension
- if (startDot === -1)
- startDot = i;
- else if (preDotState !== 1)
- preDotState = 1;
- } else if (startDot !== -1) {
- // We saw a non-dot and non-path separator before our dot, so we should
- // have a good chance at having a non-empty extension
- preDotState = -1;
- }
- }
-
- if (startDot === -1 || end === -1 ||
- // We saw a non-dot character immediately before the dot
- preDotState === 0 ||
- // The (right-most) trimmed path component is exactly '..'
- preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
- return '';
- }
- return path.slice(startDot, end);
-};
-
-function filter (xs, f) {
- if (xs.filter) return xs.filter(f);
- var res = [];
- for (var i = 0; i < xs.length; i++) {
- if (f(xs[i], i, xs)) res.push(xs[i]);
- }
- return res;
-}
-
-// String.prototype.substr - negative index don't work in IE8
-var substr = 'ab'.substr(-1) === 'b'
- ? function (str, start, len) { return str.substr(start, len) }
- : function (str, start, len) {
- if (start < 0) start = str.length + start;
- return str.substr(start, len);
- }
-;
-
-}).call(this)}).call(this,require('_process'))
-},{"_process":34}],33:[function(require,module,exports){
-(function (process){(function (){
-'use strict';
-
-if (typeof process === 'undefined' ||
- !process.version ||
- process.version.indexOf('v0.') === 0 ||
- process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
- module.exports = { nextTick: nextTick };
-} else {
- module.exports = process
-}
-
-function nextTick(fn, arg1, arg2, arg3) {
- if (typeof fn !== 'function') {
- throw new TypeError('"callback" argument must be a function');
- }
- var len = arguments.length;
- var args, i;
- switch (len) {
- case 0:
- case 1:
- return process.nextTick(fn);
- case 2:
- return process.nextTick(function afterTickOne() {
- fn.call(null, arg1);
- });
- case 3:
- return process.nextTick(function afterTickTwo() {
- fn.call(null, arg1, arg2);
- });
- case 4:
- return process.nextTick(function afterTickThree() {
- fn.call(null, arg1, arg2, arg3);
- });
- default:
- args = new Array(len - 1);
- i = 0;
- while (i < args.length) {
- args[i++] = arguments[i];
- }
- return process.nextTick(function afterTick() {
- fn.apply(null, args);
- });
- }
-}
-
-
-}).call(this)}).call(this,require('_process'))
-},{"_process":34}],34:[function(require,module,exports){
-// shim for using process in browser
-var process = module.exports = {};
-
-// cached from whatever global is present so that test runners that stub it
-// don't break things. But we need to wrap it in a try catch in case it is
-// wrapped in strict mode code which doesn't define any globals. It's inside a
-// function because try/catches deoptimize in certain engines.
-
-var cachedSetTimeout;
-var cachedClearTimeout;
-
-function defaultSetTimout() {
- throw new Error('setTimeout has not been defined');
-}
-function defaultClearTimeout () {
- throw new Error('clearTimeout has not been defined');
-}
-(function () {
- try {
- if (typeof setTimeout === 'function') {
- cachedSetTimeout = setTimeout;
- } else {
- cachedSetTimeout = defaultSetTimout;
- }
- } catch (e) {
- cachedSetTimeout = defaultSetTimout;
- }
- try {
- if (typeof clearTimeout === 'function') {
- cachedClearTimeout = clearTimeout;
- } else {
- cachedClearTimeout = defaultClearTimeout;
- }
- } catch (e) {
- cachedClearTimeout = defaultClearTimeout;
- }
-} ())
-function runTimeout(fun) {
- if (cachedSetTimeout === setTimeout) {
- //normal enviroments in sane situations
- return setTimeout(fun, 0);
- }
- // if setTimeout wasn't available but was latter defined
- if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
- cachedSetTimeout = setTimeout;
- return setTimeout(fun, 0);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedSetTimeout(fun, 0);
- } catch(e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedSetTimeout.call(null, fun, 0);
- } catch(e){
- // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
- return cachedSetTimeout.call(this, fun, 0);
- }
- }
-
-
-}
-function runClearTimeout(marker) {
- if (cachedClearTimeout === clearTimeout) {
- //normal enviroments in sane situations
- return clearTimeout(marker);
- }
- // if clearTimeout wasn't available but was latter defined
- if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
- cachedClearTimeout = clearTimeout;
- return clearTimeout(marker);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedClearTimeout(marker);
- } catch (e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedClearTimeout.call(null, marker);
- } catch (e){
- // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
- // Some versions of I.E. have different rules for clearTimeout vs setTimeout
- return cachedClearTimeout.call(this, marker);
- }
- }
-
-
-
-}
-var queue = [];
-var draining = false;
-var currentQueue;
-var queueIndex = -1;
-
-function cleanUpNextTick() {
- if (!draining || !currentQueue) {
- return;
- }
- draining = false;
- if (currentQueue.length) {
- queue = currentQueue.concat(queue);
- } else {
- queueIndex = -1;
- }
- if (queue.length) {
- drainQueue();
- }
-}
-
-function drainQueue() {
- if (draining) {
- return;
- }
- var timeout = runTimeout(cleanUpNextTick);
- draining = true;
-
- var len = queue.length;
- while(len) {
- currentQueue = queue;
- queue = [];
- while (++queueIndex < len) {
- if (currentQueue) {
- currentQueue[queueIndex].run();
- }
- }
- queueIndex = -1;
- len = queue.length;
- }
- currentQueue = null;
- draining = false;
- runClearTimeout(timeout);
-}
-
-process.nextTick = function (fun) {
- var args = new Array(arguments.length - 1);
- if (arguments.length > 1) {
- for (var i = 1; i < arguments.length; i++) {
- args[i - 1] = arguments[i];
- }
- }
- queue.push(new Item(fun, args));
- if (queue.length === 1 && !draining) {
- runTimeout(drainQueue);
- }
-};
-
-// v8 likes predictible objects
-function Item(fun, array) {
- this.fun = fun;
- this.array = array;
-}
-Item.prototype.run = function () {
- this.fun.apply(null, this.array);
-};
-process.title = 'browser';
-process.browser = true;
-process.env = {};
-process.argv = [];
-process.version = ''; // empty string to avoid regexp issues
-process.versions = {};
-
-function noop() {}
-
-process.on = noop;
-process.addListener = noop;
-process.once = noop;
-process.off = noop;
-process.removeListener = noop;
-process.removeAllListeners = noop;
-process.emit = noop;
-process.prependListener = noop;
-process.prependOnceListener = noop;
-
-process.listeners = function (name) { return [] }
-
-process.binding = function (name) {
- throw new Error('process.binding is not supported');
-};
-
-process.cwd = function () { return '/' };
-process.chdir = function (dir) {
- throw new Error('process.chdir is not supported');
-};
-process.umask = function() { return 0; };
-
-},{}],35:[function(require,module,exports){
-(function (global){(function (){
-/*! https://mths.be/punycode v1.4.1 by @mathias */
-;(function(root) {
-
- /** Detect free variables */
- var freeExports = typeof exports == 'object' && exports &&
- !exports.nodeType && exports;
- var freeModule = typeof module == 'object' && module &&
- !module.nodeType && module;
- var freeGlobal = typeof global == 'object' && global;
- if (
- freeGlobal.global === freeGlobal ||
- freeGlobal.window === freeGlobal ||
- freeGlobal.self === freeGlobal
- ) {
- root = freeGlobal;
- }
-
- /**
- * The `punycode` object.
- * @name punycode
- * @type Object
- */
- var punycode,
-
- /** Highest positive signed 32-bit float value */
- maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
-
- /** Bootstring parameters */
- base = 36,
- tMin = 1,
- tMax = 26,
- skew = 38,
- damp = 700,
- initialBias = 72,
- initialN = 128, // 0x80
- delimiter = '-', // '\x2D'
-
- /** Regular expressions */
- regexPunycode = /^xn--/,
- regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
- regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
-
- /** Error messages */
- 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 */
- baseMinusTMin = base - tMin,
- floor = Math.floor,
- stringFromCharCode = String.fromCharCode,
-
- /** Temporary variable */
- key;
-
- /*--------------------------------------------------------------------------*/
-
- /**
- * 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) {
- var length = array.length;
- var result = [];
- 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) {
- var parts = string.split('@');
- var 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');
- var labels = string.split('.');
- var 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) {
- var output = [],
- counter = 0,
- length = string.length,
- value,
- extra;
- while (counter < length) {
- value = string.charCodeAt(counter++);
- if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
- // high surrogate, and there is a next character
- extra = string.charCodeAt(counter++);
- if ((extra & 0xFC00) == 0xDC00) { // low surrogate
- output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
- } else {
- // 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).
- */
- function ucs2encode(array) {
- return map(array, function(value) {
- var output = '';
- if (value > 0xFFFF) {
- value -= 0x10000;
- output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
- value = 0xDC00 | value & 0x3FF;
- }
- output += stringFromCharCode(value);
- return output;
- }).join('');
- }
-
- /**
- * 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.
- */
- function basicToDigit(codePoint) {
- if (codePoint - 48 < 10) {
- return codePoint - 22;
- }
- if (codePoint - 65 < 26) {
- return codePoint - 65;
- }
- if (codePoint - 97 < 26) {
- return codePoint - 97;
- }
- 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.
- */
- function digitToBasic(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
- */
- function adapt(delta, numPoints, firstTime) {
- var 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.
- */
- function decode(input) {
- // Don't use UCS-2
- var output = [],
- inputLength = input.length,
- out,
- i = 0,
- n = initialN,
- bias = initialBias,
- basic,
- j,
- index,
- oldi,
- w,
- k,
- digit,
- t,
- /** Cached calculation results */
- baseMinusT;
-
- // 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.
-
- basic = input.lastIndexOf(delimiter);
- if (basic < 0) {
- basic = 0;
- }
-
- for (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 (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`.
- for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
-
- if (index >= inputLength) {
- error('invalid-input');
- }
-
- digit = basicToDigit(input.charCodeAt(index++));
-
- if (digit >= base || digit > floor((maxInt - i) / w)) {
- error('overflow');
- }
-
- i += digit * w;
- t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
-
- if (digit < t) {
- break;
- }
-
- baseMinusT = base - t;
- if (w > floor(maxInt / baseMinusT)) {
- error('overflow');
- }
-
- w *= baseMinusT;
-
- }
-
- 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 ucs2encode(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.
- */
- function encode(input) {
- var n,
- delta,
- handledCPCount,
- basicLength,
- bias,
- j,
- m,
- q,
- k,
- t,
- currentValue,
- output = [],
- /** `inputLength` will hold the number of code points in `input`. */
- inputLength,
- /** Cached calculation results */
- handledCPCountPlusOne,
- baseMinusT,
- qMinusT;
-
- // Convert the input in UCS-2 to Unicode
- input = ucs2decode(input);
-
- // Cache the length
- inputLength = input.length;
-
- // Initialize the state
- n = initialN;
- delta = 0;
- bias = initialBias;
-
- // Handle the basic code points
- for (j = 0; j < inputLength; ++j) {
- currentValue = input[j];
- if (currentValue < 0x80) {
- output.push(stringFromCharCode(currentValue));
- }
- }
-
- handledCPCount = basicLength = output.length;
-
- // `handledCPCount` is the number of code points that have been handled;
- // `basicLength` is the number of basic code points.
-
- // Finish the basic string - if it is not empty - with a delimiter
- 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:
- for (m = maxInt, j = 0; j < inputLength; ++j) {
- currentValue = input[j];
- if (currentValue >= n && currentValue < m) {
- m = currentValue;
- }
- }
-
- // Increase `delta` enough to advance the decoder's state to ,
- // but guard against overflow
- handledCPCountPlusOne = handledCPCount + 1;
- if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
- error('overflow');
- }
-
- delta += (m - n) * handledCPCountPlusOne;
- n = m;
-
- for (j = 0; j < inputLength; ++j) {
- currentValue = input[j];
-
- if (currentValue < n && ++delta > maxInt) {
- error('overflow');
- }
-
- if (currentValue == n) {
- // Represent delta as a generalized variable-length integer
- for (q = delta, k = base; /* no condition */; k += base) {
- t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
- if (q < t) {
- break;
- }
- qMinusT = q - t;
- 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.
- */
- function toUnicode(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.
- */
- function toASCII(input) {
- return mapDomain(input, function(string) {
- return regexNonASCII.test(string)
- ? 'xn--' + encode(string)
- : string;
- });
- }
-
- /*--------------------------------------------------------------------------*/
-
- /** Define the public API */
- punycode = {
- /**
- * A string representing the current Punycode.js version number.
- * @memberOf punycode
- * @type String
- */
- 'version': '1.4.1',
- /**
- * 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
- };
-
- /** Expose `punycode` */
- // Some AMD build optimizers, like r.js, check for specific condition patterns
- // like the following:
- if (
- typeof define == 'function' &&
- typeof define.amd == 'object' &&
- define.amd
- ) {
- define('punycode', function() {
- return punycode;
- });
- } else if (freeExports && freeModule) {
- if (module.exports == freeExports) {
- // in Node.js, io.js, or RingoJS v0.8.0+
- freeModule.exports = punycode;
- } else {
- // in Narwhal or RingoJS v0.7.0-
- for (key in punycode) {
- punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
- }
- }
- } else {
- // in Rhino or a web browser
- root.punycode = punycode;
- }
-
-}(this));
-
-}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{}],36:[function(require,module,exports){
-// 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';
-
-// If obj.hasOwnProperty has been overridden, then calling
-// obj.hasOwnProperty(prop) will break.
-// See: https://github.com/joyent/node/issues/1707
-function hasOwnProperty(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
-}
-
-module.exports = function(qs, sep, eq, options) {
- sep = sep || '&';
- eq = eq || '=';
- var obj = {};
-
- if (typeof qs !== 'string' || qs.length === 0) {
- return obj;
- }
-
- var regexp = /\+/g;
- qs = qs.split(sep);
-
- var maxKeys = 1000;
- if (options && typeof options.maxKeys === 'number') {
- maxKeys = options.maxKeys;
- }
-
- var len = qs.length;
- // maxKeys <= 0 means that we should not limit keys count
- if (maxKeys > 0 && len > maxKeys) {
- len = maxKeys;
- }
-
- for (var i = 0; i < len; ++i) {
- var x = qs[i].replace(regexp, '%20'),
- idx = x.indexOf(eq),
- kstr, vstr, k, v;
-
- if (idx >= 0) {
- kstr = x.substr(0, idx);
- vstr = x.substr(idx + 1);
- } else {
- kstr = x;
- vstr = '';
- }
-
- k = decodeURIComponent(kstr);
- v = decodeURIComponent(vstr);
-
- if (!hasOwnProperty(obj, k)) {
- obj[k] = v;
- } else if (isArray(obj[k])) {
- obj[k].push(v);
- } else {
- obj[k] = [obj[k], v];
- }
- }
-
- return obj;
-};
-
-var isArray = Array.isArray || function (xs) {
- return Object.prototype.toString.call(xs) === '[object Array]';
-};
-
-},{}],37:[function(require,module,exports){
-// 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 stringifyPrimitive = function(v) {
- switch (typeof v) {
- case 'string':
- return v;
-
- case 'boolean':
- return v ? 'true' : 'false';
-
- case 'number':
- return isFinite(v) ? v : '';
-
- default:
- return '';
- }
-};
-
-module.exports = function(obj, sep, eq, name) {
- sep = sep || '&';
- eq = eq || '=';
- if (obj === null) {
- obj = undefined;
- }
-
- if (typeof obj === 'object') {
- return map(objectKeys(obj), function(k) {
- var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
- if (isArray(obj[k])) {
- return map(obj[k], function(v) {
- return ks + encodeURIComponent(stringifyPrimitive(v));
- }).join(sep);
- } else {
- return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
- }
- }).join(sep);
-
- }
-
- if (!name) return '';
- return encodeURIComponent(stringifyPrimitive(name)) + eq +
- encodeURIComponent(stringifyPrimitive(obj));
-};
-
-var isArray = Array.isArray || function (xs) {
- return Object.prototype.toString.call(xs) === '[object Array]';
-};
-
-function map (xs, f) {
- if (xs.map) return xs.map(f);
- var res = [];
- for (var i = 0; i < xs.length; i++) {
- res.push(f(xs[i], i));
- }
- return res;
-}
-
-var objectKeys = Object.keys || function (obj) {
- var res = [];
- for (var key in obj) {
- if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
- }
- return res;
-};
-
-},{}],38:[function(require,module,exports){
-'use strict';
-
-exports.decode = exports.parse = require('./decode');
-exports.encode = exports.stringify = require('./encode');
-
-},{"./decode":36,"./encode":37}],39:[function(require,module,exports){
-module.exports = require('./lib/_stream_duplex.js');
-
-},{"./lib/_stream_duplex.js":40}],40:[function(require,module,exports){
-// 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 pna = require('process-nextick-args');
-/**/
-
-/**/
-var objectKeys = Object.keys || function (obj) {
- var keys = [];
- for (var key in obj) {
- keys.push(key);
- }return keys;
-};
-/**/
-
-module.exports = Duplex;
-
-/**/
-var util = Object.create(require('core-util-is'));
-util.inherits = require('inherits');
-/**/
-
-var Readable = require('./_stream_readable');
-var Writable = require('./_stream_writable');
-
-util.inherits(Duplex, Readable);
-
-{
- // avoid scope creep, the keys array can then be collected
- var keys = objectKeys(Writable.prototype);
- for (var v = 0; v < keys.length; v++) {
- var method = keys[v];
- if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
- }
-}
-
-function Duplex(options) {
- if (!(this instanceof Duplex)) return new Duplex(options);
-
- Readable.call(this, options);
- Writable.call(this, options);
-
- if (options && options.readable === false) this.readable = false;
-
- if (options && options.writable === false) this.writable = false;
-
- this.allowHalfOpen = true;
- if (options && 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 () {
- return this._writableState.highWaterMark;
- }
-});
-
-// the no-half-open enforcer
-function onend() {
- // if we allow half-open state, or if the writable side ended,
- // then we're ok.
- if (this.allowHalfOpen || this._writableState.ended) return;
-
- // no more data can be written.
- // But allow more writes to happen in this tick.
- pna.nextTick(onEndNT, this);
-}
-
-function onEndNT(self) {
- self.end();
-}
-
-Object.defineProperty(Duplex.prototype, 'destroyed', {
- get: function () {
- if (this._readableState === undefined || this._writableState === undefined) {
- return false;
- }
- return this._readableState.destroyed && this._writableState.destroyed;
- },
- set: function (value) {
- // we ignore the value if the stream
- // has not been initialized yet
- if (this._readableState === undefined || this._writableState === undefined) {
- return;
- }
-
- // backward compatibility, the user is explicitly
- // managing destroyed
- this._readableState.destroyed = value;
- this._writableState.destroyed = value;
- }
-});
-
-Duplex.prototype._destroy = function (err, cb) {
- this.push(null);
- this.end();
-
- pna.nextTick(cb, err);
-};
-},{"./_stream_readable":42,"./_stream_writable":44,"core-util-is":12,"inherits":16,"process-nextick-args":33}],41:[function(require,module,exports){
-// 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');
-
-/**/
-var util = Object.create(require('core-util-is'));
-util.inherits = require('inherits');
-/**/
-
-util.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);
-};
-},{"./_stream_transform":43,"core-util-is":12,"inherits":16}],42:[function(require,module,exports){
-(function (process,global){(function (){
-// 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 pna = require('process-nextick-args');
-/**/
-
-module.exports = Readable;
-
-/**/
-var isArray = require('isarray');
-/**/
-
-/**/
-var Duplex;
-/**/
-
-Readable.ReadableState = ReadableState;
-
-/**/
-var EE = require('events').EventEmitter;
-
-var EElistenerCount = function (emitter, type) {
- return emitter.listeners(type).length;
-};
-/**/
-
-/**/
-var Stream = require('./internal/streams/stream');
-/**/
-
-/**/
-
-var Buffer = require('safe-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 util = Object.create(require('core-util-is'));
-util.inherits = require('inherits');
-/**/
-
-/**/
-var debugUtil = require('util');
-var debug = void 0;
-if (debugUtil && debugUtil.debuglog) {
- debug = debugUtil.debuglog('stream');
-} else {
- debug = function () {};
-}
-/**/
-
-var BufferList = require('./internal/streams/BufferList');
-var destroyImpl = require('./internal/streams/destroy');
-var StringDecoder;
-
-util.inherits(Readable, Stream);
-
-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 (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
-}
-
-function ReadableState(options, stream) {
- 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.
- var 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"
- var hwm = options.highWaterMark;
- var readableHwm = options.readableHighWaterMark;
- var defaultHwm = this.objectMode ? 16 : 16 * 1024;
-
- if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
-
- // cast to ints.
- this.highWaterMark = Math.floor(this.highWaterMark);
-
- // 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;
-
- // 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);
-
- this._readableState = new ReadableState(options, this);
-
- // 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', {
- get: function () {
- if (this._readableState === undefined) {
- return false;
- }
- return this._readableState.destroyed;
- },
- set: function (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) {
- this.push(null);
- 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) {
- var state = stream._readableState;
- if (chunk === null) {
- state.reading = false;
- onEofChunk(stream, state);
- } else {
- var er;
- if (!skipChunkCheck) er = chunkInvalid(state, chunk);
- if (er) {
- stream.emit('error', er);
- } else if (state.objectMode || chunk && chunk.length > 0) {
- if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
- chunk = _uint8ArrayToBuffer(chunk);
- }
-
- if (addToFront) {
- if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
- } else if (state.ended) {
- stream.emit('error', new Error('stream.push() after EOF'));
- } else {
- state.reading = false;
- if (state.decoder && !encoding) {
- chunk = state.decoder.write(chunk);
- if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
- } else {
- addChunk(stream, state, chunk, false);
- }
- }
- } else if (!addToFront) {
- state.reading = false;
- }
- }
-
- return needMoreData(state);
-}
-
-function addChunk(stream, state, chunk, addToFront) {
- if (state.flowing && state.length === 0 && !state.sync) {
- stream.emit('data', chunk);
- stream.read(0);
- } else {
- // update the buffer info.
- state.length += state.objectMode ? 1 : chunk.length;
- if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
-
- 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 TypeError('Invalid non-string/buffer chunk');
- }
- return er;
-}
-
-// if it's past the high water mark, we can push in some more.
-// Also, if we have no data yet, we can stand some
-// more bytes. This is to work around cases where hwm=0,
-// such as the repl. Also, if the push() triggered a
-// readable event, and the user called read(largeNumber) such that
-// needReadable was set, then we ought to push more, so that another
-// 'readable' event will be triggered.
-function needMoreData(state) {
- return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
-}
-
-Readable.prototype.isPaused = function () {
- return this._readableState.flowing === false;
-};
-
-// backwards compatibility.
-Readable.prototype.setEncoding = function (enc) {
- if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
- this._readableState.decoder = new StringDecoder(enc);
- this._readableState.encoding = enc;
- return this;
-};
-
-// Don't raise the hwm > 8MB
-var MAX_HWM = 0x800000;
-function computeNewHighWaterMark(n) {
- if (n >= MAX_HWM) {
- n = MAX_HWM;
- } else {
- // Get the next highest power of 2 to prevent increasing hwm excessively in
- // tiny amounts
- n--;
- n |= n >>> 1;
- n |= n >>> 2;
- n |= n >>> 4;
- n |= n >>> 8;
- n |= n >>> 16;
- n++;
- }
- 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.length >= state.highWaterMark || state.ended)) {
- debug('read: emitReadable', state.length, state.ended);
- if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
- return null;
- }
-
- n = howMuchToRead(n, state);
-
- // 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 = true;
- n = 0;
- } else {
- state.length -= n;
- }
-
- 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) {
- 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;
-
- // emit 'readable' now to make sure it gets picked up.
- 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;
- state.needReadable = false;
- if (!state.emittedReadable) {
- debug('emitReadable', state.flowing);
- state.emittedReadable = true;
- if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
- }
-}
-
-function emitReadable_(stream) {
- debug('emit readable');
- stream.emit('readable');
- flow(stream);
-}
-
-// at this point, the user has presumably seen the 'readable' event,
-// and called read() to consume some data. that may have triggered
-// in turn another _read(n) call, in which case reading = true if
-// it's in progress.
-// However, if we're not ended, or reading, and the length < hwm,
-// then go ahead and try to read some more preemptively.
-function maybeReadMore(stream, state) {
- if (!state.readingMore) {
- state.readingMore = true;
- pna.nextTick(maybeReadMore_, stream, state);
- }
-}
-
-function maybeReadMore_(stream, state) {
- var len = state.length;
- while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
- debug('maybeReadMore read 0');
- stream.read(0);
- if (len === state.length)
- // didn't get any data, stop spinning.
- break;else len = state.length;
- }
- state.readingMore = false;
-}
-
-// abstract method. to be overridden in specific implementation classes.
-// call cb(er, data) where data is <= n in length.
-// for virtual (non-string, non-buffer) streams, "length" is somewhat
-// arbitrary, and perhaps not very meaningful.
-Readable.prototype._read = function (n) {
- this.emit('error', new Error('_read() is not implemented'));
-};
-
-Readable.prototype.pipe = function (dest, pipeOpts) {
- var src = this;
- var state = this._readableState;
-
- switch (state.pipesCount) {
- case 0:
- state.pipes = dest;
- break;
- case 1:
- state.pipes = [state.pipes, dest];
- break;
- default:
- state.pipes.push(dest);
- break;
- }
- state.pipesCount += 1;
- debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
-
- var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
-
- var endFn = doEnd ? onend : unpipe;
- if (state.endEmitted) pna.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();
- }
-
- // If the user pushes more data while we're writing to dest then we'll end up
- // in ondata again. However, we only want to increase awaitDrain once because
- // dest will only emit one 'drain' event for the multiple writes.
- // => Introduce a guard on increasing awaitDrain.
- var increasedAwaitDrain = false;
- src.on('data', ondata);
- function ondata(chunk) {
- debug('ondata');
- increasedAwaitDrain = false;
- var ret = dest.write(chunk);
- if (false === ret && !increasedAwaitDrain) {
- // If the user unpiped during `dest.write()`, it is possible
- // to get stuck in a permanently paused state if that write
- // also returned false.
- // => Check whether `dest` is still a piping destination.
- if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
- debug('false write response, pause', src._readableState.awaitDrain);
- src._readableState.awaitDrain++;
- increasedAwaitDrain = true;
- }
- src.pause();
- }
- }
-
- // if the dest has an error, then stop piping into it.
- // however, don't suppress the throwing behavior for this.
- function onerror(er) {
- debug('onerror', er);
- unpipe();
- dest.removeListener('error', onerror);
- if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
- }
-
- // 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 () {
- 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, unpipeInfo);
- }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);
-
- if (ev === 'data') {
- // Start flowing on next tick if stream isn't explicitly paused
- if (this._readableState.flowing !== false) this.resume();
- } else if (ev === 'readable') {
- var state = this._readableState;
- if (!state.endEmitted && !state.readableListening) {
- state.readableListening = state.needReadable = true;
- state.emittedReadable = false;
- if (!state.reading) {
- pna.nextTick(nReadingNextTick, this);
- } else if (state.length) {
- emitReadable(this);
- }
- }
- }
-
- return res;
-};
-Readable.prototype.addListener = Readable.prototype.on;
-
-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');
- state.flowing = true;
- resume(this, state);
- }
- return this;
-};
-
-function resume(stream, state) {
- if (!state.resumeScheduled) {
- state.resumeScheduled = true;
- pna.nextTick(resume_, stream, state);
- }
-}
-
-function resume_(stream, state) {
- if (!state.reading) {
- debug('resume read 0');
- stream.read(0);
- }
-
- state.resumeScheduled = false;
- state.awaitDrain = 0;
- 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 (false !== this._readableState.flowing) {
- debug('pause');
- this._readableState.flowing = false;
- this.emit('pause');
- }
- 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 (method) {
- return function () {
- 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;
-};
-
-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 () {
- return this._readableState.highWaterMark;
- }
-});
-
-// exposed for testing purposes only.
-Readable._fromList = fromList;
-
-// 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.head.data;else ret = state.buffer.concat(state.length);
- state.buffer.clear();
- } else {
- // read part of list
- ret = fromListPartial(n, state.buffer, state.decoder);
- }
-
- return ret;
-}
-
-// Extracts only enough buffered data to satisfy the amount requested.
-// This function is designed to be inlinable, so please take care when making
-// changes to the function body.
-function fromListPartial(n, list, hasStrings) {
- var ret;
- if (n < list.head.data.length) {
- // slice is the same for buffers and strings
- ret = list.head.data.slice(0, n);
- list.head.data = list.head.data.slice(n);
- } else if (n === list.head.data.length) {
- // first chunk is a perfect match
- ret = list.shift();
- } else {
- // result spans more than one buffer
- ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
- }
- return ret;
-}
-
-// Copies a specified amount of characters from the list of buffered data
-// chunks.
-// This function is designed to be inlinable, so please take care when making
-// changes to the function body.
-function copyFromBufferString(n, list) {
- var p = list.head;
- var c = 1;
- var ret = p.data;
- n -= ret.length;
- while (p = p.next) {
- var str = p.data;
- var nb = n > str.length ? str.length : n;
- if (nb === str.length) ret += str;else ret += str.slice(0, n);
- n -= nb;
- if (n === 0) {
- if (nb === str.length) {
- ++c;
- if (p.next) list.head = p.next;else list.head = list.tail = null;
- } else {
- list.head = p;
- p.data = str.slice(nb);
- }
- break;
- }
- ++c;
- }
- list.length -= c;
- return ret;
-}
-
-// Copies a specified amount of bytes from the list of buffered data chunks.
-// This function is designed to be inlinable, so please take care when making
-// changes to the function body.
-function copyFromBuffer(n, list) {
- var ret = Buffer.allocUnsafe(n);
- var p = list.head;
- var c = 1;
- p.data.copy(ret);
- n -= p.data.length;
- while (p = p.next) {
- var buf = p.data;
- var nb = n > buf.length ? buf.length : n;
- buf.copy(ret, ret.length - n, 0, nb);
- n -= nb;
- if (n === 0) {
- if (nb === buf.length) {
- ++c;
- if (p.next) list.head = p.next;else list.head = list.tail = null;
- } else {
- list.head = p;
- p.data = buf.slice(nb);
- }
- break;
- }
- ++c;
- }
- list.length -= c;
- return ret;
-}
-
-function endReadable(stream) {
- var state = stream._readableState;
-
- // If we get here before consuming all the bytes, then that is a
- // bug in node. Should never happen.
- if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
-
- if (!state.endEmitted) {
- state.ended = true;
- pna.nextTick(endReadableNT, state, stream);
- }
-}
-
-function endReadableNT(state, stream) {
- // Check that we didn't get one last unshift.
- if (!state.endEmitted && state.length === 0) {
- state.endEmitted = true;
- stream.readable = false;
- stream.emit('end');
- }
-}
-
-function indexOf(xs, x) {
- for (var i = 0, l = xs.length; i < l; i++) {
- if (xs[i] === x) return i;
- }
- return -1;
-}
-}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"./_stream_duplex":40,"./internal/streams/BufferList":45,"./internal/streams/destroy":46,"./internal/streams/stream":47,"_process":34,"core-util-is":12,"events":13,"inherits":16,"isarray":18,"process-nextick-args":33,"safe-buffer":48,"string_decoder/":49,"util":7}],43:[function(require,module,exports){
-// 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 Duplex = require('./_stream_duplex');
-
-/**/
-var util = Object.create(require('core-util-is'));
-util.inherits = require('inherits');
-/**/
-
-util.inherits(Transform, Duplex);
-
-function afterTransform(er, data) {
- var ts = this._transformState;
- ts.transforming = false;
-
- var cb = ts.writecb;
-
- if (!cb) {
- return this.emit('error', new Error('write callback called multiple times'));
- }
-
- 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._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) {
- throw new Error('_transform() is not implemented');
-};
-
-Transform.prototype._write = function (chunk, encoding, cb) {
- var ts = this._transformState;
- ts.writecb = cb;
- ts.writechunk = chunk;
- ts.writeencoding = encoding;
- if (!ts.transforming) {
- var rs = this._readableState;
- if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
- }
-};
-
-// Doesn't matter what the args are here.
-// _transform does all the work.
-// That we got here means that the readable side wants more data.
-Transform.prototype._read = function (n) {
- var ts = this._transformState;
-
- if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
- ts.transforming = true;
- this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
- } 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) {
- var _this2 = this;
-
- Duplex.prototype._destroy.call(this, err, function (err2) {
- cb(err2);
- _this2.emit('close');
- });
-};
-
-function done(stream, er, data) {
- if (er) return stream.emit('error', er);
-
- if (data != null) // single equals check for both `null` and `undefined`
- stream.push(data);
-
- // if there's nothing in the write buffer, then that means
- // that nothing more will ever be provided
- if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
-
- if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
-
- return stream.push(null);
-}
-},{"./_stream_duplex":40,"core-util-is":12,"inherits":16}],44:[function(require,module,exports){
-(function (process,global,setImmediate){(function (){
-// 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';
-
-/**/
-
-var pna = require('process-nextick-args');
-/**/
-
-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 asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
-/**/
-
-/**/
-var Duplex;
-/**/
-
-Writable.WritableState = WritableState;
-
-/**/
-var util = Object.create(require('core-util-is'));
-util.inherits = require('inherits');
-/**/
-
-/**/
-var internalUtil = {
- deprecate: require('util-deprecate')
-};
-/**/
-
-/**/
-var Stream = require('./internal/streams/stream');
-/**/
-
-/**/
-
-var Buffer = require('safe-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');
-
-util.inherits(Writable, Stream);
-
-function nop() {}
-
-function WritableState(options, stream) {
- 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.
- var 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()
- var hwm = options.highWaterMark;
- var writableHwm = options.writableHighWaterMark;
- var defaultHwm = this.objectMode ? 16 : 16 * 1024;
-
- if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
-
- // cast to ints.
- this.highWaterMark = Math.floor(this.highWaterMark);
-
- // if _final has been called
- this.finalCalled = false;
-
- // drain event flag.
- this.needDrain = false;
- // at the start of calling end()
- this.ending = false;
- // when end() has been called, and returned
- this.ended = false;
- // when 'finish' is emitted
- this.finished = false;
-
- // has it been destroyed
- this.destroyed = false;
-
- // should we decode strings into buffers before passing to _write?
- // this is here so that some node-core streams can optimize string
- // handling at a lower level.
- var noDecode = options.decodeStrings === false;
- this.decodeStrings = !noDecode;
-
- // Crypto is kind of old and crusty. Historically, its default string
- // encoding is 'binary' so we have to make this configurable.
- // Everything else in the universe uses 'utf8', though.
- this.defaultEncoding = options.defaultEncoding || 'utf8';
-
- // not an actual buffer we keep track of, but a measurement
- // of how much we're waiting to get pushed to some underlying
- // socket or file.
- this.length = 0;
-
- // a flag to see when we're in the middle of a write.
- this.writing = false;
-
- // when true all writes will be buffered until .uncork() call
- this.corked = 0;
-
- // a flag to be able to tell if the onwrite cb is called immediately,
- // or on a later tick. We set this to true at first, because any
- // actions that shouldn't happen until "later" should generally also
- // not happen before the first write call.
- this.sync = true;
-
- // a flag to know if we're processing previously buffered items, which
- // may call the _write() callback in the same tick, so that we don't
- // end up in an overlapped onwrite situation.
- this.bufferProcessing = false;
-
- // the callback that's passed to _write(chunk,cb)
- this.onwrite = function (er) {
- onwrite(stream, er);
- };
-
- // the callback that the user supplies to write(chunk,encoding,cb)
- this.writecb = null;
-
- // the amount that is being written when _write is called.
- this.writelen = 0;
-
- this.bufferedRequest = null;
- this.lastBufferedRequest = null;
-
- // number of pending user-supplied write callbacks
- // this must be 0 before 'finish' can be emitted
- this.pendingcb = 0;
-
- // emit prefinish if the only thing we're waiting for is _write cbs
- // This is relevant for synchronous Transform streams
- this.prefinished = false;
-
- // True if the error was already emitted and should not be thrown again
- this.errorEmitted = false;
-
- // count buffered requests
- this.bufferedRequestCount = 0;
-
- // allocate the first CorkedRequest, there is always
- // one allocated and free to use, and we maintain at most two
- this.corkedRequestsFree = new CorkedRequest(this);
-}
-
-WritableState.prototype.getBuffer = function getBuffer() {
- var current = this.bufferedRequest;
- var out = [];
- while (current) {
- out.push(current);
- current = current.next;
- }
- return out;
-};
-
-(function () {
- try {
- Object.defineProperty(WritableState.prototype, 'buffer', {
- get: internalUtil.deprecate(function () {
- return this.getBuffer();
- }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
- });
- } catch (_) {}
-})();
-
-// Test _writableState for inheritance to account for Duplex streams,
-// whose prototype chain only points to Readable.
-var realHasInstance;
-if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
- realHasInstance = Function.prototype[Symbol.hasInstance];
- Object.defineProperty(Writable, Symbol.hasInstance, {
- value: function (object) {
- if (realHasInstance.call(this, object)) return true;
- if (this !== Writable) return false;
-
- return object && object._writableState instanceof WritableState;
- }
- });
-} else {
- realHasInstance = function (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.
- if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
- return new Writable(options);
- }
-
- this._writableState = new WritableState(options, this);
-
- // legacy.
- this.writable = true;
-
- if (options) {
- if (typeof options.write === 'function') this._write = options.write;
-
- if (typeof options.writev === 'function') this._writev = options.writev;
-
- if (typeof options.destroy === 'function') this._destroy = options.destroy;
-
- if (typeof options.final === 'function') this._final = options.final;
- }
-
- Stream.call(this);
-}
-
-// Otherwise people can pipe Writable streams, which is just wrong.
-Writable.prototype.pipe = function () {
- this.emit('error', new Error('Cannot pipe, not readable'));
-};
-
-function writeAfterEnd(stream, cb) {
- var er = new Error('write after end');
- // TODO: defer error events consistently everywhere, not just the cb
- stream.emit('error', er);
- pna.nextTick(cb, er);
-}
-
-// Checks that a user-supplied chunk is valid, especially for the particular
-// mode the stream is in. Currently this means that `null` is never accepted
-// and undefined/non-string values are only allowed in object mode.
-function validChunk(stream, state, chunk, cb) {
- var valid = true;
- var er = false;
-
- if (chunk === null) {
- er = new TypeError('May not write null values to stream');
- } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
- er = new TypeError('Invalid non-string/buffer chunk');
- }
- if (er) {
- stream.emit('error', er);
- pna.nextTick(cb, er);
- valid = false;
- }
- return valid;
-}
-
-Writable.prototype.write = function (chunk, encoding, cb) {
- var state = this._writableState;
- var ret = false;
- var isBuf = !state.objectMode && _isUint8Array(chunk);
-
- if (isBuf && !Buffer.isBuffer(chunk)) {
- chunk = _uint8ArrayToBuffer(chunk);
- }
-
- 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.ended) 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 () {
- var state = this._writableState;
-
- state.corked++;
-};
-
-Writable.prototype.uncork = function () {
- var state = this._writableState;
-
- if (state.corked) {
- state.corked--;
-
- if (!state.writing && !state.corked && !state.finished && !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 TypeError('Unknown encoding: ' + encoding);
- this._writableState.defaultEncoding = encoding;
- return this;
-};
-
-function decodeChunk(state, chunk, encoding) {
- if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
- chunk = Buffer.from(chunk, encoding);
- }
- return chunk;
-}
-
-Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
- // making it explicit this property is not enumerable
- // because otherwise some prototype manipulation in
- // userland will fail
- enumerable: false,
- get: function () {
- return this._writableState.highWaterMark;
- }
-});
-
-// 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 (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
- state.sync = false;
-}
-
-function onwriteError(stream, state, sync, er, cb) {
- --state.pendingcb;
-
- if (sync) {
- // defer the callback if we are being called synchronously
- // to avoid piling up things on the stack
- pna.nextTick(cb, er);
- // this can emit finish, and it will always happen
- // after error
- pna.nextTick(finishMaybe, stream, state);
- stream._writableState.errorEmitted = true;
- stream.emit('error', er);
- } else {
- // the caller expect this to happen before if
- // it is async
- cb(er);
- stream._writableState.errorEmitted = true;
- stream.emit('error', er);
- // this can emit finish, but finish must
- // always follow error
- finishMaybe(stream, state);
- }
-}
-
-function onwriteStateUpdate(state) {
- state.writing = false;
- state.writecb = null;
- state.length -= state.writelen;
- state.writelen = 0;
-}
-
-function onwrite(stream, er) {
- var state = stream._writableState;
- var sync = state.sync;
- var cb = state.writecb;
-
- onwriteStateUpdate(state);
-
- if (er) onwriteError(stream, state, sync, er, cb);else {
- // Check if we're actually ready to finish, but don't emit yet
- var finished = needFinish(state);
-
- if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
- clearBuffer(stream, state);
- }
-
- if (sync) {
- /**/
- asyncWrite(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 Error('_write() is not implemented'));
-};
-
-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 && !state.finished) endWritable(this, state, cb);
-};
-
-function needFinish(state) {
- return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
-}
-function callFinal(stream, state) {
- stream._final(function (err) {
- state.pendingcb--;
- if (err) {
- stream.emit('error', err);
- }
- state.prefinished = true;
- stream.emit('prefinish');
- finishMaybe(stream, state);
- });
-}
-function prefinish(stream, state) {
- if (!state.prefinished && !state.finalCalled) {
- if (typeof stream._final === 'function') {
- state.pendingcb++;
- state.finalCalled = true;
- pna.nextTick(callFinal, stream, state);
- } else {
- state.prefinished = true;
- stream.emit('prefinish');
- }
- }
-}
-
-function finishMaybe(stream, state) {
- var need = needFinish(state);
- if (need) {
- prefinish(stream, state);
- if (state.pendingcb === 0) {
- state.finished = true;
- stream.emit('finish');
- }
- }
- return need;
-}
-
-function endWritable(stream, state, cb) {
- state.ending = true;
- finishMaybe(stream, state);
- if (cb) {
- if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
- }
- state.ended = true;
- stream.writable = false;
-}
-
-function onCorkedFinish(corkReq, state, err) {
- var entry = corkReq.entry;
- corkReq.entry = null;
- while (entry) {
- var cb = entry.callback;
- state.pendingcb--;
- cb(err);
- entry = entry.next;
- }
- if (state.corkedRequestsFree) {
- state.corkedRequestsFree.next = corkReq;
- } else {
- state.corkedRequestsFree = corkReq;
- }
-}
-
-Object.defineProperty(Writable.prototype, 'destroyed', {
- get: function () {
- if (this._writableState === undefined) {
- return false;
- }
- return this._writableState.destroyed;
- },
- set: function (value) {
- // we ignore the value if the stream
- // has not been initialized yet
- if (!this._writableState) {
- return;
- }
-
- // backward compatibility, the user is explicitly
- // managing destroyed
- this._writableState.destroyed = value;
- }
-});
-
-Writable.prototype.destroy = destroyImpl.destroy;
-Writable.prototype._undestroy = destroyImpl.undestroy;
-Writable.prototype._destroy = function (err, cb) {
- this.end();
- cb(err);
-};
-}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
-},{"./_stream_duplex":40,"./internal/streams/destroy":46,"./internal/streams/stream":47,"_process":34,"core-util-is":12,"inherits":16,"process-nextick-args":33,"safe-buffer":48,"timers":76,"util-deprecate":79}],45:[function(require,module,exports){
-'use strict';
-
-function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
-
-var Buffer = require('safe-buffer').Buffer;
-var util = require('util');
-
-function copyBuffer(src, target, offset) {
- src.copy(target, offset);
-}
-
-module.exports = function () {
- function BufferList() {
- _classCallCheck(this, BufferList);
-
- this.head = null;
- this.tail = null;
- this.length = 0;
- }
-
- BufferList.prototype.push = function push(v) {
- var entry = { data: v, next: null };
- if (this.length > 0) this.tail.next = entry;else this.head = entry;
- this.tail = entry;
- ++this.length;
- };
-
- BufferList.prototype.unshift = function unshift(v) {
- var entry = { data: v, next: this.head };
- if (this.length === 0) this.tail = entry;
- this.head = entry;
- ++this.length;
- };
-
- BufferList.prototype.shift = function shift() {
- if (this.length === 0) return;
- var ret = this.head.data;
- if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
- --this.length;
- return ret;
- };
-
- BufferList.prototype.clear = function clear() {
- this.head = this.tail = null;
- this.length = 0;
- };
-
- BufferList.prototype.join = function join(s) {
- if (this.length === 0) return '';
- var p = this.head;
- var ret = '' + p.data;
- while (p = p.next) {
- ret += s + p.data;
- }return ret;
- };
-
- BufferList.prototype.concat = function concat(n) {
- if (this.length === 0) return Buffer.alloc(0);
- if (this.length === 1) return this.head.data;
- var ret = Buffer.allocUnsafe(n >>> 0);
- var p = this.head;
- var i = 0;
- while (p) {
- copyBuffer(p.data, ret, i);
- i += p.data.length;
- p = p.next;
- }
- return ret;
- };
-
- return BufferList;
-}();
-
-if (util && util.inspect && util.inspect.custom) {
- module.exports.prototype[util.inspect.custom] = function () {
- var obj = util.inspect({ length: this.length });
- return this.constructor.name + ' ' + obj;
- };
-}
-},{"safe-buffer":48,"util":7}],46:[function(require,module,exports){
-'use strict';
-
-/**/
-
-var pna = require('process-nextick-args');
-/**/
-
-// 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 && (!this._writableState || !this._writableState.errorEmitted)) {
- pna.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) {
- pna.nextTick(emitErrorNT, _this, err);
- if (_this._writableState) {
- _this._writableState.errorEmitted = true;
- }
- } else if (cb) {
- cb(err);
- }
- });
-
- return this;
-}
-
-function undestroy() {
- if (this._readableState) {
- this._readableState.destroyed = false;
- this._readableState.reading = false;
- this._readableState.ended = false;
- this._readableState.endEmitted = false;
- }
-
- if (this._writableState) {
- this._writableState.destroyed = false;
- this._writableState.ended = false;
- this._writableState.ending = false;
- this._writableState.finished = false;
- this._writableState.errorEmitted = false;
- }
-}
-
-function emitErrorNT(self, err) {
- self.emit('error', err);
-}
-
-module.exports = {
- destroy: destroy,
- undestroy: undestroy
-};
-},{"process-nextick-args":33}],47:[function(require,module,exports){
-module.exports = require('events').EventEmitter;
-
-},{"events":13}],48:[function(require,module,exports){
-/* 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)
-}
-
-},{"buffer":10}],49:[function(require,module,exports){
-// 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) : '';
-}
-},{"safe-buffer":48}],50:[function(require,module,exports){
-module.exports = require('./readable').PassThrough
-
-},{"./readable":51}],51:[function(require,module,exports){
-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');
-
-},{"./lib/_stream_duplex.js":40,"./lib/_stream_passthrough.js":41,"./lib/_stream_readable.js":42,"./lib/_stream_transform.js":43,"./lib/_stream_writable.js":44}],52:[function(require,module,exports){
-module.exports = require('./readable').Transform
-
-},{"./readable":51}],53:[function(require,module,exports){
-module.exports = require('./lib/_stream_writable.js');
-
-},{"./lib/_stream_writable.js":44}],54:[function(require,module,exports){
-/*! 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)
-}
-
-},{"buffer":10}],55:[function(require,module,exports){
-// 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.
-
-module.exports = Stream;
-
-var EE = require('events').EventEmitter;
-var inherits = require('inherits');
-
-inherits(Stream, EE);
-Stream.Readable = require('readable-stream/readable.js');
-Stream.Writable = require('readable-stream/writable.js');
-Stream.Duplex = require('readable-stream/duplex.js');
-Stream.Transform = require('readable-stream/transform.js');
-Stream.PassThrough = require('readable-stream/passthrough.js');
-
-// Backwards-compat with node 0.4.x
-Stream.Stream = Stream;
-
-
-
-// old-style streams. Note that the pipe method (the only relevant
-// part of this class) is overridden in the Readable class.
-
-function Stream() {
- EE.call(this);
-}
-
-Stream.prototype.pipe = function(dest, options) {
- var source = this;
-
- function ondata(chunk) {
- if (dest.writable) {
- if (false === dest.write(chunk) && source.pause) {
- source.pause();
- }
- }
- }
-
- source.on('data', ondata);
-
- function ondrain() {
- if (source.readable && source.resume) {
- source.resume();
- }
- }
-
- dest.on('drain', ondrain);
-
- // If the 'end' option is not supplied, dest.end() will be called when
- // source gets the 'end' or 'close' events. Only dest.end() once.
- if (!dest._isStdio && (!options || options.end !== false)) {
- source.on('end', onend);
- source.on('close', onclose);
- }
-
- var didOnEnd = false;
- function onend() {
- if (didOnEnd) return;
- didOnEnd = true;
-
- dest.end();
- }
-
-
- function onclose() {
- if (didOnEnd) return;
- didOnEnd = true;
-
- if (typeof dest.destroy === 'function') dest.destroy();
- }
-
- // don't leave dangling pipes when there are errors.
- function onerror(er) {
- cleanup();
- if (EE.listenerCount(this, 'error') === 0) {
- throw er; // Unhandled stream error in pipe.
- }
- }
-
- source.on('error', onerror);
- dest.on('error', onerror);
-
- // remove all the event listeners that were added.
- function cleanup() {
- source.removeListener('data', ondata);
- dest.removeListener('drain', ondrain);
-
- source.removeListener('end', onend);
- source.removeListener('close', onclose);
-
- source.removeListener('error', onerror);
- dest.removeListener('error', onerror);
-
- source.removeListener('end', cleanup);
- source.removeListener('close', cleanup);
-
- dest.removeListener('close', cleanup);
- }
-
- source.on('end', cleanup);
- source.on('close', cleanup);
-
- dest.on('close', cleanup);
-
- dest.emit('pipe', source);
-
- // Allow for unix-like usage: A.pipe(B).pipe(C)
- return dest;
-};
-
-},{"events":13,"inherits":16,"readable-stream/duplex.js":39,"readable-stream/passthrough.js":50,"readable-stream/readable.js":51,"readable-stream/transform.js":52,"readable-stream/writable.js":53}],56:[function(require,module,exports){
-(function (global){(function (){
-var ClientRequest = require('./lib/request')
-var response = require('./lib/response')
-var extend = require('xtend')
-var statusCodes = require('builtin-status-codes')
-var url = require('url')
-
-var http = exports
-
-http.request = function (opts, cb) {
- if (typeof opts === 'string')
- opts = url.parse(opts)
- else
- opts = extend(opts)
-
- // Normally, the page is loaded from http or https, so not specifying a protocol
- // will result in a (valid) protocol-relative url. However, this won't work if
- // the protocol is something else, like 'file:'
- var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''
-
- var protocol = opts.protocol || defaultProtocol
- var host = opts.hostname || opts.host
- var port = opts.port
- var path = opts.path || '/'
-
- // Necessary for IPv6 addresses
- if (host && host.indexOf(':') !== -1)
- host = '[' + host + ']'
-
- // This may be a relative url. The browser should always be able to interpret it correctly.
- opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path
- opts.method = (opts.method || 'GET').toUpperCase()
- opts.headers = opts.headers || {}
-
- // Also valid opts.auth, opts.mode
-
- var req = new ClientRequest(opts)
- if (cb)
- req.on('response', cb)
- return req
-}
-
-http.get = function get (opts, cb) {
- var req = http.request(opts, cb)
- req.end()
- return req
-}
-
-http.ClientRequest = ClientRequest
-http.IncomingMessage = response.IncomingMessage
-
-http.Agent = function () {}
-http.Agent.defaultMaxSockets = 4
-
-http.globalAgent = new http.Agent()
-
-http.STATUS_CODES = statusCodes
-
-http.METHODS = [
- 'CHECKOUT',
- 'CONNECT',
- 'COPY',
- 'DELETE',
- 'GET',
- 'HEAD',
- 'LOCK',
- 'M-SEARCH',
- 'MERGE',
- 'MKACTIVITY',
- 'MKCOL',
- 'MOVE',
- 'NOTIFY',
- 'OPTIONS',
- 'PATCH',
- 'POST',
- 'PROPFIND',
- 'PROPPATCH',
- 'PURGE',
- 'PUT',
- 'REPORT',
- 'SEARCH',
- 'SUBSCRIBE',
- 'TRACE',
- 'UNLOCK',
- 'UNSUBSCRIBE'
-]
-}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"./lib/request":58,"./lib/response":59,"builtin-status-codes":11,"url":77,"xtend":83}],57:[function(require,module,exports){
-(function (global){(function (){
-exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream)
-
-exports.writableStream = isFunction(global.WritableStream)
-
-exports.abortController = isFunction(global.AbortController)
-
-// The xhr request to example.com may violate some restrictive CSP configurations,
-// so if we're running in a browser that supports `fetch`, avoid calling getXHR()
-// and assume support for certain features below.
-var xhr
-function getXHR () {
- // Cache the xhr value
- if (xhr !== undefined) return xhr
-
- if (global.XMLHttpRequest) {
- xhr = new global.XMLHttpRequest()
- // If XDomainRequest is available (ie only, where xhr might not work
- // cross domain), use the page location. Otherwise use example.com
- // Note: this doesn't actually make an http request.
- try {
- xhr.open('GET', global.XDomainRequest ? '/' : 'https://example.com')
- } catch(e) {
- xhr = null
- }
- } else {
- // Service workers don't have XHR
- xhr = null
- }
- return xhr
-}
-
-function checkTypeSupport (type) {
- var xhr = getXHR()
- if (!xhr) return false
- try {
- xhr.responseType = type
- return xhr.responseType === type
- } catch (e) {}
- return false
-}
-
-// If fetch is supported, then arraybuffer will be supported too. Skip calling
-// checkTypeSupport(), since that calls getXHR().
-exports.arraybuffer = exports.fetch || checkTypeSupport('arraybuffer')
-
-// These next two tests unavoidably show warnings in Chrome. Since fetch will always
-// be used if it's available, just return false for these to avoid the warnings.
-exports.msstream = !exports.fetch && checkTypeSupport('ms-stream')
-exports.mozchunkedarraybuffer = !exports.fetch && checkTypeSupport('moz-chunked-arraybuffer')
-
-// If fetch is supported, then overrideMimeType will be supported too. Skip calling
-// getXHR().
-exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false)
-
-function isFunction (value) {
- return typeof value === 'function'
-}
-
-xhr = null // Help gc
-
-}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{}],58:[function(require,module,exports){
-(function (process,global,Buffer){(function (){
-var capability = require('./capability')
-var inherits = require('inherits')
-var response = require('./response')
-var stream = require('readable-stream')
-
-var IncomingMessage = response.IncomingMessage
-var rStates = response.readyStates
-
-function decideMode (preferBinary, useFetch) {
- if (capability.fetch && useFetch) {
- return 'fetch'
- } else if (capability.mozchunkedarraybuffer) {
- return 'moz-chunked-arraybuffer'
- } else if (capability.msstream) {
- return 'ms-stream'
- } else if (capability.arraybuffer && preferBinary) {
- return 'arraybuffer'
- } else {
- return 'text'
- }
-}
-
-var ClientRequest = module.exports = function (opts) {
- var self = this
- stream.Writable.call(self)
-
- self._opts = opts
- self._body = []
- self._headers = {}
- if (opts.auth)
- self.setHeader('Authorization', 'Basic ' + Buffer.from(opts.auth).toString('base64'))
- Object.keys(opts.headers).forEach(function (name) {
- self.setHeader(name, opts.headers[name])
- })
-
- var preferBinary
- var useFetch = true
- if (opts.mode === 'disable-fetch' || ('requestTimeout' in opts && !capability.abortController)) {
- // If the use of XHR should be preferred. Not typically needed.
- useFetch = false
- preferBinary = true
- } else if (opts.mode === 'prefer-streaming') {
- // If streaming is a high priority but binary compatibility and
- // the accuracy of the 'content-type' header aren't
- preferBinary = false
- } else if (opts.mode === 'allow-wrong-content-type') {
- // If streaming is more important than preserving the 'content-type' header
- preferBinary = !capability.overrideMimeType
- } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') {
- // Use binary if text streaming may corrupt data or the content-type header, or for speed
- preferBinary = true
- } else {
- throw new Error('Invalid value for opts.mode')
- }
- self._mode = decideMode(preferBinary, useFetch)
- self._fetchTimer = null
- self._socketTimeout = null
- self._socketTimer = null
-
- self.on('finish', function () {
- self._onFinish()
- })
-}
-
-inherits(ClientRequest, stream.Writable)
-
-ClientRequest.prototype.setHeader = function (name, value) {
- var self = this
- var lowerName = name.toLowerCase()
- // This check is not necessary, but it prevents warnings from browsers about setting unsafe
- // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but
- // http-browserify did it, so I will too.
- if (unsafeHeaders.indexOf(lowerName) !== -1)
- return
-
- self._headers[lowerName] = {
- name: name,
- value: value
- }
-}
-
-ClientRequest.prototype.getHeader = function (name) {
- var header = this._headers[name.toLowerCase()]
- if (header)
- return header.value
- return null
-}
-
-ClientRequest.prototype.removeHeader = function (name) {
- var self = this
- delete self._headers[name.toLowerCase()]
-}
-
-ClientRequest.prototype._onFinish = function () {
- var self = this
-
- if (self._destroyed)
- return
- var opts = self._opts
-
- if ('timeout' in opts && opts.timeout !== 0) {
- self.setTimeout(opts.timeout)
- }
-
- var headersObj = self._headers
- var body = null
- if (opts.method !== 'GET' && opts.method !== 'HEAD') {
- body = new Blob(self._body, {
- type: (headersObj['content-type'] || {}).value || ''
- });
- }
-
- // create flattened list of headers
- var headersList = []
- Object.keys(headersObj).forEach(function (keyName) {
- var name = headersObj[keyName].name
- var value = headersObj[keyName].value
- if (Array.isArray(value)) {
- value.forEach(function (v) {
- headersList.push([name, v])
- })
- } else {
- headersList.push([name, value])
- }
- })
-
- if (self._mode === 'fetch') {
- var signal = null
- if (capability.abortController) {
- var controller = new AbortController()
- signal = controller.signal
- self._fetchAbortController = controller
-
- if ('requestTimeout' in opts && opts.requestTimeout !== 0) {
- self._fetchTimer = global.setTimeout(function () {
- self.emit('requestTimeout')
- if (self._fetchAbortController)
- self._fetchAbortController.abort()
- }, opts.requestTimeout)
- }
- }
-
- global.fetch(self._opts.url, {
- method: self._opts.method,
- headers: headersList,
- body: body || undefined,
- mode: 'cors',
- credentials: opts.withCredentials ? 'include' : 'same-origin',
- signal: signal
- }).then(function (response) {
- self._fetchResponse = response
- self._resetTimers(false)
- self._connect()
- }, function (reason) {
- self._resetTimers(true)
- if (!self._destroyed)
- self.emit('error', reason)
- })
- } else {
- var xhr = self._xhr = new global.XMLHttpRequest()
- try {
- xhr.open(self._opts.method, self._opts.url, true)
- } catch (err) {
- process.nextTick(function () {
- self.emit('error', err)
- })
- return
- }
-
- // Can't set responseType on really old browsers
- if ('responseType' in xhr)
- xhr.responseType = self._mode
-
- if ('withCredentials' in xhr)
- xhr.withCredentials = !!opts.withCredentials
-
- if (self._mode === 'text' && 'overrideMimeType' in xhr)
- xhr.overrideMimeType('text/plain; charset=x-user-defined')
-
- if ('requestTimeout' in opts) {
- xhr.timeout = opts.requestTimeout
- xhr.ontimeout = function () {
- self.emit('requestTimeout')
- }
- }
-
- headersList.forEach(function (header) {
- xhr.setRequestHeader(header[0], header[1])
- })
-
- self._response = null
- xhr.onreadystatechange = function () {
- switch (xhr.readyState) {
- case rStates.LOADING:
- case rStates.DONE:
- self._onXHRProgress()
- break
- }
- }
- // Necessary for streaming in Firefox, since xhr.response is ONLY defined
- // in onprogress, not in onreadystatechange with xhr.readyState = 3
- if (self._mode === 'moz-chunked-arraybuffer') {
- xhr.onprogress = function () {
- self._onXHRProgress()
- }
- }
-
- xhr.onerror = function () {
- if (self._destroyed)
- return
- self._resetTimers(true)
- self.emit('error', new Error('XHR error'))
- }
-
- try {
- xhr.send(body)
- } catch (err) {
- process.nextTick(function () {
- self.emit('error', err)
- })
- return
- }
- }
-}
-
-/**
- * Checks if xhr.status is readable and non-zero, indicating no error.
- * Even though the spec says it should be available in readyState 3,
- * accessing it throws an exception in IE8
- */
-function statusValid (xhr) {
- try {
- var status = xhr.status
- return (status !== null && status !== 0)
- } catch (e) {
- return false
- }
-}
-
-ClientRequest.prototype._onXHRProgress = function () {
- var self = this
-
- self._resetTimers(false)
-
- if (!statusValid(self._xhr) || self._destroyed)
- return
-
- if (!self._response)
- self._connect()
-
- self._response._onXHRProgress(self._resetTimers.bind(self))
-}
-
-ClientRequest.prototype._connect = function () {
- var self = this
-
- if (self._destroyed)
- return
-
- self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode, self._resetTimers.bind(self))
- self._response.on('error', function(err) {
- self.emit('error', err)
- })
-
- self.emit('response', self._response)
-}
-
-ClientRequest.prototype._write = function (chunk, encoding, cb) {
- var self = this
-
- self._body.push(chunk)
- cb()
-}
-
-ClientRequest.prototype._resetTimers = function (done) {
- var self = this
-
- global.clearTimeout(self._socketTimer)
- self._socketTimer = null
-
- if (done) {
- global.clearTimeout(self._fetchTimer)
- self._fetchTimer = null
- } else if (self._socketTimeout) {
- self._socketTimer = global.setTimeout(function () {
- self.emit('timeout')
- }, self._socketTimeout)
- }
-}
-
-ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function (err) {
- var self = this
- self._destroyed = true
- self._resetTimers(true)
- if (self._response)
- self._response._destroyed = true
- if (self._xhr)
- self._xhr.abort()
- else if (self._fetchAbortController)
- self._fetchAbortController.abort()
-
- if (err)
- self.emit('error', err)
-}
-
-ClientRequest.prototype.end = function (data, encoding, cb) {
- var self = this
- if (typeof data === 'function') {
- cb = data
- data = undefined
- }
-
- stream.Writable.prototype.end.call(self, data, encoding, cb)
-}
-
-ClientRequest.prototype.setTimeout = function (timeout, cb) {
- var self = this
-
- if (cb)
- self.once('timeout', cb)
-
- self._socketTimeout = timeout
- self._resetTimers(false)
-}
-
-ClientRequest.prototype.flushHeaders = function () {}
-ClientRequest.prototype.setNoDelay = function () {}
-ClientRequest.prototype.setSocketKeepAlive = function () {}
-
-// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method
-var unsafeHeaders = [
- 'accept-charset',
- 'accept-encoding',
- 'access-control-request-headers',
- 'access-control-request-method',
- 'connection',
- 'content-length',
- 'cookie',
- 'cookie2',
- 'date',
- 'dnt',
- 'expect',
- 'host',
- 'keep-alive',
- 'origin',
- 'referer',
- 'te',
- 'trailer',
- 'transfer-encoding',
- 'upgrade',
- 'via'
-]
-
-}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
-},{"./capability":57,"./response":59,"_process":34,"buffer":10,"inherits":16,"readable-stream":74}],59:[function(require,module,exports){
-(function (process,global,Buffer){(function (){
-var capability = require('./capability')
-var inherits = require('inherits')
-var stream = require('readable-stream')
-
-var rStates = exports.readyStates = {
- UNSENT: 0,
- OPENED: 1,
- HEADERS_RECEIVED: 2,
- LOADING: 3,
- DONE: 4
-}
-
-var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode, resetTimers) {
- var self = this
- stream.Readable.call(self)
-
- self._mode = mode
- self.headers = {}
- self.rawHeaders = []
- self.trailers = {}
- self.rawTrailers = []
-
- // Fake the 'close' event, but only once 'end' fires
- self.on('end', function () {
- // The nextTick is necessary to prevent the 'request' module from causing an infinite loop
- process.nextTick(function () {
- self.emit('close')
- })
- })
-
- if (mode === 'fetch') {
- self._fetchResponse = response
-
- self.url = response.url
- self.statusCode = response.status
- self.statusMessage = response.statusText
-
- response.headers.forEach(function (header, key){
- self.headers[key.toLowerCase()] = header
- self.rawHeaders.push(key, header)
- })
-
- if (capability.writableStream) {
- var writable = new WritableStream({
- write: function (chunk) {
- resetTimers(false)
- return new Promise(function (resolve, reject) {
- if (self._destroyed) {
- reject()
- } else if(self.push(Buffer.from(chunk))) {
- resolve()
- } else {
- self._resumeFetch = resolve
- }
- })
- },
- close: function () {
- resetTimers(true)
- if (!self._destroyed)
- self.push(null)
- },
- abort: function (err) {
- resetTimers(true)
- if (!self._destroyed)
- self.emit('error', err)
- }
- })
-
- try {
- response.body.pipeTo(writable).catch(function (err) {
- resetTimers(true)
- if (!self._destroyed)
- self.emit('error', err)
- })
- return
- } catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this
- }
- // fallback for when writableStream or pipeTo aren't available
- var reader = response.body.getReader()
- function read () {
- reader.read().then(function (result) {
- if (self._destroyed)
- return
- resetTimers(result.done)
- if (result.done) {
- self.push(null)
- return
- }
- self.push(Buffer.from(result.value))
- read()
- }).catch(function (err) {
- resetTimers(true)
- if (!self._destroyed)
- self.emit('error', err)
- })
- }
- read()
- } else {
- self._xhr = xhr
- self._pos = 0
-
- self.url = xhr.responseURL
- self.statusCode = xhr.status
- self.statusMessage = xhr.statusText
- var headers = xhr.getAllResponseHeaders().split(/\r?\n/)
- headers.forEach(function (header) {
- var matches = header.match(/^([^:]+):\s*(.*)/)
- if (matches) {
- var key = matches[1].toLowerCase()
- if (key === 'set-cookie') {
- if (self.headers[key] === undefined) {
- self.headers[key] = []
- }
- self.headers[key].push(matches[2])
- } else if (self.headers[key] !== undefined) {
- self.headers[key] += ', ' + matches[2]
- } else {
- self.headers[key] = matches[2]
- }
- self.rawHeaders.push(matches[1], matches[2])
- }
- })
-
- self._charset = 'x-user-defined'
- if (!capability.overrideMimeType) {
- var mimeType = self.rawHeaders['mime-type']
- if (mimeType) {
- var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/)
- if (charsetMatch) {
- self._charset = charsetMatch[1].toLowerCase()
- }
- }
- if (!self._charset)
- self._charset = 'utf-8' // best guess
- }
- }
-}
-
-inherits(IncomingMessage, stream.Readable)
-
-IncomingMessage.prototype._read = function () {
- var self = this
-
- var resolve = self._resumeFetch
- if (resolve) {
- self._resumeFetch = null
- resolve()
- }
-}
-
-IncomingMessage.prototype._onXHRProgress = function (resetTimers) {
- var self = this
-
- var xhr = self._xhr
-
- var response = null
- switch (self._mode) {
- case 'text':
- response = xhr.responseText
- if (response.length > self._pos) {
- var newData = response.substr(self._pos)
- if (self._charset === 'x-user-defined') {
- var buffer = Buffer.alloc(newData.length)
- for (var i = 0; i < newData.length; i++)
- buffer[i] = newData.charCodeAt(i) & 0xff
-
- self.push(buffer)
- } else {
- self.push(newData, self._charset)
- }
- self._pos = response.length
- }
- break
- case 'arraybuffer':
- if (xhr.readyState !== rStates.DONE || !xhr.response)
- break
- response = xhr.response
- self.push(Buffer.from(new Uint8Array(response)))
- break
- case 'moz-chunked-arraybuffer': // take whole
- response = xhr.response
- if (xhr.readyState !== rStates.LOADING || !response)
- break
- self.push(Buffer.from(new Uint8Array(response)))
- break
- case 'ms-stream':
- response = xhr.response
- if (xhr.readyState !== rStates.LOADING)
- break
- var reader = new global.MSStreamReader()
- reader.onprogress = function () {
- if (reader.result.byteLength > self._pos) {
- self.push(Buffer.from(new Uint8Array(reader.result.slice(self._pos))))
- self._pos = reader.result.byteLength
- }
- }
- reader.onload = function () {
- resetTimers(true)
- self.push(null)
- }
- // reader.onerror = ??? // TODO: this
- reader.readAsArrayBuffer(response)
- break
- }
-
- // The ms-stream case handles end separately in reader.onload()
- if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') {
- resetTimers(true)
- self.push(null)
- }
-}
-
-}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
-},{"./capability":57,"_process":34,"buffer":10,"inherits":16,"readable-stream":74}],60:[function(require,module,exports){
-'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;
-
-},{}],61:[function(require,module,exports){
-(function (process){(function (){
-// 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;
- }
-});
-}).call(this)}).call(this,require('_process'))
-},{"./_stream_readable":63,"./_stream_writable":65,"_process":34,"inherits":16}],62:[function(require,module,exports){
-// 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);
-};
-},{"./_stream_transform":64,"inherits":16}],63:[function(require,module,exports){
-(function (process,global){(function (){
-// 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;
-}
-}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"../errors":60,"./_stream_duplex":61,"./internal/streams/async_iterator":66,"./internal/streams/buffer_list":67,"./internal/streams/destroy":68,"./internal/streams/from":70,"./internal/streams/state":72,"./internal/streams/stream":73,"_process":34,"buffer":10,"events":13,"inherits":16,"string_decoder/":75,"util":7}],64:[function(require,module,exports){
-// 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);
-}
-},{"../errors":60,"./_stream_duplex":61,"inherits":16}],65:[function(require,module,exports){
-(function (process,global){(function (){
-// 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);
-};
-}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"../errors":60,"./_stream_duplex":61,"./internal/streams/destroy":68,"./internal/streams/state":72,"./internal/streams/stream":73,"_process":34,"buffer":10,"inherits":16,"util-deprecate":79}],66:[function(require,module,exports){
-(function (process){(function (){
-'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;
-}).call(this)}).call(this,require('_process'))
-},{"./end-of-stream":69,"_process":34}],67:[function(require,module,exports){
-'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;
-}();
-},{"buffer":10,"util":7}],68:[function(require,module,exports){
-(function (process){(function (){
-'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
-};
-}).call(this)}).call(this,require('_process'))
-},{"_process":34}],69:[function(require,module,exports){
-// 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;
-},{"../../../errors":60}],70:[function(require,module,exports){
-module.exports = function () {
- throw new Error('Readable.from is not available in the browser')
-};
-
-},{}],71:[function(require,module,exports){
-// 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;
-},{"../../../errors":60,"./end-of-stream":69}],72:[function(require,module,exports){
-'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
-};
-},{"../../../errors":60}],73:[function(require,module,exports){
-arguments[4][47][0].apply(exports,arguments)
-},{"dup":47,"events":13}],74:[function(require,module,exports){
-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');
-
-},{"./lib/_stream_duplex.js":61,"./lib/_stream_passthrough.js":62,"./lib/_stream_readable.js":63,"./lib/_stream_transform.js":64,"./lib/_stream_writable.js":65,"./lib/internal/streams/end-of-stream.js":69,"./lib/internal/streams/pipeline.js":71}],75:[function(require,module,exports){
-arguments[4][49][0].apply(exports,arguments)
-},{"dup":49,"safe-buffer":54}],76:[function(require,module,exports){
-(function (setImmediate,clearImmediate){(function (){
-var nextTick = require('process/browser.js').nextTick;
-var apply = Function.prototype.apply;
-var slice = Array.prototype.slice;
-var immediateIds = {};
-var nextImmediateId = 0;
-
-// DOM APIs, for completeness
-
-exports.setTimeout = function() {
- return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
-};
-exports.setInterval = function() {
- return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
-};
-exports.clearTimeout =
-exports.clearInterval = function(timeout) { timeout.close(); };
-
-function Timeout(id, clearFn) {
- this._id = id;
- this._clearFn = clearFn;
-}
-Timeout.prototype.unref = Timeout.prototype.ref = function() {};
-Timeout.prototype.close = function() {
- this._clearFn.call(window, this._id);
-};
-
-// Does not start the time, just sets up the members needed.
-exports.enroll = function(item, msecs) {
- clearTimeout(item._idleTimeoutId);
- item._idleTimeout = msecs;
-};
-
-exports.unenroll = function(item) {
- clearTimeout(item._idleTimeoutId);
- item._idleTimeout = -1;
-};
-
-exports._unrefActive = exports.active = function(item) {
- clearTimeout(item._idleTimeoutId);
-
- var msecs = item._idleTimeout;
- if (msecs >= 0) {
- item._idleTimeoutId = setTimeout(function onTimeout() {
- if (item._onTimeout)
- item._onTimeout();
- }, msecs);
- }
-};
-
-// That's not how node.js implements it but the exposed api is the same.
-exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
- var id = nextImmediateId++;
- var args = arguments.length < 2 ? false : slice.call(arguments, 1);
-
- immediateIds[id] = true;
-
- nextTick(function onNextTick() {
- if (immediateIds[id]) {
- // fn.call() is faster so we optimize for the common use-case
- // @see http://jsperf.com/call-apply-segu
- if (args) {
- fn.apply(null, args);
- } else {
- fn.call(null);
- }
- // Prevent ids from leaking
- exports.clearImmediate(id);
- }
- });
-
- return id;
-};
-
-exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
- delete immediateIds[id];
-};
-}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)
-},{"process/browser.js":34,"timers":76}],77:[function(require,module,exports){
-// 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 punycode = require('punycode');
-var util = require('./util');
-
-exports.parse = urlParse;
-exports.resolve = urlResolve;
-exports.resolveObject = urlResolveObject;
-exports.format = urlFormat;
-
-exports.Url = Url;
-
-function Url() {
- this.protocol = null;
- this.slashes = null;
- this.auth = null;
- this.host = null;
- this.port = null;
- this.hostname = null;
- this.hash = null;
- this.search = null;
- this.query = null;
- this.pathname = null;
- this.path = null;
- this.href = null;
-}
-
-// Reference: RFC 3986, RFC 1808, RFC 2396
-
-// define these here so at least they only have to be
-// compiled once on the first module load.
-var protocolPattern = /^([a-z0-9.+-]+:)/i,
- portPattern = /:[0-9]*$/,
-
- // Special case for a simple path URL
- simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
-
- // RFC 2396: characters reserved for delimiting URLs.
- // We actually just auto-escape these.
- delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
-
- // RFC 2396: characters not allowed for various reasons.
- unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
-
- // Allowed by RFCs, but cause of XSS attacks. Always escape these.
- autoEscape = ['\''].concat(unwise),
- // Characters that are never ever allowed in a hostname.
- // Note that any invalid chars are also handled, but these
- // are the ones that are *expected* to be seen, so we fast-path
- // them.
- nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
- hostEndingChars = ['/', '?', '#'],
- hostnameMaxLen = 255,
- hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
- hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
- // protocols that can allow "unsafe" and "unwise" chars.
- unsafeProtocol = {
- 'javascript': true,
- 'javascript:': true
- },
- // protocols that never have a hostname.
- hostlessProtocol = {
- 'javascript': true,
- 'javascript:': true
- },
- // protocols that always contain a // bit.
- slashedProtocol = {
- 'http': true,
- 'https': true,
- 'ftp': true,
- 'gopher': true,
- 'file': true,
- 'http:': true,
- 'https:': true,
- 'ftp:': true,
- 'gopher:': true,
- 'file:': true
- },
- querystring = require('querystring');
-
-function urlParse(url, parseQueryString, slashesDenoteHost) {
- if (url && util.isObject(url) && url instanceof Url) return url;
-
- var u = new Url;
- u.parse(url, parseQueryString, slashesDenoteHost);
- return u;
-}
-
-Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
- if (!util.isString(url)) {
- throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
- }
-
- // Copy chrome, IE, opera backslash-handling behavior.
- // Back slashes before the query string get converted to forward slashes
- // See: https://code.google.com/p/chromium/issues/detail?id=25916
- var queryIndex = url.indexOf('?'),
- splitter =
- (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
- uSplit = url.split(splitter),
- slashRegex = /\\/g;
- uSplit[0] = uSplit[0].replace(slashRegex, '/');
- url = uSplit.join(splitter);
-
- var rest = url;
-
- // trim before proceeding.
- // This is to support parse stuff like " http://foo.com \n"
- rest = rest.trim();
-
- if (!slashesDenoteHost && url.split('#').length === 1) {
- // Try fast path regexp
- var simplePath = simplePathPattern.exec(rest);
- if (simplePath) {
- this.path = rest;
- this.href = rest;
- this.pathname = simplePath[1];
- if (simplePath[2]) {
- this.search = simplePath[2];
- if (parseQueryString) {
- this.query = querystring.parse(this.search.substr(1));
- } else {
- this.query = this.search.substr(1);
- }
- } else if (parseQueryString) {
- this.search = '';
- this.query = {};
- }
- return this;
- }
- }
-
- var proto = protocolPattern.exec(rest);
- if (proto) {
- proto = proto[0];
- var lowerProto = proto.toLowerCase();
- this.protocol = lowerProto;
- rest = rest.substr(proto.length);
- }
-
- // figure out if it's got a host
- // user@server is *always* interpreted as a hostname, and url
- // resolution will treat //foo/bar as host=foo,path=bar because that's
- // how the browser resolves relative URLs.
- if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
- var slashes = rest.substr(0, 2) === '//';
- if (slashes && !(proto && hostlessProtocol[proto])) {
- rest = rest.substr(2);
- this.slashes = true;
- }
- }
-
- if (!hostlessProtocol[proto] &&
- (slashes || (proto && !slashedProtocol[proto]))) {
-
- // there's a hostname.
- // the first instance of /, ?, ;, or # ends the host.
- //
- // If there is an @ in the hostname, then non-host chars *are* allowed
- // to the left of the last @ sign, unless some host-ending character
- // comes *before* the @-sign.
- // URLs are obnoxious.
- //
- // ex:
- // http://a@b@c/ => user:a@b host:c
- // http://a@b?@c => user:a host:c path:/?@c
-
- // v0.12 TODO(isaacs): This is not quite how Chrome does things.
- // Review our test case against browsers more comprehensively.
-
- // find the first instance of any hostEndingChars
- var hostEnd = -1;
- for (var i = 0; i < hostEndingChars.length; i++) {
- var hec = rest.indexOf(hostEndingChars[i]);
- if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
- hostEnd = hec;
- }
-
- // at this point, either we have an explicit point where the
- // auth portion cannot go past, or the last @ char is the decider.
- var auth, atSign;
- if (hostEnd === -1) {
- // atSign can be anywhere.
- atSign = rest.lastIndexOf('@');
- } else {
- // atSign must be in auth portion.
- // http://a@b/c@d => host:b auth:a path:/c@d
- atSign = rest.lastIndexOf('@', hostEnd);
- }
-
- // Now we have a portion which is definitely the auth.
- // Pull that off.
- if (atSign !== -1) {
- auth = rest.slice(0, atSign);
- rest = rest.slice(atSign + 1);
- this.auth = decodeURIComponent(auth);
- }
-
- // the host is the remaining to the left of the first non-host char
- hostEnd = -1;
- for (var i = 0; i < nonHostChars.length; i++) {
- var hec = rest.indexOf(nonHostChars[i]);
- if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
- hostEnd = hec;
- }
- // if we still have not hit it, then the entire thing is a host.
- if (hostEnd === -1)
- hostEnd = rest.length;
-
- this.host = rest.slice(0, hostEnd);
- rest = rest.slice(hostEnd);
-
- // pull out port.
- this.parseHost();
-
- // we've indicated that there is a hostname,
- // so even if it's empty, it has to be present.
- this.hostname = this.hostname || '';
-
- // if hostname begins with [ and ends with ]
- // assume that it's an IPv6 address.
- var ipv6Hostname = this.hostname[0] === '[' &&
- this.hostname[this.hostname.length - 1] === ']';
-
- // validate a little.
- if (!ipv6Hostname) {
- var hostparts = this.hostname.split(/\./);
- for (var i = 0, l = hostparts.length; i < l; i++) {
- var part = hostparts[i];
- if (!part) continue;
- if (!part.match(hostnamePartPattern)) {
- var newpart = '';
- for (var j = 0, k = part.length; j < k; j++) {
- if (part.charCodeAt(j) > 127) {
- // we replace non-ASCII char with a temporary placeholder
- // we need this to make sure size of hostname is not
- // broken by replacing non-ASCII by nothing
- newpart += 'x';
- } else {
- newpart += part[j];
- }
- }
- // we test again with ASCII char only
- if (!newpart.match(hostnamePartPattern)) {
- var validParts = hostparts.slice(0, i);
- var notHost = hostparts.slice(i + 1);
- var bit = part.match(hostnamePartStart);
- if (bit) {
- validParts.push(bit[1]);
- notHost.unshift(bit[2]);
- }
- if (notHost.length) {
- rest = '/' + notHost.join('.') + rest;
- }
- this.hostname = validParts.join('.');
- break;
- }
- }
- }
- }
-
- if (this.hostname.length > hostnameMaxLen) {
- this.hostname = '';
- } else {
- // hostnames are always lower case.
- this.hostname = this.hostname.toLowerCase();
- }
-
- if (!ipv6Hostname) {
- // IDNA Support: Returns a punycoded representation of "domain".
- // It only converts parts of the domain name that
- // have non-ASCII characters, i.e. it doesn't matter if
- // you call it with a domain that already is ASCII-only.
- this.hostname = punycode.toASCII(this.hostname);
- }
-
- var p = this.port ? ':' + this.port : '';
- var h = this.hostname || '';
- this.host = h + p;
- this.href += this.host;
-
- // strip [ and ] from the hostname
- // the host field still retains them, though
- if (ipv6Hostname) {
- this.hostname = this.hostname.substr(1, this.hostname.length - 2);
- if (rest[0] !== '/') {
- rest = '/' + rest;
- }
- }
- }
-
- // now rest is set to the post-host stuff.
- // chop off any delim chars.
- if (!unsafeProtocol[lowerProto]) {
-
- // First, make 100% sure that any "autoEscape" chars get
- // escaped, even if encodeURIComponent doesn't think they
- // need to be.
- for (var i = 0, l = autoEscape.length; i < l; i++) {
- var ae = autoEscape[i];
- if (rest.indexOf(ae) === -1)
- continue;
- var esc = encodeURIComponent(ae);
- if (esc === ae) {
- esc = escape(ae);
- }
- rest = rest.split(ae).join(esc);
- }
- }
-
-
- // chop off from the tail first.
- var hash = rest.indexOf('#');
- if (hash !== -1) {
- // got a fragment string.
- this.hash = rest.substr(hash);
- rest = rest.slice(0, hash);
- }
- var qm = rest.indexOf('?');
- if (qm !== -1) {
- this.search = rest.substr(qm);
- this.query = rest.substr(qm + 1);
- if (parseQueryString) {
- this.query = querystring.parse(this.query);
- }
- rest = rest.slice(0, qm);
- } else if (parseQueryString) {
- // no query string, but parseQueryString still requested
- this.search = '';
- this.query = {};
- }
- if (rest) this.pathname = rest;
- if (slashedProtocol[lowerProto] &&
- this.hostname && !this.pathname) {
- this.pathname = '/';
- }
-
- //to support http.request
- if (this.pathname || this.search) {
- var p = this.pathname || '';
- var s = this.search || '';
- this.path = p + s;
- }
-
- // finally, reconstruct the href based on what has been validated.
- this.href = this.format();
- return this;
-};
-
-// format a parsed object into a url string
-function urlFormat(obj) {
- // ensure it's an object, and not a string url.
- // If it's an obj, this is a no-op.
- // this way, you can call url_format() on strings
- // to clean up potentially wonky urls.
- if (util.isString(obj)) obj = urlParse(obj);
- if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
- return obj.format();
-}
-
-Url.prototype.format = function() {
- var auth = this.auth || '';
- if (auth) {
- auth = encodeURIComponent(auth);
- auth = auth.replace(/%3A/i, ':');
- auth += '@';
- }
-
- var protocol = this.protocol || '',
- pathname = this.pathname || '',
- hash = this.hash || '',
- host = false,
- query = '';
-
- if (this.host) {
- host = auth + this.host;
- } else if (this.hostname) {
- host = auth + (this.hostname.indexOf(':') === -1 ?
- this.hostname :
- '[' + this.hostname + ']');
- if (this.port) {
- host += ':' + this.port;
- }
- }
-
- if (this.query &&
- util.isObject(this.query) &&
- Object.keys(this.query).length) {
- query = querystring.stringify(this.query);
- }
-
- var search = this.search || (query && ('?' + query)) || '';
-
- if (protocol && protocol.substr(-1) !== ':') protocol += ':';
-
- // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
- // unless they had them to begin with.
- if (this.slashes ||
- (!protocol || slashedProtocol[protocol]) && host !== false) {
- host = '//' + (host || '');
- if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
- } else if (!host) {
- host = '';
- }
-
- if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
- if (search && search.charAt(0) !== '?') search = '?' + search;
-
- pathname = pathname.replace(/[?#]/g, function(match) {
- return encodeURIComponent(match);
- });
- search = search.replace('#', '%23');
-
- return protocol + host + pathname + search + hash;
-};
-
-function urlResolve(source, relative) {
- return urlParse(source, false, true).resolve(relative);
-}
-
-Url.prototype.resolve = function(relative) {
- return this.resolveObject(urlParse(relative, false, true)).format();
-};
-
-function urlResolveObject(source, relative) {
- if (!source) return relative;
- return urlParse(source, false, true).resolveObject(relative);
-}
-
-Url.prototype.resolveObject = function(relative) {
- if (util.isString(relative)) {
- var rel = new Url();
- rel.parse(relative, false, true);
- relative = rel;
- }
-
- var result = new Url();
- var tkeys = Object.keys(this);
- for (var tk = 0; tk < tkeys.length; tk++) {
- var tkey = tkeys[tk];
- result[tkey] = this[tkey];
- }
-
- // hash is always overridden, no matter what.
- // even href="" will remove it.
- result.hash = relative.hash;
-
- // if the relative url is empty, then there's nothing left to do here.
- if (relative.href === '') {
- result.href = result.format();
- return result;
- }
-
- // hrefs like //foo/bar always cut to the protocol.
- if (relative.slashes && !relative.protocol) {
- // take everything except the protocol from relative
- var rkeys = Object.keys(relative);
- for (var rk = 0; rk < rkeys.length; rk++) {
- var rkey = rkeys[rk];
- if (rkey !== 'protocol')
- result[rkey] = relative[rkey];
- }
-
- //urlParse appends trailing / to urls like http://www.example.com
- if (slashedProtocol[result.protocol] &&
- result.hostname && !result.pathname) {
- result.path = result.pathname = '/';
- }
-
- result.href = result.format();
- return result;
- }
-
- if (relative.protocol && relative.protocol !== result.protocol) {
- // if it's a known url protocol, then changing
- // the protocol does weird things
- // first, if it's not file:, then we MUST have a host,
- // and if there was a path
- // to begin with, then we MUST have a path.
- // if it is file:, then the host is dropped,
- // because that's known to be hostless.
- // anything else is assumed to be absolute.
- if (!slashedProtocol[relative.protocol]) {
- var keys = Object.keys(relative);
- for (var v = 0; v < keys.length; v++) {
- var k = keys[v];
- result[k] = relative[k];
- }
- result.href = result.format();
- return result;
- }
-
- result.protocol = relative.protocol;
- if (!relative.host && !hostlessProtocol[relative.protocol]) {
- var relPath = (relative.pathname || '').split('/');
- while (relPath.length && !(relative.host = relPath.shift()));
- if (!relative.host) relative.host = '';
- if (!relative.hostname) relative.hostname = '';
- if (relPath[0] !== '') relPath.unshift('');
- if (relPath.length < 2) relPath.unshift('');
- result.pathname = relPath.join('/');
- } else {
- result.pathname = relative.pathname;
- }
- result.search = relative.search;
- result.query = relative.query;
- result.host = relative.host || '';
- result.auth = relative.auth;
- result.hostname = relative.hostname || relative.host;
- result.port = relative.port;
- // to support http.request
- if (result.pathname || result.search) {
- var p = result.pathname || '';
- var s = result.search || '';
- result.path = p + s;
- }
- result.slashes = result.slashes || relative.slashes;
- result.href = result.format();
- return result;
- }
-
- var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
- isRelAbs = (
- relative.host ||
- relative.pathname && relative.pathname.charAt(0) === '/'
- ),
- mustEndAbs = (isRelAbs || isSourceAbs ||
- (result.host && relative.pathname)),
- removeAllDots = mustEndAbs,
- srcPath = result.pathname && result.pathname.split('/') || [],
- relPath = relative.pathname && relative.pathname.split('/') || [],
- psychotic = result.protocol && !slashedProtocol[result.protocol];
-
- // if the url is a non-slashed url, then relative
- // links like ../.. should be able
- // to crawl up to the hostname, as well. This is strange.
- // result.protocol has already been set by now.
- // Later on, put the first path part into the host field.
- if (psychotic) {
- result.hostname = '';
- result.port = null;
- if (result.host) {
- if (srcPath[0] === '') srcPath[0] = result.host;
- else srcPath.unshift(result.host);
- }
- result.host = '';
- if (relative.protocol) {
- relative.hostname = null;
- relative.port = null;
- if (relative.host) {
- if (relPath[0] === '') relPath[0] = relative.host;
- else relPath.unshift(relative.host);
- }
- relative.host = null;
- }
- mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
- }
-
- if (isRelAbs) {
- // it's absolute.
- result.host = (relative.host || relative.host === '') ?
- relative.host : result.host;
- result.hostname = (relative.hostname || relative.hostname === '') ?
- relative.hostname : result.hostname;
- result.search = relative.search;
- result.query = relative.query;
- srcPath = relPath;
- // fall through to the dot-handling below.
- } else if (relPath.length) {
- // it's relative
- // throw away the existing file, and take the new path instead.
- if (!srcPath) srcPath = [];
- srcPath.pop();
- srcPath = srcPath.concat(relPath);
- result.search = relative.search;
- result.query = relative.query;
- } else if (!util.isNullOrUndefined(relative.search)) {
- // just pull out the search.
- // like href='?foo'.
- // Put this after the other two cases because it simplifies the booleans
- if (psychotic) {
- result.hostname = result.host = srcPath.shift();
- //occationaly the auth can get stuck only in host
- //this especially happens in cases like
- //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
- var authInHost = result.host && result.host.indexOf('@') > 0 ?
- result.host.split('@') : false;
- if (authInHost) {
- result.auth = authInHost.shift();
- result.host = result.hostname = authInHost.shift();
- }
- }
- result.search = relative.search;
- result.query = relative.query;
- //to support http.request
- if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
- result.path = (result.pathname ? result.pathname : '') +
- (result.search ? result.search : '');
- }
- result.href = result.format();
- return result;
- }
-
- if (!srcPath.length) {
- // no path at all. easy.
- // we've already handled the other stuff above.
- result.pathname = null;
- //to support http.request
- if (result.search) {
- result.path = '/' + result.search;
- } else {
- result.path = null;
- }
- result.href = result.format();
- return result;
- }
-
- // if a url ENDs in . or .., then it must get a trailing slash.
- // however, if it ends in anything else non-slashy,
- // then it must NOT get a trailing slash.
- var last = srcPath.slice(-1)[0];
- var hasTrailingSlash = (
- (result.host || relative.host || srcPath.length > 1) &&
- (last === '.' || last === '..') || last === '');
-
- // strip single dots, resolve double dots to parent dir
- // if the path tries to go above the root, `up` ends up > 0
- var up = 0;
- for (var i = srcPath.length; i >= 0; i--) {
- last = srcPath[i];
- if (last === '.') {
- srcPath.splice(i, 1);
- } else if (last === '..') {
- srcPath.splice(i, 1);
- up++;
- } else if (up) {
- srcPath.splice(i, 1);
- up--;
- }
- }
-
- // if the path is allowed to go above the root, restore leading ..s
- if (!mustEndAbs && !removeAllDots) {
- for (; up--; up) {
- srcPath.unshift('..');
- }
- }
-
- if (mustEndAbs && srcPath[0] !== '' &&
- (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
- srcPath.unshift('');
- }
-
- if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
- srcPath.push('');
- }
-
- var isAbsolute = srcPath[0] === '' ||
- (srcPath[0] && srcPath[0].charAt(0) === '/');
-
- // put the host back
- if (psychotic) {
- result.hostname = result.host = isAbsolute ? '' :
- srcPath.length ? srcPath.shift() : '';
- //occationaly the auth can get stuck only in host
- //this especially happens in cases like
- //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
- var authInHost = result.host && result.host.indexOf('@') > 0 ?
- result.host.split('@') : false;
- if (authInHost) {
- result.auth = authInHost.shift();
- result.host = result.hostname = authInHost.shift();
- }
- }
-
- mustEndAbs = mustEndAbs || (result.host && srcPath.length);
-
- if (mustEndAbs && !isAbsolute) {
- srcPath.unshift('');
- }
-
- if (!srcPath.length) {
- result.pathname = null;
- result.path = null;
- } else {
- result.pathname = srcPath.join('/');
- }
-
- //to support request.http
- if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
- result.path = (result.pathname ? result.pathname : '') +
- (result.search ? result.search : '');
- }
- result.auth = relative.auth || result.auth;
- result.slashes = result.slashes || relative.slashes;
- result.href = result.format();
- return result;
-};
-
-Url.prototype.parseHost = function() {
- var host = this.host;
- var port = portPattern.exec(host);
- if (port) {
- port = port[0];
- if (port !== ':') {
- this.port = port.substr(1);
- }
- host = host.substr(0, host.length - port.length);
- }
- if (host) this.hostname = host;
-};
-
-},{"./util":78,"punycode":35,"querystring":38}],78:[function(require,module,exports){
-'use strict';
-
-module.exports = {
- isString: function(arg) {
- return typeof(arg) === 'string';
- },
- isObject: function(arg) {
- return typeof(arg) === 'object' && arg !== null;
- },
- isNull: function(arg) {
- return arg === null;
- },
- isNullOrUndefined: function(arg) {
- return arg == null;
- }
-};
-
-},{}],79:[function(require,module,exports){
-(function (global){(function (){
-
-/**
- * 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';
-}
-
-}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{}],80:[function(require,module,exports){
-arguments[4][3][0].apply(exports,arguments)
-},{"dup":3}],81:[function(require,module,exports){
-arguments[4][4][0].apply(exports,arguments)
-},{"dup":4}],82:[function(require,module,exports){
-arguments[4][5][0].apply(exports,arguments)
-},{"./support/isBuffer":81,"_process":34,"dup":5,"inherits":80}],83:[function(require,module,exports){
-module.exports = extend
-
-var hasOwnProperty = Object.prototype.hasOwnProperty;
-
-function extend() {
- var target = {}
-
- for (var i = 0; i < arguments.length; i++) {
- var source = arguments[i]
-
- for (var key in source) {
- if (hasOwnProperty.call(source, key)) {
- target[key] = source[key]
- }
- }
- }
-
- return target
-}
-
-},{}],84:[function(require,module,exports){
-var adapter = require('./');
-
-/**
- * Extracts the values from process.env.
- *
- * @type {Function}
- * @public
- */
-module.exports = adapter(function hash() {
- return /(debug|diagnostics)=([^&]+)/i.exec(window.location.hash)[2];
-});
-
-},{"./":85}],85:[function(require,module,exports){
-var enabled = require('enabled');
-
-/**
- * Creates a new Adapter.
- *
- * @param {Function} fn Function that returns the value.
- * @returns {Function} The adapter logic.
- * @public
- */
-module.exports = function create(fn) {
- return function adapter(namespace) {
- try {
- return enabled(namespace, fn());
- } catch (e) { /* Any failure means that we found nothing */ }
-
- return false;
- };
-}
-
-},{"enabled":136}],86:[function(require,module,exports){
-var adapter = require('./');
-
-/**
- * Extracts the values from process.env.
- *
- * @type {Function}
- * @public
- */
-module.exports = adapter(function storage() {
- return localStorage.getItem('debug') || localStorage.getItem('diagnostics');
-});
-
-},{"./":85}],87:[function(require,module,exports){
-var create = require('../diagnostics');
-
-/**
- * Create a new diagnostics logger.
- *
- * @param {String} namespace The namespace it should enable.
- * @param {Object} options Additional options.
- * @returns {Function} The logger.
- * @public
- */
-var diagnostics = create(function dev(namespace, options) {
- options = options || {};
- options.namespace = namespace;
- options.prod = false;
- options.dev = true;
-
- if (!dev.enabled(namespace) && !(options.force || dev.force)) {
- return dev.nope(options);
- }
-
- return dev.yep(options);
-});
-
-//
-// Configure the logger for the given environment.
-//
-diagnostics.modify(require('../modifiers/namespace'));
-diagnostics.use(require('../adapters/localstorage'));
-diagnostics.use(require('../adapters/hash'));
-diagnostics.set(require('../logger/console'));
-
-//
-// Expose the diagnostics logger.
-//
-module.exports = diagnostics;
-
-},{"../adapters/hash":84,"../adapters/localstorage":86,"../diagnostics":90,"../logger/console":91,"../modifiers/namespace":92}],88:[function(require,module,exports){
-(function (process){(function (){
-//
-// Select the correct build version depending on the environment.
-//
-if (process.env.NODE_ENV === 'production') {
- module.exports = require('./production.js');
-} else {
- module.exports = require('./development.js');
-}
-
-}).call(this)}).call(this,require('_process'))
-},{"./development.js":87,"./production.js":89,"_process":34}],89:[function(require,module,exports){
-var create = require('../diagnostics');
-
-/**
- * Create a new diagnostics logger.
- *
- * @param {String} namespace The namespace it should enable.
- * @param {Object} options Additional options.
- * @returns {Function} The logger.
- * @public
- */
-var diagnostics = create(function prod(namespace, options) {
- options = options || {};
- options.namespace = namespace;
- options.prod = true;
- options.dev = false;
-
- if (!(options.force || prod.force)) return prod.nope(options);
- return prod.yep(options);
-});
-
-//
-// Expose the diagnostics logger.
-//
-module.exports = diagnostics;
-
-},{"../diagnostics":90}],90:[function(require,module,exports){
-/**
- * Contains all configured adapters for the given environment.
- *
- * @type {Array}
- * @public
- */
-var adapters = [];
-
-/**
- * Contains all modifier functions.
- *
- * @typs {Array}
- * @public
- */
-var modifiers = [];
-
-/**
- * Our default logger.
- *
- * @public
- */
-var logger = function devnull() {};
-
-/**
- * Register a new adapter that will used to find environments.
- *
- * @param {Function} adapter A function that will return the possible env.
- * @returns {Boolean} Indication of a successful add.
- * @public
- */
-function use(adapter) {
- if (~adapters.indexOf(adapter)) return false;
-
- adapters.push(adapter);
- return true;
-}
-
-/**
- * Assign a new log method.
- *
- * @param {Function} custom The log method.
- * @public
- */
-function set(custom) {
- logger = custom;
-}
-
-/**
- * Check if the namespace is allowed by any of our adapters.
- *
- * @param {String} namespace The namespace that needs to be enabled
- * @returns {Boolean|Promise} Indication if the namespace is enabled by our adapters.
- * @public
- */
-function enabled(namespace) {
- var async = [];
-
- for (var i = 0; i < adapters.length; i++) {
- if (adapters[i].async) {
- async.push(adapters[i]);
- continue;
- }
-
- if (adapters[i](namespace)) return true;
- }
-
- if (!async.length) return false;
-
- //
- // Now that we know that we Async functions, we know we run in an ES6
- // environment and can use all the API's that they offer, in this case
- // we want to return a Promise so that we can `await` in React-Native
- // for an async adapter.
- //
- return new Promise(function pinky(resolve) {
- Promise.all(
- async.map(function prebind(fn) {
- return fn(namespace);
- })
- ).then(function resolved(values) {
- resolve(values.some(Boolean));
- });
- });
-}
-
-/**
- * Add a new message modifier to the debugger.
- *
- * @param {Function} fn Modification function.
- * @returns {Boolean} Indication of a successful add.
- * @public
- */
-function modify(fn) {
- if (~modifiers.indexOf(fn)) return false;
-
- modifiers.push(fn);
- return true;
-}
-
-/**
- * Write data to the supplied logger.
- *
- * @param {Object} meta Meta information about the log.
- * @param {Array} args Arguments for console.log.
- * @public
- */
-function write() {
- logger.apply(logger, arguments);
-}
-
-/**
- * Process the message with the modifiers.
- *
- * @param {Mixed} message The message to be transformed by modifers.
- * @returns {String} Transformed message.
- * @public
- */
-function process(message) {
- for (var i = 0; i < modifiers.length; i++) {
- message = modifiers[i].apply(modifiers[i], arguments);
- }
-
- return message;
-}
-
-/**
- * Introduce options to the logger function.
- *
- * @param {Function} fn Calback function.
- * @param {Object} options Properties to introduce on fn.
- * @returns {Function} The passed function
- * @public
- */
-function introduce(fn, options) {
- var has = Object.prototype.hasOwnProperty;
-
- for (var key in options) {
- if (has.call(options, key)) {
- fn[key] = options[key];
- }
- }
-
- return fn;
-}
-
-/**
- * Nope, we're not allowed to write messages.
- *
- * @returns {Boolean} false
- * @public
- */
-function nope(options) {
- options.enabled = false;
- options.modify = modify;
- options.set = set;
- options.use = use;
-
- return introduce(function diagnopes() {
- return false;
- }, options);
-}
-
-/**
- * Yep, we're allowed to write debug messages.
- *
- * @param {Object} options The options for the process.
- * @returns {Function} The function that does the logging.
- * @public
- */
-function yep(options) {
- /**
- * The function that receives the actual debug information.
- *
- * @returns {Boolean} indication that we're logging.
- * @public
- */
- function diagnostics() {
- var args = Array.prototype.slice.call(arguments, 0);
-
- write.call(write, options, process(args, options));
- return true;
- }
-
- options.enabled = true;
- options.modify = modify;
- options.set = set;
- options.use = use;
-
- return introduce(diagnostics, options);
-}
-
-/**
- * Simple helper function to introduce various of helper methods to our given
- * diagnostics function.
- *
- * @param {Function} diagnostics The diagnostics function.
- * @returns {Function} diagnostics
- * @public
- */
-module.exports = function create(diagnostics) {
- diagnostics.introduce = introduce;
- diagnostics.enabled = enabled;
- diagnostics.process = process;
- diagnostics.modify = modify;
- diagnostics.write = write;
- diagnostics.nope = nope;
- diagnostics.yep = yep;
- diagnostics.set = set;
- diagnostics.use = use;
-
- return diagnostics;
-}
-
-},{}],91:[function(require,module,exports){
-/**
- * An idiot proof logger to be used as default. We've wrapped it in a try/catch
- * statement to ensure the environments without the `console` API do not crash
- * as well as an additional fix for ancient browsers like IE8 where the
- * `console.log` API doesn't have an `apply`, so we need to use the Function's
- * apply functionality to apply the arguments.
- *
- * @param {Object} meta Options of the logger.
- * @param {Array} messages The actuall message that needs to be logged.
- * @public
- */
-module.exports = function (meta, messages) {
- //
- // So yea. IE8 doesn't have an apply so we need a work around to puke the
- // arguments in place.
- //
- try { Function.prototype.apply.call(console.log, console, messages); }
- catch (e) {}
-}
-
-},{}],92:[function(require,module,exports){
-var colorspace = require('colorspace');
-
-/**
- * Prefix the messages with a colored namespace.
- *
- * @param {Array} messages The messages array that is getting written.
- * @param {Object} options Options for diagnostics.
- * @returns {Array} Altered messages array.
- * @public
- */
-module.exports = function colorNamespace(args, options) {
- var namespace = options.namespace;
-
- if (options.colors === false) {
- args[0] = namespace +': '+ args[0];
- return args;
- }
-
- var color = colorspace(namespace);
-
- //
- // The console API supports a special %c formatter in browsers. This is used
- // to style console messages with any CSS styling, in our case we want to
- // use colorize the namespace for clarity. As these are formatters, and
- // we need to inject our CSS string as second messages argument so it
- // gets picked up correctly.
- //
- args[0] = '%c'+ namespace +':%c '+ args[0];
- args.splice(1, 0, 'color:'+ color, 'color:inherit');
-
- return args;
-};
-
-},{"colorspace":130}],93:[function(require,module,exports){
-'use strict';
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.default = asyncify;
-
-var _initialParams = require('./internal/initialParams');
-
-var _initialParams2 = _interopRequireDefault(_initialParams);
-
-var _setImmediate = require('./internal/setImmediate');
-
-var _setImmediate2 = _interopRequireDefault(_setImmediate);
-
-var _wrapAsync = require('./internal/wrapAsync');
-
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
-/**
- * Take a sync function and make it async, passing its return value to a
- * callback. This is useful for plugging sync functions into a waterfall,
- * series, or other async functions. Any arguments passed to the generated
- * function will be passed to the wrapped function (except for the final
- * callback argument). Errors thrown will be passed to the callback.
- *
- * If the function passed to `asyncify` returns a Promise, that promises's
- * resolved/rejected state will be used to call the callback, rather than simply
- * the synchronous return value.
- *
- * This also means you can asyncify ES2017 `async` functions.
- *
- * @name asyncify
- * @static
- * @memberOf module:Utils
- * @method
- * @alias wrapSync
- * @category Util
- * @param {Function} func - The synchronous function, or Promise-returning
- * function to convert to an {@link AsyncFunction}.
- * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be
- * invoked with `(args..., callback)`.
- * @example
- *
- * // passing a regular synchronous function
- * async.waterfall([
- * async.apply(fs.readFile, filename, "utf8"),
- * async.asyncify(JSON.parse),
- * function (data, next) {
- * // data is the result of parsing the text.
- * // If there was a parsing error, it would have been caught.
- * }
- * ], callback);
- *
- * // passing a function returning a promise
- * async.waterfall([
- * async.apply(fs.readFile, filename, "utf8"),
- * async.asyncify(function (contents) {
- * return db.model.create(contents);
- * }),
- * function (model, next) {
- * // `model` is the instantiated model object.
- * // If there was an error, this function would be skipped.
- * }
- * ], callback);
- *
- * // es2017 example, though `asyncify` is not needed if your JS environment
- * // supports async functions out of the box
- * var q = async.queue(async.asyncify(async function(file) {
- * var intermediateStep = await processFile(file);
- * return await somePromise(intermediateStep)
- * }));
- *
- * q.push(files);
- */
-function asyncify(func) {
- if ((0, _wrapAsync.isAsync)(func)) {
- return function (...args /*, callback*/) {
- const callback = args.pop();
- const promise = func.apply(this, args);
- return handlePromise(promise, callback);
- };
- }
-
- return (0, _initialParams2.default)(function (args, callback) {
- var result;
- try {
- result = func.apply(this, args);
- } catch (e) {
- return callback(e);
- }
- // if result is Promise object
- if (result && typeof result.then === 'function') {
- return handlePromise(result, callback);
- } else {
- callback(null, result);
- }
- });
-}
-
-function handlePromise(promise, callback) {
- return promise.then(value => {
- invokeCallback(callback, null, value);
- }, err => {
- invokeCallback(callback, err && err.message ? err : new Error(err));
- });
-}
-
-function invokeCallback(callback, error, value) {
- try {
- callback(error, value);
- } catch (err) {
- (0, _setImmediate2.default)(e => {
- throw e;
- }, err);
- }
-}
-module.exports = exports['default'];
-},{"./internal/initialParams":103,"./internal/setImmediate":109,"./internal/wrapAsync":111}],94:[function(require,module,exports){
-'use strict';
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-
-var _isArrayLike = require('./internal/isArrayLike');
-
-var _isArrayLike2 = _interopRequireDefault(_isArrayLike);
-
-var _breakLoop = require('./internal/breakLoop');
-
-var _breakLoop2 = _interopRequireDefault(_breakLoop);
-
-var _eachOfLimit = require('./eachOfLimit');
-
-var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
-
-var _once = require('./internal/once');
-
-var _once2 = _interopRequireDefault(_once);
-
-var _onlyOnce = require('./internal/onlyOnce');
-
-var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
-
-var _wrapAsync = require('./internal/wrapAsync');
-
-var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
-
-var _awaitify = require('./internal/awaitify');
-
-var _awaitify2 = _interopRequireDefault(_awaitify);
-
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
-// eachOf implementation optimized for array-likes
-function eachOfArrayLike(coll, iteratee, callback) {
- callback = (0, _once2.default)(callback);
- var index = 0,
- completed = 0,
- { length } = coll,
- canceled = false;
- if (length === 0) {
- callback(null);
- }
-
- function iteratorCallback(err, value) {
- if (err === false) {
- canceled = true;
- }
- if (canceled === true) return;
- if (err) {
- callback(err);
- } else if (++completed === length || value === _breakLoop2.default) {
- callback(null);
- }
- }
-
- for (; index < length; index++) {
- iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback));
- }
-}
-
-// a generic version of eachOf which can handle array, object, and iterator cases.
-function eachOfGeneric(coll, iteratee, callback) {
- return (0, _eachOfLimit2.default)(coll, Infinity, iteratee, callback);
-}
-
-/**
- * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument
- * to the iteratee.
- *
- * @name eachOf
- * @static
- * @memberOf module:Collections
- * @method
- * @alias forEachOf
- * @category Collection
- * @see [async.each]{@link module:Collections.each}
- * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
- * @param {AsyncFunction} iteratee - A function to apply to each
- * item in `coll`.
- * The `key` is the item's key, or index in the case of an array.
- * Invoked with (item, key, callback).
- * @param {Function} [callback] - A callback which is called when all
- * `iteratee` functions have finished, or an error occurs. Invoked with (err).
- * @returns {Promise} a promise, if a callback is omitted
- * @example
- *
- * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"};
- * var configs = {};
- *
- * async.forEachOf(obj, function (value, key, callback) {
- * fs.readFile(__dirname + value, "utf8", function (err, data) {
- * if (err) return callback(err);
- * try {
- * configs[key] = JSON.parse(data);
- * } catch (e) {
- * return callback(e);
- * }
- * callback();
- * });
- * }, function (err) {
- * if (err) console.error(err.message);
- * // configs is now a map of JSON data
- * doSomethingWith(configs);
- * });
- */
-function eachOf(coll, iteratee, callback) {
- var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric;
- return eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback);
-}
-
-exports.default = (0, _awaitify2.default)(eachOf, 3);
-module.exports = exports['default'];
-},{"./eachOfLimit":95,"./internal/awaitify":99,"./internal/breakLoop":100,"./internal/isArrayLike":104,"./internal/once":106,"./internal/onlyOnce":107,"./internal/wrapAsync":111}],95:[function(require,module,exports){
-'use strict';
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-
-var _eachOfLimit2 = require('./internal/eachOfLimit');
-
-var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2);
-
-var _wrapAsync = require('./internal/wrapAsync');
-
-var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
-
-var _awaitify = require('./internal/awaitify');
-
-var _awaitify2 = _interopRequireDefault(_awaitify);
-
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
-/**
- * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a
- * time.
- *
- * @name eachOfLimit
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.eachOf]{@link module:Collections.eachOf}
- * @alias forEachOfLimit
- * @category Collection
- * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
- * @param {number} limit - The maximum number of async operations at a time.
- * @param {AsyncFunction} iteratee - An async function to apply to each
- * item in `coll`. The `key` is the item's key, or index in the case of an
- * array.
- * Invoked with (item, key, callback).
- * @param {Function} [callback] - A callback which is called when all
- * `iteratee` functions have finished, or an error occurs. Invoked with (err).
- * @returns {Promise} a promise, if a callback is omitted
- */
-function eachOfLimit(coll, limit, iteratee, callback) {
- return (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback);
-}
-
-exports.default = (0, _awaitify2.default)(eachOfLimit, 4);
-module.exports = exports['default'];
-},{"./internal/awaitify":99,"./internal/eachOfLimit":101,"./internal/wrapAsync":111}],96:[function(require,module,exports){
-'use strict';
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-
-var _eachOfLimit = require('./eachOfLimit');
-
-var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit);
-
-var _awaitify = require('./internal/awaitify');
-
-var _awaitify2 = _interopRequireDefault(_awaitify);
-
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
-/**
- * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.
- *
- * @name eachOfSeries
- * @static
- * @memberOf module:Collections
- * @method
- * @see [async.eachOf]{@link module:Collections.eachOf}
- * @alias forEachOfSeries
- * @category Collection
- * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
- * @param {AsyncFunction} iteratee - An async function to apply to each item in
- * `coll`.
- * Invoked with (item, key, callback).
- * @param {Function} [callback] - A callback which is called when all `iteratee`
- * functions have finished, or an error occurs. Invoked with (err).
- * @returns {Promise} a promise, if a callback is omitted
- */
-function eachOfSeries(coll, iteratee, callback) {
- return (0, _eachOfLimit2.default)(coll, 1, iteratee, callback);
-}
-exports.default = (0, _awaitify2.default)(eachOfSeries, 3);
-module.exports = exports['default'];
-},{"./eachOfLimit":95,"./internal/awaitify":99}],97:[function(require,module,exports){
-'use strict';
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-
-var _eachOf = require('./eachOf');
-
-var _eachOf2 = _interopRequireDefault(_eachOf);
-
-var _withoutIndex = require('./internal/withoutIndex');
-
-var _withoutIndex2 = _interopRequireDefault(_withoutIndex);
-
-var _wrapAsync = require('./internal/wrapAsync');
-
-var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
-
-var _awaitify = require('./internal/awaitify');
-
-var _awaitify2 = _interopRequireDefault(_awaitify);
-
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
-/**
- * Applies the function `iteratee` to each item in `coll`, in parallel.
- * The `iteratee` is called with an item from the list, and a callback for when
- * it has finished. If the `iteratee` passes an error to its `callback`, the
- * main `callback` (for the `each` function) is immediately called with the
- * error.
- *
- * Note, that since this function applies `iteratee` to each item in parallel,
- * there is no guarantee that the iteratee functions will complete in order.
- *
- * @name each
- * @static
- * @memberOf module:Collections
- * @method
- * @alias forEach
- * @category Collection
- * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
- * @param {AsyncFunction} iteratee - An async function to apply to
- * each item in `coll`. Invoked with (item, callback).
- * The array index is not passed to the iteratee.
- * If you need the index, use `eachOf`.
- * @param {Function} [callback] - A callback which is called when all
- * `iteratee` functions have finished, or an error occurs. Invoked with (err).
- * @returns {Promise} a promise, if a callback is omitted
- * @example
- *
- * // assuming openFiles is an array of file names and saveFile is a function
- * // to save the modified contents of that file:
- *
- * async.each(openFiles, saveFile, function(err){
- * // if any of the saves produced an error, err would equal that error
- * });
- *
- * // assuming openFiles is an array of file names
- * async.each(openFiles, function(file, callback) {
- *
- * // Perform operation on file here.
- * console.log('Processing file ' + file);
- *
- * if( file.length > 32 ) {
- * console.log('This file name is too long');
- * callback('File name too long');
- * } else {
- * // Do work to process file here
- * console.log('File processed');
- * callback();
- * }
- * }, function(err) {
- * // if any of the file processing produced an error, err would equal that error
- * if( err ) {
- * // One of the iterations produced an error.
- * // All processing will now stop.
- * console.log('A file failed to process');
- * } else {
- * console.log('All files have been processed successfully');
- * }
- * });
- */
-function eachLimit(coll, iteratee, callback) {
- return (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback);
-}
-
-exports.default = (0, _awaitify2.default)(eachLimit, 3);
-module.exports = exports['default'];
-},{"./eachOf":94,"./internal/awaitify":99,"./internal/withoutIndex":110,"./internal/wrapAsync":111}],98:[function(require,module,exports){
-'use strict';
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.default = asyncEachOfLimit;
-
-var _breakLoop = require('./breakLoop');
-
-var _breakLoop2 = _interopRequireDefault(_breakLoop);
-
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
-// for async generators
-function asyncEachOfLimit(generator, limit, iteratee, callback) {
- let done = false;
- let canceled = false;
- let awaiting = false;
- let running = 0;
- let idx = 0;
-
- function replenish() {
- //console.log('replenish')
- if (running >= limit || awaiting || done) return;
- //console.log('replenish awaiting')
- awaiting = true;
- generator.next().then(({ value, done: iterDone }) => {
- //console.log('got value', value)
- if (canceled || done) return;
- awaiting = false;
- if (iterDone) {
- done = true;
- if (running <= 0) {
- //console.log('done nextCb')
- callback(null);
- }
- return;
- }
- running++;
- iteratee(value, idx, iterateeCallback);
- idx++;
- replenish();
- }).catch(handleError);
- }
-
- function iterateeCallback(err, result) {
- //console.log('iterateeCallback')
- running -= 1;
- if (canceled) return;
- if (err) return handleError(err);
-
- if (err === false) {
- done = true;
- canceled = true;
- return;
- }
-
- if (result === _breakLoop2.default || done && running <= 0) {
- done = true;
- //console.log('done iterCb')
- return callback(null);
- }
- replenish();
- }
-
- function handleError(err) {
- if (canceled) return;
- awaiting = false;
- done = true;
- callback(err);
- }
-
- replenish();
-}
-module.exports = exports['default'];
-},{"./breakLoop":100}],99:[function(require,module,exports){
-'use strict';
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.default = awaitify;
-// conditionally promisify a function.
-// only return a promise if a callback is omitted
-function awaitify(asyncFn, arity = asyncFn.length) {
- if (!arity) throw new Error('arity is undefined');
- function awaitable(...args) {
- if (typeof args[arity - 1] === 'function') {
- return asyncFn.apply(this, args);
- }
-
- return new Promise((resolve, reject) => {
- args[arity - 1] = (err, ...cbArgs) => {
- if (err) return reject(err);
- resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]);
- };
- asyncFn.apply(this, args);
- });
- }
-
- return awaitable;
-}
-module.exports = exports['default'];
-},{}],100:[function(require,module,exports){
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-// A temporary value used to identify if the loop should be broken.
-// See #1064, #1293
-const breakLoop = {};
-exports.default = breakLoop;
-module.exports = exports["default"];
-},{}],101:[function(require,module,exports){
-'use strict';
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-
-var _once = require('./once');
-
-var _once2 = _interopRequireDefault(_once);
-
-var _iterator = require('./iterator');
-
-var _iterator2 = _interopRequireDefault(_iterator);
-
-var _onlyOnce = require('./onlyOnce');
-
-var _onlyOnce2 = _interopRequireDefault(_onlyOnce);
-
-var _wrapAsync = require('./wrapAsync');
-
-var _asyncEachOfLimit = require('./asyncEachOfLimit');
-
-var _asyncEachOfLimit2 = _interopRequireDefault(_asyncEachOfLimit);
-
-var _breakLoop = require('./breakLoop');
-
-var _breakLoop2 = _interopRequireDefault(_breakLoop);
-
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
-exports.default = limit => {
- return (obj, iteratee, callback) => {
- callback = (0, _once2.default)(callback);
- if (limit <= 0) {
- throw new RangeError('concurrency limit cannot be less than 1');
- }
- if (!obj) {
- return callback(null);
- }
- if ((0, _wrapAsync.isAsyncGenerator)(obj)) {
- return (0, _asyncEachOfLimit2.default)(obj, limit, iteratee, callback);
- }
- if ((0, _wrapAsync.isAsyncIterable)(obj)) {
- return (0, _asyncEachOfLimit2.default)(obj[Symbol.asyncIterator](), limit, iteratee, callback);
- }
- var nextElem = (0, _iterator2.default)(obj);
- var done = false;
- var canceled = false;
- var running = 0;
- var looping = false;
-
- function iterateeCallback(err, value) {
- if (canceled) return;
- running -= 1;
- if (err) {
- done = true;
- callback(err);
- } else if (err === false) {
- done = true;
- canceled = true;
- } else if (value === _breakLoop2.default || done && running <= 0) {
- done = true;
- return callback(null);
- } else if (!looping) {
- replenish();
- }
- }
-
- function replenish() {
- looping = true;
- while (running < limit && !done) {
- var elem = nextElem();
- if (elem === null) {
- done = true;
- if (running <= 0) {
- callback(null);
- }
- return;
- }
- running += 1;
- iteratee(elem.value, elem.key, (0, _onlyOnce2.default)(iterateeCallback));
- }
- looping = false;
- }
-
- replenish();
- };
-};
-
-module.exports = exports['default'];
-},{"./asyncEachOfLimit":98,"./breakLoop":100,"./iterator":105,"./once":106,"./onlyOnce":107,"./wrapAsync":111}],102:[function(require,module,exports){
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-
-exports.default = function (coll) {
- return coll[Symbol.iterator] && coll[Symbol.iterator]();
-};
-
-module.exports = exports["default"];
-},{}],103:[function(require,module,exports){
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-
-exports.default = function (fn) {
- return function (...args /*, callback*/) {
- var callback = args.pop();
- return fn.call(this, args, callback);
- };
-};
-
-module.exports = exports["default"];
-},{}],104:[function(require,module,exports){
-'use strict';
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.default = isArrayLike;
-function isArrayLike(value) {
- return value && typeof value.length === 'number' && value.length >= 0 && value.length % 1 === 0;
-}
-module.exports = exports['default'];
-},{}],105:[function(require,module,exports){
-'use strict';
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.default = createIterator;
-
-var _isArrayLike = require('./isArrayLike');
-
-var _isArrayLike2 = _interopRequireDefault(_isArrayLike);
-
-var _getIterator = require('./getIterator');
-
-var _getIterator2 = _interopRequireDefault(_getIterator);
-
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
-function createArrayIterator(coll) {
- var i = -1;
- var len = coll.length;
- return function next() {
- return ++i < len ? { value: coll[i], key: i } : null;
- };
-}
-
-function createES2015Iterator(iterator) {
- var i = -1;
- return function next() {
- var item = iterator.next();
- if (item.done) return null;
- i++;
- return { value: item.value, key: i };
- };
-}
-
-function createObjectIterator(obj) {
- var okeys = obj ? Object.keys(obj) : [];
- var i = -1;
- var len = okeys.length;
- return function next() {
- var key = okeys[++i];
- return i < len ? { value: obj[key], key } : null;
- };
-}
-
-function createIterator(coll) {
- if ((0, _isArrayLike2.default)(coll)) {
- return createArrayIterator(coll);
- }
-
- var iterator = (0, _getIterator2.default)(coll);
- return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);
-}
-module.exports = exports['default'];
-},{"./getIterator":102,"./isArrayLike":104}],106:[function(require,module,exports){
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.default = once;
-function once(fn) {
- function wrapper(...args) {
- if (fn === null) return;
- var callFn = fn;
- fn = null;
- callFn.apply(this, args);
- }
- Object.assign(wrapper, fn);
- return wrapper;
-}
-module.exports = exports["default"];
-},{}],107:[function(require,module,exports){
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.default = onlyOnce;
-function onlyOnce(fn) {
- return function (...args) {
- if (fn === null) throw new Error("Callback was already called.");
- var callFn = fn;
- fn = null;
- callFn.apply(this, args);
- };
-}
-module.exports = exports["default"];
-},{}],108:[function(require,module,exports){
-'use strict';
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-
-var _isArrayLike = require('./isArrayLike');
-
-var _isArrayLike2 = _interopRequireDefault(_isArrayLike);
-
-var _wrapAsync = require('./wrapAsync');
-
-var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
-
-var _awaitify = require('./awaitify');
-
-var _awaitify2 = _interopRequireDefault(_awaitify);
-
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
-exports.default = (0, _awaitify2.default)((eachfn, tasks, callback) => {
- var results = (0, _isArrayLike2.default)(tasks) ? [] : {};
-
- eachfn(tasks, (task, key, taskCb) => {
- (0, _wrapAsync2.default)(task)((err, ...result) => {
- if (result.length < 2) {
- [result] = result;
- }
- results[key] = result;
- taskCb(err);
- });
- }, err => callback(err, results));
-}, 3);
-module.exports = exports['default'];
-},{"./awaitify":99,"./isArrayLike":104,"./wrapAsync":111}],109:[function(require,module,exports){
-(function (process,setImmediate){(function (){
-'use strict';
-/* istanbul ignore file */
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.fallback = fallback;
-exports.wrap = wrap;
-var hasSetImmediate = exports.hasSetImmediate = typeof setImmediate === 'function' && setImmediate;
-var hasNextTick = exports.hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function';
-
-function fallback(fn) {
- setTimeout(fn, 0);
-}
-
-function wrap(defer) {
- return (fn, ...args) => defer(() => fn(...args));
-}
-
-var _defer;
-
-if (hasSetImmediate) {
- _defer = setImmediate;
-} else if (hasNextTick) {
- _defer = process.nextTick;
-} else {
- _defer = fallback;
-}
-
-exports.default = wrap(_defer);
-}).call(this)}).call(this,require('_process'),require("timers").setImmediate)
-},{"_process":34,"timers":76}],110:[function(require,module,exports){
-"use strict";
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.default = _withoutIndex;
-function _withoutIndex(iteratee) {
- return (value, index, callback) => iteratee(value, callback);
-}
-module.exports = exports["default"];
-},{}],111:[function(require,module,exports){
-'use strict';
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.isAsyncIterable = exports.isAsyncGenerator = exports.isAsync = undefined;
-
-var _asyncify = require('../asyncify');
-
-var _asyncify2 = _interopRequireDefault(_asyncify);
-
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
-function isAsync(fn) {
- return fn[Symbol.toStringTag] === 'AsyncFunction';
-}
-
-function isAsyncGenerator(fn) {
- return fn[Symbol.toStringTag] === 'AsyncGenerator';
-}
-
-function isAsyncIterable(obj) {
- return typeof obj[Symbol.asyncIterator] === 'function';
-}
-
-function wrapAsync(asyncFn) {
- if (typeof asyncFn !== 'function') throw new Error('expected a function');
- return isAsync(asyncFn) ? (0, _asyncify2.default)(asyncFn) : asyncFn;
-}
-
-exports.default = wrapAsync;
-exports.isAsync = isAsync;
-exports.isAsyncGenerator = isAsyncGenerator;
-exports.isAsyncIterable = isAsyncIterable;
-},{"../asyncify":93}],112:[function(require,module,exports){
-'use strict';
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.default = series;
-
-var _parallel2 = require('./internal/parallel');
-
-var _parallel3 = _interopRequireDefault(_parallel2);
-
-var _eachOfSeries = require('./eachOfSeries');
-
-var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries);
-
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
-/**
- * Run the functions in the `tasks` collection in series, each one running once
- * the previous function has completed. If any functions in the series pass an
- * error to its callback, no more functions are run, and `callback` is
- * immediately called with the value of the error. Otherwise, `callback`
- * receives an array of results when `tasks` have completed.
- *
- * It is also possible to use an object instead of an array. Each property will
- * be run as a function, and the results will be passed to the final `callback`
- * as an object instead of an array. This can be a more readable way of handling
- * results from {@link async.series}.
- *
- * **Note** that while many implementations preserve the order of object
- * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)
- * explicitly states that
- *
- * > The mechanics and order of enumerating the properties is not specified.
- *
- * So if you rely on the order in which your series of functions are executed,
- * and want this to work on all platforms, consider using an array.
- *
- * @name series
- * @static
- * @memberOf module:ControlFlow
- * @method
- * @category Control Flow
- * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing
- * [async functions]{@link AsyncFunction} to run in series.
- * Each function can complete with any number of optional `result` values.
- * @param {Function} [callback] - An optional callback to run once all the
- * functions have completed. This function gets a results array (or object)
- * containing all the result arguments passed to the `task` callbacks. Invoked
- * with (err, result).
- * @return {Promise} a promise, if no callback is passed
- * @example
- * async.series([
- * function(callback) {
- * // do some stuff ...
- * callback(null, 'one');
- * },
- * function(callback) {
- * // do some more stuff ...
- * callback(null, 'two');
- * }
- * ],
- * // optional callback
- * function(err, results) {
- * // results is now equal to ['one', 'two']
- * });
- *
- * async.series({
- * one: function(callback) {
- * setTimeout(function() {
- * callback(null, 1);
- * }, 200);
- * },
- * two: function(callback){
- * setTimeout(function() {
- * callback(null, 2);
- * }, 100);
- * }
- * }, function(err, results) {
- * // results is now equal to: {one: 1, two: 2}
- * });
- */
-function series(tasks, callback) {
- return (0, _parallel3.default)(_eachOfSeries2.default, tasks, callback);
-}
-module.exports = exports['default'];
-},{"./eachOfSeries":96,"./internal/parallel":108}],113:[function(require,module,exports){
-/* MIT license */
-var cssKeywords = require('color-name');
-
-// NOTE: conversions should only return primitive values (i.e. arrays, or
-// values that give correct `typeof` results).
-// do not use box values types (i.e. Number(), String(), etc.)
-
-var reverseKeywords = {};
-for (var key in cssKeywords) {
- if (cssKeywords.hasOwnProperty(key)) {
- reverseKeywords[cssKeywords[key]] = key;
- }
-}
-
-var convert = module.exports = {
- rgb: {channels: 3, labels: 'rgb'},
- hsl: {channels: 3, labels: 'hsl'},
- hsv: {channels: 3, labels: 'hsv'},
- hwb: {channels: 3, labels: 'hwb'},
- cmyk: {channels: 4, labels: 'cmyk'},
- xyz: {channels: 3, labels: 'xyz'},
- lab: {channels: 3, labels: 'lab'},
- lch: {channels: 3, labels: 'lch'},
- hex: {channels: 1, labels: ['hex']},
- keyword: {channels: 1, labels: ['keyword']},
- ansi16: {channels: 1, labels: ['ansi16']},
- ansi256: {channels: 1, labels: ['ansi256']},
- hcg: {channels: 3, labels: ['h', 'c', 'g']},
- apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
- gray: {channels: 1, labels: ['gray']}
-};
-
-// hide .channels and .labels properties
-for (var model in convert) {
- if (convert.hasOwnProperty(model)) {
- if (!('channels' in convert[model])) {
- throw new Error('missing channels property: ' + model);
- }
-
- if (!('labels' in convert[model])) {
- throw new Error('missing channel labels property: ' + model);
- }
-
- if (convert[model].labels.length !== convert[model].channels) {
- throw new Error('channel and label counts mismatch: ' + model);
- }
-
- var channels = convert[model].channels;
- var labels = convert[model].labels;
- delete convert[model].channels;
- delete convert[model].labels;
- Object.defineProperty(convert[model], 'channels', {value: channels});
- Object.defineProperty(convert[model], 'labels', {value: labels});
- }
-}
-
-convert.rgb.hsl = function (rgb) {
- var r = rgb[0] / 255;
- var g = rgb[1] / 255;
- var b = rgb[2] / 255;
- var min = Math.min(r, g, b);
- var max = Math.max(r, g, b);
- var delta = max - min;
- var h;
- var s;
- var l;
-
- if (max === min) {
- h = 0;
- } else if (r === max) {
- h = (g - b) / delta;
- } else if (g === max) {
- h = 2 + (b - r) / delta;
- } else if (b === max) {
- h = 4 + (r - g) / delta;
- }
-
- h = Math.min(h * 60, 360);
-
- if (h < 0) {
- h += 360;
- }
-
- l = (min + max) / 2;
-
- if (max === min) {
- s = 0;
- } else if (l <= 0.5) {
- s = delta / (max + min);
- } else {
- s = delta / (2 - max - min);
- }
-
- return [h, s * 100, l * 100];
-};
-
-convert.rgb.hsv = function (rgb) {
- var rdif;
- var gdif;
- var bdif;
- var h;
- var s;
-
- var r = rgb[0] / 255;
- var g = rgb[1] / 255;
- var b = rgb[2] / 255;
- var v = Math.max(r, g, b);
- var diff = v - Math.min(r, g, b);
- var diffc = function (c) {
- return (v - c) / 6 / diff + 1 / 2;
- };
-
- if (diff === 0) {
- h = s = 0;
- } else {
- s = diff / v;
- rdif = diffc(r);
- gdif = diffc(g);
- bdif = diffc(b);
-
- if (r === v) {
- h = bdif - gdif;
- } else if (g === v) {
- h = (1 / 3) + rdif - bdif;
- } else if (b === v) {
- h = (2 / 3) + gdif - rdif;
- }
- if (h < 0) {
- h += 1;
- } else if (h > 1) {
- h -= 1;
- }
- }
-
- return [
- h * 360,
- s * 100,
- v * 100
- ];
-};
-
-convert.rgb.hwb = function (rgb) {
- var r = rgb[0];
- var g = rgb[1];
- var b = rgb[2];
- var h = convert.rgb.hsl(rgb)[0];
- var w = 1 / 255 * Math.min(r, Math.min(g, b));
-
- b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
-
- return [h, w * 100, b * 100];
-};
-
-convert.rgb.cmyk = function (rgb) {
- var r = rgb[0] / 255;
- var g = rgb[1] / 255;
- var b = rgb[2] / 255;
- var c;
- var m;
- var y;
- var k;
-
- k = Math.min(1 - r, 1 - g, 1 - b);
- c = (1 - r - k) / (1 - k) || 0;
- m = (1 - g - k) / (1 - k) || 0;
- y = (1 - b - k) / (1 - k) || 0;
-
- return [c * 100, m * 100, y * 100, k * 100];
-};
-
-/**
- * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
- * */
-function comparativeDistance(x, y) {
- return (
- Math.pow(x[0] - y[0], 2) +
- Math.pow(x[1] - y[1], 2) +
- Math.pow(x[2] - y[2], 2)
- );
-}
-
-convert.rgb.keyword = function (rgb) {
- var reversed = reverseKeywords[rgb];
- if (reversed) {
- return reversed;
- }
-
- var currentClosestDistance = Infinity;
- var currentClosestKeyword;
-
- for (var keyword in cssKeywords) {
- if (cssKeywords.hasOwnProperty(keyword)) {
- var value = cssKeywords[keyword];
-
- // Compute comparative distance
- var distance = comparativeDistance(rgb, value);
-
- // Check if its less, if so set as closest
- if (distance < currentClosestDistance) {
- currentClosestDistance = distance;
- currentClosestKeyword = keyword;
- }
- }
- }
-
- return currentClosestKeyword;
-};
-
-convert.keyword.rgb = function (keyword) {
- return cssKeywords[keyword];
-};
-
-convert.rgb.xyz = function (rgb) {
- var r = rgb[0] / 255;
- var g = rgb[1] / 255;
- var b = rgb[2] / 255;
-
- // assume sRGB
- r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
- g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
- b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
-
- var x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
- var y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
- var z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
-
- return [x * 100, y * 100, z * 100];
-};
-
-convert.rgb.lab = function (rgb) {
- var xyz = convert.rgb.xyz(rgb);
- var x = xyz[0];
- var y = xyz[1];
- var z = xyz[2];
- var l;
- var a;
- var b;
-
- x /= 95.047;
- y /= 100;
- z /= 108.883;
-
- x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
- y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
- z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
-
- l = (116 * y) - 16;
- a = 500 * (x - y);
- b = 200 * (y - z);
-
- return [l, a, b];
-};
-
-convert.hsl.rgb = function (hsl) {
- var h = hsl[0] / 360;
- var s = hsl[1] / 100;
- var l = hsl[2] / 100;
- var t1;
- var t2;
- var t3;
- var rgb;
- var val;
-
- if (s === 0) {
- val = l * 255;
- return [val, val, val];
- }
-
- if (l < 0.5) {
- t2 = l * (1 + s);
- } else {
- t2 = l + s - l * s;
- }
-
- t1 = 2 * l - t2;
-
- rgb = [0, 0, 0];
- for (var i = 0; i < 3; i++) {
- t3 = h + 1 / 3 * -(i - 1);
- if (t3 < 0) {
- t3++;
- }
- if (t3 > 1) {
- t3--;
- }
-
- if (6 * t3 < 1) {
- val = t1 + (t2 - t1) * 6 * t3;
- } else if (2 * t3 < 1) {
- val = t2;
- } else if (3 * t3 < 2) {
- val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
- } else {
- val = t1;
- }
-
- rgb[i] = val * 255;
- }
-
- return rgb;
-};
-
-convert.hsl.hsv = function (hsl) {
- var h = hsl[0];
- var s = hsl[1] / 100;
- var l = hsl[2] / 100;
- var smin = s;
- var lmin = Math.max(l, 0.01);
- var sv;
- var v;
-
- l *= 2;
- s *= (l <= 1) ? l : 2 - l;
- smin *= lmin <= 1 ? lmin : 2 - lmin;
- v = (l + s) / 2;
- sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
-
- return [h, sv * 100, v * 100];
-};
-
-convert.hsv.rgb = function (hsv) {
- var h = hsv[0] / 60;
- var s = hsv[1] / 100;
- var v = hsv[2] / 100;
- var hi = Math.floor(h) % 6;
-
- var f = h - Math.floor(h);
- var p = 255 * v * (1 - s);
- var q = 255 * v * (1 - (s * f));
- var t = 255 * v * (1 - (s * (1 - f)));
- v *= 255;
-
- switch (hi) {
- case 0:
- return [v, t, p];
- case 1:
- return [q, v, p];
- case 2:
- return [p, v, t];
- case 3:
- return [p, q, v];
- case 4:
- return [t, p, v];
- case 5:
- return [v, p, q];
- }
-};
-
-convert.hsv.hsl = function (hsv) {
- var h = hsv[0];
- var s = hsv[1] / 100;
- var v = hsv[2] / 100;
- var vmin = Math.max(v, 0.01);
- var lmin;
- var sl;
- var l;
-
- l = (2 - s) * v;
- lmin = (2 - s) * vmin;
- sl = s * vmin;
- sl /= (lmin <= 1) ? lmin : 2 - lmin;
- sl = sl || 0;
- l /= 2;
-
- return [h, sl * 100, l * 100];
-};
-
-// http://dev.w3.org/csswg/css-color/#hwb-to-rgb
-convert.hwb.rgb = function (hwb) {
- var h = hwb[0] / 360;
- var wh = hwb[1] / 100;
- var bl = hwb[2] / 100;
- var ratio = wh + bl;
- var i;
- var v;
- var f;
- var n;
-
- // wh + bl cant be > 1
- if (ratio > 1) {
- wh /= ratio;
- bl /= ratio;
- }
-
- i = Math.floor(6 * h);
- v = 1 - bl;
- f = 6 * h - i;
-
- if ((i & 0x01) !== 0) {
- f = 1 - f;
- }
-
- n = wh + f * (v - wh); // linear interpolation
-
- var r;
- var g;
- var b;
- switch (i) {
- default:
- case 6:
- case 0: r = v; g = n; b = wh; break;
- case 1: r = n; g = v; b = wh; break;
- case 2: r = wh; g = v; b = n; break;
- case 3: r = wh; g = n; b = v; break;
- case 4: r = n; g = wh; b = v; break;
- case 5: r = v; g = wh; b = n; break;
- }
-
- return [r * 255, g * 255, b * 255];
-};
-
-convert.cmyk.rgb = function (cmyk) {
- var c = cmyk[0] / 100;
- var m = cmyk[1] / 100;
- var y = cmyk[2] / 100;
- var k = cmyk[3] / 100;
- var r;
- var g;
- var b;
-
- r = 1 - Math.min(1, c * (1 - k) + k);
- g = 1 - Math.min(1, m * (1 - k) + k);
- b = 1 - Math.min(1, y * (1 - k) + k);
-
- return [r * 255, g * 255, b * 255];
-};
-
-convert.xyz.rgb = function (xyz) {
- var x = xyz[0] / 100;
- var y = xyz[1] / 100;
- var z = xyz[2] / 100;
- var r;
- var g;
- var b;
-
- r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
- g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
- b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
-
- // assume sRGB
- r = r > 0.0031308
- ? ((1.055 * Math.pow(r, 1.0 / 2.4)) - 0.055)
- : r * 12.92;
-
- g = g > 0.0031308
- ? ((1.055 * Math.pow(g, 1.0 / 2.4)) - 0.055)
- : g * 12.92;
-
- b = b > 0.0031308
- ? ((1.055 * Math.pow(b, 1.0 / 2.4)) - 0.055)
- : b * 12.92;
-
- r = Math.min(Math.max(0, r), 1);
- g = Math.min(Math.max(0, g), 1);
- b = Math.min(Math.max(0, b), 1);
-
- return [r * 255, g * 255, b * 255];
-};
-
-convert.xyz.lab = function (xyz) {
- var x = xyz[0];
- var y = xyz[1];
- var z = xyz[2];
- var l;
- var a;
- var b;
-
- x /= 95.047;
- y /= 100;
- z /= 108.883;
-
- x = x > 0.008856 ? Math.pow(x, 1 / 3) : (7.787 * x) + (16 / 116);
- y = y > 0.008856 ? Math.pow(y, 1 / 3) : (7.787 * y) + (16 / 116);
- z = z > 0.008856 ? Math.pow(z, 1 / 3) : (7.787 * z) + (16 / 116);
-
- l = (116 * y) - 16;
- a = 500 * (x - y);
- b = 200 * (y - z);
-
- return [l, a, b];
-};
-
-convert.lab.xyz = function (lab) {
- var l = lab[0];
- var a = lab[1];
- var b = lab[2];
- var x;
- var y;
- var z;
-
- y = (l + 16) / 116;
- x = a / 500 + y;
- z = y - b / 200;
-
- var y2 = Math.pow(y, 3);
- var x2 = Math.pow(x, 3);
- var z2 = Math.pow(z, 3);
- y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
- x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
- z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
-
- x *= 95.047;
- y *= 100;
- z *= 108.883;
-
- return [x, y, z];
-};
-
-convert.lab.lch = function (lab) {
- var l = lab[0];
- var a = lab[1];
- var b = lab[2];
- var hr;
- var h;
- var c;
-
- hr = Math.atan2(b, a);
- h = hr * 360 / 2 / Math.PI;
-
- if (h < 0) {
- h += 360;
- }
-
- c = Math.sqrt(a * a + b * b);
-
- return [l, c, h];
-};
-
-convert.lch.lab = function (lch) {
- var l = lch[0];
- var c = lch[1];
- var h = lch[2];
- var a;
- var b;
- var hr;
-
- hr = h / 360 * 2 * Math.PI;
- a = c * Math.cos(hr);
- b = c * Math.sin(hr);
-
- return [l, a, b];
-};
-
-convert.rgb.ansi16 = function (args) {
- var r = args[0];
- var g = args[1];
- var b = args[2];
- var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization
-
- value = Math.round(value / 50);
-
- if (value === 0) {
- return 30;
- }
-
- var ansi = 30
- + ((Math.round(b / 255) << 2)
- | (Math.round(g / 255) << 1)
- | Math.round(r / 255));
-
- if (value === 2) {
- ansi += 60;
- }
-
- return ansi;
-};
-
-convert.hsv.ansi16 = function (args) {
- // optimization here; we already know the value and don't need to get
- // it converted for us.
- return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
-};
-
-convert.rgb.ansi256 = function (args) {
- var r = args[0];
- var g = args[1];
- var b = args[2];
-
- // we use the extended greyscale palette here, with the exception of
- // black and white. normal palette only has 4 greyscale shades.
- if (r === g && g === b) {
- if (r < 8) {
- return 16;
- }
-
- if (r > 248) {
- return 231;
- }
-
- return Math.round(((r - 8) / 247) * 24) + 232;
- }
-
- var ansi = 16
- + (36 * Math.round(r / 255 * 5))
- + (6 * Math.round(g / 255 * 5))
- + Math.round(b / 255 * 5);
-
- return ansi;
-};
-
-convert.ansi16.rgb = function (args) {
- var color = args % 10;
-
- // handle greyscale
- if (color === 0 || color === 7) {
- if (args > 50) {
- color += 3.5;
- }
-
- color = color / 10.5 * 255;
-
- return [color, color, color];
- }
-
- var mult = (~~(args > 50) + 1) * 0.5;
- var r = ((color & 1) * mult) * 255;
- var g = (((color >> 1) & 1) * mult) * 255;
- var b = (((color >> 2) & 1) * mult) * 255;
-
- return [r, g, b];
-};
-
-convert.ansi256.rgb = function (args) {
- // handle greyscale
- if (args >= 232) {
- var c = (args - 232) * 10 + 8;
- return [c, c, c];
- }
-
- args -= 16;
-
- var rem;
- var r = Math.floor(args / 36) / 5 * 255;
- var g = Math.floor((rem = args % 36) / 6) / 5 * 255;
- var b = (rem % 6) / 5 * 255;
-
- return [r, g, b];
-};
-
-convert.rgb.hex = function (args) {
- var integer = ((Math.round(args[0]) & 0xFF) << 16)
- + ((Math.round(args[1]) & 0xFF) << 8)
- + (Math.round(args[2]) & 0xFF);
-
- var string = integer.toString(16).toUpperCase();
- return '000000'.substring(string.length) + string;
-};
-
-convert.hex.rgb = function (args) {
- var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
- if (!match) {
- return [0, 0, 0];
- }
-
- var colorString = match[0];
-
- if (match[0].length === 3) {
- colorString = colorString.split('').map(function (char) {
- return char + char;
- }).join('');
- }
-
- var integer = parseInt(colorString, 16);
- var r = (integer >> 16) & 0xFF;
- var g = (integer >> 8) & 0xFF;
- var b = integer & 0xFF;
-
- return [r, g, b];
-};
-
-convert.rgb.hcg = function (rgb) {
- var r = rgb[0] / 255;
- var g = rgb[1] / 255;
- var b = rgb[2] / 255;
- var max = Math.max(Math.max(r, g), b);
- var min = Math.min(Math.min(r, g), b);
- var chroma = (max - min);
- var grayscale;
- var hue;
-
- if (chroma < 1) {
- grayscale = min / (1 - chroma);
- } else {
- grayscale = 0;
- }
-
- if (chroma <= 0) {
- hue = 0;
- } else
- if (max === r) {
- hue = ((g - b) / chroma) % 6;
- } else
- if (max === g) {
- hue = 2 + (b - r) / chroma;
- } else {
- hue = 4 + (r - g) / chroma + 4;
- }
-
- hue /= 6;
- hue %= 1;
-
- return [hue * 360, chroma * 100, grayscale * 100];
-};
-
-convert.hsl.hcg = function (hsl) {
- var s = hsl[1] / 100;
- var l = hsl[2] / 100;
- var c = 1;
- var f = 0;
-
- if (l < 0.5) {
- c = 2.0 * s * l;
- } else {
- c = 2.0 * s * (1.0 - l);
- }
-
- if (c < 1.0) {
- f = (l - 0.5 * c) / (1.0 - c);
- }
-
- return [hsl[0], c * 100, f * 100];
-};
-
-convert.hsv.hcg = function (hsv) {
- var s = hsv[1] / 100;
- var v = hsv[2] / 100;
-
- var c = s * v;
- var f = 0;
-
- if (c < 1.0) {
- f = (v - c) / (1 - c);
- }
-
- return [hsv[0], c * 100, f * 100];
-};
-
-convert.hcg.rgb = function (hcg) {
- var h = hcg[0] / 360;
- var c = hcg[1] / 100;
- var g = hcg[2] / 100;
-
- if (c === 0.0) {
- return [g * 255, g * 255, g * 255];
- }
-
- var pure = [0, 0, 0];
- var hi = (h % 1) * 6;
- var v = hi % 1;
- var w = 1 - v;
- var mg = 0;
-
- switch (Math.floor(hi)) {
- case 0:
- pure[0] = 1; pure[1] = v; pure[2] = 0; break;
- case 1:
- pure[0] = w; pure[1] = 1; pure[2] = 0; break;
- case 2:
- pure[0] = 0; pure[1] = 1; pure[2] = v; break;
- case 3:
- pure[0] = 0; pure[1] = w; pure[2] = 1; break;
- case 4:
- pure[0] = v; pure[1] = 0; pure[2] = 1; break;
- default:
- pure[0] = 1; pure[1] = 0; pure[2] = w;
- }
-
- mg = (1.0 - c) * g;
-
- return [
- (c * pure[0] + mg) * 255,
- (c * pure[1] + mg) * 255,
- (c * pure[2] + mg) * 255
- ];
-};
-
-convert.hcg.hsv = function (hcg) {
- var c = hcg[1] / 100;
- var g = hcg[2] / 100;
-
- var v = c + g * (1.0 - c);
- var f = 0;
-
- if (v > 0.0) {
- f = c / v;
- }
-
- return [hcg[0], f * 100, v * 100];
-};
-
-convert.hcg.hsl = function (hcg) {
- var c = hcg[1] / 100;
- var g = hcg[2] / 100;
-
- var l = g * (1.0 - c) + 0.5 * c;
- var s = 0;
-
- if (l > 0.0 && l < 0.5) {
- s = c / (2 * l);
- } else
- if (l >= 0.5 && l < 1.0) {
- s = c / (2 * (1 - l));
- }
-
- return [hcg[0], s * 100, l * 100];
-};
-
-convert.hcg.hwb = function (hcg) {
- var c = hcg[1] / 100;
- var g = hcg[2] / 100;
- var v = c + g * (1.0 - c);
- return [hcg[0], (v - c) * 100, (1 - v) * 100];
-};
-
-convert.hwb.hcg = function (hwb) {
- var w = hwb[1] / 100;
- var b = hwb[2] / 100;
- var v = 1 - b;
- var c = v - w;
- var g = 0;
-
- if (c < 1) {
- g = (v - c) / (1 - c);
- }
-
- return [hwb[0], c * 100, g * 100];
-};
-
-convert.apple.rgb = function (apple) {
- return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
-};
-
-convert.rgb.apple = function (rgb) {
- return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
-};
-
-convert.gray.rgb = function (args) {
- return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
-};
-
-convert.gray.hsl = convert.gray.hsv = function (args) {
- return [0, 0, args[0]];
-};
-
-convert.gray.hwb = function (gray) {
- return [0, 100, gray[0]];
-};
-
-convert.gray.cmyk = function (gray) {
- return [0, 0, 0, gray[0]];
-};
-
-convert.gray.lab = function (gray) {
- return [gray[0], 0, 0];
-};
-
-convert.gray.hex = function (gray) {
- var val = Math.round(gray[0] / 100 * 255) & 0xFF;
- var integer = (val << 16) + (val << 8) + val;
-
- var string = integer.toString(16).toUpperCase();
- return '000000'.substring(string.length) + string;
-};
-
-convert.rgb.gray = function (rgb) {
- var val = (rgb[0] + rgb[1] + rgb[2]) / 3;
- return [val / 255 * 100];
-};
-
-},{"color-name":116}],114:[function(require,module,exports){
-var conversions = require('./conversions');
-var route = require('./route');
-
-var convert = {};
-
-var models = Object.keys(conversions);
-
-function wrapRaw(fn) {
- var wrappedFn = function (args) {
- if (args === undefined || args === null) {
- return args;
- }
-
- if (arguments.length > 1) {
- args = Array.prototype.slice.call(arguments);
- }
-
- return fn(args);
- };
-
- // preserve .conversion property if there is one
- if ('conversion' in fn) {
- wrappedFn.conversion = fn.conversion;
- }
-
- return wrappedFn;
-}
-
-function wrapRounded(fn) {
- var wrappedFn = function (args) {
- if (args === undefined || args === null) {
- return args;
- }
-
- if (arguments.length > 1) {
- args = Array.prototype.slice.call(arguments);
- }
-
- var result = fn(args);
-
- // we're assuming the result is an array here.
- // see notice in conversions.js; don't use box types
- // in conversion functions.
- if (typeof result === 'object') {
- for (var len = result.length, i = 0; i < len; i++) {
- result[i] = Math.round(result[i]);
- }
- }
-
- return result;
- };
-
- // preserve .conversion property if there is one
- if ('conversion' in fn) {
- wrappedFn.conversion = fn.conversion;
- }
-
- return wrappedFn;
-}
-
-models.forEach(function (fromModel) {
- convert[fromModel] = {};
-
- Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
- Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
-
- var routes = route(fromModel);
- var routeModels = Object.keys(routes);
-
- routeModels.forEach(function (toModel) {
- var fn = routes[toModel];
-
- convert[fromModel][toModel] = wrapRounded(fn);
- convert[fromModel][toModel].raw = wrapRaw(fn);
- });
-});
-
-module.exports = convert;
-
-},{"./conversions":113,"./route":115}],115:[function(require,module,exports){
-var conversions = require('./conversions');
-
-/*
- this function routes a model to all other models.
-
- all functions that are routed have a property `.conversion` attached
- to the returned synthetic function. This property is an array
- of strings, each with the steps in between the 'from' and 'to'
- color models (inclusive).
-
- conversions that are not possible simply are not included.
-*/
-
-function buildGraph() {
- var graph = {};
- // https://jsperf.com/object-keys-vs-for-in-with-closure/3
- var models = Object.keys(conversions);
-
- for (var len = models.length, i = 0; i < len; i++) {
- graph[models[i]] = {
- // http://jsperf.com/1-vs-infinity
- // micro-opt, but this is simple.
- distance: -1,
- parent: null
- };
- }
-
- return graph;
-}
-
-// https://en.wikipedia.org/wiki/Breadth-first_search
-function deriveBFS(fromModel) {
- var graph = buildGraph();
- var queue = [fromModel]; // unshift -> queue -> pop
-
- graph[fromModel].distance = 0;
-
- while (queue.length) {
- var current = queue.pop();
- var adjacents = Object.keys(conversions[current]);
-
- for (var len = adjacents.length, i = 0; i < len; i++) {
- var adjacent = adjacents[i];
- var node = graph[adjacent];
-
- if (node.distance === -1) {
- node.distance = graph[current].distance + 1;
- node.parent = current;
- queue.unshift(adjacent);
- }
- }
- }
-
- return graph;
-}
-
-function link(from, to) {
- return function (args) {
- return to(from(args));
- };
-}
-
-function wrapConversion(toModel, graph) {
- var path = [graph[toModel].parent, toModel];
- var fn = conversions[graph[toModel].parent][toModel];
-
- var cur = graph[toModel].parent;
- while (graph[cur].parent) {
- path.unshift(graph[cur].parent);
- fn = link(conversions[graph[cur].parent][cur], fn);
- cur = graph[cur].parent;
- }
-
- fn.conversion = path;
- return fn;
-}
-
-module.exports = function (fromModel) {
- var graph = deriveBFS(fromModel);
- var conversion = {};
-
- var models = Object.keys(graph);
- for (var len = models.length, i = 0; i < len; i++) {
- var toModel = models[i];
- var node = graph[toModel];
-
- if (node.parent === null) {
- // no possible conversion, or this node is the source model.
- continue;
- }
-
- conversion[toModel] = wrapConversion(toModel, graph);
- }
-
- return conversion;
-};
-
-
-},{"./conversions":113}],116:[function(require,module,exports){
-'use strict'
-
-module.exports = {
- "aliceblue": [240, 248, 255],
- "antiquewhite": [250, 235, 215],
- "aqua": [0, 255, 255],
- "aquamarine": [127, 255, 212],
- "azure": [240, 255, 255],
- "beige": [245, 245, 220],
- "bisque": [255, 228, 196],
- "black": [0, 0, 0],
- "blanchedalmond": [255, 235, 205],
- "blue": [0, 0, 255],
- "blueviolet": [138, 43, 226],
- "brown": [165, 42, 42],
- "burlywood": [222, 184, 135],
- "cadetblue": [95, 158, 160],
- "chartreuse": [127, 255, 0],
- "chocolate": [210, 105, 30],
- "coral": [255, 127, 80],
- "cornflowerblue": [100, 149, 237],
- "cornsilk": [255, 248, 220],
- "crimson": [220, 20, 60],
- "cyan": [0, 255, 255],
- "darkblue": [0, 0, 139],
- "darkcyan": [0, 139, 139],
- "darkgoldenrod": [184, 134, 11],
- "darkgray": [169, 169, 169],
- "darkgreen": [0, 100, 0],
- "darkgrey": [169, 169, 169],
- "darkkhaki": [189, 183, 107],
- "darkmagenta": [139, 0, 139],
- "darkolivegreen": [85, 107, 47],
- "darkorange": [255, 140, 0],
- "darkorchid": [153, 50, 204],
- "darkred": [139, 0, 0],
- "darksalmon": [233, 150, 122],
- "darkseagreen": [143, 188, 143],
- "darkslateblue": [72, 61, 139],
- "darkslategray": [47, 79, 79],
- "darkslategrey": [47, 79, 79],
- "darkturquoise": [0, 206, 209],
- "darkviolet": [148, 0, 211],
- "deeppink": [255, 20, 147],
- "deepskyblue": [0, 191, 255],
- "dimgray": [105, 105, 105],
- "dimgrey": [105, 105, 105],
- "dodgerblue": [30, 144, 255],
- "firebrick": [178, 34, 34],
- "floralwhite": [255, 250, 240],
- "forestgreen": [34, 139, 34],
- "fuchsia": [255, 0, 255],
- "gainsboro": [220, 220, 220],
- "ghostwhite": [248, 248, 255],
- "gold": [255, 215, 0],
- "goldenrod": [218, 165, 32],
- "gray": [128, 128, 128],
- "green": [0, 128, 0],
- "greenyellow": [173, 255, 47],
- "grey": [128, 128, 128],
- "honeydew": [240, 255, 240],
- "hotpink": [255, 105, 180],
- "indianred": [205, 92, 92],
- "indigo": [75, 0, 130],
- "ivory": [255, 255, 240],
- "khaki": [240, 230, 140],
- "lavender": [230, 230, 250],
- "lavenderblush": [255, 240, 245],
- "lawngreen": [124, 252, 0],
- "lemonchiffon": [255, 250, 205],
- "lightblue": [173, 216, 230],
- "lightcoral": [240, 128, 128],
- "lightcyan": [224, 255, 255],
- "lightgoldenrodyellow": [250, 250, 210],
- "lightgray": [211, 211, 211],
- "lightgreen": [144, 238, 144],
- "lightgrey": [211, 211, 211],
- "lightpink": [255, 182, 193],
- "lightsalmon": [255, 160, 122],
- "lightseagreen": [32, 178, 170],
- "lightskyblue": [135, 206, 250],
- "lightslategray": [119, 136, 153],
- "lightslategrey": [119, 136, 153],
- "lightsteelblue": [176, 196, 222],
- "lightyellow": [255, 255, 224],
- "lime": [0, 255, 0],
- "limegreen": [50, 205, 50],
- "linen": [250, 240, 230],
- "magenta": [255, 0, 255],
- "maroon": [128, 0, 0],
- "mediumaquamarine": [102, 205, 170],
- "mediumblue": [0, 0, 205],
- "mediumorchid": [186, 85, 211],
- "mediumpurple": [147, 112, 219],
- "mediumseagreen": [60, 179, 113],
- "mediumslateblue": [123, 104, 238],
- "mediumspringgreen": [0, 250, 154],
- "mediumturquoise": [72, 209, 204],
- "mediumvioletred": [199, 21, 133],
- "midnightblue": [25, 25, 112],
- "mintcream": [245, 255, 250],
- "mistyrose": [255, 228, 225],
- "moccasin": [255, 228, 181],
- "navajowhite": [255, 222, 173],
- "navy": [0, 0, 128],
- "oldlace": [253, 245, 230],
- "olive": [128, 128, 0],
- "olivedrab": [107, 142, 35],
- "orange": [255, 165, 0],
- "orangered": [255, 69, 0],
- "orchid": [218, 112, 214],
- "palegoldenrod": [238, 232, 170],
- "palegreen": [152, 251, 152],
- "paleturquoise": [175, 238, 238],
- "palevioletred": [219, 112, 147],
- "papayawhip": [255, 239, 213],
- "peachpuff": [255, 218, 185],
- "peru": [205, 133, 63],
- "pink": [255, 192, 203],
- "plum": [221, 160, 221],
- "powderblue": [176, 224, 230],
- "purple": [128, 0, 128],
- "rebeccapurple": [102, 51, 153],
- "red": [255, 0, 0],
- "rosybrown": [188, 143, 143],
- "royalblue": [65, 105, 225],
- "saddlebrown": [139, 69, 19],
- "salmon": [250, 128, 114],
- "sandybrown": [244, 164, 96],
- "seagreen": [46, 139, 87],
- "seashell": [255, 245, 238],
- "sienna": [160, 82, 45],
- "silver": [192, 192, 192],
- "skyblue": [135, 206, 235],
- "slateblue": [106, 90, 205],
- "slategray": [112, 128, 144],
- "slategrey": [112, 128, 144],
- "snow": [255, 250, 250],
- "springgreen": [0, 255, 127],
- "steelblue": [70, 130, 180],
- "tan": [210, 180, 140],
- "teal": [0, 128, 128],
- "thistle": [216, 191, 216],
- "tomato": [255, 99, 71],
- "turquoise": [64, 224, 208],
- "violet": [238, 130, 238],
- "wheat": [245, 222, 179],
- "white": [255, 255, 255],
- "whitesmoke": [245, 245, 245],
- "yellow": [255, 255, 0],
- "yellowgreen": [154, 205, 50]
-};
-
-},{}],117:[function(require,module,exports){
-/* MIT license */
-var colorNames = require('color-name');
-var swizzle = require('simple-swizzle');
-
-var reverseNames = {};
-
-// create a list of reverse color names
-for (var name in colorNames) {
- if (colorNames.hasOwnProperty(name)) {
- reverseNames[colorNames[name]] = name;
- }
-}
-
-var cs = module.exports = {
- to: {},
- get: {}
-};
-
-cs.get = function (string) {
- var prefix = string.substring(0, 3).toLowerCase();
- var val;
- var model;
- switch (prefix) {
- case 'hsl':
- val = cs.get.hsl(string);
- model = 'hsl';
- break;
- case 'hwb':
- val = cs.get.hwb(string);
- model = 'hwb';
- break;
- default:
- val = cs.get.rgb(string);
- model = 'rgb';
- break;
- }
-
- if (!val) {
- return null;
- }
-
- return {model: model, value: val};
-};
-
-cs.get.rgb = function (string) {
- if (!string) {
- return null;
- }
-
- var abbr = /^#([a-f0-9]{3,4})$/i;
- var hex = /^#([a-f0-9]{6})([a-f0-9]{2})?$/i;
- var rgba = /^rgba?\(\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/;
- var per = /^rgba?\(\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*,\s*([+-]?[\d\.]+)\%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/;
- var keyword = /(\D+)/;
-
- var rgb = [0, 0, 0, 1];
- var match;
- var i;
- var hexAlpha;
-
- if (match = string.match(hex)) {
- hexAlpha = match[2];
- match = match[1];
-
- for (i = 0; i < 3; i++) {
- // https://jsperf.com/slice-vs-substr-vs-substring-methods-long-string/19
- var i2 = i * 2;
- rgb[i] = parseInt(match.slice(i2, i2 + 2), 16);
- }
-
- if (hexAlpha) {
- rgb[3] = parseInt(hexAlpha, 16) / 255;
- }
- } else if (match = string.match(abbr)) {
- match = match[1];
- hexAlpha = match[3];
-
- for (i = 0; i < 3; i++) {
- rgb[i] = parseInt(match[i] + match[i], 16);
- }
-
- if (hexAlpha) {
- rgb[3] = parseInt(hexAlpha + hexAlpha, 16) / 255;
- }
- } else if (match = string.match(rgba)) {
- for (i = 0; i < 3; i++) {
- rgb[i] = parseInt(match[i + 1], 0);
- }
-
- if (match[4]) {
- rgb[3] = parseFloat(match[4]);
- }
- } else if (match = string.match(per)) {
- for (i = 0; i < 3; i++) {
- rgb[i] = Math.round(parseFloat(match[i + 1]) * 2.55);
- }
-
- if (match[4]) {
- rgb[3] = parseFloat(match[4]);
- }
- } else if (match = string.match(keyword)) {
- if (match[1] === 'transparent') {
- return [0, 0, 0, 0];
- }
-
- rgb = colorNames[match[1]];
-
- if (!rgb) {
- return null;
- }
-
- rgb[3] = 1;
-
- return rgb;
- } else {
- return null;
- }
-
- for (i = 0; i < 3; i++) {
- rgb[i] = clamp(rgb[i], 0, 255);
- }
- rgb[3] = clamp(rgb[3], 0, 1);
-
- return rgb;
-};
-
-cs.get.hsl = function (string) {
- if (!string) {
- return null;
- }
-
- var hsl = /^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/;
- var match = string.match(hsl);
-
- if (match) {
- var alpha = parseFloat(match[4]);
- var h = (parseFloat(match[1]) + 360) % 360;
- var s = clamp(parseFloat(match[2]), 0, 100);
- var l = clamp(parseFloat(match[3]), 0, 100);
- var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1);
-
- return [h, s, l, a];
- }
-
- return null;
-};
-
-cs.get.hwb = function (string) {
- if (!string) {
- return null;
- }
-
- var hwb = /^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*,\s*([+-]?[\d\.]+)%\s*,\s*([+-]?[\d\.]+)%\s*(?:,\s*([+-]?[\d\.]+)\s*)?\)$/;
- var match = string.match(hwb);
-
- if (match) {
- var alpha = parseFloat(match[4]);
- var h = ((parseFloat(match[1]) % 360) + 360) % 360;
- var w = clamp(parseFloat(match[2]), 0, 100);
- var b = clamp(parseFloat(match[3]), 0, 100);
- var a = clamp(isNaN(alpha) ? 1 : alpha, 0, 1);
- return [h, w, b, a];
- }
-
- return null;
-};
-
-cs.to.hex = function () {
- var rgba = swizzle(arguments);
-
- return (
- '#' +
- hexDouble(rgba[0]) +
- hexDouble(rgba[1]) +
- hexDouble(rgba[2]) +
- (rgba[3] < 1
- ? (hexDouble(Math.round(rgba[3] * 255)))
- : '')
- );
-};
-
-cs.to.rgb = function () {
- var rgba = swizzle(arguments);
-
- return rgba.length < 4 || rgba[3] === 1
- ? 'rgb(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ')'
- : 'rgba(' + Math.round(rgba[0]) + ', ' + Math.round(rgba[1]) + ', ' + Math.round(rgba[2]) + ', ' + rgba[3] + ')';
-};
-
-cs.to.rgb.percent = function () {
- var rgba = swizzle(arguments);
-
- var r = Math.round(rgba[0] / 255 * 100);
- var g = Math.round(rgba[1] / 255 * 100);
- var b = Math.round(rgba[2] / 255 * 100);
-
- return rgba.length < 4 || rgba[3] === 1
- ? 'rgb(' + r + '%, ' + g + '%, ' + b + '%)'
- : 'rgba(' + r + '%, ' + g + '%, ' + b + '%, ' + rgba[3] + ')';
-};
-
-cs.to.hsl = function () {
- var hsla = swizzle(arguments);
- return hsla.length < 4 || hsla[3] === 1
- ? 'hsl(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%)'
- : 'hsla(' + hsla[0] + ', ' + hsla[1] + '%, ' + hsla[2] + '%, ' + hsla[3] + ')';
-};
-
-// hwb is a bit different than rgb(a) & hsl(a) since there is no alpha specific syntax
-// (hwb have alpha optional & 1 is default value)
-cs.to.hwb = function () {
- var hwba = swizzle(arguments);
-
- var a = '';
- if (hwba.length >= 4 && hwba[3] !== 1) {
- a = ', ' + hwba[3];
- }
-
- return 'hwb(' + hwba[0] + ', ' + hwba[1] + '%, ' + hwba[2] + '%' + a + ')';
-};
-
-cs.to.keyword = function (rgb) {
- return reverseNames[rgb.slice(0, 3)];
-};
-
-// helpers
-function clamp(num, min, max) {
- return Math.min(Math.max(min, num), max);
-}
-
-function hexDouble(num) {
- var str = num.toString(16).toUpperCase();
- return (str.length < 2) ? '0' + str : str;
-}
-
-},{"color-name":116,"simple-swizzle":175}],118:[function(require,module,exports){
-'use strict';
-
-var colorString = require('color-string');
-var convert = require('color-convert');
-
-var _slice = [].slice;
-
-var skippedModels = [
- // to be honest, I don't really feel like keyword belongs in color convert, but eh.
- 'keyword',
-
- // gray conflicts with some method names, and has its own method defined.
- 'gray',
-
- // shouldn't really be in color-convert either...
- 'hex'
-];
-
-var hashedModelKeys = {};
-Object.keys(convert).forEach(function (model) {
- hashedModelKeys[_slice.call(convert[model].labels).sort().join('')] = model;
-});
-
-var limiters = {};
-
-function Color(obj, model) {
- if (!(this instanceof Color)) {
- return new Color(obj, model);
- }
-
- if (model && model in skippedModels) {
- model = null;
- }
-
- if (model && !(model in convert)) {
- throw new Error('Unknown model: ' + model);
- }
-
- var i;
- var channels;
-
- if (!obj) {
- this.model = 'rgb';
- this.color = [0, 0, 0];
- this.valpha = 1;
- } else if (obj instanceof Color) {
- this.model = obj.model;
- this.color = obj.color.slice();
- this.valpha = obj.valpha;
- } else if (typeof obj === 'string') {
- var result = colorString.get(obj);
- if (result === null) {
- throw new Error('Unable to parse color from string: ' + obj);
- }
-
- this.model = result.model;
- channels = convert[this.model].channels;
- this.color = result.value.slice(0, channels);
- this.valpha = typeof result.value[channels] === 'number' ? result.value[channels] : 1;
- } else if (obj.length) {
- this.model = model || 'rgb';
- channels = convert[this.model].channels;
- var newArr = _slice.call(obj, 0, channels);
- this.color = zeroArray(newArr, channels);
- this.valpha = typeof obj[channels] === 'number' ? obj[channels] : 1;
- } else if (typeof obj === 'number') {
- // this is always RGB - can be converted later on.
- obj &= 0xFFFFFF;
- this.model = 'rgb';
- this.color = [
- (obj >> 16) & 0xFF,
- (obj >> 8) & 0xFF,
- obj & 0xFF
- ];
- this.valpha = 1;
- } else {
- this.valpha = 1;
-
- var keys = Object.keys(obj);
- if ('alpha' in obj) {
- keys.splice(keys.indexOf('alpha'), 1);
- this.valpha = typeof obj.alpha === 'number' ? obj.alpha : 0;
- }
-
- var hashedKeys = keys.sort().join('');
- if (!(hashedKeys in hashedModelKeys)) {
- throw new Error('Unable to parse color from object: ' + JSON.stringify(obj));
- }
-
- this.model = hashedModelKeys[hashedKeys];
-
- var labels = convert[this.model].labels;
- var color = [];
- for (i = 0; i < labels.length; i++) {
- color.push(obj[labels[i]]);
- }
-
- this.color = zeroArray(color);
- }
-
- // perform limitations (clamping, etc.)
- if (limiters[this.model]) {
- channels = convert[this.model].channels;
- for (i = 0; i < channels; i++) {
- var limit = limiters[this.model][i];
- if (limit) {
- this.color[i] = limit(this.color[i]);
- }
- }
- }
-
- this.valpha = Math.max(0, Math.min(1, this.valpha));
-
- if (Object.freeze) {
- Object.freeze(this);
- }
-}
-
-Color.prototype = {
- toString: function () {
- return this.string();
- },
-
- toJSON: function () {
- return this[this.model]();
- },
-
- string: function (places) {
- var self = this.model in colorString.to ? this : this.rgb();
- self = self.round(typeof places === 'number' ? places : 1);
- var args = self.valpha === 1 ? self.color : self.color.concat(this.valpha);
- return colorString.to[self.model](args);
- },
-
- percentString: function (places) {
- var self = this.rgb().round(typeof places === 'number' ? places : 1);
- var args = self.valpha === 1 ? self.color : self.color.concat(this.valpha);
- return colorString.to.rgb.percent(args);
- },
-
- array: function () {
- return this.valpha === 1 ? this.color.slice() : this.color.concat(this.valpha);
- },
-
- object: function () {
- var result = {};
- var channels = convert[this.model].channels;
- var labels = convert[this.model].labels;
-
- for (var i = 0; i < channels; i++) {
- result[labels[i]] = this.color[i];
- }
-
- if (this.valpha !== 1) {
- result.alpha = this.valpha;
- }
-
- return result;
- },
-
- unitArray: function () {
- var rgb = this.rgb().color;
- rgb[0] /= 255;
- rgb[1] /= 255;
- rgb[2] /= 255;
-
- if (this.valpha !== 1) {
- rgb.push(this.valpha);
- }
-
- return rgb;
- },
-
- unitObject: function () {
- var rgb = this.rgb().object();
- rgb.r /= 255;
- rgb.g /= 255;
- rgb.b /= 255;
-
- if (this.valpha !== 1) {
- rgb.alpha = this.valpha;
- }
-
- return rgb;
- },
-
- round: function (places) {
- places = Math.max(places || 0, 0);
- return new Color(this.color.map(roundToPlace(places)).concat(this.valpha), this.model);
- },
-
- alpha: function (val) {
- if (arguments.length) {
- return new Color(this.color.concat(Math.max(0, Math.min(1, val))), this.model);
- }
-
- return this.valpha;
- },
-
- // rgb
- red: getset('rgb', 0, maxfn(255)),
- green: getset('rgb', 1, maxfn(255)),
- blue: getset('rgb', 2, maxfn(255)),
-
- hue: getset(['hsl', 'hsv', 'hsl', 'hwb', 'hcg'], 0, function (val) { return ((val % 360) + 360) % 360; }), // eslint-disable-line brace-style
-
- saturationl: getset('hsl', 1, maxfn(100)),
- lightness: getset('hsl', 2, maxfn(100)),
-
- saturationv: getset('hsv', 1, maxfn(100)),
- value: getset('hsv', 2, maxfn(100)),
-
- chroma: getset('hcg', 1, maxfn(100)),
- gray: getset('hcg', 2, maxfn(100)),
-
- white: getset('hwb', 1, maxfn(100)),
- wblack: getset('hwb', 2, maxfn(100)),
-
- cyan: getset('cmyk', 0, maxfn(100)),
- magenta: getset('cmyk', 1, maxfn(100)),
- yellow: getset('cmyk', 2, maxfn(100)),
- black: getset('cmyk', 3, maxfn(100)),
-
- x: getset('xyz', 0, maxfn(100)),
- y: getset('xyz', 1, maxfn(100)),
- z: getset('xyz', 2, maxfn(100)),
-
- l: getset('lab', 0, maxfn(100)),
- a: getset('lab', 1),
- b: getset('lab', 2),
-
- keyword: function (val) {
- if (arguments.length) {
- return new Color(val);
- }
-
- return convert[this.model].keyword(this.color);
- },
-
- hex: function (val) {
- if (arguments.length) {
- return new Color(val);
- }
-
- return colorString.to.hex(this.rgb().round().color);
- },
-
- rgbNumber: function () {
- var rgb = this.rgb().color;
- return ((rgb[0] & 0xFF) << 16) | ((rgb[1] & 0xFF) << 8) | (rgb[2] & 0xFF);
- },
-
- luminosity: function () {
- // http://www.w3.org/TR/WCAG20/#relativeluminancedef
- var rgb = this.rgb().color;
-
- var lum = [];
- for (var i = 0; i < rgb.length; i++) {
- var chan = rgb[i] / 255;
- lum[i] = (chan <= 0.03928) ? chan / 12.92 : Math.pow(((chan + 0.055) / 1.055), 2.4);
- }
-
- return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2];
- },
-
- contrast: function (color2) {
- // http://www.w3.org/TR/WCAG20/#contrast-ratiodef
- var lum1 = this.luminosity();
- var lum2 = color2.luminosity();
-
- if (lum1 > lum2) {
- return (lum1 + 0.05) / (lum2 + 0.05);
- }
-
- return (lum2 + 0.05) / (lum1 + 0.05);
- },
-
- level: function (color2) {
- var contrastRatio = this.contrast(color2);
- if (contrastRatio >= 7.1) {
- return 'AAA';
- }
-
- return (contrastRatio >= 4.5) ? 'AA' : '';
- },
-
- isDark: function () {
- // YIQ equation from http://24ways.org/2010/calculating-color-contrast
- var rgb = this.rgb().color;
- var yiq = (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
- return yiq < 128;
- },
-
- isLight: function () {
- return !this.isDark();
- },
-
- negate: function () {
- var rgb = this.rgb();
- for (var i = 0; i < 3; i++) {
- rgb.color[i] = 255 - rgb.color[i];
- }
- return rgb;
- },
-
- lighten: function (ratio) {
- var hsl = this.hsl();
- hsl.color[2] += hsl.color[2] * ratio;
- return hsl;
- },
-
- darken: function (ratio) {
- var hsl = this.hsl();
- hsl.color[2] -= hsl.color[2] * ratio;
- return hsl;
- },
-
- saturate: function (ratio) {
- var hsl = this.hsl();
- hsl.color[1] += hsl.color[1] * ratio;
- return hsl;
- },
-
- desaturate: function (ratio) {
- var hsl = this.hsl();
- hsl.color[1] -= hsl.color[1] * ratio;
- return hsl;
- },
-
- whiten: function (ratio) {
- var hwb = this.hwb();
- hwb.color[1] += hwb.color[1] * ratio;
- return hwb;
- },
-
- blacken: function (ratio) {
- var hwb = this.hwb();
- hwb.color[2] += hwb.color[2] * ratio;
- return hwb;
- },
-
- grayscale: function () {
- // http://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale
- var rgb = this.rgb().color;
- var val = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11;
- return Color.rgb(val, val, val);
- },
-
- fade: function (ratio) {
- return this.alpha(this.valpha - (this.valpha * ratio));
- },
-
- opaquer: function (ratio) {
- return this.alpha(this.valpha + (this.valpha * ratio));
- },
-
- rotate: function (degrees) {
- var hsl = this.hsl();
- var hue = hsl.color[0];
- hue = (hue + degrees) % 360;
- hue = hue < 0 ? 360 + hue : hue;
- hsl.color[0] = hue;
- return hsl;
- },
-
- mix: function (mixinColor, weight) {
- // ported from sass implementation in C
- // https://github.com/sass/libsass/blob/0e6b4a2850092356aa3ece07c6b249f0221caced/functions.cpp#L209
- var color1 = mixinColor.rgb();
- var color2 = this.rgb();
- var p = weight === undefined ? 0.5 : weight;
-
- var w = 2 * p - 1;
- var a = color1.alpha() - color2.alpha();
-
- var w1 = (((w * a === -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
- var w2 = 1 - w1;
-
- return Color.rgb(
- w1 * color1.red() + w2 * color2.red(),
- w1 * color1.green() + w2 * color2.green(),
- w1 * color1.blue() + w2 * color2.blue(),
- color1.alpha() * p + color2.alpha() * (1 - p));
- }
-};
-
-// model conversion methods and static constructors
-Object.keys(convert).forEach(function (model) {
- if (skippedModels.indexOf(model) !== -1) {
- return;
- }
-
- var channels = convert[model].channels;
-
- // conversion methods
- Color.prototype[model] = function () {
- if (this.model === model) {
- return new Color(this);
- }
-
- if (arguments.length) {
- return new Color(arguments, model);
- }
-
- var newAlpha = typeof arguments[channels] === 'number' ? channels : this.valpha;
- return new Color(assertArray(convert[this.model][model].raw(this.color)).concat(newAlpha), model);
- };
-
- // 'static' construction methods
- Color[model] = function (color) {
- if (typeof color === 'number') {
- color = zeroArray(_slice.call(arguments), channels);
- }
- return new Color(color, model);
- };
-});
-
-function roundTo(num, places) {
- return Number(num.toFixed(places));
-}
-
-function roundToPlace(places) {
- return function (num) {
- return roundTo(num, places);
- };
-}
-
-function getset(model, channel, modifier) {
- model = Array.isArray(model) ? model : [model];
-
- model.forEach(function (m) {
- (limiters[m] || (limiters[m] = []))[channel] = modifier;
- });
-
- model = model[0];
-
- return function (val) {
- var result;
-
- if (arguments.length) {
- if (modifier) {
- val = modifier(val);
- }
-
- result = this[model]();
- result.color[channel] = val;
- return result;
- }
-
- result = this[model]().color[channel];
- if (modifier) {
- result = modifier(result);
- }
-
- return result;
- };
-}
-
-function maxfn(max) {
- return function (v) {
- return Math.max(0, Math.min(max, v));
- };
-}
-
-function assertArray(val) {
- return Array.isArray(val) ? val : [val];
-}
-
-function zeroArray(arr, length) {
- for (var i = 0; i < length; i++) {
- if (typeof arr[i] !== 'number') {
- arr[i] = 0;
- }
- }
-
- return arr;
-}
-
-module.exports = Color;
-
-},{"color-convert":114,"color-string":117}],119:[function(require,module,exports){
-/*
-
-The MIT License (MIT)
-
-Original Library
- - Copyright (c) Marak Squires
-
-Additional functionality
- - 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.
-
-*/
-
-var colors = {};
-module['exports'] = colors;
-
-colors.themes = {};
-
-var util = require('util');
-var ansiStyles = colors.styles = require('./styles');
-var defineProps = Object.defineProperties;
-var newLineRegex = new RegExp(/[\r\n]+/g);
-
-colors.supportsColor = require('./system/supports-colors').supportsColor;
-
-if (typeof colors.enabled === 'undefined') {
- colors.enabled = colors.supportsColor() !== false;
-}
-
-colors.enable = function() {
- colors.enabled = true;
-};
-
-colors.disable = function() {
- colors.enabled = false;
-};
-
-colors.stripColors = colors.strip = function(str) {
- return ('' + str).replace(/\x1B\[\d+m/g, '');
-};
-
-// eslint-disable-next-line no-unused-vars
-var stylize = colors.stylize = function stylize(str, style) {
- if (!colors.enabled) {
- return str+'';
- }
-
- var styleMap = ansiStyles[style];
-
- // Stylize should work for non-ANSI styles, too
- if(!styleMap && style in colors){
- // Style maps like trap operate as functions on strings;
- // they don't have properties like open or close.
- return colors[style](str);
- }
-
- return styleMap.open + str + styleMap.close;
-};
-
-var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
-var escapeStringRegexp = function(str) {
- if (typeof str !== 'string') {
- throw new TypeError('Expected a string');
- }
- return str.replace(matchOperatorsRe, '\\$&');
-};
-
-function build(_styles) {
- var builder = function builder() {
- return applyStyle.apply(builder, arguments);
- };
- builder._styles = _styles;
- // __proto__ is used because we must return a function, but there is
- // no way to create a function with a different prototype.
- builder.__proto__ = proto;
- return builder;
-}
-
-var styles = (function() {
- var ret = {};
- ansiStyles.grey = ansiStyles.gray;
- Object.keys(ansiStyles).forEach(function(key) {
- ansiStyles[key].closeRe =
- new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
- ret[key] = {
- get: function() {
- return build(this._styles.concat(key));
- },
- };
- });
- return ret;
-})();
-
-var proto = defineProps(function colors() {}, styles);
-
-function applyStyle() {
- var args = Array.prototype.slice.call(arguments);
-
- var str = args.map(function(arg) {
- // Use weak equality check so we can colorize null/undefined in safe mode
- if (arg != null && arg.constructor === String) {
- return arg;
- } else {
- return util.inspect(arg);
- }
- }).join(' ');
-
- if (!colors.enabled || !str) {
- return str;
- }
-
- var newLinesPresent = str.indexOf('\n') != -1;
-
- var nestedStyles = this._styles;
-
- var i = nestedStyles.length;
- while (i--) {
- var code = ansiStyles[nestedStyles[i]];
- str = code.open + str.replace(code.closeRe, code.open) + code.close;
- if (newLinesPresent) {
- str = str.replace(newLineRegex, function(match) {
- return code.close + match + code.open;
- });
- }
- }
-
- return str;
-}
-
-colors.setTheme = function(theme) {
- if (typeof theme === 'string') {
- console.log('colors.setTheme now only accepts an object, not a string. ' +
- 'If you are trying to set a theme from a file, it is now your (the ' +
- 'caller\'s) responsibility to require the file. The old syntax ' +
- 'looked like colors.setTheme(__dirname + ' +
- '\'/../themes/generic-logging.js\'); The new syntax looks like '+
- 'colors.setTheme(require(__dirname + ' +
- '\'/../themes/generic-logging.js\'));');
- return;
- }
- for (var style in theme) {
- (function(style) {
- colors[style] = function(str) {
- if (typeof theme[style] === 'object') {
- var out = str;
- for (var i in theme[style]) {
- out = colors[theme[style][i]](out);
- }
- return out;
- }
- return colors[theme[style]](str);
- };
- })(style);
- }
-};
-
-function init() {
- var ret = {};
- Object.keys(styles).forEach(function(name) {
- ret[name] = {
- get: function() {
- return build([name]);
- },
- };
- });
- return ret;
-}
-
-var sequencer = function sequencer(map, str) {
- var exploded = str.split('');
- exploded = exploded.map(map);
- return exploded.join('');
-};
-
-// custom formatter methods
-colors.trap = require('./custom/trap');
-colors.zalgo = require('./custom/zalgo');
-
-// maps
-colors.maps = {};
-colors.maps.america = require('./maps/america')(colors);
-colors.maps.zebra = require('./maps/zebra')(colors);
-colors.maps.rainbow = require('./maps/rainbow')(colors);
-colors.maps.random = require('./maps/random')(colors);
-
-for (var map in colors.maps) {
- (function(map) {
- colors[map] = function(str) {
- return sequencer(colors.maps[map], str);
- };
- })(map);
-}
-
-defineProps(colors, init());
-
-},{"./custom/trap":120,"./custom/zalgo":121,"./maps/america":122,"./maps/rainbow":123,"./maps/random":124,"./maps/zebra":125,"./styles":126,"./system/supports-colors":128,"util":82}],120:[function(require,module,exports){
-module['exports'] = function runTheTrap(text, options) {
- var result = '';
- text = text || 'Run the trap, drop the bass';
- text = text.split('');
- var trap = {
- a: ['\u0040', '\u0104', '\u023a', '\u0245', '\u0394', '\u039b', '\u0414'],
- b: ['\u00df', '\u0181', '\u0243', '\u026e', '\u03b2', '\u0e3f'],
- c: ['\u00a9', '\u023b', '\u03fe'],
- d: ['\u00d0', '\u018a', '\u0500', '\u0501', '\u0502', '\u0503'],
- e: ['\u00cb', '\u0115', '\u018e', '\u0258', '\u03a3', '\u03be', '\u04bc',
- '\u0a6c'],
- f: ['\u04fa'],
- g: ['\u0262'],
- h: ['\u0126', '\u0195', '\u04a2', '\u04ba', '\u04c7', '\u050a'],
- i: ['\u0f0f'],
- j: ['\u0134'],
- k: ['\u0138', '\u04a0', '\u04c3', '\u051e'],
- l: ['\u0139'],
- m: ['\u028d', '\u04cd', '\u04ce', '\u0520', '\u0521', '\u0d69'],
- n: ['\u00d1', '\u014b', '\u019d', '\u0376', '\u03a0', '\u048a'],
- o: ['\u00d8', '\u00f5', '\u00f8', '\u01fe', '\u0298', '\u047a', '\u05dd',
- '\u06dd', '\u0e4f'],
- p: ['\u01f7', '\u048e'],
- q: ['\u09cd'],
- r: ['\u00ae', '\u01a6', '\u0210', '\u024c', '\u0280', '\u042f'],
- s: ['\u00a7', '\u03de', '\u03df', '\u03e8'],
- t: ['\u0141', '\u0166', '\u0373'],
- u: ['\u01b1', '\u054d'],
- v: ['\u05d8'],
- w: ['\u0428', '\u0460', '\u047c', '\u0d70'],
- x: ['\u04b2', '\u04fe', '\u04fc', '\u04fd'],
- y: ['\u00a5', '\u04b0', '\u04cb'],
- z: ['\u01b5', '\u0240'],
- };
- text.forEach(function(c) {
- c = c.toLowerCase();
- var chars = trap[c] || [' '];
- var rand = Math.floor(Math.random() * chars.length);
- if (typeof trap[c] !== 'undefined') {
- result += trap[c][rand];
- } else {
- result += c;
- }
- });
- return result;
-};
-
-},{}],121:[function(require,module,exports){
-// please no
-module['exports'] = function zalgo(text, options) {
- text = text || ' he is here ';
- var soul = {
- 'up': [
- '̍', '̎', '̄', '̅',
- '̿', '̑', '̆', '̐',
- '͒', '͗', '͑', '̇',
- '̈', '̊', '͂', '̓',
- '̈', '͊', '͋', '͌',
- '̃', '̂', '̌', '͐',
- '̀', '́', '̋', '̏',
- '̒', '̓', '̔', '̽',
- '̉', 'ͣ', 'ͤ', 'ͥ',
- 'ͦ', 'ͧ', 'ͨ', 'ͩ',
- 'ͪ', 'ͫ', 'ͬ', 'ͭ',
- 'ͮ', 'ͯ', '̾', '͛',
- '͆', '̚',
- ],
- 'down': [
- '̖', '̗', '̘', '̙',
- '̜', '̝', '̞', '̟',
- '̠', '̤', '̥', '̦',
- '̩', '̪', '̫', '̬',
- '̭', '̮', '̯', '̰',
- '̱', '̲', '̳', '̹',
- '̺', '̻', '̼', 'ͅ',
- '͇', '͈', '͉', '͍',
- '͎', '͓', '͔', '͕',
- '͖', '͙', '͚', '̣',
- ],
- 'mid': [
- '̕', '̛', '̀', '́',
- '͘', '̡', '̢', '̧',
- '̨', '̴', '̵', '̶',
- '͜', '͝', '͞',
- '͟', '͠', '͢', '̸',
- '̷', '͡', ' ҉',
- ],
- };
- var all = [].concat(soul.up, soul.down, soul.mid);
-
- function randomNumber(range) {
- var r = Math.floor(Math.random() * range);
- return r;
- }
-
- function isChar(character) {
- var bool = false;
- all.filter(function(i) {
- bool = (i === character);
- });
- return bool;
- }
-
-
- function heComes(text, options) {
- var result = '';
- var counts;
- var l;
- options = options || {};
- options['up'] =
- typeof options['up'] !== 'undefined' ? options['up'] : true;
- options['mid'] =
- typeof options['mid'] !== 'undefined' ? options['mid'] : true;
- options['down'] =
- typeof options['down'] !== 'undefined' ? options['down'] : true;
- options['size'] =
- typeof options['size'] !== 'undefined' ? options['size'] : 'maxi';
- text = text.split('');
- for (l in text) {
- if (isChar(l)) {
- continue;
- }
- result = result + text[l];
- counts = {'up': 0, 'down': 0, 'mid': 0};
- switch (options.size) {
- case 'mini':
- counts.up = randomNumber(8);
- counts.mid = randomNumber(2);
- counts.down = randomNumber(8);
- break;
- case 'maxi':
- counts.up = randomNumber(16) + 3;
- counts.mid = randomNumber(4) + 1;
- counts.down = randomNumber(64) + 3;
- break;
- default:
- counts.up = randomNumber(8) + 1;
- counts.mid = randomNumber(6) / 2;
- counts.down = randomNumber(8) + 1;
- break;
- }
-
- var arr = ['up', 'mid', 'down'];
- for (var d in arr) {
- var index = arr[d];
- for (var i = 0; i <= counts[index]; i++) {
- if (options[index]) {
- result = result + soul[index][randomNumber(soul[index].length)];
- }
- }
- }
- }
- return result;
- }
- // don't summon him
- return heComes(text, options);
-};
-
-
-},{}],122:[function(require,module,exports){
-module['exports'] = function(colors) {
- return function(letter, i, exploded) {
- if (letter === ' ') return letter;
- switch (i%3) {
- case 0: return colors.red(letter);
- case 1: return colors.white(letter);
- case 2: return colors.blue(letter);
- }
- };
-};
-
-},{}],123:[function(require,module,exports){
-module['exports'] = function(colors) {
- // RoY G BiV
- var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta'];
- return function(letter, i, exploded) {
- if (letter === ' ') {
- return letter;
- } else {
- return colors[rainbowColors[i++ % rainbowColors.length]](letter);
- }
- };
-};
-
-
-},{}],124:[function(require,module,exports){
-module['exports'] = function(colors) {
- var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green',
- 'blue', 'white', 'cyan', 'magenta', 'brightYellow', 'brightRed',
- 'brightGreen', 'brightBlue', 'brightWhite', 'brightCyan', 'brightMagenta'];
- return function(letter, i, exploded) {
- return letter === ' ' ? letter :
- colors[
- available[Math.round(Math.random() * (available.length - 2))]
- ](letter);
- };
-};
-
-},{}],125:[function(require,module,exports){
-module['exports'] = function(colors) {
- return function(letter, i, exploded) {
- return i % 2 === 0 ? letter : colors.inverse(letter);
- };
-};
-
-},{}],126:[function(require,module,exports){
-/*
-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.
-
-*/
-
-var styles = {};
-module['exports'] = styles;
-
-var codes = {
- reset: [0, 0],
-
- bold: [1, 22],
- dim: [2, 22],
- italic: [3, 23],
- underline: [4, 24],
- inverse: [7, 27],
- hidden: [8, 28],
- strikethrough: [9, 29],
-
- black: [30, 39],
- red: [31, 39],
- green: [32, 39],
- yellow: [33, 39],
- blue: [34, 39],
- magenta: [35, 39],
- cyan: [36, 39],
- white: [37, 39],
- gray: [90, 39],
- grey: [90, 39],
-
- brightRed: [91, 39],
- brightGreen: [92, 39],
- brightYellow: [93, 39],
- brightBlue: [94, 39],
- brightMagenta: [95, 39],
- brightCyan: [96, 39],
- brightWhite: [97, 39],
-
- bgBlack: [40, 49],
- bgRed: [41, 49],
- bgGreen: [42, 49],
- bgYellow: [43, 49],
- bgBlue: [44, 49],
- bgMagenta: [45, 49],
- bgCyan: [46, 49],
- bgWhite: [47, 49],
- bgGray: [100, 49],
- bgGrey: [100, 49],
-
- bgBrightRed: [101, 49],
- bgBrightGreen: [102, 49],
- bgBrightYellow: [103, 49],
- bgBrightBlue: [104, 49],
- bgBrightMagenta: [105, 49],
- bgBrightCyan: [106, 49],
- bgBrightWhite: [107, 49],
-
- // legacy styles for colors pre v1.0.0
- blackBG: [40, 49],
- redBG: [41, 49],
- greenBG: [42, 49],
- yellowBG: [43, 49],
- blueBG: [44, 49],
- magentaBG: [45, 49],
- cyanBG: [46, 49],
- whiteBG: [47, 49],
-
-};
-
-Object.keys(codes).forEach(function(key) {
- var val = codes[key];
- var style = styles[key] = [];
- style.open = '\u001b[' + val[0] + 'm';
- style.close = '\u001b[' + val[1] + 'm';
-});
-
-},{}],127:[function(require,module,exports){
-(function (process){(function (){
-/*
-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.
-*/
-
-'use strict';
-
-module.exports = function(flag, argv) {
- argv = argv || process.argv;
-
- var terminatorPos = argv.indexOf('--');
- var prefix = /^-{1,2}/.test(flag) ? '' : '--';
- var pos = argv.indexOf(prefix + flag);
-
- return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
-};
-
-}).call(this)}).call(this,require('_process'))
-},{"_process":34}],128:[function(require,module,exports){
-(function (process){(function (){
-/*
-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.
-
-*/
-
-'use strict';
-
-var os = require('os');
-var hasFlag = require('./has-flag.js');
-
-var env = process.env;
-
-var forceColor = void 0;
-if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) {
- forceColor = false;
-} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true')
- || hasFlag('color=always')) {
- forceColor = true;
-}
-if ('FORCE_COLOR' in env) {
- forceColor = env.FORCE_COLOR.length === 0
- || parseInt(env.FORCE_COLOR, 10) !== 0;
-}
-
-function translateLevel(level) {
- if (level === 0) {
- return false;
- }
-
- return {
- level: level,
- hasBasic: true,
- has256: level >= 2,
- has16m: level >= 3,
- };
-}
-
-function supportsColor(stream) {
- if (forceColor === false) {
- return 0;
- }
-
- if (hasFlag('color=16m') || hasFlag('color=full')
- || hasFlag('color=truecolor')) {
- return 3;
- }
-
- if (hasFlag('color=256')) {
- return 2;
- }
-
- if (stream && !stream.isTTY && forceColor !== true) {
- return 0;
- }
-
- var min = forceColor ? 1 : 0;
-
- if (process.platform === 'win32') {
- // Node.js 7.5.0 is the first version of Node.js to include a patch to
- // libuv that enables 256 color output on Windows. Anything earlier and it
- // won't work. However, here we target Node.js 8 at minimum as it is an LTS
- // release, and Node.js 7 is not. Windows 10 build 10586 is the first
- // Windows release that supports 256 colors. Windows 10 build 14931 is the
- // first release that supports 16m/TrueColor.
- var osRelease = os.release().split('.');
- if (Number(process.versions.node.split('.')[0]) >= 8
- && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
- return Number(osRelease[2]) >= 14931 ? 3 : 2;
- }
-
- return 1;
- }
-
- if ('CI' in env) {
- if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) {
- return sign in env;
- }) || env.CI_NAME === 'codeship') {
- return 1;
- }
-
- return min;
- }
-
- if ('TEAMCITY_VERSION' in env) {
- return (/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0
- );
- }
-
- if ('TERM_PROGRAM' in env) {
- var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
-
- switch (env.TERM_PROGRAM) {
- case 'iTerm.app':
- return version >= 3 ? 3 : 2;
- case 'Hyper':
- return 3;
- case 'Apple_Terminal':
- return 2;
- // No default
- }
- }
-
- if (/-256(color)?$/i.test(env.TERM)) {
- return 2;
- }
-
- if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
- return 1;
- }
-
- if ('COLORTERM' in env) {
- return 1;
- }
-
- if (env.TERM === 'dumb') {
- return min;
- }
-
- return min;
-}
-
-function getSupportLevel(stream) {
- var level = supportsColor(stream);
- return translateLevel(level);
-}
-
-module.exports = {
- supportsColor: getSupportLevel,
- stdout: getSupportLevel(process.stdout),
- stderr: getSupportLevel(process.stderr),
-};
-
-}).call(this)}).call(this,require('_process'))
-},{"./has-flag.js":127,"_process":34,"os":20}],129:[function(require,module,exports){
-//
-// Remark: Requiring this file will use the "safe" colors API,
-// which will not touch String.prototype.
-//
-// var colors = require('colors/safe');
-// colors.red("foo")
-//
-//
-var colors = require('./lib/colors');
-module['exports'] = colors;
-
-},{"./lib/colors":119}],130:[function(require,module,exports){
-'use strict';
-
-var color = require('color')
- , hex = require('text-hex');
-
-/**
- * Generate a color for a given name. But be reasonably smart about it by
- * understanding name spaces and coloring each namespace a bit lighter so they
- * still have the same base color as the root.
- *
- * @param {string} namespace The namespace
- * @param {string} [delimiter] The delimiter
- * @returns {string} color
- */
-module.exports = function colorspace(namespace, delimiter) {
- var split = namespace.split(delimiter || ':');
- var base = hex(split[0]);
-
- if (!split.length) return base;
-
- for (var i = 0, l = split.length - 1; i < l; i++) {
- base = color(base)
- .mix(color(hex(split[i + 1])))
- .saturate(1)
- .hex();
- }
-
- return base;
-};
-
-},{"color":118,"text-hex":184}],131:[function(require,module,exports){
-
-/**
- * Expose `Emitter`.
- */
-
-if (typeof module !== 'undefined') {
- module.exports = Emitter;
-}
-
-/**
- * Initialize a new `Emitter`.
- *
- * @api public
- */
-
-function Emitter(obj) {
- if (obj) return mixin(obj);
-};
-
-/**
- * Mixin the emitter properties.
- *
- * @param {Object} obj
- * @return {Object}
- * @api private
- */
-
-function mixin(obj) {
- for (var key in Emitter.prototype) {
- obj[key] = Emitter.prototype[key];
- }
- return obj;
-}
-
-/**
- * Listen on the given `event` with `fn`.
- *
- * @param {String} event
- * @param {Function} fn
- * @return {Emitter}
- * @api public
- */
-
-Emitter.prototype.on =
-Emitter.prototype.addEventListener = function(event, fn){
- this._callbacks = this._callbacks || {};
- (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
- .push(fn);
- return this;
-};
-
-/**
- * Adds an `event` listener that will be invoked a single
- * time then automatically removed.
- *
- * @param {String} event
- * @param {Function} fn
- * @return {Emitter}
- * @api public
- */
-
-Emitter.prototype.once = function(event, fn){
- function on() {
- this.off(event, on);
- fn.apply(this, arguments);
- }
-
- on.fn = fn;
- this.on(event, on);
- return this;
-};
-
-/**
- * Remove the given callback for `event` or all
- * registered callbacks.
- *
- * @param {String} event
- * @param {Function} fn
- * @return {Emitter}
- * @api public
- */
-
-Emitter.prototype.off =
-Emitter.prototype.removeListener =
-Emitter.prototype.removeAllListeners =
-Emitter.prototype.removeEventListener = function(event, fn){
- this._callbacks = this._callbacks || {};
-
- // all
- if (0 == arguments.length) {
- this._callbacks = {};
- return this;
- }
-
- // specific event
- var callbacks = this._callbacks['$' + event];
- if (!callbacks) return this;
-
- // remove all handlers
- if (1 == arguments.length) {
- delete this._callbacks['$' + event];
- return this;
- }
-
- // remove specific handler
- var cb;
- for (var i = 0; i < callbacks.length; i++) {
- cb = callbacks[i];
- if (cb === fn || cb.fn === fn) {
- callbacks.splice(i, 1);
- break;
- }
- }
-
- // Remove event specific arrays for event types that no
- // one is subscribed for to avoid memory leak.
- if (callbacks.length === 0) {
- delete this._callbacks['$' + event];
- }
-
- return this;
-};
-
-/**
- * Emit `event` with the given args.
- *
- * @param {String} event
- * @param {Mixed} ...
- * @return {Emitter}
- */
-
-Emitter.prototype.emit = function(event){
- this._callbacks = this._callbacks || {};
-
- var args = new Array(arguments.length - 1)
- , callbacks = this._callbacks['$' + event];
-
- for (var i = 1; i < arguments.length; i++) {
- args[i - 1] = arguments[i];
- }
-
- if (callbacks) {
- callbacks = callbacks.slice(0);
- for (var i = 0, len = callbacks.length; i < len; ++i) {
- callbacks[i].apply(this, args);
- }
- }
-
- return this;
-};
-
-/**
- * Return array of callbacks for `event`.
- *
- * @param {String} event
- * @return {Array}
- * @api public
- */
-
-Emitter.prototype.listeners = function(event){
- this._callbacks = this._callbacks || {};
- return this._callbacks['$' + event] || [];
-};
-
-/**
- * Check if this emitter has `event` handlers.
- *
- * @param {String} event
- * @return {Boolean}
- * @api public
- */
-
-Emitter.prototype.hasListeners = function(event){
- return !! this.listeners(event).length;
-};
-
-},{}],132:[function(require,module,exports){
-const util = require('util');
-const fs = require('fs');
-const path = require('path');
-const mkdirp = require('mkdirp');
-const errors = require('./errors');
-const interpolation = require('./interpolation');
-
-/**
- * Regular Expression to match section headers.
- * @type {RegExp}
- * @private
- */
-const SECTION = new RegExp(/\s*\[([^\]]+)]/);
-
-/**
- * Regular expression to match key, value pairs.
- * @type {RegExp}
- * @private
- */
-const KEY = new RegExp(/\s*(.*?)\s*[=:]\s*(.*)/);
-
-/**
- * Regular expression to match comments. Either starting with a
- * semi-colon or a hash.
- * @type {RegExp}
- * @private
- */
-const COMMENT = new RegExp(/^\s*[;#]/);
-
-// RL1.6 Line Boundaries (for unicode)
-// ... it shall recognize not only CRLF, LF, CR,
-// but also NEL, PS and LS.
-const LINE_BOUNDARY = new RegExp(/\r\n|[\n\r\u0085\u2028\u2029]/g);
-
-const readFileAsync = util.promisify(fs.readFile);
-const writeFileAsync = util.promisify(fs.writeFile);
-const statAsync = util.promisify(fs.stat);
-const mkdirAsync = util.promisify(mkdirp);
-
-/**
- * @constructor
- */
-function ConfigParser() {
- this._sections = {};
-}
-
-/**
- * Returns an array of the sections.
- * @returns {Array}
- */
-ConfigParser.prototype.sections = function() {
- return Object.keys(this._sections);
-};
-
-/**
- * Adds a section named section to the instance. If the section already
- * exists, a DuplicateSectionError is thrown.
- * @param {string} section - Section Name
- */
-ConfigParser.prototype.addSection = function(section) {
- if(this._sections.hasOwnProperty(section)){
- throw new errors.DuplicateSectionError(section)
- }
- this._sections[section] = {};
-};
-
-/**
- * Indicates whether the section is present in the configuration
- * file.
- * @param {string} section - Section Name
- * @returns {boolean}
- */
-ConfigParser.prototype.hasSection = function(section) {
- return this._sections.hasOwnProperty(section);
-};
-
-/**
- * Returns an array of all keys in the specified section.
- * @param {string} section - Section Name
- * @returns {Array}
- */
-ConfigParser.prototype.keys = function(section) {
- try {
- return Object.keys(this._sections[section]);
- } catch(err){
- throw new errors.NoSectionError(section);
- }
-};
-
-/**
- * Indicates whether the specified key is in the section.
- * @param {string} section - Section Name
- * @param {string} key - Key Name
- * @returns {boolean}
- */
-ConfigParser.prototype.hasKey = function (section, key) {
- return this._sections.hasOwnProperty(section) &&
- this._sections[section].hasOwnProperty(key);
-};
-
-/**
- * Reads a file and parses the configuration data.
- * @param {string|Buffer|int} file - Filename or File Descriptor
- */
-ConfigParser.prototype.read = function(file) {
- const lines = fs.readFileSync(file)
- .toString('utf8')
- .split(LINE_BOUNDARY);
- parseLines.call(this, file, lines);
-};
-
-/**
- * Reads a file asynchronously and parses the configuration data.
- * @param {string|Buffer|int} file - Filename or File Descriptor
- */
-ConfigParser.prototype.readAsync = async function(file) {
- const lines = (await readFileAsync(file))
- .toString('utf8')
- .split(LINE_BOUNDARY);
- parseLines.call(this, file, lines);
-}
-
-/**
- * Gets the value for the key in the named section.
- * @param {string} section - Section Name
- * @param {string} key - Key Name
- * @param {boolean} [raw=false] - Whether or not to replace placeholders
- * @returns {string|undefined}
- */
-ConfigParser.prototype.get = function(section, key, raw) {
- if(this._sections.hasOwnProperty(section)){
- if(raw){
- return this._sections[section][key];
- } else {
- return interpolation.interpolate(this, section, key);
- }
- }
- return undefined;
-};
-
-/**
- * Coerces value to an integer of the specified radix.
- * @param {string} section - Section Name
- * @param {string} key - Key Name
- * @param {int} [radix=10] - An integer between 2 and 36 that represents the base of the string.
- * @returns {number|undefined|NaN}
- */
-ConfigParser.prototype.getInt = function(section, key, radix) {
- if(this._sections.hasOwnProperty(section)){
- if(!radix) radix = 10;
- return parseInt(this._sections[section][key], radix);
- }
- return undefined;
-};
-
-/**
- * Coerces value to a float.
- * @param {string} section - Section Name
- * @param {string} key - Key Name
- * @returns {number|undefined|NaN}
- */
-ConfigParser.prototype.getFloat = function(section, key) {
- if(this._sections.hasOwnProperty(section)){
- return parseFloat(this._sections[section][key]);
- }
- return undefined;
-};
-
-/**
- * Returns an object with every key, value pair for the named section.
- * @param {string} section - Section Name
- * @returns {Object}
- */
-ConfigParser.prototype.items = function(section) {
- return this._sections[section];
-};
-
-/**
- * Sets the given key to the specified value.
- * @param {string} section - Section Name
- * @param {string} key - Key Name
- * @param {*} value - New Key Value
- */
-ConfigParser.prototype.set = function(section, key, value) {
- if(this._sections.hasOwnProperty(section)){
- this._sections[section][key] = value;
- }
-};
-
-/**
- * Removes the property specified by key in the named section.
- * @param {string} section - Section Name
- * @param {string} key - Key Name
- * @returns {boolean}
- */
-ConfigParser.prototype.removeKey = function(section, key) {
- // delete operator returns true if the property doesn't not exist
- if(this._sections.hasOwnProperty(section) &&
- this._sections[section].hasOwnProperty(key)){
- return delete this._sections[section][key];
- }
- return false;
-};
-
-/**
- * Removes the named section (and associated key, value pairs).
- * @param {string} section - Section Name
- * @returns {boolean}
- */
-ConfigParser.prototype.removeSection = function(section) {
- if(this._sections.hasOwnProperty(section)){
- return delete this._sections[section];
- }
- return false;
-};
-
-/**
- * Writes the representation of the config file to the
- * specified file. Comments are not preserved.
- * @param {string|Buffer|int} file - Filename or File Descriptor
- * @param {bool} [createMissingDirs=false] - Whether to create the directories in the path if they don't exist
- */
-ConfigParser.prototype.write = function(file, createMissingDirs = false) {
- if (createMissingDirs) {
- const dir = path.dirname(file);
- mkdirp.sync(dir);
- }
-
- fs.writeFileSync(file, getSectionsAsString.call(this));
-};
-
-/**
- * Writes the representation of the config file to the
- * specified file asynchronously. Comments are not preserved.
- * @param {string|Buffer|int} file - Filename or File Descriptor
- * @param {bool} [createMissingDirs=false] - Whether to create the directories in the path if they don't exist
- * @returns {Promise}
- */
-ConfigParser.prototype.writeAsync = async function(file, createMissingDirs = false) {
- if (createMissingDirs) {
- const dir = path.dirname(file);
- await mkdirAsync(dir);
- }
-
- await writeFileAsync(file, getSectionsAsString.call(this));
-}
-
-function parseLines(file, lines) {
- let curSec = null;
- lines.forEach((line, lineNumber) => {
- if(!line || line.match(COMMENT)) return;
- let res = SECTION.exec(line);
- if(res){
- const header = res[1];
- curSec = {};
- this._sections[header] = curSec;
- } else if(!curSec) {
- throw new errors.MissingSectionHeaderError(file, lineNumber, line);
- } else {
- res = KEY.exec(line);
- if(res){
- const key = res[1];
- curSec[key] = res[2];
- } else {
- throw new errors.ParseError(file, lineNumber, line);
- }
- }
- });
-}
-
-function getSectionsAsString() {
- let out = '';
- let section;
- for(section in this._sections){
- if(!this._sections.hasOwnProperty(section)) continue;
- out += ('[' + section + ']\n');
- const keys = this._sections[section];
- let key;
- for(key in keys){
- if(!keys.hasOwnProperty(key)) continue;
- let value = keys[key];
- out += (key + '=' + value + '\n');
- }
- out += '\n';
- }
- return out;
-}
-
-module.exports = ConfigParser;
-
-},{"./errors":133,"./interpolation":134,"fs":1,"mkdirp":164,"path":32,"util":82}],133:[function(require,module,exports){
-/**
- * Error thrown when addSection is called with a section
- * that already exists.
- * @param {string} section - Section Name
- * @constructor
- */
-function DuplicateSectionError(section) {
- this.name = 'DuplicateSectionError';
- this.message = section + ' already exists';
- Error.captureStackTrace(this, this.constructor);
-}
-
-/**
- * Error thrown when the section being accessed, does
- * not exist.
- * @param {string} section - Section Name
- * @constructor
- */
-function NoSectionError(section) {
- this.name = this.constructor.name;
- this.message = 'Section ' + section + ' does not exist.';
- Error.captureStackTrace(this, this.constructor);
-}
-
-/**
- * Error thrown when a file is being parsed.
- * @param {string} filename - File name
- * @param {int} lineNumber - Line Number
- * @param {string} line - Contents of the line
- * @constructor
- */
-function ParseError(filename, lineNumber, line) {
- this.name = this.constructor.name;
- this.message = 'Source contains parsing errors.\nfile: ' + filename +
- ' line: ' + lineNumber + '\n' + line;
- Error.captureStackTrace(this, this.constructor);
-}
-
-/**
- * Error thrown when there are no section headers present
- * in a file.
- * @param {string} filename - File name
- * @param {int} lineNumber - Line Number
- * @param {string} line - Contents of the line
- * @constructor
- */
-function MissingSectionHeaderError(filename, lineNumber, line) {
- this.name = this.constructor.name;
- this.message = 'File contains no section headers.\nfile: ' + filename +
- ' line: ' + lineNumber + '\n' + line;
- Error.captureStackTrace(this, this.constructor);
-}
-
-/**
- * Error thrown when the interpolate function exceeds the maximum recursion
- * depth.
- * @param {string} section - Section Name
- * @param {string} key - Key Name
- * @param {string} value - Key Value
- * @param {int} maxDepth - Maximum recursion depth
- * @constructor
- */
-function MaximumInterpolationDepthError(section, key, value, maxDepth) {
- this.name = this.constructor.name;
- this.message = 'Exceeded Maximum Recursion Depth (' + maxDepth +
- ') for key ' + key + ' in section ' + section + '\nvalue: ' + value;
- Error.captureStackTrace(this, this.constructor);
-}
-
-module.exports = {
- DuplicateSectionError,
- NoSectionError,
- ParseError,
- MissingSectionHeaderError,
- MaximumInterpolationDepthError
-};
-},{}],134:[function(require,module,exports){
-const errors = require('./errors');
-
-/**
- * Regular Expression to match placeholders.
- * @type {RegExp}
- * @private
- */
-const PLACEHOLDER = new RegExp(/%\(([\w-]+)\)s/);
-
-/**
- * Maximum recursion depth for parseValue
- * @type {number}
- */
-const MAXIMUM_INTERPOLATION_DEPTH = 50;
-
-/**
- * Recursively parses a string and replaces the placeholder ( %(key)s )
- * with the value the key points to.
- * @param {ParserConfig} parser - Parser Config Object
- * @param {string} section - Section Name
- * @param {string} key - Key Name
- */
-function interpolate(parser, section, key) {
- return interpolateRecurse(parser, section, key, 1);
-}
-
-/**
- * Interpolate Recurse
- * @param parser
- * @param section
- * @param key
- * @param depth
- * @private
- */
-function interpolateRecurse(parser, section, key, depth) {
- let value = parser.get(section, key, true);
- if(depth > MAXIMUM_INTERPOLATION_DEPTH){
- throw new errors.MaximumInterpolationDepthError(section, key, value, MAXIMUM_INTERPOLATION_DEPTH);
- }
- let res = PLACEHOLDER.exec(value);
- while(res !== null){
- const placeholder = res[1];
- const rep = interpolateRecurse(parser, section, placeholder, depth + 1);
- // replace %(key)s with the returned value next
- value = value.substr(0, res.index) + rep +
- value.substr(res.index + res[0].length);
- // get next placeholder
- res = PLACEHOLDER.exec(value);
- }
- return value;
-}
-
-module.exports = {
- interpolate,
- MAXIMUM_INTERPOLATION_DEPTH
-};
-},{"./errors":133}],135:[function(require,module,exports){
-(function (Buffer){(function (){
-// 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.
-
-// NOTE: These type checking functions intentionally don't use `instanceof`
-// because it is fragile and can be easily faked with `Object.create()`.
-
-function isArray(arg) {
- if (Array.isArray) {
- return Array.isArray(arg);
- }
- return objectToString(arg) === '[object Array]';
-}
-exports.isArray = isArray;
-
-function isBoolean(arg) {
- return typeof arg === 'boolean';
-}
-exports.isBoolean = isBoolean;
-
-function isNull(arg) {
- return arg === null;
-}
-exports.isNull = isNull;
-
-function isNullOrUndefined(arg) {
- return arg == null;
-}
-exports.isNullOrUndefined = isNullOrUndefined;
-
-function isNumber(arg) {
- return typeof arg === 'number';
-}
-exports.isNumber = isNumber;
-
-function isString(arg) {
- return typeof arg === 'string';
-}
-exports.isString = isString;
-
-function isSymbol(arg) {
- return typeof arg === 'symbol';
-}
-exports.isSymbol = isSymbol;
-
-function isUndefined(arg) {
- return arg === void 0;
-}
-exports.isUndefined = isUndefined;
-
-function isRegExp(re) {
- return objectToString(re) === '[object RegExp]';
-}
-exports.isRegExp = isRegExp;
-
-function isObject(arg) {
- return typeof arg === 'object' && arg !== null;
-}
-exports.isObject = isObject;
-
-function isDate(d) {
- return objectToString(d) === '[object Date]';
-}
-exports.isDate = isDate;
-
-function isError(e) {
- return (objectToString(e) === '[object Error]' || e instanceof Error);
-}
-exports.isError = isError;
-
-function isFunction(arg) {
- return typeof arg === 'function';
-}
-exports.isFunction = isFunction;
-
-function isPrimitive(arg) {
- return arg === null ||
- typeof arg === 'boolean' ||
- typeof arg === 'number' ||
- typeof arg === 'string' ||
- typeof arg === 'symbol' || // ES6 symbol
- typeof arg === 'undefined';
-}
-exports.isPrimitive = isPrimitive;
-
-exports.isBuffer = Buffer.isBuffer;
-
-function objectToString(o) {
- return Object.prototype.toString.call(o);
-}
-
-}).call(this)}).call(this,{"isBuffer":require("../../../../../../../../tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/NodeJS_12.13.0/node-v12.13.0-linux-x64/lib/node_modules/browserify/node_modules/is-buffer/index.js")})
-},{"../../../../../../../../tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/NodeJS_12.13.0/node-v12.13.0-linux-x64/lib/node_modules/browserify/node_modules/is-buffer/index.js":17}],136:[function(require,module,exports){
-'use strict';
-
-/**
- * Checks if a given namespace is allowed by the given variable.
- *
- * @param {String} name namespace that should be included.
- * @param {String} variable Value that needs to be tested.
- * @returns {Boolean} Indication if namespace is enabled.
- * @public
- */
-module.exports = function enabled(name, variable) {
- if (!variable) return false;
-
- var variables = variable.split(/[\s,]+/)
- , i = 0;
-
- for (; i < variables.length; i++) {
- variable = variables[i].replace('*', '.*?');
-
- if ('-' === variable.charAt(0)) {
- if ((new RegExp('^'+ variable.substr(1) +'$')).test(name)) {
- return false;
- }
-
- continue;
- }
-
- if ((new RegExp('^'+ variable +'$')).test(name)) {
- return true;
- }
- }
-
- return false;
-};
-
-},{}],137:[function(require,module,exports){
-module.exports = stringify
-stringify.default = stringify
-stringify.stable = deterministicStringify
-stringify.stableStringify = deterministicStringify
-
-var arr = []
-var replacerStack = []
-
-// Regular stringify
-function stringify (obj, replacer, spacer) {
- decirc(obj, '', [], undefined)
- var res
- if (replacerStack.length === 0) {
- res = JSON.stringify(obj, replacer, spacer)
- } else {
- res = JSON.stringify(obj, replaceGetterValues(replacer), spacer)
- }
- while (arr.length !== 0) {
- var part = arr.pop()
- if (part.length === 4) {
- Object.defineProperty(part[0], part[1], part[3])
- } else {
- part[0][part[1]] = part[2]
- }
- }
- return res
-}
-function decirc (val, k, stack, parent) {
- var i
- if (typeof val === 'object' && val !== null) {
- for (i = 0; i < stack.length; i++) {
- if (stack[i] === val) {
- var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k)
- if (propertyDescriptor.get !== undefined) {
- if (propertyDescriptor.configurable) {
- Object.defineProperty(parent, k, { value: '[Circular]' })
- arr.push([parent, k, val, propertyDescriptor])
- } else {
- replacerStack.push([val, k])
- }
- } else {
- parent[k] = '[Circular]'
- arr.push([parent, k, val])
- }
- return
- }
- }
- stack.push(val)
- // Optimize for Arrays. Big arrays could kill the performance otherwise!
- if (Array.isArray(val)) {
- for (i = 0; i < val.length; i++) {
- decirc(val[i], i, stack, val)
- }
- } else {
- var keys = Object.keys(val)
- for (i = 0; i < keys.length; i++) {
- var key = keys[i]
- decirc(val[key], key, stack, val)
- }
- }
- stack.pop()
- }
-}
-
-// Stable-stringify
-function compareFunction (a, b) {
- if (a < b) {
- return -1
- }
- if (a > b) {
- return 1
- }
- return 0
-}
-
-function deterministicStringify (obj, replacer, spacer) {
- var tmp = deterministicDecirc(obj, '', [], undefined) || obj
- var res
- if (replacerStack.length === 0) {
- res = JSON.stringify(tmp, replacer, spacer)
- } else {
- res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer)
- }
- while (arr.length !== 0) {
- var part = arr.pop()
- if (part.length === 4) {
- Object.defineProperty(part[0], part[1], part[3])
- } else {
- part[0][part[1]] = part[2]
- }
- }
- return res
-}
-
-function deterministicDecirc (val, k, stack, parent) {
- var i
- if (typeof val === 'object' && val !== null) {
- for (i = 0; i < stack.length; i++) {
- if (stack[i] === val) {
- var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k)
- if (propertyDescriptor.get !== undefined) {
- if (propertyDescriptor.configurable) {
- Object.defineProperty(parent, k, { value: '[Circular]' })
- arr.push([parent, k, val, propertyDescriptor])
- } else {
- replacerStack.push([val, k])
- }
- } else {
- parent[k] = '[Circular]'
- arr.push([parent, k, val])
- }
- return
- }
- }
- if (typeof val.toJSON === 'function') {
- return
- }
- stack.push(val)
- // Optimize for Arrays. Big arrays could kill the performance otherwise!
- if (Array.isArray(val)) {
- for (i = 0; i < val.length; i++) {
- deterministicDecirc(val[i], i, stack, val)
- }
- } else {
- // Create a temporary object in the required way
- var tmp = {}
- var keys = Object.keys(val).sort(compareFunction)
- for (i = 0; i < keys.length; i++) {
- var key = keys[i]
- deterministicDecirc(val[key], key, stack, val)
- tmp[key] = val[key]
- }
- if (parent !== undefined) {
- arr.push([parent, k, val])
- parent[k] = tmp
- } else {
- return tmp
- }
- }
- stack.pop()
- }
-}
-
-// wraps replacer function to handle values we couldn't replace
-// and mark them as [Circular]
-function replaceGetterValues (replacer) {
- replacer = replacer !== undefined ? replacer : function (k, v) { return v }
- return function (key, val) {
- if (replacerStack.length > 0) {
- for (var i = 0; i < replacerStack.length; i++) {
- var part = replacerStack[i]
- if (part[1] === key && part[0] === val) {
- val = '[Circular]'
- replacerStack.splice(i, 1)
- break
- }
- }
- }
- return replacer.call(this, key, val)
- }
-}
-
-},{}],138:[function(require,module,exports){
-(function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
- (factory((global.fecha = {})));
-}(this, (function (exports) { 'use strict';
-
- var token = /d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|Z|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g;
- var twoDigitsOptional = "[1-9]\\d?";
- var twoDigits = "\\d\\d";
- var threeDigits = "\\d{3}";
- var fourDigits = "\\d{4}";
- var word = "[^\\s]+";
- var literal = /\[([^]*?)\]/gm;
- function shorten(arr, sLen) {
- var newArr = [];
- for (var i = 0, len = arr.length; i < len; i++) {
- newArr.push(arr[i].substr(0, sLen));
- }
- return newArr;
- }
- var monthUpdate = function (arrName) { return function (v, i18n) {
- var lowerCaseArr = i18n[arrName].map(function (v) { return v.toLowerCase(); });
- var index = lowerCaseArr.indexOf(v.toLowerCase());
- if (index > -1) {
- return index;
- }
- return null;
- }; };
- function assign(origObj) {
- var args = [];
- for (var _i = 1; _i < arguments.length; _i++) {
- args[_i - 1] = arguments[_i];
- }
- for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
- var obj = args_1[_a];
- for (var key in obj) {
- // @ts-ignore ex
- origObj[key] = obj[key];
- }
- }
- return origObj;
- }
- var dayNames = [
- "Sunday",
- "Monday",
- "Tuesday",
- "Wednesday",
- "Thursday",
- "Friday",
- "Saturday"
- ];
- var monthNames = [
- "January",
- "February",
- "March",
- "April",
- "May",
- "June",
- "July",
- "August",
- "September",
- "October",
- "November",
- "December"
- ];
- var monthNamesShort = shorten(monthNames, 3);
- var dayNamesShort = shorten(dayNames, 3);
- var defaultI18n = {
- dayNamesShort: dayNamesShort,
- dayNames: dayNames,
- monthNamesShort: monthNamesShort,
- monthNames: monthNames,
- amPm: ["am", "pm"],
- DoFn: function (dayOfMonth) {
- return (dayOfMonth +
- ["th", "st", "nd", "rd"][dayOfMonth % 10 > 3
- ? 0
- : ((dayOfMonth - (dayOfMonth % 10) !== 10 ? 1 : 0) * dayOfMonth) % 10]);
- }
- };
- var globalI18n = assign({}, defaultI18n);
- var setGlobalDateI18n = function (i18n) {
- return (globalI18n = assign(globalI18n, i18n));
- };
- var regexEscape = function (str) {
- return str.replace(/[|\\{()[^$+*?.-]/g, "\\$&");
- };
- var pad = function (val, len) {
- if (len === void 0) { len = 2; }
- val = String(val);
- while (val.length < len) {
- val = "0" + val;
- }
- return val;
- };
- var formatFlags = {
- D: function (dateObj) { return String(dateObj.getDate()); },
- DD: function (dateObj) { return pad(dateObj.getDate()); },
- Do: function (dateObj, i18n) {
- return i18n.DoFn(dateObj.getDate());
- },
- d: function (dateObj) { return String(dateObj.getDay()); },
- dd: function (dateObj) { return pad(dateObj.getDay()); },
- ddd: function (dateObj, i18n) {
- return i18n.dayNamesShort[dateObj.getDay()];
- },
- dddd: function (dateObj, i18n) {
- return i18n.dayNames[dateObj.getDay()];
- },
- M: function (dateObj) { return String(dateObj.getMonth() + 1); },
- MM: function (dateObj) { return pad(dateObj.getMonth() + 1); },
- MMM: function (dateObj, i18n) {
- return i18n.monthNamesShort[dateObj.getMonth()];
- },
- MMMM: function (dateObj, i18n) {
- return i18n.monthNames[dateObj.getMonth()];
- },
- YY: function (dateObj) {
- return pad(String(dateObj.getFullYear()), 4).substr(2);
- },
- YYYY: function (dateObj) { return pad(dateObj.getFullYear(), 4); },
- h: function (dateObj) { return String(dateObj.getHours() % 12 || 12); },
- hh: function (dateObj) { return pad(dateObj.getHours() % 12 || 12); },
- H: function (dateObj) { return String(dateObj.getHours()); },
- HH: function (dateObj) { return pad(dateObj.getHours()); },
- m: function (dateObj) { return String(dateObj.getMinutes()); },
- mm: function (dateObj) { return pad(dateObj.getMinutes()); },
- s: function (dateObj) { return String(dateObj.getSeconds()); },
- ss: function (dateObj) { return pad(dateObj.getSeconds()); },
- S: function (dateObj) {
- return String(Math.round(dateObj.getMilliseconds() / 100));
- },
- SS: function (dateObj) {
- return pad(Math.round(dateObj.getMilliseconds() / 10), 2);
- },
- SSS: function (dateObj) { return pad(dateObj.getMilliseconds(), 3); },
- a: function (dateObj, i18n) {
- return dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1];
- },
- A: function (dateObj, i18n) {
- return dateObj.getHours() < 12
- ? i18n.amPm[0].toUpperCase()
- : i18n.amPm[1].toUpperCase();
- },
- ZZ: function (dateObj) {
- var offset = dateObj.getTimezoneOffset();
- return ((offset > 0 ? "-" : "+") +
- pad(Math.floor(Math.abs(offset) / 60) * 100 + (Math.abs(offset) % 60), 4));
- },
- Z: function (dateObj) {
- var offset = dateObj.getTimezoneOffset();
- return ((offset > 0 ? "-" : "+") +
- pad(Math.floor(Math.abs(offset) / 60), 2) +
- ":" +
- pad(Math.abs(offset) % 60, 2));
- }
- };
- var monthParse = function (v) { return +v - 1; };
- var emptyDigits = [null, twoDigitsOptional];
- var emptyWord = [null, word];
- var amPm = [
- "isPm",
- word,
- function (v, i18n) {
- var val = v.toLowerCase();
- if (val === i18n.amPm[0]) {
- return 0;
- }
- else if (val === i18n.amPm[1]) {
- return 1;
- }
- return null;
- }
- ];
- var timezoneOffset = [
- "timezoneOffset",
- "[^\\s]*?[\\+\\-]\\d\\d:?\\d\\d|[^\\s]*?Z?",
- function (v) {
- var parts = (v + "").match(/([+-]|\d\d)/gi);
- if (parts) {
- var minutes = +parts[1] * 60 + parseInt(parts[2], 10);
- return parts[0] === "+" ? minutes : -minutes;
- }
- return 0;
- }
- ];
- var parseFlags = {
- D: ["day", twoDigitsOptional],
- DD: ["day", twoDigits],
- Do: ["day", twoDigitsOptional + word, function (v) { return parseInt(v, 10); }],
- M: ["month", twoDigitsOptional, monthParse],
- MM: ["month", twoDigits, monthParse],
- YY: [
- "year",
- twoDigits,
- function (v) {
- var now = new Date();
- var cent = +("" + now.getFullYear()).substr(0, 2);
- return +("" + (+v > 68 ? cent - 1 : cent) + v);
- }
- ],
- h: ["hour", twoDigitsOptional, undefined, "isPm"],
- hh: ["hour", twoDigits, undefined, "isPm"],
- H: ["hour", twoDigitsOptional],
- HH: ["hour", twoDigits],
- m: ["minute", twoDigitsOptional],
- mm: ["minute", twoDigits],
- s: ["second", twoDigitsOptional],
- ss: ["second", twoDigits],
- YYYY: ["year", fourDigits],
- S: ["millisecond", "\\d", function (v) { return +v * 100; }],
- SS: ["millisecond", twoDigits, function (v) { return +v * 10; }],
- SSS: ["millisecond", threeDigits],
- d: emptyDigits,
- dd: emptyDigits,
- ddd: emptyWord,
- dddd: emptyWord,
- MMM: ["month", word, monthUpdate("monthNamesShort")],
- MMMM: ["month", word, monthUpdate("monthNames")],
- a: amPm,
- A: amPm,
- ZZ: timezoneOffset,
- Z: timezoneOffset
- };
- // Some common format strings
- var globalMasks = {
- default: "ddd MMM DD YYYY HH:mm:ss",
- shortDate: "M/D/YY",
- mediumDate: "MMM D, YYYY",
- longDate: "MMMM D, YYYY",
- fullDate: "dddd, MMMM D, YYYY",
- isoDate: "YYYY-MM-DD",
- isoDateTime: "YYYY-MM-DDTHH:mm:ssZ",
- shortTime: "HH:mm",
- mediumTime: "HH:mm:ss",
- longTime: "HH:mm:ss.SSS"
- };
- var setGlobalDateMasks = function (masks) { return assign(globalMasks, masks); };
- /***
- * Format a date
- * @method format
- * @param {Date|number} dateObj
- * @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate'
- * @returns {string} Formatted date string
- */
- var format = function (dateObj, mask, i18n) {
- if (mask === void 0) { mask = globalMasks["default"]; }
- if (i18n === void 0) { i18n = {}; }
- if (typeof dateObj === "number") {
- dateObj = new Date(dateObj);
- }
- if (Object.prototype.toString.call(dateObj) !== "[object Date]" ||
- isNaN(dateObj.getTime())) {
- throw new Error("Invalid Date pass to format");
- }
- mask = globalMasks[mask] || mask;
- var literals = [];
- // Make literals inactive by replacing them with @@@
- mask = mask.replace(literal, function ($0, $1) {
- literals.push($1);
- return "@@@";
- });
- var combinedI18nSettings = assign(assign({}, globalI18n), i18n);
- // Apply formatting rules
- mask = mask.replace(token, function ($0) {
- return formatFlags[$0](dateObj, combinedI18nSettings);
- });
- // Inline literal values back into the formatted value
- return mask.replace(/@@@/g, function () { return literals.shift(); });
- };
- /**
- * Parse a date string into a Javascript Date object /
- * @method parse
- * @param {string} dateStr Date string
- * @param {string} format Date parse format
- * @param {i18n} I18nSettingsOptional Full or subset of I18N settings
- * @returns {Date|null} Returns Date object. Returns null what date string is invalid or doesn't match format
- */
- function parse(dateStr, format, i18n) {
- if (i18n === void 0) { i18n = {}; }
- if (typeof format !== "string") {
- throw new Error("Invalid format in fecha parse");
- }
- // Check to see if the format is actually a mask
- format = globalMasks[format] || format;
- // Avoid regular expression denial of service, fail early for really long strings
- // https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS
- if (dateStr.length > 1000) {
- return null;
- }
- // Default to the beginning of the year.
- var today = new Date();
- var dateInfo = {
- year: today.getFullYear(),
- month: 0,
- day: 1,
- hour: 0,
- minute: 0,
- second: 0,
- millisecond: 0,
- isPm: null,
- timezoneOffset: null
- };
- var parseInfo = [];
- var literals = [];
- // Replace all the literals with @@@. Hopefully a string that won't exist in the format
- var newFormat = format.replace(literal, function ($0, $1) {
- literals.push(regexEscape($1));
- return "@@@";
- });
- var specifiedFields = {};
- var requiredFields = {};
- // Change every token that we find into the correct regex
- newFormat = regexEscape(newFormat).replace(token, function ($0) {
- var info = parseFlags[$0];
- var field = info[0], regex = info[1], requiredField = info[3];
- // Check if the person has specified the same field twice. This will lead to confusing results.
- if (specifiedFields[field]) {
- throw new Error("Invalid format. " + field + " specified twice in format");
- }
- specifiedFields[field] = true;
- // Check if there are any required fields. For instance, 12 hour time requires AM/PM specified
- if (requiredField) {
- requiredFields[requiredField] = true;
- }
- parseInfo.push(info);
- return "(" + regex + ")";
- });
- // Check all the required fields are present
- Object.keys(requiredFields).forEach(function (field) {
- if (!specifiedFields[field]) {
- throw new Error("Invalid format. " + field + " is required in specified format");
- }
- });
- // Add back all the literals after
- newFormat = newFormat.replace(/@@@/g, function () { return literals.shift(); });
- // Check if the date string matches the format. If it doesn't return null
- var matches = dateStr.match(new RegExp(newFormat, "i"));
- if (!matches) {
- return null;
- }
- var combinedI18nSettings = assign(assign({}, globalI18n), i18n);
- // For each match, call the parser function for that date part
- for (var i = 1; i < matches.length; i++) {
- var _a = parseInfo[i - 1], field = _a[0], parser = _a[2];
- var value = parser
- ? parser(matches[i], combinedI18nSettings)
- : +matches[i];
- // If the parser can't make sense of the value, return null
- if (value == null) {
- return null;
- }
- dateInfo[field] = value;
- }
- if (dateInfo.isPm === 1 && dateInfo.hour != null && +dateInfo.hour !== 12) {
- dateInfo.hour = +dateInfo.hour + 12;
- }
- else if (dateInfo.isPm === 0 && +dateInfo.hour === 12) {
- dateInfo.hour = 0;
- }
- var dateWithoutTZ = new Date(dateInfo.year, dateInfo.month, dateInfo.day, dateInfo.hour, dateInfo.minute, dateInfo.second, dateInfo.millisecond);
- var validateFields = [
- ["month", "getMonth"],
- ["day", "getDate"],
- ["hour", "getHours"],
- ["minute", "getMinutes"],
- ["second", "getSeconds"]
- ];
- for (var i = 0, len = validateFields.length; i < len; i++) {
- // Check to make sure the date field is within the allowed range. Javascript dates allows values
- // outside the allowed range. If the values don't match the value was invalid
- if (specifiedFields[validateFields[i][0]] &&
- dateInfo[validateFields[i][0]] !== dateWithoutTZ[validateFields[i][1]]()) {
- return null;
- }
- }
- if (dateInfo.timezoneOffset == null) {
- return dateWithoutTZ;
- }
- return new Date(Date.UTC(dateInfo.year, dateInfo.month, dateInfo.day, dateInfo.hour, dateInfo.minute - dateInfo.timezoneOffset, dateInfo.second, dateInfo.millisecond));
- }
- var fecha = {
- format: format,
- parse: parse,
- defaultI18n: defaultI18n,
- setGlobalDateI18n: setGlobalDateI18n,
- setGlobalDateMasks: setGlobalDateMasks
- };
-
- exports.assign = assign;
- exports.default = fecha;
- exports.format = format;
- exports.parse = parse;
- exports.defaultI18n = defaultI18n;
- exports.setGlobalDateI18n = setGlobalDateI18n;
- exports.setGlobalDateMasks = setGlobalDateMasks;
-
- Object.defineProperty(exports, '__esModule', { value: true });
-
-})));
-
-
-},{}],139:[function(require,module,exports){
-'use strict';
-
-var toString = Object.prototype.toString;
-
-/**
- * Extract names from functions.
- *
- * @param {Function} fn The function who's name we need to extract.
- * @returns {String} The name of the function.
- * @public
- */
-module.exports = function name(fn) {
- if ('string' === typeof fn.displayName && fn.constructor.name) {
- return fn.displayName;
- } else if ('string' === typeof fn.name && fn.name) {
- return fn.name;
- }
-
- //
- // Check to see if the constructor has a name.
- //
- if (
- 'object' === typeof fn
- && fn.constructor
- && 'string' === typeof fn.constructor.name
- ) return fn.constructor.name;
-
- //
- // toString the given function and attempt to parse it out of it, or determine
- // the class.
- //
- var named = fn.toString()
- , type = toString.call(fn).slice(8, -1);
-
- if ('Function' === type) {
- named = named.substring(named.indexOf('(') + 1, named.indexOf(')'));
- } else {
- named = type;
- }
-
- return named || 'anonymous';
-};
-
-},{}],140:[function(require,module,exports){
-arguments[4][16][0].apply(exports,arguments)
-},{"dup":16}],141:[function(require,module,exports){
-module.exports = function isArrayish(obj) {
- if (!obj || typeof obj === 'string') {
- return false;
- }
-
- return obj instanceof Array || Array.isArray(obj) ||
- (obj.length >= 0 && (obj.splice instanceof Function ||
- (Object.getOwnPropertyDescriptor(obj, (obj.length - 1)) && obj.constructor.name !== 'String')));
-};
-
-},{}],142:[function(require,module,exports){
-'use strict';
-
-const isStream = stream =>
- stream !== null &&
- typeof stream === 'object' &&
- typeof stream.pipe === 'function';
-
-isStream.writable = stream =>
- isStream(stream) &&
- stream.writable !== false &&
- typeof stream._write === 'function' &&
- typeof stream._writableState === 'object';
-
-isStream.readable = stream =>
- isStream(stream) &&
- stream.readable !== false &&
- typeof stream._read === 'function' &&
- typeof stream._readableState === 'object';
-
-isStream.duplex = stream =>
- isStream.writable(stream) &&
- isStream.readable(stream);
-
-isStream.transform = stream =>
- isStream.duplex(stream) &&
- typeof stream._transform === 'function' &&
- typeof stream._transformState === 'object';
-
-module.exports = isStream;
-
-},{}],143:[function(require,module,exports){
-arguments[4][18][0].apply(exports,arguments)
-},{"dup":18}],144:[function(require,module,exports){
-'use strict';
-
-var format = require('./format');
-/*
- * function align (info)
- * Returns a new instance of the align Format which adds a `\t`
- * delimiter before the message to properly align it in the same place.
- * It was previously { align: true } in winston < 3.0.0
- */
-
-
-module.exports = format(function (info) {
- info.message = "\t".concat(info.message);
- return info;
-});
-},{"./format":149}],145:[function(require,module,exports){
-'use strict';
-/*
- * @api public
- * @property {function} format
- * Both the construction method and set of exposed
- * formats.
- */
-
-var format = exports.format = require('././format');
-/*
- * @api public
- * @method {function} levels
- * Registers the specified levels with logform.
- */
-
-
-exports.levels = require('././levels'); //
-// Setup all transports as eager-loaded exports
-// so that they are static for the bundlers.
-//
-
-Object.defineProperty(format, 'align', {
- value: require('./align')
-});
-Object.defineProperty(format, 'cli', {
- value: require('./cli')
-});
-Object.defineProperty(format, 'combine', {
- value: require('./combine')
-});
-Object.defineProperty(format, 'colorize', {
- value: require('./colorize')
-});
-Object.defineProperty(format, 'json', {
- value: require('./json')
-});
-Object.defineProperty(format, 'label', {
- value: require('./label')
-});
-Object.defineProperty(format, 'logstash', {
- value: require('./logstash')
-});
-Object.defineProperty(format, 'metadata', {
- value: require('./metadata')
-});
-Object.defineProperty(format, 'padLevels', {
- value: require('./pad-levels')
-});
-Object.defineProperty(format, 'prettyPrint', {
- value: require('./pretty-print')
-});
-Object.defineProperty(format, 'printf', {
- value: require('./printf')
-});
-Object.defineProperty(format, 'simple', {
- value: require('./simple')
-});
-Object.defineProperty(format, 'splat', {
- value: require('./splat')
-});
-Object.defineProperty(format, 'timestamp', {
- value: require('./timestamp')
-});
-Object.defineProperty(format, 'uncolorize', {
- value: require('./uncolorize')
-});
-},{"././format":149,"././levels":152,"./align":144,"./cli":146,"./colorize":147,"./combine":148,"./json":150,"./label":151,"./logstash":153,"./metadata":154,"./pad-levels":155,"./pretty-print":156,"./printf":157,"./simple":158,"./splat":159,"./timestamp":160,"./uncolorize":161}],146:[function(require,module,exports){
-'use strict';
-
-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('./colorize'),
- Colorizer = _require.Colorizer;
-
-var _require2 = require('./pad-levels'),
- Padder = _require2.Padder;
-
-var _require3 = require('triple-beam'),
- configs = _require3.configs,
- MESSAGE = _require3.MESSAGE;
-/**
- * Cli format class that handles initial state for a a separate
- * Colorizer and Padder instance.
- */
-
-
-var CliFormat = /*#__PURE__*/function () {
- function CliFormat() {
- var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
-
- _classCallCheck(this, CliFormat);
-
- if (!opts.levels) {
- opts.levels = configs.npm.levels;
- }
-
- this.colorizer = new Colorizer(opts);
- this.padder = new Padder(opts);
- this.options = opts;
- }
- /*
- * function transform (info, opts)
- * Attempts to both:
- * 1. Pad the { level }
- * 2. Colorize the { level, message }
- * of the given `logform` info object depending on the `opts`.
- */
-
-
- _createClass(CliFormat, [{
- key: "transform",
- value: function transform(info, opts) {
- this.colorizer.transform(this.padder.transform(info, opts), opts);
- info[MESSAGE] = "".concat(info.level, ":").concat(info.message);
- return info;
- }
- }]);
-
- return CliFormat;
-}();
-/*
- * function cli (opts)
- * Returns a new instance of the CLI format that turns a log
- * `info` object into the same format previously available
- * in `winston.cli()` in `winston < 3.0.0`.
- */
-
-
-module.exports = function (opts) {
- return new CliFormat(opts);
-}; //
-// Attach the CliFormat for registration purposes
-//
-
-
-module.exports.Format = CliFormat;
-},{"./colorize":147,"./pad-levels":155,"triple-beam":189}],147:[function(require,module,exports){
-'use strict';
-
-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 colors = require('colors/safe');
-
-var _require = require('triple-beam'),
- LEVEL = _require.LEVEL,
- MESSAGE = _require.MESSAGE; //
-// Fix colors not appearing in non-tty environments
-//
-
-
-colors.enabled = true;
-/**
- * @property {RegExp} hasSpace
- * Simple regex to check for presence of spaces.
- */
-
-var hasSpace = /\s+/;
-/*
- * Colorizer format. Wraps the `level` and/or `message` properties
- * of the `info` objects with ANSI color codes based on a few options.
- */
-
-var Colorizer = /*#__PURE__*/function () {
- function Colorizer() {
- var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
-
- _classCallCheck(this, Colorizer);
-
- if (opts.colors) {
- this.addColors(opts.colors);
- }
-
- this.options = opts;
- }
- /*
- * Adds the colors Object to the set of allColors
- * known by the Colorizer
- *
- * @param {Object} colors Set of color mappings to add.
- */
-
-
- _createClass(Colorizer, [{
- key: "addColors",
-
- /*
- * Adds the colors Object to the set of allColors
- * known by the Colorizer
- *
- * @param {Object} colors Set of color mappings to add.
- */
- value: function addColors(clrs) {
- return Colorizer.addColors(clrs);
- }
- /*
- * function colorize (lookup, level, message)
- * Performs multi-step colorization using colors/safe
- */
-
- }, {
- key: "colorize",
- value: function colorize(lookup, level, message) {
- if (typeof message === 'undefined') {
- message = level;
- } //
- // If the color for the level is just a string
- // then attempt to colorize the message with it.
- //
-
-
- if (!Array.isArray(Colorizer.allColors[lookup])) {
- return colors[Colorizer.allColors[lookup]](message);
- } //
- // If it is an Array then iterate over that Array, applying
- // the colors function for each item.
- //
-
-
- for (var i = 0, len = Colorizer.allColors[lookup].length; i < len; i++) {
- message = colors[Colorizer.allColors[lookup][i]](message);
- }
-
- return message;
- }
- /*
- * function transform (info, opts)
- * Attempts to colorize the { level, message } of the given
- * `logform` info object.
- */
-
- }, {
- key: "transform",
- value: function transform(info, opts) {
- if (opts.all && typeof info[MESSAGE] === 'string') {
- info[MESSAGE] = this.colorize(info[LEVEL], info.level, info[MESSAGE]);
- }
-
- if (opts.level || opts.all || !opts.message) {
- info.level = this.colorize(info[LEVEL], info.level);
- }
-
- if (opts.all || opts.message) {
- info.message = this.colorize(info[LEVEL], info.level, info.message);
- }
-
- return info;
- }
- }], [{
- key: "addColors",
- value: function addColors(clrs) {
- var nextColors = Object.keys(clrs).reduce(function (acc, level) {
- acc[level] = hasSpace.test(clrs[level]) ? clrs[level].split(hasSpace) : clrs[level];
- return acc;
- }, {});
- Colorizer.allColors = Object.assign({}, Colorizer.allColors || {}, nextColors);
- return Colorizer.allColors;
- }
- }]);
-
- return Colorizer;
-}();
-/*
- * function colorize (info)
- * Returns a new instance of the colorize Format that applies
- * level colors to `info` objects. This was previously exposed
- * as { colorize: true } to transports in `winston < 3.0.0`.
- */
-
-
-module.exports = function (opts) {
- return new Colorizer(opts);
-}; //
-// Attach the Colorizer for registration purposes
-//
-
-
-module.exports.Colorizer = module.exports.Format = Colorizer;
-},{"colors/safe":129,"triple-beam":189}],148:[function(require,module,exports){
-'use strict';
-
-var format = require('./format');
-/*
- * function cascade(formats)
- * Returns a function that invokes the `._format` function in-order
- * for the specified set of `formats`. In this manner we say that Formats
- * are "pipe-like", but not a pure pumpify implementation. Since there is no back
- * pressure we can remove all of the "readable" plumbing in Node streams.
- */
-
-
-function cascade(formats) {
- if (!formats.every(isValidFormat)) {
- return;
- }
-
- return function (info) {
- var obj = info;
-
- for (var i = 0; i < formats.length; i++) {
- obj = formats[i].transform(obj, formats[i].options);
-
- if (!obj) {
- return false;
- }
- }
-
- return obj;
- };
-}
-/*
- * function isValidFormat(format)
- * If the format does not define a `transform` function throw an error
- * with more detailed usage.
- */
-
-
-function isValidFormat(fmt) {
- if (typeof fmt.transform !== 'function') {
- throw new Error(['No transform function found on format. Did you create a format instance?', 'const myFormat = format(formatFn);', 'const instance = myFormat();'].join('\n'));
- }
-
- return true;
-}
-/*
- * function combine (info)
- * Returns a new instance of the combine Format which combines the specified
- * formats into a new format. This is similar to a pipe-chain in transform streams.
- * We choose to combine the prototypes this way because there is no back pressure in
- * an in-memory transform chain.
- */
-
-
-module.exports = function () {
- for (var _len = arguments.length, formats = new Array(_len), _key = 0; _key < _len; _key++) {
- formats[_key] = arguments[_key];
- }
-
- var combinedFormat = format(cascade(formats));
- var instance = combinedFormat();
- instance.Format = combinedFormat.Format;
- return instance;
-}; //
-// Export the cascade method for use in cli and other
-// combined formats that should not be assumed to be
-// singletons.
-//
-
-
-module.exports.cascade = cascade;
-},{"./format":149}],149:[function(require,module,exports){
-'use strict';
-/*
- * Displays a helpful message and the source of
- * the format when it is invalid.
- */
-
-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 _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
-
-function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
-
-function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
-
-function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
-
-function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
-
-function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
-
-function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
-
-function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
-
-function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
-
-function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
-
-function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
-
-var InvalidFormatError = /*#__PURE__*/function (_Error) {
- _inherits(InvalidFormatError, _Error);
-
- var _super = _createSuper(InvalidFormatError);
-
- function InvalidFormatError(formatFn) {
- var _this;
-
- _classCallCheck(this, InvalidFormatError);
-
- _this = _super.call(this, "Format functions must be synchronous taking a two arguments: (info, opts)\nFound: ".concat(formatFn.toString().split('\n')[0], "\n"));
- Error.captureStackTrace(_assertThisInitialized(_this), InvalidFormatError);
- return _this;
- }
-
- return InvalidFormatError;
-}( /*#__PURE__*/_wrapNativeSuper(Error));
-/*
- * function format (formatFn)
- * Returns a create function for the `formatFn`.
- */
-
-
-module.exports = function (formatFn) {
- if (formatFn.length > 2) {
- throw new InvalidFormatError(formatFn);
- }
- /*
- * function Format (options)
- * Base prototype which calls a `_format`
- * function and pushes the result.
- */
-
-
- function Format() {
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- this.options = options;
- }
-
- Format.prototype.transform = formatFn; //
- // Create a function which returns new instances of
- // FormatWrap for simple syntax like:
- //
- // require('winston').formats.json();
- //
-
- function createFormatWrap(opts) {
- return new Format(opts);
- } //
- // Expose the FormatWrap through the create function
- // for testability.
- //
-
-
- createFormatWrap.Format = Format;
- return createFormatWrap;
-};
-},{}],150:[function(require,module,exports){
-(function (Buffer){(function (){
-'use strict';
-
-var format = require('./format');
-
-var _require = require('triple-beam'),
- MESSAGE = _require.MESSAGE;
-
-var jsonStringify = require('fast-safe-stringify');
-/*
- * function replacer (key, value)
- * Handles proper stringification of Buffer and bigint output.
- */
-
-
-function replacer(key, value) {
- if (value instanceof Buffer) return value.toString('base64'); // eslint-disable-next-line valid-typeof
-
- if (typeof value === 'bigint') return value.toString();
- return value;
-}
-/*
- * function json (info)
- * Returns a new instance of the JSON format that turns a log `info`
- * object into pure JSON. This was previously exposed as { json: true }
- * to transports in `winston < 3.0.0`.
- */
-
-
-module.exports = format(function (info) {
- var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- info[MESSAGE] = (opts.stable ? jsonStringify.stableStringify : jsonStringify)(info, opts.replacer || replacer, opts.space);
- return info;
-});
-}).call(this)}).call(this,require("buffer").Buffer)
-},{"./format":149,"buffer":10,"fast-safe-stringify":137,"triple-beam":189}],151:[function(require,module,exports){
-'use strict';
-
-var format = require('./format');
-/*
- * function label (info)
- * Returns a new instance of the label Format which adds the specified
- * `opts.label` before the message. This was previously exposed as
- * { label: 'my label' } to transports in `winston < 3.0.0`.
- */
-
-
-module.exports = format(function (info, opts) {
- if (opts.message) {
- info.message = "[".concat(opts.label, "] ").concat(info.message);
- return info;
- }
-
- info.label = opts.label;
- return info;
-});
-},{"./format":149}],152:[function(require,module,exports){
-'use strict';
-
-var _require = require('./colorize'),
- Colorizer = _require.Colorizer;
-/*
- * Simple method to register colors with a simpler require
- * path within the module.
- */
-
-
-module.exports = function (config) {
- Colorizer.addColors(config.colors || config);
- return config;
-};
-},{"./colorize":147}],153:[function(require,module,exports){
-'use strict';
-
-var format = require('./format');
-
-var _require = require('triple-beam'),
- MESSAGE = _require.MESSAGE;
-
-var jsonStringify = require('fast-safe-stringify');
-/*
- * function logstash (info)
- * Returns a new instance of the LogStash Format that turns a
- * log `info` object into pure JSON with the appropriate logstash
- * options. This was previously exposed as { logstash: true }
- * to transports in `winston < 3.0.0`.
- */
-
-
-module.exports = format(function (info) {
- var logstash = {};
-
- if (info.message) {
- logstash['@message'] = info.message;
- delete info.message;
- }
-
- if (info.timestamp) {
- logstash['@timestamp'] = info.timestamp;
- delete info.timestamp;
- }
-
- logstash['@fields'] = info;
- info[MESSAGE] = jsonStringify(logstash);
- return info;
-});
-},{"./format":149,"fast-safe-stringify":137,"triple-beam":189}],154:[function(require,module,exports){
-'use strict';
-
-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 format = require('./format');
-
-function fillExcept(info, fillExceptKeys, metadataKey) {
- var savedKeys = fillExceptKeys.reduce(function (acc, key) {
- acc[key] = info[key];
- delete info[key];
- return acc;
- }, {});
- var metadata = Object.keys(info).reduce(function (acc, key) {
- acc[key] = info[key];
- delete info[key];
- return acc;
- }, {});
- Object.assign(info, savedKeys, _defineProperty({}, metadataKey, metadata));
- return info;
-}
-
-function fillWith(info, fillWithKeys, metadataKey) {
- info[metadataKey] = fillWithKeys.reduce(function (acc, key) {
- acc[key] = info[key];
- delete info[key];
- return acc;
- }, {});
- return info;
-}
-/**
- * Adds in a "metadata" object to collect extraneous data, similar to the metadata
- * object in winston 2.x.
- */
-
-
-module.exports = format(function (info) {
- var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- var metadataKey = 'metadata';
-
- if (opts.key) {
- metadataKey = opts.key;
- }
-
- var fillExceptKeys = [];
-
- if (!opts.fillExcept && !opts.fillWith) {
- fillExceptKeys.push('level');
- fillExceptKeys.push('message');
- }
-
- if (opts.fillExcept) {
- fillExceptKeys = opts.fillExcept;
- }
-
- if (fillExceptKeys.length > 0) {
- return fillExcept(info, fillExceptKeys, metadataKey);
- }
-
- if (opts.fillWith) {
- return fillWith(info, opts.fillWith, metadataKey);
- }
-
- return info;
-});
-},{"./format":149}],155:[function(require,module,exports){
-/* eslint no-unused-vars: 0 */
-'use strict';
-
-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; }
-
-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('triple-beam'),
- configs = _require.configs,
- LEVEL = _require.LEVEL,
- MESSAGE = _require.MESSAGE;
-
-var Padder = /*#__PURE__*/function () {
- function Padder() {
- var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
- levels: configs.npm.levels
- };
-
- _classCallCheck(this, Padder);
-
- this.paddings = Padder.paddingForLevels(opts.levels, opts.filler);
- this.options = opts;
- }
- /**
- * Returns the maximum length of keys in the specified `levels` Object.
- * @param {Object} levels Set of all levels to calculate longest level against.
- * @returns {Number} Maximum length of the longest level string.
- */
-
-
- _createClass(Padder, [{
- key: "transform",
-
- /**
- * Prepends the padding onto the `message` based on the `LEVEL` of
- * the `info`. This is based on the behavior of `winston@2` which also
- * prepended the level onto the message.
- *
- * See: https://github.com/winstonjs/winston/blob/2.x/lib/winston/logger.js#L198-L201
- *
- * @param {Info} info Logform info object
- * @param {Object} opts Options passed along to this instance.
- * @returns {Info} Modified logform info object.
- */
- value: function transform(info, opts) {
- info.message = "".concat(this.paddings[info[LEVEL]]).concat(info.message);
-
- if (info[MESSAGE]) {
- info[MESSAGE] = "".concat(this.paddings[info[LEVEL]]).concat(info[MESSAGE]);
- }
-
- return info;
- }
- }], [{
- key: "getLongestLevel",
- value: function getLongestLevel(levels) {
- var lvls = Object.keys(levels).map(function (level) {
- return level.length;
- });
- return Math.max.apply(Math, _toConsumableArray(lvls));
- }
- /**
- * Returns the padding for the specified `level` assuming that the
- * maximum length of all levels it's associated with is `maxLength`.
- * @param {String} level Level to calculate padding for.
- * @param {String} filler Repeatable text to use for padding.
- * @param {Number} maxLength Length of the longest level
- * @returns {String} Padding string for the `level`
- */
-
- }, {
- key: "paddingForLevel",
- value: function paddingForLevel(level, filler, maxLength) {
- var targetLen = maxLength + 1 - level.length;
- var rep = Math.floor(targetLen / filler.length);
- var padding = "".concat(filler).concat(filler.repeat(rep));
- return padding.slice(0, targetLen);
- }
- /**
- * Returns an object with the string paddings for the given `levels`
- * using the specified `filler`.
- * @param {Object} levels Set of all levels to calculate padding for.
- * @param {String} filler Repeatable text to use for padding.
- * @returns {Object} Mapping of level to desired padding.
- */
-
- }, {
- key: "paddingForLevels",
- value: function paddingForLevels(levels) {
- var filler = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ' ';
- var maxLength = Padder.getLongestLevel(levels);
- return Object.keys(levels).reduce(function (acc, level) {
- acc[level] = Padder.paddingForLevel(level, filler, maxLength);
- return acc;
- }, {});
- }
- }]);
-
- return Padder;
-}();
-/*
- * function padLevels (info)
- * Returns a new instance of the padLevels Format which pads
- * levels to be the same length. This was previously exposed as
- * { padLevels: true } to transports in `winston < 3.0.0`.
- */
-
-
-module.exports = function (opts) {
- return new Padder(opts);
-};
-
-module.exports.Padder = module.exports.Format = Padder;
-},{"triple-beam":189}],156:[function(require,module,exports){
-'use strict';
-
-var inspect = require('util').inspect;
-
-var format = require('./format');
-
-var _require = require('triple-beam'),
- LEVEL = _require.LEVEL,
- MESSAGE = _require.MESSAGE,
- SPLAT = _require.SPLAT;
-/*
- * function prettyPrint (info)
- * Returns a new instance of the prettyPrint Format that "prettyPrint"
- * serializes `info` objects. This was previously exposed as
- * { prettyPrint: true } to transports in `winston < 3.0.0`.
- */
-
-
-module.exports = format(function (info) {
- var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
- //
- // info[{LEVEL, MESSAGE, SPLAT}] are enumerable here. Since they
- // are internal, we remove them before util.inspect so they
- // are not printed.
- //
- var stripped = Object.assign({}, info); // Remark (indexzero): update this technique in April 2019
- // when node@6 is EOL
-
- delete stripped[LEVEL];
- delete stripped[MESSAGE];
- delete stripped[SPLAT];
- info[MESSAGE] = inspect(stripped, false, opts.depth || null, opts.colorize);
- return info;
-});
-},{"./format":149,"triple-beam":189,"util":82}],157:[function(require,module,exports){
-'use strict';
-
-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('triple-beam'),
- MESSAGE = _require.MESSAGE;
-
-var Printf = /*#__PURE__*/function () {
- function Printf(templateFn) {
- _classCallCheck(this, Printf);
-
- this.template = templateFn;
- }
-
- _createClass(Printf, [{
- key: "transform",
- value: function transform(info) {
- info[MESSAGE] = this.template(info);
- return info;
- }
- }]);
-
- return Printf;
-}();
-/*
- * function printf (templateFn)
- * Returns a new instance of the printf Format that creates an
- * intermediate prototype to store the template string-based formatter
- * function.
- */
-
-
-module.exports = function (opts) {
- return new Printf(opts);
-};
-
-module.exports.Printf = module.exports.Format = Printf;
-},{"triple-beam":189}],158:[function(require,module,exports){
-/* eslint no-undefined: 0 */
-'use strict';
-
-var format = require('./format');
-
-var _require = require('triple-beam'),
- MESSAGE = _require.MESSAGE;
-
-var jsonStringify = require('fast-safe-stringify');
-/*
- * function simple (info)
- * Returns a new instance of the simple format TransformStream
- * which writes a simple representation of logs.
- *
- * const { level, message, splat, ...rest } = info;
- *
- * ${level}: ${message} if rest is empty
- * ${level}: ${message} ${JSON.stringify(rest)} otherwise
- */
-
-
-module.exports = format(function (info) {
- var stringifiedRest = jsonStringify(Object.assign({}, info, {
- level: undefined,
- message: undefined,
- splat: undefined
- }));
- var padding = info.padding && info.padding[info.level] || '';
-
- if (stringifiedRest !== '{}') {
- info[MESSAGE] = "".concat(info.level, ":").concat(padding, " ").concat(info.message, " ").concat(stringifiedRest);
- } else {
- info[MESSAGE] = "".concat(info.level, ":").concat(padding, " ").concat(info.message);
- }
-
- return info;
-});
-},{"./format":149,"fast-safe-stringify":137,"triple-beam":189}],159:[function(require,module,exports){
-'use strict';
-
-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; }
-
-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 util = require('util');
-
-var _require = require('triple-beam'),
- SPLAT = _require.SPLAT;
-/**
- * Captures the number of format (i.e. %s strings) in a given string.
- * Based on `util.format`, see Node.js source:
- * https://github.com/nodejs/node/blob/b1c8f15c5f169e021f7c46eb7b219de95fe97603/lib/util.js#L201-L230
- * @type {RegExp}
- */
-
-
-var formatRegExp = /%[scdjifoO%]/g;
-/**
- * Captures the number of escaped % signs in a format string (i.e. %s strings).
- * @type {RegExp}
- */
-
-var escapedPercent = /%%/g;
-
-var Splatter = /*#__PURE__*/function () {
- function Splatter(opts) {
- _classCallCheck(this, Splatter);
-
- this.options = opts;
- }
- /**
- * Check to see if tokens <= splat.length, assign { splat, meta } into the
- * `info` accordingly, and write to this instance.
- *
- * @param {Info} info Logform info message.
- * @param {String[]} tokens Set of string interpolation tokens.
- * @returns {Info} Modified info message
- * @private
- */
-
-
- _createClass(Splatter, [{
- key: "_splat",
- value: function _splat(info, tokens) {
- var msg = info.message;
- var splat = info[SPLAT] || info.splat || [];
- var percents = msg.match(escapedPercent);
- var escapes = percents && percents.length || 0; // The expected splat is the number of tokens minus the number of escapes
- // e.g.
- // - { expectedSplat: 3 } '%d %s %j'
- // - { expectedSplat: 5 } '[%s] %d%% %d%% %s %j'
- //
- // Any "meta" will be arugments in addition to the expected splat size
- // regardless of type. e.g.
- //
- // logger.log('info', '%d%% %s %j', 100, 'wow', { such: 'js' }, { thisIsMeta: true });
- // would result in splat of four (4), but only three (3) are expected. Therefore:
- //
- // extraSplat = 3 - 4 = -1
- // metas = [100, 'wow', { such: 'js' }, { thisIsMeta: true }].splice(-1, -1 * -1);
- // splat = [100, 'wow', { such: 'js' }]
-
- var expectedSplat = tokens.length - escapes;
- var extraSplat = expectedSplat - splat.length;
- var metas = extraSplat < 0 ? splat.splice(extraSplat, -1 * extraSplat) : []; // Now that { splat } has been separated from any potential { meta }. we
- // can assign this to the `info` object and write it to our format stream.
- // If the additional metas are **NOT** objects or **LACK** enumerable properties
- // you are going to have a bad time.
-
- var metalen = metas.length;
-
- if (metalen) {
- for (var i = 0; i < metalen; i++) {
- Object.assign(info, metas[i]);
- }
- }
-
- info.message = util.format.apply(util, [msg].concat(_toConsumableArray(splat)));
- return info;
- }
- /**
- * Transforms the `info` message by using `util.format` to complete
- * any `info.message` provided it has string interpolation tokens.
- * If no tokens exist then `info` is immutable.
- *
- * @param {Info} info Logform info message.
- * @param {Object} opts Options for this instance.
- * @returns {Info} Modified info message
- */
-
- }, {
- key: "transform",
- value: function transform(info) {
- var msg = info.message;
- var splat = info[SPLAT] || info.splat; // No need to process anything if splat is undefined
-
- if (!splat || !splat.length) {
- return info;
- } // Extract tokens, if none available default to empty array to
- // ensure consistancy in expected results
-
-
- var tokens = msg && msg.match && msg.match(formatRegExp); // This condition will take care of inputs with info[SPLAT]
- // but no tokens present
-
- if (!tokens && (splat || splat.length)) {
- var metas = splat.length > 1 ? splat.splice(0) : splat; // Now that { splat } has been separated from any potential { meta }. we
- // can assign this to the `info` object and write it to our format stream.
- // If the additional metas are **NOT** objects or **LACK** enumerable properties
- // you are going to have a bad time.
-
- var metalen = metas.length;
-
- if (metalen) {
- for (var i = 0; i < metalen; i++) {
- Object.assign(info, metas[i]);
- }
- }
-
- return info;
- }
-
- if (tokens) {
- return this._splat(info, tokens);
- }
-
- return info;
- }
- }]);
-
- return Splatter;
-}();
-/*
- * function splat (info)
- * Returns a new instance of the splat format TransformStream
- * which performs string interpolation from `info` objects. This was
- * previously exposed implicitly in `winston < 3.0.0`.
- */
-
-
-module.exports = function (opts) {
- return new Splatter(opts);
-};
-},{"triple-beam":189,"util":82}],160:[function(require,module,exports){
-'use strict';
-
-var fecha = require('fecha');
-
-var format = require('./format');
-/*
- * function timestamp (info)
- * Returns a new instance of the timestamp Format which adds a timestamp
- * to the info. It was previously available in winston < 3.0.0 as:
- *
- * - { timestamp: true } // `new Date.toISOString()`
- * - { timestamp: function:String } // Value returned by `timestamp()`
- */
-
-
-module.exports = format(function (info) {
- var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
-
- if (opts.format) {
- info.timestamp = typeof opts.format === 'function' ? opts.format() : fecha.format(new Date(), opts.format);
- }
-
- if (!info.timestamp) {
- info.timestamp = new Date().toISOString();
- }
-
- if (opts.alias) {
- info[opts.alias] = info.timestamp;
- }
-
- return info;
-});
-},{"./format":149,"fecha":138}],161:[function(require,module,exports){
-'use strict';
-
-var colors = require('colors/safe');
-
-var format = require('./format');
-
-var _require = require('triple-beam'),
- MESSAGE = _require.MESSAGE;
-/*
- * function uncolorize (info)
- * Returns a new instance of the uncolorize Format that strips colors
- * from `info` objects. This was previously exposed as { stripColors: true }
- * to transports in `winston < 3.0.0`.
- */
-
-
-module.exports = format(function (info, opts) {
- if (opts.level !== false) {
- info.level = colors.strip(info.level);
- }
-
- if (opts.message !== false) {
- info.message = colors.strip(info.message);
- }
-
- if (opts.raw !== false && info[MESSAGE]) {
- info[MESSAGE] = colors.strip(info[MESSAGE]);
- }
-
- return info;
-});
-},{"./format":149,"colors/safe":129,"triple-beam":189}],162:[function(require,module,exports){
-'use strict';
-
-/*
- * Displays a helpful message and the source of
- * the format when it is invalid.
- */
-class InvalidFormatError extends Error {
- constructor(formatFn) {
- super(`Format functions must be synchronous taking a two arguments: (info, opts)
-Found: ${formatFn.toString().split('\n')[0]}\n`);
-
- Error.captureStackTrace(this, InvalidFormatError);
- }
-}
-
-/*
- * function format (formatFn)
- * Returns a create function for the `formatFn`.
- */
-module.exports = formatFn => {
- if (formatFn.length > 2) {
- throw new InvalidFormatError(formatFn);
- }
-
- /*
- * function Format (options)
- * Base prototype which calls a `_format`
- * function and pushes the result.
- */
- function Format(options = {}) {
- this.options = options;
- }
-
- Format.prototype.transform = formatFn;
-
- //
- // Create a function which returns new instances of
- // FormatWrap for simple syntax like:
- //
- // require('winston').formats.json();
- //
- function createFormatWrap(opts) {
- return new Format(opts);
- }
-
- //
- // Expose the FormatWrap through the create function
- // for testability.
- //
- createFormatWrap.Format = Format;
- return createFormatWrap;
-};
-
-},{}],163:[function(require,module,exports){
-(function (Buffer){(function (){
-'use strict';
-
-const format = require('./format');
-const { MESSAGE } = require('triple-beam');
-const jsonStringify = require('fast-safe-stringify');
-
-/*
- * function replacer (key, value)
- * Handles proper stringification of Buffer and bigint output.
- */
-function replacer(key, value) {
- if (value instanceof Buffer)
- return value.toString('base64');
- // eslint-disable-next-line valid-typeof
- if (typeof value === 'bigint')
- return value.toString();
- return value;
-}
-
-/*
- * function json (info)
- * Returns a new instance of the JSON format that turns a log `info`
- * object into pure JSON. This was previously exposed as { json: true }
- * to transports in `winston < 3.0.0`.
- */
-module.exports = format((info, opts = {}) => {
- info[MESSAGE] = (opts.stable ? jsonStringify.stableStringify
- : jsonStringify)(info, opts.replacer || replacer, opts.space);
- return info;
-});
-
-}).call(this)}).call(this,require("buffer").Buffer)
-},{"./format":162,"buffer":10,"fast-safe-stringify":137,"triple-beam":189}],164:[function(require,module,exports){
-var path = require('path');
-var fs = require('fs');
-var _0777 = parseInt('0777', 8);
-
-module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;
-
-function mkdirP (p, opts, f, made) {
- if (typeof opts === 'function') {
- f = opts;
- opts = {};
- }
- else if (!opts || typeof opts !== 'object') {
- opts = { mode: opts };
- }
-
- var mode = opts.mode;
- var xfs = opts.fs || fs;
-
- if (mode === undefined) {
- mode = _0777
- }
- if (!made) made = null;
-
- var cb = f || function () {};
- p = path.resolve(p);
-
- xfs.mkdir(p, mode, function (er) {
- if (!er) {
- made = made || p;
- return cb(null, made);
- }
- switch (er.code) {
- case 'ENOENT':
- if (path.dirname(p) === p) return cb(er);
- mkdirP(path.dirname(p), opts, function (er, made) {
- if (er) cb(er, made);
- else mkdirP(p, opts, cb, made);
- });
- break;
-
- // In the case of any other error, just see if there's a dir
- // there already. If so, then hooray! If not, then something
- // is borked.
- default:
- xfs.stat(p, function (er2, stat) {
- // if the stat fails, then that's super weird.
- // let the original error be the failure reason.
- if (er2 || !stat.isDirectory()) cb(er, made)
- else cb(null, made);
- });
- break;
- }
- });
-}
-
-mkdirP.sync = function sync (p, opts, made) {
- if (!opts || typeof opts !== 'object') {
- opts = { mode: opts };
- }
-
- var mode = opts.mode;
- var xfs = opts.fs || fs;
-
- if (mode === undefined) {
- mode = _0777
- }
- if (!made) made = null;
-
- p = path.resolve(p);
-
- try {
- xfs.mkdirSync(p, mode);
- made = made || p;
- }
- catch (err0) {
- switch (err0.code) {
- case 'ENOENT' :
- made = sync(path.dirname(p), opts, made);
- sync(p, opts, made);
- break;
-
- // In the case of any other error, just see if there's a dir
- // there already. If so, then hooray! If not, then something
- // is borked.
- default:
- var stat;
- try {
- stat = xfs.statSync(p);
- }
- catch (err1) {
- throw err0;
- }
- if (!stat.isDirectory()) throw err0;
- break;
- }
- }
-
- return made;
-};
-
-},{"fs":1,"path":32}],165:[function(require,module,exports){
-'use strict';
-
-var name = require('fn.name');
-
-/**
- * Wrap callbacks to prevent double execution.
- *
- * @param {Function} fn Function that should only be called once.
- * @returns {Function} A wrapped callback which prevents multiple executions.
- * @public
- */
-module.exports = function one(fn) {
- var called = 0
- , value;
-
- /**
- * The function that prevents double execution.
- *
- * @private
- */
- function onetime() {
- if (called) return value;
-
- called = 1;
- value = fn.apply(this, arguments);
- fn = null;
-
- return value;
- }
-
- //
- // To make debugging more easy we want to use the name of the supplied
- // function. So when you look at the functions that are assigned to event
- // listeners you don't see a load of `onetime` functions but actually the
- // names of the functions that this module will call.
- //
- // NOTE: We cannot override the `name` property, as that is `readOnly`
- // property, so displayName will have to do.
- //
- onetime.displayName = name(fn);
- return onetime;
-};
-
-},{"fn.name":139}],166:[function(require,module,exports){
-arguments[4][33][0].apply(exports,arguments)
-},{"_process":34,"dup":33}],167:[function(require,module,exports){
-arguments[4][40][0].apply(exports,arguments)
-},{"./_stream_readable":168,"./_stream_writable":169,"core-util-is":135,"dup":40,"inherits":140,"process-nextick-args":166}],168:[function(require,module,exports){
-arguments[4][42][0].apply(exports,arguments)
-},{"./_stream_duplex":167,"./internal/streams/BufferList":170,"./internal/streams/destroy":171,"./internal/streams/stream":172,"_process":34,"core-util-is":135,"dup":42,"events":13,"inherits":140,"isarray":143,"process-nextick-args":166,"safe-buffer":174,"string_decoder/":177,"util":7}],169:[function(require,module,exports){
-arguments[4][44][0].apply(exports,arguments)
-},{"./_stream_duplex":167,"./internal/streams/destroy":171,"./internal/streams/stream":172,"_process":34,"core-util-is":135,"dup":44,"inherits":140,"process-nextick-args":166,"safe-buffer":174,"timers":76,"util-deprecate":190}],170:[function(require,module,exports){
-arguments[4][45][0].apply(exports,arguments)
-},{"dup":45,"safe-buffer":174,"util":7}],171:[function(require,module,exports){
-arguments[4][46][0].apply(exports,arguments)
-},{"dup":46,"process-nextick-args":166}],172:[function(require,module,exports){
-arguments[4][47][0].apply(exports,arguments)
-},{"dup":47,"events":13}],173:[function(require,module,exports){
-arguments[4][53][0].apply(exports,arguments)
-},{"./lib/_stream_writable.js":169,"dup":53}],174:[function(require,module,exports){
-arguments[4][48][0].apply(exports,arguments)
-},{"buffer":10,"dup":48}],175:[function(require,module,exports){
-'use strict';
-
-var isArrayish = require('is-arrayish');
-
-var concat = Array.prototype.concat;
-var slice = Array.prototype.slice;
-
-var swizzle = module.exports = function swizzle(args) {
- var results = [];
-
- for (var i = 0, len = args.length; i < len; i++) {
- var arg = args[i];
-
- if (isArrayish(arg)) {
- // http://jsperf.com/javascript-array-concat-vs-push/98
- results = concat.call(results, slice.call(arg));
- } else {
- results.push(arg);
- }
- }
-
- return results;
-};
-
-swizzle.wrap = function (fn) {
- return function () {
- return fn(swizzle(arguments));
- };
-};
-
-},{"is-arrayish":141}],176:[function(require,module,exports){
-exports.get = function(belowFn) {
- var oldLimit = Error.stackTraceLimit;
- Error.stackTraceLimit = Infinity;
-
- var dummyObject = {};
-
- var v8Handler = Error.prepareStackTrace;
- Error.prepareStackTrace = function(dummyObject, v8StackTrace) {
- return v8StackTrace;
- };
- Error.captureStackTrace(dummyObject, belowFn || exports.get);
-
- var v8StackTrace = dummyObject.stack;
- Error.prepareStackTrace = v8Handler;
- Error.stackTraceLimit = oldLimit;
-
- return v8StackTrace;
-};
-
-exports.parse = function(err) {
- if (!err.stack) {
- return [];
- }
-
- var self = this;
- var lines = err.stack.split('\n').slice(1);
-
- return lines
- .map(function(line) {
- if (line.match(/^\s*[-]{4,}$/)) {
- return self._createParsedCallSite({
- fileName: line,
- lineNumber: null,
- functionName: null,
- typeName: null,
- methodName: null,
- columnNumber: null,
- 'native': null,
- });
- }
-
- var lineMatch = line.match(/at (?:(.+)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/);
- if (!lineMatch) {
- return;
- }
-
- var object = null;
- var method = null;
- var functionName = null;
- var typeName = null;
- var methodName = null;
- var isNative = (lineMatch[5] === 'native');
-
- if (lineMatch[1]) {
- functionName = lineMatch[1];
- var methodStart = functionName.lastIndexOf('.');
- if (functionName[methodStart-1] == '.')
- methodStart--;
- if (methodStart > 0) {
- object = functionName.substr(0, methodStart);
- method = functionName.substr(methodStart + 1);
- var objectEnd = object.indexOf('.Module');
- if (objectEnd > 0) {
- functionName = functionName.substr(objectEnd + 1);
- object = object.substr(0, objectEnd);
- }
- }
- typeName = null;
- }
-
- if (method) {
- typeName = object;
- methodName = method;
- }
-
- if (method === '') {
- methodName = null;
- functionName = null;
- }
-
- var properties = {
- fileName: lineMatch[2] || null,
- lineNumber: parseInt(lineMatch[3], 10) || null,
- functionName: functionName,
- typeName: typeName,
- methodName: methodName,
- columnNumber: parseInt(lineMatch[4], 10) || null,
- 'native': isNative,
- };
-
- return self._createParsedCallSite(properties);
- })
- .filter(function(callSite) {
- return !!callSite;
- });
-};
-
-function CallSite(properties) {
- for (var property in properties) {
- this[property] = properties[property];
- }
-}
-
-var strProperties = [
- 'this',
- 'typeName',
- 'functionName',
- 'methodName',
- 'fileName',
- 'lineNumber',
- 'columnNumber',
- 'function',
- 'evalOrigin'
-];
-var boolProperties = [
- 'topLevel',
- 'eval',
- 'native',
- 'constructor'
-];
-strProperties.forEach(function (property) {
- CallSite.prototype[property] = null;
- CallSite.prototype['get' + property[0].toUpperCase() + property.substr(1)] = function () {
- return this[property];
- }
-});
-boolProperties.forEach(function (property) {
- CallSite.prototype[property] = false;
- CallSite.prototype['is' + property[0].toUpperCase() + property.substr(1)] = function () {
- return this[property];
- }
-});
-
-exports._createParsedCallSite = function(properties) {
- return new CallSite(properties);
-};
-
-},{}],177:[function(require,module,exports){
-arguments[4][49][0].apply(exports,arguments)
-},{"dup":49,"safe-buffer":174}],178:[function(require,module,exports){
-function Agent() {
- this._defaults = [];
-}
-
-["use", "on", "once", "set", "query", "type", "accept", "auth", "withCredentials", "sortQuery", "retry", "ok", "redirects",
- "timeout", "buffer", "serialize", "parse", "ca", "key", "pfx", "cert"].forEach(function(fn) {
- /** Default setting for all requests from this agent */
- Agent.prototype[fn] = function(/*varargs*/) {
- this._defaults.push({fn:fn, arguments:arguments});
- return this;
- }
-});
-
-Agent.prototype._setDefaults = function(req) {
- this._defaults.forEach(function(def) {
- req[def.fn].apply(req, def.arguments);
- });
-};
-
-module.exports = Agent;
-
-},{}],179:[function(require,module,exports){
-/**
- * Root reference for iframes.
- */
-
-var root;
-if (typeof window !== 'undefined') { // Browser window
- root = window;
-} else if (typeof self !== 'undefined') { // Web Worker
- root = self;
-} else { // Other environments
- console.warn("Using browser-only version of superagent in non-browser environment");
- root = this;
-}
-
-var Emitter = require('component-emitter');
-var RequestBase = require('./request-base');
-var isObject = require('./is-object');
-var ResponseBase = require('./response-base');
-var Agent = require('./agent-base');
-
-/**
- * Noop.
- */
-
-function noop(){};
-
-/**
- * Expose `request`.
- */
-
-var request = exports = module.exports = function(method, url) {
- // callback
- if ('function' == typeof url) {
- return new exports.Request('GET', method).end(url);
- }
-
- // url first
- if (1 == arguments.length) {
- return new exports.Request('GET', method);
- }
-
- return new exports.Request(method, url);
-}
-
-exports.Request = Request;
-
-/**
- * Determine XHR.
- */
-
-request.getXHR = function () {
- if (root.XMLHttpRequest
- && (!root.location || 'file:' != root.location.protocol
- || !root.ActiveXObject)) {
- return new XMLHttpRequest;
- } else {
- try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}
- try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
- try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
- try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}
- }
- throw Error("Browser-only version of superagent could not find XHR");
-};
-
-/**
- * Removes leading and trailing whitespace, added to support IE.
- *
- * @param {String} s
- * @return {String}
- * @api private
- */
-
-var trim = ''.trim
- ? function(s) { return s.trim(); }
- : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); };
-
-/**
- * Serialize the given `obj`.
- *
- * @param {Object} obj
- * @return {String}
- * @api private
- */
-
-function serialize(obj) {
- if (!isObject(obj)) return obj;
- var pairs = [];
- for (var key in obj) {
- pushEncodedKeyValuePair(pairs, key, obj[key]);
- }
- return pairs.join('&');
-}
-
-/**
- * Helps 'serialize' with serializing arrays.
- * Mutates the pairs array.
- *
- * @param {Array} pairs
- * @param {String} key
- * @param {Mixed} val
- */
-
-function pushEncodedKeyValuePair(pairs, key, val) {
- if (val != null) {
- if (Array.isArray(val)) {
- val.forEach(function(v) {
- pushEncodedKeyValuePair(pairs, key, v);
- });
- } else if (isObject(val)) {
- for(var subkey in val) {
- pushEncodedKeyValuePair(pairs, key + '[' + subkey + ']', val[subkey]);
- }
- } else {
- pairs.push(encodeURIComponent(key)
- + '=' + encodeURIComponent(val));
- }
- } else if (val === null) {
- pairs.push(encodeURIComponent(key));
- }
-}
-
-/**
- * Expose serialization method.
- */
-
-request.serializeObject = serialize;
-
-/**
- * Parse the given x-www-form-urlencoded `str`.
- *
- * @param {String} str
- * @return {Object}
- * @api private
- */
-
-function parseString(str) {
- var obj = {};
- var pairs = str.split('&');
- var pair;
- var pos;
-
- for (var i = 0, len = pairs.length; i < len; ++i) {
- pair = pairs[i];
- pos = pair.indexOf('=');
- if (pos == -1) {
- obj[decodeURIComponent(pair)] = '';
- } else {
- obj[decodeURIComponent(pair.slice(0, pos))] =
- decodeURIComponent(pair.slice(pos + 1));
- }
- }
-
- return obj;
-}
-
-/**
- * Expose parser.
- */
-
-request.parseString = parseString;
-
-/**
- * Default MIME type map.
- *
- * superagent.types.xml = 'application/xml';
- *
- */
-
-request.types = {
- html: 'text/html',
- json: 'application/json',
- xml: 'text/xml',
- urlencoded: 'application/x-www-form-urlencoded',
- 'form': 'application/x-www-form-urlencoded',
- 'form-data': 'application/x-www-form-urlencoded'
-};
-
-/**
- * Default serialization map.
- *
- * superagent.serialize['application/xml'] = function(obj){
- * return 'generated xml here';
- * };
- *
- */
-
-request.serialize = {
- 'application/x-www-form-urlencoded': serialize,
- 'application/json': JSON.stringify
-};
-
-/**
- * Default parsers.
- *
- * superagent.parse['application/xml'] = function(str){
- * return { object parsed from str };
- * };
- *
- */
-
-request.parse = {
- 'application/x-www-form-urlencoded': parseString,
- 'application/json': JSON.parse
-};
-
-/**
- * Parse the given header `str` into
- * an object containing the mapped fields.
- *
- * @param {String} str
- * @return {Object}
- * @api private
- */
-
-function parseHeader(str) {
- var lines = str.split(/\r?\n/);
- var fields = {};
- var index;
- var line;
- var field;
- var val;
-
- for (var i = 0, len = lines.length; i < len; ++i) {
- line = lines[i];
- index = line.indexOf(':');
- if (index === -1) { // could be empty line, just skip it
- continue;
- }
- field = line.slice(0, index).toLowerCase();
- val = trim(line.slice(index + 1));
- fields[field] = val;
- }
-
- return fields;
-}
-
-/**
- * Check if `mime` is json or has +json structured syntax suffix.
- *
- * @param {String} mime
- * @return {Boolean}
- * @api private
- */
-
-function isJSON(mime) {
- // should match /json or +json
- // but not /json-seq
- return /[\/+]json($|[^-\w])/.test(mime);
-}
-
-/**
- * Initialize a new `Response` with the given `xhr`.
- *
- * - set flags (.ok, .error, etc)
- * - parse header
- *
- * Examples:
- *
- * Aliasing `superagent` as `request` is nice:
- *
- * request = superagent;
- *
- * We can use the promise-like API, or pass callbacks:
- *
- * request.get('/').end(function(res){});
- * request.get('/', function(res){});
- *
- * Sending data can be chained:
- *
- * request
- * .post('/user')
- * .send({ name: 'tj' })
- * .end(function(res){});
- *
- * Or passed to `.send()`:
- *
- * request
- * .post('/user')
- * .send({ name: 'tj' }, function(res){});
- *
- * Or passed to `.post()`:
- *
- * request
- * .post('/user', { name: 'tj' })
- * .end(function(res){});
- *
- * Or further reduced to a single call for simple cases:
- *
- * request
- * .post('/user', { name: 'tj' }, function(res){});
- *
- * @param {XMLHTTPRequest} xhr
- * @param {Object} options
- * @api private
- */
-
-function Response(req) {
- this.req = req;
- this.xhr = this.req.xhr;
- // responseText is accessible only if responseType is '' or 'text' and on older browsers
- this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined')
- ? this.xhr.responseText
- : null;
- this.statusText = this.req.xhr.statusText;
- var status = this.xhr.status;
- // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
- if (status === 1223) {
- status = 204;
- }
- this._setStatusProperties(status);
- this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders());
- // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but
- // getResponseHeader still works. so we get content-type even if getting
- // other headers fails.
- this.header['content-type'] = this.xhr.getResponseHeader('content-type');
- this._setHeaderProperties(this.header);
-
- if (null === this.text && req._responseType) {
- this.body = this.xhr.response;
- } else {
- this.body = this.req.method != 'HEAD'
- ? this._parseBody(this.text ? this.text : this.xhr.response)
- : null;
- }
-}
-
-ResponseBase(Response.prototype);
-
-/**
- * Parse the given body `str`.
- *
- * Used for auto-parsing of bodies. Parsers
- * are defined on the `superagent.parse` object.
- *
- * @param {String} str
- * @return {Mixed}
- * @api private
- */
-
-Response.prototype._parseBody = function(str) {
- var parse = request.parse[this.type];
- if (this.req._parser) {
- return this.req._parser(this, str);
- }
- if (!parse && isJSON(this.type)) {
- parse = request.parse['application/json'];
- }
- return parse && str && (str.length || str instanceof Object)
- ? parse(str)
- : null;
-};
-
-/**
- * Return an `Error` representative of this response.
- *
- * @return {Error}
- * @api public
- */
-
-Response.prototype.toError = function(){
- var req = this.req;
- var method = req.method;
- var url = req.url;
-
- var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')';
- var err = new Error(msg);
- err.status = this.status;
- err.method = method;
- err.url = url;
-
- return err;
-};
-
-/**
- * Expose `Response`.
- */
-
-request.Response = Response;
-
-/**
- * Initialize a new `Request` with the given `method` and `url`.
- *
- * @param {String} method
- * @param {String} url
- * @api public
- */
-
-function Request(method, url) {
- var self = this;
- this._query = this._query || [];
- this.method = method;
- this.url = url;
- this.header = {}; // preserves header name case
- this._header = {}; // coerces header names to lowercase
- this.on('end', function(){
- var err = null;
- var res = null;
-
- try {
- res = new Response(self);
- } catch(e) {
- err = new Error('Parser is unable to parse the response');
- err.parse = true;
- err.original = e;
- // issue #675: return the raw response if the response parsing fails
- if (self.xhr) {
- // ie9 doesn't have 'response' property
- err.rawResponse = typeof self.xhr.responseType == 'undefined' ? self.xhr.responseText : self.xhr.response;
- // issue #876: return the http status code if the response parsing fails
- err.status = self.xhr.status ? self.xhr.status : null;
- err.statusCode = err.status; // backwards-compat only
- } else {
- err.rawResponse = null;
- err.status = null;
- }
-
- return self.callback(err);
- }
-
- self.emit('response', res);
-
- var new_err;
- try {
- if (!self._isResponseOK(res)) {
- new_err = new Error(res.statusText || 'Unsuccessful HTTP response');
- }
- } catch(custom_err) {
- new_err = custom_err; // ok() callback can throw
- }
-
- // #1000 don't catch errors from the callback to avoid double calling it
- if (new_err) {
- new_err.original = err;
- new_err.response = res;
- new_err.status = res.status;
- self.callback(new_err, res);
- } else {
- self.callback(null, res);
- }
- });
-}
-
-/**
- * Mixin `Emitter` and `RequestBase`.
- */
-
-Emitter(Request.prototype);
-RequestBase(Request.prototype);
-
-/**
- * Set Content-Type to `type`, mapping values from `request.types`.
- *
- * Examples:
- *
- * superagent.types.xml = 'application/xml';
- *
- * request.post('/')
- * .type('xml')
- * .send(xmlstring)
- * .end(callback);
- *
- * request.post('/')
- * .type('application/xml')
- * .send(xmlstring)
- * .end(callback);
- *
- * @param {String} type
- * @return {Request} for chaining
- * @api public
- */
-
-Request.prototype.type = function(type){
- this.set('Content-Type', request.types[type] || type);
- return this;
-};
-
-/**
- * Set Accept to `type`, mapping values from `request.types`.
- *
- * Examples:
- *
- * superagent.types.json = 'application/json';
- *
- * request.get('/agent')
- * .accept('json')
- * .end(callback);
- *
- * request.get('/agent')
- * .accept('application/json')
- * .end(callback);
- *
- * @param {String} accept
- * @return {Request} for chaining
- * @api public
- */
-
-Request.prototype.accept = function(type){
- this.set('Accept', request.types[type] || type);
- return this;
-};
-
-/**
- * Set Authorization field value with `user` and `pass`.
- *
- * @param {String} user
- * @param {String} [pass] optional in case of using 'bearer' as type
- * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic')
- * @return {Request} for chaining
- * @api public
- */
-
-Request.prototype.auth = function(user, pass, options){
- if (1 === arguments.length) pass = '';
- if (typeof pass === 'object' && pass !== null) { // pass is optional and can be replaced with options
- options = pass;
- pass = '';
- }
- if (!options) {
- options = {
- type: 'function' === typeof btoa ? 'basic' : 'auto',
- };
- }
-
- var encoder = function(string) {
- if ('function' === typeof btoa) {
- return btoa(string);
- }
- throw new Error('Cannot use basic auth, btoa is not a function');
- };
-
- return this._auth(user, pass, options, encoder);
-};
-
-/**
- * Add query-string `val`.
- *
- * Examples:
- *
- * request.get('/shoes')
- * .query('size=10')
- * .query({ color: 'blue' })
- *
- * @param {Object|String} val
- * @return {Request} for chaining
- * @api public
- */
-
-Request.prototype.query = function(val){
- if ('string' != typeof val) val = serialize(val);
- if (val) this._query.push(val);
- return this;
-};
-
-/**
- * Queue the given `file` as an attachment to the specified `field`,
- * with optional `options` (or filename).
- *
- * ``` js
- * request.post('/upload')
- * .attach('content', new Blob(['hey!'], { type: "text/html"}))
- * .end(callback);
- * ```
- *
- * @param {String} field
- * @param {Blob|File} file
- * @param {String|Object} options
- * @return {Request} for chaining
- * @api public
- */
-
-Request.prototype.attach = function(field, file, options){
- if (file) {
- if (this._data) {
- throw Error("superagent can't mix .send() and .attach()");
- }
-
- this._getFormData().append(field, file, options || file.name);
- }
- return this;
-};
-
-Request.prototype._getFormData = function(){
- if (!this._formData) {
- this._formData = new root.FormData();
- }
- return this._formData;
-};
-
-/**
- * Invoke the callback with `err` and `res`
- * and handle arity check.
- *
- * @param {Error} err
- * @param {Response} res
- * @api private
- */
-
-Request.prototype.callback = function(err, res){
- if (this._shouldRetry(err, res)) {
- return this._retry();
- }
-
- var fn = this._callback;
- this.clearTimeout();
-
- if (err) {
- if (this._maxRetries) err.retries = this._retries - 1;
- this.emit('error', err);
- }
-
- fn(err, res);
-};
-
-/**
- * Invoke callback with x-domain error.
- *
- * @api private
- */
-
-Request.prototype.crossDomainError = function(){
- var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.');
- err.crossDomain = true;
-
- err.status = this.status;
- err.method = this.method;
- err.url = this.url;
-
- this.callback(err);
-};
-
-// This only warns, because the request is still likely to work
-Request.prototype.buffer = Request.prototype.ca = Request.prototype.agent = function(){
- console.warn("This is not supported in browser version of superagent");
- return this;
-};
-
-// This throws, because it can't send/receive data as expected
-Request.prototype.pipe = Request.prototype.write = function(){
- throw Error("Streaming is not supported in browser version of superagent");
-};
-
-/**
- * Check if `obj` is a host object,
- * we don't want to serialize these :)
- *
- * @param {Object} obj
- * @return {Boolean}
- * @api private
- */
-Request.prototype._isHost = function _isHost(obj) {
- // Native objects stringify to [object File], [object Blob], [object FormData], etc.
- return obj && 'object' === typeof obj && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]';
-}
-
-/**
- * Initiate request, invoking callback `fn(res)`
- * with an instanceof `Response`.
- *
- * @param {Function} fn
- * @return {Request} for chaining
- * @api public
- */
-
-Request.prototype.end = function(fn){
- if (this._endCalled) {
- console.warn("Warning: .end() was called twice. This is not supported in superagent");
- }
- this._endCalled = true;
-
- // store callback
- this._callback = fn || noop;
-
- // querystring
- this._finalizeQueryString();
-
- return this._end();
-};
-
-Request.prototype._end = function() {
- var self = this;
- var xhr = (this.xhr = request.getXHR());
- var data = this._formData || this._data;
-
- this._setTimeouts();
-
- // state change
- xhr.onreadystatechange = function(){
- var readyState = xhr.readyState;
- if (readyState >= 2 && self._responseTimeoutTimer) {
- clearTimeout(self._responseTimeoutTimer);
- }
- if (4 != readyState) {
- return;
- }
-
- // In IE9, reads to any property (e.g. status) off of an aborted XHR will
- // result in the error "Could not complete the operation due to error c00c023f"
- var status;
- try { status = xhr.status } catch(e) { status = 0; }
-
- if (!status) {
- if (self.timedout || self._aborted) return;
- return self.crossDomainError();
- }
- self.emit('end');
- };
-
- // progress
- var handleProgress = function(direction, e) {
- if (e.total > 0) {
- e.percent = e.loaded / e.total * 100;
- }
- e.direction = direction;
- self.emit('progress', e);
- };
- if (this.hasListeners('progress')) {
- try {
- xhr.onprogress = handleProgress.bind(null, 'download');
- if (xhr.upload) {
- xhr.upload.onprogress = handleProgress.bind(null, 'upload');
- }
- } catch(e) {
- // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist.
- // Reported here:
- // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context
- }
- }
-
- // initiate request
- try {
- if (this.username && this.password) {
- xhr.open(this.method, this.url, true, this.username, this.password);
- } else {
- xhr.open(this.method, this.url, true);
- }
- } catch (err) {
- // see #1149
- return this.callback(err);
- }
-
- // CORS
- if (this._withCredentials) xhr.withCredentials = true;
-
- // body
- if (!this._formData && 'GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !this._isHost(data)) {
- // serialize stuff
- var contentType = this._header['content-type'];
- var serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : ''];
- if (!serialize && isJSON(contentType)) {
- serialize = request.serialize['application/json'];
- }
- if (serialize) data = serialize(data);
- }
-
- // set header fields
- for (var field in this.header) {
- if (null == this.header[field]) continue;
-
- if (this.header.hasOwnProperty(field))
- xhr.setRequestHeader(field, this.header[field]);
- }
-
- if (this._responseType) {
- xhr.responseType = this._responseType;
- }
-
- // send stuff
- this.emit('request', this);
-
- // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing)
- // We need null here if data is undefined
- xhr.send(typeof data !== 'undefined' ? data : null);
- return this;
-};
-
-request.agent = function() {
- return new Agent();
-};
-
-["GET", "POST", "OPTIONS", "PATCH", "PUT", "DELETE"].forEach(function(method) {
- Agent.prototype[method.toLowerCase()] = function(url, fn) {
- var req = new request.Request(method, url);
- this._setDefaults(req);
- if (fn) {
- req.end(fn);
- }
- return req;
- };
-});
-
-Agent.prototype.del = Agent.prototype['delete'];
-
-/**
- * GET `url` with optional callback `fn(res)`.
- *
- * @param {String} url
- * @param {Mixed|Function} [data] or fn
- * @param {Function} [fn]
- * @return {Request}
- * @api public
- */
-
-request.get = function(url, data, fn) {
- var req = request('GET', url);
- if ('function' == typeof data) (fn = data), (data = null);
- if (data) req.query(data);
- if (fn) req.end(fn);
- return req;
-};
-
-/**
- * HEAD `url` with optional callback `fn(res)`.
- *
- * @param {String} url
- * @param {Mixed|Function} [data] or fn
- * @param {Function} [fn]
- * @return {Request}
- * @api public
- */
-
-request.head = function(url, data, fn) {
- var req = request('HEAD', url);
- if ('function' == typeof data) (fn = data), (data = null);
- if (data) req.query(data);
- if (fn) req.end(fn);
- return req;
-};
-
-/**
- * OPTIONS query to `url` with optional callback `fn(res)`.
- *
- * @param {String} url
- * @param {Mixed|Function} [data] or fn
- * @param {Function} [fn]
- * @return {Request}
- * @api public
- */
-
-request.options = function(url, data, fn) {
- var req = request('OPTIONS', url);
- if ('function' == typeof data) (fn = data), (data = null);
- if (data) req.send(data);
- if (fn) req.end(fn);
- return req;
-};
-
-/**
- * DELETE `url` with optional `data` and callback `fn(res)`.
- *
- * @param {String} url
- * @param {Mixed} [data]
- * @param {Function} [fn]
- * @return {Request}
- * @api public
- */
-
-function del(url, data, fn) {
- var req = request('DELETE', url);
- if ('function' == typeof data) (fn = data), (data = null);
- if (data) req.send(data);
- if (fn) req.end(fn);
- return req;
-}
-
-request['del'] = del;
-request['delete'] = del;
-
-/**
- * PATCH `url` with optional `data` and callback `fn(res)`.
- *
- * @param {String} url
- * @param {Mixed} [data]
- * @param {Function} [fn]
- * @return {Request}
- * @api public
- */
-
-request.patch = function(url, data, fn) {
- var req = request('PATCH', url);
- if ('function' == typeof data) (fn = data), (data = null);
- if (data) req.send(data);
- if (fn) req.end(fn);
- return req;
-};
-
-/**
- * POST `url` with optional `data` and callback `fn(res)`.
- *
- * @param {String} url
- * @param {Mixed} [data]
- * @param {Function} [fn]
- * @return {Request}
- * @api public
- */
-
-request.post = function(url, data, fn) {
- var req = request('POST', url);
- if ('function' == typeof data) (fn = data), (data = null);
- if (data) req.send(data);
- if (fn) req.end(fn);
- return req;
-};
-
-/**
- * PUT `url` with optional `data` and callback `fn(res)`.
- *
- * @param {String} url
- * @param {Mixed|Function} [data] or fn
- * @param {Function} [fn]
- * @return {Request}
- * @api public
- */
-
-request.put = function(url, data, fn) {
- var req = request('PUT', url);
- if ('function' == typeof data) (fn = data), (data = null);
- if (data) req.send(data);
- if (fn) req.end(fn);
- return req;
-};
-
-},{"./agent-base":178,"./is-object":180,"./request-base":181,"./response-base":182,"component-emitter":131}],180:[function(require,module,exports){
-'use strict';
-
-/**
- * Check if `obj` is an object.
- *
- * @param {Object} obj
- * @return {Boolean}
- * @api private
- */
-
-function isObject(obj) {
- return null !== obj && 'object' === typeof obj;
-}
-
-module.exports = isObject;
-
-},{}],181:[function(require,module,exports){
-'use strict';
-
-/**
- * Module of mixed-in functions shared between node and client code
- */
-var isObject = require('./is-object');
-
-/**
- * Expose `RequestBase`.
- */
-
-module.exports = RequestBase;
-
-/**
- * Initialize a new `RequestBase`.
- *
- * @api public
- */
-
-function RequestBase(obj) {
- if (obj) return mixin(obj);
-}
-
-/**
- * Mixin the prototype properties.
- *
- * @param {Object} obj
- * @return {Object}
- * @api private
- */
-
-function mixin(obj) {
- for (var key in RequestBase.prototype) {
- obj[key] = RequestBase.prototype[key];
- }
- return obj;
-}
-
-/**
- * Clear previous timeout.
- *
- * @return {Request} for chaining
- * @api public
- */
-
-RequestBase.prototype.clearTimeout = function _clearTimeout(){
- clearTimeout(this._timer);
- clearTimeout(this._responseTimeoutTimer);
- delete this._timer;
- delete this._responseTimeoutTimer;
- return this;
-};
-
-/**
- * Override default response body parser
- *
- * This function will be called to convert incoming data into request.body
- *
- * @param {Function}
- * @api public
- */
-
-RequestBase.prototype.parse = function parse(fn){
- this._parser = fn;
- return this;
-};
-
-/**
- * Set format of binary response body.
- * In browser valid formats are 'blob' and 'arraybuffer',
- * which return Blob and ArrayBuffer, respectively.
- *
- * In Node all values result in Buffer.
- *
- * Examples:
- *
- * req.get('/')
- * .responseType('blob')
- * .end(callback);
- *
- * @param {String} val
- * @return {Request} for chaining
- * @api public
- */
-
-RequestBase.prototype.responseType = function(val){
- this._responseType = val;
- return this;
-};
-
-/**
- * Override default request body serializer
- *
- * This function will be called to convert data set via .send or .attach into payload to send
- *
- * @param {Function}
- * @api public
- */
-
-RequestBase.prototype.serialize = function serialize(fn){
- this._serializer = fn;
- return this;
-};
-
-/**
- * Set timeouts.
- *
- * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time.
- * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections.
- *
- * Value of 0 or false means no timeout.
- *
- * @param {Number|Object} ms or {response, deadline}
- * @return {Request} for chaining
- * @api public
- */
-
-RequestBase.prototype.timeout = function timeout(options){
- if (!options || 'object' !== typeof options) {
- this._timeout = options;
- this._responseTimeout = 0;
- return this;
- }
-
- for(var option in options) {
- switch(option) {
- case 'deadline':
- this._timeout = options.deadline;
- break;
- case 'response':
- this._responseTimeout = options.response;
- break;
- default:
- console.warn("Unknown timeout option", option);
- }
- }
- return this;
-};
-
-/**
- * Set number of retry attempts on error.
- *
- * Failed requests will be retried 'count' times if timeout or err.code >= 500.
- *
- * @param {Number} count
- * @param {Function} [fn]
- * @return {Request} for chaining
- * @api public
- */
-
-RequestBase.prototype.retry = function retry(count, fn){
- // Default to 1 if no count passed or true
- if (arguments.length === 0 || count === true) count = 1;
- if (count <= 0) count = 0;
- this._maxRetries = count;
- this._retries = 0;
- this._retryCallback = fn;
- return this;
-};
-
-var ERROR_CODES = [
- 'ECONNRESET',
- 'ETIMEDOUT',
- 'EADDRINFO',
- 'ESOCKETTIMEDOUT'
-];
-
-/**
- * Determine if a request should be retried.
- * (Borrowed from segmentio/superagent-retry)
- *
- * @param {Error} err
- * @param {Response} [res]
- * @returns {Boolean}
- */
-RequestBase.prototype._shouldRetry = function(err, res) {
- if (!this._maxRetries || this._retries++ >= this._maxRetries) {
- return false;
- }
- if (this._retryCallback) {
- try {
- var override = this._retryCallback(err, res);
- if (override === true) return true;
- if (override === false) return false;
- // undefined falls back to defaults
- } catch(e) {
- console.error(e);
- }
- }
- if (res && res.status && res.status >= 500 && res.status != 501) return true;
- if (err) {
- if (err.code && ~ERROR_CODES.indexOf(err.code)) return true;
- // Superagent timeout
- if (err.timeout && err.code == 'ECONNABORTED') return true;
- if (err.crossDomain) return true;
- }
- return false;
-};
-
-/**
- * Retry request
- *
- * @return {Request} for chaining
- * @api private
- */
-
-RequestBase.prototype._retry = function() {
-
- this.clearTimeout();
-
- // node
- if (this.req) {
- this.req = null;
- this.req = this.request();
- }
-
- this._aborted = false;
- this.timedout = false;
-
- return this._end();
-};
-
-/**
- * Promise support
- *
- * @param {Function} resolve
- * @param {Function} [reject]
- * @return {Request}
- */
-
-RequestBase.prototype.then = function then(resolve, reject) {
- if (!this._fullfilledPromise) {
- var self = this;
- if (this._endCalled) {
- console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises");
- }
- this._fullfilledPromise = new Promise(function(innerResolve, innerReject) {
- self.end(function(err, res) {
- if (err) innerReject(err);
- else innerResolve(res);
- });
- });
- }
- return this._fullfilledPromise.then(resolve, reject);
-};
-
-RequestBase.prototype['catch'] = function(cb) {
- return this.then(undefined, cb);
-};
-
-/**
- * Allow for extension
- */
-
-RequestBase.prototype.use = function use(fn) {
- fn(this);
- return this;
-};
-
-RequestBase.prototype.ok = function(cb) {
- if ('function' !== typeof cb) throw Error("Callback required");
- this._okCallback = cb;
- return this;
-};
-
-RequestBase.prototype._isResponseOK = function(res) {
- if (!res) {
- return false;
- }
-
- if (this._okCallback) {
- return this._okCallback(res);
- }
-
- return res.status >= 200 && res.status < 300;
-};
-
-/**
- * Get request header `field`.
- * Case-insensitive.
- *
- * @param {String} field
- * @return {String}
- * @api public
- */
-
-RequestBase.prototype.get = function(field){
- return this._header[field.toLowerCase()];
-};
-
-/**
- * Get case-insensitive header `field` value.
- * This is a deprecated internal API. Use `.get(field)` instead.
- *
- * (getHeader is no longer used internally by the superagent code base)
- *
- * @param {String} field
- * @return {String}
- * @api private
- * @deprecated
- */
-
-RequestBase.prototype.getHeader = RequestBase.prototype.get;
-
-/**
- * Set header `field` to `val`, or multiple fields with one object.
- * Case-insensitive.
- *
- * Examples:
- *
- * req.get('/')
- * .set('Accept', 'application/json')
- * .set('X-API-Key', 'foobar')
- * .end(callback);
- *
- * req.get('/')
- * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
- * .end(callback);
- *
- * @param {String|Object} field
- * @param {String} val
- * @return {Request} for chaining
- * @api public
- */
-
-RequestBase.prototype.set = function(field, val){
- if (isObject(field)) {
- for (var key in field) {
- this.set(key, field[key]);
- }
- return this;
- }
- this._header[field.toLowerCase()] = val;
- this.header[field] = val;
- return this;
-};
-
-/**
- * Remove header `field`.
- * Case-insensitive.
- *
- * Example:
- *
- * req.get('/')
- * .unset('User-Agent')
- * .end(callback);
- *
- * @param {String} field
- */
-RequestBase.prototype.unset = function(field){
- delete this._header[field.toLowerCase()];
- delete this.header[field];
- return this;
-};
-
-/**
- * Write the field `name` and `val`, or multiple fields with one object
- * for "multipart/form-data" request bodies.
- *
- * ``` js
- * request.post('/upload')
- * .field('foo', 'bar')
- * .end(callback);
- *
- * request.post('/upload')
- * .field({ foo: 'bar', baz: 'qux' })
- * .end(callback);
- * ```
- *
- * @param {String|Object} name
- * @param {String|Blob|File|Buffer|fs.ReadStream} val
- * @return {Request} for chaining
- * @api public
- */
-RequestBase.prototype.field = function(name, val) {
- // name should be either a string or an object.
- if (null === name || undefined === name) {
- throw new Error('.field(name, val) name can not be empty');
- }
-
- if (this._data) {
- console.error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()");
- }
-
- if (isObject(name)) {
- for (var key in name) {
- this.field(key, name[key]);
- }
- return this;
- }
-
- if (Array.isArray(val)) {
- for (var i in val) {
- this.field(name, val[i]);
- }
- return this;
- }
-
- // val should be defined now
- if (null === val || undefined === val) {
- throw new Error('.field(name, val) val can not be empty');
- }
- if ('boolean' === typeof val) {
- val = '' + val;
- }
- this._getFormData().append(name, val);
- return this;
-};
-
-/**
- * Abort the request, and clear potential timeout.
- *
- * @return {Request}
- * @api public
- */
-RequestBase.prototype.abort = function(){
- if (this._aborted) {
- return this;
- }
- this._aborted = true;
- this.xhr && this.xhr.abort(); // browser
- this.req && this.req.abort(); // node
- this.clearTimeout();
- this.emit('abort');
- return this;
-};
-
-RequestBase.prototype._auth = function(user, pass, options, base64Encoder) {
- switch (options.type) {
- case 'basic':
- this.set('Authorization', 'Basic ' + base64Encoder(user + ':' + pass));
- break;
-
- case 'auto':
- this.username = user;
- this.password = pass;
- break;
-
- case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' })
- this.set('Authorization', 'Bearer ' + user);
- break;
- }
- return this;
-};
-
-/**
- * Enable transmission of cookies with x-domain requests.
- *
- * Note that for this to work the origin must not be
- * using "Access-Control-Allow-Origin" with a wildcard,
- * and also must set "Access-Control-Allow-Credentials"
- * to "true".
- *
- * @api public
- */
-
-RequestBase.prototype.withCredentials = function(on) {
- // This is browser-only functionality. Node side is no-op.
- if (on == undefined) on = true;
- this._withCredentials = on;
- return this;
-};
-
-/**
- * Set the max redirects to `n`. Does noting in browser XHR implementation.
- *
- * @param {Number} n
- * @return {Request} for chaining
- * @api public
- */
-
-RequestBase.prototype.redirects = function(n){
- this._maxRedirects = n;
- return this;
-};
-
-/**
- * Maximum size of buffered response body, in bytes. Counts uncompressed size.
- * Default 200MB.
- *
- * @param {Number} n
- * @return {Request} for chaining
- */
-RequestBase.prototype.maxResponseSize = function(n){
- if ('number' !== typeof n) {
- throw TypeError("Invalid argument");
- }
- this._maxResponseSize = n;
- return this;
-};
-
-/**
- * Convert to a plain javascript object (not JSON string) of scalar properties.
- * Note as this method is designed to return a useful non-this value,
- * it cannot be chained.
- *
- * @return {Object} describing method, url, and data of this request
- * @api public
- */
-
-RequestBase.prototype.toJSON = function() {
- return {
- method: this.method,
- url: this.url,
- data: this._data,
- headers: this._header,
- };
-};
-
-/**
- * Send `data` as the request body, defaulting the `.type()` to "json" when
- * an object is given.
- *
- * Examples:
- *
- * // manual json
- * request.post('/user')
- * .type('json')
- * .send('{"name":"tj"}')
- * .end(callback)
- *
- * // auto json
- * request.post('/user')
- * .send({ name: 'tj' })
- * .end(callback)
- *
- * // manual x-www-form-urlencoded
- * request.post('/user')
- * .type('form')
- * .send('name=tj')
- * .end(callback)
- *
- * // auto x-www-form-urlencoded
- * request.post('/user')
- * .type('form')
- * .send({ name: 'tj' })
- * .end(callback)
- *
- * // defaults to x-www-form-urlencoded
- * request.post('/user')
- * .send('name=tobi')
- * .send('species=ferret')
- * .end(callback)
- *
- * @param {String|Object} data
- * @return {Request} for chaining
- * @api public
- */
-
-RequestBase.prototype.send = function(data){
- var isObj = isObject(data);
- var type = this._header['content-type'];
-
- if (this._formData) {
- console.error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()");
- }
-
- if (isObj && !this._data) {
- if (Array.isArray(data)) {
- this._data = [];
- } else if (!this._isHost(data)) {
- this._data = {};
- }
- } else if (data && this._data && this._isHost(this._data)) {
- throw Error("Can't merge these send calls");
- }
-
- // merge
- if (isObj && isObject(this._data)) {
- for (var key in data) {
- this._data[key] = data[key];
- }
- } else if ('string' == typeof data) {
- // default to x-www-form-urlencoded
- if (!type) this.type('form');
- type = this._header['content-type'];
- if ('application/x-www-form-urlencoded' == type) {
- this._data = this._data
- ? this._data + '&' + data
- : data;
- } else {
- this._data = (this._data || '') + data;
- }
- } else {
- this._data = data;
- }
-
- if (!isObj || this._isHost(data)) {
- return this;
- }
-
- // default to json
- if (!type) this.type('json');
- return this;
-};
-
-/**
- * Sort `querystring` by the sort function
- *
- *
- * Examples:
- *
- * // default order
- * request.get('/user')
- * .query('name=Nick')
- * .query('search=Manny')
- * .sortQuery()
- * .end(callback)
- *
- * // customized sort function
- * request.get('/user')
- * .query('name=Nick')
- * .query('search=Manny')
- * .sortQuery(function(a, b){
- * return a.length - b.length;
- * })
- * .end(callback)
- *
- *
- * @param {Function} sort
- * @return {Request} for chaining
- * @api public
- */
-
-RequestBase.prototype.sortQuery = function(sort) {
- // _sort default to true but otherwise can be a function or boolean
- this._sort = typeof sort === 'undefined' ? true : sort;
- return this;
-};
-
-/**
- * Compose querystring to append to req.url
- *
- * @api private
- */
-RequestBase.prototype._finalizeQueryString = function(){
- var query = this._query.join('&');
- if (query) {
- this.url += (this.url.indexOf('?') >= 0 ? '&' : '?') + query;
- }
- this._query.length = 0; // Makes the call idempotent
-
- if (this._sort) {
- var index = this.url.indexOf('?');
- if (index >= 0) {
- var queryArr = this.url.substring(index + 1).split('&');
- if ('function' === typeof this._sort) {
- queryArr.sort(this._sort);
- } else {
- queryArr.sort();
- }
- this.url = this.url.substring(0, index) + '?' + queryArr.join('&');
- }
- }
-};
-
-// For backwards compat only
-RequestBase.prototype._appendQueryString = function() {console.trace("Unsupported");}
-
-/**
- * Invoke callback with timeout error.
- *
- * @api private
- */
-
-RequestBase.prototype._timeoutError = function(reason, timeout, errno){
- if (this._aborted) {
- return;
- }
- var err = new Error(reason + timeout + 'ms exceeded');
- err.timeout = timeout;
- err.code = 'ECONNABORTED';
- err.errno = errno;
- this.timedout = true;
- this.abort();
- this.callback(err);
-};
-
-RequestBase.prototype._setTimeouts = function() {
- var self = this;
-
- // deadline
- if (this._timeout && !this._timer) {
- this._timer = setTimeout(function(){
- self._timeoutError('Timeout of ', self._timeout, 'ETIME');
- }, this._timeout);
- }
- // response timeout
- if (this._responseTimeout && !this._responseTimeoutTimer) {
- this._responseTimeoutTimer = setTimeout(function(){
- self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT');
- }, this._responseTimeout);
- }
-};
-
-},{"./is-object":180}],182:[function(require,module,exports){
-'use strict';
-
-/**
- * Module dependencies.
- */
-
-var utils = require('./utils');
-
-/**
- * Expose `ResponseBase`.
- */
-
-module.exports = ResponseBase;
-
-/**
- * Initialize a new `ResponseBase`.
- *
- * @api public
- */
-
-function ResponseBase(obj) {
- if (obj) return mixin(obj);
-}
-
-/**
- * Mixin the prototype properties.
- *
- * @param {Object} obj
- * @return {Object}
- * @api private
- */
-
-function mixin(obj) {
- for (var key in ResponseBase.prototype) {
- obj[key] = ResponseBase.prototype[key];
- }
- return obj;
-}
-
-/**
- * Get case-insensitive `field` value.
- *
- * @param {String} field
- * @return {String}
- * @api public
- */
-
-ResponseBase.prototype.get = function(field) {
- return this.header[field.toLowerCase()];
-};
-
-/**
- * Set header related properties:
- *
- * - `.type` the content type without params
- *
- * A response of "Content-Type: text/plain; charset=utf-8"
- * will provide you with a `.type` of "text/plain".
- *
- * @param {Object} header
- * @api private
- */
-
-ResponseBase.prototype._setHeaderProperties = function(header){
- // TODO: moar!
- // TODO: make this a util
-
- // content-type
- var ct = header['content-type'] || '';
- this.type = utils.type(ct);
-
- // params
- var params = utils.params(ct);
- for (var key in params) this[key] = params[key];
-
- this.links = {};
-
- // links
- try {
- if (header.link) {
- this.links = utils.parseLinks(header.link);
- }
- } catch (err) {
- // ignore
- }
-};
-
-/**
- * Set flags such as `.ok` based on `status`.
- *
- * For example a 2xx response will give you a `.ok` of __true__
- * whereas 5xx will be __false__ and `.error` will be __true__. The
- * `.clientError` and `.serverError` are also available to be more
- * specific, and `.statusType` is the class of error ranging from 1..5
- * sometimes useful for mapping respond colors etc.
- *
- * "sugar" properties are also defined for common cases. Currently providing:
- *
- * - .noContent
- * - .badRequest
- * - .unauthorized
- * - .notAcceptable
- * - .notFound
- *
- * @param {Number} status
- * @api private
- */
-
-ResponseBase.prototype._setStatusProperties = function(status){
- var type = status / 100 | 0;
-
- // status / class
- this.status = this.statusCode = status;
- this.statusType = type;
-
- // basics
- this.info = 1 == type;
- this.ok = 2 == type;
- this.redirect = 3 == type;
- this.clientError = 4 == type;
- this.serverError = 5 == type;
- this.error = (4 == type || 5 == type)
- ? this.toError()
- : false;
-
- // sugar
- this.created = 201 == status;
- this.accepted = 202 == status;
- this.noContent = 204 == status;
- this.badRequest = 400 == status;
- this.unauthorized = 401 == status;
- this.notAcceptable = 406 == status;
- this.forbidden = 403 == status;
- this.notFound = 404 == status;
- this.unprocessableEntity = 422 == status;
-};
-
-},{"./utils":183}],183:[function(require,module,exports){
-'use strict';
-
-/**
- * Return the mime type for the given `str`.
- *
- * @param {String} str
- * @return {String}
- * @api private
- */
-
-exports.type = function(str){
- return str.split(/ *; */).shift();
-};
-
-/**
- * Return header field parameters.
- *
- * @param {String} str
- * @return {Object}
- * @api private
- */
-
-exports.params = function(str){
- return str.split(/ *; */).reduce(function(obj, str){
- var parts = str.split(/ *= */);
- var key = parts.shift();
- var val = parts.shift();
-
- if (key && val) obj[key] = val;
- return obj;
- }, {});
-};
-
-/**
- * Parse Link header fields.
- *
- * @param {String} str
- * @return {Object}
- * @api private
- */
-
-exports.parseLinks = function(str){
- return str.split(/ *, */).reduce(function(obj, str){
- var parts = str.split(/ *; */);
- var url = parts[0].slice(1, -1);
- var rel = parts[1].split(/ *= */)[1].slice(1, -1);
- obj[rel] = url;
- return obj;
- }, {});
-};
-
-/**
- * Strip content related fields from `header`.
- *
- * @param {Object} header
- * @return {Object} header
- * @api private
- */
-
-exports.cleanHeader = function(header, changesOrigin){
- delete header['content-type'];
- delete header['content-length'];
- delete header['transfer-encoding'];
- delete header['host'];
- // secuirty
- if (changesOrigin) {
- delete header['authorization'];
- delete header['cookie'];
- }
- return header;
-};
-
-},{}],184:[function(require,module,exports){
-'use strict';
-
-/***
- * Convert string to hex color.
- *
- * @param {String} str Text to hash and convert to hex.
- * @returns {String}
- * @api public
- */
-module.exports = function hex(str) {
- for (
- var i = 0, hash = 0;
- i < str.length;
- hash = str.charCodeAt(i++) + ((hash << 5) - hash)
- );
-
- var color = Math.floor(
- Math.abs(
- (Math.sin(hash) * 10000) % 1 * 16777216
- )
- ).toString(16);
-
- return '#' + Array(6 - color.length + 1).join('0') + color;
-};
-
-},{}],185:[function(require,module,exports){
-/**
- * cli.js: Config that conform to commonly used CLI logging levels.
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- */
-
-'use strict';
-
-/**
- * Default levels for the CLI configuration.
- * @type {Object}
- */
-exports.levels = {
- error: 0,
- warn: 1,
- help: 2,
- data: 3,
- info: 4,
- debug: 5,
- prompt: 6,
- verbose: 7,
- input: 8,
- silly: 9
-};
-
-/**
- * Default colors for the CLI configuration.
- * @type {Object}
- */
-exports.colors = {
- error: 'red',
- warn: 'yellow',
- help: 'cyan',
- data: 'grey',
- info: 'green',
- debug: 'blue',
- prompt: 'grey',
- verbose: 'cyan',
- input: 'grey',
- silly: 'magenta'
-};
-
-},{}],186:[function(require,module,exports){
-/**
- * index.js: Default settings for all levels that winston knows about.
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- */
-
-'use strict';
-
-/**
- * Export config set for the CLI.
- * @type {Object}
- */
-Object.defineProperty(exports, 'cli', {
- value: require('./cli')
-});
-
-/**
- * Export config set for npm.
- * @type {Object}
- */
-Object.defineProperty(exports, 'npm', {
- value: require('./npm')
-});
-
-/**
- * Export config set for the syslog.
- * @type {Object}
- */
-Object.defineProperty(exports, 'syslog', {
- value: require('./syslog')
-});
-
-},{"./cli":185,"./npm":187,"./syslog":188}],187:[function(require,module,exports){
-/**
- * npm.js: Config that conform to npm logging levels.
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- */
-
-'use strict';
-
-/**
- * Default levels for the npm configuration.
- * @type {Object}
- */
-exports.levels = {
- error: 0,
- warn: 1,
- info: 2,
- http: 3,
- verbose: 4,
- debug: 5,
- silly: 6
-};
-
-/**
- * Default levels for the npm configuration.
- * @type {Object}
- */
-exports.colors = {
- error: 'red',
- warn: 'yellow',
- info: 'green',
- http: 'green',
- verbose: 'cyan',
- debug: 'blue',
- silly: 'magenta'
-};
-
-},{}],188:[function(require,module,exports){
-/**
- * syslog.js: Config that conform to syslog logging levels.
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- */
-
-'use strict';
-
-/**
- * Default levels for the syslog configuration.
- * @type {Object}
- */
-exports.levels = {
- emerg: 0,
- alert: 1,
- crit: 2,
- error: 3,
- warning: 4,
- notice: 5,
- info: 6,
- debug: 7
-};
-
-/**
- * Default levels for the syslog configuration.
- * @type {Object}
- */
-exports.colors = {
- emerg: 'red',
- alert: 'yellow',
- crit: 'red',
- error: 'red',
- warning: 'red',
- notice: 'yellow',
- info: 'green',
- debug: 'blue'
-};
-
-},{}],189:[function(require,module,exports){
-'use strict';
-
-/**
- * A shareable symbol constant that can be used
- * as a non-enumerable / semi-hidden level identifier
- * to allow the readable level property to be mutable for
- * operations like colorization
- *
- * @type {Symbol}
- */
-Object.defineProperty(exports, 'LEVEL', {
- value: Symbol.for('level')
-});
-
-/**
- * A shareable symbol constant that can be used
- * as a non-enumerable / semi-hidden message identifier
- * to allow the final message property to not have
- * side effects on another.
- *
- * @type {Symbol}
- */
-Object.defineProperty(exports, 'MESSAGE', {
- value: Symbol.for('message')
-});
-
-/**
- * A shareable symbol constant that can be used
- * as a non-enumerable / semi-hidden message identifier
- * to allow the extracted splat property be hidden
- *
- * @type {Symbol}
- */
-Object.defineProperty(exports, 'SPLAT', {
- value: Symbol.for('splat')
-});
-
-/**
- * A shareable object constant that can be used
- * as a standard configuration for winston@3.
- *
- * @type {Object}
- */
-Object.defineProperty(exports, 'configs', {
- value: require('./config')
-});
-
-},{"./config":186}],190:[function(require,module,exports){
-arguments[4][79][0].apply(exports,arguments)
-},{"dup":79}],191:[function(require,module,exports){
-'use strict';
-
-var util = require('util');
-var Writable = require('readable-stream/writable');
-
-var _require = require('triple-beam'),
- LEVEL = _require.LEVEL;
-
-/**
- * Constructor function for the TransportStream. This is the base prototype
- * that all `winston >= 3` transports should inherit from.
- * @param {Object} options - Options for this TransportStream instance
- * @param {String} options.level - Highest level according to RFC5424.
- * @param {Boolean} options.handleExceptions - If true, info with
- * { exception: true } will be written.
- * @param {Function} options.log - Custom log function for simple Transport
- * creation
- * @param {Function} options.close - Called on "unpipe" from parent.
- */
-
-
-var TransportStream = module.exports = function TransportStream() {
- var _this = this;
-
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
-
- Writable.call(this, { objectMode: true, highWaterMark: options.highWaterMark });
-
- this.format = options.format;
- this.level = options.level;
- this.handleExceptions = options.handleExceptions;
- this.handleRejections = options.handleRejections;
- this.silent = options.silent;
-
- if (options.log) this.log = options.log;
- if (options.logv) this.logv = options.logv;
- if (options.close) this.close = options.close;
-
- // Get the levels from the source we are piped from.
- this.once('pipe', function (logger) {
- // Remark (indexzero): this bookkeeping can only support multiple
- // Logger parents with the same `levels`. This comes into play in
- // the `winston.Container` code in which `container.add` takes
- // a fully realized set of options with pre-constructed TransportStreams.
- _this.levels = logger.levels;
- _this.parent = logger;
- });
-
- // If and/or when the transport is removed from this instance
- this.once('unpipe', function (src) {
- // Remark (indexzero): this bookkeeping can only support multiple
- // Logger parents with the same `levels`. This comes into play in
- // the `winston.Container` code in which `container.add` takes
- // a fully realized set of options with pre-constructed TransportStreams.
- if (src === _this.parent) {
- _this.parent = null;
- if (_this.close) {
- _this.close();
- }
- }
- });
-};
-
-/*
- * Inherit from Writeable using Node.js built-ins
- */
-util.inherits(TransportStream, Writable);
-
-/**
- * Writes the info object to our transport instance.
- * @param {mixed} info - TODO: add param description.
- * @param {mixed} enc - TODO: add param description.
- * @param {function} callback - TODO: add param description.
- * @returns {undefined}
- * @private
- */
-TransportStream.prototype._write = function _write(info, enc, callback) {
- if (this.silent || info.exception === true && !this.handleExceptions) {
- return callback(null);
- }
-
- // Remark: This has to be handled in the base transport now because we
- // cannot conditionally write to our pipe targets as stream. We always
- // prefer any explicit level set on the Transport itself falling back to
- // any level set on the parent.
- var level = this.level || this.parent && this.parent.level;
-
- if (!level || this.levels[level] >= this.levels[info[LEVEL]]) {
- if (info && !this.format) {
- return this.log(info, callback);
- }
-
- var errState = void 0;
- var transformed = void 0;
-
- // We trap(and re-throw) any errors generated by the user-provided format, but also
- // guarantee that the streams callback is invoked so that we can continue flowing.
- try {
- transformed = this.format.transform(Object.assign({}, info), this.format.options);
- } catch (err) {
- errState = err;
- }
-
- if (errState || !transformed) {
- // eslint-disable-next-line callback-return
- callback();
- if (errState) throw errState;
- return;
- }
-
- return this.log(transformed, callback);
- }
-
- return callback(null);
-};
-
-/**
- * Writes the batch of info objects (i.e. "object chunks") to our transport
- * instance after performing any necessary filtering.
- * @param {mixed} chunks - TODO: add params description.
- * @param {function} callback - TODO: add params description.
- * @returns {mixed} - TODO: add returns description.
- * @private
- */
-TransportStream.prototype._writev = function _writev(chunks, callback) {
- if (this.logv) {
- var infos = chunks.filter(this._accept, this);
- if (!infos.length) {
- return callback(null);
- }
-
- // Remark (indexzero): from a performance perspective if Transport
- // implementers do choose to implement logv should we make it their
- // responsibility to invoke their format?
- return this.logv(infos, callback);
- }
-
- for (var i = 0; i < chunks.length; i++) {
- if (!this._accept(chunks[i])) continue;
-
- if (chunks[i].chunk && !this.format) {
- this.log(chunks[i].chunk, chunks[i].callback);
- continue;
- }
-
- var errState = void 0;
- var transformed = void 0;
-
- // We trap(and re-throw) any errors generated by the user-provided format, but also
- // guarantee that the streams callback is invoked so that we can continue flowing.
- try {
- transformed = this.format.transform(Object.assign({}, chunks[i].chunk), this.format.options);
- } catch (err) {
- errState = err;
- }
-
- if (errState || !transformed) {
- // eslint-disable-next-line callback-return
- chunks[i].callback();
- if (errState) {
- // eslint-disable-next-line callback-return
- callback(null);
- throw errState;
- }
- } else {
- this.log(transformed, chunks[i].callback);
- }
- }
-
- return callback(null);
-};
-
-/**
- * Predicate function that returns true if the specfied `info` on the
- * WriteReq, `write`, should be passed down into the derived
- * TransportStream's I/O via `.log(info, callback)`.
- * @param {WriteReq} write - winston@3 Node.js WriteReq for the `info` object
- * representing the log message.
- * @returns {Boolean} - Value indicating if the `write` should be accepted &
- * logged.
- */
-TransportStream.prototype._accept = function _accept(write) {
- var info = write.chunk;
- if (this.silent) {
- return false;
- }
-
- // We always prefer any explicit level set on the Transport itself
- // falling back to any level set on the parent.
- var level = this.level || this.parent && this.parent.level;
-
- // Immediately check the average case: log level filtering.
- if (info.exception === true || !level || this.levels[level] >= this.levels[info[LEVEL]]) {
- // Ensure the info object is valid based on `{ exception }`:
- // 1. { handleExceptions: true }: all `info` objects are valid
- // 2. { exception: false }: accepted by all transports.
- if (this.handleExceptions || info.exception !== true) {
- return true;
- }
- }
-
- return false;
-};
-
-/**
- * _nop is short for "No operation"
- * @returns {Boolean} Intentionally false.
- */
-TransportStream.prototype._nop = function _nop() {
- // eslint-disable-next-line no-undefined
- return void undefined;
-};
-
-// Expose legacy stream
-module.exports.LegacyTransportStream = require('./legacy');
-},{"./legacy":192,"readable-stream/writable":173,"triple-beam":189,"util":82}],192:[function(require,module,exports){
-'use strict';
-
-var util = require('util');
-
-var _require = require('triple-beam'),
- LEVEL = _require.LEVEL;
-
-var TransportStream = require('./');
-
-/**
- * Constructor function for the LegacyTransportStream. This is an internal
- * wrapper `winston >= 3` uses to wrap older transports implementing
- * log(level, message, meta).
- * @param {Object} options - Options for this TransportStream instance.
- * @param {Transpot} options.transport - winston@2 or older Transport to wrap.
- */
-
-var LegacyTransportStream = module.exports = function LegacyTransportStream() {
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
-
- TransportStream.call(this, options);
- if (!options.transport || typeof options.transport.log !== 'function') {
- throw new Error('Invalid transport, must be an object with a log method.');
- }
-
- this.transport = options.transport;
- this.level = this.level || options.transport.level;
- this.handleExceptions = this.handleExceptions || options.transport.handleExceptions;
-
- // Display our deprecation notice.
- this._deprecated();
-
- // Properly bubble up errors from the transport to the
- // LegacyTransportStream instance, but only once no matter how many times
- // this transport is shared.
- function transportError(err) {
- this.emit('error', err, this.transport);
- }
-
- if (!this.transport.__winstonError) {
- this.transport.__winstonError = transportError.bind(this);
- this.transport.on('error', this.transport.__winstonError);
- }
-};
-
-/*
- * Inherit from TransportStream using Node.js built-ins
- */
-util.inherits(LegacyTransportStream, TransportStream);
-
-/**
- * Writes the info object to our transport instance.
- * @param {mixed} info - TODO: add param description.
- * @param {mixed} enc - TODO: add param description.
- * @param {function} callback - TODO: add param description.
- * @returns {undefined}
- * @private
- */
-LegacyTransportStream.prototype._write = function _write(info, enc, callback) {
- if (this.silent || info.exception === true && !this.handleExceptions) {
- return callback(null);
- }
-
- // Remark: This has to be handled in the base transport now because we
- // cannot conditionally write to our pipe targets as stream.
- if (!this.level || this.levels[this.level] >= this.levels[info[LEVEL]]) {
- this.transport.log(info[LEVEL], info.message, info, this._nop);
- }
-
- callback(null);
-};
-
-/**
- * Writes the batch of info objects (i.e. "object chunks") to our transport
- * instance after performing any necessary filtering.
- * @param {mixed} chunks - TODO: add params description.
- * @param {function} callback - TODO: add params description.
- * @returns {mixed} - TODO: add returns description.
- * @private
- */
-LegacyTransportStream.prototype._writev = function _writev(chunks, callback) {
- for (var i = 0; i < chunks.length; i++) {
- if (this._accept(chunks[i])) {
- this.transport.log(chunks[i].chunk[LEVEL], chunks[i].chunk.message, chunks[i].chunk, this._nop);
- chunks[i].callback();
- }
- }
-
- return callback(null);
-};
-
-/**
- * Displays a deprecation notice. Defined as a function so it can be
- * overriden in tests.
- * @returns {undefined}
- */
-LegacyTransportStream.prototype._deprecated = function _deprecated() {
- // eslint-disable-next-line no-console
- console.error([this.transport.name + ' is a legacy winston transport. Consider upgrading: ', '- Upgrade docs: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md'].join('\n'));
-};
-
-/**
- * Clean up error handling state on the legacy transport associated
- * with this instance.
- * @returns {undefined}
- */
-LegacyTransportStream.prototype.close = function close() {
- if (this.transport.close) {
- this.transport.close();
- }
-
- if (this.transport.__winstonError) {
- this.transport.removeListener('error', this.transport.__winstonError);
- this.transport.__winstonError = null;
- }
-};
-},{"./":191,"triple-beam":189,"util":82}],193:[function(require,module,exports){
-'use strict';
-
-const util = require('util');
-const { LEVEL } = require('triple-beam');
-const TransportStream = require('./');
-
-/**
- * Constructor function for the LegacyTransportStream. This is an internal
- * wrapper `winston >= 3` uses to wrap older transports implementing
- * log(level, message, meta).
- * @param {Object} options - Options for this TransportStream instance.
- * @param {Transpot} options.transport - winston@2 or older Transport to wrap.
- */
-
-const LegacyTransportStream = module.exports = function LegacyTransportStream(options = {}) {
- TransportStream.call(this, options);
- if (!options.transport || typeof options.transport.log !== 'function') {
- throw new Error('Invalid transport, must be an object with a log method.');
- }
-
- this.transport = options.transport;
- this.level = this.level || options.transport.level;
- this.handleExceptions = this.handleExceptions || options.transport.handleExceptions;
-
- // Display our deprecation notice.
- this._deprecated();
-
- // Properly bubble up errors from the transport to the
- // LegacyTransportStream instance, but only once no matter how many times
- // this transport is shared.
- function transportError(err) {
- this.emit('error', err, this.transport);
- }
-
- if (!this.transport.__winstonError) {
- this.transport.__winstonError = transportError.bind(this);
- this.transport.on('error', this.transport.__winstonError);
- }
-};
-
-/*
- * Inherit from TransportStream using Node.js built-ins
- */
-util.inherits(LegacyTransportStream, TransportStream);
-
-/**
- * Writes the info object to our transport instance.
- * @param {mixed} info - TODO: add param description.
- * @param {mixed} enc - TODO: add param description.
- * @param {function} callback - TODO: add param description.
- * @returns {undefined}
- * @private
- */
-LegacyTransportStream.prototype._write = function _write(info, enc, callback) {
- if (this.silent || (info.exception === true && !this.handleExceptions)) {
- return callback(null);
- }
-
- // Remark: This has to be handled in the base transport now because we
- // cannot conditionally write to our pipe targets as stream.
- if (!this.level || this.levels[this.level] >= this.levels[info[LEVEL]]) {
- this.transport.log(info[LEVEL], info.message, info, this._nop);
- }
-
- callback(null);
-};
-
-/**
- * Writes the batch of info objects (i.e. "object chunks") to our transport
- * instance after performing any necessary filtering.
- * @param {mixed} chunks - TODO: add params description.
- * @param {function} callback - TODO: add params description.
- * @returns {mixed} - TODO: add returns description.
- * @private
- */
-LegacyTransportStream.prototype._writev = function _writev(chunks, callback) {
- for (let i = 0; i < chunks.length; i++) {
- if (this._accept(chunks[i])) {
- this.transport.log(
- chunks[i].chunk[LEVEL],
- chunks[i].chunk.message,
- chunks[i].chunk,
- this._nop
- );
- chunks[i].callback();
- }
- }
-
- return callback(null);
-};
-
-/**
- * Displays a deprecation notice. Defined as a function so it can be
- * overriden in tests.
- * @returns {undefined}
- */
-LegacyTransportStream.prototype._deprecated = function _deprecated() {
- // eslint-disable-next-line no-console
- console.error([
- `${this.transport.name} is a legacy winston transport. Consider upgrading: `,
- '- Upgrade docs: https://github.com/winstonjs/winston/blob/master/UPGRADE-3.0.md'
- ].join('\n'));
-};
-
-/**
- * Clean up error handling state on the legacy transport associated
- * with this instance.
- * @returns {undefined}
- */
-LegacyTransportStream.prototype.close = function close() {
- if (this.transport.close) {
- this.transport.close();
- }
-
- if (this.transport.__winstonError) {
- this.transport.removeListener('error', this.transport.__winstonError);
- this.transport.__winstonError = null;
- }
-};
-
-},{"./":191,"triple-beam":189,"util":82}],194:[function(require,module,exports){
-/**
- * winston.js: Top-level include defining Winston.
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- */
-'use strict';
-
-var logform = require('logform');
-
-var _require = require('./winston/common'),
- warn = _require.warn;
-/**
- * Setup to expose.
- * @type {Object}
- */
-
-
-var winston = exports;
-/**
- * Expose version. Use `require` method for `webpack` support.
- * @type {string}
- */
-
-winston.version = require('../package.json').version;
-/**
- * Include transports defined by default by winston
- * @type {Array}
- */
-
-winston.transports = require('./winston/transports');
-/**
- * Expose utility methods
- * @type {Object}
- */
-
-winston.config = require('./winston/config');
-/**
- * Hoist format-related functionality from logform.
- * @type {Object}
- */
-
-winston.addColors = logform.levels;
-/**
- * Hoist format-related functionality from logform.
- * @type {Object}
- */
-
-winston.format = logform.format;
-/**
- * Expose core Logging-related prototypes.
- * @type {function}
- */
-
-winston.createLogger = require('./winston/create-logger');
-/**
- * Expose core Logging-related prototypes.
- * @type {Object}
- */
-
-winston.ExceptionHandler = require('./winston/exception-handler');
-/**
- * Expose core Logging-related prototypes.
- * @type {Object}
- */
-
-winston.RejectionHandler = require('./winston/rejection-handler');
-/**
- * Expose core Logging-related prototypes.
- * @type {Container}
- */
-
-winston.Container = require('./winston/container');
-/**
- * Expose core Logging-related prototypes.
- * @type {Object}
- */
-
-winston.Transport = require('winston-transport');
-/**
- * We create and expose a default `Container` to `winston.loggers` so that the
- * programmer may manage multiple `winston.Logger` instances without any
- * additional overhead.
- * @example
- * // some-file1.js
- * const logger = require('winston').loggers.get('something');
- *
- * // some-file2.js
- * const logger = require('winston').loggers.get('something');
- */
-
-winston.loggers = new winston.Container();
-/**
- * We create and expose a 'defaultLogger' so that the programmer may do the
- * following without the need to create an instance of winston.Logger directly:
- * @example
- * const winston = require('winston');
- * winston.log('info', 'some message');
- * winston.error('some error');
- */
-
-var defaultLogger = winston.createLogger(); // Pass through the target methods onto `winston.
-
-Object.keys(winston.config.npm.levels).concat(['log', 'query', 'stream', 'add', 'remove', 'clear', 'profile', 'startTimer', 'handleExceptions', 'unhandleExceptions', 'handleRejections', 'unhandleRejections', 'configure', 'child']).forEach(function (method) {
- return winston[method] = function () {
- return defaultLogger[method].apply(defaultLogger, arguments);
- };
-});
-/**
- * Define getter / setter for the default logger level which need to be exposed
- * by winston.
- * @type {string}
- */
-
-Object.defineProperty(winston, 'level', {
- get: function get() {
- return defaultLogger.level;
- },
- set: function set(val) {
- defaultLogger.level = val;
- }
-});
-/**
- * Define getter for `exceptions` which replaces `handleExceptions` and
- * `unhandleExceptions`.
- * @type {Object}
- */
-
-Object.defineProperty(winston, 'exceptions', {
- get: function get() {
- return defaultLogger.exceptions;
- }
-});
-/**
- * Define getters / setters for appropriate properties of the default logger
- * which need to be exposed by winston.
- * @type {Logger}
- */
-
-['exitOnError'].forEach(function (prop) {
- Object.defineProperty(winston, prop, {
- get: function get() {
- return defaultLogger[prop];
- },
- set: function set(val) {
- defaultLogger[prop] = val;
- }
- });
-});
-/**
- * The default transports and exceptionHandlers for the default winston logger.
- * @type {Object}
- */
-
-Object.defineProperty(winston, 'default', {
- get: function get() {
- return {
- exceptionHandlers: defaultLogger.exceptionHandlers,
- rejectionHandlers: defaultLogger.rejectionHandlers,
- transports: defaultLogger.transports
- };
- }
-}); // Have friendlier breakage notices for properties that were exposed by default
-// on winston < 3.0.
-
-warn.deprecated(winston, 'setLevels');
-warn.forFunctions(winston, 'useFormat', ['cli']);
-warn.forProperties(winston, 'useFormat', ['padLevels', 'stripColors']);
-warn.forFunctions(winston, 'deprecated', ['addRewriter', 'addFilter', 'clone', 'extend']);
-warn.forProperties(winston, 'deprecated', ['emitErrs', 'levelLength']); // Throw a useful error when users attempt to run `new winston.Logger`.
-
-warn.moved(winston, 'createLogger', 'Logger');
-},{"../package.json":225,"./winston/common":195,"./winston/config":196,"./winston/container":197,"./winston/create-logger":198,"./winston/exception-handler":199,"./winston/rejection-handler":203,"./winston/transports":208,"logform":145,"winston-transport":191}],195:[function(require,module,exports){
-/**
- * common.js: Internal helper and utility functions for winston.
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- */
-'use strict';
-
-var _require = require('util'),
- format = _require.format;
-/**
- * Set of simple deprecation notices and a way to expose them for a set of
- * properties.
- * @type {Object}
- * @private
- */
-
-
-exports.warn = {
- deprecated: function deprecated(prop) {
- return function () {
- throw new Error(format('{ %s } was removed in winston@3.0.0.', prop));
- };
- },
- useFormat: function useFormat(prop) {
- return function () {
- throw new Error([format('{ %s } was removed in winston@3.0.0.', prop), 'Use a custom winston.format = winston.format(function) instead.'].join('\n'));
- };
- },
- forFunctions: function forFunctions(obj, type, props) {
- props.forEach(function (prop) {
- obj[prop] = exports.warn[type](prop);
- });
- },
- moved: function moved(obj, movedTo, prop) {
- function movedNotice() {
- return function () {
- throw new Error([format('winston.%s was moved in winston@3.0.0.', prop), format('Use a winston.%s instead.', movedTo)].join('\n'));
- };
- }
-
- Object.defineProperty(obj, prop, {
- get: movedNotice,
- set: movedNotice
- });
- },
- forProperties: function forProperties(obj, type, props) {
- props.forEach(function (prop) {
- var notice = exports.warn[type](prop);
- Object.defineProperty(obj, prop, {
- get: notice,
- set: notice
- });
- });
- }
-};
-},{"util":82}],196:[function(require,module,exports){
-/**
- * index.js: Default settings for all levels that winston knows about.
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- */
-'use strict';
-
-var logform = require('logform');
-
-var _require = require('triple-beam'),
- configs = _require.configs;
-/**
- * Export config set for the CLI.
- * @type {Object}
- */
-
-
-exports.cli = logform.levels(configs.cli);
-/**
- * Export config set for npm.
- * @type {Object}
- */
-
-exports.npm = logform.levels(configs.npm);
-/**
- * Export config set for the syslog.
- * @type {Object}
- */
-
-exports.syslog = logform.levels(configs.syslog);
-/**
- * Hoist addColors from logform where it was refactored into in winston@3.
- * @type {Object}
- */
-
-exports.addColors = logform.levels;
-},{"logform":145,"triple-beam":189}],197:[function(require,module,exports){
-/**
- * container.js: Inversion of control container for winston logger instances.
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- */
-'use strict';
-
-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 createLogger = require('./create-logger');
-/**
- * Inversion of control container for winston logger instances.
- * @type {Container}
- */
-
-
-module.exports = /*#__PURE__*/function () {
- /**
- * Constructor function for the Container object responsible for managing a
- * set of `winston.Logger` instances based on string ids.
- * @param {!Object} [options={}] - Default pass-thru options for Loggers.
- */
- function Container() {
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
-
- _classCallCheck(this, Container);
-
- this.loggers = new Map();
- this.options = options;
- }
- /**
- * Retreives a `winston.Logger` instance for the specified `id`. If an
- * instance does not exist, one is created.
- * @param {!string} id - The id of the Logger to get.
- * @param {?Object} [options] - Options for the Logger instance.
- * @returns {Logger} - A configured Logger instance with a specified id.
- */
-
-
- _createClass(Container, [{
- key: "add",
- value: function add(id, options) {
- var _this = this;
-
- if (!this.loggers.has(id)) {
- // Remark: Simple shallow clone for configuration options in case we pass
- // in instantiated protoypal objects
- options = Object.assign({}, options || this.options);
- var existing = options.transports || this.options.transports; // Remark: Make sure if we have an array of transports we slice it to
- // make copies of those references.
-
- options.transports = existing ? existing.slice() : [];
- var logger = createLogger(options);
- logger.on('close', function () {
- return _this._delete(id);
- });
- this.loggers.set(id, logger);
- }
-
- return this.loggers.get(id);
- }
- /**
- * Retreives a `winston.Logger` instance for the specified `id`. If
- * an instance does not exist, one is created.
- * @param {!string} id - The id of the Logger to get.
- * @param {?Object} [options] - Options for the Logger instance.
- * @returns {Logger} - A configured Logger instance with a specified id.
- */
-
- }, {
- key: "get",
- value: function get(id, options) {
- return this.add(id, options);
- }
- /**
- * Check if the container has a logger with the id.
- * @param {?string} id - The id of the Logger instance to find.
- * @returns {boolean} - Boolean value indicating if this instance has a
- * logger with the specified `id`.
- */
-
- }, {
- key: "has",
- value: function has(id) {
- return !!this.loggers.has(id);
- }
- /**
- * Closes a `Logger` instance with the specified `id` if it exists.
- * If no `id` is supplied then all Loggers are closed.
- * @param {?string} id - The id of the Logger instance to close.
- * @returns {undefined}
- */
-
- }, {
- key: "close",
- value: function close(id) {
- var _this2 = this;
-
- if (id) {
- return this._removeLogger(id);
- }
-
- this.loggers.forEach(function (val, key) {
- return _this2._removeLogger(key);
- });
- }
- /**
- * Remove a logger based on the id.
- * @param {!string} id - The id of the logger to remove.
- * @returns {undefined}
- * @private
- */
-
- }, {
- key: "_removeLogger",
- value: function _removeLogger(id) {
- if (!this.loggers.has(id)) {
- return;
- }
-
- var logger = this.loggers.get(id);
- logger.close();
-
- this._delete(id);
- }
- /**
- * Deletes a `Logger` instance with the specified `id`.
- * @param {!string} id - The id of the Logger instance to delete from
- * container.
- * @returns {undefined}
- * @private
- */
-
- }, {
- key: "_delete",
- value: function _delete(id) {
- this.loggers["delete"](id);
- }
- }]);
-
- return Container;
-}();
-},{"./create-logger":198}],198:[function(require,module,exports){
-/**
- * create-logger.js: Logger factory for winston logger instances.
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- */
-'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); }
-
-function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
-
-function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
-
-function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
-
-function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
-
-function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
-
-function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
-
-function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
-
-function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
-
-var _require = require('triple-beam'),
- LEVEL = _require.LEVEL;
-
-var config = require('./config');
-
-var Logger = require('./logger');
-
-var debug = require('@dabh/diagnostics')('winston:create-logger');
+},{}],4:[function(require,module,exports){
+
+/**
+ * Expose `Emitter`.
+ */
+
+if (typeof module !== 'undefined') {
+ module.exports = Emitter;
+}
+
+/**
+ * Initialize a new `Emitter`.
+ *
+ * @api public
+ */
+
+function Emitter(obj) {
+ if (obj) return mixin(obj);
+};
+
+/**
+ * Mixin the emitter properties.
+ *
+ * @param {Object} obj
+ * @return {Object}
+ * @api private
+ */
+
+function mixin(obj) {
+ for (var key in Emitter.prototype) {
+ obj[key] = Emitter.prototype[key];
+ }
+ return obj;
+}
+
+/**
+ * Listen on the given `event` with `fn`.
+ *
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
+ */
+
+Emitter.prototype.on =
+Emitter.prototype.addEventListener = function(event, fn){
+ this._callbacks = this._callbacks || {};
+ (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
+ .push(fn);
+ return this;
+};
+
+/**
+ * Adds an `event` listener that will be invoked a single
+ * time then automatically removed.
+ *
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
+ */
+
+Emitter.prototype.once = function(event, fn){
+ function on() {
+ this.off(event, on);
+ fn.apply(this, arguments);
+ }
+
+ on.fn = fn;
+ this.on(event, on);
+ return this;
+};
+
+/**
+ * Remove the given callback for `event` or all
+ * registered callbacks.
+ *
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
+ */
+
+Emitter.prototype.off =
+Emitter.prototype.removeListener =
+Emitter.prototype.removeAllListeners =
+Emitter.prototype.removeEventListener = function(event, fn){
+ this._callbacks = this._callbacks || {};
+
+ // all
+ if (0 == arguments.length) {
+ this._callbacks = {};
+ return this;
+ }
+
+ // specific event
+ var callbacks = this._callbacks['$' + event];
+ if (!callbacks) return this;
+
+ // remove all handlers
+ if (1 == arguments.length) {
+ delete this._callbacks['$' + event];
+ return this;
+ }
+
+ // remove specific handler
+ var cb;
+ for (var i = 0; i < callbacks.length; i++) {
+ cb = callbacks[i];
+ if (cb === fn || cb.fn === fn) {
+ callbacks.splice(i, 1);
+ break;
+ }
+ }
+
+ // Remove event specific arrays for event types that no
+ // one is subscribed for to avoid memory leak.
+ if (callbacks.length === 0) {
+ delete this._callbacks['$' + event];
+ }
+
+ return this;
+};
+
+/**
+ * Emit `event` with the given args.
+ *
+ * @param {String} event
+ * @param {Mixed} ...
+ * @return {Emitter}
+ */
+
+Emitter.prototype.emit = function(event){
+ this._callbacks = this._callbacks || {};
+
+ var args = new Array(arguments.length - 1)
+ , callbacks = this._callbacks['$' + event];
+
+ for (var i = 1; i < arguments.length; i++) {
+ args[i - 1] = arguments[i];
+ }
+
+ if (callbacks) {
+ callbacks = callbacks.slice(0);
+ for (var i = 0, len = callbacks.length; i < len; ++i) {
+ callbacks[i].apply(this, args);
+ }
+ }
+
+ return this;
+};
+
+/**
+ * Return array of callbacks for `event`.
+ *
+ * @param {String} event
+ * @return {Array}
+ * @api public
+ */
+
+Emitter.prototype.listeners = function(event){
+ this._callbacks = this._callbacks || {};
+ return this._callbacks['$' + event] || [];
+};
+
+/**
+ * Check if this emitter has `event` handlers.
+ *
+ * @param {String} event
+ * @return {Boolean}
+ * @api public
+ */
+
+Emitter.prototype.hasListeners = function(event){
+ return !! this.listeners(event).length;
+};
-function isLevelEnabledFunctionName(level) {
- return 'is' + level.charAt(0).toUpperCase() + level.slice(1) + 'Enabled';
+},{}],5:[function(require,module,exports){
+function Agent() {
+ this._defaults = [];
}
-/**
- * Create a new instance of a winston Logger. Creates a new
- * prototype for each instance.
- * @param {!Object} opts - Options for the created logger.
- * @returns {Logger} - A newly created logger instance.
- */
-
-
-module.exports = function () {
- var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- //
- // Default levels: npm
- //
- opts.levels = opts.levels || config.npm.levels;
- /**
- * DerivedLogger to attach the logs level methods.
- * @type {DerivedLogger}
- * @extends {Logger}
- */
-
- var DerivedLogger = /*#__PURE__*/function (_Logger) {
- _inherits(DerivedLogger, _Logger);
-
- var _super = _createSuper(DerivedLogger);
-
- /**
- * Create a new class derived logger for which the levels can be attached to
- * the prototype of. This is a V8 optimization that is well know to increase
- * performance of prototype functions.
- * @param {!Object} options - Options for the created logger.
- */
- function DerivedLogger(options) {
- _classCallCheck(this, DerivedLogger);
-
- return _super.call(this, options);
- }
-
- return DerivedLogger;
- }(Logger);
-
- var logger = new DerivedLogger(opts); //
- // Create the log level methods for the derived logger.
- //
-
- Object.keys(opts.levels).forEach(function (level) {
- debug('Define prototype method for "%s"', level);
-
- if (level === 'log') {
- // eslint-disable-next-line no-console
- console.warn('Level "log" not defined: conflicts with the method "log". Use a different level name.');
- return;
- } //
- // Define prototype methods for each log level e.g.:
- // logger.log('info', msg) implies these methods are defined:
- // - logger.info(msg)
- // - logger.isInfoEnabled()
- //
- // Remark: to support logger.child this **MUST** be a function
- // so it'll always be called on the instance instead of a fixed
- // place in the prototype chain.
- //
-
-
- DerivedLogger.prototype[level] = function () {
- // Prefer any instance scope, but default to "root" logger
- var self = this || logger; // Optimize the hot-path which is the single object.
-
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
-
- if (args.length === 1) {
- var msg = args[0];
- var info = msg && msg.message && msg || {
- message: msg
- };
- info.level = info[LEVEL] = level;
-
- self._addDefaultMeta(info);
-
- self.write(info);
- return this || logger;
- } // When provided nothing assume the empty string
-
-
- if (args.length === 0) {
- self.log(level, '');
- return self;
- } // Otherwise build argument list which could potentially conform to
- // either:
- // . v3 API: log(obj)
- // 2. v1/v2 API: log(level, msg, ... [string interpolate], [{metadata}], [callback])
-
-
- return self.log.apply(self, [level].concat(args));
- };
-
- DerivedLogger.prototype[isLevelEnabledFunctionName(level)] = function () {
- return (this || logger).isLevelEnabled(level);
- };
- });
- return logger;
-};
-},{"./config":196,"./logger":201,"@dabh/diagnostics":88,"triple-beam":189}],199:[function(require,module,exports){
-(function (process){(function (){
-/**
- * exception-handler.js: Object for handling uncaughtException events.
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- */
-'use strict';
-
-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 os = require('os');
-
-var asyncForEach = require('async/forEach');
-
-var debug = require('@dabh/diagnostics')('winston:exception');
-
-var once = require('one-time');
-
-var stackTrace = require('stack-trace');
-
-var ExceptionStream = require('./exception-stream');
-/**
- * Object for handling uncaughtException events.
- * @type {ExceptionHandler}
- */
-
-
-module.exports = /*#__PURE__*/function () {
- /**
- * TODO: add contructor description
- * @param {!Logger} logger - TODO: add param description
- */
- function ExceptionHandler(logger) {
- _classCallCheck(this, ExceptionHandler);
-
- if (!logger) {
- throw new Error('Logger is required to handle exceptions');
- }
-
- this.logger = logger;
- this.handlers = new Map();
- }
- /**
- * Handles `uncaughtException` events for the current process by adding any
- * handlers passed in.
- * @returns {undefined}
- */
-
-
- _createClass(ExceptionHandler, [{
- key: "handle",
- value: function handle() {
- var _this = this;
-
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
-
- args.forEach(function (arg) {
- if (Array.isArray(arg)) {
- return arg.forEach(function (handler) {
- return _this._addHandler(handler);
- });
- }
-
- _this._addHandler(arg);
- });
-
- if (!this.catcher) {
- this.catcher = this._uncaughtException.bind(this);
- process.on('uncaughtException', this.catcher);
- }
- }
- /**
- * Removes any handlers to `uncaughtException` events for the current
- * process. This does not modify the state of the `this.handlers` set.
- * @returns {undefined}
- */
-
- }, {
- key: "unhandle",
- value: function unhandle() {
- var _this2 = this;
-
- if (this.catcher) {
- process.removeListener('uncaughtException', this.catcher);
- this.catcher = false;
- Array.from(this.handlers.values()).forEach(function (wrapper) {
- return _this2.logger.unpipe(wrapper);
- });
- }
- }
- /**
- * TODO: add method description
- * @param {Error} err - Error to get information about.
- * @returns {mixed} - TODO: add return description.
- */
-
- }, {
- key: "getAllInfo",
- value: function getAllInfo(err) {
- var message = err.message;
-
- if (!message && typeof err === 'string') {
- message = err;
- }
-
- return {
- error: err,
- // TODO (indexzero): how do we configure this?
- level: 'error',
- message: ["uncaughtException: ".concat(message || '(no error message)'), err.stack || ' No stack trace'].join('\n'),
- stack: err.stack,
- exception: true,
- date: new Date().toString(),
- process: this.getProcessInfo(),
- os: this.getOsInfo(),
- trace: this.getTrace(err)
- };
- }
- /**
- * Gets all relevant process information for the currently running process.
- * @returns {mixed} - TODO: add return description.
- */
-
- }, {
- key: "getProcessInfo",
- value: function getProcessInfo() {
- return {
- pid: process.pid,
- uid: process.getuid ? process.getuid() : null,
- gid: process.getgid ? process.getgid() : null,
- cwd: process.cwd(),
- execPath: process.execPath,
- version: process.version,
- argv: process.argv,
- memoryUsage: process.memoryUsage()
- };
- }
- /**
- * Gets all relevant OS information for the currently running process.
- * @returns {mixed} - TODO: add return description.
- */
-
- }, {
- key: "getOsInfo",
- value: function getOsInfo() {
- return {
- loadavg: os.loadavg(),
- uptime: os.uptime()
- };
- }
- /**
- * Gets a stack trace for the specified error.
- * @param {mixed} err - TODO: add param description.
- * @returns {mixed} - TODO: add return description.
- */
-
- }, {
- key: "getTrace",
- value: function getTrace(err) {
- var trace = err ? stackTrace.parse(err) : stackTrace.get();
- return trace.map(function (site) {
- return {
- column: site.getColumnNumber(),
- file: site.getFileName(),
- "function": site.getFunctionName(),
- line: site.getLineNumber(),
- method: site.getMethodName(),
- "native": site.isNative()
- };
- });
- }
- /**
- * Helper method to add a transport as an exception handler.
- * @param {Transport} handler - The transport to add as an exception handler.
- * @returns {void}
- */
-
- }, {
- key: "_addHandler",
- value: function _addHandler(handler) {
- if (!this.handlers.has(handler)) {
- handler.handleExceptions = true;
- var wrapper = new ExceptionStream(handler);
- this.handlers.set(handler, wrapper);
- this.logger.pipe(wrapper);
- }
- }
- /**
- * Logs all relevant information around the `err` and exits the current
- * process.
- * @param {Error} err - Error to handle
- * @returns {mixed} - TODO: add return description.
- * @private
- */
-
- }, {
- key: "_uncaughtException",
- value: function _uncaughtException(err) {
- var info = this.getAllInfo(err);
-
- var handlers = this._getExceptionHandlers(); // Calculate if we should exit on this error
-
-
- var doExit = typeof this.logger.exitOnError === 'function' ? this.logger.exitOnError(err) : this.logger.exitOnError;
- var timeout;
-
- if (!handlers.length && doExit) {
- // eslint-disable-next-line no-console
- console.warn('winston: exitOnError cannot be true with no exception handlers.'); // eslint-disable-next-line no-console
-
- console.warn('winston: not exiting process.');
- doExit = false;
- }
-
- function gracefulExit() {
- debug('doExit', doExit);
- debug('process._exiting', process._exiting);
-
- if (doExit && !process._exiting) {
- // Remark: Currently ignoring any exceptions from transports when
- // catching uncaught exceptions.
- if (timeout) {
- clearTimeout(timeout);
- } // eslint-disable-next-line no-process-exit
-
-
- process.exit(1);
- }
- }
-
- if (!handlers || handlers.length === 0) {
- return process.nextTick(gracefulExit);
- } // Log to all transports attempting to listen for when they are completed.
-
-
- asyncForEach(handlers, function (handler, next) {
- var done = once(next);
- var transport = handler.transport || handler; // Debug wrapping so that we can inspect what's going on under the covers.
-
- function onDone(event) {
- return function () {
- debug(event);
- done();
- };
- }
-
- transport._ending = true;
- transport.once('finish', onDone('finished'));
- transport.once('error', onDone('error'));
- }, function () {
- return doExit && gracefulExit();
- });
- this.logger.log(info); // If exitOnError is true, then only allow the logging of exceptions to
- // take up to `3000ms`.
-
- if (doExit) {
- timeout = setTimeout(gracefulExit, 3000);
- }
- }
- /**
- * Returns the list of transports and exceptionHandlers for this instance.
- * @returns {Array} - List of transports and exceptionHandlers for this
- * instance.
- * @private
- */
-
- }, {
- key: "_getExceptionHandlers",
- value: function _getExceptionHandlers() {
- // Remark (indexzero): since `logger.transports` returns all of the pipes
- // from the _readableState of the stream we actually get the join of the
- // explicit handlers and the implicit transports with
- // `handleExceptions: true`
- return this.logger.transports.filter(function (wrap) {
- var transport = wrap.transport || wrap;
- return transport.handleExceptions;
- });
- }
- }]);
-
- return ExceptionHandler;
-}();
-}).call(this)}).call(this,require('_process'))
-},{"./exception-stream":200,"@dabh/diagnostics":88,"_process":34,"async/forEach":97,"one-time":165,"os":20,"stack-trace":176}],200:[function(require,module,exports){
-/**
- * exception-stream.js: TODO: add file header handler.
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- */
-'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); }
-
-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; }
-
-function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
-
-function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
-function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
-
-function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
-
-function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
-
-function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
-
-function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
-
-var _require = require('readable-stream'),
- Writable = _require.Writable;
-/**
- * TODO: add class description.
- * @type {ExceptionStream}
- * @extends {Writable}
- */
-
-
-module.exports = /*#__PURE__*/function (_Writable) {
- _inherits(ExceptionStream, _Writable);
-
- var _super = _createSuper(ExceptionStream);
-
- /**
- * Constructor function for the ExceptionStream responsible for wrapping a
- * TransportStream; only allowing writes of `info` objects with
- * `info.exception` set to true.
- * @param {!TransportStream} transport - Stream to filter to exceptions
- */
- function ExceptionStream(transport) {
- var _this;
-
- _classCallCheck(this, ExceptionStream);
-
- _this = _super.call(this, {
- objectMode: true
- });
-
- if (!transport) {
- throw new Error('ExceptionStream requires a TransportStream instance.');
- } // Remark (indexzero): we set `handleExceptions` here because it's the
- // predicate checked in ExceptionHandler.prototype.__getExceptionHandlers
-
-
- _this.handleExceptions = true;
- _this.transport = transport;
- return _this;
- }
- /**
- * Writes the info object to our transport instance if (and only if) the
- * `exception` property is set on the info.
- * @param {mixed} info - TODO: add param description.
- * @param {mixed} enc - TODO: add param description.
- * @param {mixed} callback - TODO: add param description.
- * @returns {mixed} - TODO: add return description.
- * @private
- */
-
-
- _createClass(ExceptionStream, [{
- key: "_write",
- value: function _write(info, enc, callback) {
- if (info.exception) {
- return this.transport.log(info, callback);
- }
-
- callback();
- return true;
- }
- }]);
-
- return ExceptionStream;
-}(Writable);
-},{"readable-stream":224}],201:[function(require,module,exports){
-(function (setImmediate){(function (){
-/**
- * logger.js: TODO: add file header description.
- *
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- */
-'use strict';
-
-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 _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 _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; }
-
-function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
-
-function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
-
-function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
-
-function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
-
-function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
-
-function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
-
-function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
-
-var _require = require('readable-stream'),
- Stream = _require.Stream,
- Transform = _require.Transform;
-
-var asyncForEach = require('async/forEach');
-
-var _require2 = require('triple-beam'),
- LEVEL = _require2.LEVEL,
- SPLAT = _require2.SPLAT;
-
-var isStream = require('is-stream');
-
-var ExceptionHandler = require('./exception-handler');
-
-var RejectionHandler = require('./rejection-handler');
-
-var LegacyTransportStream = require('winston-transport/legacy');
-
-var Profiler = require('./profiler');
-
-var _require3 = require('./common'),
- warn = _require3.warn;
-
-var config = require('./config');
-/**
- * Captures the number of format (i.e. %s strings) in a given string.
- * Based on `util.format`, see Node.js source:
- * https://github.com/nodejs/node/blob/b1c8f15c5f169e021f7c46eb7b219de95fe97603/lib/util.js#L201-L230
- * @type {RegExp}
- */
-
-
-var formatRegExp = /%[scdjifoO%]/g;
-/**
- * TODO: add class description.
- * @type {Logger}
- * @extends {Transform}
- */
-
-var Logger = /*#__PURE__*/function (_Transform) {
- _inherits(Logger, _Transform);
-
- var _super = _createSuper(Logger);
-
- /**
- * Constructor function for the Logger object responsible for persisting log
- * messages and metadata to one or more transports.
- * @param {!Object} options - foo
- */
- function Logger(options) {
- var _this;
-
- _classCallCheck(this, Logger);
-
- _this = _super.call(this, {
- objectMode: true
- });
-
- _this.configure(options);
-
- return _this;
- }
-
- _createClass(Logger, [{
- key: "child",
- value: function child(defaultRequestMetadata) {
- var logger = this;
- return Object.create(logger, {
- write: {
- value: function value(info) {
- var infoClone = Object.assign({}, defaultRequestMetadata, info); // Object.assign doesn't copy inherited Error
- // properties so we have to do that explicitly
- //
- // Remark (indexzero): we should remove this
- // since the errors format will handle this case.
- //
-
- if (info instanceof Error) {
- infoClone.stack = info.stack;
- infoClone.message = info.message;
- }
-
- logger.write(infoClone);
- }
- }
- });
- }
- /**
- * This will wholesale reconfigure this instance by:
- * 1. Resetting all transports. Older transports will be removed implicitly.
- * 2. Set all other options including levels, colors, rewriters, filters,
- * exceptionHandlers, etc.
- * @param {!Object} options - TODO: add param description.
- * @returns {undefined}
- */
-
- }, {
- key: "configure",
- value: function configure() {
- var _this2 = this;
-
- var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
- silent = _ref.silent,
- format = _ref.format,
- defaultMeta = _ref.defaultMeta,
- levels = _ref.levels,
- _ref$level = _ref.level,
- level = _ref$level === void 0 ? 'info' : _ref$level,
- _ref$exitOnError = _ref.exitOnError,
- exitOnError = _ref$exitOnError === void 0 ? true : _ref$exitOnError,
- transports = _ref.transports,
- colors = _ref.colors,
- emitErrs = _ref.emitErrs,
- formatters = _ref.formatters,
- padLevels = _ref.padLevels,
- rewriters = _ref.rewriters,
- stripColors = _ref.stripColors,
- exceptionHandlers = _ref.exceptionHandlers,
- rejectionHandlers = _ref.rejectionHandlers;
-
- // Reset transports if we already have them
- if (this.transports.length) {
- this.clear();
- }
-
- this.silent = silent;
- this.format = format || this.format || require('logform/json')();
- this.defaultMeta = defaultMeta || null; // Hoist other options onto this instance.
-
- this.levels = levels || this.levels || config.npm.levels;
- this.level = level;
- this.exceptions = new ExceptionHandler(this);
- this.rejections = new RejectionHandler(this);
- this.profilers = {};
- this.exitOnError = exitOnError; // Add all transports we have been provided.
-
- if (transports) {
- transports = Array.isArray(transports) ? transports : [transports];
- transports.forEach(function (transport) {
- return _this2.add(transport);
- });
- }
-
- if (colors || emitErrs || formatters || padLevels || rewriters || stripColors) {
- throw new Error(['{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.', 'Use a custom winston.format(function) instead.', 'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md'].join('\n'));
- }
-
- if (exceptionHandlers) {
- this.exceptions.handle(exceptionHandlers);
- }
-
- if (rejectionHandlers) {
- this.rejections.handle(rejectionHandlers);
- }
- }
- }, {
- key: "isLevelEnabled",
- value: function isLevelEnabled(level) {
- var _this3 = this;
-
- var givenLevelValue = getLevelValue(this.levels, level);
-
- if (givenLevelValue === null) {
- return false;
- }
-
- var configuredLevelValue = getLevelValue(this.levels, this.level);
-
- if (configuredLevelValue === null) {
- return false;
- }
-
- if (!this.transports || this.transports.length === 0) {
- return configuredLevelValue >= givenLevelValue;
- }
-
- var index = this.transports.findIndex(function (transport) {
- var transportLevelValue = getLevelValue(_this3.levels, transport.level);
-
- if (transportLevelValue === null) {
- transportLevelValue = configuredLevelValue;
- }
-
- return transportLevelValue >= givenLevelValue;
- });
- return index !== -1;
- }
- /* eslint-disable valid-jsdoc */
-
- /**
- * Ensure backwards compatibility with a `log` method
- * @param {mixed} level - Level the log message is written at.
- * @param {mixed} msg - TODO: add param description.
- * @param {mixed} meta - TODO: add param description.
- * @returns {Logger} - TODO: add return description.
- *
- * @example
- * // Supports the existing API:
- * logger.log('info', 'Hello world', { custom: true });
- * logger.log('info', new Error('Yo, it\'s on fire'));
- *
- * // Requires winston.format.splat()
- * logger.log('info', '%s %d%%', 'A string', 50, { thisIsMeta: true });
- *
- * // And the new API with a single JSON literal:
- * logger.log({ level: 'info', message: 'Hello world', custom: true });
- * logger.log({ level: 'info', message: new Error('Yo, it\'s on fire') });
- *
- * // Also requires winston.format.splat()
- * logger.log({
- * level: 'info',
- * message: '%s %d%%',
- * [SPLAT]: ['A string', 50],
- * meta: { thisIsMeta: true }
- * });
- *
- */
-
- /* eslint-enable valid-jsdoc */
-
- }, {
- key: "log",
- value: function log(level, msg) {
- var _Object$assign2;
-
- for (var _len = arguments.length, splat = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
- splat[_key - 2] = arguments[_key];
- }
-
- // eslint-disable-line max-params
- // Optimize for the hotpath of logging JSON literals
- if (arguments.length === 1) {
- // Yo dawg, I heard you like levels ... seriously ...
- // In this context the LHS `level` here is actually the `info` so read
- // this as: info[LEVEL] = info.level;
- level[LEVEL] = level.level;
-
- this._addDefaultMeta(level);
-
- this.write(level);
- return this;
- } // Slightly less hotpath, but worth optimizing for.
-
-
- if (arguments.length === 2) {
- var _this$write;
-
- if (msg && _typeof(msg) === 'object') {
- msg[LEVEL] = msg.level = level;
-
- this._addDefaultMeta(msg);
-
- this.write(msg);
- return this;
- }
-
- this.write((_this$write = {}, _defineProperty(_this$write, LEVEL, level), _defineProperty(_this$write, "level", level), _defineProperty(_this$write, "message", msg), _this$write));
- return this;
- }
-
- var meta = splat[0];
-
- if (_typeof(meta) === 'object' && meta !== null) {
- // Extract tokens, if none available default to empty array to
- // ensure consistancy in expected results
- var tokens = msg && msg.match && msg.match(formatRegExp);
-
- if (!tokens) {
- var _Object$assign;
-
- var info = Object.assign({}, this.defaultMeta, meta, (_Object$assign = {}, _defineProperty(_Object$assign, LEVEL, level), _defineProperty(_Object$assign, SPLAT, splat), _defineProperty(_Object$assign, "level", level), _defineProperty(_Object$assign, "message", msg), _Object$assign));
- if (meta.message) info.message = "".concat(info.message, " ").concat(meta.message);
- if (meta.stack) info.stack = meta.stack;
- this.write(info);
- return this;
- }
- }
-
- this.write(Object.assign({}, this.defaultMeta, (_Object$assign2 = {}, _defineProperty(_Object$assign2, LEVEL, level), _defineProperty(_Object$assign2, SPLAT, splat), _defineProperty(_Object$assign2, "level", level), _defineProperty(_Object$assign2, "message", msg), _Object$assign2)));
- return this;
- }
- /**
- * Pushes data so that it can be picked up by all of our pipe targets.
- * @param {mixed} info - TODO: add param description.
- * @param {mixed} enc - TODO: add param description.
- * @param {mixed} callback - Continues stream processing.
- * @returns {undefined}
- * @private
- */
-
- }, {
- key: "_transform",
- value: function _transform(info, enc, callback) {
- if (this.silent) {
- return callback();
- } // [LEVEL] is only soft guaranteed to be set here since we are a proper
- // stream. It is likely that `info` came in through `.log(info)` or
- // `.info(info)`. If it is not defined, however, define it.
- // This LEVEL symbol is provided by `triple-beam` and also used in:
- // - logform
- // - winston-transport
- // - abstract-winston-transport
-
-
- if (!info[LEVEL]) {
- info[LEVEL] = info.level;
- } // Remark: really not sure what to do here, but this has been reported as
- // very confusing by pre winston@2.0.0 users as quite confusing when using
- // custom levels.
-
-
- if (!this.levels[info[LEVEL]] && this.levels[info[LEVEL]] !== 0) {
- // eslint-disable-next-line no-console
- console.error('[winston] Unknown logger level: %s', info[LEVEL]);
- } // Remark: not sure if we should simply error here.
-
-
- if (!this._readableState.pipes) {
- // eslint-disable-next-line no-console
- console.error('[winston] Attempt to write logs with no transports %j', info);
- } // Here we write to the `format` pipe-chain, which on `readable` above will
- // push the formatted `info` Object onto the buffer for this instance. We trap
- // (and re-throw) any errors generated by the user-provided format, but also
- // guarantee that the streams callback is invoked so that we can continue flowing.
-
-
- try {
- this.push(this.format.transform(info, this.format.options));
- } catch (ex) {
- throw ex;
- } finally {
- // eslint-disable-next-line callback-return
- callback();
- }
- }
- /**
- * Delays the 'finish' event until all transport pipe targets have
- * also emitted 'finish' or are already finished.
- * @param {mixed} callback - Continues stream processing.
- */
-
- }, {
- key: "_final",
- value: function _final(callback) {
- var transports = this.transports.slice();
- asyncForEach(transports, function (transport, next) {
- if (!transport || transport.finished) return setImmediate(next);
- transport.once('finish', next);
- transport.end();
- }, callback);
- }
- /**
- * Adds the transport to this logger instance by piping to it.
- * @param {mixed} transport - TODO: add param description.
- * @returns {Logger} - TODO: add return description.
- */
-
- }, {
- key: "add",
- value: function add(transport) {
- // Support backwards compatibility with all existing `winston < 3.x.x`
- // transports which meet one of two criteria:
- // 1. They inherit from winston.Transport in < 3.x.x which is NOT a stream.
- // 2. They expose a log method which has a length greater than 2 (i.e. more then
- // just `log(info, callback)`.
- var target = !isStream(transport) || transport.log.length > 2 ? new LegacyTransportStream({
- transport: transport
- }) : transport;
-
- if (!target._writableState || !target._writableState.objectMode) {
- throw new Error('Transports must WritableStreams in objectMode. Set { objectMode: true }.');
- } // Listen for the `error` event and the `warn` event on the new Transport.
-
-
- this._onEvent('error', target);
+["use", "on", "once", "set", "query", "type", "accept", "auth", "withCredentials", "sortQuery", "retry", "ok", "redirects",
+ "timeout", "buffer", "serialize", "parse", "ca", "key", "pfx", "cert"].forEach(function(fn) {
+ /** Default setting for all requests from this agent */
+ Agent.prototype[fn] = function(/*varargs*/) {
+ this._defaults.push({fn:fn, arguments:arguments});
+ return this;
+ }
+});
- this._onEvent('warn', target);
+Agent.prototype._setDefaults = function(req) {
+ this._defaults.forEach(function(def) {
+ req[def.fn].apply(req, def.arguments);
+ });
+};
- this.pipe(target);
+module.exports = Agent;
- if (transport.handleExceptions) {
- this.exceptions.handle();
- }
+},{}],6:[function(require,module,exports){
+/**
+ * Root reference for iframes.
+ */
- if (transport.handleRejections) {
- this.rejections.handle();
- }
+var root;
+if (typeof window !== 'undefined') { // Browser window
+ root = window;
+} else if (typeof self !== 'undefined') { // Web Worker
+ root = self;
+} else { // Other environments
+ console.warn("Using browser-only version of superagent in non-browser environment");
+ root = this;
+}
- return this;
- }
- /**
- * Removes the transport from this logger instance by unpiping from it.
- * @param {mixed} transport - TODO: add param description.
- * @returns {Logger} - TODO: add return description.
- */
-
- }, {
- key: "remove",
- value: function remove(transport) {
- if (!transport) return this;
- var target = transport;
-
- if (!isStream(transport) || transport.log.length > 2) {
- target = this.transports.filter(function (match) {
- return match.transport === transport;
- })[0];
- }
+var Emitter = require('component-emitter');
+var RequestBase = require('./request-base');
+var isObject = require('./is-object');
+var ResponseBase = require('./response-base');
+var Agent = require('./agent-base');
- if (target) {
- this.unpipe(target);
- }
+/**
+ * Noop.
+ */
- return this;
- }
- /**
- * Removes all transports from this logger instance.
- * @returns {Logger} - TODO: add return description.
- */
-
- }, {
- key: "clear",
- value: function clear() {
- this.unpipe();
- return this;
- }
- /**
- * Cleans up resources (streams, event listeners) for all transports
- * associated with this instance (if necessary).
- * @returns {Logger} - TODO: add return description.
- */
-
- }, {
- key: "close",
- value: function close() {
- this.clear();
- this.emit('close');
- return this;
- }
- /**
- * Sets the `target` levels specified on this instance.
- * @param {Object} Target levels to use on this instance.
- */
-
- }, {
- key: "setLevels",
- value: function setLevels() {
- warn.deprecated('setLevels');
- }
- /**
- * Queries the all transports for this instance with the specified `options`.
- * This will aggregate each transport's results into one object containing
- * a property per transport.
- * @param {Object} options - Query options for this instance.
- * @param {function} callback - Continuation to respond to when complete.
- */
-
- }, {
- key: "query",
- value: function query(options, callback) {
- if (typeof options === 'function') {
- callback = options;
- options = {};
- }
+function noop(){};
- options = options || {};
- var results = {};
- var queryObject = Object.assign({}, options.query || {}); // Helper function to query a single transport
+/**
+ * Expose `request`.
+ */
- function queryTransport(transport, next) {
- if (options.query && typeof transport.formatQuery === 'function') {
- options.query = transport.formatQuery(queryObject);
- }
+var request = exports = module.exports = function(method, url) {
+ // callback
+ if ('function' == typeof url) {
+ return new exports.Request('GET', method).end(url);
+ }
- transport.query(options, function (err, res) {
- if (err) {
- return next(err);
- }
+ // url first
+ if (1 == arguments.length) {
+ return new exports.Request('GET', method);
+ }
- if (typeof transport.formatResults === 'function') {
- res = transport.formatResults(res, options.format);
- }
+ return new exports.Request(method, url);
+}
- next(null, res);
- });
- } // Helper function to accumulate the results from `queryTransport` into
- // the `results`.
+exports.Request = Request;
+/**
+ * Determine XHR.
+ */
- function addResults(transport, next) {
- queryTransport(transport, function (err, result) {
- // queryTransport could potentially invoke the callback multiple times
- // since Transport code can be unpredictable.
- if (next) {
- result = err || result;
+request.getXHR = function () {
+ if (root.XMLHttpRequest
+ && (!root.location || 'file:' != root.location.protocol
+ || !root.ActiveXObject)) {
+ return new XMLHttpRequest;
+ } else {
+ try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}
+ try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
+ try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
+ try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}
+ }
+ throw Error("Browser-only version of superagent could not find XHR");
+};
- if (result) {
- results[transport.name] = result;
- } // eslint-disable-next-line callback-return
+/**
+ * Removes leading and trailing whitespace, added to support IE.
+ *
+ * @param {String} s
+ * @return {String}
+ * @api private
+ */
+var trim = ''.trim
+ ? function(s) { return s.trim(); }
+ : function(s) { return s.replace(/(^\s*|\s*$)/g, ''); };
- next();
- }
+/**
+ * Serialize the given `obj`.
+ *
+ * @param {Object} obj
+ * @return {String}
+ * @api private
+ */
- next = null;
- });
- } // Iterate over the transports in parallel setting the appropriate key in
- // the `results`.
+function serialize(obj) {
+ if (!isObject(obj)) return obj;
+ var pairs = [];
+ for (var key in obj) {
+ pushEncodedKeyValuePair(pairs, key, obj[key]);
+ }
+ return pairs.join('&');
+}
+/**
+ * Helps 'serialize' with serializing arrays.
+ * Mutates the pairs array.
+ *
+ * @param {Array} pairs
+ * @param {String} key
+ * @param {Mixed} val
+ */
- asyncForEach(this.transports.filter(function (transport) {
- return !!transport.query;
- }), addResults, function () {
- return callback(null, results);
+function pushEncodedKeyValuePair(pairs, key, val) {
+ if (val != null) {
+ if (Array.isArray(val)) {
+ val.forEach(function(v) {
+ pushEncodedKeyValuePair(pairs, key, v);
});
+ } else if (isObject(val)) {
+ for(var subkey in val) {
+ pushEncodedKeyValuePair(pairs, key + '[' + subkey + ']', val[subkey]);
+ }
+ } else {
+ pairs.push(encodeURIComponent(key)
+ + '=' + encodeURIComponent(val));
}
- /**
- * Returns a log stream for all transports. Options object is optional.
- * @param{Object} options={} - Stream options for this instance.
- * @returns {Stream} - TODO: add return description.
- */
-
- }, {
- key: "stream",
- value: function stream() {
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- var out = new Stream();
- var streams = [];
- out._streams = streams;
-
- out.destroy = function () {
- var i = streams.length;
-
- while (i--) {
- streams[i].destroy();
- }
- }; // Create a list of all transports for this instance.
+ } else if (val === null) {
+ pairs.push(encodeURIComponent(key));
+ }
+}
+
+/**
+ * Expose serialization method.
+ */
+request.serializeObject = serialize;
- this.transports.filter(function (transport) {
- return !!transport.stream;
- }).forEach(function (transport) {
- var str = transport.stream(options);
+/**
+ * Parse the given x-www-form-urlencoded `str`.
+ *
+ * @param {String} str
+ * @return {Object}
+ * @api private
+ */
- if (!str) {
- return;
- }
+function parseString(str) {
+ var obj = {};
+ var pairs = str.split('&');
+ var pair;
+ var pos;
- streams.push(str);
- str.on('log', function (log) {
- log.transport = log.transport || [];
- log.transport.push(transport.name);
- out.emit('log', log);
- });
- str.on('error', function (err) {
- err.transport = err.transport || [];
- err.transport.push(transport.name);
- out.emit('error', err);
- });
- });
- return out;
- }
- /**
- * Returns an object corresponding to a specific timing. When done is called
- * the timer will finish and log the duration. e.g.:
- * @returns {Profile} - TODO: add return description.
- * @example
- * const timer = winston.startTimer()
- * setTimeout(() => {
- * timer.done({
- * message: 'Logging message'
- * });
- * }, 1000);
- */
-
- }, {
- key: "startTimer",
- value: function startTimer() {
- return new Profiler(this);
+ for (var i = 0, len = pairs.length; i < len; ++i) {
+ pair = pairs[i];
+ pos = pair.indexOf('=');
+ if (pos == -1) {
+ obj[decodeURIComponent(pair)] = '';
+ } else {
+ obj[decodeURIComponent(pair.slice(0, pos))] =
+ decodeURIComponent(pair.slice(pos + 1));
}
- /**
- * Tracks the time inbetween subsequent calls to this method with the same
- * `id` parameter. The second call to this method will log the difference in
- * milliseconds along with the message.
- * @param {string} id Unique id of the profiler
- * @returns {Logger} - TODO: add return description.
- */
-
- }, {
- key: "profile",
- value: function profile(id) {
- var time = Date.now();
-
- if (this.profilers[id]) {
- var timeEnd = this.profilers[id];
- delete this.profilers[id]; // Attempt to be kind to users if they are still using older APIs.
-
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
- args[_key2 - 1] = arguments[_key2];
- }
+ }
- if (typeof args[args.length - 2] === 'function') {
- // eslint-disable-next-line no-console
- console.warn('Callback function no longer supported as of winston@3.0.0');
- args.pop();
- } // Set the duration property of the metadata
+ return obj;
+}
+
+/**
+ * Expose parser.
+ */
+request.parseString = parseString;
- var info = _typeof(args[args.length - 1]) === 'object' ? args.pop() : {};
- info.level = info.level || 'info';
- info.durationMs = time - timeEnd;
- info.message = info.message || id;
- return this.write(info);
- }
+/**
+ * Default MIME type map.
+ *
+ * superagent.types.xml = 'application/xml';
+ *
+ */
- this.profilers[id] = time;
- return this;
- }
- /**
- * Backwards compatibility to `exceptions.handle` in winston < 3.0.0.
- * @returns {undefined}
- * @deprecated
- */
+request.types = {
+ html: 'text/html',
+ json: 'application/json',
+ xml: 'text/xml',
+ urlencoded: 'application/x-www-form-urlencoded',
+ 'form': 'application/x-www-form-urlencoded',
+ 'form-data': 'application/x-www-form-urlencoded'
+};
- }, {
- key: "handleExceptions",
- value: function handleExceptions() {
- var _this$exceptions;
+/**
+ * Default serialization map.
+ *
+ * superagent.serialize['application/xml'] = function(obj){
+ * return 'generated xml here';
+ * };
+ *
+ */
- // eslint-disable-next-line no-console
- console.warn('Deprecated: .handleExceptions() will be removed in winston@4. Use .exceptions.handle()');
+request.serialize = {
+ 'application/x-www-form-urlencoded': serialize,
+ 'application/json': JSON.stringify
+};
- (_this$exceptions = this.exceptions).handle.apply(_this$exceptions, arguments);
- }
- /**
- * Backwards compatibility to `exceptions.handle` in winston < 3.0.0.
- * @returns {undefined}
- * @deprecated
- */
+/**
+ * Default parsers.
+ *
+ * superagent.parse['application/xml'] = function(str){
+ * return { object parsed from str };
+ * };
+ *
+ */
- }, {
- key: "unhandleExceptions",
- value: function unhandleExceptions() {
- var _this$exceptions2;
+request.parse = {
+ 'application/x-www-form-urlencoded': parseString,
+ 'application/json': JSON.parse
+};
+
+/**
+ * Parse the given header `str` into
+ * an object containing the mapped fields.
+ *
+ * @param {String} str
+ * @return {Object}
+ * @api private
+ */
- // eslint-disable-next-line no-console
- console.warn('Deprecated: .unhandleExceptions() will be removed in winston@4. Use .exceptions.unhandle()');
+function parseHeader(str) {
+ var lines = str.split(/\r?\n/);
+ var fields = {};
+ var index;
+ var line;
+ var field;
+ var val;
- (_this$exceptions2 = this.exceptions).unhandle.apply(_this$exceptions2, arguments);
- }
- /**
- * Throw a more meaningful deprecation notice
- * @throws {Error} - TODO: add throws description.
- */
-
- }, {
- key: "cli",
- value: function cli() {
- throw new Error(['Logger.cli() was removed in winston@3.0.0', 'Use a custom winston.formats.cli() instead.', 'See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md'].join('\n'));
+ for (var i = 0, len = lines.length; i < len; ++i) {
+ line = lines[i];
+ index = line.indexOf(':');
+ if (index === -1) { // could be empty line, just skip it
+ continue;
}
- /**
- * Bubbles the `event` that occured on the specified `transport` up
- * from this instance.
- * @param {string} event - The event that occured
- * @param {Object} transport - Transport on which the event occured
- * @private
- */
-
- }, {
- key: "_onEvent",
- value: function _onEvent(event, transport) {
- function transportEvent(err) {
- // https://github.com/winstonjs/winston/issues/1364
- if (event === 'error' && !this.transports.includes(transport)) {
- this.add(transport);
- }
+ field = line.slice(0, index).toLowerCase();
+ val = trim(line.slice(index + 1));
+ fields[field] = val;
+ }
- this.emit(event, err, transport);
- }
+ return fields;
+}
- if (!transport['__winston' + event]) {
- transport['__winston' + event] = transportEvent.bind(this);
- transport.on(event, transport['__winston' + event]);
- }
- }
- }, {
- key: "_addDefaultMeta",
- value: function _addDefaultMeta(msg) {
- if (this.defaultMeta) {
- Object.assign(msg, this.defaultMeta);
- }
- }
- }]);
+/**
+ * Check if `mime` is json or has +json structured syntax suffix.
+ *
+ * @param {String} mime
+ * @return {Boolean}
+ * @api private
+ */
- return Logger;
-}(Transform);
+function isJSON(mime) {
+ // should match /json or +json
+ // but not /json-seq
+ return /[\/+]json($|[^-\w])/.test(mime);
+}
-function getLevelValue(levels, level) {
- var value = levels[level];
+/**
+ * Initialize a new `Response` with the given `xhr`.
+ *
+ * - set flags (.ok, .error, etc)
+ * - parse header
+ *
+ * Examples:
+ *
+ * Aliasing `superagent` as `request` is nice:
+ *
+ * request = superagent;
+ *
+ * We can use the promise-like API, or pass callbacks:
+ *
+ * request.get('/').end(function(res){});
+ * request.get('/', function(res){});
+ *
+ * Sending data can be chained:
+ *
+ * request
+ * .post('/user')
+ * .send({ name: 'tj' })
+ * .end(function(res){});
+ *
+ * Or passed to `.send()`:
+ *
+ * request
+ * .post('/user')
+ * .send({ name: 'tj' }, function(res){});
+ *
+ * Or passed to `.post()`:
+ *
+ * request
+ * .post('/user', { name: 'tj' })
+ * .end(function(res){});
+ *
+ * Or further reduced to a single call for simple cases:
+ *
+ * request
+ * .post('/user', { name: 'tj' }, function(res){});
+ *
+ * @param {XMLHTTPRequest} xhr
+ * @param {Object} options
+ * @api private
+ */
- if (!value && value !== 0) {
- return null;
+function Response(req) {
+ this.req = req;
+ this.xhr = this.req.xhr;
+ // responseText is accessible only if responseType is '' or 'text' and on older browsers
+ this.text = ((this.req.method !='HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text')) || typeof this.xhr.responseType === 'undefined')
+ ? this.xhr.responseText
+ : null;
+ this.statusText = this.req.xhr.statusText;
+ var status = this.xhr.status;
+ // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
+ if (status === 1223) {
+ status = 204;
}
+ this._setStatusProperties(status);
+ this.header = this.headers = parseHeader(this.xhr.getAllResponseHeaders());
+ // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but
+ // getResponseHeader still works. so we get content-type even if getting
+ // other headers fails.
+ this.header['content-type'] = this.xhr.getResponseHeader('content-type');
+ this._setHeaderProperties(this.header);
- return value;
+ if (null === this.text && req._responseType) {
+ this.body = this.xhr.response;
+ } else {
+ this.body = this.req.method != 'HEAD'
+ ? this._parseBody(this.text ? this.text : this.xhr.response)
+ : null;
+ }
}
-/**
- * Represents the current readableState pipe targets for this Logger instance.
- * @type {Array|Object}
- */
+ResponseBase(Response.prototype);
-Object.defineProperty(Logger.prototype, 'transports', {
- configurable: false,
- enumerable: true,
- get: function get() {
- var pipes = this._readableState.pipes;
- return !Array.isArray(pipes) ? [pipes].filter(Boolean) : pipes;
- }
-});
-module.exports = Logger;
-}).call(this)}).call(this,require("timers").setImmediate)
-},{"./common":195,"./config":196,"./exception-handler":199,"./profiler":202,"./rejection-handler":203,"async/forEach":97,"is-stream":142,"logform/json":163,"readable-stream":224,"timers":76,"triple-beam":189,"winston-transport/legacy":193}],202:[function(require,module,exports){
/**
- * profiler.js: TODO: add file header description.
+ * Parse the given body `str`.
*
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- */
-'use strict';
-/**
- * TODO: add class description.
- * @type {Profiler}
- * @private
+ * Used for auto-parsing of bodies. Parsers
+ * are defined on the `superagent.parse` object.
+ *
+ * @param {String} str
+ * @return {Mixed}
+ * @api private
*/
-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 _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; }
-
-module.exports = /*#__PURE__*/function () {
- /**
- * Constructor function for the Profiler instance used by
- * `Logger.prototype.startTimer`. When done is called the timer will finish
- * and log the duration.
- * @param {!Logger} logger - TODO: add param description.
- * @private
- */
- function Profiler(logger) {
- _classCallCheck(this, Profiler);
-
- if (!logger) {
- throw new Error('Logger is required for profiling.');
- }
-
- this.logger = logger;
- this.start = Date.now();
+Response.prototype._parseBody = function(str) {
+ var parse = request.parse[this.type];
+ if (this.req._parser) {
+ return this.req._parser(this, str);
}
- /**
- * Ends the current timer (i.e. Profiler) instance and logs the `msg` along
- * with the duration since creation.
- * @returns {mixed} - TODO: add return description.
- * @private
- */
-
-
- _createClass(Profiler, [{
- key: "done",
- value: function done() {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
-
- if (typeof args[args.length - 1] === 'function') {
- // eslint-disable-next-line no-console
- console.warn('Callback function no longer supported as of winston@3.0.0');
- args.pop();
- }
-
- var info = _typeof(args[args.length - 1]) === 'object' ? args.pop() : {};
- info.level = info.level || 'info';
- info.durationMs = Date.now() - this.start;
- return this.logger.write(info);
- }
- }]);
+ if (!parse && isJSON(this.type)) {
+ parse = request.parse['application/json'];
+ }
+ return parse && str && (str.length || str instanceof Object)
+ ? parse(str)
+ : null;
+};
- return Profiler;
-}();
-},{}],203:[function(require,module,exports){
-(function (process){(function (){
/**
- * exception-handler.js: Object for handling uncaughtException events.
+ * Return an `Error` representative of this response.
*
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
+ * @return {Error}
+ * @api public
*/
-'use strict';
-
-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 os = require('os');
-
-var asyncForEach = require('async/forEach');
-
-var debug = require('@dabh/diagnostics')('winston:rejection');
+Response.prototype.toError = function(){
+ var req = this.req;
+ var method = req.method;
+ var url = req.url;
-var once = require('one-time');
+ var msg = 'cannot ' + method + ' ' + url + ' (' + this.status + ')';
+ var err = new Error(msg);
+ err.status = this.status;
+ err.method = method;
+ err.url = url;
-var stackTrace = require('stack-trace');
+ return err;
+};
-var ExceptionStream = require('./exception-stream');
/**
- * Object for handling unhandledRejection events.
- * @type {RejectionHandler}
+ * Expose `Response`.
*/
+request.Response = Response;
-module.exports = /*#__PURE__*/function () {
- /**
- * TODO: add contructor description
- * @param {!Logger} logger - TODO: add param description
- */
- function RejectionHandler(logger) {
- _classCallCheck(this, RejectionHandler);
-
- if (!logger) {
- throw new Error('Logger is required to handle rejections');
- }
-
- this.logger = logger;
- this.handlers = new Map();
- }
- /**
- * Handles `unhandledRejection` events for the current process by adding any
- * handlers passed in.
- * @returns {undefined}
- */
-
+/**
+ * Initialize a new `Request` with the given `method` and `url`.
+ *
+ * @param {String} method
+ * @param {String} url
+ * @api public
+ */
- _createClass(RejectionHandler, [{
- key: "handle",
- value: function handle() {
- var _this = this;
+function Request(method, url) {
+ var self = this;
+ this._query = this._query || [];
+ this.method = method;
+ this.url = url;
+ this.header = {}; // preserves header name case
+ this._header = {}; // coerces header names to lowercase
+ this.on('end', function(){
+ var err = null;
+ var res = null;
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
+ try {
+ res = new Response(self);
+ } catch(e) {
+ err = new Error('Parser is unable to parse the response');
+ err.parse = true;
+ err.original = e;
+ // issue #675: return the raw response if the response parsing fails
+ if (self.xhr) {
+ // ie9 doesn't have 'response' property
+ err.rawResponse = typeof self.xhr.responseType == 'undefined' ? self.xhr.responseText : self.xhr.response;
+ // issue #876: return the http status code if the response parsing fails
+ err.status = self.xhr.status ? self.xhr.status : null;
+ err.statusCode = err.status; // backwards-compat only
+ } else {
+ err.rawResponse = null;
+ err.status = null;
}
- args.forEach(function (arg) {
- if (Array.isArray(arg)) {
- return arg.forEach(function (handler) {
- return _this._addHandler(handler);
- });
- }
+ return self.callback(err);
+ }
- _this._addHandler(arg);
- });
+ self.emit('response', res);
- if (!this.catcher) {
- this.catcher = this._unhandledRejection.bind(this);
- process.on('unhandledRejection', this.catcher);
- }
- }
- /**
- * Removes any handlers to `unhandledRejection` events for the current
- * process. This does not modify the state of the `this.handlers` set.
- * @returns {undefined}
- */
-
- }, {
- key: "unhandle",
- value: function unhandle() {
- var _this2 = this;
-
- if (this.catcher) {
- process.removeListener('unhandledRejection', this.catcher);
- this.catcher = false;
- Array.from(this.handlers.values()).forEach(function (wrapper) {
- return _this2.logger.unpipe(wrapper);
- });
+ var new_err;
+ try {
+ if (!self._isResponseOK(res)) {
+ new_err = new Error(res.statusText || 'Unsuccessful HTTP response');
}
+ } catch(custom_err) {
+ new_err = custom_err; // ok() callback can throw
}
- /**
- * TODO: add method description
- * @param {Error} err - Error to get information about.
- * @returns {mixed} - TODO: add return description.
- */
-
- }, {
- key: "getAllInfo",
- value: function getAllInfo(err) {
- var message = err.message;
-
- if (!message && typeof err === 'string') {
- message = err;
- }
- return {
- error: err,
- // TODO (indexzero): how do we configure this?
- level: 'error',
- message: ["unhandledRejection: ".concat(message || '(no error message)'), err.stack || ' No stack trace'].join('\n'),
- stack: err.stack,
- exception: true,
- date: new Date().toString(),
- process: this.getProcessInfo(),
- os: this.getOsInfo(),
- trace: this.getTrace(err)
- };
- }
- /**
- * Gets all relevant process information for the currently running process.
- * @returns {mixed} - TODO: add return description.
- */
-
- }, {
- key: "getProcessInfo",
- value: function getProcessInfo() {
- return {
- pid: process.pid,
- uid: process.getuid ? process.getuid() : null,
- gid: process.getgid ? process.getgid() : null,
- cwd: process.cwd(),
- execPath: process.execPath,
- version: process.version,
- argv: process.argv,
- memoryUsage: process.memoryUsage()
- };
- }
- /**
- * Gets all relevant OS information for the currently running process.
- * @returns {mixed} - TODO: add return description.
- */
-
- }, {
- key: "getOsInfo",
- value: function getOsInfo() {
- return {
- loadavg: os.loadavg(),
- uptime: os.uptime()
- };
- }
- /**
- * Gets a stack trace for the specified error.
- * @param {mixed} err - TODO: add param description.
- * @returns {mixed} - TODO: add return description.
- */
-
- }, {
- key: "getTrace",
- value: function getTrace(err) {
- var trace = err ? stackTrace.parse(err) : stackTrace.get();
- return trace.map(function (site) {
- return {
- column: site.getColumnNumber(),
- file: site.getFileName(),
- "function": site.getFunctionName(),
- line: site.getLineNumber(),
- method: site.getMethodName(),
- "native": site.isNative()
- };
- });
- }
- /**
- * Helper method to add a transport as an exception handler.
- * @param {Transport} handler - The transport to add as an exception handler.
- * @returns {void}
- */
-
- }, {
- key: "_addHandler",
- value: function _addHandler(handler) {
- if (!this.handlers.has(handler)) {
- handler.handleRejections = true;
- var wrapper = new ExceptionStream(handler);
- this.handlers.set(handler, wrapper);
- this.logger.pipe(wrapper);
- }
+ // #1000 don't catch errors from the callback to avoid double calling it
+ if (new_err) {
+ new_err.original = err;
+ new_err.response = res;
+ new_err.status = res.status;
+ self.callback(new_err, res);
+ } else {
+ self.callback(null, res);
}
- /**
- * Logs all relevant information around the `err` and exits the current
- * process.
- * @param {Error} err - Error to handle
- * @returns {mixed} - TODO: add return description.
- * @private
- */
-
- }, {
- key: "_unhandledRejection",
- value: function _unhandledRejection(err) {
- var info = this.getAllInfo(err);
-
- var handlers = this._getRejectionHandlers(); // Calculate if we should exit on this error
-
-
- var doExit = typeof this.logger.exitOnError === 'function' ? this.logger.exitOnError(err) : this.logger.exitOnError;
- var timeout;
-
- if (!handlers.length && doExit) {
- // eslint-disable-next-line no-console
- console.warn('winston: exitOnError cannot be true with no rejection handlers.'); // eslint-disable-next-line no-console
-
- console.warn('winston: not exiting process.');
- doExit = false;
- }
-
- function gracefulExit() {
- debug('doExit', doExit);
- debug('process._exiting', process._exiting);
-
- if (doExit && !process._exiting) {
- // Remark: Currently ignoring any rejections from transports when
- // catching unhandled rejections.
- if (timeout) {
- clearTimeout(timeout);
- } // eslint-disable-next-line no-process-exit
-
-
- process.exit(1);
- }
- }
+ });
+}
- if (!handlers || handlers.length === 0) {
- return process.nextTick(gracefulExit);
- } // Log to all transports attempting to listen for when they are completed.
+/**
+ * Mixin `Emitter` and `RequestBase`.
+ */
+Emitter(Request.prototype);
+RequestBase(Request.prototype);
- asyncForEach(handlers, function (handler, next) {
- var done = once(next);
- var transport = handler.transport || handler; // Debug wrapping so that we can inspect what's going on under the covers.
+/**
+ * Set Content-Type to `type`, mapping values from `request.types`.
+ *
+ * Examples:
+ *
+ * superagent.types.xml = 'application/xml';
+ *
+ * request.post('/')
+ * .type('xml')
+ * .send(xmlstring)
+ * .end(callback);
+ *
+ * request.post('/')
+ * .type('application/xml')
+ * .send(xmlstring)
+ * .end(callback);
+ *
+ * @param {String} type
+ * @return {Request} for chaining
+ * @api public
+ */
- function onDone(event) {
- return function () {
- debug(event);
- done();
- };
- }
+Request.prototype.type = function(type){
+ this.set('Content-Type', request.types[type] || type);
+ return this;
+};
- transport._ending = true;
- transport.once('finish', onDone('finished'));
- transport.once('error', onDone('error'));
- }, function () {
- return doExit && gracefulExit();
- });
- this.logger.log(info); // If exitOnError is true, then only allow the logging of exceptions to
- // take up to `3000ms`.
+/**
+ * Set Accept to `type`, mapping values from `request.types`.
+ *
+ * Examples:
+ *
+ * superagent.types.json = 'application/json';
+ *
+ * request.get('/agent')
+ * .accept('json')
+ * .end(callback);
+ *
+ * request.get('/agent')
+ * .accept('application/json')
+ * .end(callback);
+ *
+ * @param {String} accept
+ * @return {Request} for chaining
+ * @api public
+ */
- if (doExit) {
- timeout = setTimeout(gracefulExit, 3000);
- }
- }
- /**
- * Returns the list of transports and exceptionHandlers for this instance.
- * @returns {Array} - List of transports and exceptionHandlers for this
- * instance.
- * @private
- */
-
- }, {
- key: "_getRejectionHandlers",
- value: function _getRejectionHandlers() {
- // Remark (indexzero): since `logger.transports` returns all of the pipes
- // from the _readableState of the stream we actually get the join of the
- // explicit handlers and the implicit transports with
- // `handleRejections: true`
- return this.logger.transports.filter(function (wrap) {
- var transport = wrap.transport || wrap;
- return transport.handleRejections;
- });
- }
- }]);
+Request.prototype.accept = function(type){
+ this.set('Accept', request.types[type] || type);
+ return this;
+};
- return RejectionHandler;
-}();
-}).call(this)}).call(this,require('_process'))
-},{"./exception-stream":200,"@dabh/diagnostics":88,"_process":34,"async/forEach":97,"one-time":165,"os":20,"stack-trace":176}],204:[function(require,module,exports){
-(function (Buffer){(function (){
/**
- * tail-file.js: TODO: add file header description.
+ * Set Authorization field value with `user` and `pass`.
*
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
+ * @param {String} user
+ * @param {String} [pass] optional in case of using 'bearer' as type
+ * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic')
+ * @return {Request} for chaining
+ * @api public
*/
-'use strict';
-var fs = require('fs');
+Request.prototype.auth = function(user, pass, options){
+ if (1 === arguments.length) pass = '';
+ if (typeof pass === 'object' && pass !== null) { // pass is optional and can be replaced with options
+ options = pass;
+ pass = '';
+ }
+ if (!options) {
+ options = {
+ type: 'function' === typeof btoa ? 'basic' : 'auto',
+ };
+ }
+
+ var encoder = function(string) {
+ if ('function' === typeof btoa) {
+ return btoa(string);
+ }
+ throw new Error('Cannot use basic auth, btoa is not a function');
+ };
-var _require = require('string_decoder'),
- StringDecoder = _require.StringDecoder;
+ return this._auth(user, pass, options, encoder);
+};
-var _require2 = require('readable-stream'),
- Stream = _require2.Stream;
/**
- * Simple no-op function.
- * @returns {undefined}
+ * Add query-string `val`.
+ *
+ * Examples:
+ *
+ * request.get('/shoes')
+ * .query('size=10')
+ * .query({ color: 'blue' })
+ *
+ * @param {Object|String} val
+ * @return {Request} for chaining
+ * @api public
*/
+Request.prototype.query = function(val){
+ if ('string' != typeof val) val = serialize(val);
+ if (val) this._query.push(val);
+ return this;
+};
-function noop() {}
/**
- * TODO: add function description.
- * @param {Object} options - Options for tail.
- * @param {function} iter - Iterator function to execute on every line.
-* `tail -f` a file. Options must include file.
- * @returns {mixed} - TODO: add return description.
+ * Queue the given `file` as an attachment to the specified `field`,
+ * with optional `options` (or filename).
+ *
+ * ``` js
+ * request.post('/upload')
+ * .attach('content', new Blob(['hey!'], { type: "text/html"}))
+ * .end(callback);
+ * ```
+ *
+ * @param {String} field
+ * @param {Blob|File} file
+ * @param {String|Object} options
+ * @return {Request} for chaining
+ * @api public
*/
-
-module.exports = function (options, iter) {
- var buffer = Buffer.alloc(64 * 1024);
- var decode = new StringDecoder('utf8');
- var stream = new Stream();
- var buff = '';
- var pos = 0;
- var row = 0;
-
- if (options.start === -1) {
- delete options.start;
- }
-
- stream.readable = true;
-
- stream.destroy = function () {
- stream.destroyed = true;
- stream.emit('end');
- stream.emit('close');
- };
-
- fs.open(options.file, 'a+', '0644', function (err, fd) {
- if (err) {
- if (!iter) {
- stream.emit('error', err);
- } else {
- iter(err);
- }
-
- stream.destroy();
- return;
+Request.prototype.attach = function(field, file, options){
+ if (file) {
+ if (this._data) {
+ throw Error("superagent can't mix .send() and .attach()");
}
- (function read() {
- if (stream.destroyed) {
- fs.close(fd, noop);
- return;
- }
-
- return fs.read(fd, buffer, 0, buffer.length, pos, function (error, bytes) {
- if (error) {
- if (!iter) {
- stream.emit('error', error);
- } else {
- iter(error);
- }
-
- stream.destroy();
- return;
- }
-
- if (!bytes) {
- if (buff) {
- // eslint-disable-next-line eqeqeq
- if (options.start == null || row > options.start) {
- if (!iter) {
- stream.emit('line', buff);
- } else {
- iter(null, buff);
- }
- }
-
- row++;
- buff = '';
- }
-
- return setTimeout(read, 1000);
- }
-
- var data = decode.write(buffer.slice(0, bytes));
-
- if (!iter) {
- stream.emit('data', data);
- }
-
- data = (buff + data).split(/\n+/);
- var l = data.length - 1;
- var i = 0;
-
- for (; i < l; i++) {
- // eslint-disable-next-line eqeqeq
- if (options.start == null || row > options.start) {
- if (!iter) {
- stream.emit('line', data[i]);
- } else {
- iter(null, data[i]);
- }
- }
-
- row++;
- }
-
- buff = data[l];
- pos += bytes;
- return read();
- });
- })();
- });
-
- if (!iter) {
- return stream;
+ this._getFormData().append(field, file, options || file.name);
}
+ return this;
+};
- return stream.destroy;
+Request.prototype._getFormData = function(){
+ if (!this._formData) {
+ this._formData = new root.FormData();
+ }
+ return this._formData;
};
-}).call(this)}).call(this,require("buffer").Buffer)
-},{"buffer":10,"fs":1,"readable-stream":224,"string_decoder":75}],205:[function(require,module,exports){
-(function (setImmediate){(function (){
-/* eslint-disable no-console */
-/*
- * console.js: Transport for outputting to the console.
+/**
+ * Invoke the callback with `err` and `res`
+ * and handle arity check.
*
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
+ * @param {Error} err
+ * @param {Response} res
+ * @api private
*/
-'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); }
-
-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); } }
+Request.prototype.callback = function(err, res){
+ if (this._shouldRetry(err, res)) {
+ return this._retry();
+ }
-function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+ var fn = this._callback;
+ this.clearTimeout();
-function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
+ if (err) {
+ if (this._maxRetries) err.retries = this._retries - 1;
+ this.emit('error', err);
+ }
-function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
+ fn(err, res);
+};
-function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
+/**
+ * Invoke callback with x-domain error.
+ *
+ * @api private
+ */
-function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
+Request.prototype.crossDomainError = function(){
+ var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.');
+ err.crossDomain = true;
-function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
+ err.status = this.status;
+ err.method = this.method;
+ err.url = this.url;
-function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
+ this.callback(err);
+};
-function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
+// This only warns, because the request is still likely to work
+Request.prototype.buffer = Request.prototype.ca = Request.prototype.agent = function(){
+ console.warn("This is not supported in browser version of superagent");
+ return this;
+};
-var os = require('os');
+// This throws, because it can't send/receive data as expected
+Request.prototype.pipe = Request.prototype.write = function(){
+ throw Error("Streaming is not supported in browser version of superagent");
+};
-var _require = require('triple-beam'),
- LEVEL = _require.LEVEL,
- MESSAGE = _require.MESSAGE;
+/**
+ * Check if `obj` is a host object,
+ * we don't want to serialize these :)
+ *
+ * @param {Object} obj
+ * @return {Boolean}
+ * @api private
+ */
+Request.prototype._isHost = function _isHost(obj) {
+ // Native objects stringify to [object File], [object Blob], [object FormData], etc.
+ return obj && 'object' === typeof obj && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]';
+}
-var TransportStream = require('winston-transport');
/**
- * Transport for outputting to the console.
- * @type {Console}
- * @extends {TransportStream}
+ * Initiate request, invoking callback `fn(res)`
+ * with an instanceof `Response`.
+ *
+ * @param {Function} fn
+ * @return {Request} for chaining
+ * @api public
*/
+Request.prototype.end = function(fn){
+ if (this._endCalled) {
+ console.warn("Warning: .end() was called twice. This is not supported in superagent");
+ }
+ this._endCalled = true;
-module.exports = /*#__PURE__*/function (_TransportStream) {
- _inherits(Console, _TransportStream);
+ // store callback
+ this._callback = fn || noop;
- var _super = _createSuper(Console);
+ // querystring
+ this._finalizeQueryString();
- /**
- * Constructor function for the Console transport object responsible for
- * persisting log messages and metadata to a terminal or TTY.
- * @param {!Object} [options={}] - Options for this instance.
- */
- function Console() {
- var _this;
+ return this._end();
+};
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
+Request.prototype._end = function() {
+ var self = this;
+ var xhr = (this.xhr = request.getXHR());
+ var data = this._formData || this._data;
- _classCallCheck(this, Console);
+ this._setTimeouts();
- _this = _super.call(this, options); // Expose the name of this Transport on the prototype
+ // state change
+ xhr.onreadystatechange = function(){
+ var readyState = xhr.readyState;
+ if (readyState >= 2 && self._responseTimeoutTimer) {
+ clearTimeout(self._responseTimeoutTimer);
+ }
+ if (4 != readyState) {
+ return;
+ }
- _this.name = options.name || 'console';
- _this.stderrLevels = _this._stringArrayToSet(options.stderrLevels);
- _this.consoleWarnLevels = _this._stringArrayToSet(options.consoleWarnLevels);
- _this.eol = options.eol || os.EOL;
+ // In IE9, reads to any property (e.g. status) off of an aborted XHR will
+ // result in the error "Could not complete the operation due to error c00c023f"
+ var status;
+ try { status = xhr.status } catch(e) { status = 0; }
- _this.setMaxListeners(30);
+ if (!status) {
+ if (self.timedout || self._aborted) return;
+ return self.crossDomainError();
+ }
+ self.emit('end');
+ };
- return _this;
+ // progress
+ var handleProgress = function(direction, e) {
+ if (e.total > 0) {
+ e.percent = e.loaded / e.total * 100;
+ }
+ e.direction = direction;
+ self.emit('progress', e);
+ };
+ if (this.hasListeners('progress')) {
+ try {
+ xhr.onprogress = handleProgress.bind(null, 'download');
+ if (xhr.upload) {
+ xhr.upload.onprogress = handleProgress.bind(null, 'upload');
+ }
+ } catch(e) {
+ // Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist.
+ // Reported here:
+ // https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context
+ }
}
- /**
- * Core logging method exposed to Winston.
- * @param {Object} info - TODO: add param description.
- * @param {Function} callback - TODO: add param description.
- * @returns {undefined}
- */
-
-
- _createClass(Console, [{
- key: "log",
- value: function log(info, callback) {
- var _this2 = this;
- setImmediate(function () {
- return _this2.emit('logged', info);
- }); // Remark: what if there is no raw...?
+ // initiate request
+ try {
+ if (this.username && this.password) {
+ xhr.open(this.method, this.url, true, this.username, this.password);
+ } else {
+ xhr.open(this.method, this.url, true);
+ }
+ } catch (err) {
+ // see #1149
+ return this.callback(err);
+ }
- if (this.stderrLevels[info[LEVEL]]) {
- if (console._stderr) {
- // Node.js maps `process.stderr` to `console._stderr`.
- console._stderr.write("".concat(info[MESSAGE]).concat(this.eol));
- } else {
- // console.error adds a newline
- console.error(info[MESSAGE]);
- }
+ // CORS
+ if (this._withCredentials) xhr.withCredentials = true;
- if (callback) {
- callback(); // eslint-disable-line callback-return
- }
+ // body
+ if (!this._formData && 'GET' != this.method && 'HEAD' != this.method && 'string' != typeof data && !this._isHost(data)) {
+ // serialize stuff
+ var contentType = this._header['content-type'];
+ var serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : ''];
+ if (!serialize && isJSON(contentType)) {
+ serialize = request.serialize['application/json'];
+ }
+ if (serialize) data = serialize(data);
+ }
- return;
- } else if (this.consoleWarnLevels[info[LEVEL]]) {
- if (console._stderr) {
- // Node.js maps `process.stderr` to `console._stderr`.
- // in Node.js console.warn is an alias for console.error
- console._stderr.write("".concat(info[MESSAGE]).concat(this.eol));
- } else {
- // console.warn adds a newline
- console.warn(info[MESSAGE]);
- }
+ // set header fields
+ for (var field in this.header) {
+ if (null == this.header[field]) continue;
- if (callback) {
- callback(); // eslint-disable-line callback-return
- }
+ if (this.header.hasOwnProperty(field))
+ xhr.setRequestHeader(field, this.header[field]);
+ }
- return;
- }
+ if (this._responseType) {
+ xhr.responseType = this._responseType;
+ }
- if (console._stdout) {
- // Node.js maps `process.stdout` to `console._stdout`.
- console._stdout.write("".concat(info[MESSAGE]).concat(this.eol));
- } else {
- // console.log adds a newline.
- console.log(info[MESSAGE]);
- }
+ // send stuff
+ this.emit('request', this);
- if (callback) {
- callback(); // eslint-disable-line callback-return
- }
- }
- /**
- * Returns a Set-like object with strArray's elements as keys (each with the
- * value true).
- * @param {Array} strArray - Array of Set-elements as strings.
- * @param {?string} [errMsg] - Custom error message thrown on invalid input.
- * @returns {Object} - TODO: add return description.
- * @private
- */
-
- }, {
- key: "_stringArrayToSet",
- value: function _stringArrayToSet(strArray, errMsg) {
- if (!strArray) return {};
- errMsg = errMsg || 'Cannot make set from type other than Array of string elements';
-
- if (!Array.isArray(strArray)) {
- throw new Error(errMsg);
- }
+ // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing)
+ // We need null here if data is undefined
+ xhr.send(typeof data !== 'undefined' ? data : null);
+ return this;
+};
- return strArray.reduce(function (set, el) {
- if (typeof el !== 'string') {
- throw new Error(errMsg);
- }
+request.agent = function() {
+ return new Agent();
+};
- set[el] = true;
- return set;
- }, {});
+["GET", "POST", "OPTIONS", "PATCH", "PUT", "DELETE"].forEach(function(method) {
+ Agent.prototype[method.toLowerCase()] = function(url, fn) {
+ var req = new request.Request(method, url);
+ this._setDefaults(req);
+ if (fn) {
+ req.end(fn);
}
- }]);
+ return req;
+ };
+});
- return Console;
-}(TransportStream);
-}).call(this)}).call(this,require("timers").setImmediate)
-},{"os":20,"timers":76,"triple-beam":189,"winston-transport":191}],206:[function(require,module,exports){
-(function (Buffer,setImmediate){(function (){
-/* eslint-disable complexity,max-statements */
+Agent.prototype.del = Agent.prototype['delete'];
/**
- * file.js: Transport for outputting to a local log file.
+ * GET `url` with optional callback `fn(res)`.
*
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
+ * @param {String} url
+ * @param {Mixed|Function} [data] or fn
+ * @param {Function} [fn]
+ * @return {Request}
+ * @api public
*/
-'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); }
-
-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; }
-
-function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
-
-function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
-
-function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
-
-function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
-
-function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
-
-function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
-
-function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
-
-var fs = require('fs');
-
-var path = require('path');
-
-var asyncSeries = require('async/series');
-var zlib = require('zlib');
-
-var _require = require('triple-beam'),
- MESSAGE = _require.MESSAGE;
-
-var _require2 = require('readable-stream'),
- Stream = _require2.Stream,
- PassThrough = _require2.PassThrough;
-
-var TransportStream = require('winston-transport');
-
-var debug = require('@dabh/diagnostics')('winston:file');
-
-var os = require('os');
+request.get = function(url, data, fn) {
+ var req = request('GET', url);
+ if ('function' == typeof data) (fn = data), (data = null);
+ if (data) req.query(data);
+ if (fn) req.end(fn);
+ return req;
+};
-var tailFile = require('../tail-file');
/**
- * Transport for outputting to a local log file.
- * @type {File}
- * @extends {TransportStream}
+ * HEAD `url` with optional callback `fn(res)`.
+ *
+ * @param {String} url
+ * @param {Mixed|Function} [data] or fn
+ * @param {Function} [fn]
+ * @return {Request}
+ * @api public
*/
+request.head = function(url, data, fn) {
+ var req = request('HEAD', url);
+ if ('function' == typeof data) (fn = data), (data = null);
+ if (data) req.query(data);
+ if (fn) req.end(fn);
+ return req;
+};
-module.exports = /*#__PURE__*/function (_TransportStream) {
- _inherits(File, _TransportStream);
-
- var _super = _createSuper(File);
-
- /**
- * Constructor function for the File transport object responsible for
- * persisting log messages and metadata to one or more files.
- * @param {Object} options - Options for this instance.
- */
- function File() {
- var _this;
-
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
-
- _classCallCheck(this, File);
-
- _this = _super.call(this, options); // Expose the name of this Transport on the prototype.
+/**
+ * OPTIONS query to `url` with optional callback `fn(res)`.
+ *
+ * @param {String} url
+ * @param {Mixed|Function} [data] or fn
+ * @param {Function} [fn]
+ * @return {Request}
+ * @api public
+ */
- _this.name = options.name || 'file'; // Helper function which throws an `Error` in the event that any of the
- // rest of the arguments is present in `options`.
+request.options = function(url, data, fn) {
+ var req = request('OPTIONS', url);
+ if ('function' == typeof data) (fn = data), (data = null);
+ if (data) req.send(data);
+ if (fn) req.end(fn);
+ return req;
+};
- function throwIf(target) {
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
- args[_key - 1] = arguments[_key];
- }
+/**
+ * DELETE `url` with optional `data` and callback `fn(res)`.
+ *
+ * @param {String} url
+ * @param {Mixed} [data]
+ * @param {Function} [fn]
+ * @return {Request}
+ * @api public
+ */
- args.slice(1).forEach(function (name) {
- if (options[name]) {
- throw new Error("Cannot set ".concat(name, " and ").concat(target, " together"));
- }
- });
- } // Setup the base stream that always gets piped to to handle buffering.
+function del(url, data, fn) {
+ var req = request('DELETE', url);
+ if ('function' == typeof data) (fn = data), (data = null);
+ if (data) req.send(data);
+ if (fn) req.end(fn);
+ return req;
+}
+request['del'] = del;
+request['delete'] = del;
- _this._stream = new PassThrough();
+/**
+ * PATCH `url` with optional `data` and callback `fn(res)`.
+ *
+ * @param {String} url
+ * @param {Mixed} [data]
+ * @param {Function} [fn]
+ * @return {Request}
+ * @api public
+ */
- _this._stream.setMaxListeners(30); // Bind this context for listener methods.
+request.patch = function(url, data, fn) {
+ var req = request('PATCH', url);
+ if ('function' == typeof data) (fn = data), (data = null);
+ if (data) req.send(data);
+ if (fn) req.end(fn);
+ return req;
+};
+/**
+ * POST `url` with optional `data` and callback `fn(res)`.
+ *
+ * @param {String} url
+ * @param {Mixed} [data]
+ * @param {Function} [fn]
+ * @return {Request}
+ * @api public
+ */
- _this._onError = _this._onError.bind(_assertThisInitialized(_this));
+request.post = function(url, data, fn) {
+ var req = request('POST', url);
+ if ('function' == typeof data) (fn = data), (data = null);
+ if (data) req.send(data);
+ if (fn) req.end(fn);
+ return req;
+};
- if (options.filename || options.dirname) {
- throwIf('filename or dirname', 'stream');
- _this._basename = _this.filename = options.filename ? path.basename(options.filename) : 'winston.log';
- _this.dirname = options.dirname || path.dirname(options.filename);
- _this.options = options.options || {
- flags: 'a'
- };
- } else if (options.stream) {
- // eslint-disable-next-line no-console
- console.warn('options.stream will be removed in winston@4. Use winston.transports.Stream');
- throwIf('stream', 'filename', 'maxsize');
- _this._dest = _this._stream.pipe(_this._setupStream(options.stream));
- _this.dirname = path.dirname(_this._dest.path); // We need to listen for drain events when write() returns false. This
- // can make node mad at times.
- } else {
- throw new Error('Cannot log to file without filename or stream.');
- }
+/**
+ * PUT `url` with optional `data` and callback `fn(res)`.
+ *
+ * @param {String} url
+ * @param {Mixed|Function} [data] or fn
+ * @param {Function} [fn]
+ * @return {Request}
+ * @api public
+ */
- _this.maxsize = options.maxsize || null;
- _this.rotationFormat = options.rotationFormat || false;
- _this.zippedArchive = options.zippedArchive || false;
- _this.maxFiles = options.maxFiles || null;
- _this.eol = options.eol || os.EOL;
- _this.tailable = options.tailable || false; // Internal state variables representing the number of files this instance
- // has created and the current size (in bytes) of the current logfile.
-
- _this._size = 0;
- _this._pendingSize = 0;
- _this._created = 0;
- _this._drain = false;
- _this._opening = false;
- _this._ending = false;
- if (_this.dirname) _this._createLogDirIfNotExist(_this.dirname);
-
- _this.open();
-
- return _this;
- }
-
- _createClass(File, [{
- key: "finishIfEnding",
- value: function finishIfEnding() {
- var _this2 = this;
-
- if (this._ending) {
- if (this._opening) {
- this.once('open', function () {
- _this2._stream.once('finish', function () {
- return _this2.emit('finish');
- });
-
- setImmediate(function () {
- return _this2._stream.end();
- });
- });
- } else {
- this._stream.once('finish', function () {
- return _this2.emit('finish');
- });
-
- setImmediate(function () {
- return _this2._stream.end();
- });
- }
- }
- }
- /**
- * Core logging method exposed to Winston. Metadata is optional.
- * @param {Object} info - TODO: add param description.
- * @param {Function} callback - TODO: add param description.
- * @returns {undefined}
- */
+request.put = function(url, data, fn) {
+ var req = request('PUT', url);
+ if ('function' == typeof data) (fn = data), (data = null);
+ if (data) req.send(data);
+ if (fn) req.end(fn);
+ return req;
+};
- }, {
- key: "log",
- value: function log(info) {
- var _this3 = this;
+},{"./agent-base":5,"./is-object":7,"./request-base":8,"./response-base":9,"component-emitter":4}],7:[function(require,module,exports){
+'use strict';
- var callback = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {};
+/**
+ * Check if `obj` is an object.
+ *
+ * @param {Object} obj
+ * @return {Boolean}
+ * @api private
+ */
- // Remark: (jcrugzz) What is necessary about this callback(null, true) now
- // when thinking about 3.x? Should silent be handled in the base
- // TransportStream _write method?
- if (this.silent) {
- callback();
- return true;
- } // Output stream buffer is full and has asked us to wait for the drain event
+function isObject(obj) {
+ return null !== obj && 'object' === typeof obj;
+}
+module.exports = isObject;
- if (this._drain) {
- this._stream.once('drain', function () {
- _this3._drain = false;
+},{}],8:[function(require,module,exports){
+'use strict';
- _this3.log(info, callback);
- });
+/**
+ * Module of mixed-in functions shared between node and client code
+ */
+var isObject = require('./is-object');
- return;
- }
+/**
+ * Expose `RequestBase`.
+ */
- if (this._rotate) {
- this._stream.once('rotate', function () {
- _this3._rotate = false;
+module.exports = RequestBase;
- _this3.log(info, callback);
- });
+/**
+ * Initialize a new `RequestBase`.
+ *
+ * @api public
+ */
- return;
- } // Grab the raw string and append the expected EOL.
+function RequestBase(obj) {
+ if (obj) return mixin(obj);
+}
+/**
+ * Mixin the prototype properties.
+ *
+ * @param {Object} obj
+ * @return {Object}
+ * @api private
+ */
- var output = "".concat(info[MESSAGE]).concat(this.eol);
- var bytes = Buffer.byteLength(output); // After we have written to the PassThrough check to see if we need
- // to rotate to the next file.
- //
- // Remark: This gets called too early and does not depict when data
- // has been actually flushed to disk.
+function mixin(obj) {
+ for (var key in RequestBase.prototype) {
+ obj[key] = RequestBase.prototype[key];
+ }
+ return obj;
+}
- function logged() {
- var _this4 = this;
+/**
+ * Clear previous timeout.
+ *
+ * @return {Request} for chaining
+ * @api public
+ */
- this._size += bytes;
- this._pendingSize -= bytes;
- debug('logged %s %s', this._size, output);
- this.emit('logged', info); // Do not attempt to rotate files while opening
+RequestBase.prototype.clearTimeout = function _clearTimeout(){
+ clearTimeout(this._timer);
+ clearTimeout(this._responseTimeoutTimer);
+ delete this._timer;
+ delete this._responseTimeoutTimer;
+ return this;
+};
- if (this._opening) {
- return;
- } // Check to see if we need to end the stream and create a new one.
+/**
+ * Override default response body parser
+ *
+ * This function will be called to convert incoming data into request.body
+ *
+ * @param {Function}
+ * @api public
+ */
+RequestBase.prototype.parse = function parse(fn){
+ this._parser = fn;
+ return this;
+};
- if (!this._needsNewFile()) {
- return;
- } // End the current stream, ensure it flushes and create a new one.
- // This could potentially be optimized to not run a stat call but its
- // the safest way since we are supporting `maxFiles`.
+/**
+ * Set format of binary response body.
+ * In browser valid formats are 'blob' and 'arraybuffer',
+ * which return Blob and ArrayBuffer, respectively.
+ *
+ * In Node all values result in Buffer.
+ *
+ * Examples:
+ *
+ * req.get('/')
+ * .responseType('blob')
+ * .end(callback);
+ *
+ * @param {String} val
+ * @return {Request} for chaining
+ * @api public
+ */
+RequestBase.prototype.responseType = function(val){
+ this._responseType = val;
+ return this;
+};
- this._rotate = true;
+/**
+ * Override default request body serializer
+ *
+ * This function will be called to convert data set via .send or .attach into payload to send
+ *
+ * @param {Function}
+ * @api public
+ */
- this._endStream(function () {
- return _this4._rotateFile();
- });
- } // Keep track of the pending bytes being written while files are opening
- // in order to properly rotate the PassThrough this._stream when the file
- // eventually does open.
+RequestBase.prototype.serialize = function serialize(fn){
+ this._serializer = fn;
+ return this;
+};
+/**
+ * Set timeouts.
+ *
+ * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time.
+ * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections.
+ *
+ * Value of 0 or false means no timeout.
+ *
+ * @param {Number|Object} ms or {response, deadline}
+ * @return {Request} for chaining
+ * @api public
+ */
- this._pendingSize += bytes;
+RequestBase.prototype.timeout = function timeout(options){
+ if (!options || 'object' !== typeof options) {
+ this._timeout = options;
+ this._responseTimeout = 0;
+ return this;
+ }
- if (this._opening && !this.rotatedWhileOpening && this._needsNewFile(this._size + this._pendingSize)) {
- this.rotatedWhileOpening = true;
- }
+ for(var option in options) {
+ switch(option) {
+ case 'deadline':
+ this._timeout = options.deadline;
+ break;
+ case 'response':
+ this._responseTimeout = options.response;
+ break;
+ default:
+ console.warn("Unknown timeout option", option);
+ }
+ }
+ return this;
+};
- var written = this._stream.write(output, logged.bind(this));
+/**
+ * Set number of retry attempts on error.
+ *
+ * Failed requests will be retried 'count' times if timeout or err.code >= 500.
+ *
+ * @param {Number} count
+ * @param {Function} [fn]
+ * @return {Request} for chaining
+ * @api public
+ */
- if (!written) {
- this._drain = true;
+RequestBase.prototype.retry = function retry(count, fn){
+ // Default to 1 if no count passed or true
+ if (arguments.length === 0 || count === true) count = 1;
+ if (count <= 0) count = 0;
+ this._maxRetries = count;
+ this._retries = 0;
+ this._retryCallback = fn;
+ return this;
+};
- this._stream.once('drain', function () {
- _this3._drain = false;
- callback();
- });
- } else {
- callback(); // eslint-disable-line callback-return
- }
+var ERROR_CODES = [
+ 'ECONNRESET',
+ 'ETIMEDOUT',
+ 'EADDRINFO',
+ 'ESOCKETTIMEDOUT'
+];
- debug('written', written, this._drain);
- this.finishIfEnding();
- return written;
+/**
+ * Determine if a request should be retried.
+ * (Borrowed from segmentio/superagent-retry)
+ *
+ * @param {Error} err
+ * @param {Response} [res]
+ * @returns {Boolean}
+ */
+RequestBase.prototype._shouldRetry = function(err, res) {
+ if (!this._maxRetries || this._retries++ >= this._maxRetries) {
+ return false;
+ }
+ if (this._retryCallback) {
+ try {
+ var override = this._retryCallback(err, res);
+ if (override === true) return true;
+ if (override === false) return false;
+ // undefined falls back to defaults
+ } catch(e) {
+ console.error(e);
}
- /**
- * Query the transport. Options object is optional.
- * @param {Object} options - Loggly-like query options for this instance.
- * @param {function} callback - Continuation to respond to when complete.
- * TODO: Refactor me.
- */
-
- }, {
- key: "query",
- value: function query(options, callback) {
- if (typeof options === 'function') {
- callback = options;
- options = {};
- }
+ }
+ if (res && res.status && res.status >= 500 && res.status != 501) return true;
+ if (err) {
+ if (err.code && ~ERROR_CODES.indexOf(err.code)) return true;
+ // Superagent timeout
+ if (err.timeout && err.code == 'ECONNABORTED') return true;
+ if (err.crossDomain) return true;
+ }
+ return false;
+};
- options = normalizeQuery(options);
- var file = path.join(this.dirname, this.filename);
- var buff = '';
- var results = [];
- var row = 0;
- var stream = fs.createReadStream(file, {
- encoding: 'utf8'
- });
- stream.on('error', function (err) {
- if (stream.readable) {
- stream.destroy();
- }
+/**
+ * Retry request
+ *
+ * @return {Request} for chaining
+ * @api private
+ */
- if (!callback) {
- return;
- }
+RequestBase.prototype._retry = function() {
- return err.code !== 'ENOENT' ? callback(err) : callback(null, results);
- });
- stream.on('data', function (data) {
- data = (buff + data).split(/\n+/);
- var l = data.length - 1;
- var i = 0;
-
- for (; i < l; i++) {
- if (!options.start || row >= options.start) {
- add(data[i]);
- }
+ this.clearTimeout();
- row++;
- }
+ // node
+ if (this.req) {
+ this.req = null;
+ this.req = this.request();
+ }
- buff = data[l];
- });
- stream.on('close', function () {
- if (buff) {
- add(buff, true);
- }
+ this._aborted = false;
+ this.timedout = false;
- if (options.order === 'desc') {
- results = results.reverse();
- } // eslint-disable-next-line callback-return
+ return this._end();
+};
+/**
+ * Promise support
+ *
+ * @param {Function} resolve
+ * @param {Function} [reject]
+ * @return {Request}
+ */
- if (callback) callback(null, results);
+RequestBase.prototype.then = function then(resolve, reject) {
+ if (!this._fullfilledPromise) {
+ var self = this;
+ if (this._endCalled) {
+ console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises");
+ }
+ this._fullfilledPromise = new Promise(function(innerResolve, innerReject) {
+ self.end(function(err, res) {
+ if (err) innerReject(err);
+ else innerResolve(res);
});
+ });
+ }
+ return this._fullfilledPromise.then(resolve, reject);
+};
- function add(buff, attempt) {
- try {
- var log = JSON.parse(buff);
-
- if (check(log)) {
- push(log);
- }
- } catch (e) {
- if (!attempt) {
- stream.emit('error', e);
- }
- }
- }
-
- function push(log) {
- if (options.rows && results.length >= options.rows && options.order !== 'desc') {
- if (stream.readable) {
- stream.destroy();
- }
-
- return;
- }
-
- if (options.fields) {
- log = options.fields.reduce(function (obj, key) {
- obj[key] = log[key];
- return obj;
- }, {});
- }
-
- if (options.order === 'desc') {
- if (results.length >= options.rows) {
- results.shift();
- }
- }
+RequestBase.prototype['catch'] = function(cb) {
+ return this.then(undefined, cb);
+};
- results.push(log);
- }
+/**
+ * Allow for extension
+ */
- function check(log) {
- if (!log) {
- return;
- }
+RequestBase.prototype.use = function use(fn) {
+ fn(this);
+ return this;
+};
- if (_typeof(log) !== 'object') {
- return;
- }
+RequestBase.prototype.ok = function(cb) {
+ if ('function' !== typeof cb) throw Error("Callback required");
+ this._okCallback = cb;
+ return this;
+};
- var time = new Date(log.timestamp);
+RequestBase.prototype._isResponseOK = function(res) {
+ if (!res) {
+ return false;
+ }
- if (options.from && time < options.from || options.until && time > options.until || options.level && options.level !== log.level) {
- return;
- }
+ if (this._okCallback) {
+ return this._okCallback(res);
+ }
- return true;
- }
+ return res.status >= 200 && res.status < 300;
+};
- function normalizeQuery(options) {
- options = options || {}; // limit
+/**
+ * Get request header `field`.
+ * Case-insensitive.
+ *
+ * @param {String} field
+ * @return {String}
+ * @api public
+ */
- options.rows = options.rows || options.limit || 10; // starting row offset
+RequestBase.prototype.get = function(field){
+ return this._header[field.toLowerCase()];
+};
- options.start = options.start || 0; // now
+/**
+ * Get case-insensitive header `field` value.
+ * This is a deprecated internal API. Use `.get(field)` instead.
+ *
+ * (getHeader is no longer used internally by the superagent code base)
+ *
+ * @param {String} field
+ * @return {String}
+ * @api private
+ * @deprecated
+ */
- options.until = options.until || new Date();
+RequestBase.prototype.getHeader = RequestBase.prototype.get;
- if (_typeof(options.until) !== 'object') {
- options.until = new Date(options.until);
- } // now - 24
+/**
+ * Set header `field` to `val`, or multiple fields with one object.
+ * Case-insensitive.
+ *
+ * Examples:
+ *
+ * req.get('/')
+ * .set('Accept', 'application/json')
+ * .set('X-API-Key', 'foobar')
+ * .end(callback);
+ *
+ * req.get('/')
+ * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
+ * .end(callback);
+ *
+ * @param {String|Object} field
+ * @param {String} val
+ * @return {Request} for chaining
+ * @api public
+ */
+RequestBase.prototype.set = function(field, val){
+ if (isObject(field)) {
+ for (var key in field) {
+ this.set(key, field[key]);
+ }
+ return this;
+ }
+ this._header[field.toLowerCase()] = val;
+ this.header[field] = val;
+ return this;
+};
- options.from = options.from || options.until - 24 * 60 * 60 * 1000;
+/**
+ * Remove header `field`.
+ * Case-insensitive.
+ *
+ * Example:
+ *
+ * req.get('/')
+ * .unset('User-Agent')
+ * .end(callback);
+ *
+ * @param {String} field
+ */
+RequestBase.prototype.unset = function(field){
+ delete this._header[field.toLowerCase()];
+ delete this.header[field];
+ return this;
+};
- if (_typeof(options.from) !== 'object') {
- options.from = new Date(options.from);
- } // 'asc' or 'desc'
+/**
+ * Write the field `name` and `val`, or multiple fields with one object
+ * for "multipart/form-data" request bodies.
+ *
+ * ``` js
+ * request.post('/upload')
+ * .field('foo', 'bar')
+ * .end(callback);
+ *
+ * request.post('/upload')
+ * .field({ foo: 'bar', baz: 'qux' })
+ * .end(callback);
+ * ```
+ *
+ * @param {String|Object} name
+ * @param {String|Blob|File|Buffer|fs.ReadStream} val
+ * @return {Request} for chaining
+ * @api public
+ */
+RequestBase.prototype.field = function(name, val) {
+ // name should be either a string or an object.
+ if (null === name || undefined === name) {
+ throw new Error('.field(name, val) name can not be empty');
+ }
+ if (this._data) {
+ console.error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()");
+ }
- options.order = options.order || 'desc';
- return options;
- }
+ if (isObject(name)) {
+ for (var key in name) {
+ this.field(key, name[key]);
}
- /**
- * Returns a log stream for this transport. Options object is optional.
- * @param {Object} options - Stream options for this instance.
- * @returns {Stream} - TODO: add return description.
- * TODO: Refactor me.
- */
-
- }, {
- key: "stream",
- value: function stream() {
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- var file = path.join(this.dirname, this.filename);
- var stream = new Stream();
- var tail = {
- file: file,
- start: options.start
- };
- stream.destroy = tailFile(tail, function (err, line) {
- if (err) {
- return stream.emit('error', err);
- }
+ return this;
+ }
- try {
- stream.emit('data', line);
- line = JSON.parse(line);
- stream.emit('log', line);
- } catch (e) {
- stream.emit('error', e);
- }
- });
- return stream;
+ if (Array.isArray(val)) {
+ for (var i in val) {
+ this.field(name, val[i]);
}
- /**
- * Checks to see the filesize of.
- * @returns {undefined}
- */
-
- }, {
- key: "open",
- value: function open() {
- var _this5 = this;
-
- // If we do not have a filename then we were passed a stream and
- // don't need to keep track of size.
- if (!this.filename) return;
- if (this._opening) return;
- this._opening = true; // Stat the target file to get the size and create the stream.
-
- this.stat(function (err, size) {
- if (err) {
- return _this5.emit('error', err);
- }
+ return this;
+ }
- debug('stat done: %s { size: %s }', _this5.filename, size);
- _this5._size = size;
- _this5._dest = _this5._createStream(_this5._stream);
- _this5._opening = false;
+ // val should be defined now
+ if (null === val || undefined === val) {
+ throw new Error('.field(name, val) val can not be empty');
+ }
+ if ('boolean' === typeof val) {
+ val = '' + val;
+ }
+ this._getFormData().append(name, val);
+ return this;
+};
- _this5.once('open', function () {
- if (_this5._stream.eventNames().includes('rotate')) {
- _this5._stream.emit('rotate');
- } else {
- _this5._rotate = false;
- }
- });
- });
- }
- /**
- * Stat the file and assess information in order to create the proper stream.
- * @param {function} callback - TODO: add param description.
- * @returns {undefined}
- */
-
- }, {
- key: "stat",
- value: function stat(callback) {
- var _this6 = this;
-
- var target = this._getFile();
-
- var fullpath = path.join(this.dirname, target);
- fs.stat(fullpath, function (err, stat) {
- if (err && err.code === 'ENOENT') {
- debug('ENOENT ok', fullpath); // Update internally tracked filename with the new target name.
-
- _this6.filename = target;
- return callback(null, 0);
- }
+/**
+ * Abort the request, and clear potential timeout.
+ *
+ * @return {Request}
+ * @api public
+ */
+RequestBase.prototype.abort = function(){
+ if (this._aborted) {
+ return this;
+ }
+ this._aborted = true;
+ this.xhr && this.xhr.abort(); // browser
+ this.req && this.req.abort(); // node
+ this.clearTimeout();
+ this.emit('abort');
+ return this;
+};
- if (err) {
- debug("err ".concat(err.code, " ").concat(fullpath));
- return callback(err);
- }
+RequestBase.prototype._auth = function(user, pass, options, base64Encoder) {
+ switch (options.type) {
+ case 'basic':
+ this.set('Authorization', 'Basic ' + base64Encoder(user + ':' + pass));
+ break;
- if (!stat || _this6._needsNewFile(stat.size)) {
- // If `stats.size` is greater than the `maxsize` for this
- // instance then try again.
- return _this6._incFile(function () {
- return _this6.stat(callback);
- });
- } // Once we have figured out what the filename is, set it
- // and return the size.
+ case 'auto':
+ this.username = user;
+ this.password = pass;
+ break;
+ case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' })
+ this.set('Authorization', 'Bearer ' + user);
+ break;
+ }
+ return this;
+};
- _this6.filename = target;
- callback(null, stat.size);
- });
- }
- /**
- * Closes the stream associated with this instance.
- * @param {function} cb - TODO: add param description.
- * @returns {undefined}
- */
-
- }, {
- key: "close",
- value: function close(cb) {
- var _this7 = this;
-
- if (!this._stream) {
- return;
- }
+/**
+ * Enable transmission of cookies with x-domain requests.
+ *
+ * Note that for this to work the origin must not be
+ * using "Access-Control-Allow-Origin" with a wildcard,
+ * and also must set "Access-Control-Allow-Credentials"
+ * to "true".
+ *
+ * @api public
+ */
- this._stream.end(function () {
- if (cb) {
- cb(); // eslint-disable-line callback-return
- }
+RequestBase.prototype.withCredentials = function(on) {
+ // This is browser-only functionality. Node side is no-op.
+ if (on == undefined) on = true;
+ this._withCredentials = on;
+ return this;
+};
- _this7.emit('flush');
+/**
+ * Set the max redirects to `n`. Does noting in browser XHR implementation.
+ *
+ * @param {Number} n
+ * @return {Request} for chaining
+ * @api public
+ */
- _this7.emit('closed');
- });
- }
- /**
- * TODO: add method description.
- * @param {number} size - TODO: add param description.
- * @returns {undefined}
- */
-
- }, {
- key: "_needsNewFile",
- value: function _needsNewFile(size) {
- size = size || this._size;
- return this.maxsize && size >= this.maxsize;
- }
- /**
- * TODO: add method description.
- * @param {Error} err - TODO: add param description.
- * @returns {undefined}
- */
-
- }, {
- key: "_onError",
- value: function _onError(err) {
- this.emit('error', err);
- }
- /**
- * TODO: add method description.
- * @param {Stream} stream - TODO: add param description.
- * @returns {mixed} - TODO: add return description.
- */
-
- }, {
- key: "_setupStream",
- value: function _setupStream(stream) {
- stream.on('error', this._onError);
- return stream;
- }
- /**
- * TODO: add method description.
- * @param {Stream} stream - TODO: add param description.
- * @returns {mixed} - TODO: add return description.
- */
-
- }, {
- key: "_cleanupStream",
- value: function _cleanupStream(stream) {
- stream.removeListener('error', this._onError);
- return stream;
- }
- /**
- * TODO: add method description.
- */
+RequestBase.prototype.redirects = function(n){
+ this._maxRedirects = n;
+ return this;
+};
- }, {
- key: "_rotateFile",
- value: function _rotateFile() {
- var _this8 = this;
+/**
+ * Maximum size of buffered response body, in bytes. Counts uncompressed size.
+ * Default 200MB.
+ *
+ * @param {Number} n
+ * @return {Request} for chaining
+ */
+RequestBase.prototype.maxResponseSize = function(n){
+ if ('number' !== typeof n) {
+ throw TypeError("Invalid argument");
+ }
+ this._maxResponseSize = n;
+ return this;
+};
- this._incFile(function () {
- return _this8.open();
- });
- }
- /**
- * Unpipe from the stream that has been marked as full and end it so it
- * flushes to disk.
- *
- * @param {function} callback - Callback for when the current file has closed.
- * @private
- */
+/**
+ * Convert to a plain javascript object (not JSON string) of scalar properties.
+ * Note as this method is designed to return a useful non-this value,
+ * it cannot be chained.
+ *
+ * @return {Object} describing method, url, and data of this request
+ * @api public
+ */
- }, {
- key: "_endStream",
- value: function _endStream() {
- var _this9 = this;
+RequestBase.prototype.toJSON = function() {
+ return {
+ method: this.method,
+ url: this.url,
+ data: this._data,
+ headers: this._header,
+ };
+};
- var callback = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function () {};
+/**
+ * Send `data` as the request body, defaulting the `.type()` to "json" when
+ * an object is given.
+ *
+ * Examples:
+ *
+ * // manual json
+ * request.post('/user')
+ * .type('json')
+ * .send('{"name":"tj"}')
+ * .end(callback)
+ *
+ * // auto json
+ * request.post('/user')
+ * .send({ name: 'tj' })
+ * .end(callback)
+ *
+ * // manual x-www-form-urlencoded
+ * request.post('/user')
+ * .type('form')
+ * .send('name=tj')
+ * .end(callback)
+ *
+ * // auto x-www-form-urlencoded
+ * request.post('/user')
+ * .type('form')
+ * .send({ name: 'tj' })
+ * .end(callback)
+ *
+ * // defaults to x-www-form-urlencoded
+ * request.post('/user')
+ * .send('name=tobi')
+ * .send('species=ferret')
+ * .end(callback)
+ *
+ * @param {String|Object} data
+ * @return {Request} for chaining
+ * @api public
+ */
- if (this._dest) {
- this._stream.unpipe(this._dest);
+RequestBase.prototype.send = function(data){
+ var isObj = isObject(data);
+ var type = this._header['content-type'];
- this._dest.end(function () {
- _this9._cleanupStream(_this9._dest);
+ if (this._formData) {
+ console.error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()");
+ }
- callback();
- });
- } else {
- callback(); // eslint-disable-line callback-return
- }
+ if (isObj && !this._data) {
+ if (Array.isArray(data)) {
+ this._data = [];
+ } else if (!this._isHost(data)) {
+ this._data = {};
}
- /**
- * Returns the WritableStream for the active file on this instance. If we
- * should gzip the file then a zlib stream is returned.
- *
- * @param {ReadableStream} source – PassThrough to pipe to the file when open.
- * @returns {WritableStream} Stream that writes to disk for the active file.
- */
-
- }, {
- key: "_createStream",
- value: function _createStream(source) {
- var _this10 = this;
-
- var fullpath = path.join(this.dirname, this.filename);
- debug('create stream start', fullpath, this.options);
- var dest = fs.createWriteStream(fullpath, this.options) // TODO: What should we do with errors here?
- .on('error', function (err) {
- return debug(err);
- }).on('close', function () {
- return debug('close', dest.path, dest.bytesWritten);
- }).on('open', function () {
- debug('file open ok', fullpath);
-
- _this10.emit('open', fullpath);
-
- source.pipe(dest); // If rotation occured during the open operation then we immediately
- // start writing to a new PassThrough, begin opening the next file
- // and cleanup the previous source and dest once the source has drained.
-
- if (_this10.rotatedWhileOpening) {
- _this10._stream = new PassThrough();
+ } else if (data && this._data && this._isHost(this._data)) {
+ throw Error("Can't merge these send calls");
+ }
- _this10._stream.setMaxListeners(30);
+ // merge
+ if (isObj && isObject(this._data)) {
+ for (var key in data) {
+ this._data[key] = data[key];
+ }
+ } else if ('string' == typeof data) {
+ // default to x-www-form-urlencoded
+ if (!type) this.type('form');
+ type = this._header['content-type'];
+ if ('application/x-www-form-urlencoded' == type) {
+ this._data = this._data
+ ? this._data + '&' + data
+ : data;
+ } else {
+ this._data = (this._data || '') + data;
+ }
+ } else {
+ this._data = data;
+ }
- _this10._rotateFile();
+ if (!isObj || this._isHost(data)) {
+ return this;
+ }
- _this10.rotatedWhileOpening = false;
+ // default to json
+ if (!type) this.type('json');
+ return this;
+};
- _this10._cleanupStream(dest);
+/**
+ * Sort `querystring` by the sort function
+ *
+ *
+ * Examples:
+ *
+ * // default order
+ * request.get('/user')
+ * .query('name=Nick')
+ * .query('search=Manny')
+ * .sortQuery()
+ * .end(callback)
+ *
+ * // customized sort function
+ * request.get('/user')
+ * .query('name=Nick')
+ * .query('search=Manny')
+ * .sortQuery(function(a, b){
+ * return a.length - b.length;
+ * })
+ * .end(callback)
+ *
+ *
+ * @param {Function} sort
+ * @return {Request} for chaining
+ * @api public
+ */
- source.end();
- }
- });
- debug('create stream ok', fullpath);
+RequestBase.prototype.sortQuery = function(sort) {
+ // _sort default to true but otherwise can be a function or boolean
+ this._sort = typeof sort === 'undefined' ? true : sort;
+ return this;
+};
- if (this.zippedArchive) {
- var gzip = zlib.createGzip();
- gzip.pipe(dest);
- return gzip;
- }
+/**
+ * Compose querystring to append to req.url
+ *
+ * @api private
+ */
+RequestBase.prototype._finalizeQueryString = function(){
+ var query = this._query.join('&');
+ if (query) {
+ this.url += (this.url.indexOf('?') >= 0 ? '&' : '?') + query;
+ }
+ this._query.length = 0; // Makes the call idempotent
- return dest;
- }
- /**
- * TODO: add method description.
- * @param {function} callback - TODO: add param description.
- * @returns {undefined}
- */
-
- }, {
- key: "_incFile",
- value: function _incFile(callback) {
- debug('_incFile', this.filename);
- var ext = path.extname(this._basename);
- var basename = path.basename(this._basename, ext);
-
- if (!this.tailable) {
- this._created += 1;
-
- this._checkMaxFilesIncrementing(ext, basename, callback);
+ if (this._sort) {
+ var index = this.url.indexOf('?');
+ if (index >= 0) {
+ var queryArr = this.url.substring(index + 1).split('&');
+ if ('function' === typeof this._sort) {
+ queryArr.sort(this._sort);
} else {
- this._checkMaxFilesTailable(ext, basename, callback);
- }
- }
- /**
- * Gets the next filename to use for this instance in the case that log
- * filesizes are being capped.
- * @returns {string} - TODO: add return description.
- * @private
- */
-
- }, {
- key: "_getFile",
- value: function _getFile() {
- var ext = path.extname(this._basename);
- var basename = path.basename(this._basename, ext);
- var isRotation = this.rotationFormat ? this.rotationFormat() : this._created; // Caveat emptor (indexzero): rotationFormat() was broken by design When
- // combined with max files because the set of files to unlink is never
- // stored.
-
- var target = !this.tailable && this._created ? "".concat(basename).concat(isRotation).concat(ext) : "".concat(basename).concat(ext);
- return this.zippedArchive && !this.tailable ? "".concat(target, ".gz") : target;
- }
- /**
- * Increment the number of files created or checked by this instance.
- * @param {mixed} ext - TODO: add param description.
- * @param {mixed} basename - TODO: add param description.
- * @param {mixed} callback - TODO: add param description.
- * @returns {undefined}
- * @private
- */
-
- }, {
- key: "_checkMaxFilesIncrementing",
- value: function _checkMaxFilesIncrementing(ext, basename, callback) {
- // Check for maxFiles option and delete file.
- if (!this.maxFiles || this._created < this.maxFiles) {
- return setImmediate(callback);
- }
-
- var oldest = this._created - this.maxFiles;
- var isOldest = oldest !== 0 ? oldest : '';
- var isZipped = this.zippedArchive ? '.gz' : '';
- var filePath = "".concat(basename).concat(isOldest).concat(ext).concat(isZipped);
- var target = path.join(this.dirname, filePath);
- fs.unlink(target, callback);
- }
- /**
- * Roll files forward based on integer, up to maxFiles. e.g. if base if
- * file.log and it becomes oversized, roll to file1.log, and allow file.log
- * to be re-used. If file is oversized again, roll file1.log to file2.log,
- * roll file.log to file1.log, and so on.
- * @param {mixed} ext - TODO: add param description.
- * @param {mixed} basename - TODO: add param description.
- * @param {mixed} callback - TODO: add param description.
- * @returns {undefined}
- * @private
- */
-
- }, {
- key: "_checkMaxFilesTailable",
- value: function _checkMaxFilesTailable(ext, basename, callback) {
- var _this12 = this;
-
- var tasks = [];
-
- if (!this.maxFiles) {
- return;
- } // const isZipped = this.zippedArchive ? '.gz' : '';
-
-
- var isZipped = this.zippedArchive ? '.gz' : '';
-
- for (var x = this.maxFiles - 1; x > 1; x--) {
- tasks.push(function (i, cb) {
- var _this11 = this;
-
- var fileName = "".concat(basename).concat(i - 1).concat(ext).concat(isZipped);
- var tmppath = path.join(this.dirname, fileName);
- fs.exists(tmppath, function (exists) {
- if (!exists) {
- return cb(null);
- }
-
- fileName = "".concat(basename).concat(i).concat(ext).concat(isZipped);
- fs.rename(tmppath, path.join(_this11.dirname, fileName), cb);
- });
- }.bind(this, x));
+ queryArr.sort();
}
-
- asyncSeries(tasks, function () {
- fs.rename(path.join(_this12.dirname, "".concat(basename).concat(ext)), path.join(_this12.dirname, "".concat(basename, "1").concat(ext).concat(isZipped)), callback);
- });
+ this.url = this.url.substring(0, index) + '?' + queryArr.join('&');
}
- }, {
- key: "_createLogDirIfNotExist",
- value: function _createLogDirIfNotExist(dirPath) {
- /* eslint-disable no-sync */
- if (!fs.existsSync(dirPath)) {
- fs.mkdirSync(dirPath, {
- recursive: true
- });
- }
- /* eslint-enable no-sync */
+ }
+};
- }
- }]);
+// For backwards compat only
+RequestBase.prototype._appendQueryString = function() {console.trace("Unsupported");}
- return File;
-}(TransportStream);
-}).call(this)}).call(this,require("buffer").Buffer,require("timers").setImmediate)
-},{"../tail-file":204,"@dabh/diagnostics":88,"async/series":112,"buffer":10,"fs":1,"os":20,"path":32,"readable-stream":224,"timers":76,"triple-beam":189,"winston-transport":191,"zlib":9}],207:[function(require,module,exports){
-(function (Buffer,setImmediate){(function (){
/**
- * http.js: Transport for outputting to a json-rpcserver.
+ * Invoke callback with timeout error.
*
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
+ * @api private
*/
-'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); }
-
-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; }
-
-function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
-
-function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
-function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
-
-function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
-
-function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
-
-function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
-
-function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
+RequestBase.prototype._timeoutError = function(reason, timeout, errno){
+ if (this._aborted) {
+ return;
+ }
+ var err = new Error(reason + timeout + 'ms exceeded');
+ err.timeout = timeout;
+ err.code = 'ECONNABORTED';
+ err.errno = errno;
+ this.timedout = true;
+ this.abort();
+ this.callback(err);
+};
-var http = require('http');
+RequestBase.prototype._setTimeouts = function() {
+ var self = this;
-var https = require('https');
+ // deadline
+ if (this._timeout && !this._timer) {
+ this._timer = setTimeout(function(){
+ self._timeoutError('Timeout of ', self._timeout, 'ETIME');
+ }, this._timeout);
+ }
+ // response timeout
+ if (this._responseTimeout && !this._responseTimeoutTimer) {
+ this._responseTimeoutTimer = setTimeout(function(){
+ self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT');
+ }, this._responseTimeout);
+ }
+};
-var _require = require('readable-stream'),
- Stream = _require.Stream;
+},{"./is-object":7}],9:[function(require,module,exports){
+'use strict';
-var TransportStream = require('winston-transport');
/**
- * Transport for outputting to a json-rpc server.
- * @type {Stream}
- * @extends {TransportStream}
+ * Module dependencies.
*/
+var utils = require('./utils');
-module.exports = /*#__PURE__*/function (_TransportStream) {
- _inherits(Http, _TransportStream);
-
- var _super = _createSuper(Http);
-
- /**
- * Constructor function for the Http transport object responsible for
- * persisting log messages and metadata to a terminal or TTY.
- * @param {!Object} [options={}] - Options for this instance.
- */
- function Http() {
- var _this;
+/**
+ * Expose `ResponseBase`.
+ */
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
+module.exports = ResponseBase;
- _classCallCheck(this, Http);
+/**
+ * Initialize a new `ResponseBase`.
+ *
+ * @api public
+ */
- _this = _super.call(this, options);
- _this.options = options;
- _this.name = options.name || 'http';
- _this.ssl = !!options.ssl;
- _this.host = options.host || 'localhost';
- _this.port = options.port;
- _this.auth = options.auth;
- _this.path = options.path || '';
- _this.agent = options.agent;
- _this.headers = options.headers || {};
- _this.headers['content-type'] = 'application/json';
+function ResponseBase(obj) {
+ if (obj) return mixin(obj);
+}
- if (!_this.port) {
- _this.port = _this.ssl ? 443 : 80;
- }
+/**
+ * Mixin the prototype properties.
+ *
+ * @param {Object} obj
+ * @return {Object}
+ * @api private
+ */
- return _this;
+function mixin(obj) {
+ for (var key in ResponseBase.prototype) {
+ obj[key] = ResponseBase.prototype[key];
}
- /**
- * Core logging method exposed to Winston.
- * @param {Object} info - TODO: add param description.
- * @param {function} callback - TODO: add param description.
- * @returns {undefined}
- */
-
-
- _createClass(Http, [{
- key: "log",
- value: function log(info, callback) {
- var _this2 = this;
-
- this._request(info, function (err, res) {
- if (res && res.statusCode !== 200) {
- err = new Error("Invalid HTTP Status Code: ".concat(res.statusCode));
- }
-
- if (err) {
- _this2.emit('warn', err);
- } else {
- _this2.emit('logged', info);
- }
- }); // Remark: (jcrugzz) Fire and forget here so requests dont cause buffering
- // and block more requests from happening?
+ return obj;
+}
+/**
+ * Get case-insensitive `field` value.
+ *
+ * @param {String} field
+ * @return {String}
+ * @api public
+ */
- if (callback) {
- setImmediate(callback);
- }
- }
- /**
- * Query the transport. Options object is optional.
- * @param {Object} options - Loggly-like query options for this instance.
- * @param {function} callback - Continuation to respond to when complete.
- * @returns {undefined}
- */
-
- }, {
- key: "query",
- value: function query(options, callback) {
- if (typeof options === 'function') {
- callback = options;
- options = {};
- }
+ResponseBase.prototype.get = function(field) {
+ return this.header[field.toLowerCase()];
+};
- options = {
- method: 'query',
- params: this.normalizeQuery(options)
- };
+/**
+ * Set header related properties:
+ *
+ * - `.type` the content type without params
+ *
+ * A response of "Content-Type: text/plain; charset=utf-8"
+ * will provide you with a `.type` of "text/plain".
+ *
+ * @param {Object} header
+ * @api private
+ */
- if (options.params.path) {
- options.path = options.params.path;
- delete options.params.path;
- }
+ResponseBase.prototype._setHeaderProperties = function(header){
+ // TODO: moar!
+ // TODO: make this a util
- if (options.params.auth) {
- options.auth = options.params.auth;
- delete options.params.auth;
- }
+ // content-type
+ var ct = header['content-type'] || '';
+ this.type = utils.type(ct);
- this._request(options, function (err, res, body) {
- if (res && res.statusCode !== 200) {
- err = new Error("Invalid HTTP Status Code: ".concat(res.statusCode));
- }
+ // params
+ var params = utils.params(ct);
+ for (var key in params) this[key] = params[key];
- if (err) {
- return callback(err);
- }
+ this.links = {};
- if (typeof body === 'string') {
- try {
- body = JSON.parse(body);
- } catch (e) {
- return callback(e);
- }
+ // links
+ try {
+ if (header.link) {
+ this.links = utils.parseLinks(header.link);
}
-
- callback(null, body);
- });
+ } catch (err) {
+ // ignore
}
- /**
- * Returns a log stream for this transport. Options object is optional.
- * @param {Object} options - Stream options for this instance.
- * @returns {Stream} - TODO: add return description
- */
-
- }, {
- key: "stream",
- value: function stream() {
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- var stream = new Stream();
- options = {
- method: 'stream',
- params: options
- };
-
- if (options.params.path) {
- options.path = options.params.path;
- delete options.params.path;
- }
-
- if (options.params.auth) {
- options.auth = options.params.auth;
- delete options.params.auth;
- }
-
- var buff = '';
+};
- var req = this._request(options);
+/**
+ * Set flags such as `.ok` based on `status`.
+ *
+ * For example a 2xx response will give you a `.ok` of __true__
+ * whereas 5xx will be __false__ and `.error` will be __true__. The
+ * `.clientError` and `.serverError` are also available to be more
+ * specific, and `.statusType` is the class of error ranging from 1..5
+ * sometimes useful for mapping respond colors etc.
+ *
+ * "sugar" properties are also defined for common cases. Currently providing:
+ *
+ * - .noContent
+ * - .badRequest
+ * - .unauthorized
+ * - .notAcceptable
+ * - .notFound
+ *
+ * @param {Number} status
+ * @api private
+ */
- stream.destroy = function () {
- return req.destroy();
- };
+ResponseBase.prototype._setStatusProperties = function(status){
+ var type = status / 100 | 0;
- req.on('data', function (data) {
- data = (buff + data).split(/\n+/);
- var l = data.length - 1;
- var i = 0;
+ // status / class
+ this.status = this.statusCode = status;
+ this.statusType = type;
- for (; i < l; i++) {
- try {
- stream.emit('log', JSON.parse(data[i]));
- } catch (e) {
- stream.emit('error', e);
- }
- }
+ // basics
+ this.info = 1 == type;
+ this.ok = 2 == type;
+ this.redirect = 3 == type;
+ this.clientError = 4 == type;
+ this.serverError = 5 == type;
+ this.error = (4 == type || 5 == type)
+ ? this.toError()
+ : false;
- buff = data[l];
- });
- req.on('error', function (err) {
- return stream.emit('error', err);
- });
- return stream;
- }
- /**
- * Make a request to a winstond server or any http server which can
- * handle json-rpc.
- * @param {function} options - Options to sent the request.
- * @param {function} callback - Continuation to respond to when complete.
- */
-
- }, {
- key: "_request",
- value: function _request(options, callback) {
- options = options || {};
- var auth = options.auth || this.auth;
- var path = options.path || this.path || '';
- delete options.auth;
- delete options.path; // Prepare options for outgoing HTTP request
-
- var headers = Object.assign({}, this.headers);
-
- if (auth && auth.bearer) {
- headers.Authorization = "Bearer ".concat(auth.bearer);
- }
+ // sugar
+ this.created = 201 == status;
+ this.accepted = 202 == status;
+ this.noContent = 204 == status;
+ this.badRequest = 400 == status;
+ this.unauthorized = 401 == status;
+ this.notAcceptable = 406 == status;
+ this.forbidden = 403 == status;
+ this.notFound = 404 == status;
+ this.unprocessableEntity = 422 == status;
+};
- var req = (this.ssl ? https : http).request(_objectSpread(_objectSpread({}, this.options), {}, {
- method: 'POST',
- host: this.host,
- port: this.port,
- path: "/".concat(path.replace(/^\//, '')),
- headers: headers,
- auth: auth && auth.username && auth.password ? "".concat(auth.username, ":").concat(auth.password) : '',
- agent: this.agent
- }));
- req.on('error', callback);
- req.on('response', function (res) {
- return res.on('end', function () {
- return callback(null, res);
- }).resume();
- });
- req.end(Buffer.from(JSON.stringify(options), 'utf8'));
- }
- }]);
+},{"./utils":10}],10:[function(require,module,exports){
+'use strict';
- return Http;
-}(TransportStream);
-}).call(this)}).call(this,require("buffer").Buffer,require("timers").setImmediate)
-},{"buffer":10,"http":56,"https":14,"readable-stream":224,"timers":76,"winston-transport":191}],208:[function(require,module,exports){
/**
- * transports.js: Set of all transports Winston knows about.
+ * Return the mime type for the given `str`.
*
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
- */
-'use strict';
-/**
- * TODO: add property description.
- * @type {Console}
+ * @param {String} str
+ * @return {String}
+ * @api private
*/
-Object.defineProperty(exports, 'Console', {
- configurable: true,
- enumerable: true,
- get: function get() {
- return require('./console');
- }
-});
-/**
- * TODO: add property description.
- * @type {File}
- */
+exports.type = function(str){
+ return str.split(/ *; */).shift();
+};
-Object.defineProperty(exports, 'File', {
- configurable: true,
- enumerable: true,
- get: function get() {
- return require('./file');
- }
-});
/**
- * TODO: add property description.
- * @type {Http}
+ * Return header field parameters.
+ *
+ * @param {String} str
+ * @return {Object}
+ * @api private
*/
-Object.defineProperty(exports, 'Http', {
- configurable: true,
- enumerable: true,
- get: function get() {
- return require('./http');
- }
-});
-/**
- * TODO: add property description.
- * @type {Stream}
- */
+exports.params = function(str){
+ return str.split(/ *; */).reduce(function(obj, str){
+ var parts = str.split(/ *= */);
+ var key = parts.shift();
+ var val = parts.shift();
+
+ if (key && val) obj[key] = val;
+ return obj;
+ }, {});
+};
-Object.defineProperty(exports, 'Stream', {
- configurable: true,
- enumerable: true,
- get: function get() {
- return require('./stream');
- }
-});
-},{"./console":205,"./file":206,"./http":207,"./stream":209}],209:[function(require,module,exports){
-(function (setImmediate){(function (){
/**
- * stream.js: Transport for outputting to any arbitrary stream.
+ * Parse Link header fields.
*
- * (C) 2010 Charlie Robbins
- * MIT LICENCE
+ * @param {String} str
+ * @return {Object}
+ * @api private
*/
-'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); }
-
-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; }
-
-function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
-function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
-
-function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
-
-function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
-
-function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
-
-function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
-
-function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
-
-var isStream = require('is-stream');
-
-var _require = require('triple-beam'),
- MESSAGE = _require.MESSAGE;
-
-var os = require('os');
+exports.parseLinks = function(str){
+ return str.split(/ *, */).reduce(function(obj, str){
+ var parts = str.split(/ *; */);
+ var url = parts[0].slice(1, -1);
+ var rel = parts[1].split(/ *= */)[1].slice(1, -1);
+ obj[rel] = url;
+ return obj;
+ }, {});
+};
-var TransportStream = require('winston-transport');
/**
- * Transport for outputting to any arbitrary stream.
- * @type {Stream}
- * @extends {TransportStream}
+ * Strip content related fields from `header`.
+ *
+ * @param {Object} header
+ * @return {Object} header
+ * @api private
*/
-
-module.exports = /*#__PURE__*/function (_TransportStream) {
- _inherits(Stream, _TransportStream);
-
- var _super = _createSuper(Stream);
-
- /**
- * Constructor function for the Console transport object responsible for
- * persisting log messages and metadata to a terminal or TTY.
- * @param {!Object} [options={}] - Options for this instance.
- */
- function Stream() {
- var _this;
-
- var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
-
- _classCallCheck(this, Stream);
-
- _this = _super.call(this, options);
-
- if (!options.stream || !isStream(options.stream)) {
- throw new Error('options.stream is required.');
- } // We need to listen for drain events when write() returns false. This can
- // make node mad at times.
-
-
- _this._stream = options.stream;
-
- _this._stream.setMaxListeners(Infinity);
-
- _this.isObjectMode = options.stream._writableState.objectMode;
- _this.eol = options.eol || os.EOL;
- return _this;
+exports.cleanHeader = function(header, changesOrigin){
+ delete header['content-type'];
+ delete header['content-length'];
+ delete header['transfer-encoding'];
+ delete header['host'];
+ // secuirty
+ if (changesOrigin) {
+ delete header['authorization'];
+ delete header['cookie'];
}
- /**
- * Core logging method exposed to Winston.
- * @param {Object} info - TODO: add param description.
- * @param {Function} callback - TODO: add param description.
- * @returns {undefined}
- */
-
-
- _createClass(Stream, [{
- key: "log",
- value: function log(info, callback) {
- var _this2 = this;
-
- setImmediate(function () {
- return _this2.emit('logged', info);
- });
-
- if (this.isObjectMode) {
- this._stream.write(info);
-
- if (callback) {
- callback(); // eslint-disable-line callback-return
- }
-
- return;
- }
-
- this._stream.write("".concat(info[MESSAGE]).concat(this.eol));
-
- if (callback) {
- callback(); // eslint-disable-line callback-return
- }
-
- return;
- }
- }]);
-
- return Stream;
-}(TransportStream);
-}).call(this)}).call(this,require("timers").setImmediate)
-},{"is-stream":142,"os":20,"timers":76,"triple-beam":189,"winston-transport":191}],210:[function(require,module,exports){
-arguments[4][60][0].apply(exports,arguments)
-},{"dup":60}],211:[function(require,module,exports){
-arguments[4][61][0].apply(exports,arguments)
-},{"./_stream_readable":213,"./_stream_writable":215,"_process":34,"dup":61,"inherits":140}],212:[function(require,module,exports){
-arguments[4][62][0].apply(exports,arguments)
-},{"./_stream_transform":214,"dup":62,"inherits":140}],213:[function(require,module,exports){
-arguments[4][63][0].apply(exports,arguments)
-},{"../errors":210,"./_stream_duplex":211,"./internal/streams/async_iterator":216,"./internal/streams/buffer_list":217,"./internal/streams/destroy":218,"./internal/streams/from":220,"./internal/streams/state":222,"./internal/streams/stream":223,"_process":34,"buffer":10,"dup":63,"events":13,"inherits":140,"string_decoder/":177,"util":7}],214:[function(require,module,exports){
-arguments[4][64][0].apply(exports,arguments)
-},{"../errors":210,"./_stream_duplex":211,"dup":64,"inherits":140}],215:[function(require,module,exports){
-arguments[4][65][0].apply(exports,arguments)
-},{"../errors":210,"./_stream_duplex":211,"./internal/streams/destroy":218,"./internal/streams/state":222,"./internal/streams/stream":223,"_process":34,"buffer":10,"dup":65,"inherits":140,"util-deprecate":190}],216:[function(require,module,exports){
-arguments[4][66][0].apply(exports,arguments)
-},{"./end-of-stream":219,"_process":34,"dup":66}],217:[function(require,module,exports){
-arguments[4][67][0].apply(exports,arguments)
-},{"buffer":10,"dup":67,"util":7}],218:[function(require,module,exports){
-arguments[4][68][0].apply(exports,arguments)
-},{"_process":34,"dup":68}],219:[function(require,module,exports){
-arguments[4][69][0].apply(exports,arguments)
-},{"../../../errors":210,"dup":69}],220:[function(require,module,exports){
-arguments[4][70][0].apply(exports,arguments)
-},{"dup":70}],221:[function(require,module,exports){
-arguments[4][71][0].apply(exports,arguments)
-},{"../../../errors":210,"./end-of-stream":219,"dup":71}],222:[function(require,module,exports){
-arguments[4][72][0].apply(exports,arguments)
-},{"../../../errors":210,"dup":72}],223:[function(require,module,exports){
-arguments[4][47][0].apply(exports,arguments)
-},{"dup":47,"events":13}],224:[function(require,module,exports){
-arguments[4][74][0].apply(exports,arguments)
-},{"./lib/_stream_duplex.js":211,"./lib/_stream_passthrough.js":212,"./lib/_stream_readable.js":213,"./lib/_stream_transform.js":214,"./lib/_stream_writable.js":215,"./lib/internal/streams/end-of-stream.js":219,"./lib/internal/streams/pipeline.js":221,"dup":74}],225:[function(require,module,exports){
-module.exports={
- "_from": "winston@^3.3.3",
- "_id": "winston@3.3.3",
- "_inBundle": false,
- "_integrity": "sha1-rmFyBCyvspeGr6PQnI/4M6t8kXA=",
- "_location": "/winston",
- "_phantomChildren": {
- "inherits": "2.0.4",
- "string_decoder": "1.1.1",
- "util-deprecate": "1.0.2"
- },
- "_requested": {
- "type": "range",
- "registry": true,
- "raw": "winston@^3.3.3",
- "name": "winston",
- "escapedName": "winston",
- "rawSpec": "^3.3.3",
- "saveSpec": null,
- "fetchSpec": "^3.3.3"
- },
- "_requiredBy": [
- "/"
- ],
- "_resolved": "https://purecloud.jfrog.io/purecloud/api/npm/inin-internal-npm/winston/-/winston-3.3.3.tgz",
- "_shasum": "ae6172042cafb29786afa3d09c8ff833ab7c9170",
- "_spec": "winston@^3.3.3",
- "_where": "/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build",
- "author": {
- "name": "Charlie Robbins",
- "email": "charlie.robbins@gmail.com"
- },
- "browser": "./dist/winston",
- "bugs": {
- "url": "https://github.com/winstonjs/winston/issues"
- },
- "bundleDependencies": false,
- "dependencies": {
- "@dabh/diagnostics": "^2.0.2",
- "async": "^3.1.0",
- "is-stream": "^2.0.0",
- "logform": "^2.2.0",
- "one-time": "^1.0.0",
- "readable-stream": "^3.4.0",
- "stack-trace": "0.0.x",
- "triple-beam": "^1.3.0",
- "winston-transport": "^4.4.0"
- },
- "deprecated": false,
- "description": "A logger for just about everything.",
- "devDependencies": {
- "@babel/cli": "^7.10.3",
- "@babel/core": "^7.10.3",
- "@babel/preset-env": "^7.10.3",
- "@types/node": "^14.0.13",
- "abstract-winston-transport": "^0.5.1",
- "assume": "^2.2.0",
- "colors": "^1.4.0",
- "cross-spawn-async": "^2.2.5",
- "eslint-config-populist": "^4.2.0",
- "hock": "^1.4.1",
- "mocha": "^8.0.1",
- "nyc": "^15.1.0",
- "rimraf": "^3.0.2",
- "split2": "^3.1.1",
- "std-mocks": "^1.0.1",
- "through2": "^3.0.1",
- "winston-compat": "^0.1.5"
- },
- "engines": {
- "node": ">= 6.4.0"
- },
- "homepage": "https://github.com/winstonjs/winston#readme",
- "keywords": [
- "winston",
- "logger",
- "logging",
- "logs",
- "sysadmin",
- "bunyan",
- "pino",
- "loglevel",
- "tools",
- "json",
- "stream"
- ],
- "license": "MIT",
- "main": "./lib/winston",
- "maintainers": [
- {
- "name": "Jarrett Cruger",
- "email": "jcrugzz@gmail.com"
- },
- {
- "name": "Chris Alderson",
- "email": "chrisalderson@protonmail.com"
- },
- {
- "name": "David Hyde",
- "email": "dabh@stanford.edu"
- }
- ],
- "name": "winston",
- "repository": {
- "type": "git",
- "url": "git+https://github.com/winstonjs/winston.git"
- },
- "scripts": {
- "build": "rimraf dist && babel lib -d dist",
- "lint": "populist lib/*.js lib/winston/*.js lib/winston/**/*.js",
- "prepublishOnly": "npm run build",
- "pretest": "npm run lint",
- "test": "nyc --reporter=text --reporter lcov npm run test:mocha",
- "test:mocha": "mocha test/*.test.js test/**/*.test.js --exit"
- },
- "types": "./index.d.ts",
- "version": "3.3.3"
-}
+ return header;
+};
},{}],"platformClient":[function(require,module,exports){
(function (global,Buffer){(function (){
@@ -34968,326 +6048,9 @@ function isSlowBuffer (obj) {
return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))
}
-const winston = require('winston');
-
-const logLevels = {
- levels: {
- none: 0,
- error: 1,
- debug: 2,
- trace: 3,
- },
-};
-
-const logLevelEnum = {
- level: {
- LNone: 'none',
- LError: 'error',
- LDebug: 'debug',
- LTrace: 'trace',
- },
-};
-
-const logFormatEnum = {
- formats: {
- JSON: 'json',
- TEXT: 'text',
- },
-};
-
-class Logger {
- get logLevelEnum() {
- return logLevelEnum;
- }
-
- get logFormatEnum() {
- return logFormatEnum;
- }
-
- constructor() {
- this.log_level = logLevelEnum.level.LNone;
- this.log_format = logFormatEnum.formats.TEXT;
- this.log_to_console = true;
- this.log_file_path;
- this.log_response_body = false;
- this.log_request_body = false;
-
- this.setLogger();
- }
-
- createNewLogger() {
- this.logger = winston.createLogger({
- levels: logLevels.levels,
- level: this.log_level,
- });
- }
-
- setLogger() {
- this.createNewLogger();
- if (this.log_file_path && this.log_file_path !== '') {
- if (this.log_format === logFormatEnum.formats.JSON) {
- this.logger.add(new winston.transports.File({ format: winston.format.json(), filename: this.log_file_path }));
- } else {
- this.logger.add(
- new winston.transports.File({
- format: winston.format.combine(
- winston.format((info) => {
- info.level = info.level.toUpperCase();
- return info;
- })(),
- winston.format.simple()
- ),
- filename: this.log_file_path,
- })
- );
- }
- }
- if (this.log_to_console) {
- if (this.log_format === logFormatEnum.formats.JSON) {
- this.logger.add(new winston.transports.Console({ format: winston.format.json() }));
- } else {
- this.logger.add(
- new winston.transports.Console({
- format: winston.format.combine(
- winston.format((info) => {
- info.level = info.level.toUpperCase();
- return info;
- })(),
- winston.format.simple()
- ),
- })
- );
- }
- }
- }
-
- log(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody) {
- var content = this.formatLog(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody);
- if (this.logger.transports.length > 0) this.logger.log(level, content);
- }
-
- formatLog(level, statusCode, method, url, requestHeaders, responseHeaders, requestBody, responseBody) {
- var result;
- if (requestHeaders) requestHeaders['Authorization'] = '[REDACTED]';
- if (!this.log_request_body) requestBody = undefined;
- if (!this.log_response_body) responseBody = undefined;
- if (this.log_format && this.log_format === logFormatEnum.formats.JSON) {
- result = {
- level: level,
- date: new Date().toISOString(),
- method: method,
- url: decodeURIComponent(url),
- correlationId: responseHeaders ? (responseHeaders['inin-correlation-id'] ? responseHeaders['inin-correlation-id'] : '') : '',
- statusCode: statusCode,
- };
- if (requestHeaders) result.requestHeaders = requestHeaders;
- if (responseHeaders) result.responseHeaders = responseHeaders;
- if (requestBody) result.requestBody = requestBody;
- if (responseBody) result.responseBody = responseBody;
- } else {
- result = `${new Date().toISOString()}
-=== REQUEST ===
-${this.formatValue('URL', decodeURIComponent(url))}${this.formatValue('Method', method)}${this.formatValue(
- 'Headers',
- this.formatHeaderString(requestHeaders)
- )}${this.formatValue('Body', requestBody ? JSON.stringify(requestBody, null, 2) : '')}
-=== RESPONSE ===
-${this.formatValue('Status', statusCode)}${this.formatValue('Headers', this.formatHeaderString(responseHeaders))}${this.formatValue(
- 'CorrelationId',
- responseHeaders ? (responseHeaders['inin-correlation-id'] ? responseHeaders['inin-correlation-id'] : '') : ''
- )}${this.formatValue('Body', responseBody ? JSON.stringify(responseBody, null, 2) : '')}`;
- }
-
- return result;
- }
-
- formatHeaderString(headers) {
- var headerString = '';
- if (!headers) return headerString;
- for (const [key, value] of Object.entries(headers)) {
- headerString += `\n\t${key}: ${value}`;
- }
- return headerString;
- }
-
- formatValue(key, value) {
- if (!value || value === '' || value === '{}') return '';
- return `${key}: ${value}\n`;
- }
-
- getLogLevel(level) {
- switch (level) {
- case 'error':
- return logLevelEnum.level.LError;
- case 'debug':
- return logLevelEnum.level.LDebug;
- case 'trace':
- return logLevelEnum.level.LTrace;
- default:
- return logLevelEnum.level.LNone;
- }
- }
-
- getLogFormat(format) {
- switch (format) {
- case 'json':
- return logFormatEnum.formats.JSON;
- default:
- return logFormatEnum.formats.TEXT;
- }
- }
-}
-
-const ConfigParser = require('configparser');
-const os = require('os');
-const path = require('path');
-const fs = require('fs');
-
-class Configuration {
- /**
- * Singleton getter
- */
- get instance() {
- return Configuration.instance;
- }
-
- /**
- * Singleton setter
- */
- set instance(value) {
- Configuration.instance = value;
- }
-
- constructor() {
- if (!Configuration.instance) {
- Configuration.instance = this;
- }
-
- this.configPath = typeof window !== 'undefined' ? '' : path.join(os.homedir(), '.genesyscloudjavascript-guest', 'config');
- this.live_reload_config = true;
- this.host;
- this.environment;
- this.basePath;
- this.authUrl;
- this.config;
- this.logger = new Logger();
- this.setEnvironment();
- this.liveLoadConfig();
- }
-
- liveLoadConfig() {
- // If in browser, don't read config file, use default values
- if (typeof window !== 'undefined') {
- this.configPath = '';
- return;
- }
-
- this.updateConfigFromFile();
-
- if (this.live_reload_config && this.live_reload_config === true) {
- try {
- fs.watchFile(this.configPath, { persistent: false }, (eventType, filename) => {
- this.updateConfigFromFile();
- if (!this.live_reload_config) {
- fs.unwatchFile(this.configPath);
- }
- });
- } catch (err) {
- // do nothing
- }
- }
- }
-
- setConfigPath(path) {
- if (path && path !== this.configPath) {
- this.configPath = path;
- this.liveLoadConfig();
- }
- }
-
- updateConfigFromFile() {
- var configparser = new ConfigParser();
-
- try {
- configparser.read(this.configPath); // If no error catched, indicates it's INI format
- this.config = configparser;
- } catch (error) {
- if (error.name && error.name === 'MissingSectionHeaderError') {
- // Not INI format, see if it's JSON format
- var configData = fs.readFileSync(this.configPath, 'utf8');
- this.config = {
- _sections: JSON.parse(configData), // To match INI data format
- };
- }
- }
-
- if (this.config) this.updateConfigValues();
- }
-
- updateConfigValues() {
- this.logger.log_level = this.logger.getLogLevel(this.getConfigString('logging', 'log_level'));
- this.logger.log_format = this.logger.getLogFormat(this.getConfigString('logging', 'log_format'));
- this.logger.log_to_console =
- this.getConfigBoolean('logging', 'log_to_console') !== undefined
- ? this.getConfigBoolean('logging', 'log_to_console')
- : this.logger.log_to_console;
- this.logger.log_file_path =
- this.getConfigString('logging', 'log_file_path') !== undefined
- ? this.getConfigString('logging', 'log_file_path')
- : this.logger.log_file_path;
- this.logger.log_response_body =
- this.getConfigBoolean('logging', 'log_response_body') !== undefined
- ? this.getConfigBoolean('logging', 'log_response_body')
- : this.logger.log_response_body;
- this.logger.log_request_body =
- this.getConfigBoolean('logging', 'log_request_body') !== undefined
- ? this.getConfigBoolean('logging', 'log_request_body')
- : this.logger.log_request_body;
- this.live_reload_config =
- this.getConfigBoolean('general', 'live_reload_config') !== undefined
- ? this.getConfigBoolean('general', 'live_reload_config')
- : this.live_reload_config;
- this.host = this.getConfigString('general', 'host') !== undefined ? this.getConfigString('general', 'host') : this.host;
-
- this.setEnvironment();
-
- // Update logging configs
- this.logger.setLogger();
- }
-
- setEnvironment(env) {
- // Default value
- if (env) this.environment = env;
- else this.environment = this.host ? this.host : 'mypurecloud.com';
-
- // Strip trailing slash
- this.environment = this.environment.replace(/\/+$/, '');
-
- // Strip protocol and subdomain
- if (this.environment.startsWith('https://')) this.environment = this.environment.substring(8);
- if (this.environment.startsWith('http://')) this.environment = this.environment.substring(7);
- if (this.environment.startsWith('api.')) this.environment = this.environment.substring(4);
-
- this.basePath = `https://api.${this.environment}`;
- this.authUrl = `https://login.${this.environment}`;
- }
-
- getConfigString(section, key) {
- if (this.config._sections[section]) return this.config._sections[section][key];
- }
-
- getConfigBoolean(section, key) {
- if (this.config._sections[section] && this.config._sections[section][key] !== undefined) {
- if (typeof this.config._sections[section][key] === 'string') {
- return this.config._sections[section][key] === 'true';
- } else return this.config._sections[section][key];
- }
- }
-}
-
/**
* @module purecloud-guest-chat-client/ApiClient
- * @version 7.0.0
+ * @version 7.1.0
*/
class ApiClient {
/**
@@ -35364,11 +6127,6 @@ class ApiClient {
this.hasLocalStorage = false;
}
- /**
- * Create configuration instance for ApiClient and prepare logger.
- */
- this.config = new Configuration();
-
/**
* The base URL against which to resolve every API call's (relative) path.
* @type {String}
@@ -35408,6 +6166,16 @@ class ApiClient {
if (typeof(window) !== 'undefined') window.ApiClient = this;
}
+ /**
+ * @description Sets the debug log to enable debug logging
+ * @param {log} debugLog - In most cases use `console.log`
+ * @param {integer} maxLines - (optional) The max number of lines to write to the log. Must be > 0.
+ */
+ setDebugLog(debugLog, maxLines) {
+ this.debugLog = debugLog;
+ this.debugLogMaxLines = (maxLines && maxLines > 0) ? maxLines : undefined;
+ }
+
/**
* @description If set to `true`, the response object will contain additional information about the HTTP response. When `false` (default) only the body object will be returned.
* @param {boolean} returnExtended - `true` to return extended responses
@@ -35424,6 +6192,7 @@ class ApiClient {
setPersistSettings(doPersist, prefix) {
this.persistSettings = doPersist;
this.settingsPrefix = prefix ? prefix.replace(/\W+/g, '_') : 'purecloud';
+ this._debugTrace(`this.settingsPrefix=${this.settingsPrefix}`);
}
/**
@@ -35448,6 +6217,7 @@ class ApiClient {
// Ensure we can access local storage
if (!this.hasLocalStorage) {
+ this._debugTrace('Warning: Cannot access local storage. Settings will not be saved.');
return;
}
@@ -35457,6 +6227,7 @@ class ApiClient {
// Save updated auth data
localStorage.setItem(`${this.settingsPrefix}_auth_data`, JSON.stringify(tempData));
+ this._debugTrace('Auth data saved to local storage');
} catch (e) {
console.error(e);
}
@@ -35471,6 +6242,7 @@ class ApiClient {
// Ensure we can access local storage
if (!this.hasLocalStorage) {
+ this._debugTrace('Warning: Cannot access local storage. Settings will not be loaded.');
return;
}
@@ -35490,7 +6262,24 @@ class ApiClient {
* @param {string} environment - (Optional, default "mypurecloud.com") Environment the session use, e.g. mypurecloud.ie, mypurecloud.com.au, etc.
*/
setEnvironment(environment) {
- this.config.setEnvironment(environment);
+ if (!environment)
+ environment = 'mypurecloud.com';
+
+ // Strip trailing slash
+ environment = environment.replace(/\/+$/, '');
+
+ // Strip protocol and subdomain
+ if (environment.startsWith('https://'))
+ environment = environment.substring(8);
+ if (environment.startsWith('http://'))
+ environment = environment.substring(7);
+ if (environment.startsWith('api.'))
+ environment = environment.substring(4);
+
+ // Set vars
+ this.environment = environment;
+ this.basePath = `https://api.${environment}`;
+ this.authUrl = `https://login.${environment}`;
}
/**
@@ -35547,7 +6336,7 @@ class ApiClient {
*/
_buildAuthUrl(path, query) {
if (!query) query = {};
- return Object.keys(query).reduce((url, key) => !query[key] ? url : `${url}&${key}=${query[key]}`, `${this.config.authUrl}/${path}?`);
+ return Object.keys(query).reduce((url, key) => !query[key] ? url : `${url}&${key}=${query[key]}`, `${this.authUrl}/${path}?`);
}
/**
@@ -35576,7 +6365,7 @@ class ApiClient {
if (!path.match(/^\//)) {
path = `/${path}`;
}
- var url = this.config.basePath + path;
+ var url = this.basePath + path;
url = url.replace(/\{([\w-]+)\}/g, (fullMatch, key) => {
var value;
if (pathParams.hasOwnProperty(key)) {
@@ -35754,6 +6543,23 @@ class ApiClient {
request.proxy(this.proxy);
}
+ if(this.debugLog){
+ var trace = `[REQUEST] ${httpMethod} ${url}`;
+ if(pathParams && Object.keys(pathParams).count > 0 && pathParams[Object.keys(pathParams)[0]]){
+ trace += `\nPath Params: ${JSON.stringify(pathParams)}`;
+ }
+
+ if(queryParams && Object.keys(queryParams).count > 0 && queryParams[Object.keys(queryParams)[0]]){
+ trace += `\nQuery Params: ${JSON.stringify(queryParams)}`;
+ }
+
+ if(bodyParam){
+ trace += `\nnBody: ${JSON.stringify(bodyParam)}`;
+ }
+
+ this._debugTrace(trace);
+ }
+
// apply authentications
this.applyAuthToRequest(request, authNames);
@@ -35762,7 +6568,7 @@ class ApiClient {
// set header parameters
request.set(this.defaultHeaders).set(this.normalizeParams(headerParams));
- //request.set({ 'purecloud-sdk': '7.0.0' });
+ //request.set({ 'purecloud-sdk': '7.1.0' });
// set request timeout
request.timeout(this.timeout);
@@ -35824,22 +6630,23 @@ class ApiClient {
} : response.body ? response.body : response.text;
// Debug logging
- this.config.logger.log('trace', response.statusCode, httpMethod, url, request.header, response.headers, bodyParam, undefined);
- this.config.logger.log('debug', response.statusCode, httpMethod, url, request.header, undefined, bodyParam, undefined);
+ if (this.debugLog) {
+ var trace = `[RESPONSE] ${response.status}: ${httpMethod} ${url}`;
+ if (response.headers)
+ trace += `\ninin-correlation-id: ${response.headers['inin-correlation-id']}`;
+ if (response.body)
+ trace += `\nBody: ${JSON.stringify(response.body,null,2)}`;
+
+ // Log trace message
+ this._debugTrace(trace);
+
+ // Log stack trace
+ if (error)
+ this._debugTrace(error);
+ }
// Resolve promise
if (error) {
- // Log error
- this.config.logger.log(
- 'error',
- response.statusCode,
- httpMethod,
- url,
- request.header,
- response.headers,
- bodyParam,
- response.body
- );
reject(data);
} else {
resolve(data);
@@ -35847,13 +6654,46 @@ class ApiClient {
});
});
}
+
+ /**
+ * @description Parses an ISO-8601 string representation of a date value.
+ * @param {String} str The date value as a string.
+ * @returns {Date} The parsed date object.
+ */
+ parseDate(str) {
+ return new Date(str.replace(/T/i, ' '));
+ }
+
+ /**
+ * @description Logs to the debug log
+ * @param {String} str The date value as a string.
+ * @returns {Date} The parsed date object.
+ */
+ _debugTrace(trace) {
+ if (!this.debugLog) return;
+
+ if (typeof(trace) === 'string') {
+ // Truncate
+ var truncTrace = '';
+ var lines = trace.split('\n');
+ if (this.debugLogMaxLines && lines.length > this.debugLogMaxLines) {
+ for (var i = 0; i < this.debugLogMaxLines; i++) {
+ truncTrace += `${lines[i]}\n`;
+ }
+ truncTrace += '...response truncated...';
+ trace = truncTrace;
+ }
+ }
+
+ this.debugLog(trace);
+ }
}
class WebChatApi {
/**
* WebChat service.
* @module purecloud-guest-chat-client/api/WebChatApi
- * @version 7.0.0
+ * @version 7.1.0
*/
/**
@@ -36232,7 +7072,7 @@ class WebChatApi {
*
*
* @module purecloud-guest-chat-client/index
- * @version 7.0.0
+ * @version 7.1.0
*/
class platformClient {
constructor() {
@@ -36260,4 +7100,4 @@ var index = new platformClient();
module.exports = index;
}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
-},{"buffer":10,"configparser":132,"fs":1,"os":20,"path":32,"superagent":179,"winston":194}]},{},[]);
+},{"buffer":2,"superagent":6}]},{},[]);
diff --git a/build/dist/web-cjs/purecloud-guest-chat-client.min.js b/build/dist/web-cjs/purecloud-guest-chat-client.min.js
index 4a96f600..819a92e6 100644
--- a/build/dist/web-cjs/purecloud-guest-chat-client.min.js
+++ b/build/dist/web-cjs/purecloud-guest-chat-client.min.js
@@ -1 +1 @@
-require=function(){return function e(t,r,n){function i(a,s){if(!r[a]){if(!t[a]){var u="function"==typeof require&&require;if(!s&&u)return u(a,!0);if(o)return o(a,!0);var l=new Error("Cannot find module '"+a+"'");throw l.code="MODULE_NOT_FOUND",l}var c=r[a]={exports:{}};t[a][0].call(c.exports,function(e){return i(t[a][1][e]||e)},c,c.exports,e,t,r,n)}return r[a].exports}for(var o="function"==typeof require&&require,a=0;a=0;l--)if(c[l]!==f[l])return!1;for(l=c.length-1;l>=0;l--)if(s=c[l],!v(e[s],t[s],r,n))return!1;return!0}(e,t,r,n))}return r?e===t:e==t}function _(e){return"[object Arguments]"==Object.prototype.toString.call(e)}function w(e,t){if(!e||!t)return!1;if("[object RegExp]"==Object.prototype.toString.call(t))return t.test(e);try{if(e instanceof t)return!0}catch(e){}return!Error.isPrototypeOf(t)&&!0===t.call({},e)}function E(e,t,r,n){var i;if("function"!=typeof t)throw new TypeError('"block" argument must be a function');"string"==typeof r&&(n=r,r=null),i=function(e){var t;try{e()}catch(e){t=e}return t}(t),n=(r&&r.name?" ("+r.name+").":".")+(n?" "+n:"."),e&&!i&&y(i,r,"Missing expected exception"+n);var o="string"==typeof n,s=!e&&a.isError(i),u=!e&&i&&!r;if((s&&o&&w(i,r)||u)&&y(i,r,"Got unwanted exception"+n),e&&i&&r&&!w(i,r)||!e&&i)throw i}h.AssertionError=function(e){var t;this.name="AssertionError",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,e.message?(this.message=e.message,this.generatedMessage=!1):(this.message=g(m((t=this).actual),128)+" "+t.operator+" "+g(m(t.expected),128),this.generatedMessage=!0);var r=e.stackStartFunction||y;if(Error.captureStackTrace)Error.captureStackTrace(this,r);else{var n=new Error;if(n.stack){var i=n.stack,o=d(r),a=i.indexOf("\n"+o);if(a>=0){var s=i.indexOf("\n",a+1);i=i.substring(s+1)}this.stack=i}}},a.inherits(h.AssertionError,Error),h.fail=y,h.ok=b,h.equal=function(e,t,r){e!=t&&y(e,t,r,"==",h.equal)},h.notEqual=function(e,t,r){e==t&&y(e,t,r,"!=",h.notEqual)},h.deepEqual=function(e,t,r){v(e,t,!1)||y(e,t,r,"deepEqual",h.deepEqual)},h.deepStrictEqual=function(e,t,r){v(e,t,!0)||y(e,t,r,"deepStrictEqual",h.deepStrictEqual)},h.notDeepEqual=function(e,t,r){v(e,t,!1)&&y(e,t,r,"notDeepEqual",h.notDeepEqual)},h.notDeepStrictEqual=function e(t,r,n){v(t,r,!0)&&y(t,r,n,"notDeepStrictEqual",e)},h.strictEqual=function(e,t,r){e!==t&&y(e,t,r,"===",h.strictEqual)},h.notStrictEqual=function(e,t,r){e===t&&y(e,t,r,"!==",h.notStrictEqual)},h.throws=function(e,t,r){E(!0,e,t,r)},h.doesNotThrow=function(e,t,r){E(!1,e,t,r)},h.ifError=function(e){if(e)throw e},h.strict=n(function e(t,r){t||y(t,!0,r,"==",e)},h,{equal:h.strictEqual,deepEqual:h.deepStrictEqual,notEqual:h.notStrictEqual,notDeepEqual:h.notDeepStrictEqual}),h.strict.strict=h.strict;var k=Object.keys||function(e){var t=[];for(var r in e)s.call(e,r)&&t.push(r);return t}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"object-assign":19,"util/":5}],3:[function(e,t,r){"function"==typeof Object.create?t.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}},{}],4:[function(e,t,r){t.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},{}],5:[function(e,t,r){(function(t,n){(function(){var i=/%[sdj%]/g;r.format=function(e){if(!y(e)){for(var t=[],r=0;r=o)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(e){return"[Circular]"}default:return e}}),u=n[r];r=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),d(t)?n.showHidden=t:t&&r._extend(n,t),b(n.showHidden)&&(n.showHidden=!1),b(n.depth)&&(n.depth=2),b(n.colors)&&(n.colors=!1),b(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=u),c(n,e,n.depth)}function u(e,t){var r=s.styles[t];return r?"["+s.colors[r][0]+"m"+e+"["+s.colors[r][1]+"m":e}function l(e,t){return e}function c(e,t,n){if(e.customInspect&&t&&k(t.inspect)&&t.inspect!==r.inspect&&(!t.constructor||t.constructor.prototype!==t)){var i=t.inspect(n,e);return y(i)||(i=c(e,i,n)),i}var o=function(e,t){if(b(t))return e.stylize("undefined","undefined");if(y(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(m(t))return e.stylize(""+t,"number");if(d(t))return e.stylize(""+t,"boolean");if(g(t))return e.stylize("null","null")}(e,t);if(o)return o;var a=Object.keys(t),s=function(e){var t={};return e.forEach(function(e,r){t[e]=!0}),t}(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(t)),E(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return f(t);if(0===a.length){if(k(t)){var u=t.name?": "+t.name:"";return e.stylize("[Function"+u+"]","special")}if(v(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(w(t))return e.stylize(Date.prototype.toString.call(t),"date");if(E(t))return f(t)}var l,_="",S=!1,x=["{","}"];(p(t)&&(S=!0,x=["[","]"]),k(t))&&(_=" [Function"+(t.name?": "+t.name:"")+"]");return v(t)&&(_=" "+RegExp.prototype.toString.call(t)),w(t)&&(_=" "+Date.prototype.toUTCString.call(t)),E(t)&&(_=" "+f(t)),0!==a.length||S&&0!=t.length?n<0?v(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),l=S?function(e,t,r,n,i){for(var o=[],a=0,s=t.length;a=0&&0,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60)return r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1];return r[0]+t+" "+e.join(", ")+" "+r[1]}(l,_,x)):x[0]+_+x[1]}function f(e){return"["+Error.prototype.toString.call(e)+"]"}function h(e,t,r,n,i,o){var a,s,u;if((u=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]}).get?s=u.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):u.set&&(s=e.stylize("[Setter]","special")),T(n,i)||(a="["+i+"]"),s||(e.seen.indexOf(u.value)<0?(s=g(r)?c(e,u.value,null):c(e,u.value,r-1)).indexOf("\n")>-1&&(s=o?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n")):s=e.stylize("[Circular]","special")),b(a)){if(o&&i.match(/^\d+$/))return s;(a=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function p(e){return Array.isArray(e)}function d(e){return"boolean"==typeof e}function g(e){return null===e}function m(e){return"number"==typeof e}function y(e){return"string"==typeof e}function b(e){return void 0===e}function v(e){return _(e)&&"[object RegExp]"===S(e)}function _(e){return"object"==typeof e&&null!==e}function w(e){return _(e)&&"[object Date]"===S(e)}function E(e){return _(e)&&("[object Error]"===S(e)||e instanceof Error)}function k(e){return"function"==typeof e}function S(e){return Object.prototype.toString.call(e)}function x(e){return e<10?"0"+e.toString(10):e.toString(10)}r.debuglog=function(e){if(b(o)&&(o=t.env.NODE_DEBUG||""),e=e.toUpperCase(),!a[e])if(new RegExp("\\b"+e+"\\b","i").test(o)){var n=t.pid;a[e]=function(){var t=r.format.apply(r,arguments);console.error("%s %d: %s",e,n,t)}}else a[e]=function(){};return a[e]},r.inspect=s,s.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]},s.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},r.isArray=p,r.isBoolean=d,r.isNull=g,r.isNullOrUndefined=function(e){return null==e},r.isNumber=m,r.isString=y,r.isSymbol=function(e){return"symbol"==typeof e},r.isUndefined=b,r.isRegExp=v,r.isObject=_,r.isDate=w,r.isError=E,r.isFunction=k,r.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},r.isBuffer=e("./support/isBuffer");var O=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function T(e,t){return Object.prototype.hasOwnProperty.call(e,t)}r.log=function(){var e,t;console.log("%s - %s",(e=new Date,t=[x(e.getHours()),x(e.getMinutes()),x(e.getSeconds())].join(":"),[e.getDate(),O[e.getMonth()],t].join(" ")),r.format.apply(r,arguments))},r.inherits=e("inherits"),r._extend=function(e,t){if(!t||!_(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e}}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":4,_process:34,inherits:3}],6:[function(e,t,r){"use strict";r.byteLength=function(e){var t=l(e),r=t[0],n=t[1];return 3*(r+n)/4-n},r.toByteArray=function(e){var t,r,n=l(e),a=n[0],s=n[1],u=new o(function(e,t,r){return 3*(t+r)/4-r}(0,a,s)),c=0,f=s>0?a-4:a;for(r=0;r>16&255,u[c++]=t>>8&255,u[c++]=255&t;2===s&&(t=i[e.charCodeAt(r)]<<2|i[e.charCodeAt(r+1)]>>4,u[c++]=255&t);1===s&&(t=i[e.charCodeAt(r)]<<10|i[e.charCodeAt(r+1)]<<4|i[e.charCodeAt(r+2)]>>2,u[c++]=t>>8&255,u[c++]=255&t);return u},r.fromByteArray=function(e){for(var t,r=e.length,i=r%3,o=[],a=0,s=r-i;as?s:a+16383));1===i?(t=e[r-1],o.push(n[t>>2]+n[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],o.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return o.join("")};for(var n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,u=a.length;s0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function c(e,t,r){for(var i,o,a=[],s=t;s>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return a.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},{}],7:[function(e,t,r){arguments[4][1][0].apply(r,arguments)},{dup:1}],8:[function(e,t,r){(function(t,n){(function(){"use strict";var i=e("assert"),o=e("pako/lib/zlib/zstream"),a=e("pako/lib/zlib/deflate.js"),s=e("pako/lib/zlib/inflate.js"),u=e("pako/lib/zlib/constants");for(var l in u)r[l]=u[l];r.NONE=0,r.DEFLATE=1,r.INFLATE=2,r.GZIP=3,r.GUNZIP=4,r.DEFLATERAW=5,r.INFLATERAW=6,r.UNZIP=7;function c(e){if("number"!=typeof e||er.UNZIP)throw new TypeError("Bad argument");this.dictionary=null,this.err=0,this.flush=0,this.init_done=!1,this.level=0,this.memLevel=0,this.mode=e,this.strategy=0,this.windowBits=0,this.write_in_progress=!1,this.pending_close=!1,this.gzip_id_bytes_read=0}c.prototype.close=function(){this.write_in_progress?this.pending_close=!0:(this.pending_close=!1,i(this.init_done,"close before init"),i(this.mode<=r.UNZIP),this.mode===r.DEFLATE||this.mode===r.GZIP||this.mode===r.DEFLATERAW?a.deflateEnd(this.strm):this.mode!==r.INFLATE&&this.mode!==r.GUNZIP&&this.mode!==r.INFLATERAW&&this.mode!==r.UNZIP||s.inflateEnd(this.strm),this.mode=r.NONE,this.dictionary=null)},c.prototype.write=function(e,t,r,n,i,o,a){return this._write(!0,e,t,r,n,i,o,a)},c.prototype.writeSync=function(e,t,r,n,i,o,a){return this._write(!1,e,t,r,n,i,o,a)},c.prototype._write=function(e,o,a,s,u,l,c,f){if(i.equal(arguments.length,8),i(this.init_done,"write before init"),i(this.mode!==r.NONE,"already finalized"),i.equal(!1,this.write_in_progress,"write already in progress"),i.equal(!1,this.pending_close,"close is pending"),this.write_in_progress=!0,i.equal(!1,void 0===o,"must provide flush value"),this.write_in_progress=!0,o!==r.Z_NO_FLUSH&&o!==r.Z_PARTIAL_FLUSH&&o!==r.Z_SYNC_FLUSH&&o!==r.Z_FULL_FLUSH&&o!==r.Z_FINISH&&o!==r.Z_BLOCK)throw new Error("Invalid flush value");if(null==a&&(a=n.alloc(0),u=0,s=0),this.strm.avail_in=u,this.strm.input=a,this.strm.next_in=s,this.strm.avail_out=f,this.strm.output=l,this.strm.next_out=c,this.flush=o,!e)return this._process(),this._checkError()?this._afterSync():void 0;var h=this;return t.nextTick(function(){h._process(),h._after()}),this},c.prototype._afterSync=function(){var e=this.strm.avail_out,t=this.strm.avail_in;return this.write_in_progress=!1,[t,e]},c.prototype._process=function(){var e=null;switch(this.mode){case r.DEFLATE:case r.GZIP:case r.DEFLATERAW:this.err=a.deflate(this.strm,this.flush);break;case r.UNZIP:switch(this.strm.avail_in>0&&(e=this.strm.next_in),this.gzip_id_bytes_read){case 0:if(null===e)break;if(31!==this.strm.input[e]){this.mode=r.INFLATE;break}if(this.gzip_id_bytes_read=1,e++,1===this.strm.avail_in)break;case 1:if(null===e)break;139===this.strm.input[e]?(this.gzip_id_bytes_read=2,this.mode=r.GUNZIP):this.mode=r.INFLATE;break;default:throw new Error("invalid number of gzip magic number bytes read")}case r.INFLATE:case r.GUNZIP:case r.INFLATERAW:for(this.err=s.inflate(this.strm,this.flush),this.err===r.Z_NEED_DICT&&this.dictionary&&(this.err=s.inflateSetDictionary(this.strm,this.dictionary),this.err===r.Z_OK?this.err=s.inflate(this.strm,this.flush):this.err===r.Z_DATA_ERROR&&(this.err=r.Z_NEED_DICT));this.strm.avail_in>0&&this.mode===r.GUNZIP&&this.err===r.Z_STREAM_END&&0!==this.strm.next_in[0];)this.reset(),this.err=s.inflate(this.strm,this.flush);break;default:throw new Error("Unknown mode "+this.mode)}},c.prototype._checkError=function(){switch(this.err){case r.Z_OK:case r.Z_BUF_ERROR:if(0!==this.strm.avail_out&&this.flush===r.Z_FINISH)return this._error("unexpected end of file"),!1;break;case r.Z_STREAM_END:break;case r.Z_NEED_DICT:return null==this.dictionary?this._error("Missing dictionary"):this._error("Bad dictionary"),!1;default:return this._error("Zlib error"),!1}return!0},c.prototype._after=function(){if(this._checkError()){var e=this.strm.avail_out,t=this.strm.avail_in;this.write_in_progress=!1,this.callback(t,e),this.pending_close&&this.close()}},c.prototype._error=function(e){this.strm.msg&&(e=this.strm.msg),this.onerror(e,this.err),this.write_in_progress=!1,this.pending_close&&this.close()},c.prototype.init=function(e,t,n,o,a){i(4===arguments.length||5===arguments.length,"init(windowBits, level, memLevel, strategy, [dictionary])"),i(e>=8&&e<=15,"invalid windowBits"),i(t>=-1&&t<=9,"invalid compression level"),i(n>=1&&n<=9,"invalid memlevel"),i(o===r.Z_FILTERED||o===r.Z_HUFFMAN_ONLY||o===r.Z_RLE||o===r.Z_FIXED||o===r.Z_DEFAULT_STRATEGY,"invalid strategy"),this._init(t,e,n,o,a),this._setDictionary()},c.prototype.params=function(){throw new Error("deflateParams Not supported")},c.prototype.reset=function(){this._reset(),this._setDictionary()},c.prototype._init=function(e,t,n,i,u){switch(this.level=e,this.windowBits=t,this.memLevel=n,this.strategy=i,this.flush=r.Z_NO_FLUSH,this.err=r.Z_OK,this.mode!==r.GZIP&&this.mode!==r.GUNZIP||(this.windowBits+=16),this.mode===r.UNZIP&&(this.windowBits+=32),this.mode!==r.DEFLATERAW&&this.mode!==r.INFLATERAW||(this.windowBits=-1*this.windowBits),this.strm=new o,this.mode){case r.DEFLATE:case r.GZIP:case r.DEFLATERAW:this.err=a.deflateInit2(this.strm,this.level,r.Z_DEFLATED,this.windowBits,this.memLevel,this.strategy);break;case r.INFLATE:case r.GUNZIP:case r.INFLATERAW:case r.UNZIP:this.err=s.inflateInit2(this.strm,this.windowBits);break;default:throw new Error("Unknown mode "+this.mode)}this.err!==r.Z_OK&&this._error("Init error"),this.dictionary=u,this.write_in_progress=!1,this.init_done=!0},c.prototype._setDictionary=function(){if(null!=this.dictionary){switch(this.err=r.Z_OK,this.mode){case r.DEFLATE:case r.DEFLATERAW:this.err=a.deflateSetDictionary(this.strm,this.dictionary)}this.err!==r.Z_OK&&this._error("Failed to set dictionary")}},c.prototype._reset=function(){switch(this.err=r.Z_OK,this.mode){case r.DEFLATE:case r.DEFLATERAW:case r.GZIP:this.err=a.deflateReset(this.strm);break;case r.INFLATE:case r.INFLATERAW:case r.GUNZIP:this.err=s.inflateReset(this.strm)}this.err!==r.Z_OK&&this._error("Failed to reset stream")},r.Zlib=c}).call(this)}).call(this,e("_process"),e("buffer").Buffer)},{_process:34,assert:2,buffer:10,"pako/lib/zlib/constants":23,"pako/lib/zlib/deflate.js":25,"pako/lib/zlib/inflate.js":27,"pako/lib/zlib/zstream":31}],9:[function(e,t,r){(function(t){(function(){"use strict";var n=e("buffer").Buffer,i=e("stream").Transform,o=e("./binding"),a=e("util"),s=e("assert").ok,u=e("buffer").kMaxLength,l="Cannot create final Buffer. It would be larger than 0x"+u.toString(16)+" bytes";o.Z_MIN_WINDOWBITS=8,o.Z_MAX_WINDOWBITS=15,o.Z_DEFAULT_WINDOWBITS=15,o.Z_MIN_CHUNK=64,o.Z_MAX_CHUNK=1/0,o.Z_DEFAULT_CHUNK=16384,o.Z_MIN_MEMLEVEL=1,o.Z_MAX_MEMLEVEL=9,o.Z_DEFAULT_MEMLEVEL=8,o.Z_MIN_LEVEL=-1,o.Z_MAX_LEVEL=9,o.Z_DEFAULT_LEVEL=o.Z_DEFAULT_COMPRESSION;for(var c=Object.keys(o),f=0;f=u?a=new RangeError(l):t=n.concat(i,o),i=[],e.close(),r(a,t)}e.on("error",function(t){e.removeListener("end",s),e.removeListener("readable",a),r(t)}),e.on("end",s),e.end(t),a()}function b(e,t){if("string"==typeof t&&(t=n.from(t)),!n.isBuffer(t))throw new TypeError("Not a string or buffer");var r=e._finishFlushFlag;return e._processChunk(t,r)}function v(e){if(!(this instanceof v))return new v(e);T.call(this,e,o.DEFLATE)}function _(e){if(!(this instanceof _))return new _(e);T.call(this,e,o.INFLATE)}function w(e){if(!(this instanceof w))return new w(e);T.call(this,e,o.GZIP)}function E(e){if(!(this instanceof E))return new E(e);T.call(this,e,o.GUNZIP)}function k(e){if(!(this instanceof k))return new k(e);T.call(this,e,o.DEFLATERAW)}function S(e){if(!(this instanceof S))return new S(e);T.call(this,e,o.INFLATERAW)}function x(e){if(!(this instanceof x))return new x(e);T.call(this,e,o.UNZIP)}function O(e){return e===o.Z_NO_FLUSH||e===o.Z_PARTIAL_FLUSH||e===o.Z_SYNC_FLUSH||e===o.Z_FULL_FLUSH||e===o.Z_FINISH||e===o.Z_BLOCK}function T(e,t){var a=this;if(this._opts=e=e||{},this._chunkSize=e.chunkSize||r.Z_DEFAULT_CHUNK,i.call(this,e),e.flush&&!O(e.flush))throw new Error("Invalid flush flag: "+e.flush);if(e.finishFlush&&!O(e.finishFlush))throw new Error("Invalid flush flag: "+e.finishFlush);if(this._flushFlag=e.flush||o.Z_NO_FLUSH,this._finishFlushFlag=void 0!==e.finishFlush?e.finishFlush:o.Z_FINISH,e.chunkSize&&(e.chunkSizer.Z_MAX_CHUNK))throw new Error("Invalid chunk size: "+e.chunkSize);if(e.windowBits&&(e.windowBitsr.Z_MAX_WINDOWBITS))throw new Error("Invalid windowBits: "+e.windowBits);if(e.level&&(e.levelr.Z_MAX_LEVEL))throw new Error("Invalid compression level: "+e.level);if(e.memLevel&&(e.memLevelr.Z_MAX_MEMLEVEL))throw new Error("Invalid memLevel: "+e.memLevel);if(e.strategy&&e.strategy!=r.Z_FILTERED&&e.strategy!=r.Z_HUFFMAN_ONLY&&e.strategy!=r.Z_RLE&&e.strategy!=r.Z_FIXED&&e.strategy!=r.Z_DEFAULT_STRATEGY)throw new Error("Invalid strategy: "+e.strategy);if(e.dictionary&&!n.isBuffer(e.dictionary))throw new Error("Invalid dictionary: it should be a Buffer instance");this._handle=new o.Zlib(t);var s=this;this._hadError=!1,this._handle.onerror=function(e,t){j(s),s._hadError=!0;var n=new Error(e);n.errno=t,n.code=r.codes[t],s.emit("error",n)};var u=r.Z_DEFAULT_COMPRESSION;"number"==typeof e.level&&(u=e.level);var l=r.Z_DEFAULT_STRATEGY;"number"==typeof e.strategy&&(l=e.strategy),this._handle.init(e.windowBits||r.Z_DEFAULT_WINDOWBITS,u,e.memLevel||r.Z_DEFAULT_MEMLEVEL,l,e.dictionary),this._buffer=n.allocUnsafe(this._chunkSize),this._offset=0,this._level=u,this._strategy=l,this.once("end",this.close),Object.defineProperty(this,"_closed",{get:function(){return!a._handle},configurable:!0,enumerable:!0})}function j(e,r){r&&t.nextTick(r),e._handle&&(e._handle.close(),e._handle=null)}function R(e){e.emit("close")}Object.defineProperty(r,"codes",{enumerable:!0,value:Object.freeze(p),writable:!1}),r.Deflate=v,r.Inflate=_,r.Gzip=w,r.Gunzip=E,r.DeflateRaw=k,r.InflateRaw=S,r.Unzip=x,r.createDeflate=function(e){return new v(e)},r.createInflate=function(e){return new _(e)},r.createDeflateRaw=function(e){return new k(e)},r.createInflateRaw=function(e){return new S(e)},r.createGzip=function(e){return new w(e)},r.createGunzip=function(e){return new E(e)},r.createUnzip=function(e){return new x(e)},r.deflate=function(e,t,r){return"function"==typeof t&&(r=t,t={}),y(new v(t),e,r)},r.deflateSync=function(e,t){return b(new v(t),e)},r.gzip=function(e,t,r){return"function"==typeof t&&(r=t,t={}),y(new w(t),e,r)},r.gzipSync=function(e,t){return b(new w(t),e)},r.deflateRaw=function(e,t,r){return"function"==typeof t&&(r=t,t={}),y(new k(t),e,r)},r.deflateRawSync=function(e,t){return b(new k(t),e)},r.unzip=function(e,t,r){return"function"==typeof t&&(r=t,t={}),y(new x(t),e,r)},r.unzipSync=function(e,t){return b(new x(t),e)},r.inflate=function(e,t,r){return"function"==typeof t&&(r=t,t={}),y(new _(t),e,r)},r.inflateSync=function(e,t){return b(new _(t),e)},r.gunzip=function(e,t,r){return"function"==typeof t&&(r=t,t={}),y(new E(t),e,r)},r.gunzipSync=function(e,t){return b(new E(t),e)},r.inflateRaw=function(e,t,r){return"function"==typeof t&&(r=t,t={}),y(new S(t),e,r)},r.inflateRawSync=function(e,t){return b(new S(t),e)},a.inherits(T,i),T.prototype.params=function(e,n,i){if(er.Z_MAX_LEVEL)throw new RangeError("Invalid compression level: "+e);if(n!=r.Z_FILTERED&&n!=r.Z_HUFFMAN_ONLY&&n!=r.Z_RLE&&n!=r.Z_FIXED&&n!=r.Z_DEFAULT_STRATEGY)throw new TypeError("Invalid strategy: "+n);if(this._level!==e||this._strategy!==n){var a=this;this.flush(o.Z_SYNC_FLUSH,function(){s(a._handle,"zlib binding closed"),a._handle.params(e,n),a._hadError||(a._level=e,a._strategy=n,i&&i())})}else t.nextTick(i)},T.prototype.reset=function(){return s(this._handle,"zlib binding closed"),this._handle.reset()},T.prototype._flush=function(e){this._transform(n.alloc(0),"",e)},T.prototype.flush=function(e,r){var i=this,a=this._writableState;("function"==typeof e||void 0===e&&!r)&&(r=e,e=o.Z_FULL_FLUSH),a.ended?r&&t.nextTick(r):a.ending?r&&this.once("end",r):a.needDrain?r&&this.once("drain",function(){return i.flush(e,r)}):(this._flushFlag=e,this.write(n.alloc(0),"",r))},T.prototype.close=function(e){j(this,e),t.nextTick(R,this)},T.prototype._transform=function(e,t,r){var i,a=this._writableState,s=(a.ending||a.ended)&&(!e||a.length===e.length);return null===e||n.isBuffer(e)?this._handle?(s?i=this._finishFlushFlag:(i=this._flushFlag,e.length>=a.length&&(this._flushFlag=this._opts.flush||o.Z_NO_FLUSH)),void this._processChunk(e,i,r)):r(new Error("zlib binding closed")):r(new Error("invalid input"))},T.prototype._processChunk=function(e,t,r){var i=e&&e.length,o=this._chunkSize-this._offset,a=0,c=this,f="function"==typeof r;if(!f){var h,p=[],d=0;this.on("error",function(e){h=e}),s(this._handle,"zlib binding closed");do{var g=this._handle.writeSync(t,e,a,i,this._buffer,this._offset,o)}while(!this._hadError&&b(g[0],g[1]));if(this._hadError)throw h;if(d>=u)throw j(this),new RangeError(l);var m=n.concat(p,d);return j(this),m}s(this._handle,"zlib binding closed");var y=this._handle.write(t,e,a,i,this._buffer,this._offset,o);function b(u,l){if(this&&(this.buffer=null,this.callback=null),!c._hadError){var h=o-l;if(s(h>=0,"have should not go down"),h>0){var g=c._buffer.slice(c._offset,c._offset+h);c._offset+=h,f?c.push(g):(p.push(g),d+=g.length)}if((0===l||c._offset>=c._chunkSize)&&(o=c._chunkSize,c._offset=0,c._buffer=n.allocUnsafe(c._chunkSize)),0===l){if(a+=i-u,i=u,!f)return!0;var m=c._handle.write(t,e,a,i,c._buffer,c._offset,c._chunkSize);return m.callback=b,void(m.buffer=e)}if(!f)return!1;r()}}y.buffer=e,y.callback=b},a.inherits(v,T),a.inherits(_,T),a.inherits(w,T),a.inherits(E,T),a.inherits(k,T),a.inherits(S,T),a.inherits(x,T)}).call(this)}).call(this,e("_process"))},{"./binding":8,_process:34,assert:2,buffer:10,stream:55,util:82}],10:[function(e,t,r){(function(t){(function(){"use strict";var t=e("base64-js"),n=e("ieee754");r.Buffer=a,r.SlowBuffer=function(e){+e!=e&&(e=0);return a.alloc(+e)},r.INSPECT_MAX_BYTES=50;var i=2147483647;function o(e){if(e>i)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return t.__proto__=a.prototype,t}function a(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return l(e)}return s(e,t,r)}function s(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!a.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var r=0|h(e,t),n=o(r),i=n.write(e,t);i!==r&&(n=n.slice(0,i));return n}(e,t);if(ArrayBuffer.isView(e))return c(e);if(null==e)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(B(e,ArrayBuffer)||e&&B(e.buffer,ArrayBuffer))return function(e,t,r){if(t<0||e.byteLength=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|e}function h(e,t){if(a.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||B(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);var r=e.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;for(var i=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return D(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return N(e).length;default:if(i)return n?-1:D(e).length;t=(""+t).toLowerCase(),i=!0}}function p(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function d(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),z(r=+r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=a.from(t,n)),a.isBuffer(t))return 0===t.length?-1:g(e,t,r,n,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):g(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function g(e,t,r,n,i){var o,a=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,r/=2}function l(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(i){var c=-1;for(o=r;os&&(r=s-u),o=r;o>=0;o--){for(var f=!0,h=0;hi&&(n=i):n=i;var o=t.length;n>o/2&&(n=o/2);for(var a=0;a>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function E(e,r,n){return 0===r&&n===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(r,n))}function k(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i239?4:l>223?3:l>191?2:1;if(i+f<=r)switch(f){case 1:l<128&&(c=l);break;case 2:128==(192&(o=e[i+1]))&&(u=(31&l)<<6|63&o)>127&&(c=u);break;case 3:o=e[i+1],a=e[i+2],128==(192&o)&&128==(192&a)&&(u=(15&l)<<12|(63&o)<<6|63&a)>2047&&(u<55296||u>57343)&&(c=u);break;case 4:o=e[i+1],a=e[i+2],s=e[i+3],128==(192&o)&&128==(192&a)&&128==(192&s)&&(u=(15&l)<<18|(63&o)<<12|(63&a)<<6|63&s)>65535&&u<1114112&&(c=u)}null===c?(c=65533,f=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),i+=f}return function(e){var t=e.length;if(t<=S)return String.fromCharCode.apply(String,e);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return T(this,t,r);case"utf8":case"utf-8":return k(this,t,r);case"ascii":return x(this,t,r);case"latin1":case"binary":return O(this,t,r);case"base64":return E(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(e){if(!a.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===a.compare(this,e)},a.prototype.inspect=function(){var e="",t=r.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),""},a.prototype.compare=function(e,t,r,n,i){if(B(e,Uint8Array)&&(e=a.from(e,e.offset,e.byteLength)),!a.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(t>>>=0,r>>>=0,n>>>=0,i>>>=0,this===e)return 0;for(var o=i-n,s=r-t,u=Math.min(o,s),l=this.slice(n,i),c=e.slice(t,r),f=0;f>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-t;if((void 0===r||r>i)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return m(this,e,t,r);case"utf8":case"utf-8":return y(this,e,t,r);case"ascii":return b(this,e,t,r);case"latin1":case"binary":return v(this,e,t,r);case"base64":return _(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return w(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var S=4096;function x(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;in)&&(r=n);for(var i="",o=t;or)throw new RangeError("Trying to access beyond buffer length")}function A(e,t,r,n,i,o){if(!a.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function M(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function C(e,t,r,i,o){return t=+t,r>>>=0,o||M(e,0,r,4),n.write(e,t,r,i,23,4),r+4}function L(e,t,r,i,o){return t=+t,r>>>=0,o||M(e,0,r,8),n.write(e,t,r,i,52,8),r+8}a.prototype.slice=function(e,t){var r=this.length;e=~~e,t=void 0===t?r:~~t,e<0?(e+=r)<0&&(e=0):e>r&&(e=r),t<0?(t+=r)<0&&(t=0):t>r&&(t=r),t>>=0,t>>>=0,r||R(e,t,this.length);for(var n=this[e],i=1,o=0;++o>>=0,t>>>=0,r||R(e,t,this.length);for(var n=this[e+--t],i=1;t>0&&(i*=256);)n+=this[e+--t]*i;return n},a.prototype.readUInt8=function(e,t){return e>>>=0,t||R(e,1,this.length),this[e]},a.prototype.readUInt16LE=function(e,t){return e>>>=0,t||R(e,2,this.length),this[e]|this[e+1]<<8},a.prototype.readUInt16BE=function(e,t){return e>>>=0,t||R(e,2,this.length),this[e]<<8|this[e+1]},a.prototype.readUInt32LE=function(e,t){return e>>>=0,t||R(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},a.prototype.readUInt32BE=function(e,t){return e>>>=0,t||R(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},a.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||R(e,t,this.length);for(var n=this[e],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*t)),n},a.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||R(e,t,this.length);for(var n=t,i=1,o=this[e+--n];n>0&&(i*=256);)o+=this[e+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*t)),o},a.prototype.readInt8=function(e,t){return e>>>=0,t||R(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},a.prototype.readInt16LE=function(e,t){e>>>=0,t||R(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},a.prototype.readInt16BE=function(e,t){e>>>=0,t||R(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},a.prototype.readInt32LE=function(e,t){return e>>>=0,t||R(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},a.prototype.readInt32BE=function(e,t){return e>>>=0,t||R(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},a.prototype.readFloatLE=function(e,t){return e>>>=0,t||R(e,4,this.length),n.read(this,e,!0,23,4)},a.prototype.readFloatBE=function(e,t){return e>>>=0,t||R(e,4,this.length),n.read(this,e,!1,23,4)},a.prototype.readDoubleLE=function(e,t){return e>>>=0,t||R(e,8,this.length),n.read(this,e,!0,52,8)},a.prototype.readDoubleBE=function(e,t){return e>>>=0,t||R(e,8,this.length),n.read(this,e,!1,52,8)},a.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t>>>=0,r>>>=0,n)||A(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[t]=255&e;++o>>=0,r>>>=0,n)||A(this,e,t,r,Math.pow(2,8*r)-1,0);var i=r-1,o=1;for(this[t+i]=255&e;--i>=0&&(o*=256);)this[t+i]=e/o&255;return t+r},a.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||A(this,e,t,1,255,0),this[t]=255&e,t+1},a.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||A(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},a.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||A(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},a.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||A(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},a.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||A(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},a.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);A(this,e,t,r,i-1,-i)}var o=0,a=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+r},a.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var i=Math.pow(2,8*r-1);A(this,e,t,r,i-1,-i)}var o=r-1,a=1,s=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a>>0)-s&255;return t+r},a.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||A(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},a.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||A(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},a.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||A(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},a.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||A(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},a.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||A(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},a.prototype.writeFloatLE=function(e,t,r){return C(this,e,t,!0,r)},a.prototype.writeFloatBE=function(e,t,r){return C(this,e,t,!1,r)},a.prototype.writeDoubleLE=function(e,t,r){return L(this,e,t,!0,r)},a.prototype.writeDoubleBE=function(e,t,r){return L(this,e,t,!1,r)},a.prototype.copy=function(e,t,r,n){if(!a.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--o)e[o+t]=this[o+r];else Uint8Array.prototype.set.call(e,this.subarray(r,n),t);return i},a.prototype.fill=function(e,t,r,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!a.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===e.length){var i=e.charCodeAt(0);("utf8"===n&&i<128||"latin1"===n)&&(e=i)}}else"number"==typeof e&&(e&=255);if(t<0||this.length>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function N(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(P,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function U(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function B(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function z(e){return e!=e}}).call(this)}).call(this,e("buffer").Buffer)},{"base64-js":6,buffer:10,ieee754:15}],11:[function(e,t,r){t.exports={100:"Continue",101:"Switching Protocols",102:"Processing",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",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"}},{}],12:[function(e,t,r){(function(e){(function(){function t(e){return Object.prototype.toString.call(e)}r.isArray=function(e){return Array.isArray?Array.isArray(e):"[object Array]"===t(e)},r.isBoolean=function(e){return"boolean"==typeof e},r.isNull=function(e){return null===e},r.isNullOrUndefined=function(e){return null==e},r.isNumber=function(e){return"number"==typeof e},r.isString=function(e){return"string"==typeof e},r.isSymbol=function(e){return"symbol"==typeof e},r.isUndefined=function(e){return void 0===e},r.isRegExp=function(e){return"[object RegExp]"===t(e)},r.isObject=function(e){return"object"==typeof e&&null!==e},r.isDate=function(e){return"[object Date]"===t(e)},r.isError=function(e){return"[object Error]"===t(e)||e instanceof Error},r.isFunction=function(e){return"function"==typeof e},r.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},r.isBuffer=e.isBuffer}).call(this)}).call(this,{isBuffer:e("../../is-buffer/index.js")})},{"../../is-buffer/index.js":17}],13:[function(e,t,r){var n=Object.create||function(e){var t=function(){};return t.prototype=e,new t},i=Object.keys||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return r},o=Function.prototype.bind||function(e){var t=this;return function(){return t.apply(e,arguments)}};function a(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=n(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}t.exports=a,a.EventEmitter=a,a.prototype._events=void 0,a.prototype._maxListeners=void 0;var s,u=10;try{var l={};Object.defineProperty&&Object.defineProperty(l,"x",{value:0}),s=0===l.x}catch(e){s=!1}function c(e){return void 0===e._maxListeners?a.defaultMaxListeners:e._maxListeners}function f(e,t,r,i){var o,a,s;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');if((a=e._events)?(a.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),a=e._events),s=a[t]):(a=e._events=n(null),e._eventsCount=0),s){if("function"==typeof s?s=a[t]=i?[r,s]:[s,r]:i?s.unshift(r):s.push(r),!s.warned&&(o=c(e))&&o>0&&s.length>o){s.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+s.length+' "'+String(t)+'" listeners added. Use emitter.setMaxListeners() to increase limit.');u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=s.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",u.name,u.message)}}else s=a[t]=r,++e._eventsCount;return e}function h(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var e=new Array(arguments.length),t=0;t1&&(t=arguments[1]),t instanceof Error)throw t;var u=new Error('Unhandled "error" event. ('+t+")");throw u.context=t,u}if(!(r=a[e]))return!1;var l="function"==typeof r;switch(n=arguments.length){case 1:!function(e,t,r){if(t)e.call(r);else for(var n=e.length,i=m(e,n),o=0;o=0;a--)if(r[a]===t||r[a].listener===t){s=r[a].listener,o=a;break}if(o<0)return this;0===o?r.shift():function(e,t){for(var r=t,n=r+1,i=e.length;n=0;o--)this.removeListener(e,t[o]);return this},a.prototype.listeners=function(e){return d(this,e,!0)},a.prototype.rawListeners=function(e){return d(this,e,!1)},a.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):g.call(e,t)},a.prototype.listenerCount=g,a.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]}},{}],14:[function(e,t,r){var n=e("http"),i=e("url"),o=t.exports;for(var a in n)n.hasOwnProperty(a)&&(o[a]=n[a]);function s(e){if("string"==typeof e&&(e=i.parse(e)),e.protocol||(e.protocol="https:"),"https:"!==e.protocol)throw new Error('Protocol "'+e.protocol+'" not supported. Expected "https:"');return e}o.request=function(e,t){return e=s(e),n.request.call(this,e,t)},o.get=function(e,t){return e=s(e),n.get.call(this,e,t)}},{http:56,url:77}],15:[function(e,t,r){r.read=function(e,t,r,n,i){var o,a,s=8*i-n-1,u=(1<>1,c=-7,f=r?i-1:0,h=r?-1:1,p=e[t+f];for(f+=h,o=p&(1<<-c)-1,p>>=-c,c+=s;c>0;o=256*o+e[t+f],f+=h,c-=8);for(a=o&(1<<-c)-1,o>>=-c,c+=n;c>0;a=256*a+e[t+f],f+=h,c-=8);if(0===o)o=1-l;else{if(o===u)return a?NaN:1/0*(p?-1:1);a+=Math.pow(2,n),o-=l}return(p?-1:1)*a*Math.pow(2,o-n)},r.write=function(e,t,r,n,i,o){var a,s,u,l=8*o-i-1,c=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=c):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+f>=1?h/u:h*Math.pow(2,1-f))*u>=2&&(a++,u/=2),a+f>=c?(s=0,a=c):a+f>=1?(s=(t*u-1)*Math.pow(2,i),a+=f):(s=t*Math.pow(2,f-1)*Math.pow(2,i),a=0));i>=8;e[r+p]=255&s,p+=d,s/=256,i-=8);for(a=a<0;e[r+p]=255&a,p+=d,a/=256,l-=8);e[r+p-d]|=128*g}},{}],16:[function(e,t,r){"function"==typeof Object.create?t.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:t.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}},{}],17:[function(e,t,r){function n(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}t.exports=function(e){return null!=e&&(n(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&n(e.slice(0,0))}(e)||!!e._isBuffer)}},{}],18:[function(e,t,r){var n={}.toString;t.exports=Array.isArray||function(e){return"[object Array]"==n.call(e)}},{}],19:[function(e,t,r){"use strict";var n=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable;t.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},r=0;r<10;r++)t["_"+String.fromCharCode(r)]=r;if("0123456789"!==Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(""))return!1;var n={};return"abcdefghijklmnopqrst".split("").forEach(function(e){n[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},n)).join("")}catch(e){return!1}}()?Object.assign:function(e,t){for(var r,a,s=function(e){if(null===e||void 0===e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}(e),u=1;u>>16&65535|0,a=0;0!==r;){r-=a=r>2e3?2e3:r;do{o=o+(i=i+t[n++]|0)|0}while(--a);i%=65521,o%=65521}return i|o<<16|0}},{}],23:[function(e,t,r){"use strict";t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,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,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],24:[function(e,t,r){"use strict";var n=function(){for(var e,t=[],r=0;r<256;r++){e=r;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[r]=e}return t}();t.exports=function(e,t,r,i){var o=n,a=i+r;e^=-1;for(var s=i;s>>8^o[255&(e^t[s])];return-1^e}},{}],25:[function(e,t,r){"use strict";var n,i=e("../utils/common"),o=e("./trees"),a=e("./adler32"),s=e("./crc32"),u=e("./messages"),l=0,c=1,f=3,h=4,p=5,d=0,g=1,m=-2,y=-3,b=-5,v=-1,_=1,w=2,E=3,k=4,S=0,x=2,O=8,T=9,j=15,R=8,A=286,M=30,C=19,L=2*A+1,P=15,I=3,D=258,N=D+I+1,U=32,B=42,z=69,F=73,q=91,H=103,W=113,Z=666,G=1,Y=2,V=3,$=4,J=3;function K(e,t){return e.msg=u[t],t}function X(e){return(e<<1)-(e>4?9:0)}function Q(e){for(var t=e.length;--t>=0;)e[t]=0}function ee(e){var t=e.state,r=t.pending;r>e.avail_out&&(r=e.avail_out),0!==r&&(i.arraySet(e.output,t.pending_buf,t.pending_out,r,e.next_out),e.next_out+=r,t.pending_out+=r,e.total_out+=r,e.avail_out-=r,t.pending-=r,0===t.pending&&(t.pending_out=0))}function te(e,t){o._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,ee(e.strm)}function re(e,t){e.pending_buf[e.pending++]=t}function ne(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function ie(e,t){var r,n,i=e.max_chain_length,o=e.strstart,a=e.prev_length,s=e.nice_match,u=e.strstart>e.w_size-N?e.strstart-(e.w_size-N):0,l=e.window,c=e.w_mask,f=e.prev,h=e.strstart+D,p=l[o+a-1],d=l[o+a];e.prev_length>=e.good_match&&(i>>=2),s>e.lookahead&&(s=e.lookahead);do{if(l[(r=t)+a]===d&&l[r+a-1]===p&&l[r]===l[o]&&l[++r]===l[o+1]){o+=2,r++;do{}while(l[++o]===l[++r]&&l[++o]===l[++r]&&l[++o]===l[++r]&&l[++o]===l[++r]&&l[++o]===l[++r]&&l[++o]===l[++r]&&l[++o]===l[++r]&&l[++o]===l[++r]&&oa){if(e.match_start=t,a=n,n>=s)break;p=l[o+a-1],d=l[o+a]}}}while((t=f[t&c])>u&&0!=--i);return a<=e.lookahead?a:e.lookahead}function oe(e){var t,r,n,o,u,l,c,f,h,p,d=e.w_size;do{if(o=e.window_size-e.lookahead-e.strstart,e.strstart>=d+(d-N)){i.arraySet(e.window,e.window,d,d,0),e.match_start-=d,e.strstart-=d,e.block_start-=d,t=r=e.hash_size;do{n=e.head[--t],e.head[t]=n>=d?n-d:0}while(--r);t=r=d;do{n=e.prev[--t],e.prev[t]=n>=d?n-d:0}while(--r);o+=d}if(0===e.strm.avail_in)break;if(l=e.strm,c=e.window,f=e.strstart+e.lookahead,h=o,p=void 0,(p=l.avail_in)>h&&(p=h),r=0===p?0:(l.avail_in-=p,i.arraySet(c,l.input,l.next_in,p,f),1===l.state.wrap?l.adler=a(l.adler,c,p,f):2===l.state.wrap&&(l.adler=s(l.adler,c,p,f)),l.next_in+=p,l.total_in+=p,p),e.lookahead+=r,e.lookahead+e.insert>=I)for(u=e.strstart-e.insert,e.ins_h=e.window[u],e.ins_h=(e.ins_h<=I&&(e.ins_h=(e.ins_h<=I)if(n=o._tr_tally(e,e.strstart-e.match_start,e.match_length-I),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=I){e.match_length--;do{e.strstart++,e.ins_h=(e.ins_h<=I&&(e.ins_h=(e.ins_h<4096)&&(e.match_length=I-1)),e.prev_length>=I&&e.match_length<=e.prev_length){i=e.strstart+e.lookahead-I,n=o._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-I),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=i&&(e.ins_h=(e.ins_h<15&&(s=2,n-=16),o<1||o>T||r!==O||n<8||n>15||t<0||t>9||a<0||a>k)return K(e,m);8===n&&(n=9);var u=new function(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=O,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new i.Buf16(2*L),this.dyn_dtree=new i.Buf16(2*(2*M+1)),this.bl_tree=new i.Buf16(2*(2*C+1)),Q(this.dyn_ltree),Q(this.dyn_dtree),Q(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new i.Buf16(P+1),this.heap=new i.Buf16(2*A+1),Q(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new i.Buf16(2*A+1),Q(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0};return e.state=u,u.strm=e,u.wrap=s,u.gzhead=null,u.w_bits=n,u.w_size=1<e.pending_buf_size-5&&(r=e.pending_buf_size-5);;){if(e.lookahead<=1){if(oe(e),0===e.lookahead&&t===l)return G;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var n=e.block_start+r;if((0===e.strstart||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,te(e,!1),0===e.strm.avail_out))return G;if(e.strstart-e.block_start>=e.w_size-N&&(te(e,!1),0===e.strm.avail_out))return G}return e.insert=0,t===h?(te(e,!0),0===e.strm.avail_out?V:$):(e.strstart>e.block_start&&(te(e,!1),e.strm.avail_out),G)}),new ue(4,4,8,4,ae),new ue(4,5,16,8,ae),new ue(4,6,32,32,ae),new ue(4,4,16,16,se),new ue(8,16,32,32,se),new ue(8,16,128,128,se),new ue(8,32,128,256,se),new ue(32,128,258,1024,se),new ue(32,258,258,4096,se)],r.deflateInit=function(e,t){return fe(e,t,O,j,R,S)},r.deflateInit2=fe,r.deflateReset=ce,r.deflateResetKeep=le,r.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?m:(e.state.gzhead=t,d):m},r.deflate=function(e,t){var r,i,a,u;if(!e||!e.state||t>p||t<0)return e?K(e,m):m;if(i=e.state,!e.output||!e.input&&0!==e.avail_in||i.status===Z&&t!==h)return K(e,0===e.avail_out?b:m);if(i.strm=e,r=i.last_flush,i.last_flush=t,i.status===B)if(2===i.wrap)e.adler=0,re(i,31),re(i,139),re(i,8),i.gzhead?(re(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),re(i,255&i.gzhead.time),re(i,i.gzhead.time>>8&255),re(i,i.gzhead.time>>16&255),re(i,i.gzhead.time>>24&255),re(i,9===i.level?2:i.strategy>=w||i.level<2?4:0),re(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(re(i,255&i.gzhead.extra.length),re(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=s(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=z):(re(i,0),re(i,0),re(i,0),re(i,0),re(i,0),re(i,9===i.level?2:i.strategy>=w||i.level<2?4:0),re(i,J),i.status=W);else{var y=O+(i.w_bits-8<<4)<<8;y|=(i.strategy>=w||i.level<2?0:i.level<6?1:6===i.level?2:3)<<6,0!==i.strstart&&(y|=U),y+=31-y%31,i.status=W,ne(i,y),0!==i.strstart&&(ne(i,e.adler>>>16),ne(i,65535&e.adler)),e.adler=1}if(i.status===z)if(i.gzhead.extra){for(a=i.pending;i.gzindex<(65535&i.gzhead.extra.length)&&(i.pending!==i.pending_buf_size||(i.gzhead.hcrc&&i.pending>a&&(e.adler=s(e.adler,i.pending_buf,i.pending-a,a)),ee(e),a=i.pending,i.pending!==i.pending_buf_size));)re(i,255&i.gzhead.extra[i.gzindex]),i.gzindex++;i.gzhead.hcrc&&i.pending>a&&(e.adler=s(e.adler,i.pending_buf,i.pending-a,a)),i.gzindex===i.gzhead.extra.length&&(i.gzindex=0,i.status=F)}else i.status=F;if(i.status===F)if(i.gzhead.name){a=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>a&&(e.adler=s(e.adler,i.pending_buf,i.pending-a,a)),ee(e),a=i.pending,i.pending===i.pending_buf_size)){u=1;break}u=i.gzindexa&&(e.adler=s(e.adler,i.pending_buf,i.pending-a,a)),0===u&&(i.gzindex=0,i.status=q)}else i.status=q;if(i.status===q)if(i.gzhead.comment){a=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>a&&(e.adler=s(e.adler,i.pending_buf,i.pending-a,a)),ee(e),a=i.pending,i.pending===i.pending_buf_size)){u=1;break}u=i.gzindexa&&(e.adler=s(e.adler,i.pending_buf,i.pending-a,a)),0===u&&(i.status=H)}else i.status=H;if(i.status===H&&(i.gzhead.hcrc?(i.pending+2>i.pending_buf_size&&ee(e),i.pending+2<=i.pending_buf_size&&(re(i,255&e.adler),re(i,e.adler>>8&255),e.adler=0,i.status=W)):i.status=W),0!==i.pending){if(ee(e),0===e.avail_out)return i.last_flush=-1,d}else if(0===e.avail_in&&X(t)<=X(r)&&t!==h)return K(e,b);if(i.status===Z&&0!==e.avail_in)return K(e,b);if(0!==e.avail_in||0!==i.lookahead||t!==l&&i.status!==Z){var v=i.strategy===w?function(e,t){for(var r;;){if(0===e.lookahead&&(oe(e),0===e.lookahead)){if(t===l)return G;break}if(e.match_length=0,r=o._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(te(e,!1),0===e.strm.avail_out))return G}return e.insert=0,t===h?(te(e,!0),0===e.strm.avail_out?V:$):e.last_lit&&(te(e,!1),0===e.strm.avail_out)?G:Y}(i,t):i.strategy===E?function(e,t){for(var r,n,i,a,s=e.window;;){if(e.lookahead<=D){if(oe(e),e.lookahead<=D&&t===l)return G;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=I&&e.strstart>0&&(n=s[i=e.strstart-1])===s[++i]&&n===s[++i]&&n===s[++i]){a=e.strstart+D;do{}while(n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&n===s[++i]&&ie.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=I?(r=o._tr_tally(e,1,e.match_length-I),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=o._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(te(e,!1),0===e.strm.avail_out))return G}return e.insert=0,t===h?(te(e,!0),0===e.strm.avail_out?V:$):e.last_lit&&(te(e,!1),0===e.strm.avail_out)?G:Y}(i,t):n[i.level].func(i,t);if(v!==V&&v!==$||(i.status=Z),v===G||v===V)return 0===e.avail_out&&(i.last_flush=-1),d;if(v===Y&&(t===c?o._tr_align(i):t!==p&&(o._tr_stored_block(i,0,0,!1),t===f&&(Q(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),ee(e),0===e.avail_out))return i.last_flush=-1,d}return t!==h?d:i.wrap<=0?g:(2===i.wrap?(re(i,255&e.adler),re(i,e.adler>>8&255),re(i,e.adler>>16&255),re(i,e.adler>>24&255),re(i,255&e.total_in),re(i,e.total_in>>8&255),re(i,e.total_in>>16&255),re(i,e.total_in>>24&255)):(ne(i,e.adler>>>16),ne(i,65535&e.adler)),ee(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?d:g)},r.deflateEnd=function(e){var t;return e&&e.state?(t=e.state.status)!==B&&t!==z&&t!==F&&t!==q&&t!==H&&t!==W&&t!==Z?K(e,m):(e.state=null,t===W?K(e,y):d):m},r.deflateSetDictionary=function(e,t){var r,n,o,s,u,l,c,f,h=t.length;if(!e||!e.state)return m;if(2===(s=(r=e.state).wrap)||1===s&&r.status!==B||r.lookahead)return m;for(1===s&&(e.adler=a(e.adler,t,h,0)),r.wrap=0,h>=r.w_size&&(0===s&&(Q(r.head),r.strstart=0,r.block_start=0,r.insert=0),f=new i.Buf8(r.w_size),i.arraySet(f,t,h-r.w_size,r.w_size,0),t=f,h=r.w_size),u=e.avail_in,l=e.next_in,c=e.input,e.avail_in=h,e.next_in=0,e.input=t,oe(r);r.lookahead>=I;){n=r.strstart,o=r.lookahead-(I-1);do{r.ins_h=(r.ins_h<>>=_=v>>>24,d-=_,0===(_=v>>>16&255))O[o++]=65535&v;else{if(!(16&_)){if(0==(64&_)){v=g[(65535&v)+(p&(1<<_)-1)];continue t}if(32&_){r.mode=12;break e}e.msg="invalid literal/length code",r.mode=30;break e}w=65535&v,(_&=15)&&(d<_&&(p+=x[n++]<>>=_,d-=_),d<15&&(p+=x[n++]<>>=_=v>>>24,d-=_,!(16&(_=v>>>16&255))){if(0==(64&_)){v=m[(65535&v)+(p&(1<<_)-1)];continue r}e.msg="invalid distance code",r.mode=30;break e}if(E=65535&v,d<(_&=15)&&(p+=x[n++]<u){e.msg="invalid distance too far back",r.mode=30;break e}if(p>>>=_,d-=_,E>(_=o-a)){if((_=E-_)>c&&r.sane){e.msg="invalid distance too far back",r.mode=30;break e}if(k=0,S=h,0===f){if(k+=l-_,_2;)O[o++]=S[k++],O[o++]=S[k++],O[o++]=S[k++],w-=3;w&&(O[o++]=S[k++],w>1&&(O[o++]=S[k++]))}else{k=o-E;do{O[o++]=O[k++],O[o++]=O[k++],O[o++]=O[k++],w-=3}while(w>2);w&&(O[o++]=O[k++],w>1&&(O[o++]=O[k++]))}break}}break}}while(n>3,p&=(1<<(d-=w<<3))-1,e.next_in=n,e.next_out=o,e.avail_in=n>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function ie(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=E,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new n.Buf32(ee),t.distcode=t.distdyn=new n.Buf32(te),t.sane=1,t.back=-1,d):y}function oe(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,ie(e)):y}function ae(e,t){var r,n;return e&&e.state?(n=e.state,t<0?(r=0,t=-t):(r=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?y:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=r,n.wbits=t,oe(e))):y}function se(e,t){var r,i;return e?(i=new function(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new n.Buf16(320),this.work=new n.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0},e.state=i,i.window=null,(r=ae(e,t))!==d&&(e.state=null),r):y}var ue,le,ce=!0;function fe(e){if(ce){var t;for(ue=new n.Buf32(512),le=new n.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(s(l,e.lens,0,288,ue,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;s(c,e.lens,0,32,le,0,e.work,{bits:5}),ce=!1}e.lencode=ue,e.lenbits=9,e.distcode=le,e.distbits=5}function he(e,t,r,i){var o,a=e.state;return null===a.window&&(a.wsize=1<=a.wsize?(n.arraySet(a.window,t,r-a.wsize,a.wsize,0),a.wnext=0,a.whave=a.wsize):((o=a.wsize-a.wnext)>i&&(o=i),n.arraySet(a.window,t,r-i,o,a.wnext),(i-=o)?(n.arraySet(a.window,t,r-i,i,0),a.wnext=i,a.whave=a.wsize):(a.wnext+=o,a.wnext===a.wsize&&(a.wnext=0),a.whave>>8&255,r.check=o(r.check,Te,2,0),se=0,ue=0,r.mode=k;break}if(r.flags=0,r.head&&(r.head.done=!1),!(1&r.wrap)||(((255&se)<<8)+(se>>8))%31){e.msg="incorrect header check",r.mode=K;break}if((15&se)!==w){e.msg="unknown compression method",r.mode=K;break}if(ue-=4,Ee=8+(15&(se>>>=4)),0===r.wbits)r.wbits=Ee;else if(Ee>r.wbits){e.msg="invalid window size",r.mode=K;break}r.dmax=1<>8&1),512&r.flags&&(Te[0]=255&se,Te[1]=se>>>8&255,r.check=o(r.check,Te,2,0)),se=0,ue=0,r.mode=S;case S:for(;ue<32;){if(0===oe)break e;oe--,se+=ee[re++]<>>8&255,Te[2]=se>>>16&255,Te[3]=se>>>24&255,r.check=o(r.check,Te,4,0)),se=0,ue=0,r.mode=x;case x:for(;ue<16;){if(0===oe)break e;oe--,se+=ee[re++]<>8),512&r.flags&&(Te[0]=255&se,Te[1]=se>>>8&255,r.check=o(r.check,Te,2,0)),se=0,ue=0,r.mode=O;case O:if(1024&r.flags){for(;ue<16;){if(0===oe)break e;oe--,se+=ee[re++]<>>8&255,r.check=o(r.check,Te,2,0)),se=0,ue=0}else r.head&&(r.head.extra=null);r.mode=T;case T:if(1024&r.flags&&((pe=r.length)>oe&&(pe=oe),pe&&(r.head&&(Ee=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),n.arraySet(r.head.extra,ee,re,pe,Ee)),512&r.flags&&(r.check=o(r.check,ee,pe,re)),oe-=pe,re+=pe,r.length-=pe),r.length))break e;r.length=0,r.mode=j;case j:if(2048&r.flags){if(0===oe)break e;pe=0;do{Ee=ee[re+pe++],r.head&&Ee&&r.length<65536&&(r.head.name+=String.fromCharCode(Ee))}while(Ee&&pe>9&1,r.head.done=!0),e.adler=r.check=0,r.mode=L;break;case M:for(;ue<32;){if(0===oe)break e;oe--,se+=ee[re++]<>>=7&ue,ue-=7&ue,r.mode=V;break}for(;ue<3;){if(0===oe)break e;oe--,se+=ee[re++]<>>=1)){case 0:r.mode=I;break;case 1:if(fe(r),r.mode=F,t===p){se>>>=2,ue-=2;break e}break;case 2:r.mode=U;break;case 3:e.msg="invalid block type",r.mode=K}se>>>=2,ue-=2;break;case I:for(se>>>=7&ue,ue-=7&ue;ue<32;){if(0===oe)break e;oe--,se+=ee[re++]<>>16^65535)){e.msg="invalid stored block lengths",r.mode=K;break}if(r.length=65535&se,se=0,ue=0,r.mode=D,t===p)break e;case D:r.mode=N;case N:if(pe=r.length){if(pe>oe&&(pe=oe),pe>ae&&(pe=ae),0===pe)break e;n.arraySet(te,ee,re,pe,ie),oe-=pe,re+=pe,ae-=pe,ie+=pe,r.length-=pe;break}r.mode=L;break;case U:for(;ue<14;){if(0===oe)break e;oe--,se+=ee[re++]<>>=5,ue-=5,r.ndist=1+(31&se),se>>>=5,ue-=5,r.ncode=4+(15&se),se>>>=4,ue-=4,r.nlen>286||r.ndist>30){e.msg="too many length or distance symbols",r.mode=K;break}r.have=0,r.mode=B;case B:for(;r.have>>=3,ue-=3}for(;r.have<19;)r.lens[je[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,Se={bits:r.lenbits},ke=s(u,r.lens,0,19,r.lencode,0,r.work,Se),r.lenbits=Se.bits,ke){e.msg="invalid code lengths set",r.mode=K;break}r.have=0,r.mode=z;case z:for(;r.have>>16&255,be=65535&Oe,!((me=Oe>>>24)<=ue);){if(0===oe)break e;oe--,se+=ee[re++]<>>=me,ue-=me,r.lens[r.have++]=be;else{if(16===be){for(xe=me+2;ue>>=me,ue-=me,0===r.have){e.msg="invalid bit length repeat",r.mode=K;break}Ee=r.lens[r.have-1],pe=3+(3&se),se>>>=2,ue-=2}else if(17===be){for(xe=me+3;ue>>=me)),se>>>=3,ue-=3}else{for(xe=me+7;ue>>=me)),se>>>=7,ue-=7}if(r.have+pe>r.nlen+r.ndist){e.msg="invalid bit length repeat",r.mode=K;break}for(;pe--;)r.lens[r.have++]=Ee}}if(r.mode===K)break;if(0===r.lens[256]){e.msg="invalid code -- missing end-of-block",r.mode=K;break}if(r.lenbits=9,Se={bits:r.lenbits},ke=s(l,r.lens,0,r.nlen,r.lencode,0,r.work,Se),r.lenbits=Se.bits,ke){e.msg="invalid literal/lengths set",r.mode=K;break}if(r.distbits=6,r.distcode=r.distdyn,Se={bits:r.distbits},ke=s(c,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,Se),r.distbits=Se.bits,ke){e.msg="invalid distances set",r.mode=K;break}if(r.mode=F,t===p)break e;case F:r.mode=q;case q:if(oe>=6&&ae>=258){e.next_out=ie,e.avail_out=ae,e.next_in=re,e.avail_in=oe,r.hold=se,r.bits=ue,a(e,ce),ie=e.next_out,te=e.output,ae=e.avail_out,re=e.next_in,ee=e.input,oe=e.avail_in,se=r.hold,ue=r.bits,r.mode===L&&(r.back=-1);break}for(r.back=0;ye=(Oe=r.lencode[se&(1<>>16&255,be=65535&Oe,!((me=Oe>>>24)<=ue);){if(0===oe)break e;oe--,se+=ee[re++]<>ve)])>>>16&255,be=65535&Oe,!(ve+(me=Oe>>>24)<=ue);){if(0===oe)break e;oe--,se+=ee[re++]<>>=ve,ue-=ve,r.back+=ve}if(se>>>=me,ue-=me,r.back+=me,r.length=be,0===ye){r.mode=Y;break}if(32&ye){r.back=-1,r.mode=L;break}if(64&ye){e.msg="invalid literal/length code",r.mode=K;break}r.extra=15&ye,r.mode=H;case H:if(r.extra){for(xe=r.extra;ue>>=r.extra,ue-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=W;case W:for(;ye=(Oe=r.distcode[se&(1<>>16&255,be=65535&Oe,!((me=Oe>>>24)<=ue);){if(0===oe)break e;oe--,se+=ee[re++]<>ve)])>>>16&255,be=65535&Oe,!(ve+(me=Oe>>>24)<=ue);){if(0===oe)break e;oe--,se+=ee[re++]<>>=ve,ue-=ve,r.back+=ve}if(se>>>=me,ue-=me,r.back+=me,64&ye){e.msg="invalid distance code",r.mode=K;break}r.offset=be,r.extra=15&ye,r.mode=Z;case Z:if(r.extra){for(xe=r.extra;ue>>=r.extra,ue-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){e.msg="invalid distance too far back",r.mode=K;break}r.mode=G;case G:if(0===ae)break e;if(pe=ce-ae,r.offset>pe){if((pe=r.offset-pe)>r.whave&&r.sane){e.msg="invalid distance too far back",r.mode=K;break}pe>r.wnext?(pe-=r.wnext,de=r.wsize-pe):de=r.wnext-pe,pe>r.length&&(pe=r.length),ge=r.window}else ge=te,de=ie-r.offset,pe=r.length;pe>ae&&(pe=ae),ae-=pe,r.length-=pe;do{te[ie++]=ge[de++]}while(--pe);0===r.length&&(r.mode=q);break;case Y:if(0===ae)break e;te[ie++]=r.length,ae--,r.mode=q;break;case V:if(r.wrap){for(;ue<32;){if(0===oe)break e;oe--,se|=ee[re++]<=1&&0===I[O];O--);if(T>O&&(T=O),0===O)return l[c++]=20971520,l[c++]=20971520,h.bits=1,0;for(x=1;x0&&(0===e||1!==O))return-1;for(D[1]=0,k=1;k<15;k++)D[k+1]=D[k]+I[k];for(S=0;S852||2===e&&M>592)return 1;for(;;){v=k-R,f[S]b?(_=N[U+f[S]],w=L[P+f[S]]):(_=96,w=0),p=1<>R)+(d-=p)]=v<<24|_<<16|w|0}while(0!==d);for(p=1<>=1;if(0!==p?(C&=p-1,C+=p):C=0,S++,0==--I[k]){if(k===O)break;k=t[r+f[S]]}if(k>T&&(C&m)!==g){for(0===R&&(R=T),y+=x,A=1<<(j=k-R);j+R852||2===e&&M>592)return 1;l[g=C&m]=T<<24|j<<16|y-c|0}}return 0!==C&&(l[y+C]=k-R<<24|64<<16|0),h.bits=T,0}},{"../utils/common":21}],29:[function(e,t,r){"use strict";t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],30:[function(e,t,r){"use strict";var n=e("../utils/common"),i=4,o=0,a=1,s=2;function u(e){for(var t=e.length;--t>=0;)e[t]=0}var l=0,c=1,f=2,h=29,p=256,d=p+1+h,g=30,m=19,y=2*d+1,b=15,v=16,_=7,w=256,E=16,k=17,S=18,x=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],O=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],T=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],j=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],R=new Array(2*(d+2));u(R);var A=new Array(2*g);u(A);var M=new Array(512);u(M);var C=new Array(256);u(C);var L=new Array(h);u(L);var P,I,D,N=new Array(g);function U(e,t,r,n,i){this.static_tree=e,this.extra_bits=t,this.extra_base=r,this.elems=n,this.max_length=i,this.has_stree=e&&e.length}function B(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function z(e){return e<256?M[e]:M[256+(e>>>7)]}function F(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function q(e,t,r){e.bi_valid>v-r?(e.bi_buf|=t<>v-e.bi_valid,e.bi_valid+=r-v):(e.bi_buf|=t<>>=1,r<<=1}while(--t>0);return r>>>1}function Z(e,t,r){var n,i,o=new Array(b+1),a=0;for(n=1;n<=b;n++)o[n]=a=a+r[n-1]<<1;for(i=0;i<=t;i++){var s=e[2*i+1];0!==s&&(e[2*i]=W(o[s]++,s))}}function G(e){var t;for(t=0;t8?F(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function V(e,t,r,n){var i=2*t,o=2*r;return e[i]>1;r>=1;r--)$(e,o,r);i=u;do{r=e.heap[1],e.heap[1]=e.heap[e.heap_len--],$(e,o,1),n=e.heap[1],e.heap[--e.heap_max]=r,e.heap[--e.heap_max]=n,o[2*i]=o[2*r]+o[2*n],e.depth[i]=(e.depth[r]>=e.depth[n]?e.depth[r]:e.depth[n])+1,o[2*r+1]=o[2*n+1]=i,e.heap[1]=i++,$(e,o,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){var r,n,i,o,a,s,u=t.dyn_tree,l=t.max_code,c=t.stat_desc.static_tree,f=t.stat_desc.has_stree,h=t.stat_desc.extra_bits,p=t.stat_desc.extra_base,d=t.stat_desc.max_length,g=0;for(o=0;o<=b;o++)e.bl_count[o]=0;for(u[2*e.heap[e.heap_max]+1]=0,r=e.heap_max+1;rd&&(o=d,g++),u[2*n+1]=o,n>l||(e.bl_count[o]++,a=0,n>=p&&(a=h[n-p]),s=u[2*n],e.opt_len+=s*(o+a),f&&(e.static_len+=s*(c[2*n+1]+a)));if(0!==g){do{for(o=d-1;0===e.bl_count[o];)o--;e.bl_count[o]--,e.bl_count[o+1]+=2,e.bl_count[d]--,g-=2}while(g>0);for(o=d;0!==o;o--)for(n=e.bl_count[o];0!==n;)(i=e.heap[--r])>l||(u[2*i+1]!==o&&(e.opt_len+=(o-u[2*i+1])*u[2*i],u[2*i+1]=o),n--)}}(e,t),Z(o,l,e.bl_count)}function X(e,t,r){var n,i,o=-1,a=t[1],s=0,u=7,l=4;for(0===a&&(u=138,l=3),t[2*(r+1)+1]=65535,n=0;n<=r;n++)i=a,a=t[2*(n+1)+1],++s>=7;n0?(e.strm.data_type===s&&(e.strm.data_type=function(e){var t,r=4093624447;for(t=0;t<=31;t++,r>>>=1)if(1&r&&0!==e.dyn_ltree[2*t])return o;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return a;for(t=32;t=3&&0===e.bl_tree[2*j[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),u=e.opt_len+3+7>>>3,(l=e.static_len+3+7>>>3)<=u&&(u=l)):u=l=r+5,r+4<=u&&-1!==t?te(e,t,r,n):e.strategy===i||l===u?(q(e,(c<<1)+(n?1:0),3),J(e,R,A)):(q(e,(f<<1)+(n?1:0),3),function(e,t,r,n){var i;for(q(e,t-257,5),q(e,r-1,5),q(e,n-4,4),i=0;i>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&r,e.last_lit++,0===t?e.dyn_ltree[2*r]++:(e.matches++,t--,e.dyn_ltree[2*(C[r]+p+1)]++,e.dyn_dtree[2*z(t)]++),e.last_lit===e.lit_bufsize-1},r._tr_align=function(e){q(e,c<<1,3),H(e,w,R),function(e){16===e.bi_valid?(F(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}},{"../utils/common":21}],31:[function(e,t,r){"use strict";t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],32:[function(e,t,r){(function(e){(function(){function t(e,t){for(var r=0,n=e.length-1;n>=0;n--){var i=e[n];"."===i?e.splice(n,1):".."===i?(e.splice(n,1),r++):r&&(e.splice(n,1),r--)}if(t)for(;r--;r)e.unshift("..");return e}function n(e,t){if(e.filter)return e.filter(t);for(var r=[],n=0;n=-1&&!i;o--){var a=o>=0?arguments[o]:e.cwd();if("string"!=typeof a)throw new TypeError("Arguments to path.resolve must be strings");a&&(r=a+"/"+r,i="/"===a.charAt(0))}return r=t(n(r.split("/"),function(e){return!!e}),!i).join("/"),(i?"/":"")+r||"."},r.normalize=function(e){var o=r.isAbsolute(e),a="/"===i(e,-1);return(e=t(n(e.split("/"),function(e){return!!e}),!o).join("/"))||o||(e="."),e&&a&&(e+="/"),(o?"/":"")+e},r.isAbsolute=function(e){return"/"===e.charAt(0)},r.join=function(){var e=Array.prototype.slice.call(arguments,0);return r.normalize(n(e,function(e,t){if("string"!=typeof e)throw new TypeError("Arguments to path.join must be strings");return e}).join("/"))},r.relative=function(e,t){function n(e){for(var t=0;t=0&&""===e[r];r--);return t>r?[]:e.slice(t,r-t+1)}e=r.resolve(e).substr(1),t=r.resolve(t).substr(1);for(var i=n(e.split("/")),o=n(t.split("/")),a=Math.min(i.length,o.length),s=a,u=0;u=1;--o)if(47===(t=e.charCodeAt(o))){if(!i){n=o;break}}else i=!1;return-1===n?r?"/":".":r&&1===n?"/":e.slice(0,n)},r.basename=function(e,t){var r=function(e){"string"!=typeof e&&(e+="");var t,r=0,n=-1,i=!0;for(t=e.length-1;t>=0;--t)if(47===e.charCodeAt(t)){if(!i){r=t+1;break}}else-1===n&&(i=!1,n=t+1);return-1===n?"":e.slice(r,n)}(e);return t&&r.substr(-1*t.length)===t&&(r=r.substr(0,r.length-t.length)),r},r.extname=function(e){"string"!=typeof e&&(e+="");for(var t=-1,r=0,n=-1,i=!0,o=0,a=e.length-1;a>=0;--a){var s=e.charCodeAt(a);if(47!==s)-1===n&&(i=!1,n=a+1),46===s?-1===t?t=a:1!==o&&(o=1):-1!==t&&(o=-1);else if(!i){r=a+1;break}}return-1===t||-1===n||0===o||1===o&&t===n-1&&t===r+1?"":e.slice(t,n)};var i="b"==="ab".substr(-1)?function(e,t,r){return e.substr(t,r)}:function(e,t,r){return t<0&&(t=e.length+t),e.substr(t,r)}}).call(this)}).call(this,e("_process"))},{_process:34}],33:[function(e,t,r){(function(e){(function(){"use strict";void 0===e||!e.version||0===e.version.indexOf("v0.")||0===e.version.indexOf("v1.")&&0!==e.version.indexOf("v1.8.")?t.exports={nextTick:function(t,r,n,i){if("function"!=typeof t)throw new TypeError('"callback" argument must be a function');var o,a,s=arguments.length;switch(s){case 0:case 1:return e.nextTick(t);case 2:return e.nextTick(function(){t.call(null,r)});case 3:return e.nextTick(function(){t.call(null,r,n)});case 4:return e.nextTick(function(){t.call(null,r,n,i)});default:for(o=new Array(s-1),a=0;a1)for(var r=1;r= 0x80 (not a basic code point)","invalid-input":"Invalid input"},E=c-f,k=Math.floor,S=String.fromCharCode;function x(e){throw new RangeError(w[e])}function O(e,t){for(var r=e.length,n=[];r--;)n[r]=t(e[r]);return n}function T(e,t){var r=e.split("@"),n="";return r.length>1&&(n=r[0]+"@",e=r[1]),n+O((e=e.replace(_,".")).split("."),t).join(".")}function j(e){for(var t,r,n=[],i=0,o=e.length;i=55296&&t<=56319&&i65535&&(t+=S((e-=65536)>>>10&1023|55296),e=56320|1023&e),t+=S(e)}).join("")}function A(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function M(e,t,r){var n=0;for(e=r?k(e/d):e>>1,e+=k(e/t);e>E*h>>1;n+=c)e=k(e/E);return k(n+(E+1)*e/(e+p))}function C(e){var t,r,n,i,o,a,s,u,p,d,b,v=[],_=e.length,w=0,E=m,S=g;for((r=e.lastIndexOf(y))<0&&(r=0),n=0;n=128&&x("not-basic"),v.push(e.charCodeAt(n));for(i=r>0?r+1:0;i<_;){for(o=w,a=1,s=c;i>=_&&x("invalid-input"),((u=(b=e.charCodeAt(i++))-48<10?b-22:b-65<26?b-65:b-97<26?b-97:c)>=c||u>k((l-w)/a))&&x("overflow"),w+=u*a,!(u<(p=s<=S?f:s>=S+h?h:s-S));s+=c)a>k(l/(d=c-p))&&x("overflow"),a*=d;S=M(w-o,t=v.length+1,0==o),k(w/t)>l-E&&x("overflow"),E+=k(w/t),w%=t,v.splice(w++,0,E)}return R(v)}function L(e){var t,r,n,i,o,a,s,u,p,d,b,v,_,w,E,O=[];for(v=(e=j(e)).length,t=m,r=0,o=g,a=0;a=t&&bk((l-r)/(_=n+1))&&x("overflow"),r+=(s-t)*_,t=s,a=0;al&&x("overflow"),b==t){for(u=r,p=c;!(u<(d=p<=o?f:p>=o+h?h:p-o));p+=c)E=u-d,w=c-d,O.push(S(A(d+E%w,0))),u=k(E/w);O.push(S(A(u,0))),o=M(r,_,n==i),r=0,++n}++r,++t}return O.join("")}if(s={version:"1.4.1",ucs2:{decode:j,encode:R},decode:C,encode:L,toASCII:function(e){return T(e,function(e){return v.test(e)?"xn--"+L(e):e})},toUnicode:function(e){return T(e,function(e){return b.test(e)?C(e.slice(4).toLowerCase()):e})}},"function"==typeof define&&"object"==typeof define.amd&&define.amd)define("punycode",function(){return s});else if(i&&o)if(t.exports==i)o.exports=s;else for(u in s)s.hasOwnProperty(u)&&(i[u]=s[u]);else n.punycode=s}(this)}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],36:[function(e,t,r){"use strict";function n(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.exports=function(e,t,r,o){t=t||"&",r=r||"=";var a={};if("string"!=typeof e||0===e.length)return a;var s=/\+/g;e=e.split(t);var u=1e3;o&&"number"==typeof o.maxKeys&&(u=o.maxKeys);var l=e.length;u>0&&l>u&&(l=u);for(var c=0;c=0?(f=g.substr(0,m),h=g.substr(m+1)):(f=g,h=""),p=decodeURIComponent(f),d=decodeURIComponent(h),n(a,p)?i(a[p])?a[p].push(d):a[p]=[a[p],d]:a[p]=d}return a};var i=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)}},{}],37:[function(e,t,r){"use strict";var n=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}};t.exports=function(e,t,r,s){return t=t||"&",r=r||"=",null===e&&(e=void 0),"object"==typeof e?o(a(e),function(a){var s=encodeURIComponent(n(a))+r;return i(e[a])?o(e[a],function(e){return s+encodeURIComponent(n(e))}).join(t):s+encodeURIComponent(n(e[a]))}).join(t):s?encodeURIComponent(n(s))+r+encodeURIComponent(n(e)):""};var i=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function o(e,t){if(e.map)return e.map(t);for(var r=[],n=0;n0?("string"==typeof t||a.objectMode||Object.getPrototypeOf(t)===l.prototype||(t=function(e){return l.from(e)}(t)),n?a.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):w(e,a,t,!0):a.ended?e.emit("error",new Error("stream.push() after EOF")):(a.reading=!1,a.decoder&&!r?(t=a.decoder.write(t),a.objectMode||0!==t.length?w(e,a,t,!1):O(e,a)):w(e,a,t,!1))):n||(a.reading=!1));return function(e){return!e.ended&&(e.needReadable||e.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=E?e=E:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function S(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(p("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?i.nextTick(x,e):x(e))}function x(e){p("emit readable"),e.emit("readable"),A(e)}function O(e,t){t.readingMore||(t.readingMore=!0,i.nextTick(T,e,t))}function T(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):r=function(e,t,r){var n;eo.length?o.length:e;if(a===o.length?i+=o:i+=o.slice(0,e),0===(e-=a)){a===o.length?(++n,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=o.slice(a));break}++n}return t.length-=n,i}(e,t):function(e,t){var r=l.allocUnsafe(e),n=t.head,i=1;n.data.copy(r),e-=n.data.length;for(;n=n.next;){var o=n.data,a=e>o.length?o.length:e;if(o.copy(r,r.length-e,0,a),0===(e-=a)){a===o.length?(++i,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(a));break}++i}return t.length-=i,r}(e,t);return n}(e,t.buffer,t.decoder),r);var r}function C(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,i.nextTick(L,t,e))}function L(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function P(e,t){for(var r=0,n=e.length;r=t.highWaterMark||t.ended))return p("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?C(this):S(this),null;if(0===(e=k(e,t))&&t.ended)return 0===t.length&&C(this),null;var n,i=t.needReadable;return p("need readable",i),(0===t.length||t.length-e0?M(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&C(this)),null!==n&&this.emit("data",n),n},v.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},v.prototype.pipe=function(e,t){var n=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,p("pipe count=%d opts=%j",o.pipesCount,t);var u=(!t||!1!==t.end)&&e!==r.stdout&&e!==r.stderr?c:v;function l(t,r){p("onunpipe"),t===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,p("cleanup"),e.removeListener("close",y),e.removeListener("finish",b),e.removeListener("drain",f),e.removeListener("error",m),e.removeListener("unpipe",l),n.removeListener("end",c),n.removeListener("end",v),n.removeListener("data",g),h=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||f())}function c(){p("onend"),e.end()}o.endEmitted?i.nextTick(u):n.once("end",u),e.on("unpipe",l);var f=function(e){return function(){var t=e._readableState;p("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&s(e,"data")&&(t.flowing=!0,A(e))}}(n);e.on("drain",f);var h=!1;var d=!1;function g(t){p("ondata"),d=!1,!1!==e.write(t)||d||((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==P(o.pipes,e))&&!h&&(p("false write response, pause",n._readableState.awaitDrain),n._readableState.awaitDrain++,d=!0),n.pause())}function m(t){p("onerror",t),v(),e.removeListener("error",m),0===s(e,"error")&&e.emit("error",t)}function y(){e.removeListener("finish",b),v()}function b(){p("onfinish"),e.removeListener("close",y),v()}function v(){p("unpipe"),n.unpipe(e)}return n.on("data",g),function(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?a(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}(e,"error",m),e.once("close",y),e.once("finish",b),e.emit("pipe",n),o.flowing||(p("pipe resume"),n.resume()),e},v.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r),this);if(!e){var n=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o-1?i:o.nextTick;b.WritableState=y;var l=Object.create(e("core-util-is"));l.inherits=e("inherits");var c={deprecate:e("util-deprecate")},f=e("./internal/streams/stream"),h=e("safe-buffer").Buffer,p=n.Uint8Array||function(){};var d,g=e("./internal/streams/destroy");function m(){}function y(t,r){s=s||e("./_stream_duplex"),t=t||{};var n=r instanceof s;this.objectMode=!!t.objectMode,n&&(this.objectMode=this.objectMode||!!t.writableObjectMode);var i=t.highWaterMark,l=t.writableHighWaterMark,c=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:n&&(l||0===l)?l:c,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var f=!1===t.decodeStrings;this.decodeStrings=!f,this.defaultEncoding=t.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var r=e._writableState,n=r.sync,i=r.writecb;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(r),t)!function(e,t,r,n,i){--t.pendingcb,r?(o.nextTick(i,n),o.nextTick(S,e,t),e._writableState.errorEmitted=!0,e.emit("error",n)):(i(n),e._writableState.errorEmitted=!0,e.emit("error",n),S(e,t))}(e,r,n,t,i);else{var a=E(r);a||r.corked||r.bufferProcessing||!r.bufferedRequest||w(e,r),n?u(_,e,r,a,i):_(e,r,a,i)}}(r,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new a(this)}function b(t){if(s=s||e("./_stream_duplex"),!(d.call(b,this)||this instanceof s))return new b(t);this._writableState=new y(t,this),this.writable=!0,t&&("function"==typeof t.write&&(this._write=t.write),"function"==typeof t.writev&&(this._writev=t.writev),"function"==typeof t.destroy&&(this._destroy=t.destroy),"function"==typeof t.final&&(this._final=t.final)),f.call(this)}function v(e,t,r,n,i,o,a){t.writelen=n,t.writecb=a,t.writing=!0,t.sync=!0,r?e._writev(i,t.onwrite):e._write(i,o,t.onwrite),t.sync=!1}function _(e,t,r,n){r||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,n(),S(e,t)}function w(e,t){t.bufferProcessing=!0;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var n=t.bufferedRequestCount,i=new Array(n),o=t.corkedRequestsFree;o.entry=r;for(var s=0,u=!0;r;)i[s]=r,r.isBuf||(u=!1),r=r.next,s+=1;i.allBuffers=u,v(e,t,!0,t.length,i,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new a(t),t.bufferedRequestCount=0}else{for(;r;){var l=r.chunk,c=r.encoding,f=r.callback;if(v(e,t,!1,t.objectMode?1:l.length,l,c,f),r=r.next,t.bufferedRequestCount--,t.writing)break}null===r&&(t.lastBufferedRequest=null)}t.bufferedRequest=r,t.bufferProcessing=!1}function E(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function k(e,t){e._final(function(r){t.pendingcb--,r&&e.emit("error",r),t.prefinished=!0,e.emit("prefinish"),S(e,t)})}function S(e,t){var r=E(t);return r&&(!function(e,t){t.prefinished||t.finalCalled||("function"==typeof e._final?(t.pendingcb++,t.finalCalled=!0,o.nextTick(k,e,t)):(t.prefinished=!0,e.emit("prefinish")))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"))),r}l.inherits(b,f),y.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(y.prototype,"buffer",{get:c.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(d=Function.prototype[Symbol.hasInstance],Object.defineProperty(b,Symbol.hasInstance,{value:function(e){return!!d.call(this,e)||this===b&&(e&&e._writableState instanceof y)}})):d=function(e){return e instanceof this},b.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},b.prototype.write=function(e,t,r){var n,i=this._writableState,a=!1,s=!i.objectMode&&(n=e,h.isBuffer(n)||n instanceof p);return s&&!h.isBuffer(e)&&(e=function(e){return h.from(e)}(e)),"function"==typeof t&&(r=t,t=null),s?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof r&&(r=m),i.ended?function(e,t){var r=new Error("write after end");e.emit("error",r),o.nextTick(t,r)}(this,r):(s||function(e,t,r,n){var i=!0,a=!1;return null===r?a=new TypeError("May not write null values to stream"):"string"==typeof r||void 0===r||t.objectMode||(a=new TypeError("Invalid non-string/buffer chunk")),a&&(e.emit("error",a),o.nextTick(n,a),i=!1),i}(this,i,e,r))&&(i.pendingcb++,a=function(e,t,r,n,i,o){if(!r){var a=function(e,t,r){e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=h.from(t,r));return t}(t,n,i);n!==a&&(r=!0,i="buffer",n=a)}var s=t.objectMode?1:n.length;t.length+=s;var u=t.length-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(b.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),b.prototype._write=function(e,t,r){r(new Error("_write() is not implemented"))},b.prototype._writev=null,b.prototype.end=function(e,t,r){var n=this._writableState;"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!==e&&void 0!==e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||function(e,t,r){t.ending=!0,S(e,t),r&&(t.finished?o.nextTick(r):e.once("finish",r));t.ended=!0,e.writable=!1}(this,n,r)},Object.defineProperty(b.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),b.prototype.destroy=g.destroy,b.prototype._undestroy=g.undestroy,b.prototype._destroy=function(e,t){this.end(),t(e)}}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("timers").setImmediate)},{"./_stream_duplex":40,"./internal/streams/destroy":46,"./internal/streams/stream":47,_process:34,"core-util-is":12,inherits:16,"process-nextick-args":33,"safe-buffer":48,timers:76,"util-deprecate":79}],45:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=e("util");t.exports=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.head=null,this.tail=null,this.length=0}return e.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},e.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},e.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r},e.prototype.concat=function(e){if(0===this.length)return n.alloc(0);if(1===this.length)return this.head.data;for(var t,r,i,o=n.allocUnsafe(e>>>0),a=this.head,s=0;a;)t=a.data,r=o,i=s,t.copy(r,i),s+=a.data.length,a=a.next;return o},e}(),i&&i.inspect&&i.inspect.custom&&(t.exports.prototype[i.inspect.custom]=function(){var e=i.inspect({length:this.length});return this.constructor.name+" "+e})},{"safe-buffer":48,util:7}],46:[function(e,t,r){"use strict";var n=e("process-nextick-args");function i(e,t){e.emit("error",t)}t.exports={destroy:function(e,t){var r=this,o=this._readableState&&this._readableState.destroyed,a=this._writableState&&this._writableState.destroyed;return o||a?(t?t(e):!e||this._writableState&&this._writableState.errorEmitted||n.nextTick(i,this,e),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!t&&e?(n.nextTick(i,r,e),r._writableState&&(r._writableState.errorEmitted=!0)):t&&t(e)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}}},{"process-nextick-args":33}],47:[function(e,t,r){t.exports=e("events").EventEmitter},{events:13}],48:[function(e,t,r){var n=e("buffer"),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function a(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=n:(o(n,r),r.Buffer=a),o(i,a),a.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},a.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},{buffer:10}],49:[function(e,t,r){"use strict";var n=e("safe-buffer").Buffer,i=n.isEncoding||function(e){switch((e=""+e)&&e.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!0;default:return!1}};function o(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){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 e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(n.isEncoding===i||!i(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=u,this.end=l,t=4;break;case"utf8":this.fillLast=s,t=4;break;case"base64":this.text=c,this.end=f,t=3;break;default:return this.write=h,void(this.end=p)}this.lastNeed=0,this.lastTotal=0,this.lastChar=n.allocUnsafe(t)}function a(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function s(e){var t=this.lastTotal-this.lastNeed,r=function(e,t,r){if(128!=(192&t[0]))return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�"}}(this,e);return void 0!==r?r:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function u(e,t){if((e.length-t)%2==0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function l(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function c(e,t){var r=(e.length-t)%3;return 0===r?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function f(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function h(e){return e.toString(this.encoding)}function p(e){return e&&e.length?this.write(e):""}r.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,r;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r=0)return i>0&&(e.lastNeed=i-1),i;if(--n=0)return i>0&&(e.lastNeed=i-2),i;if(--n=0)return i>0&&(2===i?i=0:e.lastNeed=i-3),i;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)},o.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},{"safe-buffer":48}],50:[function(e,t,r){t.exports=e("./readable").PassThrough},{"./readable":51}],51:[function(e,t,r){(r=t.exports=e("./lib/_stream_readable.js")).Stream=r,r.Readable=r,r.Writable=e("./lib/_stream_writable.js"),r.Duplex=e("./lib/_stream_duplex.js"),r.Transform=e("./lib/_stream_transform.js"),r.PassThrough=e("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":40,"./lib/_stream_passthrough.js":41,"./lib/_stream_readable.js":42,"./lib/_stream_transform.js":43,"./lib/_stream_writable.js":44}],52:[function(e,t,r){t.exports=e("./readable").Transform},{"./readable":51}],53:[function(e,t,r){t.exports=e("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":44}],54:[function(e,t,r){var n=e("buffer"),i=n.Buffer;function o(e,t){for(var r in e)t[r]=e[r]}function a(e,t,r){return i(e,t,r)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?t.exports=n:(o(n,r),r.Buffer=a),a.prototype=Object.create(i.prototype),o(i,a),a.from=function(e,t,r){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,r)},a.alloc=function(e,t,r){if("number"!=typeof e)throw new TypeError("Argument must be a number");var n=i(e);return void 0!==t?"string"==typeof r?n.fill(t,r):n.fill(t):n.fill(0),n},a.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},a.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return n.SlowBuffer(e)}},{buffer:10}],55:[function(e,t,r){t.exports=i;var n=e("events").EventEmitter;function i(){n.call(this)}e("inherits")(i,n),i.Readable=e("readable-stream/readable.js"),i.Writable=e("readable-stream/writable.js"),i.Duplex=e("readable-stream/duplex.js"),i.Transform=e("readable-stream/transform.js"),i.PassThrough=e("readable-stream/passthrough.js"),i.Stream=i,i.prototype.pipe=function(e,t){var r=this;function i(t){e.writable&&!1===e.write(t)&&r.pause&&r.pause()}function o(){r.readable&&r.resume&&r.resume()}r.on("data",i),e.on("drain",o),e._isStdio||t&&!1===t.end||(r.on("end",s),r.on("close",u));var a=!1;function s(){a||(a=!0,e.end())}function u(){a||(a=!0,"function"==typeof e.destroy&&e.destroy())}function l(e){if(c(),0===n.listenerCount(this,"error"))throw e}function c(){r.removeListener("data",i),e.removeListener("drain",o),r.removeListener("end",s),r.removeListener("close",u),r.removeListener("error",l),e.removeListener("error",l),r.removeListener("end",c),r.removeListener("close",c),e.removeListener("close",c)}return r.on("error",l),e.on("error",l),r.on("end",c),r.on("close",c),e.on("close",c),e.emit("pipe",r),e}},{events:13,inherits:16,"readable-stream/duplex.js":39,"readable-stream/passthrough.js":50,"readable-stream/readable.js":51,"readable-stream/transform.js":52,"readable-stream/writable.js":53}],56:[function(e,t,r){(function(t){(function(){var n=e("./lib/request"),i=e("./lib/response"),o=e("xtend"),a=e("builtin-status-codes"),s=e("url"),u=r;u.request=function(e,r){e="string"==typeof e?s.parse(e):o(e);var i=-1===t.location.protocol.search(/^https?:$/)?"http:":"",a=e.protocol||i,u=e.hostname||e.host,l=e.port,c=e.path||"/";u&&-1!==u.indexOf(":")&&(u="["+u+"]"),e.url=(u?a+"//"+u:"")+(l?":"+l:"")+c,e.method=(e.method||"GET").toUpperCase(),e.headers=e.headers||{};var f=new n(e);return r&&f.on("response",r),f},u.get=function(e,t){var r=u.request(e,t);return r.end(),r},u.ClientRequest=n,u.IncomingMessage=i.IncomingMessage,u.Agent=function(){},u.Agent.defaultMaxSockets=4,u.globalAgent=new u.Agent,u.STATUS_CODES=a,u.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"]}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./lib/request":58,"./lib/response":59,"builtin-status-codes":11,url:77,xtend:83}],57:[function(e,t,r){(function(e){(function(){var t;function n(){if(void 0!==t)return t;if(e.XMLHttpRequest){t=new e.XMLHttpRequest;try{t.open("GET",e.XDomainRequest?"/":"https://example.com")}catch(e){t=null}}else t=null;return t}function i(e){var t=n();if(!t)return!1;try{return t.responseType=e,t.responseType===e}catch(e){}return!1}function o(e){return"function"==typeof e}r.fetch=o(e.fetch)&&o(e.ReadableStream),r.writableStream=o(e.WritableStream),r.abortController=o(e.AbortController),r.arraybuffer=r.fetch||i("arraybuffer"),r.msstream=!r.fetch&&i("ms-stream"),r.mozchunkedarraybuffer=!r.fetch&&i("moz-chunked-arraybuffer"),r.overrideMimeType=r.fetch||!!n()&&o(n().overrideMimeType),t=null}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],58:[function(e,t,r){(function(r,n,i){(function(){var o=e("./capability"),a=e("inherits"),s=e("./response"),u=e("readable-stream"),l=s.IncomingMessage,c=s.readyStates;var f=t.exports=function(e){var t,r=this;u.Writable.call(r),r._opts=e,r._body=[],r._headers={},e.auth&&r.setHeader("Authorization","Basic "+i.from(e.auth).toString("base64")),Object.keys(e.headers).forEach(function(t){r.setHeader(t,e.headers[t])});var n=!0;if("disable-fetch"===e.mode||"requestTimeout"in e&&!o.abortController)n=!1,t=!0;else if("prefer-streaming"===e.mode)t=!1;else if("allow-wrong-content-type"===e.mode)t=!o.overrideMimeType;else{if(e.mode&&"default"!==e.mode&&"prefer-fast"!==e.mode)throw new Error("Invalid value for opts.mode");t=!0}r._mode=function(e,t){return o.fetch&&t?"fetch":o.mozchunkedarraybuffer?"moz-chunked-arraybuffer":o.msstream?"ms-stream":o.arraybuffer&&e?"arraybuffer":"text"}(t,n),r._fetchTimer=null,r._socketTimeout=null,r._socketTimer=null,r.on("finish",function(){r._onFinish()})};a(f,u.Writable),f.prototype.setHeader=function(e,t){var r=e.toLowerCase();-1===h.indexOf(r)&&(this._headers[r]={name:e,value:t})},f.prototype.getHeader=function(e){var t=this._headers[e.toLowerCase()];return t?t.value:null},f.prototype.removeHeader=function(e){delete this._headers[e.toLowerCase()]},f.prototype._onFinish=function(){var e=this;if(!e._destroyed){var t=e._opts;"timeout"in t&&0!==t.timeout&&e.setTimeout(t.timeout);var i=e._headers,a=null;"GET"!==t.method&&"HEAD"!==t.method&&(a=new Blob(e._body,{type:(i["content-type"]||{}).value||""}));var s=[];if(Object.keys(i).forEach(function(e){var t=i[e].name,r=i[e].value;Array.isArray(r)?r.forEach(function(e){s.push([t,e])}):s.push([t,r])}),"fetch"===e._mode){var u=null;if(o.abortController){var l=new AbortController;u=l.signal,e._fetchAbortController=l,"requestTimeout"in t&&0!==t.requestTimeout&&(e._fetchTimer=n.setTimeout(function(){e.emit("requestTimeout"),e._fetchAbortController&&e._fetchAbortController.abort()},t.requestTimeout))}n.fetch(e._opts.url,{method:e._opts.method,headers:s,body:a||void 0,mode:"cors",credentials:t.withCredentials?"include":"same-origin",signal:u}).then(function(t){e._fetchResponse=t,e._resetTimers(!1),e._connect()},function(t){e._resetTimers(!0),e._destroyed||e.emit("error",t)})}else{var f=e._xhr=new n.XMLHttpRequest;try{f.open(e._opts.method,e._opts.url,!0)}catch(t){return void r.nextTick(function(){e.emit("error",t)})}"responseType"in f&&(f.responseType=e._mode),"withCredentials"in f&&(f.withCredentials=!!t.withCredentials),"text"===e._mode&&"overrideMimeType"in f&&f.overrideMimeType("text/plain; charset=x-user-defined"),"requestTimeout"in t&&(f.timeout=t.requestTimeout,f.ontimeout=function(){e.emit("requestTimeout")}),s.forEach(function(e){f.setRequestHeader(e[0],e[1])}),e._response=null,f.onreadystatechange=function(){switch(f.readyState){case c.LOADING:case c.DONE:e._onXHRProgress()}},"moz-chunked-arraybuffer"===e._mode&&(f.onprogress=function(){e._onXHRProgress()}),f.onerror=function(){e._destroyed||(e._resetTimers(!0),e.emit("error",new Error("XHR error")))};try{f.send(a)}catch(t){return void r.nextTick(function(){e.emit("error",t)})}}}},f.prototype._onXHRProgress=function(){this._resetTimers(!1),function(e){try{var t=e.status;return null!==t&&0!==t}catch(e){return!1}}(this._xhr)&&!this._destroyed&&(this._response||this._connect(),this._response._onXHRProgress(this._resetTimers.bind(this)))},f.prototype._connect=function(){var e=this;e._destroyed||(e._response=new l(e._xhr,e._fetchResponse,e._mode,e._resetTimers.bind(e)),e._response.on("error",function(t){e.emit("error",t)}),e.emit("response",e._response))},f.prototype._write=function(e,t,r){this._body.push(e),r()},f.prototype._resetTimers=function(e){var t=this;n.clearTimeout(t._socketTimer),t._socketTimer=null,e?(n.clearTimeout(t._fetchTimer),t._fetchTimer=null):t._socketTimeout&&(t._socketTimer=n.setTimeout(function(){t.emit("timeout")},t._socketTimeout))},f.prototype.abort=f.prototype.destroy=function(e){this._destroyed=!0,this._resetTimers(!0),this._response&&(this._response._destroyed=!0),this._xhr?this._xhr.abort():this._fetchAbortController&&this._fetchAbortController.abort(),e&&this.emit("error",e)},f.prototype.end=function(e,t,r){"function"==typeof e&&(r=e,e=void 0),u.Writable.prototype.end.call(this,e,t,r)},f.prototype.setTimeout=function(e,t){t&&this.once("timeout",t),this._socketTimeout=e,this._resetTimers(!1)},f.prototype.flushHeaders=function(){},f.prototype.setNoDelay=function(){},f.prototype.setSocketKeepAlive=function(){};var h=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"]}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"./capability":57,"./response":59,_process:34,buffer:10,inherits:16,"readable-stream":74}],59:[function(e,t,r){(function(t,n,i){(function(){var o=e("./capability"),a=e("inherits"),s=e("readable-stream"),u=r.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},l=r.IncomingMessage=function(e,r,n,a){var u=this;if(s.Readable.call(u),u._mode=n,u.headers={},u.rawHeaders=[],u.trailers={},u.rawTrailers=[],u.on("end",function(){t.nextTick(function(){u.emit("close")})}),"fetch"===n){if(u._fetchResponse=r,u.url=r.url,u.statusCode=r.status,u.statusMessage=r.statusText,r.headers.forEach(function(e,t){u.headers[t.toLowerCase()]=e,u.rawHeaders.push(t,e)}),o.writableStream){var l=new WritableStream({write:function(e){return a(!1),new Promise(function(t,r){u._destroyed?r():u.push(i.from(e))?t():u._resumeFetch=t})},close:function(){a(!0),u._destroyed||u.push(null)},abort:function(e){a(!0),u._destroyed||u.emit("error",e)}});try{return void r.body.pipeTo(l).catch(function(e){a(!0),u._destroyed||u.emit("error",e)})}catch(e){}}var c=r.body.getReader();!function e(){c.read().then(function(t){u._destroyed||(a(t.done),t.done?u.push(null):(u.push(i.from(t.value)),e()))}).catch(function(e){a(!0),u._destroyed||u.emit("error",e)})}()}else{if(u._xhr=e,u._pos=0,u.url=e.responseURL,u.statusCode=e.status,u.statusMessage=e.statusText,e.getAllResponseHeaders().split(/\r?\n/).forEach(function(e){var t=e.match(/^([^:]+):\s*(.*)/);if(t){var r=t[1].toLowerCase();"set-cookie"===r?(void 0===u.headers[r]&&(u.headers[r]=[]),u.headers[r].push(t[2])):void 0!==u.headers[r]?u.headers[r]+=", "+t[2]:u.headers[r]=t[2],u.rawHeaders.push(t[1],t[2])}}),u._charset="x-user-defined",!o.overrideMimeType){var f=u.rawHeaders["mime-type"];if(f){var h=f.match(/;\s*charset=([^;])(;|$)/);h&&(u._charset=h[1].toLowerCase())}u._charset||(u._charset="utf-8")}}};a(l,s.Readable),l.prototype._read=function(){var e=this._resumeFetch;e&&(this._resumeFetch=null,e())},l.prototype._onXHRProgress=function(e){var t=this,r=t._xhr,o=null;switch(t._mode){case"text":if((o=r.responseText).length>t._pos){var a=o.substr(t._pos);if("x-user-defined"===t._charset){for(var s=i.alloc(a.length),l=0;lt._pos&&(t.push(i.from(new Uint8Array(c.result.slice(t._pos)))),t._pos=c.result.byteLength)},c.onload=function(){e(!0),t.push(null)},c.readAsArrayBuffer(o)}t._xhr.readyState===u.DONE&&"ms-stream"!==t._mode&&(e(!0),t.push(null))}}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{"./capability":57,_process:34,buffer:10,inherits:16,"readable-stream":74}],60:[function(e,t,r){"use strict";var n={};function i(e,t,r){r||(r=Error);var i=function(e){var r,n;function i(r,n,i){return e.call(this,function(e,r,n){return"string"==typeof t?t:t(e,r,n)}(r,n,i))||this}return n=e,(r=i).prototype=Object.create(n.prototype),r.prototype.constructor=r,r.__proto__=n,i}(r);i.prototype.name=r.name,i.prototype.code=e,n[e]=i}function o(e,t){if(Array.isArray(e)){var r=e.length;return e=e.map(function(e){return String(e)}),r>2?"one of ".concat(t," ").concat(e.slice(0,r-1).join(", "),", or ")+e[r-1]:2===r?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}i("ERR_INVALID_OPT_VALUE",function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'},TypeError),i("ERR_INVALID_ARG_TYPE",function(e,t,r){var n,i,a,s;if("string"==typeof t&&(i="not ",t.substr(!a||a<0?0:+a,i.length)===i)?(n="must not be",t=t.replace(/^not /,"")):n="must be",function(e,t,r){return(void 0===r||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}(e," argument"))s="The ".concat(e," ").concat(n," ").concat(o(t,"type"));else{var u=function(e,t,r){return"number"!=typeof r&&(r=0),!(r+t.length>e.length)&&-1!==e.indexOf(t,r)}(e,".")?"property":"argument";s='The "'.concat(e,'" ').concat(u," ").concat(n," ").concat(o(t,"type"))}return s+=". Received type ".concat(typeof r)},TypeError),i("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),i("ERR_METHOD_NOT_IMPLEMENTED",function(e){return"The "+e+" method is not implemented"}),i("ERR_STREAM_PREMATURE_CLOSE","Premature close"),i("ERR_STREAM_DESTROYED",function(e){return"Cannot call "+e+" after a stream was destroyed"}),i("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),i("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),i("ERR_STREAM_WRITE_AFTER_END","write after end"),i("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),i("ERR_UNKNOWN_ENCODING",function(e){return"Unknown encoding: "+e},TypeError),i("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),t.exports.codes=n},{}],61:[function(e,t,r){(function(r){(function(){"use strict";var n=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};t.exports=l;var i=e("./_stream_readable"),o=e("./_stream_writable");e("inherits")(l,i);for(var a=n(o.prototype),s=0;s0)if("string"==typeof t||a.objectMode||Object.getPrototypeOf(t)===s.prototype||(t=function(e){return s.from(e)}(t)),n)a.endEmitted?E(e,new w):T(e,a,t,!0);else if(a.ended)E(e,new v);else{if(a.destroyed)return!1;a.reading=!1,a.decoder&&!r?(t=a.decoder.write(t),a.objectMode||0!==t.length?T(e,a,t,!1):C(e,a)):T(e,a,t,!1)}else n||(a.reading=!1,C(e,a));return!a.ended&&(a.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=j?e=j:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function A(e){var t=e._readableState;l("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(l("emitReadable",t.flowing),t.emittedReadable=!0,r.nextTick(M,e))}function M(e){var t=e._readableState;l("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,N(e)}function C(e,t){t.readingMore||(t.readingMore=!0,r.nextTick(L,e,t))}function L(e,t){for(;!t.reading&&!t.ended&&(t.length0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function I(e){l("readable nexttick read 0"),e.read(0)}function D(e,t){l("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),N(e),t.flowing&&!t.reading&&e.read(0)}function N(e){var t=e._readableState;for(l("flow",t.flowing);t.flowing&&null!==e.read(););}function U(e,t){return 0===t.length?null:(t.objectMode?r=t.buffer.shift():!e||e>=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):r=t.buffer.consume(e,t.decoder),r);var r}function B(e){var t=e._readableState;l("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,r.nextTick(z,t,e))}function z(e,t){if(l("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var r=t._writableState;(!r||r.autoDestroy&&r.finished)&&t.destroy()}}function F(e,t){for(var r=0,n=e.length;r=t.highWaterMark:t.length>0)||t.ended))return l("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?B(this):A(this),null;if(0===(e=R(e,t))&&t.ended)return 0===t.length&&B(this),null;var n,i=t.needReadable;return l("need readable",i),(0===t.length||t.length-e0?U(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&B(this)),null!==n&&this.emit("data",n),n},x.prototype._read=function(e){E(this,new _("_read()"))},x.prototype.pipe=function(e,t){var n=this,i=this._readableState;switch(i.pipesCount){case 0:i.pipes=e;break;case 1:i.pipes=[i.pipes,e];break;default:i.pipes.push(e)}i.pipesCount+=1,l("pipe count=%d opts=%j",i.pipesCount,t);var a=(!t||!1!==t.end)&&e!==r.stdout&&e!==r.stderr?u:m;function s(t,r){l("onunpipe"),t===n&&r&&!1===r.hasUnpiped&&(r.hasUnpiped=!0,l("cleanup"),e.removeListener("close",d),e.removeListener("finish",g),e.removeListener("drain",c),e.removeListener("error",p),e.removeListener("unpipe",s),n.removeListener("end",u),n.removeListener("end",m),n.removeListener("data",h),f=!0,!i.awaitDrain||e._writableState&&!e._writableState.needDrain||c())}function u(){l("onend"),e.end()}i.endEmitted?r.nextTick(a):n.once("end",a),e.on("unpipe",s);var c=function(e){return function(){var t=e._readableState;l("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&o(e,"data")&&(t.flowing=!0,N(e))}}(n);e.on("drain",c);var f=!1;function h(t){l("ondata");var r=e.write(t);l("dest.write",r),!1===r&&((1===i.pipesCount&&i.pipes===e||i.pipesCount>1&&-1!==F(i.pipes,e))&&!f&&(l("false write response, pause",i.awaitDrain),i.awaitDrain++),n.pause())}function p(t){l("onerror",t),m(),e.removeListener("error",p),0===o(e,"error")&&E(e,t)}function d(){e.removeListener("finish",g),m()}function g(){l("onfinish"),e.removeListener("close",d),m()}function m(){l("unpipe"),n.unpipe(e)}return n.on("data",h),function(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}(e,"error",p),e.once("close",d),e.once("finish",g),e.emit("pipe",n),i.flowing||(l("pipe resume"),n.resume()),e},x.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,r),this);if(!e){var n=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o0,!1!==i.flowing&&this.resume()):"readable"===e&&(i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.flowing=!1,i.emittedReadable=!1,l("on readable",i.length,i.reading),i.length?A(this):i.reading||r.nextTick(I,this))),n},x.prototype.addListener=x.prototype.on,x.prototype.removeListener=function(e,t){var n=a.prototype.removeListener.call(this,e,t);return"readable"===e&&r.nextTick(P,this),n},x.prototype.removeAllListeners=function(e){var t=a.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||r.nextTick(P,this),t},x.prototype.resume=function(){var e=this._readableState;return e.flowing||(l("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,r.nextTick(D,e,t))}(this,e)),e.paused=!1,this},x.prototype.pause=function(){return l("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(l("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},x.prototype.wrap=function(e){var t=this,r=this._readableState,n=!1;for(var i in e.on("end",function(){if(l("wrapped end"),r.decoder&&!r.ended){var e=r.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on("data",function(i){(l("wrapped data"),r.decoder&&(i=r.decoder.write(i)),!r.objectMode||null!==i&&void 0!==i)&&((r.objectMode||i&&i.length)&&(t.push(i)||(n=!0,e.pause())))}),e)void 0===this[i]&&"function"==typeof e[i]&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var o=0;o-1))throw new w(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(x.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(x.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),x.prototype._write=function(e,t,r){r(new g("_write()"))},x.prototype._writev=null,x.prototype.end=function(e,t,n){var i=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!==e&&void 0!==e&&this.write(e,t),i.corked&&(i.corked=1,this.uncork()),i.ending||function(e,t,n){t.ending=!0,M(e,t),n&&(t.finished?r.nextTick(n):e.once("finish",n));t.ended=!0,e.writable=!1}(this,i,n),this},Object.defineProperty(x.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(x.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),x.prototype.destroy=f.destroy,x.prototype._undestroy=f.undestroy,x.prototype._destroy=function(e,t){t(e)}}).call(this)}).call(this,e("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"../errors":60,"./_stream_duplex":61,"./internal/streams/destroy":68,"./internal/streams/state":72,"./internal/streams/stream":73,_process:34,buffer:10,inherits:16,"util-deprecate":79}],66:[function(e,t,r){(function(r){(function(){"use strict";var n;function i(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var o=e("./end-of-stream"),a=Symbol("lastResolve"),s=Symbol("lastReject"),u=Symbol("error"),l=Symbol("ended"),c=Symbol("lastPromise"),f=Symbol("handlePromise"),h=Symbol("stream");function p(e,t){return{value:e,done:t}}function d(e){var t=e[a];if(null!==t){var r=e[h].read();null!==r&&(e[c]=null,e[a]=null,e[s]=null,t(p(r,!1)))}}var g=Object.getPrototypeOf(function(){}),m=Object.setPrototypeOf((i(n={get stream(){return this[h]},next:function(){var e=this,t=this[u];if(null!==t)return Promise.reject(t);if(this[l])return Promise.resolve(p(void 0,!0));if(this[h].destroyed)return new Promise(function(t,n){r.nextTick(function(){e[u]?n(e[u]):t(p(void 0,!0))})});var n,i=this[c];if(i)n=new Promise(function(e,t){return function(r,n){e.then(function(){t[l]?r(p(void 0,!0)):t[f](r,n)},n)}}(i,this));else{var o=this[h].read();if(null!==o)return Promise.resolve(p(o,!1));n=new Promise(this[f])}return this[c]=n,n}},Symbol.asyncIterator,function(){return this}),i(n,"return",function(){var e=this;return new Promise(function(t,r){e[h].destroy(null,function(e){e?r(e):t(p(void 0,!0))})})}),n),g);t.exports=function(e){var t,n=Object.create(m,(i(t={},h,{value:e,writable:!0}),i(t,a,{value:null,writable:!0}),i(t,s,{value:null,writable:!0}),i(t,u,{value:null,writable:!0}),i(t,l,{value:e._readableState.endEmitted,writable:!0}),i(t,f,{value:function(e,t){var r=n[h].read();r?(n[c]=null,n[a]=null,n[s]=null,e(p(r,!1))):(n[a]=e,n[s]=t)},writable:!0}),t));return n[c]=null,o(e,function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=n[s];return null!==t&&(n[c]=null,n[a]=null,n[s]=null,t(e)),void(n[u]=e)}var r=n[a];null!==r&&(n[c]=null,n[a]=null,n[s]=null,r(p(void 0,!0))),n[l]=!0}),e.on("readable",function(e){r.nextTick(d,e)}.bind(null,n)),n}}).call(this)}).call(this,e("_process"))},{"./end-of-stream":69,_process:34}],67:[function(e,t,r){"use strict";function n(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function i(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function o(e,t){for(var r=0;r0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r}},{key:"concat",value:function(e){if(0===this.length)return a.alloc(0);for(var t,r,n,i=a.allocUnsafe(e>>>0),o=this.head,s=0;o;)t=o.data,r=i,n=s,a.prototype.copy.call(t,r,n),s+=o.data.length,o=o.next;return i}},{key:"consume",value:function(e,t){var r;return ei.length?i.length:e;if(o===i.length?n+=i:n+=i.slice(0,e),0===(e-=o)){o===i.length?(++r,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(o));break}++r}return this.length-=r,n}},{key:"_getBuffer",value:function(e){var t=a.allocUnsafe(e),r=this.head,n=1;for(r.data.copy(t),e-=r.data.length;r=r.next;){var i=r.data,o=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,o),0===(e-=o)){o===i.length?(++n,r.next?this.head=r.next:this.head=this.tail=null):(this.head=r,r.data=i.slice(o));break}++n}return this.length-=n,t}},{key:u,value:function(e,t){return s(this,function(e){for(var t=1;t0,function(e){c||(c=e),e&&h.forEach(u),o||(h.forEach(u),f(c))})});return r.reduce(l)}},{"../../../errors":60,"./end-of-stream":69}],72:[function(e,t,r){"use strict";var n=e("../../../errors").codes.ERR_INVALID_OPT_VALUE;t.exports={getHighWaterMark:function(e,t,r,i){var o=function(e,t,r){return null!=e.highWaterMark?e.highWaterMark:t?e[r]:null}(t,i,r);if(null!=o){if(!isFinite(o)||Math.floor(o)!==o||o<0)throw new n(i?r:"highWaterMark",o);return Math.floor(o)}return e.objectMode?16:16384}}},{"../../../errors":60}],73:[function(e,t,r){arguments[4][47][0].apply(r,arguments)},{dup:47,events:13}],74:[function(e,t,r){(r=t.exports=e("./lib/_stream_readable.js")).Stream=r,r.Readable=r,r.Writable=e("./lib/_stream_writable.js"),r.Duplex=e("./lib/_stream_duplex.js"),r.Transform=e("./lib/_stream_transform.js"),r.PassThrough=e("./lib/_stream_passthrough.js"),r.finished=e("./lib/internal/streams/end-of-stream.js"),r.pipeline=e("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":61,"./lib/_stream_passthrough.js":62,"./lib/_stream_readable.js":63,"./lib/_stream_transform.js":64,"./lib/_stream_writable.js":65,"./lib/internal/streams/end-of-stream.js":69,"./lib/internal/streams/pipeline.js":71}],75:[function(e,t,r){arguments[4][49][0].apply(r,arguments)},{dup:49,"safe-buffer":54}],76:[function(e,t,r){(function(t,n){(function(){var i=e("process/browser.js").nextTick,o=Function.prototype.apply,a=Array.prototype.slice,s={},u=0;function l(e,t){this._id=e,this._clearFn=t}r.setTimeout=function(){return new l(o.call(setTimeout,window,arguments),clearTimeout)},r.setInterval=function(){return new l(o.call(setInterval,window,arguments),clearInterval)},r.clearTimeout=r.clearInterval=function(e){e.close()},l.prototype.unref=l.prototype.ref=function(){},l.prototype.close=function(){this._clearFn.call(window,this._id)},r.enroll=function(e,t){clearTimeout(e._idleTimeoutId),e._idleTimeout=t},r.unenroll=function(e){clearTimeout(e._idleTimeoutId),e._idleTimeout=-1},r._unrefActive=r.active=function(e){clearTimeout(e._idleTimeoutId);var t=e._idleTimeout;t>=0&&(e._idleTimeoutId=setTimeout(function(){e._onTimeout&&e._onTimeout()},t))},r.setImmediate="function"==typeof t?t:function(e){var t=u++,n=!(arguments.length<2)&&a.call(arguments,1);return s[t]=!0,i(function(){s[t]&&(n?e.apply(null,n):e.call(null),r.clearImmediate(t))}),t},r.clearImmediate="function"==typeof n?n:function(e){delete s[e]}}).call(this)}).call(this,e("timers").setImmediate,e("timers").clearImmediate)},{"process/browser.js":34,timers:76}],77:[function(e,t,r){"use strict";var n=e("punycode"),i=e("./util");function o(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}r.parse=v,r.resolve=function(e,t){return v(e,!1,!0).resolve(t)},r.resolveObject=function(e,t){return e?v(e,!1,!0).resolveObject(t):t},r.format=function(e){i.isString(e)&&(e=v(e));return e instanceof o?e.format():o.prototype.format.call(e)},r.Url=o;var a=/^([a-z0-9.+-]+:)/i,s=/:[0-9]*$/,u=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,l=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),c=["'"].concat(l),f=["%","/","?",";","#"].concat(c),h=["/","?","#"],p=/^[+a-z0-9A-Z_-]{0,63}$/,d=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,g={javascript:!0,"javascript:":!0},m={javascript:!0,"javascript:":!0},y={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},b=e("querystring");function v(e,t,r){if(e&&i.isObject(e)&&e instanceof o)return e;var n=new o;return n.parse(e,t,r),n}o.prototype.parse=function(e,t,r){if(!i.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var o=e.indexOf("?"),s=-1!==o&&o127?L+="x":L+=C[P];if(!L.match(p)){var D=A.slice(0,T),N=A.slice(T+1),U=C.match(d);U&&(D.push(U[1]),N.unshift(U[2])),N.length&&(v="/"+N.join(".")+v),this.hostname=D.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),R||(this.hostname=n.toASCII(this.hostname));var B=this.port?":"+this.port:"",z=this.hostname||"";this.host=z+B,this.href+=this.host,R&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==v[0]&&(v="/"+v))}if(!g[E])for(T=0,M=c.length;T0)&&r.host.split("@"))&&(r.auth=R.shift(),r.host=r.hostname=R.shift());return r.search=e.search,r.query=e.query,i.isNull(r.pathname)&&i.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!k.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var x=k.slice(-1)[0],O=(r.host||e.host||k.length>1)&&("."===x||".."===x)||""===x,T=0,j=k.length;j>=0;j--)"."===(x=k[j])?k.splice(j,1):".."===x?(k.splice(j,1),T++):T&&(k.splice(j,1),T--);if(!w&&!E)for(;T--;T)k.unshift("..");!w||""===k[0]||k[0]&&"/"===k[0].charAt(0)||k.unshift(""),O&&"/"!==k.join("/").substr(-1)&&k.push("");var R,A=""===k[0]||k[0]&&"/"===k[0].charAt(0);S&&(r.hostname=r.host=A?"":k.length?k.shift():"",(R=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@"))&&(r.auth=R.shift(),r.host=r.hostname=R.shift()));return(w=w||r.host&&k.length)&&!A&&k.unshift(""),k.length?r.pathname=k.join("/"):(r.pathname=null,r.path=null),i.isNull(r.pathname)&&i.isNull(r.search)||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=e.auth||r.auth,r.slashes=r.slashes||e.slashes,r.href=r.format(),r},o.prototype.parseHost=function(){var e=this.host,t=s.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)}},{"./util":78,punycode:35,querystring:38}],78:[function(e,t,r){"use strict";t.exports={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}}},{}],79:[function(e,t,r){(function(e){(function(){function r(t){try{if(!e.localStorage)return!1}catch(e){return!1}var r=e.localStorage[t];return null!=r&&"true"===String(r).toLowerCase()}t.exports=function(e,t){if(r("noDeprecation"))return e;var n=!1;return function(){if(!n){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],80:[function(e,t,r){arguments[4][3][0].apply(r,arguments)},{dup:3}],81:[function(e,t,r){arguments[4][4][0].apply(r,arguments)},{dup:4}],82:[function(e,t,r){arguments[4][5][0].apply(r,arguments)},{"./support/isBuffer":81,_process:34,dup:5,inherits:80}],83:[function(e,t,r){t.exports=function(){for(var e={},t=0;t{u(t,null,e)},e=>{u(t,e&&e.message?e:new Error(e))})}function u(e,t,r){try{e(t,r)}catch(e){(0,i.default)(e=>{throw e},e)}}t.exports=r.default},{"./internal/initialParams":103,"./internal/setImmediate":109,"./internal/wrapAsync":111}],94:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=c(e("./internal/isArrayLike")),i=c(e("./internal/breakLoop")),o=c(e("./eachOfLimit")),a=c(e("./internal/once")),s=c(e("./internal/onlyOnce")),u=c(e("./internal/wrapAsync")),l=c(e("./internal/awaitify"));function c(e){return e&&e.__esModule?e:{default:e}}function f(e,t,r){r=(0,a.default)(r);var n=0,o=0,{length:u}=e,l=!1;function c(e,t){!1===e&&(l=!0),!0!==l&&(e?r(e):++o!==u&&t!==i.default||r(null))}for(0===u&&r(null);n=t||s||i||(s=!0,e.next().then(({value:e,done:t})=>{if(!a&&!i){if(s=!1,t)return i=!0,void(u<=0&&n(null));u++,r(e,l,f),l++,c()}}).catch(h))}function f(e,t){if(u-=1,!a)return e?h(e):!1===e?(i=!0,void(a=!0)):t===o.default||i&&u<=0?(i=!0,n(null)):void c()}function h(e){a||(s=!1,i=!0,n(e))}c()};var n,i=e("./breakLoop"),o=(n=i)&&n.__esModule?n:{default:n};t.exports=r.default},{"./breakLoop":100}],99:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t=e.length){if(!t)throw new Error("arity is undefined");return function(...r){if("function"==typeof r[t-1])return e.apply(this,r);return new Promise((n,i)=>{r[t-1]=((e,...t)=>{if(e)return i(e);n(t.length>1?t:t[0])}),e.apply(this,r)})}},t.exports=r.default},{}],100:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});r.default={},t.exports=r.default},{}],101:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0});var n=l(e("./once")),i=l(e("./iterator")),o=l(e("./onlyOnce")),a=e("./wrapAsync"),s=l(e("./asyncEachOfLimit")),u=l(e("./breakLoop"));function l(e){return e&&e.__esModule?e:{default:e}}r.default=(e=>(t,r,l)=>{if(l=(0,n.default)(l),e<=0)throw new RangeError("concurrency limit cannot be less than 1");if(!t)return l(null);if((0,a.isAsyncGenerator)(t))return(0,s.default)(t,e,r,l);if((0,a.isAsyncIterable)(t))return(0,s.default)(t[Symbol.asyncIterator](),e,r,l);var c=(0,i.default)(t),f=!1,h=!1,p=0,d=!1;function g(e,t){if(!h)if(p-=1,e)f=!0,l(e);else if(!1===e)f=!0,h=!0;else{if(t===u.default||f&&p<=0)return f=!0,l(null);d||m()}}function m(){for(d=!0;p=0&&e.length%1==0},t.exports=r.default},{}],105:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){if((0,n.default)(e))return function(e){var t=-1,r=e.length;return function(){return++t{var o=(0,n.default)(t)?[]:{};e(t,(e,t,r)=>{(0,i.default)(e)((e,...n)=>{n.length<2&&([n]=n),o[t]=n,r(e)})},e=>r(e,o))},3),t.exports=r.default},{"./awaitify":99,"./isArrayLike":104,"./wrapAsync":111}],109:[function(e,t,r){(function(e,t){(function(){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.fallback=a,r.wrap=s;var n,i=r.hasSetImmediate="function"==typeof t&&t,o=r.hasNextTick="object"==typeof e&&"function"==typeof e.nextTick;function a(e){setTimeout(e,0)}function s(e){return(t,...r)=>e(()=>t(...r))}n=i?t:o?e.nextTick:a,r.default=s(n)}).call(this)}).call(this,e("_process"),e("timers").setImmediate)},{_process:34,timers:76}],110:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e){return(t,r,n)=>e(t,n)},t.exports=r.default},{}],111:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.isAsyncIterable=r.isAsyncGenerator=r.isAsync=void 0;var n,i=e("../asyncify"),o=(n=i)&&n.__esModule?n:{default:n};function a(e){return"AsyncFunction"===e[Symbol.toStringTag]}r.default=function(e){if("function"!=typeof e)throw new Error("expected a function");return a(e)?(0,o.default)(e):e},r.isAsync=a,r.isAsyncGenerator=function(e){return"AsyncGenerator"===e[Symbol.toStringTag]},r.isAsyncIterable=function(e){return"function"==typeof e[Symbol.asyncIterator]}},{"../asyncify":93}],112:[function(e,t,r){"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.default=function(e,t){return(0,n.default)(i.default,e,t)};var n=o(e("./internal/parallel")),i=o(e("./eachOfSeries"));function o(e){return e&&e.__esModule?e:{default:e}}t.exports=r.default},{"./eachOfSeries":96,"./internal/parallel":108}],113:[function(e,t,r){var n=e("color-name"),i={};for(var o in n)n.hasOwnProperty(o)&&(i[n[o]]=o);var a=t.exports={rgb:{channels:3,labels:"rgb"},hsl:{channels:3,labels:"hsl"},hsv:{channels:3,labels:"hsv"},hwb:{channels:3,labels:"hwb"},cmyk:{channels:4,labels:"cmyk"},xyz:{channels:3,labels:"xyz"},lab:{channels:3,labels:"lab"},lch:{channels:3,labels:"lch"},hex:{channels:1,labels:["hex"]},keyword:{channels:1,labels:["keyword"]},ansi16:{channels:1,labels:["ansi16"]},ansi256:{channels:1,labels:["ansi256"]},hcg:{channels:3,labels:["h","c","g"]},apple:{channels:3,labels:["r16","g16","b16"]},gray:{channels:1,labels:["gray"]}};for(var s in a)if(a.hasOwnProperty(s)){if(!("channels"in a[s]))throw new Error("missing channels property: "+s);if(!("labels"in a[s]))throw new Error("missing channel labels property: "+s);if(a[s].labels.length!==a[s].channels)throw new Error("channel and label counts mismatch: "+s);var u=a[s].channels,l=a[s].labels;delete a[s].channels,delete a[s].labels,Object.defineProperty(a[s],"channels",{value:u}),Object.defineProperty(a[s],"labels",{value:l})}a.rgb.hsl=function(e){var t,r,n=e[0]/255,i=e[1]/255,o=e[2]/255,a=Math.min(n,i,o),s=Math.max(n,i,o),u=s-a;return s===a?t=0:n===s?t=(i-o)/u:i===s?t=2+(o-n)/u:o===s&&(t=4+(n-i)/u),(t=Math.min(60*t,360))<0&&(t+=360),r=(a+s)/2,[t,100*(s===a?0:r<=.5?u/(s+a):u/(2-s-a)),100*r]},a.rgb.hsv=function(e){var t,r,n,i,o,a=e[0]/255,s=e[1]/255,u=e[2]/255,l=Math.max(a,s,u),c=l-Math.min(a,s,u),f=function(e){return(l-e)/6/c+.5};return 0===c?i=o=0:(o=c/l,t=f(a),r=f(s),n=f(u),a===l?i=n-r:s===l?i=1/3+t-n:u===l&&(i=2/3+r-t),i<0?i+=1:i>1&&(i-=1)),[360*i,100*o,100*l]},a.rgb.hwb=function(e){var t=e[0],r=e[1],n=e[2];return[a.rgb.hsl(e)[0],100*(1/255*Math.min(t,Math.min(r,n))),100*(n=1-1/255*Math.max(t,Math.max(r,n)))]},a.rgb.cmyk=function(e){var t,r=e[0]/255,n=e[1]/255,i=e[2]/255;return[100*((1-r-(t=Math.min(1-r,1-n,1-i)))/(1-t)||0),100*((1-n-t)/(1-t)||0),100*((1-i-t)/(1-t)||0),100*t]},a.rgb.keyword=function(e){var t=i[e];if(t)return t;var r,o,a,s=1/0;for(var u in n)if(n.hasOwnProperty(u)){var l=n[u],c=(o=e,a=l,Math.pow(o[0]-a[0],2)+Math.pow(o[1]-a[1],2)+Math.pow(o[2]-a[2],2));c.04045?Math.pow((t+.055)/1.055,2.4):t/12.92)+.3576*(r=r>.04045?Math.pow((r+.055)/1.055,2.4):r/12.92)+.1805*(n=n>.04045?Math.pow((n+.055)/1.055,2.4):n/12.92)),100*(.2126*t+.7152*r+.0722*n),100*(.0193*t+.1192*r+.9505*n)]},a.rgb.lab=function(e){var t=a.rgb.xyz(e),r=t[0],n=t[1],i=t[2];return n/=100,i/=108.883,r=(r/=95.047)>.008856?Math.pow(r,1/3):7.787*r+16/116,[116*(n=n>.008856?Math.pow(n,1/3):7.787*n+16/116)-16,500*(r-n),200*(n-(i=i>.008856?Math.pow(i,1/3):7.787*i+16/116))]},a.hsl.rgb=function(e){var t,r,n,i,o,a=e[0]/360,s=e[1]/100,u=e[2]/100;if(0===s)return[o=255*u,o,o];t=2*u-(r=u<.5?u*(1+s):u+s-u*s),i=[0,0,0];for(var l=0;l<3;l++)(n=a+1/3*-(l-1))<0&&n++,n>1&&n--,o=6*n<1?t+6*(r-t)*n:2*n<1?r:3*n<2?t+(r-t)*(2/3-n)*6:t,i[l]=255*o;return i},a.hsl.hsv=function(e){var t=e[0],r=e[1]/100,n=e[2]/100,i=r,o=Math.max(n,.01);return r*=(n*=2)<=1?n:2-n,i*=o<=1?o:2-o,[t,100*(0===n?2*i/(o+i):2*r/(n+r)),100*((n+r)/2)]},a.hsv.rgb=function(e){var t=e[0]/60,r=e[1]/100,n=e[2]/100,i=Math.floor(t)%6,o=t-Math.floor(t),a=255*n*(1-r),s=255*n*(1-r*o),u=255*n*(1-r*(1-o));switch(n*=255,i){case 0:return[n,u,a];case 1:return[s,n,a];case 2:return[a,n,u];case 3:return[a,s,n];case 4:return[u,a,n];case 5:return[n,a,s]}},a.hsv.hsl=function(e){var t,r,n,i=e[0],o=e[1]/100,a=e[2]/100,s=Math.max(a,.01);return n=(2-o)*a,r=o*s,[i,100*(r=(r/=(t=(2-o)*s)<=1?t:2-t)||0),100*(n/=2)]},a.hwb.rgb=function(e){var t,r,n,i,o,a,s,u=e[0]/360,l=e[1]/100,c=e[2]/100,f=l+c;switch(f>1&&(l/=f,c/=f),r=1-c,n=6*u-(t=Math.floor(6*u)),0!=(1&t)&&(n=1-n),i=l+n*(r-l),t){default:case 6:case 0:o=r,a=i,s=l;break;case 1:o=i,a=r,s=l;break;case 2:o=l,a=r,s=i;break;case 3:o=l,a=i,s=r;break;case 4:o=i,a=l,s=r;break;case 5:o=r,a=l,s=i}return[255*o,255*a,255*s]},a.cmyk.rgb=function(e){var t=e[0]/100,r=e[1]/100,n=e[2]/100,i=e[3]/100;return[255*(1-Math.min(1,t*(1-i)+i)),255*(1-Math.min(1,r*(1-i)+i)),255*(1-Math.min(1,n*(1-i)+i))]},a.xyz.rgb=function(e){var t,r,n,i=e[0]/100,o=e[1]/100,a=e[2]/100;return r=-.9689*i+1.8758*o+.0415*a,n=.0557*i+-.204*o+1.057*a,t=(t=3.2406*i+-1.5372*o+-.4986*a)>.0031308?1.055*Math.pow(t,1/2.4)-.055:12.92*t,r=r>.0031308?1.055*Math.pow(r,1/2.4)-.055:12.92*r,n=n>.0031308?1.055*Math.pow(n,1/2.4)-.055:12.92*n,[255*(t=Math.min(Math.max(0,t),1)),255*(r=Math.min(Math.max(0,r),1)),255*(n=Math.min(Math.max(0,n),1))]},a.xyz.lab=function(e){var t=e[0],r=e[1],n=e[2];return r/=100,n/=108.883,t=(t/=95.047)>.008856?Math.pow(t,1/3):7.787*t+16/116,[116*(r=r>.008856?Math.pow(r,1/3):7.787*r+16/116)-16,500*(t-r),200*(r-(n=n>.008856?Math.pow(n,1/3):7.787*n+16/116))]},a.lab.xyz=function(e){var t,r,n,i=e[0],o=e[1],a=e[2];t=o/500+(r=(i+16)/116),n=r-a/200;var s=Math.pow(r,3),u=Math.pow(t,3),l=Math.pow(n,3);return r=s>.008856?s:(r-16/116)/7.787,t=u>.008856?u:(t-16/116)/7.787,n=l>.008856?l:(n-16/116)/7.787,[t*=95.047,r*=100,n*=108.883]},a.lab.lch=function(e){var t,r=e[0],n=e[1],i=e[2];return(t=360*Math.atan2(i,n)/2/Math.PI)<0&&(t+=360),[r,Math.sqrt(n*n+i*i),t]},a.lch.lab=function(e){var t,r=e[0],n=e[1];return t=e[2]/360*2*Math.PI,[r,n*Math.cos(t),n*Math.sin(t)]},a.rgb.ansi16=function(e){var t=e[0],r=e[1],n=e[2],i=1 in arguments?arguments[1]:a.rgb.hsv(e)[2];if(0===(i=Math.round(i/50)))return 30;var o=30+(Math.round(n/255)<<2|Math.round(r/255)<<1|Math.round(t/255));return 2===i&&(o+=60),o},a.hsv.ansi16=function(e){return a.rgb.ansi16(a.hsv.rgb(e),e[2])},a.rgb.ansi256=function(e){var t=e[0],r=e[1],n=e[2];return t===r&&r===n?t<8?16:t>248?231:Math.round((t-8)/247*24)+232:16+36*Math.round(t/255*5)+6*Math.round(r/255*5)+Math.round(n/255*5)},a.ansi16.rgb=function(e){var t=e%10;if(0===t||7===t)return e>50&&(t+=3.5),[t=t/10.5*255,t,t];var r=.5*(1+~~(e>50));return[(1&t)*r*255,(t>>1&1)*r*255,(t>>2&1)*r*255]},a.ansi256.rgb=function(e){if(e>=232){var t=10*(e-232)+8;return[t,t,t]}var r;return e-=16,[Math.floor(e/36)/5*255,Math.floor((r=e%36)/6)/5*255,r%6/5*255]},a.rgb.hex=function(e){var t=(((255&Math.round(e[0]))<<16)+((255&Math.round(e[1]))<<8)+(255&Math.round(e[2]))).toString(16).toUpperCase();return"000000".substring(t.length)+t},a.hex.rgb=function(e){var t=e.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!t)return[0,0,0];var r=t[0];3===t[0].length&&(r=r.split("").map(function(e){return e+e}).join(""));var n=parseInt(r,16);return[n>>16&255,n>>8&255,255&n]},a.rgb.hcg=function(e){var t,r,n=e[0]/255,i=e[1]/255,o=e[2]/255,a=Math.max(Math.max(n,i),o),s=Math.min(Math.min(n,i),o),u=a-s;return t=u<1?s/(1-u):0,r=u<=0?0:a===n?(i-o)/u%6:a===i?2+(o-n)/u:4+(n-i)/u+4,r/=6,[360*(r%=1),100*u,100*t]},a.hsl.hcg=function(e){var t=e[1]/100,r=e[2]/100,n=1,i=0;return(n=r<.5?2*t*r:2*t*(1-r))<1&&(i=(r-.5*n)/(1-n)),[e[0],100*n,100*i]},a.hsv.hcg=function(e){var t=e[1]/100,r=e[2]/100,n=t*r,i=0;return n<1&&(i=(r-n)/(1-n)),[e[0],100*n,100*i]},a.hcg.rgb=function(e){var t=e[0]/360,r=e[1]/100,n=e[2]/100;if(0===r)return[255*n,255*n,255*n];var i,o=[0,0,0],a=t%1*6,s=a%1,u=1-s;switch(Math.floor(a)){case 0:o[0]=1,o[1]=s,o[2]=0;break;case 1:o[0]=u,o[1]=1,o[2]=0;break;case 2:o[0]=0,o[1]=1,o[2]=s;break;case 3:o[0]=0,o[1]=u,o[2]=1;break;case 4:o[0]=s,o[1]=0,o[2]=1;break;default:o[0]=1,o[1]=0,o[2]=u}return i=(1-r)*n,[255*(r*o[0]+i),255*(r*o[1]+i),255*(r*o[2]+i)]},a.hcg.hsv=function(e){var t=e[1]/100,r=t+e[2]/100*(1-t),n=0;return r>0&&(n=t/r),[e[0],100*n,100*r]},a.hcg.hsl=function(e){var t=e[1]/100,r=e[2]/100*(1-t)+.5*t,n=0;return r>0&&r<.5?n=t/(2*r):r>=.5&&r<1&&(n=t/(2*(1-r))),[e[0],100*n,100*r]},a.hcg.hwb=function(e){var t=e[1]/100,r=t+e[2]/100*(1-t);return[e[0],100*(r-t),100*(1-r)]},a.hwb.hcg=function(e){var t=e[1]/100,r=1-e[2]/100,n=r-t,i=0;return n<1&&(i=(r-n)/(1-n)),[e[0],100*n,100*i]},a.apple.rgb=function(e){return[e[0]/65535*255,e[1]/65535*255,e[2]/65535*255]},a.rgb.apple=function(e){return[e[0]/255*65535,e[1]/255*65535,e[2]/255*65535]},a.gray.rgb=function(e){return[e[0]/100*255,e[0]/100*255,e[0]/100*255]},a.gray.hsl=a.gray.hsv=function(e){return[0,0,e[0]]},a.gray.hwb=function(e){return[0,100,e[0]]},a.gray.cmyk=function(e){return[0,0,0,e[0]]},a.gray.lab=function(e){return[e[0],0,0]},a.gray.hex=function(e){var t=255&Math.round(e[0]/100*255),r=((t<<16)+(t<<8)+t).toString(16).toUpperCase();return"000000".substring(r.length)+r},a.rgb.gray=function(e){return[(e[0]+e[1]+e[2])/3/255*100]}},{"color-name":116}],114:[function(e,t,r){var n=e("./conversions"),i=e("./route"),o={};Object.keys(n).forEach(function(e){o[e]={},Object.defineProperty(o[e],"channels",{value:n[e].channels}),Object.defineProperty(o[e],"labels",{value:n[e].labels});var t=i(e);Object.keys(t).forEach(function(r){var n=t[r];o[e][r]=function(e){var t=function(t){if(void 0===t||null===t)return t;arguments.length>1&&(t=Array.prototype.slice.call(arguments));var r=e(t);if("object"==typeof r)for(var n=r.length,i=0;i1&&(t=Array.prototype.slice.call(arguments)),e(t))};return"conversion"in e&&(t.conversion=e.conversion),t}(n)})}),t.exports=o},{"./conversions":113,"./route":115}],115:[function(e,t,r){var n=e("./conversions");function i(e){var t=function(){for(var e={},t=Object.keys(n),r=t.length,i=0;i=4&&1!==e[3]&&(t=", "+e[3]),"hwb("+e[0]+", "+e[1]+"%, "+e[2]+"%"+t+")"},s.to.keyword=function(e){return o[e.slice(0,3)]}},{"color-name":116,"simple-swizzle":175}],118:[function(e,t,r){"use strict";var n=e("color-string"),i=e("color-convert"),o=[].slice,a=["keyword","gray","hex"],s={};Object.keys(i).forEach(function(e){s[o.call(i[e].labels).sort().join("")]=e});var u={};function l(e,t){if(!(this instanceof l))return new l(e,t);if(t&&t in a&&(t=null),t&&!(t in i))throw new Error("Unknown model: "+t);var r,c;if(e)if(e instanceof l)this.model=e.model,this.color=e.color.slice(),this.valpha=e.valpha;else if("string"==typeof e){var f=n.get(e);if(null===f)throw new Error("Unable to parse color from string: "+e);this.model=f.model,c=i[this.model].channels,this.color=f.value.slice(0,c),this.valpha="number"==typeof f.value[c]?f.value[c]:1}else if(e.length){this.model=t||"rgb",c=i[this.model].channels;var p=o.call(e,0,c);this.color=h(p,c),this.valpha="number"==typeof e[c]?e[c]:1}else if("number"==typeof e)e&=16777215,this.model="rgb",this.color=[e>>16&255,e>>8&255,255&e],this.valpha=1;else{this.valpha=1;var d=Object.keys(e);"alpha"in e&&(d.splice(d.indexOf("alpha"),1),this.valpha="number"==typeof e.alpha?e.alpha:0);var g=d.sort().join("");if(!(g in s))throw new Error("Unable to parse color from object: "+JSON.stringify(e));this.model=s[g];var m=i[this.model].labels,y=[];for(r=0;rr?(t+.05)/(r+.05):(r+.05)/(t+.05)},level:function(e){var t=this.contrast(e);return t>=7.1?"AAA":t>=4.5?"AA":""},isDark:function(){var e=this.rgb().color;return(299*e[0]+587*e[1]+114*e[2])/1e3<128},isLight:function(){return!this.isDark()},negate:function(){for(var e=this.rgb(),t=0;t<3;t++)e.color[t]=255-e.color[t];return e},lighten:function(e){var t=this.hsl();return t.color[2]+=t.color[2]*e,t},darken:function(e){var t=this.hsl();return t.color[2]-=t.color[2]*e,t},saturate:function(e){var t=this.hsl();return t.color[1]+=t.color[1]*e,t},desaturate:function(e){var t=this.hsl();return t.color[1]-=t.color[1]*e,t},whiten:function(e){var t=this.hwb();return t.color[1]+=t.color[1]*e,t},blacken:function(e){var t=this.hwb();return t.color[2]+=t.color[2]*e,t},grayscale:function(){var e=this.rgb().color,t=.3*e[0]+.59*e[1]+.11*e[2];return l.rgb(t,t,t)},fade:function(e){return this.alpha(this.valpha-this.valpha*e)},opaquer:function(e){return this.alpha(this.valpha+this.valpha*e)},rotate:function(e){var t=this.hsl(),r=t.color[0];return r=(r=(r+e)%360)<0?360+r:r,t.color[0]=r,t},mix:function(e,t){var r=e.rgb(),n=this.rgb(),i=void 0===t?.5:t,o=2*i-1,a=r.alpha()-n.alpha(),s=((o*a==-1?o:(o+a)/(1+o*a))+1)/2,u=1-s;return l.rgb(s*r.red()+u*n.red(),s*r.green()+u*n.green(),s*r.blue()+u*n.blue(),r.alpha()*i+n.alpha()*(1-i))}},Object.keys(i).forEach(function(e){if(-1===a.indexOf(e)){var t=i[e].channels;l.prototype[e]=function(){if(this.model===e)return new l(this);if(arguments.length)return new l(arguments,e);var r,n="number"==typeof arguments[t]?t:this.valpha;return new l((r=i[this.model][e].raw(this.color),Array.isArray(r)?r:[r]).concat(n),e)},l[e]=function(r){return"number"==typeof r&&(r=h(o.call(arguments),t)),new l(r,e)}}}),t.exports=l},{"color-convert":114,"color-string":117}],119:[function(e,t,r){var n={};t.exports=n,n.themes={};var i=e("util"),o=n.styles=e("./styles"),a=Object.defineProperties,s=new RegExp(/[\r\n]+/g);n.supportsColor=e("./system/supports-colors").supportsColor,void 0===n.enabled&&(n.enabled=!1!==n.supportsColor()),n.enable=function(){n.enabled=!0},n.disable=function(){n.enabled=!1},n.stripColors=n.strip=function(e){return(""+e).replace(/\x1B\[\d+m/g,"")};n.stylize=function(e,t){if(!n.enabled)return e+"";var r=o[t];return!r&&t in n?n[t](e):r.open+e+r.close};var u=/[|\\{}()[\]^$+*?.]/g;function l(e){var t=function e(){return function(){var e=Array.prototype.slice.call(arguments).map(function(e){return null!=e&&e.constructor===String?e:i.inspect(e)}).join(" ");if(!n.enabled||!e)return e;var t=-1!=e.indexOf("\n"),r=this._styles,a=r.length;for(;a--;){var u=o[r[a]];e=u.open+e.replace(u.closeRe,u.open)+u.close,t&&(e=e.replace(s,function(e){return u.close+e+u.open}))}return e}.apply(e,arguments)};return t._styles=e,t.__proto__=h,t}var c,f=(c={},o.grey=o.gray,Object.keys(o).forEach(function(e){o[e].closeRe=new RegExp(function(e){if("string"!=typeof e)throw new TypeError("Expected a string");return e.replace(u,"\\$&")}(o[e].close),"g"),c[e]={get:function(){return l(this._styles.concat(e))}}}),c),h=a(function(){},f);n.setTheme=function(e){if("string"!=typeof e)for(var t in e)!function(t){n[t]=function(r){if("object"==typeof e[t]){var i=r;for(var o in e[t])i=n[e[t][o]](i);return i}return n[e[t]](r)}}(t);else console.log("colors.setTheme now only accepts an object, not a string. If you are trying to set a theme from a file, it is now your (the caller's) responsibility to require the file. The old syntax looked like colors.setTheme(__dirname + '/../themes/generic-logging.js'); The new syntax looks like colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));")};var p=function(e,t){var r=t.split("");return(r=r.map(e)).join("")};for(var d in n.trap=e("./custom/trap"),n.zalgo=e("./custom/zalgo"),n.maps={},n.maps.america=e("./maps/america")(n),n.maps.zebra=e("./maps/zebra")(n),n.maps.rainbow=e("./maps/rainbow")(n),n.maps.random=e("./maps/random")(n),n.maps)!function(e){n[e]=function(t){return p(n.maps[e],t)}}(d);a(n,function(){var e={};return Object.keys(f).forEach(function(t){e[t]={get:function(){return l([t])}}}),e}())},{"./custom/trap":120,"./custom/zalgo":121,"./maps/america":122,"./maps/rainbow":123,"./maps/random":124,"./maps/zebra":125,"./styles":126,"./system/supports-colors":128,util:82}],120:[function(e,t,r){t.exports=function(e,t){var r="",n={a:["@","Ą","Ⱥ","Ʌ","Δ","Λ","Д"],b:["ß","Ɓ","Ƀ","ɮ","β","฿"],c:["©","Ȼ","Ͼ"],d:["Ð","Ɗ","Ԁ","ԁ","Ԃ","ԃ"],e:["Ë","ĕ","Ǝ","ɘ","Σ","ξ","Ҽ","੬"],f:["Ӻ"],g:["ɢ"],h:["Ħ","ƕ","Ң","Һ","Ӈ","Ԋ"],i:["༏"],j:["Ĵ"],k:["ĸ","Ҡ","Ӄ","Ԟ"],l:["Ĺ"],m:["ʍ","Ӎ","ӎ","Ԡ","ԡ","൩"],n:["Ñ","ŋ","Ɲ","Ͷ","Π","Ҋ"],o:["Ø","õ","ø","Ǿ","ʘ","Ѻ","ם","","๏"],p:["Ƿ","Ҏ"],q:["্"],r:["®","Ʀ","Ȑ","Ɍ","ʀ","Я"],s:["§","Ϟ","ϟ","Ϩ"],t:["Ł","Ŧ","ͳ"],u:["Ʊ","Ս"],v:["ט"],w:["Ш","Ѡ","Ѽ","൰"],x:["Ҳ","Ӿ","Ӽ","ӽ"],y:["¥","Ұ","Ӌ"],z:["Ƶ","ɀ"]};return(e=(e=e||"Run the trap, drop the bass").split("")).forEach(function(e){e=e.toLowerCase();var t=n[e]||[" "],i=Math.floor(Math.random()*t.length);r+=void 0!==n[e]?n[e][i]:e}),r}},{}],121:[function(e,t,r){t.exports=function(e,t){e=e||" he is here ";var r={up:["̍","̎","̄","̅","̿","̑","̆","̐","͒","͗","͑","̇","̈","̊","͂","̓","̈","͊","͋","͌","̃","̂","̌","͐","̀","́","̋","̏","̒","̓","̔","̽","̉","ͣ","ͤ","ͥ","ͦ","ͧ","ͨ","ͩ","ͪ","ͫ","ͬ","ͭ","ͮ","ͯ","̾","͛","͆","̚"],down:["̖","̗","̘","̙","̜","̝","̞","̟","̠","̤","̥","̦","̩","̪","̫","̬","̭","̮","̯","̰","̱","̲","̳","̹","̺","̻","̼","ͅ","͇","͈","͉","͍","͎","͓","͔","͕","͖","͙","͚","̣"],mid:["̕","̛","̀","́","͘","̡","̢","̧","̨","̴","̵","̶","͜","͝","͞","͟","͠","͢","̸","̷","͡"," ҉"]},n=[].concat(r.up,r.down,r.mid);function i(e){return Math.floor(Math.random()*e)}function o(e){var t=!1;return n.filter(function(r){t=r===e}),t}return function(e,t){var n,a,s="";for(a in(t=t||{}).up=void 0===t.up||t.up,t.mid=void 0===t.mid||t.mid,t.down=void 0===t.down||t.down,t.size=void 0!==t.size?t.size:"maxi",e=e.split(""))if(!o(a)){switch(s+=e[a],n={up:0,down:0,mid:0},t.size){case"mini":n.up=i(8),n.mid=i(2),n.down=i(8);break;case"maxi":n.up=i(16)+3,n.mid=i(4)+1,n.down=i(64)+3;break;default:n.up=i(8)+1,n.mid=i(6)/2,n.down=i(8)+1}var u=["up","mid","down"];for(var l in u)for(var c=u[l],f=0;f<=n[c];f++)t[c]&&(s+=r[c][i(r[c].length)])}return s}(e,t)}},{}],122:[function(e,t,r){t.exports=function(e){return function(t,r,n){if(" "===t)return t;switch(r%3){case 0:return e.red(t);case 1:return e.white(t);case 2:return e.blue(t)}}}},{}],123:[function(e,t,r){t.exports=function(e){var t=["red","yellow","green","blue","magenta"];return function(r,n,i){return" "===r?r:e[t[n++%t.length]](r)}}},{}],124:[function(e,t,r){t.exports=function(e){var t=["underline","inverse","grey","yellow","red","green","blue","white","cyan","magenta","brightYellow","brightRed","brightGreen","brightBlue","brightWhite","brightCyan","brightMagenta"];return function(r,n,i){return" "===r?r:e[t[Math.round(Math.random()*(t.length-2))]](r)}}},{}],125:[function(e,t,r){t.exports=function(e){return function(t,r,n){return r%2==0?t:e.inverse(t)}}},{}],126:[function(e,t,r){var n={};t.exports=n;var i={reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29],black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],grey:[90,39],brightRed:[91,39],brightGreen:[92,39],brightYellow:[93,39],brightBlue:[94,39],brightMagenta:[95,39],brightCyan:[96,39],brightWhite:[97,39],bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgGray:[100,49],bgGrey:[100,49],bgBrightRed:[101,49],bgBrightGreen:[102,49],bgBrightYellow:[103,49],bgBrightBlue:[104,49],bgBrightMagenta:[105,49],bgBrightCyan:[106,49],bgBrightWhite:[107,49],blackBG:[40,49],redBG:[41,49],greenBG:[42,49],yellowBG:[43,49],blueBG:[44,49],magentaBG:[45,49],cyanBG:[46,49],whiteBG:[47,49]};Object.keys(i).forEach(function(e){var t=i[e],r=n[e]=[];r.open="["+t[0]+"m",r.close="["+t[1]+"m"})},{}],127:[function(e,t,r){(function(e){(function(){"use strict";t.exports=function(t,r){var n=(r=r||e.argv).indexOf("--"),i=/^-{1,2}/.test(t)?"":"--",o=r.indexOf(i+t);return-1!==o&&(-1===n||o=2,has16m:e>=3}}(function(e){if(!1===a)return 0;if(i("color=16m")||i("color=full")||i("color=truecolor"))return 3;if(i("color=256"))return 2;if(e&&!e.isTTY&&!0!==a)return 0;var t=a?1:0;if("win32"===r.platform){var s=n.release().split(".");return Number(r.versions.node.split(".")[0])>=8&&Number(s[0])>=10&&Number(s[2])>=10586?Number(s[2])>=14931?3:2:1}if("CI"in o)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI"].some(function(e){return e in o})||"codeship"===o.CI_NAME?1:t;if("TEAMCITY_VERSION"in o)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o.TEAMCITY_VERSION)?1:0;if("TERM_PROGRAM"in o){var u=parseInt((o.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(o.TERM_PROGRAM){case"iTerm.app":return u>=3?3:2;case"Hyper":return 3;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(o.TERM)?2:/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(o.TERM)?1:"COLORTERM"in o?1:(o.TERM,t)}(e))}i("no-color")||i("no-colors")||i("color=false")?a=!1:(i("color")||i("colors")||i("color=true")||i("color=always"))&&(a=!0),"FORCE_COLOR"in o&&(a=0===o.FORCE_COLOR.length||0!==parseInt(o.FORCE_COLOR,10)),t.exports={supportsColor:s,stdout:s(r.stdout),stderr:s(r.stderr)}}).call(this)}).call(this,e("_process"))},{"./has-flag.js":127,_process:34,os:20}],129:[function(e,t,r){var n=e("./lib/colors");t.exports=n},{"./lib/colors":119}],130:[function(e,t,r){"use strict";var n=e("color"),i=e("text-hex");t.exports=function(e,t){var r=e.split(t||":"),o=i(r[0]);if(!r.length)return o;for(var a=0,s=r.length-1;a{if(!t||t.match(f))return;let i=l.exec(t);if(i){const e=i[1];r={},this._sections[e]=r}else{if(!r)throw new s.MissingSectionHeaderError(e,n,t);if(!(i=c.exec(t)))throw new s.ParseError(e,n,t);{const e=i[1];r[e]=i[2]}}})}function b(){let e,t="";for(e in this._sections){if(!this._sections.hasOwnProperty(e))continue;t+="["+e+"]\n";const r=this._sections[e];let n;for(n in r){if(!r.hasOwnProperty(n))continue;t+=n+"="+r[n]+"\n"}t+="\n"}return t}m.prototype.sections=function(){return Object.keys(this._sections)},m.prototype.addSection=function(e){if(this._sections.hasOwnProperty(e))throw new s.DuplicateSectionError(e);this._sections[e]={}},m.prototype.hasSection=function(e){return this._sections.hasOwnProperty(e)},m.prototype.keys=function(e){try{return Object.keys(this._sections[e])}catch(t){throw new s.NoSectionError(e)}},m.prototype.hasKey=function(e,t){return this._sections.hasOwnProperty(e)&&this._sections[e].hasOwnProperty(t)},m.prototype.read=function(e){const t=i.readFileSync(e).toString("utf8").split(h);y.call(this,e,t)},m.prototype.readAsync=async function(e){const t=(await p(e)).toString("utf8").split(h);y.call(this,e,t)},m.prototype.get=function(e,t,r){if(this._sections.hasOwnProperty(e))return r?this._sections[e][t]:u.interpolate(this,e,t)},m.prototype.getInt=function(e,t,r){if(this._sections.hasOwnProperty(e))return r||(r=10),parseInt(this._sections[e][t],r)},m.prototype.getFloat=function(e,t){if(this._sections.hasOwnProperty(e))return parseFloat(this._sections[e][t])},m.prototype.items=function(e){return this._sections[e]},m.prototype.set=function(e,t,r){this._sections.hasOwnProperty(e)&&(this._sections[e][t]=r)},m.prototype.removeKey=function(e,t){return!(!this._sections.hasOwnProperty(e)||!this._sections[e].hasOwnProperty(t))&&delete this._sections[e][t]},m.prototype.removeSection=function(e){return!!this._sections.hasOwnProperty(e)&&delete this._sections[e]},m.prototype.write=function(e,t=!1){if(t){const t=o.dirname(e);a.sync(t)}i.writeFileSync(e,b.call(this))},m.prototype.writeAsync=async function(e,t=!1){if(t){const t=o.dirname(e);await g(t)}await d(e,b.call(this))},t.exports=m},{"./errors":133,"./interpolation":134,fs:1,mkdirp:164,path:32,util:82}],133:[function(e,t,r){t.exports={DuplicateSectionError:function(e){this.name="DuplicateSectionError",this.message=e+" already exists",Error.captureStackTrace(this,this.constructor)},NoSectionError:function(e){this.name=this.constructor.name,this.message="Section "+e+" does not exist.",Error.captureStackTrace(this,this.constructor)},ParseError:function(e,t,r){this.name=this.constructor.name,this.message="Source contains parsing errors.\nfile: "+e+" line: "+t+"\n"+r,Error.captureStackTrace(this,this.constructor)},MissingSectionHeaderError:function(e,t,r){this.name=this.constructor.name,this.message="File contains no section headers.\nfile: "+e+" line: "+t+"\n"+r,Error.captureStackTrace(this,this.constructor)},MaximumInterpolationDepthError:function(e,t,r,n){this.name=this.constructor.name,this.message="Exceeded Maximum Recursion Depth ("+n+") for key "+t+" in section "+e+"\nvalue: "+r,Error.captureStackTrace(this,this.constructor)}}},{}],134:[function(e,t,r){const n=e("./errors"),i=new RegExp(/%\(([\w-]+)\)s/),o=50;t.exports={interpolate:function(e,t,r){return function e(t,r,a,s){let u=t.get(r,a,!0);if(s>o)throw new n.MaximumInterpolationDepthError(r,a,u,o);let l=i.exec(u);for(;null!==l;){const n=l[1],o=e(t,r,n,s+1);u=u.substr(0,l.index)+o+u.substr(l.index+l[0].length),l=i.exec(u)}return u}(e,t,r,1)},MAXIMUM_INTERPOLATION_DEPTH:o}},{"./errors":133}],135:[function(e,t,r){(function(e){(function(){function t(e){return Object.prototype.toString.call(e)}r.isArray=function(e){return Array.isArray?Array.isArray(e):"[object Array]"===t(e)},r.isBoolean=function(e){return"boolean"==typeof e},r.isNull=function(e){return null===e},r.isNullOrUndefined=function(e){return null==e},r.isNumber=function(e){return"number"==typeof e},r.isString=function(e){return"string"==typeof e},r.isSymbol=function(e){return"symbol"==typeof e},r.isUndefined=function(e){return void 0===e},r.isRegExp=function(e){return"[object RegExp]"===t(e)},r.isObject=function(e){return"object"==typeof e&&null!==e},r.isDate=function(e){return"[object Date]"===t(e)},r.isError=function(e){return"[object Error]"===t(e)||e instanceof Error},r.isFunction=function(e){return"function"==typeof e},r.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},r.isBuffer=e.isBuffer}).call(this)}).call(this,{isBuffer:e("../../../../../../../../tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/NodeJS_12.13.0/node-v12.13.0-linux-x64/lib/node_modules/browserify/node_modules/is-buffer/index.js")})},{"../../../../../../../../tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/NodeJS_12.13.0/node-v12.13.0-linux-x64/lib/node_modules/browserify/node_modules/is-buffer/index.js":17}],136:[function(e,t,r){"use strict";t.exports=function(e,t){if(!t)return!1;for(var r=t.split(/[\s,]+/),n=0;nt?1:0}function s(e,t,r){var o,s=function e(t,r,o,s){var u;if("object"==typeof t&&null!==t){for(u=0;u0)for(var n=0;n-1?n:null}};function a(e){for(var t=[],r=1;r3?0:(e-e%10!=10?1:0)*e%10]}},f=a({},c),h=function(e){return f=a(f,e)},p=function(e){return e.replace(/[|\\{()[^$+*?.-]/g,"\\$&")},d=function(e,t){for(void 0===t&&(t=2),e=String(e);e.length0?"-":"+")+d(100*Math.floor(Math.abs(t)/60)+Math.abs(t)%60,4)},Z:function(e){var t=e.getTimezoneOffset();return(t>0?"-":"+")+d(Math.floor(Math.abs(t)/60),2)+":"+d(Math.abs(t)%60,2)}},m=function(e){return+e-1},y=[null,"[1-9]\\d?"],b=[null,r],v=["isPm",r,function(e,t){var r=e.toLowerCase();return r===t.amPm[0]?0:r===t.amPm[1]?1:null}],_=["timezoneOffset","[^\\s]*?[\\+\\-]\\d\\d:?\\d\\d|[^\\s]*?Z?",function(e){var t=(e+"").match(/([+-]|\d\d)/gi);if(t){var r=60*+t[1]+parseInt(t[2],10);return"+"===t[0]?r:-r}return 0}],w={D:["day","[1-9]\\d?"],DD:["day","\\d\\d"],Do:["day","[1-9]\\d?"+r,function(e){return parseInt(e,10)}],M:["month","[1-9]\\d?",m],MM:["month","\\d\\d",m],YY:["year","\\d\\d",function(e){var t=+(""+(new Date).getFullYear()).substr(0,2);return+(""+(+e>68?t-1:t)+e)}],h:["hour","[1-9]\\d?",void 0,"isPm"],hh:["hour","\\d\\d",void 0,"isPm"],H:["hour","[1-9]\\d?"],HH:["hour","\\d\\d"],m:["minute","[1-9]\\d?"],mm:["minute","\\d\\d"],s:["second","[1-9]\\d?"],ss:["second","\\d\\d"],YYYY:["year","\\d{4}"],S:["millisecond","\\d",function(e){return 100*+e}],SS:["millisecond","\\d\\d",function(e){return 10*+e}],SSS:["millisecond","\\d{3}"],d:y,dd:y,ddd:b,dddd:b,MMM:["month",r,o("monthNamesShort")],MMMM:["month",r,o("monthNames")],a:v,A:v,ZZ:_,Z:_},E={default:"ddd MMM DD YYYY HH:mm:ss",shortDate:"M/D/YY",mediumDate:"MMM D, YYYY",longDate:"MMMM D, YYYY",fullDate:"dddd, MMMM D, YYYY",isoDate:"YYYY-MM-DD",isoDateTime:"YYYY-MM-DDTHH:mm:ssZ",shortTime:"HH:mm",mediumTime:"HH:mm:ss",longTime:"HH:mm:ss.SSS"},k=function(e){return a(E,e)},S=function(e,r,i){if(void 0===r&&(r=E.default),void 0===i&&(i={}),"number"==typeof e&&(e=new Date(e)),"[object Date]"!==Object.prototype.toString.call(e)||isNaN(e.getTime()))throw new Error("Invalid Date pass to format");var o=[];r=(r=E[r]||r).replace(n,function(e,t){return o.push(t),"@@@"});var s=a(a({},f),i);return(r=r.replace(t,function(t){return g[t](e,s)})).replace(/@@@/g,function(){return o.shift()})};function x(e,r,i){if(void 0===i&&(i={}),"string"!=typeof r)throw new Error("Invalid format in fecha parse");if(r=E[r]||r,e.length>1e3)return null;var o={year:(new Date).getFullYear(),month:0,day:1,hour:0,minute:0,second:0,millisecond:0,isPm:null,timezoneOffset:null},s=[],u=[],l=r.replace(n,function(e,t){return u.push(p(t)),"@@@"}),c={},h={};l=p(l).replace(t,function(e){var t=w[e],r=t[0],n=t[1],i=t[3];if(c[r])throw new Error("Invalid format. "+r+" specified twice in format");return c[r]=!0,i&&(h[i]=!0),s.push(t),"("+n+")"}),Object.keys(h).forEach(function(e){if(!c[e])throw new Error("Invalid format. "+e+" is required in specified format")}),l=l.replace(/@@@/g,function(){return u.shift()});var d=e.match(new RegExp(l,"i"));if(!d)return null;for(var g=a(a({},f),i),m=1;m=0&&(e.splice instanceof Function||Object.getOwnPropertyDescriptor(e,e.length-1)&&"String"!==e.constructor.name))}},{}],142:[function(e,t,r){"use strict";const n=e=>null!==e&&"object"==typeof e&&"function"==typeof e.pipe;n.writable=(e=>n(e)&&!1!==e.writable&&"function"==typeof e._write&&"object"==typeof e._writableState),n.readable=(e=>n(e)&&!1!==e.readable&&"function"==typeof e._read&&"object"==typeof e._readableState),n.duplex=(e=>n.writable(e)&&n.readable(e)),n.transform=(e=>n.duplex(e)&&"function"==typeof e._transform&&"object"==typeof e._transformState),t.exports=n},{}],143:[function(e,t,r){arguments[4][18][0].apply(r,arguments)},{dup:18}],144:[function(e,t,r){"use strict";var n=e("./format");t.exports=n(function(e){return e.message="\t".concat(e.message),e})},{"./format":149}],145:[function(e,t,r){"use strict";var n=r.format=e("././format");r.levels=e("././levels"),Object.defineProperty(n,"align",{value:e("./align")}),Object.defineProperty(n,"cli",{value:e("./cli")}),Object.defineProperty(n,"combine",{value:e("./combine")}),Object.defineProperty(n,"colorize",{value:e("./colorize")}),Object.defineProperty(n,"json",{value:e("./json")}),Object.defineProperty(n,"label",{value:e("./label")}),Object.defineProperty(n,"logstash",{value:e("./logstash")}),Object.defineProperty(n,"metadata",{value:e("./metadata")}),Object.defineProperty(n,"padLevels",{value:e("./pad-levels")}),Object.defineProperty(n,"prettyPrint",{value:e("./pretty-print")}),Object.defineProperty(n,"printf",{value:e("./printf")}),Object.defineProperty(n,"simple",{value:e("./simple")}),Object.defineProperty(n,"splat",{value:e("./splat")}),Object.defineProperty(n,"timestamp",{value:e("./timestamp")}),Object.defineProperty(n,"uncolorize",{value:e("./uncolorize")})},{"././format":149,"././levels":152,"./align":144,"./cli":146,"./colorize":147,"./combine":148,"./json":150,"./label":151,"./logstash":153,"./metadata":154,"./pad-levels":155,"./pretty-print":156,"./printf":157,"./simple":158,"./splat":159,"./timestamp":160,"./uncolorize":161}],146:[function(e,t,r){"use strict";function n(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),t.levels||(t.levels=s.npm.levels),this.colorizer=new i(t),this.padder=new o(t),this.options=t}var t,r,a;return t=e,(r=[{key:"transform",value:function(e,t){return this.colorizer.transform(this.padder.transform(e,t),t),e[u]="".concat(e.level,":").concat(e.message),e}}])&&n(t.prototype,r),a&&n(t,a),e}();t.exports=function(e){return new l(e)},t.exports.Format=l},{"./colorize":147,"./pad-levels":155,"triple-beam":189}],147:[function(e,t,r){"use strict";function n(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),t.colors&&this.addColors(t.colors),this.options=t}var t,r,o;return t=e,o=[{key:"addColors",value:function(t){var r=Object.keys(t).reduce(function(e,r){return e[r]=u.test(t[r])?t[r].split(u):t[r],e},{});return e.allColors=Object.assign({},e.allColors||{},r),e.allColors}}],(r=[{key:"addColors",value:function(t){return e.addColors(t)}},{key:"colorize",value:function(t,r,n){if(void 0===n&&(n=r),!Array.isArray(e.allColors[t]))return i[e.allColors[t]](n);for(var o=0,a=e.allColors[t].length;o2)throw new f(e);function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.options=e}function r(e){return new t(e)}return t.prototype.transform=e,r.Format=t,r}},{}],150:[function(e,t,r){(function(r){(function(){"use strict";var n=e("./format"),i=e("triple-beam").MESSAGE,o=e("fast-safe-stringify");function a(e,t){return t instanceof r?t.toString("base64"):"bigint"==typeof t?t.toString():t}t.exports=n(function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e[i]=(t.stable?o.stableStringify:o)(e,t.replacer||a,t.space),e})}).call(this)}).call(this,e("buffer").Buffer)},{"./format":149,buffer:10,"fast-safe-stringify":137,"triple-beam":189}],151:[function(e,t,r){"use strict";var n=e("./format");t.exports=n(function(e,t){return t.message?(e.message="[".concat(t.label,"] ").concat(e.message),e):(e.label=t.label,e)})},{"./format":149}],152:[function(e,t,r){"use strict";var n=e("./colorize").Colorizer;t.exports=function(e){return n.addColors(e.colors||e),e}},{"./colorize":147}],153:[function(e,t,r){"use strict";var n=e("./format"),i=e("triple-beam").MESSAGE,o=e("fast-safe-stringify");t.exports=n(function(e){var t={};return e.message&&(t["@message"]=e.message,delete e.message),e.timestamp&&(t["@timestamp"]=e.timestamp,delete e.timestamp),t["@fields"]=e,e[i]=o(t),e})},{"./format":149,"fast-safe-stringify":137,"triple-beam":189}],154:[function(e,t,r){"use strict";var n=e("./format");function i(e,t,r){var n,i,o,a=t.reduce(function(t,r){return t[r]=e[r],delete e[r],t},{}),s=Object.keys(e).reduce(function(t,r){return t[r]=e[r],delete e[r],t},{});return Object.assign(e,a,(o=s,(i=r)in(n={})?Object.defineProperty(n,i,{value:o,enumerable:!0,configurable:!0,writable:!0}):n[i]=o,n)),e}t.exports=n(function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r="metadata";t.key&&(r=t.key);var n=[];return t.fillExcept||t.fillWith||(n.push("level"),n.push("message")),t.fillExcept&&(n=t.fillExcept),n.length>0?i(e,n,r):t.fillWith?function(e,t,r){return e[r]=t.reduce(function(t,r){return t[r]=e[r],delete e[r],t},{}),e}(e,t.fillWith,r):e})},{"./format":149}],155:[function(e,t,r){"use strict";function n(e){return function(e){if(Array.isArray(e))return i(e)}(e)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||function(e,t){if(!e)return;if("string"==typeof e)return i(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);"Object"===r&&e.constructor&&(r=e.constructor.name);if("Map"===r||"Set"===r)return Array.from(e);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return i(e,t)}(e)||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 i(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r0&&void 0!==arguments[0]?arguments[0]:{levels:s.npm.levels};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.paddings=e.paddingForLevels(t.levels,t.filler),this.options=t}var t,r,i;return t=e,i=[{key:"getLongestLevel",value:function(e){var t=Object.keys(e).map(function(e){return e.length});return Math.max.apply(Math,n(t))}},{key:"paddingForLevel",value:function(e,t,r){var n=r+1-e.length,i=Math.floor(n/t.length);return"".concat(t).concat(t.repeat(i)).slice(0,n)}},{key:"paddingForLevels",value:function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:" ",n=e.getLongestLevel(t);return Object.keys(t).reduce(function(t,i){return t[i]=e.paddingForLevel(i,r,n),t},{})}}],(r=[{key:"transform",value:function(e,t){return e.message="".concat(this.paddings[e[u]]).concat(e.message),e[l]&&(e[l]="".concat(this.paddings[e[u]]).concat(e[l])),e}}])&&o(t.prototype,r),i&&o(t,i),e}();t.exports=function(e){return new c(e)},t.exports.Padder=t.exports.Format=c},{"triple-beam":189}],156:[function(e,t,r){"use strict";var n=e("util").inspect,i=e("./format"),o=e("triple-beam"),a=o.LEVEL,s=o.MESSAGE,u=o.SPLAT;t.exports=i(function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=Object.assign({},e);return delete r[a],delete r[s],delete r[u],e[s]=n(r,!1,t.depth||null,t.colorize),e})},{"./format":149,"triple-beam":189,util:82}],157:[function(e,t,r){"use strict";function n(e,t){for(var r=0;re.length)&&(t=e.length);for(var r=0,n=new Array(t);r1?r.splice(0):r,o=i.length;if(o)for(var a=0;a1&&void 0!==arguments[1]?arguments[1]:{};return t.format&&(e.timestamp="function"==typeof t.format?t.format():n.format(new Date,t.format)),e.timestamp||(e.timestamp=(new Date).toISOString()),t.alias&&(e[t.alias]=e.timestamp),e})},{"./format":149,fecha:138}],161:[function(e,t,r){"use strict";var n=e("colors/safe"),i=e("./format"),o=e("triple-beam").MESSAGE;t.exports=i(function(e,t){return!1!==t.level&&(e.level=n.strip(e.level)),!1!==t.message&&(e.message=n.strip(e.message)),!1!==t.raw&&e[o]&&(e[o]=n.strip(e[o])),e})},{"./format":149,"colors/safe":129,"triple-beam":189}],162:[function(e,t,r){"use strict";class n extends Error{constructor(e){super(`Format functions must be synchronous taking a two arguments: (info, opts)\nFound: ${e.toString().split("\n")[0]}\n`),Error.captureStackTrace(this,n)}}t.exports=(e=>{if(e.length>2)throw new n(e);function t(e={}){this.options=e}function r(e){return new t(e)}return t.prototype.transform=e,r.Format=t,r})},{}],163:[function(e,t,r){(function(r){(function(){"use strict";const n=e("./format"),{MESSAGE:i}=e("triple-beam"),o=e("fast-safe-stringify");function a(e,t){return t instanceof r?t.toString("base64"):"bigint"==typeof t?t.toString():t}t.exports=n((e,t={})=>(e[i]=(t.stable?o.stableStringify:o)(e,t.replacer||a,t.space),e))}).call(this)}).call(this,e("buffer").Buffer)},{"./format":162,buffer:10,"fast-safe-stringify":137,"triple-beam":189}],164:[function(e,t,r){var n=e("path"),i=e("fs"),o=parseInt("0777",8);function a(e,t,r,s){"function"==typeof t?(r=t,t={}):t&&"object"==typeof t||(t={mode:t});var u=t.mode,l=t.fs||i;void 0===u&&(u=o),s||(s=null);var c=r||function(){};e=n.resolve(e),l.mkdir(e,u,function(r){if(!r)return c(null,s=s||e);switch(r.code){case"ENOENT":if(n.dirname(e)===e)return c(r);a(n.dirname(e),t,function(r,n){r?c(r,n):a(e,t,c,n)});break;default:l.stat(e,function(e,t){e||!t.isDirectory()?c(r,s):c(null,s)})}})}t.exports=a.mkdirp=a.mkdirP=a,a.sync=function e(t,r,a){r&&"object"==typeof r||(r={mode:r});var s=r.mode,u=r.fs||i;void 0===s&&(s=o),a||(a=null),t=n.resolve(t);try{u.mkdirSync(t,s),a=a||t}catch(i){switch(i.code){case"ENOENT":e(t,r,a=e(n.dirname(t),r,a));break;default:var l;try{l=u.statSync(t)}catch(e){throw i}if(!l.isDirectory())throw i}}return a}},{fs:1,path:32}],165:[function(e,t,r){"use strict";var n=e("fn.name");t.exports=function(e){var t,r=0;function i(){return r?t:(r=1,t=e.apply(this,arguments),e=null,t)}return i.displayName=n(e),i}},{"fn.name":139}],166:[function(e,t,r){arguments[4][33][0].apply(r,arguments)},{_process:34,dup:33}],167:[function(e,t,r){arguments[4][40][0].apply(r,arguments)},{"./_stream_readable":168,"./_stream_writable":169,"core-util-is":135,dup:40,inherits:140,"process-nextick-args":166}],168:[function(e,t,r){arguments[4][42][0].apply(r,arguments)},{"./_stream_duplex":167,"./internal/streams/BufferList":170,"./internal/streams/destroy":171,"./internal/streams/stream":172,_process:34,"core-util-is":135,dup:42,events:13,inherits:140,isarray:143,"process-nextick-args":166,"safe-buffer":174,"string_decoder/":177,util:7}],169:[function(e,t,r){arguments[4][44][0].apply(r,arguments)},{"./_stream_duplex":167,"./internal/streams/destroy":171,"./internal/streams/stream":172,_process:34,"core-util-is":135,dup:44,inherits:140,"process-nextick-args":166,"safe-buffer":174,timers:76,"util-deprecate":190}],170:[function(e,t,r){arguments[4][45][0].apply(r,arguments)},{dup:45,"safe-buffer":174,util:7}],171:[function(e,t,r){arguments[4][46][0].apply(r,arguments)},{dup:46,"process-nextick-args":166}],172:[function(e,t,r){arguments[4][47][0].apply(r,arguments)},{dup:47,events:13}],173:[function(e,t,r){arguments[4][53][0].apply(r,arguments)},{"./lib/_stream_writable.js":169,dup:53}],174:[function(e,t,r){arguments[4][48][0].apply(r,arguments)},{buffer:10,dup:48}],175:[function(e,t,r){"use strict";var n=e("is-arrayish"),i=Array.prototype.concat,o=Array.prototype.slice,a=t.exports=function(e){for(var t=[],r=0,a=e.length;r0){n=o.substr(0,l),i=o.substr(l+1);var c=n.indexOf(".Module");c>0&&(o=o.substr(c+1),n=n.substr(0,c))}a=null}i&&(a=n,s=i),""===i&&(s=null,o=null);var f={fileName:r[2]||null,lineNumber:parseInt(r[3],10)||null,functionName:o,typeName:a,methodName:s,columnNumber:parseInt(r[4],10)||null,native:u};return t._createParsedCallSite(f)}}).filter(function(e){return!!e})};["this","typeName","functionName","methodName","fileName","lineNumber","columnNumber","function","evalOrigin"].forEach(function(e){n.prototype[e]=null,n.prototype["get"+e[0].toUpperCase()+e.substr(1)]=function(){return this[e]}}),["topLevel","eval","native","constructor"].forEach(function(e){n.prototype[e]=!1,n.prototype["is"+e[0].toUpperCase()+e.substr(1)]=function(){return this[e]}}),r._createParsedCallSite=function(e){return new n(e)}},{}],177:[function(e,t,r){arguments[4][49][0].apply(r,arguments)},{dup:49,"safe-buffer":174}],178:[function(e,t,r){function n(){this._defaults=[]}["use","on","once","set","query","type","accept","auth","withCredentials","sortQuery","retry","ok","redirects","timeout","buffer","serialize","parse","ca","key","pfx","cert"].forEach(function(e){n.prototype[e]=function(){return this._defaults.push({fn:e,arguments:arguments}),this}}),n.prototype._setDefaults=function(e){this._defaults.forEach(function(t){e[t.fn].apply(e,t.arguments)})},t.exports=n},{}],179:[function(e,t,r){var n;"undefined"!=typeof window?n=window:"undefined"!=typeof self?n=self:(console.warn("Using browser-only version of superagent in non-browser environment"),n=this);var i=e("component-emitter"),o=e("./request-base"),a=e("./is-object"),s=e("./response-base"),u=e("./agent-base");function l(){}var c=r=t.exports=function(e,t){return"function"==typeof t?new r.Request("GET",e).end(t):1==arguments.length?new r.Request("GET",e):new r.Request(e,t)};r.Request=y,c.getXHR=function(){if(!(!n.XMLHttpRequest||n.location&&"file:"==n.location.protocol&&n.ActiveXObject))return new XMLHttpRequest;try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(e){}throw Error("Browser-only version of superagent could not find XHR")};var f="".trim?function(e){return e.trim()}:function(e){return e.replace(/(^\s*|\s*$)/g,"")};function h(e){if(!a(e))return e;var t=[];for(var r in e)p(t,r,e[r]);return t.join("&")}function p(e,t,r){if(null!=r)if(Array.isArray(r))r.forEach(function(r){p(e,t,r)});else if(a(r))for(var n in r)p(e,t+"["+n+"]",r[n]);else e.push(encodeURIComponent(t)+"="+encodeURIComponent(r));else null===r&&e.push(encodeURIComponent(t))}function d(e){for(var t,r,n={},i=e.split("&"),o=0,a=i.length;o=2&&e._responseTimeoutTimer&&clearTimeout(e._responseTimeoutTimer),4==r){var n;try{n=t.status}catch(e){n=0}if(!n){if(e.timedout||e._aborted)return;return e.crossDomainError()}e.emit("end")}};var n=function(t,r){r.total>0&&(r.percent=r.loaded/r.total*100),r.direction=t,e.emit("progress",r)};if(this.hasListeners("progress"))try{t.onprogress=n.bind(null,"download"),t.upload&&(t.upload.onprogress=n.bind(null,"upload"))}catch(e){}try{this.username&&this.password?t.open(this.method,this.url,!0,this.username,this.password):t.open(this.method,this.url,!0)}catch(e){return this.callback(e)}if(this._withCredentials&&(t.withCredentials=!0),!this._formData&&"GET"!=this.method&&"HEAD"!=this.method&&"string"!=typeof r&&!this._isHost(r)){var i=this._header["content-type"],o=this._serializer||c.serialize[i?i.split(";")[0]:""];!o&&g(i)&&(o=c.serialize["application/json"]),o&&(r=o(r))}for(var a in this.header)null!=this.header[a]&&this.header.hasOwnProperty(a)&&t.setRequestHeader(a,this.header[a]);return this._responseType&&(t.responseType=this._responseType),this.emit("request",this),t.send(void 0!==r?r:null),this},c.agent=function(){return new u},["GET","POST","OPTIONS","PATCH","PUT","DELETE"].forEach(function(e){u.prototype[e.toLowerCase()]=function(t,r){var n=new c.Request(e,t);return this._setDefaults(n),r&&n.end(r),n}}),u.prototype.del=u.prototype.delete,c.get=function(e,t,r){var n=c("GET",e);return"function"==typeof t&&(r=t,t=null),t&&n.query(t),r&&n.end(r),n},c.head=function(e,t,r){var n=c("HEAD",e);return"function"==typeof t&&(r=t,t=null),t&&n.query(t),r&&n.end(r),n},c.options=function(e,t,r){var n=c("OPTIONS",e);return"function"==typeof t&&(r=t,t=null),t&&n.send(t),r&&n.end(r),n},c.del=b,c.delete=b,c.patch=function(e,t,r){var n=c("PATCH",e);return"function"==typeof t&&(r=t,t=null),t&&n.send(t),r&&n.end(r),n},c.post=function(e,t,r){var n=c("POST",e);return"function"==typeof t&&(r=t,t=null),t&&n.send(t),r&&n.end(r),n},c.put=function(e,t,r){var n=c("PUT",e);return"function"==typeof t&&(r=t,t=null),t&&n.send(t),r&&n.end(r),n}},{"./agent-base":178,"./is-object":180,"./request-base":181,"./response-base":182,"component-emitter":131}],180:[function(e,t,r){"use strict";t.exports=function(e){return null!==e&&"object"==typeof e}},{}],181:[function(e,t,r){"use strict";var n=e("./is-object");function i(e){if(e)return function(e){for(var t in i.prototype)e[t]=i.prototype[t];return e}(e)}t.exports=i,i.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,this},i.prototype.parse=function(e){return this._parser=e,this},i.prototype.responseType=function(e){return this._responseType=e,this},i.prototype.serialize=function(e){return this._serializer=e,this},i.prototype.timeout=function(e){if(!e||"object"!=typeof e)return this._timeout=e,this._responseTimeout=0,this;for(var t in e)switch(t){case"deadline":this._timeout=e.deadline;break;case"response":this._responseTimeout=e.response;break;default:console.warn("Unknown timeout option",t)}return this},i.prototype.retry=function(e,t){return 0!==arguments.length&&!0!==e||(e=1),e<=0&&(e=0),this._maxRetries=e,this._retries=0,this._retryCallback=t,this};var o=["ECONNRESET","ETIMEDOUT","EADDRINFO","ESOCKETTIMEDOUT"];i.prototype._shouldRetry=function(e,t){if(!this._maxRetries||this._retries++>=this._maxRetries)return!1;if(this._retryCallback)try{var r=this._retryCallback(e,t);if(!0===r)return!0;if(!1===r)return!1}catch(e){console.error(e)}if(t&&t.status&&t.status>=500&&501!=t.status)return!0;if(e){if(e.code&&~o.indexOf(e.code))return!0;if(e.timeout&&"ECONNABORTED"==e.code)return!0;if(e.crossDomain)return!0}return!1},i.prototype._retry=function(){return this.clearTimeout(),this.req&&(this.req=null,this.req=this.request()),this._aborted=!1,this.timedout=!1,this._end()},i.prototype.then=function(e,t){if(!this._fullfilledPromise){var r=this;this._endCalled&&console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises"),this._fullfilledPromise=new Promise(function(e,t){r.end(function(r,n){r?t(r):e(n)})})}return this._fullfilledPromise.then(e,t)},i.prototype.catch=function(e){return this.then(void 0,e)},i.prototype.use=function(e){return e(this),this},i.prototype.ok=function(e){if("function"!=typeof e)throw Error("Callback required");return this._okCallback=e,this},i.prototype._isResponseOK=function(e){return!!e&&(this._okCallback?this._okCallback(e):e.status>=200&&e.status<300)},i.prototype.get=function(e){return this._header[e.toLowerCase()]},i.prototype.getHeader=i.prototype.get,i.prototype.set=function(e,t){if(n(e)){for(var r in e)this.set(r,e[r]);return this}return this._header[e.toLowerCase()]=t,this.header[e]=t,this},i.prototype.unset=function(e){return delete this._header[e.toLowerCase()],delete this.header[e],this},i.prototype.field=function(e,t){if(null===e||void 0===e)throw new Error(".field(name, val) name can not be empty");if(this._data&&console.error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()"),n(e)){for(var r in e)this.field(r,e[r]);return this}if(Array.isArray(t)){for(var i in t)this.field(e,t[i]);return this}if(null===t||void 0===t)throw new Error(".field(name, val) val can not be empty");return"boolean"==typeof t&&(t=""+t),this._getFormData().append(e,t),this},i.prototype.abort=function(){return this._aborted?this:(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req&&this.req.abort(),this.clearTimeout(),this.emit("abort"),this)},i.prototype._auth=function(e,t,r,n){switch(r.type){case"basic":this.set("Authorization","Basic "+n(e+":"+t));break;case"auto":this.username=e,this.password=t;break;case"bearer":this.set("Authorization","Bearer "+e)}return this},i.prototype.withCredentials=function(e){return void 0==e&&(e=!0),this._withCredentials=e,this},i.prototype.redirects=function(e){return this._maxRedirects=e,this},i.prototype.maxResponseSize=function(e){if("number"!=typeof e)throw TypeError("Invalid argument");return this._maxResponseSize=e,this},i.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},i.prototype.send=function(e){var t=n(e),r=this._header["content-type"];if(this._formData&&console.error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()"),t&&!this._data)Array.isArray(e)?this._data=[]:this._isHost(e)||(this._data={});else if(e&&this._data&&this._isHost(this._data))throw Error("Can't merge these send calls");if(t&&n(this._data))for(var i in e)this._data[i]=e[i];else"string"==typeof e?(r||this.type("form"),r=this._header["content-type"],this._data="application/x-www-form-urlencoded"==r?this._data?this._data+"&"+e:e:(this._data||"")+e):this._data=e;return!t||this._isHost(e)?this:(r||this.type("json"),this)},i.prototype.sortQuery=function(e){return this._sort=void 0===e||e,this},i.prototype._finalizeQueryString=function(){var e=this._query.join("&");if(e&&(this.url+=(this.url.indexOf("?")>=0?"&":"?")+e),this._query.length=0,this._sort){var t=this.url.indexOf("?");if(t>=0){var r=this.url.substring(t+1).split("&");"function"==typeof this._sort?r.sort(this._sort):r.sort(),this.url=this.url.substring(0,t)+"?"+r.join("&")}}},i.prototype._appendQueryString=function(){console.trace("Unsupported")},i.prototype._timeoutError=function(e,t,r){if(!this._aborted){var n=new Error(e+t+"ms exceeded");n.timeout=t,n.code="ECONNABORTED",n.errno=r,this.timedout=!0,this.abort(),this.callback(n)}},i.prototype._setTimeouts=function(){var e=this;this._timeout&&!this._timer&&(this._timer=setTimeout(function(){e._timeoutError("Timeout of ",e._timeout,"ETIME")},this._timeout)),this._responseTimeout&&!this._responseTimeoutTimer&&(this._responseTimeoutTimer=setTimeout(function(){e._timeoutError("Response timeout of ",e._responseTimeout,"ETIMEDOUT")},this._responseTimeout))}},{"./is-object":180}],182:[function(e,t,r){"use strict";var n=e("./utils");function i(e){if(e)return function(e){for(var t in i.prototype)e[t]=i.prototype[t];return e}(e)}t.exports=i,i.prototype.get=function(e){return this.header[e.toLowerCase()]},i.prototype._setHeaderProperties=function(e){var t=e["content-type"]||"";this.type=n.type(t);var r=n.params(t);for(var i in r)this[i]=r[i];this.links={};try{e.link&&(this.links=n.parseLinks(e.link))}catch(e){}},i.prototype._setStatusProperties=function(e){var t=e/100|0;this.status=this.statusCode=e,this.statusType=t,this.info=1==t,this.ok=2==t,this.redirect=3==t,this.clientError=4==t,this.serverError=5==t,this.error=(4==t||5==t)&&this.toError(),this.created=201==e,this.accepted=202==e,this.noContent=204==e,this.badRequest=400==e,this.unauthorized=401==e,this.notAcceptable=406==e,this.forbidden=403==e,this.notFound=404==e,this.unprocessableEntity=422==e}},{"./utils":183}],183:[function(e,t,r){"use strict";r.type=function(e){return e.split(/ *; */).shift()},r.params=function(e){return e.split(/ *; */).reduce(function(e,t){var r=t.split(/ *= */),n=r.shift(),i=r.shift();return n&&i&&(e[n]=i),e},{})},r.parseLinks=function(e){return e.split(/ *, */).reduce(function(e,t){var r=t.split(/ *; */),n=r[0].slice(1,-1);return e[r[1].split(/ *= */)[1].slice(1,-1)]=n,e},{})},r.cleanHeader=function(e,t){return delete e["content-type"],delete e["content-length"],delete e["transfer-encoding"],delete e.host,t&&(delete e.authorization,delete e.cookie),e}},{}],184:[function(e,t,r){"use strict";t.exports=function(e){for(var t=0,r=0;t0&&void 0!==arguments[0]?arguments[0]:{};i.call(this,{objectMode:!0,highWaterMark:t.highWaterMark}),this.format=t.format,this.level=t.level,this.handleExceptions=t.handleExceptions,this.handleRejections=t.handleRejections,this.silent=t.silent,t.log&&(this.log=t.log),t.logv&&(this.logv=t.logv),t.close&&(this.close=t.close),this.once("pipe",function(t){e.levels=t.levels,e.parent=t}),this.once("unpipe",function(t){t===e.parent&&(e.parent=null,e.close&&e.close())})};n.inherits(a,i),a.prototype._write=function(e,t,r){if(this.silent||!0===e.exception&&!this.handleExceptions)return r(null);var n=this.level||this.parent&&this.parent.level;if(!n||this.levels[n]>=this.levels[e[o]]){if(e&&!this.format)return this.log(e,r);var i=void 0,a=void 0;try{a=this.format.transform(Object.assign({},e),this.format.options)}catch(e){i=e}if(i||!a){if(r(),i)throw i;return}return this.log(a,r)}return r(null)},a.prototype._writev=function(e,t){if(this.logv){var r=e.filter(this._accept,this);return r.length?this.logv(r,t):t(null)}for(var n=0;n=this.levels[t[o]])||!this.handleExceptions&&!0===t.exception)},a.prototype._nop=function(){},t.exports.LegacyTransportStream=e("./legacy")},{"./legacy":192,"readable-stream/writable":173,"triple-beam":189,util:82}],192:[function(e,t,r){"use strict";var n=e("util"),i=e("triple-beam").LEVEL,o=e("./"),a=t.exports=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(o.call(this,e),!e.transport||"function"!=typeof e.transport.log)throw new Error("Invalid transport, must be an object with a log method.");this.transport=e.transport,this.level=this.level||e.transport.level,this.handleExceptions=this.handleExceptions||e.transport.handleExceptions,this._deprecated(),this.transport.__winstonError||(this.transport.__winstonError=function(e){this.emit("error",e,this.transport)}.bind(this),this.transport.on("error",this.transport.__winstonError))};n.inherits(a,o),a.prototype._write=function(e,t,r){if(this.silent||!0===e.exception&&!this.handleExceptions)return r(null);(!this.level||this.levels[this.level]>=this.levels[e[i]])&&this.transport.log(e[i],e.message,e,this._nop),r(null)},a.prototype._writev=function(e,t){for(var r=0;r=this.levels[e[i]])&&this.transport.log(e[i],e.message,e,this._nop),r(null)},a.prototype._writev=function(e,t){for(let t=0;t0&&void 0!==arguments[0]?arguments[0]:{};!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.loggers=new Map,this.options=t}var t,r,o;return t=e,(r=[{key:"add",value:function(e,t){var r=this;if(!this.loggers.has(e)){var n=(t=Object.assign({},t||this.options)).transports||this.options.transports;t.transports=n?n.slice():[];var o=i(t);o.on("close",function(){return r._delete(e)}),this.loggers.set(e,o)}return this.loggers.get(e)}},{key:"get",value:function(e,t){return this.add(e,t)}},{key:"has",value:function(e){return!!this.loggers.has(e)}},{key:"close",value:function(e){var t=this;if(e)return this._removeLogger(e);this.loggers.forEach(function(e,r){return t._removeLogger(r)})}},{key:"_removeLogger",value:function(e){this.loggers.has(e)&&(this.loggers.get(e).close(),this._delete(e))}},{key:"_delete",value:function(e){this.loggers.delete(e)}}])&&n(t.prototype,r),o&&n(t,o),e}()},{"./create-logger":198}],198:[function(e,t,r){"use strict";function n(e){"@babel/helpers - typeof";return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e,t){return(i=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function o(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch(e){return!1}}();return function(){var r,i=a(e);if(t){var o=a(this).constructor;r=Reflect.construct(i,arguments,o)}else r=i.apply(this,arguments);return function(e,t){if(t&&("object"===n(t)||"function"==typeof t))return t;return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(this,r)}}function a(e){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}var s=e("triple-beam").LEVEL,u=e("./config"),l=e("./logger"),c=e("@dabh/diagnostics")("winston:create-logger");t.exports=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e.levels=e.levels||u.npm.levels;var t=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&i(e,t)}(r,l);var t=o(r);function r(e){return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,r),t.call(this,e)}return r}(),r=new t(e);return Object.keys(e.levels).forEach(function(e){c('Define prototype method for "%s"',e),"log"!==e?(t.prototype[e]=function(){for(var t=this||r,n=arguments.length,i=new Array(n),o=0;o0&&void 0!==arguments[0]?arguments[0]:{},n=r.silent,i=r.format,o=r.defaultMeta,a=r.levels,s=r.level,u=void 0===s?"info":s,l=r.exitOnError,c=void 0===l||l,f=r.transports,h=r.colors,p=r.emitErrs,d=r.formatters,g=r.padLevels,m=r.rewriters,v=r.stripColors,_=r.exceptionHandlers,w=r.rejectionHandlers;if(this.transports.length&&this.clear(),this.silent=n,this.format=i||this.format||e("logform/json")(),this.defaultMeta=o||null,this.levels=a||this.levels||E.npm.levels,this.level=u,this.exceptions=new y(this),this.rejections=new b(this),this.profilers={},this.exitOnError=c,f&&(f=Array.isArray(f)?f:[f]).forEach(function(e){return t.add(e)}),h||p||d||g||m||v)throw new Error(["{ colors, emitErrs, formatters, padLevels, rewriters, stripColors } were removed in winston@3.0.0.","Use a custom winston.format(function) instead.","See: https://github.com/winstonjs/winston/tree/master/UPGRADE-3.0.md"].join("\n"));_&&this.exceptions.handle(_),w&&this.rejections.handle(w)}},{key:"isLevelEnabled",value:function(e){var t=this,r=x(this.levels,e);if(null===r)return!1;var n=x(this.levels,this.level);return null!==n&&(this.transports&&0!==this.transports.length?-1!==this.transports.findIndex(function(e){var i=x(t.levels,e.level);return null===i&&(i=n),i>=r}):n>=r)}},{key:"log",value:function(e,t){for(var r,o,a=arguments.length,s=new Array(a>2?a-2:0),u=2;u2?new v({transport:e}):e;if(!t._writableState||!t._writableState.objectMode)throw new Error("Transports must WritableStreams in objectMode. Set { objectMode: true }.");return this._onEvent("error",t),this._onEvent("warn",t),this.pipe(t),e.handleExceptions&&this.exceptions.handle(),e.handleRejections&&this.rejections.handle(),this}},{key:"remove",value:function(e){if(!e)return this;var t=e;return(!m(e)||e.log.length>2)&&(t=this.transports.filter(function(t){return t.transport===e})[0]),t&&this.unpipe(t),this}},{key:"clear",value:function(){return this.unpipe(),this}},{key:"close",value:function(){return this.clear(),this.emit("close"),this}},{key:"setLevels",value:function(){w.deprecated("setLevels")}},{key:"query",value:function(e,t){"function"==typeof e&&(t=e,e={}),e=e||{};var r={},n=Object.assign({},e.query||{});h(this.transports.filter(function(e){return!!e.query}),function(t,i){!function(t,r){e.query&&"function"==typeof t.formatQuery&&(e.query=t.formatQuery(n)),t.query(e,function(n,i){if(n)return r(n);"function"==typeof t.formatResults&&(i=t.formatResults(i,e.format)),r(null,i)})}(t,function(e,n){i&&((n=e||n)&&(r[t.name]=n),i()),i=null})},function(){return t(null,r)})}},{key:"stream",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=new c,r=[];return t._streams=r,t.destroy=function(){for(var e=r.length;e--;)r[e].destroy()},this.transports.filter(function(e){return!!e.stream}).forEach(function(n){var i=n.stream(e);i&&(r.push(i),i.on("log",function(e){e.transport=e.transport||[],e.transport.push(n.name),t.emit("log",e)}),i.on("error",function(e){e.transport=e.transport||[],e.transport.push(n.name),t.emit("error",e)}))}),t}},{key:"startTimer",value:function(){return new _(this)}},{key:"profile",value:function(e){var t=Date.now();if(this.profilers[e]){var r=this.profilers[e];delete this.profilers[e];for(var n=arguments.length,o=new Array(n>1?n-1:0),a=1;ae.start)&&(t?t(null,c):l.emit("line",c)),h++,c=""),setTimeout(r,1e3);var o=u.write(s.slice(0,i));t||l.emit("data",o);for(var a=(o=(c+o).split(/\n+/)).length-1,p=0;pe.start)&&(t?t(null,o[p]):l.emit("line",o[p])),h++;return c=o[a],f+=i,r()});n.close(i,a)}()}),t?l.destroy:l}}).call(this)}).call(this,e("buffer").Buffer)},{buffer:10,fs:1,"readable-stream":224,string_decoder:75}],205:[function(e,t,r){(function(r){(function(){"use strict";function n(e){"@babel/helpers - typeof";return(n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{};return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,p),(e=l.call(this,t)).name=t.name||"console",e.stderrLevels=e._stringArrayToSet(t.stderrLevels),e.consoleWarnLevels=e._stringArrayToSet(t.consoleWarnLevels),e.eol=t.eol||u.EOL,e.setMaxListeners(30),e}return t=p,(n=[{key:"log",value:function(e,t){var n=this;return r(function(){return n.emit("logged",e)}),this.stderrLevels[e[c]]?(console._stderr?console._stderr.write("".concat(e[f]).concat(this.eol)):console.error(e[f]),void(t&&t())):this.consoleWarnLevels[e[c]]?(console._stderr?console._stderr.write("".concat(e[f]).concat(this.eol)):console.warn(e[f]),void(t&&t())):(console._stdout?console._stdout.write("".concat(e[f]).concat(this.eol)):console.log(e[f]),void(t&&t()))}},{key:"_stringArrayToSet",value:function(e,t){if(!e)return{};if(t=t||"Cannot make set from type other than Array of string elements",!Array.isArray(e))throw new Error(t);return e.reduce(function(e,r){if("string"!=typeof r)throw new Error(t);return e[r]=!0,e},{})}}])&&i(t.prototype,n),s&&i(t,s),p}()}).call(this)}).call(this,e("timers").setImmediate)},{os:20,timers:76,"triple-beam":189,"winston-transport":191}],206:[function(e,t,r){(function(r,n){(function(){"use strict";function i(e){"@babel/helpers - typeof";return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function o(e,t){for(var r=0;r0&&void 0!==arguments[0]?arguments[0]:{};function r(e){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i1&&void 0!==arguments[1]?arguments[1]:function(){};if(this.silent)return n(),!0;if(this._drain)this._stream.once("drain",function(){t._drain=!1,t.log(e,n)});else{if(!this._rotate){var i="".concat(e[d]).concat(this.eol),o=r.byteLength(i);this._pendingSize+=o,this._opening&&!this.rotatedWhileOpening&&this._needsNewFile(this._size+this._pendingSize)&&(this.rotatedWhileOpening=!0);var a=this._stream.write(i,function(){var t=this;this._size+=o,this._pendingSize-=o,v("logged %s %s",this._size,i),this.emit("logged",e),this._opening||this._needsNewFile()&&(this._rotate=!0,this._endStream(function(){return t._rotateFile()}))}.bind(this));return a?n():(this._drain=!0,this._stream.once("drain",function(){t._drain=!1,n()})),v("written",a,this._drain),this.finishIfEnding(),a}this._stream.once("rotate",function(){t._rotate=!1,t.log(e,n)})}}},{key:"query",value:function(e,t){"function"==typeof e&&(t=e,e={}),e=function(e){(e=e||{}).rows=e.rows||e.limit||10,e.start=e.start||0,e.until=e.until||new Date,"object"!==i(e.until)&&(e.until=new Date(e.until));e.from=e.from||e.until-864e5,"object"!==i(e.from)&&(e.from=new Date(e.from));return e.order=e.order||"desc",e}(e);var r=f.join(this.dirname,this.filename),n="",o=[],a=0,s=c.createReadStream(r,{encoding:"utf8"});function u(t,r){try{var n=JSON.parse(t);(function(t){if(!t)return;if("object"!==i(t))return;var r=new Date(t.timestamp);if(e.from&&re.until||e.level&&e.level!==t.level)return;return!0})(n)&&function(t){if(e.rows&&o.length>=e.rows&&"desc"!==e.order)return void(s.readable&&s.destroy());e.fields&&(t=e.fields.reduce(function(e,r){return e[r]=t[r],e},{}));"desc"===e.order&&o.length>=e.rows&&o.shift();o.push(t)}(n)}catch(e){r||s.emit("error",e)}}s.on("error",function(e){if(s.readable&&s.destroy(),t)return"ENOENT"!==e.code?t(e):t(null,o)}),s.on("data",function(t){for(var r=(t=(n+t).split(/\n+/)).length-1,i=0;i=e.start)&&u(t[i]),a++;n=t[r]}),s.on("close",function(){n&&u(n,!0),"desc"===e.order&&(o=o.reverse()),t&&t(null,o)})}},{key:"stream",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=f.join(this.dirname,this.filename),r=new m,n={file:t,start:e.start};return r.destroy=w(n,function(e,t){if(e)return r.emit("error",e);try{r.emit("data",t),t=JSON.parse(t),r.emit("log",t)}catch(e){r.emit("error",e)}}),r}},{key:"open",value:function(){var e=this;this.filename&&(this._opening||(this._opening=!0,this.stat(function(t,r){if(t)return e.emit("error",t);v("stat done: %s { size: %s }",e.filename,r),e._size=r,e._dest=e._createStream(e._stream),e._opening=!1,e.once("open",function(){e._stream.eventNames().includes("rotate")?e._stream.emit("rotate"):e._rotate=!1})})))}},{key:"stat",value:function(e){var t=this,r=this._getFile(),n=f.join(this.dirname,r);c.stat(n,function(i,o){return i&&"ENOENT"===i.code?(v("ENOENT ok",n),t.filename=r,e(null,0)):i?(v("err ".concat(i.code," ").concat(n)),e(i)):!o||t._needsNewFile(o.size)?t._incFile(function(){return t.stat(e)}):(t.filename=r,void e(null,o.size))})}},{key:"close",value:function(e){var t=this;this._stream&&this._stream.end(function(){e&&e(),t.emit("flush"),t.emit("closed")})}},{key:"_needsNewFile",value:function(e){return e=e||this._size,this.maxsize&&e>=this.maxsize}},{key:"_onError",value:function(e){this.emit("error",e)}},{key:"_setupStream",value:function(e){return e.on("error",this._onError),e}},{key:"_cleanupStream",value:function(e){return e.removeListener("error",this._onError),e}},{key:"_rotateFile",value:function(){var e=this;this._incFile(function(){return e.open()})}},{key:"_endStream",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:function(){};this._dest?(this._stream.unpipe(this._dest),this._dest.end(function(){e._cleanupStream(e._dest),t()})):t()}},{key:"_createStream",value:function(e){var t=this,r=f.join(this.dirname,this.filename);v("create stream start",r,this.options);var n=c.createWriteStream(r,this.options).on("error",function(e){return v(e)}).on("close",function(){return v("close",n.path,n.bytesWritten)}).on("open",function(){v("file open ok",r),t.emit("open",r),e.pipe(n),t.rotatedWhileOpening&&(t._stream=new y,t._stream.setMaxListeners(30),t._rotateFile(),t.rotatedWhileOpening=!1,t._cleanupStream(n),e.end())});if(v("create stream ok",r),this.zippedArchive){var i=p.createGzip();return i.pipe(n),i}return n}},{key:"_incFile",value:function(e){v("_incFile",this.filename);var t=f.extname(this._basename),r=f.basename(this._basename,t);this.tailable?this._checkMaxFilesTailable(t,r,e):(this._created+=1,this._checkMaxFilesIncrementing(t,r,e))}},{key:"_getFile",value:function(){var e=f.extname(this._basename),t=f.basename(this._basename,e),r=this.rotationFormat?this.rotationFormat():this._created,n=!this.tailable&&this._created?"".concat(t).concat(r).concat(e):"".concat(t).concat(e);return this.zippedArchive&&!this.tailable?"".concat(n,".gz"):n}},{key:"_checkMaxFilesIncrementing",value:function(e,t,r){if(!this.maxFiles||this._created1;a--)i.push(function(r,n){var i=this,a="".concat(t).concat(r-1).concat(e).concat(o),s=f.join(this.dirname,a);c.exists(s,function(u){if(!u)return n(null);a="".concat(t).concat(r).concat(e).concat(o),c.rename(s,f.join(i.dirname,a),n)})}.bind(this,a));h(i,function(){c.rename(f.join(n.dirname,"".concat(t).concat(e)),f.join(n.dirname,"".concat(t,"1").concat(e).concat(o)),r)})}}},{key:"_createLogDirIfNotExist",value:function(e){c.existsSync(e)||c.mkdirSync(e,{recursive:!0})}}])&&o(t.prototype,l),g&&o(t,g),k}()}).call(this)}).call(this,e("buffer").Buffer,e("timers").setImmediate)},{"../tail-file":204,"@dabh/diagnostics":88,"async/series":112,buffer:10,fs:1,os:20,path:32,"readable-stream":224,timers:76,"triple-beam":189,"winston-transport":191,zlib:9}],207:[function(e,t,r){(function(r,n){(function(){"use strict";function i(e){"@babel/helpers - typeof";return(i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function o(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function a(e){for(var t=1;t0&&void 0!==arguments[0]?arguments[0]:{};return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,f),(e=s.call(this,t)).options=t,e.name=t.name||"http",e.ssl=!!t.ssl,e.host=t.host||"localhost",e.port=t.port,e.auth=t.auth,e.path=t.path||"",e.agent=t.agent,e.headers=t.headers||{},e.headers["content-type"]="application/json",e.port||(e.port=e.ssl?443:80),e}return t=f,(i=[{key:"log",value:function(e,t){var r=this;this._request(e,function(t,n){n&&200!==n.statusCode&&(t=new Error("Invalid HTTP Status Code: ".concat(n.statusCode))),t?r.emit("warn",t):r.emit("logged",e)}),t&&n(t)}},{key:"query",value:function(e,t){"function"==typeof e&&(t=e,e={}),(e={method:"query",params:this.normalizeQuery(e)}).params.path&&(e.path=e.params.path,delete e.params.path),e.params.auth&&(e.auth=e.params.auth,delete e.params.auth),this._request(e,function(e,r,n){if(r&&200!==r.statusCode&&(e=new Error("Invalid HTTP Status Code: ".concat(r.statusCode))),e)return t(e);if("string"==typeof n)try{n=JSON.parse(n)}catch(e){return t(e)}t(null,n)})}},{key:"stream",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=new d;(e={method:"stream",params:e}).params.path&&(e.path=e.params.path,delete e.params.path),e.params.auth&&(e.auth=e.params.auth,delete e.params.auth);var r="",n=this._request(e);return t.destroy=function(){return n.destroy()},n.on("data",function(e){for(var n=(e=(r+e).split(/\n+/)).length-1,i=0;i0&&void 0!==arguments[0]?arguments[0]:{};if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,p),e=h.call(this,t),!t.stream||!u(t.stream))throw new Error("options.stream is required.");return e._stream=t.stream,e._stream.setMaxListeners(1/0),e.isObjectMode=t.stream._writableState.objectMode,e.eol=t.eol||c.EOL,e}return t=p,(n=[{key:"log",value:function(e,t){var n=this;if(r(function(){return n.emit("logged",e)}),this.isObjectMode)return this._stream.write(e),void(t&&t());this._stream.write("".concat(e[l]).concat(this.eol)),t&&t()}}])&&i(t.prototype,n),s&&i(t,s),p}()}).call(this)}).call(this,e("timers").setImmediate)},{"is-stream":142,os:20,timers:76,"triple-beam":189,"winston-transport":191}],210:[function(e,t,r){arguments[4][60][0].apply(r,arguments)},{dup:60}],211:[function(e,t,r){arguments[4][61][0].apply(r,arguments)},{"./_stream_readable":213,"./_stream_writable":215,_process:34,dup:61,inherits:140}],212:[function(e,t,r){arguments[4][62][0].apply(r,arguments)},{"./_stream_transform":214,dup:62,inherits:140}],213:[function(e,t,r){arguments[4][63][0].apply(r,arguments)},{"../errors":210,"./_stream_duplex":211,"./internal/streams/async_iterator":216,"./internal/streams/buffer_list":217,"./internal/streams/destroy":218,"./internal/streams/from":220,"./internal/streams/state":222,"./internal/streams/stream":223,_process:34,buffer:10,dup:63,events:13,inherits:140,"string_decoder/":177,util:7}],214:[function(e,t,r){arguments[4][64][0].apply(r,arguments)},{"../errors":210,"./_stream_duplex":211,dup:64,inherits:140}],215:[function(e,t,r){arguments[4][65][0].apply(r,arguments)},{"../errors":210,"./_stream_duplex":211,"./internal/streams/destroy":218,"./internal/streams/state":222,"./internal/streams/stream":223,_process:34,buffer:10,dup:65,inherits:140,"util-deprecate":190}],216:[function(e,t,r){arguments[4][66][0].apply(r,arguments)},{"./end-of-stream":219,_process:34,dup:66}],217:[function(e,t,r){arguments[4][67][0].apply(r,arguments)},{buffer:10,dup:67,util:7}],218:[function(e,t,r){arguments[4][68][0].apply(r,arguments)},{_process:34,dup:68}],219:[function(e,t,r){arguments[4][69][0].apply(r,arguments)},{"../../../errors":210,dup:69}],220:[function(e,t,r){arguments[4][70][0].apply(r,arguments)},{dup:70}],221:[function(e,t,r){arguments[4][71][0].apply(r,arguments)},{"../../../errors":210,"./end-of-stream":219,dup:71}],222:[function(e,t,r){arguments[4][72][0].apply(r,arguments)},{"../../../errors":210,dup:72}],223:[function(e,t,r){arguments[4][47][0].apply(r,arguments)},{dup:47,events:13}],224:[function(e,t,r){arguments[4][74][0].apply(r,arguments)},{"./lib/_stream_duplex.js":211,"./lib/_stream_passthrough.js":212,"./lib/_stream_readable.js":213,"./lib/_stream_transform.js":214,"./lib/_stream_writable.js":215,"./lib/internal/streams/end-of-stream.js":219,"./lib/internal/streams/pipeline.js":221,dup:74}],225:[function(e,t,r){t.exports={_from:"winston@^3.3.3",_id:"winston@3.3.3",_inBundle:!1,_integrity:"sha1-rmFyBCyvspeGr6PQnI/4M6t8kXA=",_location:"/winston",_phantomChildren:{inherits:"2.0.4",string_decoder:"1.1.1","util-deprecate":"1.0.2"},_requested:{type:"range",registry:!0,raw:"winston@^3.3.3",name:"winston",escapedName:"winston",rawSpec:"^3.3.3",saveSpec:null,fetchSpec:"^3.3.3"},_requiredBy:["/"],_resolved:"https://purecloud.jfrog.io/purecloud/api/npm/inin-internal-npm/winston/-/winston-3.3.3.tgz",_shasum:"ae6172042cafb29786afa3d09c8ff833ab7c9170",_spec:"winston@^3.3.3",_where:"/var/build/workspace/build-platform-sdks-pipeline/output/purecloudjavascript-guest/build",author:{name:"Charlie Robbins",email:"charlie.robbins@gmail.com"},browser:"./dist/winston",bugs:{url:"https://github.com/winstonjs/winston/issues"},bundleDependencies:!1,dependencies:{"@dabh/diagnostics":"^2.0.2",async:"^3.1.0","is-stream":"^2.0.0",logform:"^2.2.0","one-time":"^1.0.0","readable-stream":"^3.4.0","stack-trace":"0.0.x","triple-beam":"^1.3.0","winston-transport":"^4.4.0"},deprecated:!1,description:"A logger for just about everything.",devDependencies:{"@babel/cli":"^7.10.3","@babel/core":"^7.10.3","@babel/preset-env":"^7.10.3","@types/node":"^14.0.13","abstract-winston-transport":"^0.5.1",assume:"^2.2.0",colors:"^1.4.0","cross-spawn-async":"^2.2.5","eslint-config-populist":"^4.2.0",hock:"^1.4.1",mocha:"^8.0.1",nyc:"^15.1.0",rimraf:"^3.0.2",split2:"^3.1.1","std-mocks":"^1.0.1",through2:"^3.0.1","winston-compat":"^0.1.5"},engines:{node:">= 6.4.0"},homepage:"https://github.com/winstonjs/winston#readme",keywords:["winston","logger","logging","logs","sysadmin","bunyan","pino","loglevel","tools","json","stream"],license:"MIT",main:"./lib/winston",maintainers:[{name:"Jarrett Cruger",email:"jcrugzz@gmail.com"},{name:"Chris Alderson",email:"chrisalderson@protonmail.com"},{name:"David Hyde",email:"dabh@stanford.edu"}],name:"winston",repository:{type:"git",url:"git+https://github.com/winstonjs/winston.git"},scripts:{build:"rimraf dist && babel lib -d dist",lint:"populist lib/*.js lib/winston/*.js lib/winston/**/*.js",prepublishOnly:"npm run build",pretest:"npm run lint",test:"nyc --reporter=text --reporter lcov npm run test:mocha","test:mocha":"mocha test/*.test.js test/**/*.test.js --exit"},types:"./index.d.ts",version:"3.3.3"}},{}],platformClient:[function(e,t,r){(function(r,n){(function(){"use strict";var n,i=(n=e("superagent"))&&"object"==typeof n&&"default"in n?n.default:n,o={us_east_1:"mypurecloud.com",eu_west_1:"mypurecloud.ie",ap_southeast_2:"mypurecloud.com.au",ap_northeast_1:"mypurecloud.jp",eu_central_1:"mypurecloud.de",us_west_2:"usw2.pure.cloud",ca_central_1:"cac1.pure.cloud",ap_northeast_2:"apne2.pure.cloud",eu_west_2:"euw2.pure.cloud"},a=void 0!==r?r:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},s=[],u=[],l="undefined"!=typeof Uint8Array?Uint8Array:Array,c=!1;function f(){c=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0,r=e.length;t>18&63]+s[i>>12&63]+s[i>>6&63]+s[63&i]);return o.join("")}function p(e){var t;c||f();for(var r=e.length,n=r%3,i="",o=[],a=0,u=r-n;au?u:a+16383));return 1===n?(t=e[r-1],i+=s[t>>2],i+=s[t<<4&63],i+="=="):2===n&&(t=(e[r-2]<<8)+e[r-1],i+=s[t>>10],i+=s[t>>4&63],i+=s[t<<2&63],i+="="),o.push(i),o.join("")}function d(e,t,r,n,i){var o,a,s=8*i-n-1,u=(1<>1,c=-7,f=r?i-1:0,h=r?-1:1,p=e[t+f];for(f+=h,o=p&(1<<-c)-1,p>>=-c,c+=s;c>0;o=256*o+e[t+f],f+=h,c-=8);for(a=o&(1<<-c)-1,o>>=-c,c+=n;c>0;a=256*a+e[t+f],f+=h,c-=8);if(0===o)o=1-l;else{if(o===u)return a?NaN:1/0*(p?-1:1);a+=Math.pow(2,n),o-=l}return(p?-1:1)*a*Math.pow(2,o-n)}function g(e,t,r,n,i,o){var a,s,u,l=8*o-i-1,c=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:o-1,d=n?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=c):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+f>=1?h/u:h*Math.pow(2,1-f))*u>=2&&(a++,u/=2),a+f>=c?(s=0,a=c):a+f>=1?(s=(t*u-1)*Math.pow(2,i),a+=f):(s=t*Math.pow(2,f-1)*Math.pow(2,i),a=0));i>=8;e[r+p]=255&s,p+=d,s/=256,i-=8);for(a=a<0;e[r+p]=255&a,p+=d,a/=256,l-=8);e[r+p-d]|=128*g}var m={}.toString,y=Array.isArray||function(e){return"[object Array]"==m.call(e)};function b(){return _.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function v(e,t){if(b()=b())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+b().toString(16)+" bytes");return 0|e}function O(e){return!(null==e||!e._isBuffer)}function T(e,t){if(O(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return Q(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return ee(e).length;default:if(n)return Q(e).length;t=(""+t).toLowerCase(),n=!0}}function j(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function R(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=_.from(t,n)),O(t))return 0===t.length?-1:A(e,t,r,n,i);if("number"==typeof t)return t&=255,_.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):A(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function A(e,t,r,n,i){var o,a=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,r/=2}function l(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(i){var c=-1;for(o=r;os&&(r=s-u),o=r;o>=0;o--){for(var f=!0,h=0;hi&&(n=i):n=i;var o=t.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var a=0;a>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function N(e,t,r){return 0===t&&r===e.length?p(e):p(e.slice(t,r))}function U(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i239?4:l>223?3:l>191?2:1;if(i+f<=r)switch(f){case 1:l<128&&(c=l);break;case 2:128==(192&(o=e[i+1]))&&(u=(31&l)<<6|63&o)>127&&(c=u);break;case 3:o=e[i+1],a=e[i+2],128==(192&o)&&128==(192&a)&&(u=(15&l)<<12|(63&o)<<6|63&a)>2047&&(u<55296||u>57343)&&(c=u);break;case 4:o=e[i+1],a=e[i+2],s=e[i+3],128==(192&o)&&128==(192&a)&&128==(192&s)&&(u=(15&l)<<18|(63&o)<<12|(63&a)<<6|63&s)>65535&&u<1114112&&(c=u)}null===c?(c=65533,f=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),i+=f}return function(e){var t=e.length;if(t<=B)return String.fromCharCode.apply(String,e);var r="",n=0;for(;nthis.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return q(this,t,r);case"utf8":case"utf-8":return U(this,t,r);case"ascii":return z(this,t,r);case"latin1":case"binary":return F(this,t,r);case"base64":return N(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return H(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}.apply(this,arguments)},_.prototype.equals=function(e){if(!O(e))throw new TypeError("Argument must be a Buffer");return this===e||0===_.compare(this,e)},_.prototype.inspect=function(){var e="";return this.length>0&&(e=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(e+=" ... ")),""},_.prototype.compare=function(e,t,r,n,i){if(!O(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(t>>>=0,r>>>=0,n>>>=0,i>>>=0,this===e)return 0;for(var o=i-n,a=r-t,s=Math.min(o,a),u=this.slice(n,i),l=e.slice(t,r),c=0;ci)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return M(this,e,t,r);case"utf8":case"utf-8":return C(this,e,t,r);case"ascii":return L(this,e,t,r);case"latin1":case"binary":return P(this,e,t,r);case"base64":return I(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return D(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},_.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var B=4096;function z(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;in)&&(r=n);for(var i="",o=t;or)throw new RangeError("Trying to access beyond buffer length")}function Z(e,t,r,n,i,o){if(!O(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function G(e,t,r,n){t<0&&(t=65535+t+1);for(var i=0,o=Math.min(e.length-r,2);i>>8*(n?i:1-i)}function Y(e,t,r,n){t<0&&(t=4294967295+t+1);for(var i=0,o=Math.min(e.length-r,4);i>>8*(n?i:3-i)&255}function V(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function $(e,t,r,n,i){return i||V(e,0,r,4),g(e,t,r,n,23,4),r+4}function J(e,t,r,n,i){return i||V(e,0,r,8),g(e,t,r,n,52,8),r+8}_.prototype.slice=function(e,t){var r,n=this.length;if(e=~~e,t=void 0===t?n:~~t,e<0?(e+=n)<0&&(e=0):e>n&&(e=n),t<0?(t+=n)<0&&(t=0):t>n&&(t=n),t0&&(i*=256);)n+=this[e+--t]*i;return n},_.prototype.readUInt8=function(e,t){return t||W(e,1,this.length),this[e]},_.prototype.readUInt16LE=function(e,t){return t||W(e,2,this.length),this[e]|this[e+1]<<8},_.prototype.readUInt16BE=function(e,t){return t||W(e,2,this.length),this[e]<<8|this[e+1]},_.prototype.readUInt32LE=function(e,t){return t||W(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},_.prototype.readUInt32BE=function(e,t){return t||W(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},_.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||W(e,t,this.length);for(var n=this[e],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*t)),n},_.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||W(e,t,this.length);for(var n=t,i=1,o=this[e+--n];n>0&&(i*=256);)o+=this[e+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*t)),o},_.prototype.readInt8=function(e,t){return t||W(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},_.prototype.readInt16LE=function(e,t){t||W(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},_.prototype.readInt16BE=function(e,t){t||W(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},_.prototype.readInt32LE=function(e,t){return t||W(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},_.prototype.readInt32BE=function(e,t){return t||W(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},_.prototype.readFloatLE=function(e,t){return t||W(e,4,this.length),d(this,e,!0,23,4)},_.prototype.readFloatBE=function(e,t){return t||W(e,4,this.length),d(this,e,!1,23,4)},_.prototype.readDoubleLE=function(e,t){return t||W(e,8,this.length),d(this,e,!0,52,8)},_.prototype.readDoubleBE=function(e,t){return t||W(e,8,this.length),d(this,e,!1,52,8)},_.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t|=0,r|=0,n)||Z(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[t]=255&e;++o=0&&(o*=256);)this[t+i]=e/o&255;return t+r},_.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||Z(this,e,t,1,255,0),_.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},_.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||Z(this,e,t,2,65535,0),_.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):G(this,e,t,!0),t+2},_.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||Z(this,e,t,2,65535,0),_.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):G(this,e,t,!1),t+2},_.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||Z(this,e,t,4,4294967295,0),_.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):Y(this,e,t,!0),t+4},_.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||Z(this,e,t,4,4294967295,0),_.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Y(this,e,t,!1),t+4},_.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);Z(this,e,t,r,i-1,-i)}var o=0,a=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+r},_.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);Z(this,e,t,r,i-1,-i)}var o=r-1,a=1,s=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a>>0)-s&255;return t+r},_.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||Z(this,e,t,1,127,-128),_.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},_.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||Z(this,e,t,2,32767,-32768),_.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):G(this,e,t,!0),t+2},_.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||Z(this,e,t,2,32767,-32768),_.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):G(this,e,t,!1),t+2},_.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||Z(this,e,t,4,2147483647,-2147483648),_.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):Y(this,e,t,!0),t+4},_.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||Z(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),_.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Y(this,e,t,!1),t+4},_.prototype.writeFloatLE=function(e,t,r){return $(this,e,t,!0,r)},_.prototype.writeFloatBE=function(e,t,r){return $(this,e,t,!1,r)},_.prototype.writeDoubleLE=function(e,t,r){return J(this,e,t,!0,r)},_.prototype.writeDoubleBE=function(e,t,r){return J(this,e,t,!1,r)},_.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=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),e.length-t=0;--i)e[i+t]=this[i+r];else if(o<1e3||!_.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function ee(e){return function(e){var t,r,n,i,o,a;c||f();var s=e.length;if(s%4>0)throw new Error("Invalid string. Length must be a multiple of 4");o="="===e[s-2]?2:"="===e[s-1]?1:0,a=new l(3*s/4-o),n=o>0?s-4:s;var h=0;for(t=0,r=0;t>16&255,a[h++]=i>>8&255,a[h++]=255&i;return 2===o?(i=u[e.charCodeAt(t)]<<2|u[e.charCodeAt(t+1)]>>4,a[h++]=255&i):1===o&&(i=u[e.charCodeAt(t)]<<10|u[e.charCodeAt(t+1)]<<4|u[e.charCodeAt(t+2)]>>2,a[h++]=i>>8&255,a[h++]=255&i),a}(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(K,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function te(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function re(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}const ne=e("winston"),ie={levels:{none:0,error:1,debug:2,trace:3}},oe={level:{LNone:"none",LError:"error",LDebug:"debug",LTrace:"trace"}},ae={formats:{JSON:"json",TEXT:"text"}};class se{get logLevelEnum(){return oe}get logFormatEnum(){return ae}constructor(){this.log_level=oe.level.LNone,this.log_format=ae.formats.TEXT,this.log_to_console=!0,this.log_file_path,this.log_response_body=!1,this.log_request_body=!1,this.setLogger()}createNewLogger(){this.logger=ne.createLogger({levels:ie.levels,level:this.log_level})}setLogger(){this.createNewLogger(),this.log_file_path&&""!==this.log_file_path&&(this.log_format===ae.formats.JSON?this.logger.add(new ne.transports.File({format:ne.format.json(),filename:this.log_file_path})):this.logger.add(new ne.transports.File({format:ne.format.combine(ne.format(e=>(e.level=e.level.toUpperCase(),e))(),ne.format.simple()),filename:this.log_file_path}))),this.log_to_console&&(this.log_format===ae.formats.JSON?this.logger.add(new ne.transports.Console({format:ne.format.json()})):this.logger.add(new ne.transports.Console({format:ne.format.combine(ne.format(e=>(e.level=e.level.toUpperCase(),e))(),ne.format.simple())})))}log(e,t,r,n,i,o,a,s){var u=this.formatLog(e,t,r,n,i,o,a,s);this.logger.transports.length>0&&this.logger.log(e,u)}formatLog(e,t,r,n,i,o,a,s){var u;return i&&(i.Authorization="[REDACTED]"),this.log_request_body||(a=void 0),this.log_response_body||(s=void 0),this.log_format&&this.log_format===ae.formats.JSON?(u={level:e,date:(new Date).toISOString(),method:r,url:decodeURIComponent(n),correlationId:o&&o["inin-correlation-id"]?o["inin-correlation-id"]:"",statusCode:t},i&&(u.requestHeaders=i),o&&(u.responseHeaders=o),a&&(u.requestBody=a),s&&(u.responseBody=s)):u=`${(new Date).toISOString()}\n=== REQUEST === \n${this.formatValue("URL",decodeURIComponent(n))}${this.formatValue("Method",r)}${this.formatValue("Headers",this.formatHeaderString(i))}${this.formatValue("Body",a?JSON.stringify(a,null,2):"")}\n=== RESPONSE ===\n${this.formatValue("Status",t)}${this.formatValue("Headers",this.formatHeaderString(o))}${this.formatValue("CorrelationId",o&&o["inin-correlation-id"]?o["inin-correlation-id"]:"")}${this.formatValue("Body",s?JSON.stringify(s,null,2):"")}`,u}formatHeaderString(e){var t="";if(!e)return t;for(const[r,n]of Object.entries(e))t+=`\n\t${r}: ${n}`;return t}formatValue(e,t){return t&&""!==t&&"{}"!==t?`${e}: ${t}\n`:""}getLogLevel(e){switch(e){case"error":return oe.level.LError;case"debug":return oe.level.LDebug;case"trace":return oe.level.LTrace;default:return oe.level.LNone}}getLogFormat(e){switch(e){case"json":return ae.formats.JSON;default:return ae.formats.TEXT}}}const ue=e("configparser"),le=e("os"),ce=e("path"),fe=e("fs");class he{get instance(){return he.instance}set instance(e){he.instance=e}constructor(){he.instance||(he.instance=this),this.configPath="undefined"!=typeof window?"":ce.join(le.homedir(),".genesyscloudjavascript-guest","config"),this.live_reload_config=!0,this.host,this.environment,this.basePath,this.authUrl,this.config,this.logger=new se,this.setEnvironment(),this.liveLoadConfig()}liveLoadConfig(){if("undefined"==typeof window){if(this.updateConfigFromFile(),this.live_reload_config&&!0===this.live_reload_config)try{fe.watchFile(this.configPath,{persistent:!1},(e,t)=>{this.updateConfigFromFile(),this.live_reload_config||fe.unwatchFile(this.configPath)})}catch(e){}}else this.configPath=""}setConfigPath(e){e&&e!==this.configPath&&(this.configPath=e,this.liveLoadConfig())}updateConfigFromFile(){var e=new ue;try{e.read(this.configPath),this.config=e}catch(e){if(e.name&&"MissingSectionHeaderError"===e.name){var t=fe.readFileSync(this.configPath,"utf8");this.config={_sections:JSON.parse(t)}}}this.config&&this.updateConfigValues()}updateConfigValues(){this.logger.log_level=this.logger.getLogLevel(this.getConfigString("logging","log_level")),this.logger.log_format=this.logger.getLogFormat(this.getConfigString("logging","log_format")),this.logger.log_to_console=void 0!==this.getConfigBoolean("logging","log_to_console")?this.getConfigBoolean("logging","log_to_console"):this.logger.log_to_console,this.logger.log_file_path=void 0!==this.getConfigString("logging","log_file_path")?this.getConfigString("logging","log_file_path"):this.logger.log_file_path,this.logger.log_response_body=void 0!==this.getConfigBoolean("logging","log_response_body")?this.getConfigBoolean("logging","log_response_body"):this.logger.log_response_body,this.logger.log_request_body=void 0!==this.getConfigBoolean("logging","log_request_body")?this.getConfigBoolean("logging","log_request_body"):this.logger.log_request_body,this.live_reload_config=void 0!==this.getConfigBoolean("general","live_reload_config")?this.getConfigBoolean("general","live_reload_config"):this.live_reload_config,this.host=void 0!==this.getConfigString("general","host")?this.getConfigString("general","host"):this.host,this.setEnvironment(),this.logger.setLogger()}setEnvironment(e){this.environment=e||(this.host?this.host:"mypurecloud.com"),this.environment=this.environment.replace(/\/+$/,""),this.environment.startsWith("https://")&&(this.environment=this.environment.substring(8)),this.environment.startsWith("http://")&&(this.environment=this.environment.substring(7)),this.environment.startsWith("api.")&&(this.environment=this.environment.substring(4)),this.basePath=`https://api.${this.environment}`,this.authUrl=`https://login.${this.environment}`}getConfigString(e,t){if(this.config._sections[e])return this.config._sections[e][t]}getConfigBoolean(e,t){if(this.config._sections[e]&&void 0!==this.config._sections[e][t])return"string"==typeof this.config._sections[e][t]?"true"===this.config._sections[e][t]:this.config._sections[e][t]}}class pe{get instance(){return pe.instance}set instance(e){pe.instance=e}constructor(){pe.instance||(pe.instance=this),this.CollectionFormatEnum={CSV:",",SSV:" ",TSV:"\t",PIPES:"|",MULTI:"multi"};try{localStorage.setItem("purecloud_local_storage_test","purecloud_local_storage_test"),localStorage.removeItem("purecloud_local_storage_test"),this.hasLocalStorage=!0}catch(e){this.hasLocalStorage=!1}this.config=new he,this.setEnvironment("https://api.mypurecloud.com"),this.authentications={"PureCloud OAuth":{type:"oauth2"},"Guest Chat JWT":{type:"apiKey",in:"header",name:"Authorization",apiKeyPrefix:"Bearer"}},this.defaultHeaders={},this.timeout=16e3,this.authData={},this.settingsPrefix="purecloud",this.superagent=i,"undefined"!=typeof window&&(window.ApiClient=this)}setReturnExtendedResponses(e){this.returnExtended=e}setPersistSettings(e,t){this.persistSettings=e,this.settingsPrefix=t?t.replace(/\W+/g,"_"):"purecloud"}_saveSettings(e){try{if(this.authData.apiKey=e.apiKey,this.authentications["Guest Chat JWT"].apiKey=e.apiKey,e.state&&(this.authData.state=e.state),e.tokenExpiryTime&&(this.authData.tokenExpiryTime=e.tokenExpiryTime,this.authData.tokenExpiryTimeString=e.tokenExpiryTimeString),!0!==this.persistSettings)return;if(!this.hasLocalStorage)return;let t=JSON.parse(JSON.stringify(this.authData));delete t.state,localStorage.setItem(`${this.settingsPrefix}_auth_data`,JSON.stringify(t))}catch(e){console.error(e)}}_loadSettings(){if(!0!==this.persistSettings)return;if(!this.hasLocalStorage)return;const e=this.authData.state;this.authData=localStorage.getItem(`${this.settingsPrefix}_auth_data`),this.authData?this.authData=JSON.parse(this.authData):this.authData={},this.authData.apiKey&&this.setJwt(this.authData.apiKey),this.authData.state=e}setEnvironment(e){this.config.setEnvironment(e)}_testTokenAccess(){return new Promise((e,t)=>{this._loadSettings(),this.authentications["Guest Chat JWT"].apiKey?this.callApi("/api/v2/authorization/permissions","GET",null,null,null,null,null,["Guest Chat JWT"],["application/json"],["application/json"]).then(()=>{e()}).catch(e=>{this._saveSettings({apiKey:void 0}),t(e)}):t(new Error("Token is not set"))})}setJwt(e){this._saveSettings({apiKey:e})}setStorageKey(e){this.storageKey=e,this.setJwt(this.authentications["Guest Chat JWT"].apiKey)}_buildAuthUrl(e,t){return t||(t={}),Object.keys(t).reduce((e,r)=>t[r]?`${e}&${r}=${t[r]}`:e,`${this.config.authUrl}/${e}?`)}paramToString(e){return e?e instanceof Date?e.toJSON():e.toString():""}buildUrl(e,t){e.match(/^\//)||(e=`/${e}`);var r=this.config.basePath+e;return r=r.replace(/\{([\w-]+)\}/g,(e,r)=>{var n;return n=t.hasOwnProperty(r)?this.paramToString(t[r]):e,encodeURIComponent(n)})}isJsonMime(e){return Boolean(e&&e.match(/^application\/json(;.*)?$/i))}jsonPreferredMime(e){for(var t=0;t{var r=this.authentications[t];switch(r.type){case"basic":(r.username||r.password)&&e.auth(r.username||"",r.password||"");break;case"apiKey":if(r.apiKey){var n={};r.apiKeyPrefix?n[r.name]=`${r.apiKeyPrefix} ${r.apiKey}`:n[r.name]=r.apiKey,"header"===r.in?e.set(n):e.query(n)}break;case"oauth2":r.accessToken&&e.set({Authorization:`Bearer ${r.accessToken}`});break;default:throw new Error(`Unknown authentication type: ${r.type}`)}})}callApi(e,t,r,n,o,a,s,u,l,c){var f=this.buildUrl(e,r),h=i(t,f);this.proxy&&h.proxy&&h.proxy(this.proxy),this.applyAuthToRequest(h,u),h.query(this.normalizeParams(n)),h.set(this.defaultHeaders).set(this.normalizeParams(o)),h.timeout(this.timeout);var p=this.jsonPreferredMime(l);if(p?h.type(p):h.header["Content-Type"]||h.type("application/json"),"application/x-www-form-urlencoded"===p)h.send(this.normalizeParams(a));else if("multipart/form-data"==p){var d=this.normalizeParams(a);for(var g in d)d.hasOwnProperty(g)&&(this.isFileParam(d[g])?h.attach(g,d[g]):h.field(g,d[g]))}else s&&h.send(s);var m=this.jsonPreferredMime(c);return m&&h.accept(m),new Promise((e,r)=>{h.end((n,i)=>{if(!n||i){var o=!0===this.returnExtended||n?{status:i.status,statusText:i.statusText,headers:i.headers,body:i.body,text:i.text,error:n}:i.body?i.body:i.text;this.config.logger.log("trace",i.statusCode,t,f,h.header,i.headers,s,void 0),this.config.logger.log("debug",i.statusCode,t,f,h.header,void 0,s,void 0),n?(this.config.logger.log("error",i.statusCode,t,f,h.header,i.headers,s,i.body),r(o)):e(o)}else r({status:0,statusText:"error",headers:[],body:{},text:"error",error:n})})})}}class de{constructor(e){this.apiClient=e||pe.instance}deleteWebchatGuestConversationMember(e,t){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling deleteWebchatGuestConversationMember';if(void 0===t||null===t)throw'Missing the required parameter "memberId" when calling deleteWebchatGuestConversationMember';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/members/{memberId}","DELETE",{conversationId:e,memberId:t},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMediarequest(e,t){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMediarequest';if(void 0===t||null===t)throw'Missing the required parameter "mediaRequestId" when calling getWebchatGuestConversationMediarequest';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/mediarequests/{mediaRequestId}","GET",{conversationId:e,mediaRequestId:t},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMediarequests(e){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMediarequests';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/mediarequests","GET",{conversationId:e},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMember(e,t){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMember';if(void 0===t||null===t)throw'Missing the required parameter "memberId" when calling getWebchatGuestConversationMember';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/members/{memberId}","GET",{conversationId:e,memberId:t},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMembers(e,t){if(t=t||{},void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMembers';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/members","GET",{conversationId:e},{pageSize:t.pageSize,pageNumber:t.pageNumber,excludeDisconnectedMembers:t.excludeDisconnectedMembers},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMessage(e,t){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMessage';if(void 0===t||null===t)throw'Missing the required parameter "messageId" when calling getWebchatGuestConversationMessage';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/messages/{messageId}","GET",{conversationId:e,messageId:t},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}getWebchatGuestConversationMessages(e,t){if(t=t||{},void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling getWebchatGuestConversationMessages';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/messages","GET",{conversationId:e},{after:t.after,before:t.before,sortOrder:t.sortOrder,maxResults:t.maxResults},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}patchWebchatGuestConversationMediarequest(e,t,r){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling patchWebchatGuestConversationMediarequest';if(void 0===t||null===t)throw'Missing the required parameter "mediaRequestId" when calling patchWebchatGuestConversationMediarequest';if(void 0===r||null===r)throw'Missing the required parameter "body" when calling patchWebchatGuestConversationMediarequest';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/mediarequests/{mediaRequestId}","PATCH",{conversationId:e,mediaRequestId:t},{},{},{},r,["Guest Chat JWT"],["application/json"],["application/json"])}postWebchatGuestConversationMemberMessages(e,t,r){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling postWebchatGuestConversationMemberMessages';if(void 0===t||null===t)throw'Missing the required parameter "memberId" when calling postWebchatGuestConversationMemberMessages';if(void 0===r||null===r)throw'Missing the required parameter "body" when calling postWebchatGuestConversationMemberMessages';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/members/{memberId}/messages","POST",{conversationId:e,memberId:t},{},{},{},r,["Guest Chat JWT"],["application/json"],["application/json"])}postWebchatGuestConversationMemberTyping(e,t){if(void 0===e||null===e)throw'Missing the required parameter "conversationId" when calling postWebchatGuestConversationMemberTyping';if(void 0===t||null===t)throw'Missing the required parameter "memberId" when calling postWebchatGuestConversationMemberTyping';return this.apiClient.callApi("/api/v2/webchat/guest/conversations/{conversationId}/members/{memberId}/typing","POST",{conversationId:e,memberId:t},{},{},{},null,["Guest Chat JWT"],["application/json"],["application/json"])}postWebchatGuestConversations(e){if(void 0===e||null===e)throw'Missing the required parameter "body" when calling postWebchatGuestConversations';return this.apiClient.callApi("/api/v2/webchat/guest/conversations","POST",{},{},{},{},e,[],["application/json"],["application/json"])}}var ge=new class{constructor(){this.ApiClient=new pe,this.WebChatApi=de,this.PureCloudRegionHosts=o}};t.exports=ge}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer)},{buffer:10,configparser:132,fs:1,os:20,path:32,superagent:179,winston:194}]},{},[]);
\ No newline at end of file
+require=function(){return function t(e,r,n){function i(s,a){if(!r[s]){if(!e[s]){var u="function"==typeof require&&require;if(!a&&u)return u(s,!0);if(o)return o(s,!0);var h=new Error("Cannot find module '"+s+"'");throw h.code="MODULE_NOT_FOUND",h}var f=r[s]={exports:{}};e[s][0].call(f.exports,function(t){return i(e[s][1][t]||t)},f,f.exports,t,e,r,n)}return r[s].exports}for(var o="function"==typeof require&&require,s=0;s0?s-4:s;for(r=0;r>16&255,u[f++]=e>>8&255,u[f++]=255&e;2===a&&(e=i[t.charCodeAt(r)]<<2|i[t.charCodeAt(r+1)]>>4,u[f++]=255&e);1===a&&(e=i[t.charCodeAt(r)]<<10|i[t.charCodeAt(r+1)]<<4|i[t.charCodeAt(r+2)]>>2,u[f++]=e>>8&255,u[f++]=255&e);return u},r.fromByteArray=function(t){for(var e,r=t.length,i=r%3,o=[],s=0,a=r-i;sa?a:s+16383));1===i?(e=t[r-1],o.push(n[e>>2]+n[e<<4&63]+"==")):2===i&&(e=(t[r-2]<<8)+t[r-1],o.push(n[e>>10]+n[e>>4&63]+n[e<<2&63]+"="));return o.join("")};for(var n=[],i=[],o="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 f(t,e,r){for(var i,o,s=[],a=e;a>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return s.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},{}],2:[function(t,e,r){(function(e){(function(){"use strict";var e=t("base64-js"),n=t("ieee754");r.Buffer=s,r.SlowBuffer=function(t){+t!=t&&(t=0);return s.alloc(+t)},r.INSPECT_MAX_BYTES=50;var i=2147483647;function o(t){if(t>i)throw new RangeError('The value "'+t+'" is invalid for option "size"');var e=new Uint8Array(t);return e.__proto__=s.prototype,e}function s(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return h(t)}return a(t,e,r)}function a(t,e,r){if("string"==typeof t)return function(t,e){"string"==typeof e&&""!==e||(e="utf8");if(!s.isEncoding(e))throw new TypeError("Unknown encoding: "+e);var r=0|l(t,e),n=o(r),i=n.write(t,e);i!==r&&(n=n.slice(0,i));return n}(t,e);if(ArrayBuffer.isView(t))return f(t);if(null==t)throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(j(t,ArrayBuffer)||t&&j(t.buffer,ArrayBuffer))return function(t,e,r){if(e<0||t.byteLength=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|t}function l(t,e){if(s.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||j(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);var r=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;for(var i=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return k(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return q(t).length;default:if(i)return n?-1:k(t).length;e=(""+e).toLowerCase(),i=!0}}function p(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function d(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),G(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=s.from(e,n)),s.isBuffer(e))return 0===e.length?-1:g(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):g(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function g(t,e,r,n,i){var o,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 h(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){var f=-1;for(o=r;oa&&(r=a-u),o=r;o>=0;o--){for(var c=!0,l=0;li&&(n=i):n=i;var o=e.length;n>o/2&&(n=o/2);for(var s=0;s>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function E(t,r,n){return 0===r&&n===t.length?e.fromByteArray(t):e.fromByteArray(t.slice(r,n))}function T(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i239?4:h>223?3:h>191?2:1;if(i+c<=r)switch(c){case 1:h<128&&(f=h);break;case 2:128==(192&(o=t[i+1]))&&(u=(31&h)<<6|63&o)>127&&(f=u);break;case 3:o=t[i+1],s=t[i+2],128==(192&o)&&128==(192&s)&&(u=(15&h)<<12|(63&o)<<6|63&s)>2047&&(u<55296||u>57343)&&(f=u);break;case 4:o=t[i+1],s=t[i+2],a=t[i+3],128==(192&o)&&128==(192&s)&&128==(192&a)&&(u=(15&h)<<18|(63&o)<<12|(63&s)<<6|63&a)>65535&&u<1114112&&(f=u)}null===f?(f=65533,c=1):f>65535&&(f-=65536,n.push(f>>>10&1023|55296),f=56320|1023&f),n.push(f),i+=c}return function(t){var e=t.length;if(e<=A)return String.fromCharCode.apply(String,t);var r="",n=0;for(;nthis.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 I(this,e,r);case"utf8":case"utf-8":return T(this,e,r);case"ascii":return C(this,e,r);case"latin1":case"binary":return R(this,e,r);case"base64":return E(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(t){if(!s.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===s.compare(this,t)},s.prototype.inspect=function(){var t="",e=r.INSPECT_MAX_BYTES;return t=this.toString("hex",0,e).replace(/(.{2})/g,"$1 ").trim(),this.length>e&&(t+=" ... "),""},s.prototype.compare=function(t,e,r,n,i){if(j(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(e>>>=0,r>>>=0,n>>>=0,i>>>=0,this===t)return 0;for(var o=i-n,a=r-e,u=Math.min(o,a),h=this.slice(n,i),f=t.slice(e,r),c=0;c>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return y(this,t,e,r);case"utf8":case"utf-8":return w(this,t,e,r);case"ascii":return m(this,t,e,r);case"latin1":case"binary":return v(this,t,e,r);case"base64":return b(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var A=4096;function C(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;in)&&(r=n);for(var i="",o=e;or)throw new RangeError("Trying to access beyond buffer length")}function P(t,e,r,n,i,o){if(!s.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}function M(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function B(t,e,r,i,o){return e=+e,r>>>=0,o||M(t,0,r,4),n.write(t,e,r,i,23,4),r+4}function U(t,e,r,i,o){return e=+e,r>>>=0,o||M(t,0,r,8),n.write(t,e,r,i,52,8),r+8}s.prototype.slice=function(t,e){var r=this.length;t=~~t,e=void 0===e?r:~~e,t<0?(t+=r)<0&&(t=0):t>r&&(t=r),e<0?(e+=r)<0&&(e=0):e>r&&(e=r),e>>=0,e>>>=0,r||x(t,e,this.length);for(var n=this[t],i=1,o=0;++o>>=0,e>>>=0,r||x(t,e,this.length);for(var n=this[t+--e],i=1;e>0&&(i*=256);)n+=this[t+--e]*i;return n},s.prototype.readUInt8=function(t,e){return t>>>=0,e||x(t,1,this.length),this[t]},s.prototype.readUInt16LE=function(t,e){return t>>>=0,e||x(t,2,this.length),this[t]|this[t+1]<<8},s.prototype.readUInt16BE=function(t,e){return t>>>=0,e||x(t,2,this.length),this[t]<<8|this[t+1]},s.prototype.readUInt32LE=function(t,e){return t>>>=0,e||x(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},s.prototype.readUInt32BE=function(t,e){return t>>>=0,e||x(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},s.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||x(t,e,this.length);for(var n=this[t],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*e)),n},s.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||x(t,e,this.length);for(var n=e,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*e)),o},s.prototype.readInt8=function(t,e){return t>>>=0,e||x(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},s.prototype.readInt16LE=function(t,e){t>>>=0,e||x(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt16BE=function(t,e){t>>>=0,e||x(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt32LE=function(t,e){return t>>>=0,e||x(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},s.prototype.readInt32BE=function(t,e){return t>>>=0,e||x(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},s.prototype.readFloatLE=function(t,e){return t>>>=0,e||x(t,4,this.length),n.read(this,t,!0,23,4)},s.prototype.readFloatBE=function(t,e){return t>>>=0,e||x(t,4,this.length),n.read(this,t,!1,23,4)},s.prototype.readDoubleLE=function(t,e){return t>>>=0,e||x(t,8,this.length),n.read(this,t,!0,52,8)},s.prototype.readDoubleBE=function(t,e){return t>>>=0,e||x(t,8,this.length),n.read(this,t,!1,52,8)},s.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e>>>=0,r>>>=0,n)||P(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[e]=255&t;++o>>=0,r>>>=0,n)||P(this,t,e,r,Math.pow(2,8*r)-1,0);var i=r-1,o=1;for(this[e+i]=255&t;--i>=0&&(o*=256);)this[e+i]=t/o&255;return e+r},s.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,1,255,0),this[e]=255&t,e+1},s.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},s.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},s.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},s.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},s.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);P(this,t,e,r,i-1,-i)}var o=0,s=1,a=0;for(this[e]=255&t;++o>0)-a&255;return e+r},s.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);P(this,t,e,r,i-1,-i)}var o=r-1,s=1,a=0;for(this[e+o]=255&t;--o>=0&&(s*=256);)t<0&&0===a&&0!==this[e+o+1]&&(a=1),this[e+o]=(t/s>>0)-a&255;return e+r},s.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},s.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},s.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},s.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},s.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||P(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},s.prototype.writeFloatLE=function(t,e,r){return B(this,t,e,!0,r)},s.prototype.writeFloatBE=function(t,e,r){return B(this,t,e,!1,r)},s.prototype.writeDoubleLE=function(t,e,r){return U(this,t,e,!0,r)},s.prototype.writeDoubleBE=function(t,e,r){return U(this,t,e,!1,r)},s.prototype.copy=function(t,e,r,n){if(!s.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n