[DeviceHome] Reduce size of libraries 90/256990/1 submit/tizen/20210416.053116
authorHunseop Jeong <hs85.jeong@samsung.com>
Fri, 16 Apr 2021 05:20:31 +0000 (14:20 +0900)
committerHunseop Jeong <hs85.jeong@samsung.com>
Fri, 16 Apr 2021 05:20:31 +0000 (14:20 +0900)
Change-Id: I07ff8bb243f8f138c7f46aec57242319582a0e6f
Signed-off-by: Hunseop Jeong <hs85.jeong@samsung.com>
384 files changed:
device_home/node_modules/accepts/index.js
device_home/node_modules/after/index.js
device_home/node_modules/after/test/after-test.js
device_home/node_modules/ansi-regex/index.js
device_home/node_modules/ansi-styles/index.js
device_home/node_modules/array-flatten/array-flatten.js
device_home/node_modules/arraybuffer.slice/index.js
device_home/node_modules/arraybuffer.slice/test/slice-buffer.js
device_home/node_modules/async/lib/async.js
device_home/node_modules/async/support/sync-package-managers.js
device_home/node_modules/backo2/index.js
device_home/node_modules/backo2/test/index.js
device_home/node_modules/balanced-match/index.js
device_home/node_modules/base64-arraybuffer/lib/base64-arraybuffer.js
device_home/node_modules/base64-js/base64js.min.js
device_home/node_modules/base64-js/index.js
device_home/node_modules/blob/index.js
device_home/node_modules/blob/test/index.js
device_home/node_modules/body-parser/index.js
device_home/node_modules/body-parser/lib/read.js
device_home/node_modules/body-parser/lib/types/json.js
device_home/node_modules/body-parser/lib/types/raw.js
device_home/node_modules/body-parser/lib/types/text.js
device_home/node_modules/body-parser/lib/types/urlencoded.js
device_home/node_modules/brace-expansion/index.js
device_home/node_modules/buffer-alloc-unsafe/index.js
device_home/node_modules/buffer-alloc/index.js
device_home/node_modules/buffer-fill/index.js
device_home/node_modules/buffer-from/index.js
device_home/node_modules/buffer/index.js
device_home/node_modules/bytes/index.js
device_home/node_modules/camelcase/index.js
device_home/node_modules/chalk/index.js
device_home/node_modules/chalk/templates.js
device_home/node_modules/cliui/index.js
device_home/node_modules/color-convert/conversions.js
device_home/node_modules/color-convert/index.js
device_home/node_modules/color-convert/route.js
device_home/node_modules/color-name/index.js
device_home/node_modules/color-name/test.js
device_home/node_modules/component-bind/index.js
device_home/node_modules/component-emitter/index.js
device_home/node_modules/component-inherit/index.js
device_home/node_modules/component-inherit/test/inherit.js
device_home/node_modules/concat-map/example/map.js
device_home/node_modules/concat-map/index.js
device_home/node_modules/concat-map/test/map.js
device_home/node_modules/content-disposition/index.js
device_home/node_modules/content-type/index.js
device_home/node_modules/cookie-signature/index.js
device_home/node_modules/cookie/index.js
device_home/node_modules/debug/karma.conf.js
device_home/node_modules/debug/node.js
device_home/node_modules/debug/src/browser.js
device_home/node_modules/debug/src/debug.js
device_home/node_modules/debug/src/index.js
device_home/node_modules/debug/src/inspector-log.js
device_home/node_modules/debug/src/node.js
device_home/node_modules/decamelize/index.js
device_home/node_modules/depd/index.js
device_home/node_modules/depd/lib/browser/index.js
device_home/node_modules/depd/lib/compat/callsite-tostring.js
device_home/node_modules/depd/lib/compat/event-listener-count.js
device_home/node_modules/depd/lib/compat/index.js
device_home/node_modules/destroy/index.js
device_home/node_modules/dijkstrajs/dijkstra.js
device_home/node_modules/dijkstrajs/test/dijkstra.test.js
device_home/node_modules/ee-first/index.js
device_home/node_modules/ejs/bin/cli.js
device_home/node_modules/ejs/ejs.js
device_home/node_modules/ejs/ejs.min.js
device_home/node_modules/ejs/jakefile.js
device_home/node_modules/ejs/lib/ejs.js
device_home/node_modules/ejs/lib/utils.js
device_home/node_modules/emoji-regex/es2015/index.js
device_home/node_modules/emoji-regex/es2015/text.js
device_home/node_modules/emoji-regex/index.js
device_home/node_modules/emoji-regex/text.js
device_home/node_modules/encodeurl/index.js
device_home/node_modules/engine.io-client/engine.io.js
device_home/node_modules/engine.io-client/lib/globalThis.browser.js
device_home/node_modules/engine.io-client/lib/globalThis.js
device_home/node_modules/engine.io-client/lib/index.js
device_home/node_modules/engine.io-client/lib/socket.js
device_home/node_modules/engine.io-client/lib/transport.js
device_home/node_modules/engine.io-client/lib/transports/index.js
device_home/node_modules/engine.io-client/lib/transports/polling-jsonp.js
device_home/node_modules/engine.io-client/lib/transports/polling-xhr.js
device_home/node_modules/engine.io-client/lib/transports/polling.js
device_home/node_modules/engine.io-client/lib/transports/websocket.js
device_home/node_modules/engine.io-client/lib/xmlhttprequest.js
device_home/node_modules/engine.io-parser/lib/browser.js
device_home/node_modules/engine.io-parser/lib/index.js
device_home/node_modules/engine.io-parser/lib/keys.js
device_home/node_modules/engine.io-parser/lib/utf8.js
device_home/node_modules/engine.io/lib/engine.io.js
device_home/node_modules/engine.io/lib/server.js
device_home/node_modules/engine.io/lib/socket.js
device_home/node_modules/engine.io/lib/transport.js
device_home/node_modules/engine.io/lib/transports/index.js
device_home/node_modules/engine.io/lib/transports/polling-jsonp.js
device_home/node_modules/engine.io/lib/transports/polling-xhr.js
device_home/node_modules/engine.io/lib/transports/polling.js
device_home/node_modules/engine.io/lib/transports/websocket.js
device_home/node_modules/engine.io/node_modules/base64id/lib/base64id.js
device_home/node_modules/escape-html/index.js
device_home/node_modules/escape-string-regexp/index.js
device_home/node_modules/etag/index.js
device_home/node_modules/express-session/index.js
device_home/node_modules/express-session/session/cookie.js
device_home/node_modules/express-session/session/memory.js
device_home/node_modules/express-session/session/session.js
device_home/node_modules/express-session/session/store.js
device_home/node_modules/express/index.js
device_home/node_modules/express/lib/application.js
device_home/node_modules/express/lib/express.js
device_home/node_modules/express/lib/middleware/init.js
device_home/node_modules/express/lib/middleware/query.js
device_home/node_modules/express/lib/request.js
device_home/node_modules/express/lib/response.js
device_home/node_modules/express/lib/router/index.js
device_home/node_modules/express/lib/router/layer.js
device_home/node_modules/express/lib/router/route.js
device_home/node_modules/express/lib/utils.js
device_home/node_modules/express/lib/view.js
device_home/node_modules/finalhandler/index.js
device_home/node_modules/find-up/index.js
device_home/node_modules/forwarded/index.js
device_home/node_modules/fresh/index.js
device_home/node_modules/get-caller-file/index.js
device_home/node_modules/get-port/index.js
device_home/node_modules/has-binary2/index.js
device_home/node_modules/has-cors/index.js
device_home/node_modules/has-cors/test.js
device_home/node_modules/has-flag/index.js
device_home/node_modules/http-errors/index.js
device_home/node_modules/iconv-lite/encodings/dbcs-codec.js
device_home/node_modules/iconv-lite/encodings/dbcs-data.js
device_home/node_modules/iconv-lite/encodings/index.js
device_home/node_modules/iconv-lite/encodings/internal.js
device_home/node_modules/iconv-lite/encodings/sbcs-codec.js
device_home/node_modules/iconv-lite/encodings/sbcs-data-generated.js
device_home/node_modules/iconv-lite/encodings/sbcs-data.js
device_home/node_modules/iconv-lite/encodings/utf16.js
device_home/node_modules/iconv-lite/encodings/utf7.js
device_home/node_modules/iconv-lite/lib/bom-handling.js
device_home/node_modules/iconv-lite/lib/extend-node.js
device_home/node_modules/iconv-lite/lib/index.js
device_home/node_modules/iconv-lite/lib/streams.js
device_home/node_modules/ieee754/index.js
device_home/node_modules/indexof/index.js
device_home/node_modules/inherits/inherits.js
device_home/node_modules/inherits/inherits_browser.js
device_home/node_modules/ipaddr.js/ipaddr.min.js
device_home/node_modules/ipaddr.js/lib/ipaddr.js
device_home/node_modules/is-fullwidth-code-point/index.js
device_home/node_modules/isarray/index.js
device_home/node_modules/jake/bin/cli.js
device_home/node_modules/jake/jakefile.js
device_home/node_modules/jake/lib/api.js
device_home/node_modules/jake/lib/jake.js
device_home/node_modules/jake/lib/loader.js
device_home/node_modules/jake/lib/namespace.js
device_home/node_modules/jake/lib/package_task.js
device_home/node_modules/jake/lib/parseargs.js
device_home/node_modules/jake/lib/program.js
device_home/node_modules/jake/lib/publish_task.js
device_home/node_modules/jake/lib/rule.js
device_home/node_modules/jake/lib/task/directory_task.js
device_home/node_modules/jake/lib/task/file_task.js
device_home/node_modules/jake/lib/task/index.js
device_home/node_modules/jake/lib/task/task.js
device_home/node_modules/jake/lib/test_task.js
device_home/node_modules/jake/lib/utils/file.js
device_home/node_modules/jake/lib/utils/index.js
device_home/node_modules/jake/lib/utils/logger.js
device_home/node_modules/jake/test/integration/concurrent.js
device_home/node_modules/jake/test/integration/file.js
device_home/node_modules/jake/test/integration/file_task.js
device_home/node_modules/jake/test/integration/helpers.js
device_home/node_modules/jake/test/integration/jakefile.js
device_home/node_modules/jake/test/integration/jakelib/concurrent.jake.js
device_home/node_modules/jake/test/integration/jakelib/publish.jake.js
device_home/node_modules/jake/test/integration/jakelib/required_module.jake.js
device_home/node_modules/jake/test/integration/jakelib/rule.jake.js
device_home/node_modules/jake/test/integration/publish_task.js
device_home/node_modules/jake/test/integration/rule.js
device_home/node_modules/jake/test/integration/selfdep.js
device_home/node_modules/jake/test/integration/task_base.js
device_home/node_modules/jake/test/unit/jakefile.js
device_home/node_modules/jake/test/unit/namespace.js
device_home/node_modules/jake/test/unit/parseargs.js
device_home/node_modules/locate-path/index.js
device_home/node_modules/media-typer/index.js
device_home/node_modules/merge-descriptors/index.js
device_home/node_modules/methods/index.js
device_home/node_modules/mime-db/index.js
device_home/node_modules/mime-types/index.js
device_home/node_modules/mime/cli.js
device_home/node_modules/mime/mime.js
device_home/node_modules/mime/src/build.js
device_home/node_modules/mime/src/test.js
device_home/node_modules/minimatch/minimatch.js
device_home/node_modules/ms/index.js
device_home/node_modules/negotiator/index.js
device_home/node_modules/negotiator/lib/charset.js
device_home/node_modules/negotiator/lib/encoding.js
device_home/node_modules/negotiator/lib/language.js
device_home/node_modules/negotiator/lib/mediaType.js
device_home/node_modules/on-finished/index.js
device_home/node_modules/on-headers/index.js
device_home/node_modules/p-limit/index.js
device_home/node_modules/p-locate/index.js
device_home/node_modules/p-try/index.js
device_home/node_modules/parseqs/index.js
device_home/node_modules/parseqs/test.js
device_home/node_modules/parseuri/index.js
device_home/node_modules/parseuri/test.js
device_home/node_modules/parseurl/index.js
device_home/node_modules/path-exists/index.js
device_home/node_modules/path-to-regexp/index.js
device_home/node_modules/pngjs/browser.js
device_home/node_modules/pngjs/lib/bitmapper.js
device_home/node_modules/pngjs/lib/bitpacker.js
device_home/node_modules/pngjs/lib/chunkstream.js
device_home/node_modules/pngjs/lib/constants.js
device_home/node_modules/pngjs/lib/crc.js
device_home/node_modules/pngjs/lib/filter-pack.js
device_home/node_modules/pngjs/lib/filter-parse-async.js
device_home/node_modules/pngjs/lib/filter-parse-sync.js
device_home/node_modules/pngjs/lib/filter-parse.js
device_home/node_modules/pngjs/lib/format-normaliser.js
device_home/node_modules/pngjs/lib/interlace.js
device_home/node_modules/pngjs/lib/packer-async.js
device_home/node_modules/pngjs/lib/packer-sync.js
device_home/node_modules/pngjs/lib/packer.js
device_home/node_modules/pngjs/lib/paeth-predictor.js
device_home/node_modules/pngjs/lib/parser-async.js
device_home/node_modules/pngjs/lib/parser-sync.js
device_home/node_modules/pngjs/lib/parser.js
device_home/node_modules/pngjs/lib/png-sync.js
device_home/node_modules/pngjs/lib/png.js
device_home/node_modules/pngjs/lib/sync-inflate.js
device_home/node_modules/pngjs/lib/sync-reader.js
device_home/node_modules/proxy-addr/index.js
device_home/node_modules/qrcode/build/qrcode.js
device_home/node_modules/qrcode/build/qrcode.min.js
device_home/node_modules/qrcode/build/qrcode.tosjis.js
device_home/node_modules/qrcode/build/qrcode.tosjis.min.js
device_home/node_modules/qrcode/helper/to-sjis.js
device_home/node_modules/qrcode/lib/browser.js
device_home/node_modules/qrcode/lib/can-promise.js
device_home/node_modules/qrcode/lib/core/alignment-pattern.js
device_home/node_modules/qrcode/lib/core/alphanumeric-data.js
device_home/node_modules/qrcode/lib/core/bit-buffer.js
device_home/node_modules/qrcode/lib/core/bit-matrix.js
device_home/node_modules/qrcode/lib/core/byte-data.js
device_home/node_modules/qrcode/lib/core/error-correction-code.js
device_home/node_modules/qrcode/lib/core/error-correction-level.js
device_home/node_modules/qrcode/lib/core/finder-pattern.js
device_home/node_modules/qrcode/lib/core/format-info.js
device_home/node_modules/qrcode/lib/core/galois-field.js
device_home/node_modules/qrcode/lib/core/kanji-data.js
device_home/node_modules/qrcode/lib/core/mask-pattern.js
device_home/node_modules/qrcode/lib/core/mode.js
device_home/node_modules/qrcode/lib/core/numeric-data.js
device_home/node_modules/qrcode/lib/core/polynomial.js
device_home/node_modules/qrcode/lib/core/qrcode.js
device_home/node_modules/qrcode/lib/core/reed-solomon-encoder.js
device_home/node_modules/qrcode/lib/core/regex.js
device_home/node_modules/qrcode/lib/core/segments.js
device_home/node_modules/qrcode/lib/core/utils.js
device_home/node_modules/qrcode/lib/core/version-check.js
device_home/node_modules/qrcode/lib/core/version.js
device_home/node_modules/qrcode/lib/index.js
device_home/node_modules/qrcode/lib/renderer/canvas.js
device_home/node_modules/qrcode/lib/renderer/png.js
device_home/node_modules/qrcode/lib/renderer/svg-tag.js
device_home/node_modules/qrcode/lib/renderer/svg.js
device_home/node_modules/qrcode/lib/renderer/terminal.js
device_home/node_modules/qrcode/lib/renderer/utf8.js
device_home/node_modules/qrcode/lib/renderer/utils.js
device_home/node_modules/qrcode/lib/server.js
device_home/node_modules/qrcode/lib/utils/buffer.js
device_home/node_modules/qrcode/lib/utils/typedarray-buffer.js
device_home/node_modules/qs/dist/qs.js
device_home/node_modules/qs/lib/formats.js
device_home/node_modules/qs/lib/index.js
device_home/node_modules/qs/lib/parse.js
device_home/node_modules/qs/lib/stringify.js
device_home/node_modules/qs/lib/utils.js
device_home/node_modules/qs/test/index.js
device_home/node_modules/qs/test/parse.js
device_home/node_modules/qs/test/stringify.js
device_home/node_modules/qs/test/utils.js
device_home/node_modules/random-bytes/index.js
device_home/node_modules/range-parser/index.js
device_home/node_modules/raw-body/index.js
device_home/node_modules/require-directory/index.js
device_home/node_modules/require-main-filename/index.js
device_home/node_modules/safe-buffer/index.js
device_home/node_modules/safer-buffer/dangerous.js
device_home/node_modules/safer-buffer/safer.js
device_home/node_modules/safer-buffer/tests.js
device_home/node_modules/send/index.js
device_home/node_modules/serve-static/index.js
device_home/node_modules/set-blocking/index.js
device_home/node_modules/setprototypeof/index.js
device_home/node_modules/setprototypeof/test/index.js
device_home/node_modules/socket.io-adapter/index.js
device_home/node_modules/socket.io-parser/binary.js
device_home/node_modules/socket.io-parser/index.js
device_home/node_modules/socket.io-parser/is-buffer.js
device_home/node_modules/socket.io/lib/client.js
device_home/node_modules/socket.io/lib/index.js
device_home/node_modules/socket.io/lib/namespace.js
device_home/node_modules/socket.io/lib/parent-namespace.js
device_home/node_modules/socket.io/lib/socket.js
device_home/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.dev.js
device_home/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js
device_home/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.slim.dev.js
device_home/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.slim.js
device_home/node_modules/socket.io/node_modules/socket.io-client/lib/index.js
device_home/node_modules/socket.io/node_modules/socket.io-client/lib/manager.js
device_home/node_modules/socket.io/node_modules/socket.io-client/lib/on.js
device_home/node_modules/socket.io/node_modules/socket.io-client/lib/socket.js
device_home/node_modules/socket.io/node_modules/socket.io-client/lib/url.js
device_home/node_modules/statuses/index.js
device_home/node_modules/string-width/index.js
device_home/node_modules/strip-ansi/index.js
device_home/node_modules/supports-color/browser.js
device_home/node_modules/supports-color/index.js
device_home/node_modules/to-array/index.js
device_home/node_modules/toidentifier/index.js
device_home/node_modules/type-is/index.js
device_home/node_modules/uid-safe/index.js
device_home/node_modules/unpipe/index.js
device_home/node_modules/utils-merge/index.js
device_home/node_modules/vary/index.js
device_home/node_modules/which-module/index.js
device_home/node_modules/wrap-ansi/index.js
device_home/node_modules/ws/index.js
device_home/node_modules/ws/lib/buffer-util.js
device_home/node_modules/ws/lib/constants.js
device_home/node_modules/ws/lib/event-target.js
device_home/node_modules/ws/lib/extension.js
device_home/node_modules/ws/lib/permessage-deflate.js
device_home/node_modules/ws/lib/receiver.js
device_home/node_modules/ws/lib/sender.js
device_home/node_modules/ws/lib/validation.js
device_home/node_modules/ws/lib/websocket-server.js
device_home/node_modules/ws/lib/websocket.js
device_home/node_modules/ws/node_modules/async-limiter/index.js
device_home/node_modules/xmlhttprequest-ssl/example/demo.js
device_home/node_modules/xmlhttprequest-ssl/lib/XMLHttpRequest.js
device_home/node_modules/xmlhttprequest-ssl/tests/test-constants.js
device_home/node_modules/xmlhttprequest-ssl/tests/test-events.js
device_home/node_modules/xmlhttprequest-ssl/tests/test-exceptions.js
device_home/node_modules/xmlhttprequest-ssl/tests/test-headers.js
device_home/node_modules/xmlhttprequest-ssl/tests/test-redirect-302.js
device_home/node_modules/xmlhttprequest-ssl/tests/test-redirect-303.js
device_home/node_modules/xmlhttprequest-ssl/tests/test-redirect-307.js
device_home/node_modules/xmlhttprequest-ssl/tests/test-request-methods.js
device_home/node_modules/xmlhttprequest-ssl/tests/test-request-protocols.js
device_home/node_modules/xmlhttprequest/lib/XMLHttpRequest.js
device_home/node_modules/y18n/index.js
device_home/node_modules/yargs-parser/index.js
device_home/node_modules/yargs-parser/lib/tokenize-arg-string.js
device_home/node_modules/yargs/index.js
device_home/node_modules/yargs/lib/apply-extends.js
device_home/node_modules/yargs/lib/argsert.js
device_home/node_modules/yargs/lib/command.js
device_home/node_modules/yargs/lib/completion-templates.js
device_home/node_modules/yargs/lib/completion.js
device_home/node_modules/yargs/lib/decamelize.js
device_home/node_modules/yargs/lib/is-promise.js
device_home/node_modules/yargs/lib/levenshtein.js
device_home/node_modules/yargs/lib/middleware.js
device_home/node_modules/yargs/lib/obj-filter.js
device_home/node_modules/yargs/lib/usage.js
device_home/node_modules/yargs/lib/validation.js
device_home/node_modules/yargs/lib/yerror.js
device_home/node_modules/yargs/yargs.js
device_home/node_modules/yeast/index.js

index e9b2f63..2f5ca2c 100644 (file)
@@ -4,235 +4,4 @@
  * Copyright(c) 2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module dependencies.
- * @private
- */
-
-var Negotiator = require('negotiator')
-var mime = require('mime-types')
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = Accepts
-
-/**
- * Create a new Accepts object for the given req.
- *
- * @param {object} req
- * @public
- */
-
-function Accepts (req) {
-  if (!(this instanceof Accepts)) {
-    return new Accepts(req)
-  }
-
-  this.headers = req.headers
-  this.negotiator = new Negotiator(req)
-}
-
-/**
- * Check if the given `type(s)` is acceptable, returning
- * the best match when true, otherwise `undefined`, in which
- * case you should respond with 406 "Not Acceptable".
- *
- * The `type` value may be a single mime type string
- * such as "application/json", the extension name
- * such as "json" or an array `["json", "html", "text/plain"]`. When a list
- * or array is given the _best_ match, if any is returned.
- *
- * Examples:
- *
- *     // Accept: text/html
- *     this.types('html');
- *     // => "html"
- *
- *     // Accept: text/*, application/json
- *     this.types('html');
- *     // => "html"
- *     this.types('text/html');
- *     // => "text/html"
- *     this.types('json', 'text');
- *     // => "json"
- *     this.types('application/json');
- *     // => "application/json"
- *
- *     // Accept: text/*, application/json
- *     this.types('image/png');
- *     this.types('png');
- *     // => undefined
- *
- *     // Accept: text/*;q=.5, application/json
- *     this.types(['html', 'json']);
- *     this.types('html', 'json');
- *     // => "json"
- *
- * @param {String|Array} types...
- * @return {String|Array|Boolean}
- * @public
- */
-
-Accepts.prototype.type =
-Accepts.prototype.types = function (types_) {
-  var types = types_
-
-  // support flattened arguments
-  if (types && !Array.isArray(types)) {
-    types = new Array(arguments.length)
-    for (var i = 0; i < types.length; i++) {
-      types[i] = arguments[i]
-    }
-  }
-
-  // no types, return all requested types
-  if (!types || types.length === 0) {
-    return this.negotiator.mediaTypes()
-  }
-
-  // no accept header, return first given type
-  if (!this.headers.accept) {
-    return types[0]
-  }
-
-  var mimes = types.map(extToMime)
-  var accepts = this.negotiator.mediaTypes(mimes.filter(validMime))
-  var first = accepts[0]
-
-  return first
-    ? types[mimes.indexOf(first)]
-    : false
-}
-
-/**
- * Return accepted encodings or best fit based on `encodings`.
- *
- * Given `Accept-Encoding: gzip, deflate`
- * an array sorted by quality is returned:
- *
- *     ['gzip', 'deflate']
- *
- * @param {String|Array} encodings...
- * @return {String|Array}
- * @public
- */
-
-Accepts.prototype.encoding =
-Accepts.prototype.encodings = function (encodings_) {
-  var encodings = encodings_
-
-  // support flattened arguments
-  if (encodings && !Array.isArray(encodings)) {
-    encodings = new Array(arguments.length)
-    for (var i = 0; i < encodings.length; i++) {
-      encodings[i] = arguments[i]
-    }
-  }
-
-  // no encodings, return all requested encodings
-  if (!encodings || encodings.length === 0) {
-    return this.negotiator.encodings()
-  }
-
-  return this.negotiator.encodings(encodings)[0] || false
-}
-
-/**
- * Return accepted charsets or best fit based on `charsets`.
- *
- * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5`
- * an array sorted by quality is returned:
- *
- *     ['utf-8', 'utf-7', 'iso-8859-1']
- *
- * @param {String|Array} charsets...
- * @return {String|Array}
- * @public
- */
-
-Accepts.prototype.charset =
-Accepts.prototype.charsets = function (charsets_) {
-  var charsets = charsets_
-
-  // support flattened arguments
-  if (charsets && !Array.isArray(charsets)) {
-    charsets = new Array(arguments.length)
-    for (var i = 0; i < charsets.length; i++) {
-      charsets[i] = arguments[i]
-    }
-  }
-
-  // no charsets, return all requested charsets
-  if (!charsets || charsets.length === 0) {
-    return this.negotiator.charsets()
-  }
-
-  return this.negotiator.charsets(charsets)[0] || false
-}
-
-/**
- * Return accepted languages or best fit based on `langs`.
- *
- * Given `Accept-Language: en;q=0.8, es, pt`
- * an array sorted by quality is returned:
- *
- *     ['es', 'pt', 'en']
- *
- * @param {String|Array} langs...
- * @return {Array|String}
- * @public
- */
-
-Accepts.prototype.lang =
-Accepts.prototype.langs =
-Accepts.prototype.language =
-Accepts.prototype.languages = function (languages_) {
-  var languages = languages_
-
-  // support flattened arguments
-  if (languages && !Array.isArray(languages)) {
-    languages = new Array(arguments.length)
-    for (var i = 0; i < languages.length; i++) {
-      languages[i] = arguments[i]
-    }
-  }
-
-  // no languages, return all requested languages
-  if (!languages || languages.length === 0) {
-    return this.negotiator.languages()
-  }
-
-  return this.negotiator.languages(languages)[0] || false
-}
-
-/**
- * Convert extnames to mime.
- *
- * @param {String} type
- * @return {String}
- * @private
- */
-
-function extToMime (type) {
-  return type.indexOf('/') === -1
-    ? mime.lookup(type)
-    : type
-}
-
-/**
- * Check if mime is valid.
- *
- * @param {String} type
- * @return {String}
- * @private
- */
-
-function validMime (type) {
-  return typeof type === 'string'
-}
+"use strict";var Negotiator=require("negotiator"),mime=require("mime-types");function Accepts(t){if(!(this instanceof Accepts))return new Accepts(t);this.headers=t.headers,this.negotiator=new Negotiator(t)}function extToMime(t){return-1===t.indexOf("/")?mime.lookup(t):t}function validMime(t){return"string"==typeof t}module.exports=Accepts,Accepts.prototype.type=Accepts.prototype.types=function(t){var e=t;if(e&&!Array.isArray(e)){e=new Array(arguments.length);for(var r=0;r<e.length;r++)e[r]=arguments[r]}if(!e||0===e.length)return this.negotiator.mediaTypes();if(!this.headers.accept)return e[0];var n=e.map(extToMime),o=this.negotiator.mediaTypes(n.filter(validMime)),i=o[0];return!!i&&e[n.indexOf(i)]},Accepts.prototype.encoding=Accepts.prototype.encodings=function(t){var e=t;if(e&&!Array.isArray(e)){e=new Array(arguments.length);for(var r=0;r<e.length;r++)e[r]=arguments[r]}return e&&0!==e.length?this.negotiator.encodings(e)[0]||!1:this.negotiator.encodings()},Accepts.prototype.charset=Accepts.prototype.charsets=function(t){var e=t;if(e&&!Array.isArray(e)){e=new Array(arguments.length);for(var r=0;r<e.length;r++)e[r]=arguments[r]}return e&&0!==e.length?this.negotiator.charsets(e)[0]||!1:this.negotiator.charsets()},Accepts.prototype.lang=Accepts.prototype.langs=Accepts.prototype.language=Accepts.prototype.languages=function(t){var e=t;if(e&&!Array.isArray(e)){e=new Array(arguments.length);for(var r=0;r<e.length;r++)e[r]=arguments[r]}return e&&0!==e.length?this.negotiator.languages(e)[0]||!1:this.negotiator.languages()};
\ No newline at end of file
index ec24879..d022023 100644 (file)
@@ -1,28 +1 @@
-module.exports = after
-
-function after(count, callback, err_cb) {
-    var bail = false
-    err_cb = err_cb || noop
-    proxy.count = count
-
-    return (count === 0) ? callback() : proxy
-
-    function proxy(err, result) {
-        if (proxy.count <= 0) {
-            throw new Error('after called too many times')
-        }
-        --proxy.count
-
-        // after first error, rest are passed to err_cb
-        if (err) {
-            bail = true
-            callback(err)
-            // future error callbacks will go to error handler
-            callback = err_cb
-        } else if (proxy.count === 0 && !bail) {
-            callback(null, result)
-        }
-    }
-}
-
-function noop() {}
+function after(o,n,t){var r=!1;return t=t||noop,u.count=o,0===o?n():u;function u(o,e){if(u.count<=0)throw new Error("after called too many times");--u.count,o?(r=!0,n(o),n=t):0!==u.count||r||n(null,e)}}function noop(){}module.exports=after;
\ No newline at end of file
index 0d63f4c..4c1fdb8 100644 (file)
@@ -1,120 +1 @@
-/*global suite, test*/
-
-var assert = require("assert")
-    , after = require("../")
-
-test("exists", function () {
-    assert(typeof after === "function", "after is not a function")
-})
-
-test("after when called with 0 invokes", function (done) {
-    after(0, done)
-});
-
-test("after 1", function (done) {
-    var next = after(1, done)
-    next()
-})
-
-test("after 5", function (done) {
-    var next = after(5, done)
-    , i = 5
-
-    while (i--) {
-        next()
-    }
-})
-
-test("manipulate count", function (done) {
-    var next = after(1, done)
-    , i = 5
-
-    next.count = i
-    while (i--) {
-        next()
-    }
-})
-
-test("after terminates on error", function (done) {
-    var next = after(2, function(err) {
-        assert.equal(err.message, 'test');
-        done();
-    })
-    next(new Error('test'))
-    next(new Error('test2'))
-})
-
-test('gee', function(done) {
-    done = after(2, done)
-
-    function cb(err) {
-        assert.equal(err.message, 1);
-        done()
-    }
-
-    var next = after(3, cb, function(err) {
-        assert.equal(err.message, 2)
-        done()
-    });
-
-    next()
-    next(new Error(1))
-    next(new Error(2))
-})
-
-test('eee', function(done) {
-    done = after(3, done)
-
-    function cb(err) {
-        assert.equal(err.message, 1);
-        done()
-    }
-
-    var next = after(3, cb, function(err) {
-        assert.equal(err.message, 2)
-        done()
-    });
-
-    next(new Error(1))
-    next(new Error(2))
-    next(new Error(2))
-})
-
-test('gge', function(done) {
-    function cb(err) {
-        assert.equal(err.message, 1);
-        done()
-    }
-
-    var next = after(3, cb, function(err) {
-        // should not happen
-        assert.ok(false);
-    });
-
-    next()
-    next()
-    next(new Error(1))
-})
-
-test('egg', function(done) {
-    function cb(err) {
-        assert.equal(err.message, 1);
-        done()
-    }
-
-    var next = after(3, cb, function(err) {
-        // should not happen
-        assert.ok(false);
-    });
-
-    next(new Error(1))
-    next()
-    next()
-})
-
-test('throws on too many calls', function(done) {
-    var next = after(1, done);
-    next()
-    assert.throws(next, /after called too many times/);
-});
-
+var assert=require("assert"),after=require("../");test("exists",(function(){assert("function"==typeof after,"after is not a function")})),test("after when called with 0 invokes",(function(e){after(0,e)})),test("after 1",(function(e){after(1,e)()})),test("after 5",(function(e){for(var t=after(5,e),r=5;r--;)t()})),test("manipulate count",(function(e){var t=after(1,e),r=5;for(t.count=r;r--;)t()})),test("after terminates on error",(function(e){var t=after(2,(function(t){assert.equal(t.message,"test"),e()}));t(new Error("test")),t(new Error("test2"))})),test("gee",(function(e){e=after(2,e);var t=after(3,(function(t){assert.equal(t.message,1),e()}),(function(t){assert.equal(t.message,2),e()}));t(),t(new Error(1)),t(new Error(2))})),test("eee",(function(e){e=after(3,e);var t=after(3,(function(t){assert.equal(t.message,1),e()}),(function(t){assert.equal(t.message,2),e()}));t(new Error(1)),t(new Error(2)),t(new Error(2))})),test("gge",(function(e){var t=after(3,(function(t){assert.equal(t.message,1),e()}),(function(e){assert.ok(!1)}));t(),t(),t(new Error(1))})),test("egg",(function(e){var t=after(3,(function(t){assert.equal(t.message,1),e()}),(function(e){assert.ok(!1)}));t(new Error(1)),t(),t()})),test("throws on too many calls",(function(e){var t=after(1,e);t(),assert.throws(t,/after called too many times/)}));
\ No newline at end of file
index c254480..0cd5a73 100644 (file)
@@ -1,14 +1 @@
-'use strict';
-
-module.exports = options => {
-       options = Object.assign({
-               onlyFirst: false
-       }, options);
-
-       const pattern = [
-               '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)',
-               '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))'
-       ].join('|');
-
-       return new RegExp(pattern, options.onlyFirst ? undefined : 'g');
-};
+"use strict";module.exports=t=>{t=Object.assign({onlyFirst:!1},t);const n=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|");return new RegExp(n,t.onlyFirst?void 0:"g")};
\ No newline at end of file
index 90a871c..c5d91da 100644 (file)
@@ -1,165 +1 @@
-'use strict';
-const colorConvert = require('color-convert');
-
-const wrapAnsi16 = (fn, offset) => function () {
-       const code = fn.apply(colorConvert, arguments);
-       return `\u001B[${code + offset}m`;
-};
-
-const wrapAnsi256 = (fn, offset) => function () {
-       const code = fn.apply(colorConvert, arguments);
-       return `\u001B[${38 + offset};5;${code}m`;
-};
-
-const wrapAnsi16m = (fn, offset) => function () {
-       const rgb = fn.apply(colorConvert, arguments);
-       return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
-};
-
-function assembleStyles() {
-       const codes = new Map();
-       const styles = {
-               modifier: {
-                       reset: [0, 0],
-                       // 21 isn't widely supported and 22 does the same thing
-                       bold: [1, 22],
-                       dim: [2, 22],
-                       italic: [3, 23],
-                       underline: [4, 24],
-                       inverse: [7, 27],
-                       hidden: [8, 28],
-                       strikethrough: [9, 29]
-               },
-               color: {
-                       black: [30, 39],
-                       red: [31, 39],
-                       green: [32, 39],
-                       yellow: [33, 39],
-                       blue: [34, 39],
-                       magenta: [35, 39],
-                       cyan: [36, 39],
-                       white: [37, 39],
-                       gray: [90, 39],
-
-                       // Bright color
-                       redBright: [91, 39],
-                       greenBright: [92, 39],
-                       yellowBright: [93, 39],
-                       blueBright: [94, 39],
-                       magentaBright: [95, 39],
-                       cyanBright: [96, 39],
-                       whiteBright: [97, 39]
-               },
-               bgColor: {
-                       bgBlack: [40, 49],
-                       bgRed: [41, 49],
-                       bgGreen: [42, 49],
-                       bgYellow: [43, 49],
-                       bgBlue: [44, 49],
-                       bgMagenta: [45, 49],
-                       bgCyan: [46, 49],
-                       bgWhite: [47, 49],
-
-                       // Bright color
-                       bgBlackBright: [100, 49],
-                       bgRedBright: [101, 49],
-                       bgGreenBright: [102, 49],
-                       bgYellowBright: [103, 49],
-                       bgBlueBright: [104, 49],
-                       bgMagentaBright: [105, 49],
-                       bgCyanBright: [106, 49],
-                       bgWhiteBright: [107, 49]
-               }
-       };
-
-       // Fix humans
-       styles.color.grey = styles.color.gray;
-
-       for (const groupName of Object.keys(styles)) {
-               const group = styles[groupName];
-
-               for (const styleName of Object.keys(group)) {
-                       const style = group[styleName];
-
-                       styles[styleName] = {
-                               open: `\u001B[${style[0]}m`,
-                               close: `\u001B[${style[1]}m`
-                       };
-
-                       group[styleName] = styles[styleName];
-
-                       codes.set(style[0], style[1]);
-               }
-
-               Object.defineProperty(styles, groupName, {
-                       value: group,
-                       enumerable: false
-               });
-
-               Object.defineProperty(styles, 'codes', {
-                       value: codes,
-                       enumerable: false
-               });
-       }
-
-       const ansi2ansi = n => n;
-       const rgb2rgb = (r, g, b) => [r, g, b];
-
-       styles.color.close = '\u001B[39m';
-       styles.bgColor.close = '\u001B[49m';
-
-       styles.color.ansi = {
-               ansi: wrapAnsi16(ansi2ansi, 0)
-       };
-       styles.color.ansi256 = {
-               ansi256: wrapAnsi256(ansi2ansi, 0)
-       };
-       styles.color.ansi16m = {
-               rgb: wrapAnsi16m(rgb2rgb, 0)
-       };
-
-       styles.bgColor.ansi = {
-               ansi: wrapAnsi16(ansi2ansi, 10)
-       };
-       styles.bgColor.ansi256 = {
-               ansi256: wrapAnsi256(ansi2ansi, 10)
-       };
-       styles.bgColor.ansi16m = {
-               rgb: wrapAnsi16m(rgb2rgb, 10)
-       };
-
-       for (let key of Object.keys(colorConvert)) {
-               if (typeof colorConvert[key] !== 'object') {
-                       continue;
-               }
-
-               const suite = colorConvert[key];
-
-               if (key === 'ansi16') {
-                       key = 'ansi';
-               }
-
-               if ('ansi16' in suite) {
-                       styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0);
-                       styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10);
-               }
-
-               if ('ansi256' in suite) {
-                       styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0);
-                       styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10);
-               }
-
-               if ('rgb' in suite) {
-                       styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0);
-                       styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10);
-               }
-       }
-
-       return styles;
-}
-
-// Make the export immutable
-Object.defineProperty(module, 'exports', {
-       enumerable: true,
-       get: assembleStyles
-});
+"use strict";const colorConvert=require("color-convert"),wrapAnsi16=(r,e)=>function(){const o=r.apply(colorConvert,arguments);return`\e[${o+e}m`},wrapAnsi256=(r,e)=>function(){const o=r.apply(colorConvert,arguments);return`\e[${38+e};5;${o}m`},wrapAnsi16m=(r,e)=>function(){const o=r.apply(colorConvert,arguments);return`\e[${38+e};2;${o[0]};${o[1]};${o[2]}m`};function assembleStyles(){const r=new Map,e={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],gray:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};e.color.grey=e.color.gray;for(const o of Object.keys(e)){const n=e[o];for(const o of Object.keys(n)){const i=n[o];e[o]={open:`\e[${i[0]}m`,close:`\e[${i[1]}m`},n[o]=e[o],r.set(i[0],i[1])}Object.defineProperty(e,o,{value:n,enumerable:!1}),Object.defineProperty(e,"codes",{value:r,enumerable:!1})}const o=r=>r,n=(r,e,o)=>[r,e,o];e.color.close="\e[39m",e.bgColor.close="\e[49m",e.color.ansi={ansi:wrapAnsi16(o,0)},e.color.ansi256={ansi256:wrapAnsi256(o,0)},e.color.ansi16m={rgb:wrapAnsi16m(n,0)},e.bgColor.ansi={ansi:wrapAnsi16(o,10)},e.bgColor.ansi256={ansi256:wrapAnsi256(o,10)},e.bgColor.ansi16m={rgb:wrapAnsi16m(n,10)};for(let r of Object.keys(colorConvert)){if("object"!=typeof colorConvert[r])continue;const o=colorConvert[r];"ansi16"===r&&(r="ansi"),"ansi16"in o&&(e.color.ansi[r]=wrapAnsi16(o.ansi16,0),e.bgColor.ansi[r]=wrapAnsi16(o.ansi16,10)),"ansi256"in o&&(e.color.ansi256[r]=wrapAnsi256(o.ansi256,0),e.bgColor.ansi256[r]=wrapAnsi256(o.ansi256,10)),"rgb"in o&&(e.color.ansi16m[r]=wrapAnsi16m(o.rgb,0),e.bgColor.ansi16m[r]=wrapAnsi16m(o.rgb,10))}return e}Object.defineProperty(module,"exports",{enumerable:!0,get:assembleStyles});
\ No newline at end of file
index 089117b..2b36da6 100644 (file)
@@ -1,64 +1 @@
-'use strict'
-
-/**
- * Expose `arrayFlatten`.
- */
-module.exports = arrayFlatten
-
-/**
- * Recursive flatten function with depth.
- *
- * @param  {Array}  array
- * @param  {Array}  result
- * @param  {Number} depth
- * @return {Array}
- */
-function flattenWithDepth (array, result, depth) {
-  for (var i = 0; i < array.length; i++) {
-    var value = array[i]
-
-    if (depth > 0 && Array.isArray(value)) {
-      flattenWithDepth(value, result, depth - 1)
-    } else {
-      result.push(value)
-    }
-  }
-
-  return result
-}
-
-/**
- * Recursive flatten function. Omitting depth is slightly faster.
- *
- * @param  {Array} array
- * @param  {Array} result
- * @return {Array}
- */
-function flattenForever (array, result) {
-  for (var i = 0; i < array.length; i++) {
-    var value = array[i]
-
-    if (Array.isArray(value)) {
-      flattenForever(value, result)
-    } else {
-      result.push(value)
-    }
-  }
-
-  return result
-}
-
-/**
- * Flatten an array, with the ability to define a depth.
- *
- * @param  {Array}  array
- * @param  {Number} depth
- * @return {Array}
- */
-function arrayFlatten (array, depth) {
-  if (depth == null) {
-    return flattenForever(array, [])
-  }
-
-  return flattenWithDepth(array, [], depth)
-}
+"use strict";function flattenWithDepth(t,r,e){for(var a=0;a<t.length;a++){var n=t[a];e>0&&Array.isArray(n)?flattenWithDepth(n,r,e-1):r.push(n)}return r}function flattenForever(t,r){for(var e=0;e<t.length;e++){var a=t[e];Array.isArray(a)?flattenForever(a,r):r.push(a)}return r}function arrayFlatten(t,r){return null==r?flattenForever(t,[]):flattenWithDepth(t,[],r)}module.exports=arrayFlatten;
\ No newline at end of file
index 11ac556..b8f4eb3 100644 (file)
@@ -1,29 +1 @@
-/**
- * An abstraction for slicing an arraybuffer even when
- * ArrayBuffer.prototype.slice is not supported
- *
- * @api public
- */
-
-module.exports = function(arraybuffer, start, end) {
-  var bytes = arraybuffer.byteLength;
-  start = start || 0;
-  end = end || bytes;
-
-  if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
-
-  if (start < 0) { start += bytes; }
-  if (end < 0) { end += bytes; }
-  if (end > bytes) { end = bytes; }
-
-  if (start >= bytes || start >= end || bytes === 0) {
-    return new ArrayBuffer(0);
-  }
-
-  var abv = new Uint8Array(arraybuffer);
-  var result = new Uint8Array(end - start);
-  for (var i = start, ii = 0; i < end; i++, ii++) {
-    result[ii] = abv[i];
-  }
-  return result.buffer;
-};
+module.exports=function(r,e,n){var t=r.byteLength;if(e=e||0,n=n||t,r.slice)return r.slice(e,n);if(e<0&&(e+=t),n<0&&(n+=t),n>t&&(n=t),e>=t||e>=n||0===t)return new ArrayBuffer(0);for(var f=new Uint8Array(r),i=new Uint8Array(n-e),u=e,a=0;u<n;u++,a++)i[a]=f[u];return i.buffer};
\ No newline at end of file
index 4778da6..07f01d2 100644 (file)
@@ -1,227 +1 @@
-/*
- * Test dependencies
- */
-
-var sliceBuffer = require('../index.js');
-var expect = require('expect.js');
-
-/**
- * Tests
- */
-
-describe('sliceBuffer', function() {
-  describe('using standard slice', function() {
-    it('should slice correctly with only start provided', function() {
-      var abv = new Uint8Array(10);
-      for (var i = 0; i < abv.length; i++) {
-        abv[i] = i;
-      }
-
-      var sliced = sliceBuffer(abv.buffer, 3);
-      var sabv = new Uint8Array(sliced);
-      for (var i = 3, ii = 0; i < abv.length; i++, ii++) {
-        expect(abv[i]).to.equal(sabv[ii]);
-      }
-    });
-
-    it('should slice correctly with start and end provided', function() {
-      var abv = new Uint8Array(10);
-      for (var i = 0; i < abv.length; i++) {
-        abv[i] = i;
-      }
-
-      var sliced = sliceBuffer(abv.buffer, 3, 8);
-      var sabv = new Uint8Array(sliced);
-      for (var i = 3, ii = 0; i < 8; i++, ii++) {
-        expect(abv[i]).to.equal(sabv[ii]);
-      }
-    });
-
-    it('should slice correctly with negative start', function() {
-      var abv = new Uint8Array(10);
-      for (var i = 0; i < abv.length; i++) {
-        abv[i] = i;
-      }
-
-      var sliced = sliceBuffer(abv.buffer, -3);
-      var sabv = new Uint8Array(sliced);
-      for (var i = abv.length - 3, ii = 0; i < abv.length; i++, ii++) {
-        expect(abv[i]).to.equal(sabv[ii]);
-      }
-    });
-
-    it('should slice correctly with negative end', function() {
-      var abv = new Uint8Array(10);
-      for (var i = 0; i < abv.length; i++) {
-        abv[i] = i;
-      }
-
-      var sliced = sliceBuffer(abv.buffer, 0, -3);
-      var sabv = new Uint8Array(sliced);
-      for (var i = 0, ii = 0; i < abv.length - 3; i++, ii++) {
-        expect(abv[i]).to.equal(sabv[ii]);
-      }
-    });
-
-    it('should slice correctly with negative start and end', function() {
-      var abv = new Uint8Array(10);
-      for (var i = 0; i < abv.length; i++) {
-        abv[i] = i;
-      }
-
-      var sliced = sliceBuffer(abv.buffer, -6, -3);
-      var sabv = new Uint8Array(sliced);
-      for (var i = abv.length - 6, ii = 0; i < abv.length - 3; i++, ii++) {
-        expect(abv[i]).to.equal(sabv[ii]);
-      }
-    });
-
-    it('should slice correctly with equal start and end', function() {
-      var abv = new Uint8Array(10);
-      for (var i = 0; i < abv.length; i++) {
-        abv[i] = i;
-      }
-
-      var sliced = sliceBuffer(abv.buffer, 1, 1);
-      expect(sliced.byteLength).to.equal(0);
-    });
-    
-    it('should slice correctly when end larger than buffer', function() {
-      var abv = new Uint8Array(10);
-      for (var i = 0; i < abv.length; i++) {
-        abv[i] = i;
-      }
-
-      var sliced = sliceBuffer(abv.buffer, 0, 100);
-      expect(new Uint8Array(sliced)).to.eql(abv);
-    });
-
-    it('shoud slice correctly when start larger than end', function() {
-      var abv = new Uint8Array(10);
-      for (var i = 0; i < abv.length; i++) {
-        abv[i] = i;
-      }
-
-      var sliced = sliceBuffer(abv.buffer, 6, 5);
-      expect(sliced.byteLength).to.equal(0);
-    });
-  });
-
-  describe('using fallback', function() {
-    it('should slice correctly with only start provided', function() {
-      var abv = new Uint8Array(10);
-      for (var i = 0; i < abv.length; i++) {
-        abv[i] = i;
-      }
-      var ab = abv.buffer;
-      ab.slice = undefined;
-
-      var sliced = sliceBuffer(ab, 3);
-      var sabv = new Uint8Array(sliced);
-      for (var i = 3, ii = 0; i < abv.length; i++, ii++) {
-        expect(abv[i]).to.equal(sabv[ii]);
-      }
-    });
-
-    it('should slice correctly with start and end provided', function() {
-      var abv = new Uint8Array(10);
-      for (var i = 0; i < abv.length; i++) {
-        abv[i] = i;
-      }
-      var ab = abv.buffer;
-      ab.slice = undefined;
-
-
-      var sliced = sliceBuffer(ab, 3, 8);
-      var sabv = new Uint8Array(sliced);
-      for (var i = 3, ii = 0; i < 8; i++, ii++) {
-        expect(abv[i]).to.equal(sabv[ii]);
-      }
-    });
-
-    it('should slice correctly with negative start', function() {
-      var abv = new Uint8Array(10);
-      for (var i = 0; i < abv.length; i++) {
-        abv[i] = i;
-      }
-      var ab = abv.buffer;
-      ab.slice = undefined;
-
-
-      var sliced = sliceBuffer(ab, -3);
-      var sabv = new Uint8Array(sliced);
-      for (var i = abv.length - 3, ii = 0; i < abv.length; i++, ii++) {
-        expect(abv[i]).to.equal(sabv[ii]);
-      }
-    });
-
-    it('should slice correctly with negative end', function() {
-      var abv = new Uint8Array(10);
-      for (var i = 0; i < abv.length; i++) {
-        abv[i] = i;
-      }
-      var ab = abv.buffer;
-      ab.slice = undefined;
-
-      var sliced = sliceBuffer(ab, 0, -3);
-      var sabv = new Uint8Array(sliced);
-      for (var i = 0, ii = 0; i < abv.length - 3; i++, ii++) {
-        expect(abv[i]).to.equal(sabv[ii]);
-      }
-    });
-
-    it('should slice correctly with negative start and end', function() {
-      var abv = new Uint8Array(10);
-      for (var i = 0; i < abv.length; i++) {
-        abv[i] = i;
-      }
-      var ab = abv.buffer;
-      ab.slice = undefined;
-
-      var sliced = sliceBuffer(ab, -6, -3);
-      var sabv = new Uint8Array(sliced);
-      for (var i = abv.length - 6, ii = 0; i < abv.length - 3; i++, ii++) {
-        expect(abv[i]).to.equal(sabv[ii]);
-      }
-    });
-
-    it('should slice correctly with equal start and end', function() {
-      var abv = new Uint8Array(10);
-      for (var i = 0; i < abv.length; i++) {
-        abv[i] = i;
-      }
-      var ab = abv.buffer;
-      ab.slice = undefined;
-
-      var sliced = sliceBuffer(ab, 1, 1);
-      expect(sliced.byteLength).to.equal(0);
-    });
-
-    it('should slice correctly when end larger than buffer', function() {
-      var abv = new Uint8Array(10);
-      for (var i = 0; i < abv.length; i++) {
-        abv[i] = i;
-      }
-      var ab = abv.buffer;
-      ab.slice = undefined;
-
-      var sliced = sliceBuffer(ab, 0, 100);
-      var sabv = new Uint8Array(sliced);
-      for (var i = 0; i < abv.length; i++) {
-        expect(abv[i]).to.equal(sabv[i]);
-      }
-    });
-
-    it('shoud slice correctly when start larger than end', function() {
-      var abv = new Uint8Array(10);
-      for (var i = 0; i < abv.length; i++) {
-        abv[i] = i;
-      }
-      var ab = abv.buffer;
-      ab.slice = undefined;
-
-      var sliced = sliceBuffer(ab, 6, 5);
-      expect(sliced.byteLength).to.equal(0);
-    });
-  });
-});
+var sliceBuffer=require("../index.js"),expect=require("expect.js");describe("sliceBuffer",(function(){describe("using standard slice",(function(){it("should slice correctly with only start provided",(function(){for(var e=new Uint8Array(10),r=0;r<e.length;r++)e[r]=r;for(var t=sliceBuffer(e.buffer,3),n=new Uint8Array(t),i=(r=3,0);r<e.length;r++,i++)expect(e[r]).to.equal(n[i])})),it("should slice correctly with start and end provided",(function(){for(var e=new Uint8Array(10),r=0;r<e.length;r++)e[r]=r;for(var t=sliceBuffer(e.buffer,3,8),n=new Uint8Array(t),i=(r=3,0);r<8;r++,i++)expect(e[r]).to.equal(n[i])})),it("should slice correctly with negative start",(function(){for(var e=new Uint8Array(10),r=0;r<e.length;r++)e[r]=r;for(var t=sliceBuffer(e.buffer,-3),n=new Uint8Array(t),i=(r=e.length-3,0);r<e.length;r++,i++)expect(e[r]).to.equal(n[i])})),it("should slice correctly with negative end",(function(){for(var e=new Uint8Array(10),r=0;r<e.length;r++)e[r]=r;for(var t=sliceBuffer(e.buffer,0,-3),n=new Uint8Array(t),i=(r=0,0);r<e.length-3;r++,i++)expect(e[r]).to.equal(n[i])})),it("should slice correctly with negative start and end",(function(){for(var e=new Uint8Array(10),r=0;r<e.length;r++)e[r]=r;for(var t=sliceBuffer(e.buffer,-6,-3),n=new Uint8Array(t),i=(r=e.length-6,0);r<e.length-3;r++,i++)expect(e[r]).to.equal(n[i])})),it("should slice correctly with equal start and end",(function(){for(var e=new Uint8Array(10),r=0;r<e.length;r++)e[r]=r;var t=sliceBuffer(e.buffer,1,1);expect(t.byteLength).to.equal(0)})),it("should slice correctly when end larger than buffer",(function(){for(var e=new Uint8Array(10),r=0;r<e.length;r++)e[r]=r;var t=sliceBuffer(e.buffer,0,100);expect(new Uint8Array(t)).to.eql(e)})),it("shoud slice correctly when start larger than end",(function(){for(var e=new Uint8Array(10),r=0;r<e.length;r++)e[r]=r;var t=sliceBuffer(e.buffer,6,5);expect(t.byteLength).to.equal(0)}))})),describe("using fallback",(function(){it("should slice correctly with only start provided",(function(){for(var e=new Uint8Array(10),r=0;r<e.length;r++)e[r]=r;var t=e.buffer;t.slice=void 0;for(var n=sliceBuffer(t,3),i=new Uint8Array(n),l=(r=3,0);r<e.length;r++,l++)expect(e[r]).to.equal(i[l])})),it("should slice correctly with start and end provided",(function(){for(var e=new Uint8Array(10),r=0;r<e.length;r++)e[r]=r;var t=e.buffer;t.slice=void 0;for(var n=sliceBuffer(t,3,8),i=new Uint8Array(n),l=(r=3,0);r<8;r++,l++)expect(e[r]).to.equal(i[l])})),it("should slice correctly with negative start",(function(){for(var e=new Uint8Array(10),r=0;r<e.length;r++)e[r]=r;var t=e.buffer;t.slice=void 0;for(var n=sliceBuffer(t,-3),i=new Uint8Array(n),l=(r=e.length-3,0);r<e.length;r++,l++)expect(e[r]).to.equal(i[l])})),it("should slice correctly with negative end",(function(){for(var e=new Uint8Array(10),r=0;r<e.length;r++)e[r]=r;var t=e.buffer;t.slice=void 0;for(var n=sliceBuffer(t,0,-3),i=new Uint8Array(n),l=(r=0,0);r<e.length-3;r++,l++)expect(e[r]).to.equal(i[l])})),it("should slice correctly with negative start and end",(function(){for(var e=new Uint8Array(10),r=0;r<e.length;r++)e[r]=r;var t=e.buffer;t.slice=void 0;for(var n=sliceBuffer(t,-6,-3),i=new Uint8Array(n),l=(r=e.length-6,0);r<e.length-3;r++,l++)expect(e[r]).to.equal(i[l])})),it("should slice correctly with equal start and end",(function(){for(var e=new Uint8Array(10),r=0;r<e.length;r++)e[r]=r;var t=e.buffer;t.slice=void 0;var n=sliceBuffer(t,1,1);expect(n.byteLength).to.equal(0)})),it("should slice correctly when end larger than buffer",(function(){for(var e=new Uint8Array(10),r=0;r<e.length;r++)e[r]=r;var t=e.buffer;t.slice=void 0;var n=sliceBuffer(t,0,100),i=new Uint8Array(n);for(r=0;r<e.length;r++)expect(e[r]).to.equal(i[r])})),it("shoud slice correctly when start larger than end",(function(){for(var e=new Uint8Array(10),r=0;r<e.length;r++)e[r]=r;var t=e.buffer;t.slice=void 0;var n=sliceBuffer(t,6,5);expect(n.byteLength).to.equal(0)}))}))}));
\ No newline at end of file
index 394c41c..282c1ea 100644 (file)
  * Copyright 2010-2014 Caolan McMahon
  * Released under the MIT license
  */
-/*jshint onevar: false, indent:4 */
-/*global setImmediate: false, setTimeout: false, console: false */
-(function () {
-
-    var async = {};
-
-    // global on the server, window in the browser
-    var root, previous_async;
-
-    root = this;
-    if (root != null) {
-      previous_async = root.async;
-    }
-
-    async.noConflict = function () {
-        root.async = previous_async;
-        return async;
-    };
-
-    function only_once(fn) {
-        var called = false;
-        return function() {
-            if (called) throw new Error("Callback was already called.");
-            called = true;
-            fn.apply(root, arguments);
-        }
-    }
-
-    //// cross-browser compatiblity functions ////
-
-    var _toString = Object.prototype.toString;
-
-    var _isArray = Array.isArray || function (obj) {
-        return _toString.call(obj) === '[object Array]';
-    };
-
-    var _each = function (arr, iterator) {
-        for (var i = 0; i < arr.length; i += 1) {
-            iterator(arr[i], i, arr);
-        }
-    };
-
-    var _map = function (arr, iterator) {
-        if (arr.map) {
-            return arr.map(iterator);
-        }
-        var results = [];
-        _each(arr, function (x, i, a) {
-            results.push(iterator(x, i, a));
-        });
-        return results;
-    };
-
-    var _reduce = function (arr, iterator, memo) {
-        if (arr.reduce) {
-            return arr.reduce(iterator, memo);
-        }
-        _each(arr, function (x, i, a) {
-            memo = iterator(memo, x, i, a);
-        });
-        return memo;
-    };
-
-    var _keys = function (obj) {
-        if (Object.keys) {
-            return Object.keys(obj);
-        }
-        var keys = [];
-        for (var k in obj) {
-            if (obj.hasOwnProperty(k)) {
-                keys.push(k);
-            }
-        }
-        return keys;
-    };
-
-    //// exported async module functions ////
-
-    //// nextTick implementation with browser-compatible fallback ////
-    if (typeof process === 'undefined' || !(process.nextTick)) {
-        if (typeof setImmediate === 'function') {
-            async.nextTick = function (fn) {
-                // not a direct alias for IE10 compatibility
-                setImmediate(fn);
-            };
-            async.setImmediate = async.nextTick;
-        }
-        else {
-            async.nextTick = function (fn) {
-                setTimeout(fn, 0);
-            };
-            async.setImmediate = async.nextTick;
-        }
-    }
-    else {
-        async.nextTick = process.nextTick;
-        if (typeof setImmediate !== 'undefined') {
-            async.setImmediate = function (fn) {
-              // not a direct alias for IE10 compatibility
-              setImmediate(fn);
-            };
-        }
-        else {
-            async.setImmediate = async.nextTick;
-        }
-    }
-
-    async.each = function (arr, iterator, callback) {
-        callback = callback || function () {};
-        if (!arr.length) {
-            return callback();
-        }
-        var completed = 0;
-        _each(arr, function (x) {
-            iterator(x, only_once(done) );
-        });
-        function done(err) {
-          if (err) {
-              callback(err);
-              callback = function () {};
-          }
-          else {
-              completed += 1;
-              if (completed >= arr.length) {
-                  callback();
-              }
-          }
-        }
-    };
-    async.forEach = async.each;
-
-    async.eachSeries = function (arr, iterator, callback) {
-        callback = callback || function () {};
-        if (!arr.length) {
-            return callback();
-        }
-        var completed = 0;
-        var iterate = function () {
-            iterator(arr[completed], function (err) {
-                if (err) {
-                    callback(err);
-                    callback = function () {};
-                }
-                else {
-                    completed += 1;
-                    if (completed >= arr.length) {
-                        callback();
-                    }
-                    else {
-                        iterate();
-                    }
-                }
-            });
-        };
-        iterate();
-    };
-    async.forEachSeries = async.eachSeries;
-
-    async.eachLimit = function (arr, limit, iterator, callback) {
-        var fn = _eachLimit(limit);
-        fn.apply(null, [arr, iterator, callback]);
-    };
-    async.forEachLimit = async.eachLimit;
-
-    var _eachLimit = function (limit) {
-
-        return function (arr, iterator, callback) {
-            callback = callback || function () {};
-            if (!arr.length || limit <= 0) {
-                return callback();
-            }
-            var completed = 0;
-            var started = 0;
-            var running = 0;
-
-            (function replenish () {
-                if (completed >= arr.length) {
-                    return callback();
-                }
-
-                while (running < limit && started < arr.length) {
-                    started += 1;
-                    running += 1;
-                    iterator(arr[started - 1], function (err) {
-                        if (err) {
-                            callback(err);
-                            callback = function () {};
-                        }
-                        else {
-                            completed += 1;
-                            running -= 1;
-                            if (completed >= arr.length) {
-                                callback();
-                            }
-                            else {
-                                replenish();
-                            }
-                        }
-                    });
-                }
-            })();
-        };
-    };
-
-
-    var doParallel = function (fn) {
-        return function () {
-            var args = Array.prototype.slice.call(arguments);
-            return fn.apply(null, [async.each].concat(args));
-        };
-    };
-    var doParallelLimit = function(limit, fn) {
-        return function () {
-            var args = Array.prototype.slice.call(arguments);
-            return fn.apply(null, [_eachLimit(limit)].concat(args));
-        };
-    };
-    var doSeries = function (fn) {
-        return function () {
-            var args = Array.prototype.slice.call(arguments);
-            return fn.apply(null, [async.eachSeries].concat(args));
-        };
-    };
-
-
-    var _asyncMap = function (eachfn, arr, iterator, callback) {
-        arr = _map(arr, function (x, i) {
-            return {index: i, value: x};
-        });
-        if (!callback) {
-            eachfn(arr, function (x, callback) {
-                iterator(x.value, function (err) {
-                    callback(err);
-                });
-            });
-        } else {
-            var results = [];
-            eachfn(arr, function (x, callback) {
-                iterator(x.value, function (err, v) {
-                    results[x.index] = v;
-                    callback(err);
-                });
-            }, function (err) {
-                callback(err, results);
-            });
-        }
-    };
-    async.map = doParallel(_asyncMap);
-    async.mapSeries = doSeries(_asyncMap);
-    async.mapLimit = function (arr, limit, iterator, callback) {
-        return _mapLimit(limit)(arr, iterator, callback);
-    };
-
-    var _mapLimit = function(limit) {
-        return doParallelLimit(limit, _asyncMap);
-    };
-
-    // reduce only has a series version, as doing reduce in parallel won't
-    // work in many situations.
-    async.reduce = function (arr, memo, iterator, callback) {
-        async.eachSeries(arr, function (x, callback) {
-            iterator(memo, x, function (err, v) {
-                memo = v;
-                callback(err);
-            });
-        }, function (err) {
-            callback(err, memo);
-        });
-    };
-    // inject alias
-    async.inject = async.reduce;
-    // foldl alias
-    async.foldl = async.reduce;
-
-    async.reduceRight = function (arr, memo, iterator, callback) {
-        var reversed = _map(arr, function (x) {
-            return x;
-        }).reverse();
-        async.reduce(reversed, memo, iterator, callback);
-    };
-    // foldr alias
-    async.foldr = async.reduceRight;
-
-    var _filter = function (eachfn, arr, iterator, callback) {
-        var results = [];
-        arr = _map(arr, function (x, i) {
-            return {index: i, value: x};
-        });
-        eachfn(arr, function (x, callback) {
-            iterator(x.value, function (v) {
-                if (v) {
-                    results.push(x);
-                }
-                callback();
-            });
-        }, function (err) {
-            callback(_map(results.sort(function (a, b) {
-                return a.index - b.index;
-            }), function (x) {
-                return x.value;
-            }));
-        });
-    };
-    async.filter = doParallel(_filter);
-    async.filterSeries = doSeries(_filter);
-    // select alias
-    async.select = async.filter;
-    async.selectSeries = async.filterSeries;
-
-    var _reject = function (eachfn, arr, iterator, callback) {
-        var results = [];
-        arr = _map(arr, function (x, i) {
-            return {index: i, value: x};
-        });
-        eachfn(arr, function (x, callback) {
-            iterator(x.value, function (v) {
-                if (!v) {
-                    results.push(x);
-                }
-                callback();
-            });
-        }, function (err) {
-            callback(_map(results.sort(function (a, b) {
-                return a.index - b.index;
-            }), function (x) {
-                return x.value;
-            }));
-        });
-    };
-    async.reject = doParallel(_reject);
-    async.rejectSeries = doSeries(_reject);
-
-    var _detect = function (eachfn, arr, iterator, main_callback) {
-        eachfn(arr, function (x, callback) {
-            iterator(x, function (result) {
-                if (result) {
-                    main_callback(x);
-                    main_callback = function () {};
-                }
-                else {
-                    callback();
-                }
-            });
-        }, function (err) {
-            main_callback();
-        });
-    };
-    async.detect = doParallel(_detect);
-    async.detectSeries = doSeries(_detect);
-
-    async.some = function (arr, iterator, main_callback) {
-        async.each(arr, function (x, callback) {
-            iterator(x, function (v) {
-                if (v) {
-                    main_callback(true);
-                    main_callback = function () {};
-                }
-                callback();
-            });
-        }, function (err) {
-            main_callback(false);
-        });
-    };
-    // any alias
-    async.any = async.some;
-
-    async.every = function (arr, iterator, main_callback) {
-        async.each(arr, function (x, callback) {
-            iterator(x, function (v) {
-                if (!v) {
-                    main_callback(false);
-                    main_callback = function () {};
-                }
-                callback();
-            });
-        }, function (err) {
-            main_callback(true);
-        });
-    };
-    // all alias
-    async.all = async.every;
-
-    async.sortBy = function (arr, iterator, callback) {
-        async.map(arr, function (x, callback) {
-            iterator(x, function (err, criteria) {
-                if (err) {
-                    callback(err);
-                }
-                else {
-                    callback(null, {value: x, criteria: criteria});
-                }
-            });
-        }, function (err, results) {
-            if (err) {
-                return callback(err);
-            }
-            else {
-                var fn = function (left, right) {
-                    var a = left.criteria, b = right.criteria;
-                    return a < b ? -1 : a > b ? 1 : 0;
-                };
-                callback(null, _map(results.sort(fn), function (x) {
-                    return x.value;
-                }));
-            }
-        });
-    };
-
-    async.auto = function (tasks, callback) {
-        callback = callback || function () {};
-        var keys = _keys(tasks);
-        var remainingTasks = keys.length
-        if (!remainingTasks) {
-            return callback();
-        }
-
-        var results = {};
-
-        var listeners = [];
-        var addListener = function (fn) {
-            listeners.unshift(fn);
-        };
-        var removeListener = function (fn) {
-            for (var i = 0; i < listeners.length; i += 1) {
-                if (listeners[i] === fn) {
-                    listeners.splice(i, 1);
-                    return;
-                }
-            }
-        };
-        var taskComplete = function () {
-            remainingTasks--
-            _each(listeners.slice(0), function (fn) {
-                fn();
-            });
-        };
-
-        addListener(function () {
-            if (!remainingTasks) {
-                var theCallback = callback;
-                // prevent final callback from calling itself if it errors
-                callback = function () {};
-
-                theCallback(null, results);
-            }
-        });
-
-        _each(keys, function (k) {
-            var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
-            var taskCallback = function (err) {
-                var args = Array.prototype.slice.call(arguments, 1);
-                if (args.length <= 1) {
-                    args = args[0];
-                }
-                if (err) {
-                    var safeResults = {};
-                    _each(_keys(results), function(rkey) {
-                        safeResults[rkey] = results[rkey];
-                    });
-                    safeResults[k] = args;
-                    callback(err, safeResults);
-                    // stop subsequent errors hitting callback multiple times
-                    callback = function () {};
-                }
-                else {
-                    results[k] = args;
-                    async.setImmediate(taskComplete);
-                }
-            };
-            var requires = task.slice(0, Math.abs(task.length - 1)) || [];
-            var ready = function () {
-                return _reduce(requires, function (a, x) {
-                    return (a && results.hasOwnProperty(x));
-                }, true) && !results.hasOwnProperty(k);
-            };
-            if (ready()) {
-                task[task.length - 1](taskCallback, results);
-            }
-            else {
-                var listener = function () {
-                    if (ready()) {
-                        removeListener(listener);
-                        task[task.length - 1](taskCallback, results);
-                    }
-                };
-                addListener(listener);
-            }
-        });
-    };
-
-    async.retry = function(times, task, callback) {
-        var DEFAULT_TIMES = 5;
-        var attempts = [];
-        // Use defaults if times not passed
-        if (typeof times === 'function') {
-            callback = task;
-            task = times;
-            times = DEFAULT_TIMES;
-        }
-        // Make sure times is a number
-        times = parseInt(times, 10) || DEFAULT_TIMES;
-        var wrappedTask = function(wrappedCallback, wrappedResults) {
-            var retryAttempt = function(task, finalAttempt) {
-                return function(seriesCallback) {
-                    task(function(err, result){
-                        seriesCallback(!err || finalAttempt, {err: err, result: result});
-                    }, wrappedResults);
-                };
-            };
-            while (times) {
-                attempts.push(retryAttempt(task, !(times-=1)));
-            }
-            async.series(attempts, function(done, data){
-                data = data[data.length - 1];
-                (wrappedCallback || callback)(data.err, data.result);
-            });
-        }
-        // If a callback is passed, run this as a controll flow
-        return callback ? wrappedTask() : wrappedTask
-    };
-
-    async.waterfall = function (tasks, callback) {
-        callback = callback || function () {};
-        if (!_isArray(tasks)) {
-          var err = new Error('First argument to waterfall must be an array of functions');
-          return callback(err);
-        }
-        if (!tasks.length) {
-            return callback();
-        }
-        var wrapIterator = function (iterator) {
-            return function (err) {
-                if (err) {
-                    callback.apply(null, arguments);
-                    callback = function () {};
-                }
-                else {
-                    var args = Array.prototype.slice.call(arguments, 1);
-                    var next = iterator.next();
-                    if (next) {
-                        args.push(wrapIterator(next));
-                    }
-                    else {
-                        args.push(callback);
-                    }
-                    async.setImmediate(function () {
-                        iterator.apply(null, args);
-                    });
-                }
-            };
-        };
-        wrapIterator(async.iterator(tasks))();
-    };
-
-    var _parallel = function(eachfn, tasks, callback) {
-        callback = callback || function () {};
-        if (_isArray(tasks)) {
-            eachfn.map(tasks, function (fn, callback) {
-                if (fn) {
-                    fn(function (err) {
-                        var args = Array.prototype.slice.call(arguments, 1);
-                        if (args.length <= 1) {
-                            args = args[0];
-                        }
-                        callback.call(null, err, args);
-                    });
-                }
-            }, callback);
-        }
-        else {
-            var results = {};
-            eachfn.each(_keys(tasks), function (k, callback) {
-                tasks[k](function (err) {
-                    var args = Array.prototype.slice.call(arguments, 1);
-                    if (args.length <= 1) {
-                        args = args[0];
-                    }
-                    results[k] = args;
-                    callback(err);
-                });
-            }, function (err) {
-                callback(err, results);
-            });
-        }
-    };
-
-    async.parallel = function (tasks, callback) {
-        _parallel({ map: async.map, each: async.each }, tasks, callback);
-    };
-
-    async.parallelLimit = function(tasks, limit, callback) {
-        _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
-    };
-
-    async.series = function (tasks, callback) {
-        callback = callback || function () {};
-        if (_isArray(tasks)) {
-            async.mapSeries(tasks, function (fn, callback) {
-                if (fn) {
-                    fn(function (err) {
-                        var args = Array.prototype.slice.call(arguments, 1);
-                        if (args.length <= 1) {
-                            args = args[0];
-                        }
-                        callback.call(null, err, args);
-                    });
-                }
-            }, callback);
-        }
-        else {
-            var results = {};
-            async.eachSeries(_keys(tasks), function (k, callback) {
-                tasks[k](function (err) {
-                    var args = Array.prototype.slice.call(arguments, 1);
-                    if (args.length <= 1) {
-                        args = args[0];
-                    }
-                    results[k] = args;
-                    callback(err);
-                });
-            }, function (err) {
-                callback(err, results);
-            });
-        }
-    };
-
-    async.iterator = function (tasks) {
-        var makeCallback = function (index) {
-            var fn = function () {
-                if (tasks.length) {
-                    tasks[index].apply(null, arguments);
-                }
-                return fn.next();
-            };
-            fn.next = function () {
-                return (index < tasks.length - 1) ? makeCallback(index + 1): null;
-            };
-            return fn;
-        };
-        return makeCallback(0);
-    };
-
-    async.apply = function (fn) {
-        var args = Array.prototype.slice.call(arguments, 1);
-        return function () {
-            return fn.apply(
-                null, args.concat(Array.prototype.slice.call(arguments))
-            );
-        };
-    };
-
-    var _concat = function (eachfn, arr, fn, callback) {
-        var r = [];
-        eachfn(arr, function (x, cb) {
-            fn(x, function (err, y) {
-                r = r.concat(y || []);
-                cb(err);
-            });
-        }, function (err) {
-            callback(err, r);
-        });
-    };
-    async.concat = doParallel(_concat);
-    async.concatSeries = doSeries(_concat);
-
-    async.whilst = function (test, iterator, callback) {
-        if (test()) {
-            iterator(function (err) {
-                if (err) {
-                    return callback(err);
-                }
-                async.whilst(test, iterator, callback);
-            });
-        }
-        else {
-            callback();
-        }
-    };
-
-    async.doWhilst = function (iterator, test, callback) {
-        iterator(function (err) {
-            if (err) {
-                return callback(err);
-            }
-            var args = Array.prototype.slice.call(arguments, 1);
-            if (test.apply(null, args)) {
-                async.doWhilst(iterator, test, callback);
-            }
-            else {
-                callback();
-            }
-        });
-    };
-
-    async.until = function (test, iterator, callback) {
-        if (!test()) {
-            iterator(function (err) {
-                if (err) {
-                    return callback(err);
-                }
-                async.until(test, iterator, callback);
-            });
-        }
-        else {
-            callback();
-        }
-    };
-
-    async.doUntil = function (iterator, test, callback) {
-        iterator(function (err) {
-            if (err) {
-                return callback(err);
-            }
-            var args = Array.prototype.slice.call(arguments, 1);
-            if (!test.apply(null, args)) {
-                async.doUntil(iterator, test, callback);
-            }
-            else {
-                callback();
-            }
-        });
-    };
-
-    async.queue = function (worker, concurrency) {
-        if (concurrency === undefined) {
-            concurrency = 1;
-        }
-        function _insert(q, data, pos, callback) {
-          if (!q.started){
-            q.started = true;
-          }
-          if (!_isArray(data)) {
-              data = [data];
-          }
-          if(data.length == 0) {
-             // call drain immediately if there are no tasks
-             return async.setImmediate(function() {
-                 if (q.drain) {
-                     q.drain();
-                 }
-             });
-          }
-          _each(data, function(task) {
-              var item = {
-                  data: task,
-                  callback: typeof callback === 'function' ? callback : null
-              };
-
-              if (pos) {
-                q.tasks.unshift(item);
-              } else {
-                q.tasks.push(item);
-              }
-
-              if (q.saturated && q.tasks.length === q.concurrency) {
-                  q.saturated();
-              }
-              async.setImmediate(q.process);
-          });
-        }
-
-        var workers = 0;
-        var q = {
-            tasks: [],
-            concurrency: concurrency,
-            saturated: null,
-            empty: null,
-            drain: null,
-            started: false,
-            paused: false,
-            push: function (data, callback) {
-              _insert(q, data, false, callback);
-            },
-            kill: function () {
-              q.drain = null;
-              q.tasks = [];
-            },
-            unshift: function (data, callback) {
-              _insert(q, data, true, callback);
-            },
-            process: function () {
-                if (!q.paused && workers < q.concurrency && q.tasks.length) {
-                    var task = q.tasks.shift();
-                    if (q.empty && q.tasks.length === 0) {
-                        q.empty();
-                    }
-                    workers += 1;
-                    var next = function () {
-                        workers -= 1;
-                        if (task.callback) {
-                            task.callback.apply(task, arguments);
-                        }
-                        if (q.drain && q.tasks.length + workers === 0) {
-                            q.drain();
-                        }
-                        q.process();
-                    };
-                    var cb = only_once(next);
-                    worker(task.data, cb);
-                }
-            },
-            length: function () {
-                return q.tasks.length;
-            },
-            running: function () {
-                return workers;
-            },
-            idle: function() {
-                return q.tasks.length + workers === 0;
-            },
-            pause: function () {
-                if (q.paused === true) { return; }
-                q.paused = true;
-            },
-            resume: function () {
-                if (q.paused === false) { return; }
-                q.paused = false;
-                // Need to call q.process once per concurrent
-                // worker to preserve full concurrency after pause
-                for (var w = 1; w <= q.concurrency; w++) {
-                    async.setImmediate(q.process);
-                }
-            }
-        };
-        return q;
-    };
-
-    async.priorityQueue = function (worker, concurrency) {
-
-        function _compareTasks(a, b){
-          return a.priority - b.priority;
-        };
-
-        function _binarySearch(sequence, item, compare) {
-          var beg = -1,
-              end = sequence.length - 1;
-          while (beg < end) {
-            var mid = beg + ((end - beg + 1) >>> 1);
-            if (compare(item, sequence[mid]) >= 0) {
-              beg = mid;
-            } else {
-              end = mid - 1;
-            }
-          }
-          return beg;
-        }
-
-        function _insert(q, data, priority, callback) {
-          if (!q.started){
-            q.started = true;
-          }
-          if (!_isArray(data)) {
-              data = [data];
-          }
-          if(data.length == 0) {
-             // call drain immediately if there are no tasks
-             return async.setImmediate(function() {
-                 if (q.drain) {
-                     q.drain();
-                 }
-             });
-          }
-          _each(data, function(task) {
-              var item = {
-                  data: task,
-                  priority: priority,
-                  callback: typeof callback === 'function' ? callback : null
-              };
-
-              q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
-
-              if (q.saturated && q.tasks.length === q.concurrency) {
-                  q.saturated();
-              }
-              async.setImmediate(q.process);
-          });
-        }
-
-        // Start with a normal queue
-        var q = async.queue(worker, concurrency);
-
-        // Override push to accept second parameter representing priority
-        q.push = function (data, priority, callback) {
-          _insert(q, data, priority, callback);
-        };
-
-        // Remove unshift function
-        delete q.unshift;
-
-        return q;
-    };
-
-    async.cargo = function (worker, payload) {
-        var working     = false,
-            tasks       = [];
-
-        var cargo = {
-            tasks: tasks,
-            payload: payload,
-            saturated: null,
-            empty: null,
-            drain: null,
-            drained: true,
-            push: function (data, callback) {
-                if (!_isArray(data)) {
-                    data = [data];
-                }
-                _each(data, function(task) {
-                    tasks.push({
-                        data: task,
-                        callback: typeof callback === 'function' ? callback : null
-                    });
-                    cargo.drained = false;
-                    if (cargo.saturated && tasks.length === payload) {
-                        cargo.saturated();
-                    }
-                });
-                async.setImmediate(cargo.process);
-            },
-            process: function process() {
-                if (working) return;
-                if (tasks.length === 0) {
-                    if(cargo.drain && !cargo.drained) cargo.drain();
-                    cargo.drained = true;
-                    return;
-                }
-
-                var ts = typeof payload === 'number'
-                            ? tasks.splice(0, payload)
-                            : tasks.splice(0, tasks.length);
-
-                var ds = _map(ts, function (task) {
-                    return task.data;
-                });
-
-                if(cargo.empty) cargo.empty();
-                working = true;
-                worker(ds, function () {
-                    working = false;
-
-                    var args = arguments;
-                    _each(ts, function (data) {
-                        if (data.callback) {
-                            data.callback.apply(null, args);
-                        }
-                    });
-
-                    process();
-                });
-            },
-            length: function () {
-                return tasks.length;
-            },
-            running: function () {
-                return working;
-            }
-        };
-        return cargo;
-    };
-
-    var _console_fn = function (name) {
-        return function (fn) {
-            var args = Array.prototype.slice.call(arguments, 1);
-            fn.apply(null, args.concat([function (err) {
-                var args = Array.prototype.slice.call(arguments, 1);
-                if (typeof console !== 'undefined') {
-                    if (err) {
-                        if (console.error) {
-                            console.error(err);
-                        }
-                    }
-                    else if (console[name]) {
-                        _each(args, function (x) {
-                            console[name](x);
-                        });
-                    }
-                }
-            }]));
-        };
-    };
-    async.log = _console_fn('log');
-    async.dir = _console_fn('dir');
-    /*async.info = _console_fn('info');
-    async.warn = _console_fn('warn');
-    async.error = _console_fn('error');*/
-
-    async.memoize = function (fn, hasher) {
-        var memo = {};
-        var queues = {};
-        hasher = hasher || function (x) {
-            return x;
-        };
-        var memoized = function () {
-            var args = Array.prototype.slice.call(arguments);
-            var callback = args.pop();
-            var key = hasher.apply(null, args);
-            if (key in memo) {
-                async.nextTick(function () {
-                    callback.apply(null, memo[key]);
-                });
-            }
-            else if (key in queues) {
-                queues[key].push(callback);
-            }
-            else {
-                queues[key] = [callback];
-                fn.apply(null, args.concat([function () {
-                    memo[key] = arguments;
-                    var q = queues[key];
-                    delete queues[key];
-                    for (var i = 0, l = q.length; i < l; i++) {
-                      q[i].apply(null, arguments);
-                    }
-                }]));
-            }
-        };
-        memoized.memo = memo;
-        memoized.unmemoized = fn;
-        return memoized;
-    };
-
-    async.unmemoize = function (fn) {
-      return function () {
-        return (fn.unmemoized || fn).apply(null, arguments);
-      };
-    };
-
-    async.times = function (count, iterator, callback) {
-        var counter = [];
-        for (var i = 0; i < count; i++) {
-            counter.push(i);
-        }
-        return async.map(counter, iterator, callback);
-    };
-
-    async.timesSeries = function (count, iterator, callback) {
-        var counter = [];
-        for (var i = 0; i < count; i++) {
-            counter.push(i);
-        }
-        return async.mapSeries(counter, iterator, callback);
-    };
-
-    async.seq = function (/* functions... */) {
-        var fns = arguments;
-        return function () {
-            var that = this;
-            var args = Array.prototype.slice.call(arguments);
-            var callback = args.pop();
-            async.reduce(fns, args, function (newargs, fn, cb) {
-                fn.apply(that, newargs.concat([function () {
-                    var err = arguments[0];
-                    var nextargs = Array.prototype.slice.call(arguments, 1);
-                    cb(err, nextargs);
-                }]))
-            },
-            function (err, results) {
-                callback.apply(that, [err].concat(results));
-            });
-        };
-    };
-
-    async.compose = function (/* functions... */) {
-      return async.seq.apply(null, Array.prototype.reverse.call(arguments));
-    };
-
-    var _applyEach = function (eachfn, fns /*args...*/) {
-        var go = function () {
-            var that = this;
-            var args = Array.prototype.slice.call(arguments);
-            var callback = args.pop();
-            return eachfn(fns, function (fn, cb) {
-                fn.apply(that, args.concat([cb]));
-            },
-            callback);
-        };
-        if (arguments.length > 2) {
-            var args = Array.prototype.slice.call(arguments, 2);
-            return go.apply(this, args);
-        }
-        else {
-            return go;
-        }
-    };
-    async.applyEach = doParallel(_applyEach);
-    async.applyEachSeries = doSeries(_applyEach);
-
-    async.forever = function (fn, callback) {
-        function next(err) {
-            if (err) {
-                if (callback) {
-                    return callback(err);
-                }
-                throw err;
-            }
-            fn(next);
-        }
-        next();
-    };
-
-    // Node.js
-    if (typeof module !== 'undefined' && module.exports) {
-        module.exports = async;
-    }
-    // AMD / RequireJS
-    else if (typeof define !== 'undefined' && define.amd) {
-        define([], function () {
-            return async;
-        });
-    }
-    // included directly via <script> tag
-    else {
-        root.async = async;
-    }
-
-}());
+!function(){var n,t,e={};function r(t){var e=!1;return function(){if(e)throw new Error("Callback was already called.");e=!0,t.apply(n,arguments)}}null!=(n=this)&&(t=n.async),e.noConflict=function(){return n.async=t,e};var i=Object.prototype.toString,u=Array.isArray||function(n){return"[object Array]"===i.call(n)},c=function(n,t){for(var e=0;e<n.length;e+=1)t(n[e],e,n)},o=function(n,t){if(n.map)return n.map(t);var e=[];return c(n,(function(n,r,i){e.push(t(n,r,i))})),e},a=function(n){if(Object.keys)return Object.keys(n);var t=[];for(var e in n)n.hasOwnProperty(e)&&t.push(e);return t};"undefined"!=typeof process&&process.nextTick?(e.nextTick=process.nextTick,"undefined"!=typeof setImmediate?e.setImmediate=function(n){setImmediate(n)}:e.setImmediate=e.nextTick):"function"==typeof setImmediate?(e.nextTick=function(n){setImmediate(n)},e.setImmediate=e.nextTick):(e.nextTick=function(n){setTimeout(n,0)},e.setImmediate=e.nextTick),e.each=function(n,t,e){if(e=e||function(){},!n.length)return e();var i=0;function u(t){t?(e(t),e=function(){}):(i+=1)>=n.length&&e()}c(n,(function(n){t(n,r(u))}))},e.forEach=e.each,e.eachSeries=function(n,t,e){if(e=e||function(){},!n.length)return e();var r=0,i=function(){t(n[r],(function(t){t?(e(t),e=function(){}):(r+=1)>=n.length?e():i()}))};i()},e.forEachSeries=e.eachSeries,e.eachLimit=function(n,t,e,r){l(t).apply(null,[n,e,r])},e.forEachLimit=e.eachLimit;var l=function(n){return function(t,e,r){if(r=r||function(){},!t.length||n<=0)return r();var i=0,u=0,c=0;!function o(){if(i>=t.length)return r();for(;c<n&&u<t.length;)c+=1,e(t[(u+=1)-1],(function(n){n?(r(n),r=function(){}):(c-=1,(i+=1)>=t.length?r():o())}))}()}},f=function(n){return function(){var t=Array.prototype.slice.call(arguments);return n.apply(null,[e.each].concat(t))}},s=function(n){return function(){var t=Array.prototype.slice.call(arguments);return n.apply(null,[e.eachSeries].concat(t))}},p=function(n,t,e,r){if(t=o(t,(function(n,t){return{index:t,value:n}})),r){var i=[];n(t,(function(n,t){e(n.value,(function(e,r){i[n.index]=r,t(e)}))}),(function(n){r(n,i)}))}else n(t,(function(n,t){e(n.value,(function(n){t(n)}))}))};e.map=f(p),e.mapSeries=s(p),e.mapLimit=function(n,t,e,r){return y(t)(n,e,r)};var y=function(n){return function(n,t){return function(){var e=Array.prototype.slice.call(arguments);return t.apply(null,[l(n)].concat(e))}}(n,p)};e.reduce=function(n,t,r,i){e.eachSeries(n,(function(n,e){r(t,n,(function(n,r){t=r,e(n)}))}),(function(n){i(n,t)}))},e.inject=e.reduce,e.foldl=e.reduce,e.reduceRight=function(n,t,r,i){var u=o(n,(function(n){return n})).reverse();e.reduce(u,t,r,i)},e.foldr=e.reduceRight;var d=function(n,t,e,r){var i=[];n(t=o(t,(function(n,t){return{index:t,value:n}})),(function(n,t){e(n.value,(function(e){e&&i.push(n),t()}))}),(function(n){r(o(i.sort((function(n,t){return n.index-t.index})),(function(n){return n.value})))}))};e.filter=f(d),e.filterSeries=s(d),e.select=e.filter,e.selectSeries=e.filterSeries;var v=function(n,t,e,r){var i=[];n(t=o(t,(function(n,t){return{index:t,value:n}})),(function(n,t){e(n.value,(function(e){e||i.push(n),t()}))}),(function(n){r(o(i.sort((function(n,t){return n.index-t.index})),(function(n){return n.value})))}))};e.reject=f(v),e.rejectSeries=s(v);var h=function(n,t,e,r){n(t,(function(n,t){e(n,(function(e){e?(r(n),r=function(){}):t()}))}),(function(n){r()}))};e.detect=f(h),e.detectSeries=s(h),e.some=function(n,t,r){e.each(n,(function(n,e){t(n,(function(n){n&&(r(!0),r=function(){}),e()}))}),(function(n){r(!1)}))},e.any=e.some,e.every=function(n,t,r){e.each(n,(function(n,e){t(n,(function(n){n||(r(!1),r=function(){}),e()}))}),(function(n){r(!0)}))},e.all=e.every,e.sortBy=function(n,t,r){e.map(n,(function(n,e){t(n,(function(t,r){t?e(t):e(null,{value:n,criteria:r})}))}),(function(n,t){if(n)return r(n);r(null,o(t.sort((function(n,t){var e=n.criteria,r=t.criteria;return e<r?-1:e>r?1:0})),(function(n){return n.value})))}))},e.auto=function(n,t){t=t||function(){};var r=a(n),i=r.length;if(!i)return t();var o={},l=[],f=function(n){l.unshift(n)},s=function(){i--,c(l.slice(0),(function(n){n()}))};f((function(){if(!i){var n=t;t=function(){},n(null,o)}})),c(r,(function(r){var i=u(n[r])?n[r]:[n[r]],p=function(n){var i=Array.prototype.slice.call(arguments,1);if(i.length<=1&&(i=i[0]),n){var u={};c(a(o),(function(n){u[n]=o[n]})),u[r]=i,t(n,u),t=function(){}}else o[r]=i,e.setImmediate(s)},y=i.slice(0,Math.abs(i.length-1))||[],d=function(){return t=function(n,t){return n&&o.hasOwnProperty(t)},e=!0,((n=y).reduce?n.reduce(t,e):(c(n,(function(n,r,i){e=t(e,n,r,i)})),e))&&!o.hasOwnProperty(r);var n,t,e};if(d())i[i.length-1](p,o);else{var v=function(){d()&&(!function(n){for(var t=0;t<l.length;t+=1)if(l[t]===n)return void l.splice(t,1)}(v),i[i.length-1](p,o))};f(v)}}))},e.retry=function(n,t,r){var i=[];"function"==typeof n&&(r=t,t=n,n=5),n=parseInt(n,10)||5;var u=function(u,c){for(var o=function(n,t){return function(e){n((function(n,r){e(!n||t,{err:n,result:r})}),c)}};n;)i.push(o(t,!(n-=1)));e.series(i,(function(n,t){t=t[t.length-1],(u||r)(t.err,t.result)}))};return r?u():u},e.waterfall=function(n,t){if(t=t||function(){},!u(n)){var r=new Error("First argument to waterfall must be an array of functions");return t(r)}if(!n.length)return t();var i=function(n){return function(r){if(r)t.apply(null,arguments),t=function(){};else{var u=Array.prototype.slice.call(arguments,1),c=n.next();c?u.push(i(c)):u.push(t),e.setImmediate((function(){n.apply(null,u)}))}}};i(e.iterator(n))()};var m=function(n,t,e){if(e=e||function(){},u(t))n.map(t,(function(n,t){n&&n((function(n){var e=Array.prototype.slice.call(arguments,1);e.length<=1&&(e=e[0]),t.call(null,n,e)}))}),e);else{var r={};n.each(a(t),(function(n,e){t[n]((function(t){var i=Array.prototype.slice.call(arguments,1);i.length<=1&&(i=i[0]),r[n]=i,e(t)}))}),(function(n){e(n,r)}))}};e.parallel=function(n,t){m({map:e.map,each:e.each},n,t)},e.parallelLimit=function(n,t,e){m({map:y(t),each:l(t)},n,e)},e.series=function(n,t){if(t=t||function(){},u(n))e.mapSeries(n,(function(n,t){n&&n((function(n){var e=Array.prototype.slice.call(arguments,1);e.length<=1&&(e=e[0]),t.call(null,n,e)}))}),t);else{var r={};e.eachSeries(a(n),(function(t,e){n[t]((function(n){var i=Array.prototype.slice.call(arguments,1);i.length<=1&&(i=i[0]),r[t]=i,e(n)}))}),(function(n){t(n,r)}))}},e.iterator=function(n){var t=function(e){var r=function(){return n.length&&n[e].apply(null,arguments),r.next()};return r.next=function(){return e<n.length-1?t(e+1):null},r};return t(0)},e.apply=function(n){var t=Array.prototype.slice.call(arguments,1);return function(){return n.apply(null,t.concat(Array.prototype.slice.call(arguments)))}};var g=function(n,t,e,r){var i=[];n(t,(function(n,t){e(n,(function(n,e){i=i.concat(e||[]),t(n)}))}),(function(n){r(n,i)}))};e.concat=f(g),e.concatSeries=s(g),e.whilst=function(n,t,r){n()?t((function(i){if(i)return r(i);e.whilst(n,t,r)})):r()},e.doWhilst=function(n,t,r){n((function(i){if(i)return r(i);var u=Array.prototype.slice.call(arguments,1);t.apply(null,u)?e.doWhilst(n,t,r):r()}))},e.until=function(n,t,r){n()?r():t((function(i){if(i)return r(i);e.until(n,t,r)}))},e.doUntil=function(n,t,r){n((function(i){if(i)return r(i);var u=Array.prototype.slice.call(arguments,1);t.apply(null,u)?r():e.doUntil(n,t,r)}))},e.queue=function(n,t){function i(n,t,r,i){if(n.started||(n.started=!0),u(t)||(t=[t]),0==t.length)return e.setImmediate((function(){n.drain&&n.drain()}));c(t,(function(t){var u={data:t,callback:"function"==typeof i?i:null};r?n.tasks.unshift(u):n.tasks.push(u),n.saturated&&n.tasks.length===n.concurrency&&n.saturated(),e.setImmediate(n.process)}))}void 0===t&&(t=1);var o=0,a={tasks:[],concurrency:t,saturated:null,empty:null,drain:null,started:!1,paused:!1,push:function(n,t){i(a,n,!1,t)},kill:function(){a.drain=null,a.tasks=[]},unshift:function(n,t){i(a,n,!0,t)},process:function(){if(!a.paused&&o<a.concurrency&&a.tasks.length){var t=a.tasks.shift();a.empty&&0===a.tasks.length&&a.empty(),o+=1;var e=r((function(){o-=1,t.callback&&t.callback.apply(t,arguments),a.drain&&a.tasks.length+o===0&&a.drain(),a.process()}));n(t.data,e)}},length:function(){return a.tasks.length},running:function(){return o},idle:function(){return a.tasks.length+o===0},pause:function(){!0!==a.paused&&(a.paused=!0)},resume:function(){if(!1!==a.paused){a.paused=!1;for(var n=1;n<=a.concurrency;n++)e.setImmediate(a.process)}}};return a},e.priorityQueue=function(n,t){function r(n,t){return n.priority-t.priority}var i=e.queue(n,t);return i.push=function(n,t,o){!function(n,t,i,o){if(n.started||(n.started=!0),u(t)||(t=[t]),0==t.length)return e.setImmediate((function(){n.drain&&n.drain()}));c(t,(function(t){var u={data:t,priority:i,callback:"function"==typeof o?o:null};n.tasks.splice(function(n,t,e){for(var r=-1,i=n.length-1;r<i;){var u=r+(i-r+1>>>1);e(t,n[u])>=0?r=u:i=u-1}return r}(n.tasks,u,r)+1,0,u),n.saturated&&n.tasks.length===n.concurrency&&n.saturated(),e.setImmediate(n.process)}))}(i,n,t,o)},delete i.unshift,i},e.cargo=function(n,t){var r=!1,i=[],a={tasks:i,payload:t,saturated:null,empty:null,drain:null,drained:!0,push:function(n,r){u(n)||(n=[n]),c(n,(function(n){i.push({data:n,callback:"function"==typeof r?r:null}),a.drained=!1,a.saturated&&i.length===t&&a.saturated()})),e.setImmediate(a.process)},process:function e(){if(!r){if(0===i.length)return a.drain&&!a.drained&&a.drain(),void(a.drained=!0);var u="number"==typeof t?i.splice(0,t):i.splice(0,i.length),l=o(u,(function(n){return n.data}));a.empty&&a.empty(),r=!0,n(l,(function(){r=!1;var n=arguments;c(u,(function(t){t.callback&&t.callback.apply(null,n)})),e()}))}},length:function(){return i.length},running:function(){return r}};return a};var k=function(n){return function(t){var e=Array.prototype.slice.call(arguments,1);t.apply(null,e.concat([function(t){var e=Array.prototype.slice.call(arguments,1);"undefined"!=typeof console&&(t?console.error&&console.error(t):console[n]&&c(e,(function(t){console[n](t)})))}]))}};e.log=k("log"),e.dir=k("dir"),e.memoize=function(n,t){var r={},i={};t=t||function(n){return n};var u=function(){var u=Array.prototype.slice.call(arguments),c=u.pop(),o=t.apply(null,u);o in r?e.nextTick((function(){c.apply(null,r[o])})):o in i?i[o].push(c):(i[o]=[c],n.apply(null,u.concat([function(){r[o]=arguments;var n=i[o];delete i[o];for(var t=0,e=n.length;t<e;t++)n[t].apply(null,arguments)}])))};return u.memo=r,u.unmemoized=n,u},e.unmemoize=function(n){return function(){return(n.unmemoized||n).apply(null,arguments)}},e.times=function(n,t,r){for(var i=[],u=0;u<n;u++)i.push(u);return e.map(i,t,r)},e.timesSeries=function(n,t,r){for(var i=[],u=0;u<n;u++)i.push(u);return e.mapSeries(i,t,r)},e.seq=function(){var n=arguments;return function(){var t=this,r=Array.prototype.slice.call(arguments),i=r.pop();e.reduce(n,r,(function(n,e,r){e.apply(t,n.concat([function(){var n=arguments[0],t=Array.prototype.slice.call(arguments,1);r(n,t)}]))}),(function(n,e){i.apply(t,[n].concat(e))}))}},e.compose=function(){return e.seq.apply(null,Array.prototype.reverse.call(arguments))};var A=function(n,t){var e=function(){var e=this,r=Array.prototype.slice.call(arguments),i=r.pop();return n(t,(function(n,t){n.apply(e,r.concat([t]))}),i)};if(arguments.length>2){var r=Array.prototype.slice.call(arguments,2);return e.apply(this,r)}return e};e.applyEach=f(A),e.applyEachSeries=s(A),e.forever=function(n,t){!function e(r){if(r){if(t)return t(r);throw r}n(e)}()},"undefined"!=typeof module&&module.exports?module.exports=e:"undefined"!=typeof define&&define.amd?define([],(function(){return e})):n.async=e}();
\ No newline at end of file
index 30cb7c2..864d970 100755 (executable)
@@ -1,53 +1,2 @@
 #!/usr/bin/env node
-
-// This should probably be its own module but complaints about bower/etc.
-// support keep coming up and I'd rather just enable the workflow here for now
-// and figure out where this should live later. -- @beaugunderson
-
-var fs = require('fs');
-var _ = require('lodash');
-
-var packageJson = require('../package.json');
-
-var IGNORES = ['**/.*', 'node_modules', 'bower_components', 'test', 'tests'];
-var INCLUDES = ['lib/async.js', 'README.md', 'LICENSE'];
-var REPOSITORY_NAME = 'caolan/async';
-
-packageJson.jam = {
-  main: packageJson.main,
-  include: INCLUDES,
-  categories: ['Utilities']
-};
-
-packageJson.spm = {
-  main: packageJson.main
-};
-
-packageJson.volo = {
-  main: packageJson.main,
-  ignore: IGNORES
-};
-
-var bowerSpecific = {
-  moduleType: ['amd', 'globals', 'node'],
-  ignore: IGNORES,
-  authors: [packageJson.author]
-};
-
-var bowerInclude = ['name', 'description', 'version', 'main', 'keywords',
-  'license', 'homepage', 'repository', 'devDependencies'];
-
-var componentSpecific = {
-  repository: REPOSITORY_NAME,
-  scripts: [packageJson.main]
-};
-
-var componentInclude = ['name', 'description', 'version', 'keywords',
-  'license'];
-
-var bowerJson = _.merge({}, _.pick(packageJson, bowerInclude), bowerSpecific);
-var componentJson = _.merge({}, _.pick(packageJson, componentInclude), componentSpecific);
-
-fs.writeFileSync('./bower.json', JSON.stringify(bowerJson, null, 2));
-fs.writeFileSync('./component.json', JSON.stringify(componentJson, null, 2));
-fs.writeFileSync('./package.json', JSON.stringify(packageJson, null, 2));
+var fs=require("fs"),_=require("lodash"),packageJson=require("../package.json"),IGNORES=["**/.*","node_modules","bower_components","test","tests"],INCLUDES=["lib/async.js","README.md","LICENSE"],REPOSITORY_NAME="caolan/async";packageJson.jam={main:packageJson.main,include:INCLUDES,categories:["Utilities"]},packageJson.spm={main:packageJson.main},packageJson.volo={main:packageJson.main,ignore:IGNORES};var bowerSpecific={moduleType:["amd","globals","node"],ignore:IGNORES,authors:[packageJson.author]},bowerInclude=["name","description","version","main","keywords","license","homepage","repository","devDependencies"],componentSpecific={repository:REPOSITORY_NAME,scripts:[packageJson.main]},componentInclude=["name","description","version","keywords","license"],bowerJson=_.merge({},_.pick(packageJson,bowerInclude),bowerSpecific),componentJson=_.merge({},_.pick(packageJson,componentInclude),componentSpecific);fs.writeFileSync("./bower.json",JSON.stringify(bowerJson,null,2)),fs.writeFileSync("./component.json",JSON.stringify(componentJson,null,2)),fs.writeFileSync("./package.json",JSON.stringify(packageJson,null,2));
\ No newline at end of file
index fac4429..19d92fe 100644 (file)
@@ -1,85 +1 @@
-
-/**
- * Expose `Backoff`.
- */
-
-module.exports = Backoff;
-
-/**
- * Initialize backoff timer with `opts`.
- *
- * - `min` initial timeout in milliseconds [100]
- * - `max` max timeout [10000]
- * - `jitter` [0]
- * - `factor` [2]
- *
- * @param {Object} opts
- * @api public
- */
-
-function Backoff(opts) {
-  opts = opts || {};
-  this.ms = opts.min || 100;
-  this.max = opts.max || 10000;
-  this.factor = opts.factor || 2;
-  this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
-  this.attempts = 0;
-}
-
-/**
- * Return the backoff duration.
- *
- * @return {Number}
- * @api public
- */
-
-Backoff.prototype.duration = function(){
-  var ms = this.ms * Math.pow(this.factor, this.attempts++);
-  if (this.jitter) {
-    var rand =  Math.random();
-    var deviation = Math.floor(rand * this.jitter * ms);
-    ms = (Math.floor(rand * 10) & 1) == 0  ? ms - deviation : ms + deviation;
-  }
-  return Math.min(ms, this.max) | 0;
-};
-
-/**
- * Reset the number of attempts.
- *
- * @api public
- */
-
-Backoff.prototype.reset = function(){
-  this.attempts = 0;
-};
-
-/**
- * Set the minimum duration
- *
- * @api public
- */
-
-Backoff.prototype.setMin = function(min){
-  this.ms = min;
-};
-
-/**
- * Set the maximum duration
- *
- * @api public
- */
-
-Backoff.prototype.setMax = function(max){
-  this.max = max;
-};
-
-/**
- * Set the jitter
- *
- * @api public
- */
-
-Backoff.prototype.setJitter = function(jitter){
-  this.jitter = jitter;
-};
-
+function Backoff(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}module.exports=Backoff,Backoff.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var o=Math.random(),i=Math.floor(o*this.jitter*t);t=0==(1&Math.floor(10*o))?t-i:t+i}return 0|Math.min(t,this.max)},Backoff.prototype.reset=function(){this.attempts=0},Backoff.prototype.setMin=function(t){this.ms=t},Backoff.prototype.setMax=function(t){this.max=t},Backoff.prototype.setJitter=function(t){this.jitter=t};
\ No newline at end of file
index ea1f6de..d9ef3b1 100644 (file)
@@ -1,18 +1 @@
-
-var Backoff = require('..');
-var assert = require('assert');
-
-describe('.duration()', function(){
-  it('should increase the backoff', function(){
-    var b = new Backoff;
-
-    assert(100 == b.duration());
-    assert(200 == b.duration());
-    assert(400 == b.duration());
-    assert(800 == b.duration());
-
-    b.reset();
-    assert(100 == b.duration());
-    assert(200 == b.duration());
-  })
-})
\ No newline at end of file
+var Backoff=require(".."),assert=require("assert");describe(".duration()",(function(){it("should increase the backoff",(function(){var r=new Backoff;assert(100==r.duration()),assert(200==r.duration()),assert(400==r.duration()),assert(800==r.duration()),r.reset(),assert(100==r.duration()),assert(200==r.duration())}))}));
\ No newline at end of file
index 1685a76..1231112 100644 (file)
@@ -1,59 +1 @@
-'use strict';
-module.exports = balanced;
-function balanced(a, b, str) {
-  if (a instanceof RegExp) a = maybeMatch(a, str);
-  if (b instanceof RegExp) b = maybeMatch(b, str);
-
-  var r = range(a, b, str);
-
-  return r && {
-    start: r[0],
-    end: r[1],
-    pre: str.slice(0, r[0]),
-    body: str.slice(r[0] + a.length, r[1]),
-    post: str.slice(r[1] + b.length)
-  };
-}
-
-function maybeMatch(reg, str) {
-  var m = str.match(reg);
-  return m ? m[0] : null;
-}
-
-balanced.range = range;
-function range(a, b, str) {
-  var begs, beg, left, right, result;
-  var ai = str.indexOf(a);
-  var bi = str.indexOf(b, ai + 1);
-  var i = ai;
-
-  if (ai >= 0 && bi > 0) {
-    begs = [];
-    left = str.length;
-
-    while (i >= 0 && !result) {
-      if (i == ai) {
-        begs.push(i);
-        ai = str.indexOf(a, i + 1);
-      } else if (begs.length == 1) {
-        result = [ begs.pop(), bi ];
-      } else {
-        beg = begs.pop();
-        if (beg < left) {
-          left = beg;
-          right = bi;
-        }
-
-        bi = str.indexOf(b, i + 1);
-      }
-
-      i = ai < bi && ai >= 0 ? ai : bi;
-    }
-
-    if (begs.length) {
-      result = [ left, right ];
-    }
-  }
-
-  return result;
-}
+"use strict";function balanced(e,n,a){e instanceof RegExp&&(e=maybeMatch(e,a)),n instanceof RegExp&&(n=maybeMatch(n,a));var t=range(e,n,a);return t&&{start:t[0],end:t[1],pre:a.slice(0,t[0]),body:a.slice(t[0]+e.length,t[1]),post:a.slice(t[1]+n.length)}}function maybeMatch(e,n){var a=n.match(e);return a?a[0]:null}function range(e,n,a){var t,r,c,i,l,o=a.indexOf(e),f=a.indexOf(n,o+1),g=o;if(o>=0&&f>0){for(t=[],c=a.length;g>=0&&!l;)g==o?(t.push(g),o=a.indexOf(e,g+1)):1==t.length?l=[t.pop(),f]:((r=t.pop())<c&&(c=r,i=f),f=a.indexOf(n,g+1)),g=o<f&&o>=0?o:f;t.length&&(l=[c,i])}return l}module.exports=balanced,balanced.range=range;
\ No newline at end of file
index 362fbfa..1d8fbcf 100644 (file)
@@ -1,59 +1 @@
-/*
- * base64-arraybuffer
- * https://github.com/niklasvh/base64-arraybuffer
- *
- * Copyright (c) 2012 Niklas von Hertzen
- * Licensed under the MIT license.
- */
-(function(chars){
-  "use strict";
-
-  exports.encode = function(arraybuffer) {
-    var bytes = new Uint8Array(arraybuffer),
-    i, len = bytes.length, base64 = "";
-
-    for (i = 0; i < len; i+=3) {
-      base64 += chars[bytes[i] >> 2];
-      base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
-      base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
-      base64 += chars[bytes[i + 2] & 63];
-    }
-
-    if ((len % 3) === 2) {
-      base64 = base64.substring(0, base64.length - 1) + "=";
-    } else if (len % 3 === 1) {
-      base64 = base64.substring(0, base64.length - 2) + "==";
-    }
-
-    return base64;
-  };
-
-  exports.decode =  function(base64) {
-    var bufferLength = base64.length * 0.75,
-    len = base64.length, i, p = 0,
-    encoded1, encoded2, encoded3, encoded4;
-
-    if (base64[base64.length - 1] === "=") {
-      bufferLength--;
-      if (base64[base64.length - 2] === "=") {
-        bufferLength--;
-      }
-    }
-
-    var arraybuffer = new ArrayBuffer(bufferLength),
-    bytes = new Uint8Array(arraybuffer);
-
-    for (i = 0; i < len; i+=4) {
-      encoded1 = chars.indexOf(base64[i]);
-      encoded2 = chars.indexOf(base64[i+1]);
-      encoded3 = chars.indexOf(base64[i+2]);
-      encoded4 = chars.indexOf(base64[i+3]);
-
-      bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
-      bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
-      bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
-    }
-
-    return arraybuffer;
-  };
-})("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
+!function(n){"use strict";exports.encode=function(e){var r,t=new Uint8Array(e),i=t.length,f="";for(r=0;r<i;r+=3)f+=n[t[r]>>2],f+=n[(3&t[r])<<4|t[r+1]>>4],f+=n[(15&t[r+1])<<2|t[r+2]>>6],f+=n[63&t[r+2]];return i%3==2?f=f.substring(0,f.length-1)+"=":i%3==1&&(f=f.substring(0,f.length-2)+"=="),f},exports.decode=function(e){var r,t,i,f,g,o=.75*e.length,u=e.length,s=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);var d=new ArrayBuffer(o),h=new Uint8Array(d);for(r=0;r<u;r+=4)t=n.indexOf(e[r]),i=n.indexOf(e[r+1]),f=n.indexOf(e[r+2]),g=n.indexOf(e[r+3]),h[s++]=t<<2|i>>4,h[s++]=(15&i)<<4|f>>2,h[s++]=(3&f)<<6|63&g;return d}}("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
\ No newline at end of file
index 908ac83..8a00c11 100644 (file)
@@ -1 +1 @@
-(function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window,b.base64js=a()}})(function(){return function(){function b(d,e,g){function a(j,i){if(!e[j]){if(!d[j]){var f="function"==typeof require&&require;if(!i&&f)return f(j,!0);if(h)return h(j,!0);var c=new Error("Cannot find module '"+j+"'");throw c.code="MODULE_NOT_FOUND",c}var k=e[j]={exports:{}};d[j][0].call(k.exports,function(b){var c=d[j][1][b];return a(c||b)},k,k.exports,b,d,e,g)}return e[j].exports}for(var h="function"==typeof require&&require,c=0;c<g.length;c++)a(g[c]);return a}return b}()({"/":[function(a,b,c){'use strict';function d(a){var b=a.length;if(0<b%4)throw new Error("Invalid string. Length must be a multiple of 4");var c=a.indexOf("=");-1===c&&(c=b);var d=c===b?0:4-c%4;return[c,d]}function e(a,b,c){return 3*(b+c)/4-c}function f(a){var b,c,f=d(a),g=f[0],h=f[1],j=new m(e(a,g,h)),k=0,n=0<h?g-4:g;for(c=0;c<n;c+=4)b=l[a.charCodeAt(c)]<<18|l[a.charCodeAt(c+1)]<<12|l[a.charCodeAt(c+2)]<<6|l[a.charCodeAt(c+3)],j[k++]=255&b>>16,j[k++]=255&b>>8,j[k++]=255&b;return 2===h&&(b=l[a.charCodeAt(c)]<<2|l[a.charCodeAt(c+1)]>>4,j[k++]=255&b),1===h&&(b=l[a.charCodeAt(c)]<<10|l[a.charCodeAt(c+1)]<<4|l[a.charCodeAt(c+2)]>>2,j[k++]=255&b>>8,j[k++]=255&b),j}function g(a){return k[63&a>>18]+k[63&a>>12]+k[63&a>>6]+k[63&a]}function h(a,b,c){for(var d,e=[],f=b;f<c;f+=3)d=(16711680&a[f]<<16)+(65280&a[f+1]<<8)+(255&a[f+2]),e.push(g(d));return e.join("")}function j(a){for(var b,c=a.length,d=c%3,e=[],f=16383,g=0,j=c-d;g<j;g+=f)e.push(h(a,g,g+f>j?j:g+f));return 1===d?(b=a[c-1],e.push(k[b>>2]+k[63&b<<4]+"==")):2===d&&(b=(a[c-2]<<8)+a[c-1],e.push(k[b>>10]+k[63&b>>4]+k[63&b<<2]+"=")),e.join("")}c.byteLength=function(a){var b=d(a),c=b[0],e=b[1];return 3*(c+e)/4-e},c.toByteArray=f,c.fromByteArray=j;for(var k=[],l=[],m="undefined"==typeof Uint8Array?Array:Uint8Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,p=n.length;o<p;++o)k[o]=n[o],l[n.charCodeAt(o)]=o;l[45]=62,l[95]=63},{}]},{},[])("/")});
\ No newline at end of file
+!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"==typeof window?"undefined"==typeof global?"undefined"==typeof self?this:self:global:window).base64js=e()}}((function(){return function e(r,n,t){function o(i,u){if(!n[i]){if(!r[i]){var a="function"==typeof require&&require;if(!u&&a)return a(i,!0);if(f)return f(i,!0);var d=new Error("Cannot find module '"+i+"'");throw d.code="MODULE_NOT_FOUND",d}var c=n[i]={exports:{}};r[i][0].call(c.exports,(function(e){return o(r[i][1][e]||e)}),c,c.exports,e,r,n,t)}return n[i].exports}for(var f="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}({"/":[function(e,r,n){"use strict";function t(e){var r=e.length;if(0<r%4)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=r),[n,n===r?0:4-n%4]}function o(e){return i[63&e>>18]+i[63&e>>12]+i[63&e>>6]+i[63&e]}function f(e,r,n){for(var t,f=[],i=r;i<n;i+=3)t=(16711680&e[i]<<16)+(65280&e[i+1]<<8)+(255&e[i+2]),f.push(o(t));return f.join("")}n.byteLength=function(e){var r=t(e),n=r[0],o=r[1];return 3*(n+o)/4-o},n.toByteArray=function(e){var r,n,o=t(e),f=o[0],i=o[1],d=new a(function(e,r,n){return 3*(r+n)/4-n}(0,f,i)),c=0,h=0<i?f-4:f;for(n=0;n<h;n+=4)r=u[e.charCodeAt(n)]<<18|u[e.charCodeAt(n+1)]<<12|u[e.charCodeAt(n+2)]<<6|u[e.charCodeAt(n+3)],d[c++]=255&r>>16,d[c++]=255&r>>8,d[c++]=255&r;return 2===i&&(r=u[e.charCodeAt(n)]<<2|u[e.charCodeAt(n+1)]>>4,d[c++]=255&r),1===i&&(r=u[e.charCodeAt(n)]<<10|u[e.charCodeAt(n+1)]<<4|u[e.charCodeAt(n+2)]>>2,d[c++]=255&r>>8,d[c++]=255&r),d},n.fromByteArray=function(e){for(var r,n=e.length,t=n%3,o=[],u=16383,a=0,d=n-t;a<d;a+=u)o.push(f(e,a,a+u>d?d:a+u));return 1===t?(r=e[n-1],o.push(i[r>>2]+i[63&r<<4]+"==")):2===t&&(r=(e[n-2]<<8)+e[n-1],o.push(i[r>>10]+i[63&r>>4]+i[63&r<<2]+"=")),o.join("")};for(var i=[],u=[],a="undefined"==typeof Uint8Array?Array:Uint8Array,d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c=0,h=d.length;c<h;++c)i[c]=d[c],u[d.charCodeAt(c)]=c;u[45]=62,u[95]=63},{}]},{},[])("/")}));
\ No newline at end of file
index 0599f3e..2d1eabd 100644 (file)
@@ -1,150 +1 @@
-'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')
-  }
-
-  // Trim off extra bytes after placeholder bytes are found
-  // See: https://github.com/beatgammit/base64-js/issues/42
-  var validLen = b64.indexOf('=')
-  if (validLen === -1) validLen = len
-
-  var placeHoldersLen = validLen === len
-    ? 0
-    : 4 - (validLen % 4)
-
-  return [validLen, placeHoldersLen]
-}
-
-// base64 is 4/3 + up to two characters of the original data
-function byteLength (b64) {
-  var lens = getLens(b64)
-  var validLen = lens[0]
-  var placeHoldersLen = lens[1]
-  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
-}
-
-function _byteLength (b64, validLen, placeHoldersLen) {
-  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
-}
-
-function toByteArray (b64) {
-  var tmp
-  var lens = getLens(b64)
-  var validLen = lens[0]
-  var placeHoldersLen = lens[1]
-
-  var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
-
-  var curByte = 0
-
-  // if there are placeholders, only get up to the last complete 4 chars
-  var len = placeHoldersLen > 0
-    ? validLen - 4
-    : validLen
-
-  var i
-  for (i = 0; i < len; i += 4) {
-    tmp =
-      (revLookup[b64.charCodeAt(i)] << 18) |
-      (revLookup[b64.charCodeAt(i + 1)] << 12) |
-      (revLookup[b64.charCodeAt(i + 2)] << 6) |
-      revLookup[b64.charCodeAt(i + 3)]
-    arr[curByte++] = (tmp >> 16) & 0xFF
-    arr[curByte++] = (tmp >> 8) & 0xFF
-    arr[curByte++] = tmp & 0xFF
-  }
-
-  if (placeHoldersLen === 2) {
-    tmp =
-      (revLookup[b64.charCodeAt(i)] << 2) |
-      (revLookup[b64.charCodeAt(i + 1)] >> 4)
-    arr[curByte++] = tmp & 0xFF
-  }
-
-  if (placeHoldersLen === 1) {
-    tmp =
-      (revLookup[b64.charCodeAt(i)] << 10) |
-      (revLookup[b64.charCodeAt(i + 1)] << 4) |
-      (revLookup[b64.charCodeAt(i + 2)] >> 2)
-    arr[curByte++] = (tmp >> 8) & 0xFF
-    arr[curByte++] = tmp & 0xFF
-  }
-
-  return arr
-}
-
-function tripletToBase64 (num) {
-  return lookup[num >> 18 & 0x3F] +
-    lookup[num >> 12 & 0x3F] +
-    lookup[num >> 6 & 0x3F] +
-    lookup[num & 0x3F]
-}
-
-function encodeChunk (uint8, start, end) {
-  var tmp
-  var output = []
-  for (var i = start; i < end; i += 3) {
-    tmp =
-      ((uint8[i] << 16) & 0xFF0000) +
-      ((uint8[i + 1] << 8) & 0xFF00) +
-      (uint8[i + 2] & 0xFF)
-    output.push(tripletToBase64(tmp))
-  }
-  return output.join('')
-}
-
-function fromByteArray (uint8) {
-  var tmp
-  var len = uint8.length
-  var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
-  var parts = []
-  var maxChunkLength = 16383 // must be multiple of 3
-
-  // go through the array every three bytes, we'll deal with trailing stuff later
-  for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
-    parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
-  }
-
-  // pad the end with zeros, but make sure to not forget the extra bytes
-  if (extraBytes === 1) {
-    tmp = uint8[len - 1]
-    parts.push(
-      lookup[tmp >> 2] +
-      lookup[(tmp << 4) & 0x3F] +
-      '=='
-    )
-  } else if (extraBytes === 2) {
-    tmp = (uint8[len - 2] << 8) + uint8[len - 1]
-    parts.push(
-      lookup[tmp >> 10] +
-      lookup[(tmp >> 4) & 0x3F] +
-      lookup[(tmp << 2) & 0x3F] +
-      '='
-    )
-  }
-
-  return parts.join('')
-}
+"use strict";exports.byteLength=byteLength,exports.toByteArray=toByteArray,exports.fromByteArray=fromByteArray;for(var lookup=[],revLookup=[],Arr="undefined"!=typeof Uint8Array?Uint8Array:Array,code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,len=code.length;i<len;++i)lookup[i]=code[i],revLookup[code.charCodeAt(i)]=i;function getLens(o){var r=o.length;if(r%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var e=o.indexOf("=");return-1===e&&(e=r),[e,e===r?0:4-e%4]}function byteLength(o){var r=getLens(o),e=r[0],t=r[1];return 3*(e+t)/4-t}function _byteLength(o,r,e){return 3*(r+e)/4-e}function toByteArray(o){var r,e,t=getLens(o),n=t[0],u=t[1],p=new Arr(_byteLength(o,n,u)),a=0,h=u>0?n-4:n;for(e=0;e<h;e+=4)r=revLookup[o.charCodeAt(e)]<<18|revLookup[o.charCodeAt(e+1)]<<12|revLookup[o.charCodeAt(e+2)]<<6|revLookup[o.charCodeAt(e+3)],p[a++]=r>>16&255,p[a++]=r>>8&255,p[a++]=255&r;return 2===u&&(r=revLookup[o.charCodeAt(e)]<<2|revLookup[o.charCodeAt(e+1)]>>4,p[a++]=255&r),1===u&&(r=revLookup[o.charCodeAt(e)]<<10|revLookup[o.charCodeAt(e+1)]<<4|revLookup[o.charCodeAt(e+2)]>>2,p[a++]=r>>8&255,p[a++]=255&r),p}function tripletToBase64(o){return lookup[o>>18&63]+lookup[o>>12&63]+lookup[o>>6&63]+lookup[63&o]}function encodeChunk(o,r,e){for(var t,n=[],u=r;u<e;u+=3)t=(o[u]<<16&16711680)+(o[u+1]<<8&65280)+(255&o[u+2]),n.push(tripletToBase64(t));return n.join("")}function fromByteArray(o){for(var r,e=o.length,t=e%3,n=[],u=16383,p=0,a=e-t;p<a;p+=u)n.push(encodeChunk(o,p,p+u>a?a:p+u));return 1===t?(r=o[e-1],n.push(lookup[r>>2]+lookup[r<<4&63]+"==")):2===t&&(r=(o[e-2]<<8)+o[e-1],n.push(lookup[r>>10]+lookup[r>>4&63]+lookup[r<<2&63]+"=")),n.join("")}revLookup["-".charCodeAt(0)]=62,revLookup["_".charCodeAt(0)]=63;
\ No newline at end of file
index ee179d7..7fef02f 100644 (file)
@@ -1,100 +1 @@
-/**\r
- * Create a blob builder even when vendor prefixes exist\r
- */\r
-\r
-var BlobBuilder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :\r
-  typeof WebKitBlobBuilder !== 'undefined' ? WebKitBlobBuilder :\r
-  typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :\r
-  typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : \r
-  false;\r
-\r
-/**\r
- * Check if Blob constructor is supported\r
- */\r
-\r
-var blobSupported = (function() {\r
-  try {\r
-    var a = new Blob(['hi']);\r
-    return a.size === 2;\r
-  } catch(e) {\r
-    return false;\r
-  }\r
-})();\r
-\r
-/**\r
- * Check if Blob constructor supports ArrayBufferViews\r
- * Fails in Safari 6, so we need to map to ArrayBuffers there.\r
- */\r
-\r
-var blobSupportsArrayBufferView = blobSupported && (function() {\r
-  try {\r
-    var b = new Blob([new Uint8Array([1,2])]);\r
-    return b.size === 2;\r
-  } catch(e) {\r
-    return false;\r
-  }\r
-})();\r
-\r
-/**\r
- * Check if BlobBuilder is supported\r
- */\r
-\r
-var blobBuilderSupported = BlobBuilder\r
-  && BlobBuilder.prototype.append\r
-  && BlobBuilder.prototype.getBlob;\r
-\r
-/**\r
- * Helper function that maps ArrayBufferViews to ArrayBuffers\r
- * Used by BlobBuilder constructor and old browsers that didn't\r
- * support it in the Blob constructor.\r
- */\r
-\r
-function mapArrayBufferViews(ary) {\r
-  return ary.map(function(chunk) {\r
-    if (chunk.buffer instanceof ArrayBuffer) {\r
-      var buf = chunk.buffer;\r
-\r
-      // if this is a subarray, make a copy so we only\r
-      // include the subarray region from the underlying buffer\r
-      if (chunk.byteLength !== buf.byteLength) {\r
-        var copy = new Uint8Array(chunk.byteLength);\r
-        copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));\r
-        buf = copy.buffer;\r
-      }\r
-\r
-      return buf;\r
-    }\r
-\r
-    return chunk;\r
-  });\r
-}\r
-\r
-function BlobBuilderConstructor(ary, options) {\r
-  options = options || {};\r
-\r
-  var bb = new BlobBuilder();\r
-  mapArrayBufferViews(ary).forEach(function(part) {\r
-    bb.append(part);\r
-  });\r
-\r
-  return (options.type) ? bb.getBlob(options.type) : bb.getBlob();\r
-};\r
-\r
-function BlobConstructor(ary, options) {\r
-  return new Blob(mapArrayBufferViews(ary), options || {});\r
-};\r
-\r
-if (typeof Blob !== 'undefined') {\r
-  BlobBuilderConstructor.prototype = Blob.prototype;\r
-  BlobConstructor.prototype = Blob.prototype;\r
-}\r
-\r
-module.exports = (function() {\r
-  if (blobSupported) {\r
-    return blobSupportsArrayBufferView ? Blob : BlobConstructor;\r
-  } else if (blobBuilderSupported) {\r
-    return BlobBuilderConstructor;\r
-  } else {\r
-    return undefined;\r
-  }\r
-})();\r
+var BlobBuilder=void 0!==BlobBuilder?BlobBuilder:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder&&MozBlobBuilder,blobSupported=function(){try{return 2===new Blob(["hi"]).size}catch(e){return!1}}(),blobSupportsArrayBufferView=blobSupported&&function(){try{return 2===new Blob([new Uint8Array([1,2])]).size}catch(e){return!1}}(),blobBuilderSupported=BlobBuilder&&BlobBuilder.prototype.append&&BlobBuilder.prototype.getBlob;function mapArrayBufferViews(e){return e.map((function(e){if(e.buffer instanceof ArrayBuffer){var r=e.buffer;if(e.byteLength!==r.byteLength){var o=new Uint8Array(e.byteLength);o.set(new Uint8Array(r,e.byteOffset,e.byteLength)),r=o.buffer}return r}return e}))}function BlobBuilderConstructor(e,r){r=r||{};var o=new BlobBuilder;return mapArrayBufferViews(e).forEach((function(e){o.append(e)})),r.type?o.getBlob(r.type):o.getBlob()}function BlobConstructor(e,r){return new Blob(mapArrayBufferViews(e),r||{})}"undefined"!=typeof Blob&&(BlobBuilderConstructor.prototype=Blob.prototype,BlobConstructor.prototype=Blob.prototype),module.exports=blobSupported?blobSupportsArrayBufferView?Blob:BlobConstructor:blobBuilderSupported?BlobBuilderConstructor:void 0;
\ No newline at end of file
index fe9105e..a922ae6 100644 (file)
@@ -1,100 +1 @@
-var Blob = require('../');\r
-var expect = require('expect.js');\r
-\r
-describe('blob', function() {\r
-  if (!Blob) {\r
-    it('should not have a blob or a blob builder in the global namespace, or blob should not be a constructor function if the module exports false', function() {\r
-      try {\r
-        var ab = (new Uint8Array(5)).buffer;\r
-        global.Blob([ab]);\r
-        expect().fail('Blob shouldn\'t be constructable');\r
-      } catch (e) {}\r
-\r
-      var BlobBuilder = global.BlobBuilder\r
-        || global.WebKitBlobBuilder\r
-        || global.MSBlobBuilder\r
-        || global.MozBlobBuilder;\r
-      expect(BlobBuilder).to.be(undefined);\r
-    });\r
-  } else {\r
-    it('should encode a proper sized blob when given a string argument', function() {\r
-      var b = new Blob(['hi']);\r
-      expect(b.size).to.be(2);\r
-    });\r
-\r
-    it('should encode a blob with proper size when given two strings as arguments', function() {\r
-      var b = new Blob(['hi', 'hello']);\r
-      expect(b.size).to.be(7);\r
-    });\r
-\r
-    it('should encode arraybuffers with right content', function(done) {\r
-      var ary = new Uint8Array(5);\r
-      for (var i = 0; i < 5; i++) ary[i] = i;\r
-      var b = new Blob([ary.buffer]);\r
-      var fr = new FileReader();\r
-      fr.onload = function() {\r
-        var newAry = new Uint8Array(this.result);\r
-        for (var i = 0; i < 5; i++) expect(newAry[i]).to.be(i);\r
-        done();\r
-      };\r
-      fr.readAsArrayBuffer(b);\r
-    });\r
-\r
-    it('should encode typed arrays with right content', function(done) {\r
-      var ary = new Uint8Array(5);\r
-      for (var i = 0; i < 5; i++) ary[i] = i;\r
-      var b = new Blob([ary]);\r
-      var fr = new FileReader();\r
-      fr.onload = function() {\r
-        var newAry = new Uint8Array(this.result);\r
-        for (var i = 0; i < 5; i++) expect(newAry[i]).to.be(i);\r
-        done();\r
-      };\r
-      fr.readAsArrayBuffer(b);\r
-    });\r
-\r
-    it('should encode sliced typed arrays with right content', function(done) {\r
-      var ary = new Uint8Array(5);\r
-      for (var i = 0; i < 5; i++) ary[i] = i;\r
-      var b = new Blob([ary.subarray(2)]);\r
-      var fr = new FileReader();\r
-      fr.onload = function() {\r
-        var newAry = new Uint8Array(this.result);\r
-        for (var i = 0; i < 3; i++) expect(newAry[i]).to.be(i + 2);\r
-        done();\r
-      };\r
-      fr.readAsArrayBuffer(b);\r
-    });\r
-\r
-    it('should encode with blobs', function(done) {\r
-      var ary = new Uint8Array(5);\r
-      for (var i = 0; i < 5; i++) ary[i] = i;\r
-      var b = new Blob([new Blob([ary.buffer])]);\r
-      var fr = new FileReader();\r
-      fr.onload = function() {\r
-        var newAry = new Uint8Array(this.result);\r
-        for (var i = 0; i < 5; i++) expect(newAry[i]).to.be(i);\r
-        done();\r
-      };\r
-      fr.readAsArrayBuffer(b);\r
-    });\r
-\r
-    it('should enode mixed contents to right size', function() {\r
-      var ary = new Uint8Array(5);\r
-      for (var i = 0; i < 5; i++) ary[i] = i;\r
-      var b = new Blob([ary.buffer, 'hello']);\r
-      expect(b.size).to.be(10);\r
-    });\r
-\r
-    it('should accept mime type', function() {\r
-      var b = new Blob(['hi', 'hello'], { type: 'text/html' });\r
-      expect(b.type).to.be('text/html');\r
-    });\r
-\r
-    it('should be an instance of constructor', function() {\r
-      var b = new Blob(['hi']);\r
-      expect(b).to.be.a(Blob);\r
-      expect(b).to.be.a(global.Blob);\r
-    });\r
-  }\r
-});\r
+var Blob=require("../"),expect=require("expect.js");describe("blob",(function(){Blob?(it("should encode a proper sized blob when given a string argument",(function(){var e=new Blob(["hi"]);expect(e.size).to.be(2)})),it("should encode a blob with proper size when given two strings as arguments",(function(){var e=new Blob(["hi","hello"]);expect(e.size).to.be(7)})),it("should encode arraybuffers with right content",(function(e){for(var o=new Uint8Array(5),t=0;t<5;t++)o[t]=t;var r=new Blob([o.buffer]),n=new FileReader;n.onload=function(){for(var o=new Uint8Array(this.result),t=0;t<5;t++)expect(o[t]).to.be(t);e()},n.readAsArrayBuffer(r)})),it("should encode typed arrays with right content",(function(e){for(var o=new Uint8Array(5),t=0;t<5;t++)o[t]=t;var r=new Blob([o]),n=new FileReader;n.onload=function(){for(var o=new Uint8Array(this.result),t=0;t<5;t++)expect(o[t]).to.be(t);e()},n.readAsArrayBuffer(r)})),it("should encode sliced typed arrays with right content",(function(e){for(var o=new Uint8Array(5),t=0;t<5;t++)o[t]=t;var r=new Blob([o.subarray(2)]),n=new FileReader;n.onload=function(){for(var o=new Uint8Array(this.result),t=0;t<3;t++)expect(o[t]).to.be(t+2);e()},n.readAsArrayBuffer(r)})),it("should encode with blobs",(function(e){for(var o=new Uint8Array(5),t=0;t<5;t++)o[t]=t;var r=new Blob([new Blob([o.buffer])]),n=new FileReader;n.onload=function(){for(var o=new Uint8Array(this.result),t=0;t<5;t++)expect(o[t]).to.be(t);e()},n.readAsArrayBuffer(r)})),it("should enode mixed contents to right size",(function(){for(var e=new Uint8Array(5),o=0;o<5;o++)e[o]=o;var t=new Blob([e.buffer,"hello"]);expect(t.size).to.be(10)})),it("should accept mime type",(function(){var e=new Blob(["hi","hello"],{type:"text/html"});expect(e.type).to.be("text/html")})),it("should be an instance of constructor",(function(){var e=new Blob(["hi"]);expect(e).to.be.a(Blob),expect(e).to.be.a(global.Blob)}))):it("should not have a blob or a blob builder in the global namespace, or blob should not be a constructor function if the module exports false",(function(){try{var e=new Uint8Array(5).buffer;global.Blob([e]),expect().fail("Blob shouldn't be constructable")}catch(e){}var o=global.BlobBuilder||global.WebKitBlobBuilder||global.MSBlobBuilder||global.MozBlobBuilder;expect(o).to.be(void 0)}))}));
\ No newline at end of file
index 93c3a1f..7b8fdf7 100644 (file)
@@ -3,155 +3,4 @@
  * Copyright(c) 2014-2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module dependencies.
- * @private
- */
-
-var deprecate = require('depd')('body-parser')
-
-/**
- * Cache of loaded parsers.
- * @private
- */
-
-var parsers = Object.create(null)
-
-/**
- * @typedef Parsers
- * @type {function}
- * @property {function} json
- * @property {function} raw
- * @property {function} text
- * @property {function} urlencoded
- */
-
-/**
- * Module exports.
- * @type {Parsers}
- */
-
-exports = module.exports = deprecate.function(bodyParser,
-  'bodyParser: use individual json/urlencoded middlewares')
-
-/**
- * JSON parser.
- * @public
- */
-
-Object.defineProperty(exports, 'json', {
-  configurable: true,
-  enumerable: true,
-  get: createParserGetter('json')
-})
-
-/**
- * Raw parser.
- * @public
- */
-
-Object.defineProperty(exports, 'raw', {
-  configurable: true,
-  enumerable: true,
-  get: createParserGetter('raw')
-})
-
-/**
- * Text parser.
- * @public
- */
-
-Object.defineProperty(exports, 'text', {
-  configurable: true,
-  enumerable: true,
-  get: createParserGetter('text')
-})
-
-/**
- * URL-encoded parser.
- * @public
- */
-
-Object.defineProperty(exports, 'urlencoded', {
-  configurable: true,
-  enumerable: true,
-  get: createParserGetter('urlencoded')
-})
-
-/**
- * Create a middleware to parse json and urlencoded bodies.
- *
- * @param {object} [options]
- * @return {function}
- * @deprecated
- * @public
- */
-
-function bodyParser (options) {
-  var opts = {}
-
-  // exclude type option
-  if (options) {
-    for (var prop in options) {
-      if (prop !== 'type') {
-        opts[prop] = options[prop]
-      }
-    }
-  }
-
-  var _urlencoded = exports.urlencoded(opts)
-  var _json = exports.json(opts)
-
-  return function bodyParser (req, res, next) {
-    _json(req, res, function (err) {
-      if (err) return next(err)
-      _urlencoded(req, res, next)
-    })
-  }
-}
-
-/**
- * Create a getter for loading a parser.
- * @private
- */
-
-function createParserGetter (name) {
-  return function get () {
-    return loadParser(name)
-  }
-}
-
-/**
- * Load a parser module.
- * @private
- */
-
-function loadParser (parserName) {
-  var parser = parsers[parserName]
-
-  if (parser !== undefined) {
-    return parser
-  }
-
-  // this uses a switch for static require analysis
-  switch (parserName) {
-    case 'json':
-      parser = require('./lib/types/json')
-      break
-    case 'raw':
-      parser = require('./lib/types/raw')
-      break
-    case 'text':
-      parser = require('./lib/types/text')
-      break
-    case 'urlencoded':
-      parser = require('./lib/types/urlencoded')
-      break
-  }
-
-  // store to prevent invoking require()
-  return (parsers[parserName] = parser)
-}
+"use strict";var deprecate=require("depd")("body-parser"),parsers=Object.create(null);function bodyParser(e){var r={};if(e)for(var t in e)"type"!==t&&(r[t]=e[t]);var a=exports.urlencoded(r),n=exports.json(r);return function(e,r,t){n(e,r,(function(n){if(n)return t(n);a(e,r,t)}))}}function createParserGetter(e){return function(){return loadParser(e)}}function loadParser(e){var r=parsers[e];if(void 0!==r)return r;switch(e){case"json":r=require("./lib/types/json");break;case"raw":r=require("./lib/types/raw");break;case"text":r=require("./lib/types/text");break;case"urlencoded":r=require("./lib/types/urlencoded")}return parsers[e]=r}exports=module.exports=deprecate.function(bodyParser,"bodyParser: use individual json/urlencoded middlewares"),Object.defineProperty(exports,"json",{configurable:!0,enumerable:!0,get:createParserGetter("json")}),Object.defineProperty(exports,"raw",{configurable:!0,enumerable:!0,get:createParserGetter("raw")}),Object.defineProperty(exports,"text",{configurable:!0,enumerable:!0,get:createParserGetter("text")}),Object.defineProperty(exports,"urlencoded",{configurable:!0,enumerable:!0,get:createParserGetter("urlencoded")});
\ No newline at end of file
index c102609..7dac2ea 100644 (file)
@@ -3,179 +3,4 @@
  * Copyright(c) 2014-2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module dependencies.
- * @private
- */
-
-var createError = require('http-errors')
-var getBody = require('raw-body')
-var iconv = require('iconv-lite')
-var onFinished = require('on-finished')
-var zlib = require('zlib')
-
-/**
- * Module exports.
- */
-
-module.exports = read
-
-/**
- * Read a request into a buffer and parse.
- *
- * @param {object} req
- * @param {object} res
- * @param {function} next
- * @param {function} parse
- * @param {function} debug
- * @param {object} options
- * @private
- */
-
-function read (req, res, next, parse, debug, options) {
-  var length
-  var opts = options
-  var stream
-
-  // flag as parsed
-  req._body = true
-
-  // read options
-  var encoding = opts.encoding !== null
-    ? opts.encoding
-    : null
-  var verify = opts.verify
-
-  try {
-    // get the content stream
-    stream = contentstream(req, debug, opts.inflate)
-    length = stream.length
-    stream.length = undefined
-  } catch (err) {
-    return next(err)
-  }
-
-  // set raw-body options
-  opts.length = length
-  opts.encoding = verify
-    ? null
-    : encoding
-
-  // assert charset is supported
-  if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) {
-    return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
-      charset: encoding.toLowerCase(),
-      type: 'charset.unsupported'
-    }))
-  }
-
-  // read body
-  debug('read body')
-  getBody(stream, opts, function (error, body) {
-    if (error) {
-      var _error
-
-      if (error.type === 'encoding.unsupported') {
-        // echo back charset
-        _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', {
-          charset: encoding.toLowerCase(),
-          type: 'charset.unsupported'
-        })
-      } else {
-        // set status code on error
-        _error = createError(400, error)
-      }
-
-      // read off entire request
-      stream.resume()
-      onFinished(req, function onfinished () {
-        next(createError(400, _error))
-      })
-      return
-    }
-
-    // verify
-    if (verify) {
-      try {
-        debug('verify body')
-        verify(req, res, body, encoding)
-      } catch (err) {
-        next(createError(403, err, {
-          body: body,
-          type: err.type || 'entity.verify.failed'
-        }))
-        return
-      }
-    }
-
-    // parse
-    var str = body
-    try {
-      debug('parse body')
-      str = typeof body !== 'string' && encoding !== null
-        ? iconv.decode(body, encoding)
-        : body
-      req.body = parse(str)
-    } catch (err) {
-      next(createError(400, err, {
-        body: str,
-        type: err.type || 'entity.parse.failed'
-      }))
-      return
-    }
-
-    next()
-  })
-}
-
-/**
- * Get the content stream of the request.
- *
- * @param {object} req
- * @param {function} debug
- * @param {boolean} [inflate=true]
- * @return {object}
- * @api private
- */
-
-function contentstream (req, debug, inflate) {
-  var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase()
-  var length = req.headers['content-length']
-  var stream
-
-  debug('content-encoding "%s"', encoding)
-
-  if (inflate === false && encoding !== 'identity') {
-    throw createError(415, 'content encoding unsupported', {
-      encoding: encoding,
-      type: 'encoding.unsupported'
-    })
-  }
-
-  switch (encoding) {
-    case 'deflate':
-      stream = zlib.createInflate()
-      debug('inflate body')
-      req.pipe(stream)
-      break
-    case 'gzip':
-      stream = zlib.createGunzip()
-      debug('gunzip body')
-      req.pipe(stream)
-      break
-    case 'identity':
-      stream = req
-      stream.length = length
-      break
-    default:
-      throw createError(415, 'unsupported content encoding "' + encoding + '"', {
-        encoding: encoding,
-        type: 'encoding.unsupported'
-      })
-  }
-
-  return stream
-}
+"use strict";var createError=require("http-errors"),getBody=require("raw-body"),iconv=require("iconv-lite"),onFinished=require("on-finished"),zlib=require("zlib");function read(e,r,t,n,o,i){var c,d,a=i;e._body=!0;var u=null!==a.encoding?a.encoding:null,p=a.verify;try{c=(d=contentstream(e,o,a.inflate)).length,d.length=void 0}catch(e){return t(e)}if(a.length=c,a.encoding=p?null:u,null===a.encoding&&null!==u&&!iconv.encodingExists(u))return t(createError(415,'unsupported charset "'+u.toUpperCase()+'"',{charset:u.toLowerCase(),type:"charset.unsupported"}));o("read body"),getBody(d,a,(function(i,c){var a;if(i)return a="encoding.unsupported"===i.type?createError(415,'unsupported charset "'+u.toUpperCase()+'"',{charset:u.toLowerCase(),type:"charset.unsupported"}):createError(400,i),d.resume(),void onFinished(e,(function(){t(createError(400,a))}));if(p)try{o("verify body"),p(e,r,c,u)}catch(e){return void t(createError(403,e,{body:c,type:e.type||"entity.verify.failed"}))}var s=c;try{o("parse body"),s="string"!=typeof c&&null!==u?iconv.decode(c,u):c,e.body=n(s)}catch(e){return void t(createError(400,e,{body:s,type:e.type||"entity.parse.failed"}))}t()}))}function contentstream(e,r,t){var n,o=(e.headers["content-encoding"]||"identity").toLowerCase(),i=e.headers["content-length"];if(r('content-encoding "%s"',o),!1===t&&"identity"!==o)throw createError(415,"content encoding unsupported",{encoding:o,type:"encoding.unsupported"});switch(o){case"deflate":n=zlib.createInflate(),r("inflate body"),e.pipe(n);break;case"gzip":n=zlib.createGunzip(),r("gunzip body"),e.pipe(n);break;case"identity":(n=e).length=i;break;default:throw createError(415,'unsupported content encoding "'+o+'"',{encoding:o,type:"encoding.unsupported"})}return n}module.exports=read;
\ No newline at end of file
index 2971dc1..0b520bb 100644 (file)
@@ -4,227 +4,4 @@
  * Copyright(c) 2014-2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module dependencies.
- * @private
- */
-
-var bytes = require('bytes')
-var contentType = require('content-type')
-var createError = require('http-errors')
-var debug = require('debug')('body-parser:json')
-var read = require('../read')
-var typeis = require('type-is')
-
-/**
- * Module exports.
- */
-
-module.exports = json
-
-/**
- * RegExp to match the first non-space in a string.
- *
- * Allowed whitespace is defined in RFC 7159:
- *
- *    ws = *(
- *            %x20 /              ; Space
- *            %x09 /              ; Horizontal tab
- *            %x0A /              ; Line feed or New line
- *            %x0D )              ; Carriage return
- */
-
-var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*(.)/ // eslint-disable-line no-control-regex
-
-/**
- * Create a middleware to parse JSON bodies.
- *
- * @param {object} [options]
- * @return {function}
- * @public
- */
-
-function json (options) {
-  var opts = options || {}
-
-  var limit = typeof opts.limit !== 'number'
-    ? bytes.parse(opts.limit || '100kb')
-    : opts.limit
-  var inflate = opts.inflate !== false
-  var reviver = opts.reviver
-  var strict = opts.strict !== false
-  var type = opts.type || 'application/json'
-  var verify = opts.verify || false
-
-  if (verify !== false && typeof verify !== 'function') {
-    throw new TypeError('option verify must be function')
-  }
-
-  // create the appropriate type checking function
-  var shouldParse = typeof type !== 'function'
-    ? typeChecker(type)
-    : type
-
-  function parse (body) {
-    if (body.length === 0) {
-      // special-case empty json body, as it's a common client-side mistake
-      // TODO: maybe make this configurable or part of "strict" option
-      return {}
-    }
-
-    if (strict) {
-      var first = firstchar(body)
-
-      if (first !== '{' && first !== '[') {
-        debug('strict violation')
-        throw createStrictSyntaxError(body, first)
-      }
-    }
-
-    try {
-      debug('parse json')
-      return JSON.parse(body, reviver)
-    } catch (e) {
-      throw normalizeJsonSyntaxError(e, {
-        message: e.message,
-        stack: e.stack
-      })
-    }
-  }
-
-  return function jsonParser (req, res, next) {
-    if (req._body) {
-      debug('body already parsed')
-      next()
-      return
-    }
-
-    req.body = req.body || {}
-
-    // skip requests without bodies
-    if (!typeis.hasBody(req)) {
-      debug('skip empty body')
-      next()
-      return
-    }
-
-    debug('content-type %j', req.headers['content-type'])
-
-    // determine if request should be parsed
-    if (!shouldParse(req)) {
-      debug('skip parsing')
-      next()
-      return
-    }
-
-    // assert charset per RFC 7159 sec 8.1
-    var charset = getCharset(req) || 'utf-8'
-    if (charset.substr(0, 4) !== 'utf-') {
-      debug('invalid charset')
-      next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
-        charset: charset,
-        type: 'charset.unsupported'
-      }))
-      return
-    }
-
-    // read
-    read(req, res, next, parse, debug, {
-      encoding: charset,
-      inflate: inflate,
-      limit: limit,
-      verify: verify
-    })
-  }
-}
-
-/**
- * Create strict violation syntax error matching native error.
- *
- * @param {string} str
- * @param {string} char
- * @return {Error}
- * @private
- */
-
-function createStrictSyntaxError (str, char) {
-  var index = str.indexOf(char)
-  var partial = str.substring(0, index) + '#'
-
-  try {
-    JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation')
-  } catch (e) {
-    return normalizeJsonSyntaxError(e, {
-      message: e.message.replace('#', char),
-      stack: e.stack
-    })
-  }
-}
-
-/**
- * Get the first non-whitespace character in a string.
- *
- * @param {string} str
- * @return {function}
- * @private
- */
-
-function firstchar (str) {
-  return FIRST_CHAR_REGEXP.exec(str)[1]
-}
-
-/**
- * Get the charset of a request.
- *
- * @param {object} req
- * @api private
- */
-
-function getCharset (req) {
-  try {
-    return (contentType.parse(req).parameters.charset || '').toLowerCase()
-  } catch (e) {
-    return undefined
-  }
-}
-
-/**
- * Normalize a SyntaxError for JSON.parse.
- *
- * @param {SyntaxError} error
- * @param {object} obj
- * @return {SyntaxError}
- */
-
-function normalizeJsonSyntaxError (error, obj) {
-  var keys = Object.getOwnPropertyNames(error)
-
-  for (var i = 0; i < keys.length; i++) {
-    var key = keys[i]
-    if (key !== 'stack' && key !== 'message') {
-      delete error[key]
-    }
-  }
-
-  // replace stack before message for Node.js 0.10 and below
-  error.stack = obj.stack.replace(error.message, obj.message)
-  error.message = obj.message
-
-  return error
-}
-
-/**
- * Get the simple type checker.
- *
- * @param {string} type
- * @return {function}
- */
-
-function typeChecker (type) {
-  return function checkType (req) {
-    return Boolean(typeis(req, type))
-  }
-}
+"use strict";var bytes=require("bytes"),contentType=require("content-type"),createError=require("http-errors"),debug=require("debug")("body-parser:json"),read=require("../read"),typeis=require("type-is");module.exports=json;var FIRST_CHAR_REGEXP=/^[\x20\x09\x0a\x0d]*(.)/;function json(e){var r=e||{},t="number"!=typeof r.limit?bytes.parse(r.limit||"100kb"):r.limit,n=!1!==r.inflate,a=r.reviver,s=!1!==r.strict,o=r.type||"application/json",i=r.verify||!1;if(!1!==i&&"function"!=typeof i)throw new TypeError("option verify must be function");var c="function"!=typeof o?typeChecker(o):o;function u(e){if(0===e.length)return{};if(s){var r=firstchar(e);if("{"!==r&&"["!==r)throw debug("strict violation"),createStrictSyntaxError(e,r)}try{return debug("parse json"),JSON.parse(e,a)}catch(e){throw normalizeJsonSyntaxError(e,{message:e.message,stack:e.stack})}}return function(e,r,a){if(e._body)return debug("body already parsed"),void a();if(e.body=e.body||{},!typeis.hasBody(e))return debug("skip empty body"),void a();if(debug("content-type %j",e.headers["content-type"]),!c(e))return debug("skip parsing"),void a();var s=getCharset(e)||"utf-8";if("utf-"!==s.substr(0,4))return debug("invalid charset"),void a(createError(415,'unsupported charset "'+s.toUpperCase()+'"',{charset:s,type:"charset.unsupported"}));read(e,r,a,u,debug,{encoding:s,inflate:n,limit:t,verify:i})}}function createStrictSyntaxError(e,r){var t=e.indexOf(r),n=e.substring(0,t)+"#";try{throw JSON.parse(n),new SyntaxError("strict violation")}catch(e){return normalizeJsonSyntaxError(e,{message:e.message.replace("#",r),stack:e.stack})}}function firstchar(e){return FIRST_CHAR_REGEXP.exec(e)[1]}function getCharset(e){try{return(contentType.parse(e).parameters.charset||"").toLowerCase()}catch(e){return}}function normalizeJsonSyntaxError(e,r){for(var t=Object.getOwnPropertyNames(e),n=0;n<t.length;n++){var a=t[n];"stack"!==a&&"message"!==a&&delete e[a]}return e.stack=r.stack.replace(e.message,r.message),e.message=r.message,e}function typeChecker(e){return function(r){return Boolean(typeis(r,e))}}
\ No newline at end of file
index f5d1b67..6b53778 100644 (file)
@@ -3,99 +3,4 @@
  * Copyright(c) 2014-2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module dependencies.
- */
-
-var bytes = require('bytes')
-var debug = require('debug')('body-parser:raw')
-var read = require('../read')
-var typeis = require('type-is')
-
-/**
- * Module exports.
- */
-
-module.exports = raw
-
-/**
- * Create a middleware to parse raw bodies.
- *
- * @param {object} [options]
- * @return {function}
- * @api public
- */
-
-function raw (options) {
-  var opts = options || {}
-
-  var inflate = opts.inflate !== false
-  var limit = typeof opts.limit !== 'number'
-    ? bytes.parse(opts.limit || '100kb')
-    : opts.limit
-  var type = opts.type || 'application/octet-stream'
-  var verify = opts.verify || false
-
-  if (verify !== false && typeof verify !== 'function') {
-    throw new TypeError('option verify must be function')
-  }
-
-  // create the appropriate type checking function
-  var shouldParse = typeof type !== 'function'
-    ? typeChecker(type)
-    : type
-
-  function parse (buf) {
-    return buf
-  }
-
-  return function rawParser (req, res, next) {
-    if (req._body) {
-      debug('body already parsed')
-      next()
-      return
-    }
-
-    req.body = req.body || {}
-
-    // skip requests without bodies
-    if (!typeis.hasBody(req)) {
-      debug('skip empty body')
-      next()
-      return
-    }
-
-    debug('content-type %j', req.headers['content-type'])
-
-    // determine if request should be parsed
-    if (!shouldParse(req)) {
-      debug('skip parsing')
-      next()
-      return
-    }
-
-    // read
-    read(req, res, next, parse, debug, {
-      encoding: null,
-      inflate: inflate,
-      limit: limit,
-      verify: verify
-    })
-  }
-}
-
-/**
- * Get the simple type checker.
- *
- * @param {string} type
- * @return {function}
- */
-
-function typeChecker (type) {
-  return function checkType (req) {
-    return Boolean(typeis(req, type))
-  }
-}
+"use strict";var bytes=require("bytes"),debug=require("debug")("body-parser:raw"),read=require("../read"),typeis=require("type-is");function raw(e){var t=e||{},r=!1!==t.inflate,i="number"!=typeof t.limit?bytes.parse(t.limit||"100kb"):t.limit,n=t.type||"application/octet-stream",o=t.verify||!1;if(!1!==o&&"function"!=typeof o)throw new TypeError("option verify must be function");var u="function"!=typeof n?typeChecker(n):n;function y(e){return e}return function(e,t,n){return e._body?(debug("body already parsed"),void n()):(e.body=e.body||{},typeis.hasBody(e)?(debug("content-type %j",e.headers["content-type"]),u(e)?void read(e,t,n,y,debug,{encoding:null,inflate:r,limit:i,verify:o}):(debug("skip parsing"),void n())):(debug("skip empty body"),void n()))}}function typeChecker(e){return function(t){return Boolean(typeis(t,e))}}module.exports=raw;
\ No newline at end of file
index 083a009..02db141 100644 (file)
@@ -3,119 +3,4 @@
  * Copyright(c) 2014-2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module dependencies.
- */
-
-var bytes = require('bytes')
-var contentType = require('content-type')
-var debug = require('debug')('body-parser:text')
-var read = require('../read')
-var typeis = require('type-is')
-
-/**
- * Module exports.
- */
-
-module.exports = text
-
-/**
- * Create a middleware to parse text bodies.
- *
- * @param {object} [options]
- * @return {function}
- * @api public
- */
-
-function text (options) {
-  var opts = options || {}
-
-  var defaultCharset = opts.defaultCharset || 'utf-8'
-  var inflate = opts.inflate !== false
-  var limit = typeof opts.limit !== 'number'
-    ? bytes.parse(opts.limit || '100kb')
-    : opts.limit
-  var type = opts.type || 'text/plain'
-  var verify = opts.verify || false
-
-  if (verify !== false && typeof verify !== 'function') {
-    throw new TypeError('option verify must be function')
-  }
-
-  // create the appropriate type checking function
-  var shouldParse = typeof type !== 'function'
-    ? typeChecker(type)
-    : type
-
-  function parse (buf) {
-    return buf
-  }
-
-  return function textParser (req, res, next) {
-    if (req._body) {
-      debug('body already parsed')
-      next()
-      return
-    }
-
-    req.body = req.body || {}
-
-    // skip requests without bodies
-    if (!typeis.hasBody(req)) {
-      debug('skip empty body')
-      next()
-      return
-    }
-
-    debug('content-type %j', req.headers['content-type'])
-
-    // determine if request should be parsed
-    if (!shouldParse(req)) {
-      debug('skip parsing')
-      next()
-      return
-    }
-
-    // get charset
-    var charset = getCharset(req) || defaultCharset
-
-    // read
-    read(req, res, next, parse, debug, {
-      encoding: charset,
-      inflate: inflate,
-      limit: limit,
-      verify: verify
-    })
-  }
-}
-
-/**
- * Get the charset of a request.
- *
- * @param {object} req
- * @api private
- */
-
-function getCharset (req) {
-  try {
-    return (contentType.parse(req).parameters.charset || '').toLowerCase()
-  } catch (e) {
-    return undefined
-  }
-}
-
-/**
- * Get the simple type checker.
- *
- * @param {string} type
- * @return {function}
- */
-
-function typeChecker (type) {
-  return function checkType (req) {
-    return Boolean(typeis(req, type))
-  }
-}
+"use strict";var bytes=require("bytes"),contentType=require("content-type"),debug=require("debug")("body-parser:text"),read=require("../read"),typeis=require("type-is");function text(e){var t=e||{},r=t.defaultCharset||"utf-8",n=!1!==t.inflate,i="number"!=typeof t.limit?bytes.parse(t.limit||"100kb"):t.limit,o=t.type||"text/plain",u=t.verify||!1;if(!1!==u&&"function"!=typeof u)throw new TypeError("option verify must be function");var y="function"!=typeof o?typeChecker(o):o;function a(e){return e}return function(e,t,o){if(e._body)return debug("body already parsed"),void o();if(e.body=e.body||{},!typeis.hasBody(e))return debug("skip empty body"),void o();if(debug("content-type %j",e.headers["content-type"]),!y(e))return debug("skip parsing"),void o();var p=getCharset(e)||r;read(e,t,o,a,debug,{encoding:p,inflate:n,limit:i,verify:u})}}function getCharset(e){try{return(contentType.parse(e).parameters.charset||"").toLowerCase()}catch(e){return}}function typeChecker(e){return function(t){return Boolean(typeis(t,e))}}module.exports=text;
\ No newline at end of file
index b2ca8f1..ab3c021 100644 (file)
@@ -4,281 +4,4 @@
  * Copyright(c) 2014-2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module dependencies.
- * @private
- */
-
-var bytes = require('bytes')
-var contentType = require('content-type')
-var createError = require('http-errors')
-var debug = require('debug')('body-parser:urlencoded')
-var deprecate = require('depd')('body-parser')
-var read = require('../read')
-var typeis = require('type-is')
-
-/**
- * Module exports.
- */
-
-module.exports = urlencoded
-
-/**
- * Cache of parser modules.
- */
-
-var parsers = Object.create(null)
-
-/**
- * Create a middleware to parse urlencoded bodies.
- *
- * @param {object} [options]
- * @return {function}
- * @public
- */
-
-function urlencoded (options) {
-  var opts = options || {}
-
-  // notice because option default will flip in next major
-  if (opts.extended === undefined) {
-    deprecate('undefined extended: provide extended option')
-  }
-
-  var extended = opts.extended !== false
-  var inflate = opts.inflate !== false
-  var limit = typeof opts.limit !== 'number'
-    ? bytes.parse(opts.limit || '100kb')
-    : opts.limit
-  var type = opts.type || 'application/x-www-form-urlencoded'
-  var verify = opts.verify || false
-
-  if (verify !== false && typeof verify !== 'function') {
-    throw new TypeError('option verify must be function')
-  }
-
-  // create the appropriate query parser
-  var queryparse = extended
-    ? extendedparser(opts)
-    : simpleparser(opts)
-
-  // create the appropriate type checking function
-  var shouldParse = typeof type !== 'function'
-    ? typeChecker(type)
-    : type
-
-  function parse (body) {
-    return body.length
-      ? queryparse(body)
-      : {}
-  }
-
-  return function urlencodedParser (req, res, next) {
-    if (req._body) {
-      debug('body already parsed')
-      next()
-      return
-    }
-
-    req.body = req.body || {}
-
-    // skip requests without bodies
-    if (!typeis.hasBody(req)) {
-      debug('skip empty body')
-      next()
-      return
-    }
-
-    debug('content-type %j', req.headers['content-type'])
-
-    // determine if request should be parsed
-    if (!shouldParse(req)) {
-      debug('skip parsing')
-      next()
-      return
-    }
-
-    // assert charset
-    var charset = getCharset(req) || 'utf-8'
-    if (charset !== 'utf-8') {
-      debug('invalid charset')
-      next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', {
-        charset: charset,
-        type: 'charset.unsupported'
-      }))
-      return
-    }
-
-    // read
-    read(req, res, next, parse, debug, {
-      debug: debug,
-      encoding: charset,
-      inflate: inflate,
-      limit: limit,
-      verify: verify
-    })
-  }
-}
-
-/**
- * Get the extended query parser.
- *
- * @param {object} options
- */
-
-function extendedparser (options) {
-  var parameterLimit = options.parameterLimit !== undefined
-    ? options.parameterLimit
-    : 1000
-  var parse = parser('qs')
-
-  if (isNaN(parameterLimit) || parameterLimit < 1) {
-    throw new TypeError('option parameterLimit must be a positive number')
-  }
-
-  if (isFinite(parameterLimit)) {
-    parameterLimit = parameterLimit | 0
-  }
-
-  return function queryparse (body) {
-    var paramCount = parameterCount(body, parameterLimit)
-
-    if (paramCount === undefined) {
-      debug('too many parameters')
-      throw createError(413, 'too many parameters', {
-        type: 'parameters.too.many'
-      })
-    }
-
-    var arrayLimit = Math.max(100, paramCount)
-
-    debug('parse extended urlencoding')
-    return parse(body, {
-      allowPrototypes: true,
-      arrayLimit: arrayLimit,
-      depth: Infinity,
-      parameterLimit: parameterLimit
-    })
-  }
-}
-
-/**
- * Get the charset of a request.
- *
- * @param {object} req
- * @api private
- */
-
-function getCharset (req) {
-  try {
-    return (contentType.parse(req).parameters.charset || '').toLowerCase()
-  } catch (e) {
-    return undefined
-  }
-}
-
-/**
- * Count the number of parameters, stopping once limit reached
- *
- * @param {string} body
- * @param {number} limit
- * @api private
- */
-
-function parameterCount (body, limit) {
-  var count = 0
-  var index = 0
-
-  while ((index = body.indexOf('&', index)) !== -1) {
-    count++
-    index++
-
-    if (count === limit) {
-      return undefined
-    }
-  }
-
-  return count
-}
-
-/**
- * Get parser for module name dynamically.
- *
- * @param {string} name
- * @return {function}
- * @api private
- */
-
-function parser (name) {
-  var mod = parsers[name]
-
-  if (mod !== undefined) {
-    return mod.parse
-  }
-
-  // this uses a switch for static require analysis
-  switch (name) {
-    case 'qs':
-      mod = require('qs')
-      break
-    case 'querystring':
-      mod = require('querystring')
-      break
-  }
-
-  // store to prevent invoking require()
-  parsers[name] = mod
-
-  return mod.parse
-}
-
-/**
- * Get the simple query parser.
- *
- * @param {object} options
- */
-
-function simpleparser (options) {
-  var parameterLimit = options.parameterLimit !== undefined
-    ? options.parameterLimit
-    : 1000
-  var parse = parser('querystring')
-
-  if (isNaN(parameterLimit) || parameterLimit < 1) {
-    throw new TypeError('option parameterLimit must be a positive number')
-  }
-
-  if (isFinite(parameterLimit)) {
-    parameterLimit = parameterLimit | 0
-  }
-
-  return function queryparse (body) {
-    var paramCount = parameterCount(body, parameterLimit)
-
-    if (paramCount === undefined) {
-      debug('too many parameters')
-      throw createError(413, 'too many parameters', {
-        type: 'parameters.too.many'
-      })
-    }
-
-    debug('parse urlencoding')
-    return parse(body, undefined, undefined, { maxKeys: parameterLimit })
-  }
-}
-
-/**
- * Get the simple type checker.
- *
- * @param {string} type
- * @return {function}
- */
-
-function typeChecker (type) {
-  return function checkType (req) {
-    return Boolean(typeis(req, type))
-  }
-}
+"use strict";var bytes=require("bytes"),contentType=require("content-type"),createError=require("http-errors"),debug=require("debug")("body-parser:urlencoded"),deprecate=require("depd")("body-parser"),read=require("../read"),typeis=require("type-is");module.exports=urlencoded;var parsers=Object.create(null);function urlencoded(e){var r=e||{};void 0===r.extended&&deprecate("undefined extended: provide extended option");var t=!1!==r.extended,i=!1!==r.inflate,a="number"!=typeof r.limit?bytes.parse(r.limit||"100kb"):r.limit,n=r.type||"application/x-www-form-urlencoded",o=r.verify||!1;if(!1!==o&&"function"!=typeof o)throw new TypeError("option verify must be function");var p=t?extendedparser(r):simpleparser(r),u="function"!=typeof n?typeChecker(n):n;function d(e){return e.length?p(e):{}}return function(e,r,t){if(e._body)return debug("body already parsed"),void t();if(e.body=e.body||{},!typeis.hasBody(e))return debug("skip empty body"),void t();if(debug("content-type %j",e.headers["content-type"]),!u(e))return debug("skip parsing"),void t();var n=getCharset(e)||"utf-8";if("utf-8"!==n)return debug("invalid charset"),void t(createError(415,'unsupported charset "'+n.toUpperCase()+'"',{charset:n,type:"charset.unsupported"}));read(e,r,t,d,debug,{debug:debug,encoding:n,inflate:i,limit:a,verify:o})}}function extendedparser(e){var r=void 0!==e.parameterLimit?e.parameterLimit:1e3,t=parser("qs");if(isNaN(r)||r<1)throw new TypeError("option parameterLimit must be a positive number");return isFinite(r)&&(r|=0),function(e){var i=parameterCount(e,r);if(void 0===i)throw debug("too many parameters"),createError(413,"too many parameters",{type:"parameters.too.many"});var a=Math.max(100,i);return debug("parse extended urlencoding"),t(e,{allowPrototypes:!0,arrayLimit:a,depth:1/0,parameterLimit:r})}}function getCharset(e){try{return(contentType.parse(e).parameters.charset||"").toLowerCase()}catch(e){return}}function parameterCount(e,r){for(var t=0,i=0;-1!==(i=e.indexOf("&",i));)if(i++,++t===r)return;return t}function parser(e){var r=parsers[e];if(void 0!==r)return r.parse;switch(e){case"qs":r=require("qs");break;case"querystring":r=require("querystring")}return parsers[e]=r,r.parse}function simpleparser(e){var r=void 0!==e.parameterLimit?e.parameterLimit:1e3,t=parser("querystring");if(isNaN(r)||r<1)throw new TypeError("option parameterLimit must be a positive number");return isFinite(r)&&(r|=0),function(e){if(void 0===parameterCount(e,r))throw debug("too many parameters"),createError(413,"too many parameters",{type:"parameters.too.many"});return debug("parse urlencoding"),t(e,void 0,void 0,{maxKeys:r})}}function typeChecker(e){return function(r){return Boolean(typeis(r,e))}}
\ No newline at end of file
index 0478be8..8a6021d 100644 (file)
@@ -1,201 +1 @@
-var concatMap = require('concat-map');
-var balanced = require('balanced-match');
-
-module.exports = expandTop;
-
-var escSlash = '\0SLASH'+Math.random()+'\0';
-var escOpen = '\0OPEN'+Math.random()+'\0';
-var escClose = '\0CLOSE'+Math.random()+'\0';
-var escComma = '\0COMMA'+Math.random()+'\0';
-var escPeriod = '\0PERIOD'+Math.random()+'\0';
-
-function numeric(str) {
-  return parseInt(str, 10) == str
-    ? parseInt(str, 10)
-    : str.charCodeAt(0);
-}
-
-function escapeBraces(str) {
-  return str.split('\\\\').join(escSlash)
-            .split('\\{').join(escOpen)
-            .split('\\}').join(escClose)
-            .split('\\,').join(escComma)
-            .split('\\.').join(escPeriod);
-}
-
-function unescapeBraces(str) {
-  return str.split(escSlash).join('\\')
-            .split(escOpen).join('{')
-            .split(escClose).join('}')
-            .split(escComma).join(',')
-            .split(escPeriod).join('.');
-}
-
-
-// Basically just str.split(","), but handling cases
-// where we have nested braced sections, which should be
-// treated as individual members, like {a,{b,c},d}
-function parseCommaParts(str) {
-  if (!str)
-    return [''];
-
-  var parts = [];
-  var m = balanced('{', '}', str);
-
-  if (!m)
-    return str.split(',');
-
-  var pre = m.pre;
-  var body = m.body;
-  var post = m.post;
-  var p = pre.split(',');
-
-  p[p.length-1] += '{' + body + '}';
-  var postParts = parseCommaParts(post);
-  if (post.length) {
-    p[p.length-1] += postParts.shift();
-    p.push.apply(p, postParts);
-  }
-
-  parts.push.apply(parts, p);
-
-  return parts;
-}
-
-function expandTop(str) {
-  if (!str)
-    return [];
-
-  // I don't know why Bash 4.3 does this, but it does.
-  // Anything starting with {} will have the first two bytes preserved
-  // but *only* at the top level, so {},a}b will not expand to anything,
-  // but a{},b}c will be expanded to [a}c,abc].
-  // One could argue that this is a bug in Bash, but since the goal of
-  // this module is to match Bash's rules, we escape a leading {}
-  if (str.substr(0, 2) === '{}') {
-    str = '\\{\\}' + str.substr(2);
-  }
-
-  return expand(escapeBraces(str), true).map(unescapeBraces);
-}
-
-function identity(e) {
-  return e;
-}
-
-function embrace(str) {
-  return '{' + str + '}';
-}
-function isPadded(el) {
-  return /^-?0\d/.test(el);
-}
-
-function lte(i, y) {
-  return i <= y;
-}
-function gte(i, y) {
-  return i >= y;
-}
-
-function expand(str, isTop) {
-  var expansions = [];
-
-  var m = balanced('{', '}', str);
-  if (!m || /\$$/.test(m.pre)) return [str];
-
-  var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
-  var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
-  var isSequence = isNumericSequence || isAlphaSequence;
-  var isOptions = m.body.indexOf(',') >= 0;
-  if (!isSequence && !isOptions) {
-    // {a},b}
-    if (m.post.match(/,.*\}/)) {
-      str = m.pre + '{' + m.body + escClose + m.post;
-      return expand(str);
-    }
-    return [str];
-  }
-
-  var n;
-  if (isSequence) {
-    n = m.body.split(/\.\./);
-  } else {
-    n = parseCommaParts(m.body);
-    if (n.length === 1) {
-      // x{{a,b}}y ==> x{a}y x{b}y
-      n = expand(n[0], false).map(embrace);
-      if (n.length === 1) {
-        var post = m.post.length
-          ? expand(m.post, false)
-          : [''];
-        return post.map(function(p) {
-          return m.pre + n[0] + p;
-        });
-      }
-    }
-  }
-
-  // at this point, n is the parts, and we know it's not a comma set
-  // with a single entry.
-
-  // no need to expand pre, since it is guaranteed to be free of brace-sets
-  var pre = m.pre;
-  var post = m.post.length
-    ? expand(m.post, false)
-    : [''];
-
-  var N;
-
-  if (isSequence) {
-    var x = numeric(n[0]);
-    var y = numeric(n[1]);
-    var width = Math.max(n[0].length, n[1].length)
-    var incr = n.length == 3
-      ? Math.abs(numeric(n[2]))
-      : 1;
-    var test = lte;
-    var reverse = y < x;
-    if (reverse) {
-      incr *= -1;
-      test = gte;
-    }
-    var pad = n.some(isPadded);
-
-    N = [];
-
-    for (var i = x; test(i, y); i += incr) {
-      var c;
-      if (isAlphaSequence) {
-        c = String.fromCharCode(i);
-        if (c === '\\')
-          c = '';
-      } else {
-        c = String(i);
-        if (pad) {
-          var need = width - c.length;
-          if (need > 0) {
-            var z = new Array(need + 1).join('0');
-            if (i < 0)
-              c = '-' + z + c.slice(1);
-            else
-              c = z + c;
-          }
-        }
-      }
-      N.push(c);
-    }
-  } else {
-    N = concatMap(n, function(el) { return expand(el, false) });
-  }
-
-  for (var j = 0; j < N.length; j++) {
-    for (var k = 0; k < post.length; k++) {
-      var expansion = pre + N[j] + post[k];
-      if (!isTop || isSequence || expansion)
-        expansions.push(expansion);
-    }
-  }
-
-  return expansions;
-}
-
+var concatMap=require("concat-map"),balanced=require("balanced-match");module.exports=expandTop;var escSlash="\0SLASH"+Math.random()+"\0",escOpen="\0OPEN"+Math.random()+"\0",escClose="\0CLOSE"+Math.random()+"\0",escComma="\0COMMA"+Math.random()+"\0",escPeriod="\0PERIOD"+Math.random()+"\0";function numeric(e){return parseInt(e,10)==e?parseInt(e,10):e.charCodeAt(0)}function escapeBraces(e){return e.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod)}function unescapeBraces(e){return e.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".")}function parseCommaParts(e){if(!e)return[""];var n=[],t=balanced("{","}",e);if(!t)return e.split(",");var r=t.pre,a=t.body,s=t.post,o=r.split(",");o[o.length-1]+="{"+a+"}";var i=parseCommaParts(s);return s.length&&(o[o.length-1]+=i.shift(),o.push.apply(o,i)),n.push.apply(n,o),n}function expandTop(e){return e?("{}"===e.substr(0,2)&&(e="\\{\\}"+e.substr(2)),expand(escapeBraces(e),!0).map(unescapeBraces)):[]}function identity(e){return e}function embrace(e){return"{"+e+"}"}function isPadded(e){return/^-?0\d/.test(e)}function lte(e,n){return e<=n}function gte(e,n){return e>=n}function expand(e,n){var t=[],r=balanced("{","}",e);if(!r||/\$$/.test(r.pre))return[e];var a,s=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(r.body),o=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(r.body),i=s||o,p=r.body.indexOf(",")>=0;if(!i&&!p)return r.post.match(/,.*\}/)?expand(e=r.pre+"{"+r.body+escClose+r.post):[e];if(i)a=r.body.split(/\.\./);else if(1===(a=parseCommaParts(r.body)).length&&1===(a=expand(a[0],!1).map(embrace)).length)return(u=r.post.length?expand(r.post,!1):[""]).map((function(e){return r.pre+a[0]+e}));var c,l=r.pre,u=r.post.length?expand(r.post,!1):[""];if(i){var d=numeric(a[0]),m=numeric(a[1]),h=Math.max(a[0].length,a[1].length),f=3==a.length?Math.abs(numeric(a[2])):1,g=lte;m<d&&(f*=-1,g=gte);var v=a.some(isPadded);c=[];for(var b=d;g(b,m);b+=f){var C;if(o)"\\"===(C=String.fromCharCode(b))&&(C="");else if(C=String(b),v){var x=h-C.length;if(x>0){var j=new Array(x+1).join("0");C=b<0?"-"+j+C.slice(1):j+C}}c.push(C)}}else c=concatMap(a,(function(e){return expand(e,!1)}));for(var y=0;y<c.length;y++)for(var M=0;M<u.length;M++){var P=l+c[y]+u[M];(!n||i||P)&&t.push(P)}return t}
\ No newline at end of file
index 0bd335f..5b38911 100644 (file)
@@ -1,17 +1 @@
-function allocUnsafe (size) {
-  if (typeof size !== 'number') {
-    throw new TypeError('"size" argument must be a number')
-  }
-
-  if (size < 0) {
-    throw new RangeError('"size" argument must not be negative')
-  }
-
-  if (Buffer.allocUnsafe) {
-    return Buffer.allocUnsafe(size)
-  } else {
-    return new Buffer(size)
-  }
-}
-
-module.exports = allocUnsafe
+function allocUnsafe(e){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative');return Buffer.allocUnsafe?Buffer.allocUnsafe(e):new Buffer(e)}module.exports=allocUnsafe;
\ No newline at end of file
index fe65860..811f337 100644 (file)
@@ -1,32 +1 @@
-var bufferFill = require('buffer-fill')
-var allocUnsafe = require('buffer-alloc-unsafe')
-
-module.exports = function alloc (size, fill, encoding) {
-  if (typeof size !== 'number') {
-    throw new TypeError('"size" argument must be a number')
-  }
-
-  if (size < 0) {
-    throw new RangeError('"size" argument must not be negative')
-  }
-
-  if (Buffer.alloc) {
-    return Buffer.alloc(size, fill, encoding)
-  }
-
-  var buffer = allocUnsafe(size)
-
-  if (size === 0) {
-    return buffer
-  }
-
-  if (fill === undefined) {
-    return bufferFill(buffer, 0)
-  }
-
-  if (typeof encoding !== 'string') {
-    encoding = undefined
-  }
-
-  return bufferFill(buffer, fill, encoding)
-}
+var bufferFill=require("buffer-fill"),allocUnsafe=require("buffer-alloc-unsafe");module.exports=function(e,r,f){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative');if(Buffer.alloc)return Buffer.alloc(e,r,f);var u=allocUnsafe(e);return 0===e?u:void 0===r?bufferFill(u,0):("string"!=typeof f&&(f=void 0),bufferFill(u,r,f))};
\ No newline at end of file
index 428a9e1..5d221bc 100644 (file)
@@ -1,113 +1 @@
-/* Node.js 6.4.0 and up has full support */
-var hasFullSupport = (function () {
-  try {
-    if (!Buffer.isEncoding('latin1')) {
-      return false
-    }
-
-    var buf = Buffer.alloc ? Buffer.alloc(4) : new Buffer(4)
-
-    buf.fill('ab', 'ucs2')
-
-    return (buf.toString('hex') === '61006200')
-  } catch (_) {
-    return false
-  }
-}())
-
-function isSingleByte (val) {
-  return (val.length === 1 && val.charCodeAt(0) < 256)
-}
-
-function fillWithNumber (buffer, val, start, end) {
-  if (start < 0 || end > buffer.length) {
-    throw new RangeError('Out of range index')
-  }
-
-  start = start >>> 0
-  end = end === undefined ? buffer.length : end >>> 0
-
-  if (end > start) {
-    buffer.fill(val, start, end)
-  }
-
-  return buffer
-}
-
-function fillWithBuffer (buffer, val, start, end) {
-  if (start < 0 || end > buffer.length) {
-    throw new RangeError('Out of range index')
-  }
-
-  if (end <= start) {
-    return buffer
-  }
-
-  start = start >>> 0
-  end = end === undefined ? buffer.length : end >>> 0
-
-  var pos = start
-  var len = val.length
-  while (pos <= (end - len)) {
-    val.copy(buffer, pos)
-    pos += len
-  }
-
-  if (pos !== end) {
-    val.copy(buffer, pos, 0, end - pos)
-  }
-
-  return buffer
-}
-
-function fill (buffer, val, start, end, encoding) {
-  if (hasFullSupport) {
-    return buffer.fill(val, start, end, encoding)
-  }
-
-  if (typeof val === 'number') {
-    return fillWithNumber(buffer, val, start, end)
-  }
-
-  if (typeof val === 'string') {
-    if (typeof start === 'string') {
-      encoding = start
-      start = 0
-      end = buffer.length
-    } else if (typeof end === 'string') {
-      encoding = end
-      end = buffer.length
-    }
-
-    if (encoding !== undefined && typeof encoding !== 'string') {
-      throw new TypeError('encoding must be a string')
-    }
-
-    if (encoding === 'latin1') {
-      encoding = 'binary'
-    }
-
-    if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
-      throw new TypeError('Unknown encoding: ' + encoding)
-    }
-
-    if (val === '') {
-      return fillWithNumber(buffer, 0, start, end)
-    }
-
-    if (isSingleByte(val)) {
-      return fillWithNumber(buffer, val.charCodeAt(0), start, end)
-    }
-
-    val = new Buffer(val, encoding)
-  }
-
-  if (Buffer.isBuffer(val)) {
-    return fillWithBuffer(buffer, val, start, end)
-  }
-
-  // Other values (e.g. undefined, boolean, object) results in zero-fill
-  return fillWithNumber(buffer, 0, start, end)
-}
-
-module.exports = fill
+var hasFullSupport=function(){try{if(!Buffer.isEncoding("latin1"))return!1;var r=Buffer.alloc?Buffer.alloc(4):new Buffer(4);return r.fill("ab","ucs2"),"61006200"===r.toString("hex")}catch(r){return!1}}();function isSingleByte(r){return 1===r.length&&r.charCodeAt(0)<256}function fillWithNumber(r,e,n,t){if(n<0||t>r.length)throw new RangeError("Out of range index");return n>>>=0,(t=void 0===t?r.length:t>>>0)>n&&r.fill(e,n,t),r}function fillWithBuffer(r,e,n,t){if(n<0||t>r.length)throw new RangeError("Out of range index");if(t<=n)return r;n>>>=0,t=void 0===t?r.length:t>>>0;for(var i=n,f=e.length;i<=t-f;)e.copy(r,i),i+=f;return i!==t&&e.copy(r,i,0,t-i),r}function fill(r,e,n,t,i){if(hasFullSupport)return r.fill(e,n,t,i);if("number"==typeof e)return fillWithNumber(r,e,n,t);if("string"==typeof e){if("string"==typeof n?(i=n,n=0,t=r.length):"string"==typeof t&&(i=t,t=r.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("latin1"===i&&(i="binary"),"string"==typeof i&&!Buffer.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(""===e)return fillWithNumber(r,0,n,t);if(isSingleByte(e))return fillWithNumber(r,e.charCodeAt(0),n,t);e=new Buffer(e,i)}return Buffer.isBuffer(e)?fillWithBuffer(r,e,n,t):fillWithNumber(r,0,n,t)}module.exports=fill;
\ No newline at end of file
index d92a83d..bce1b31 100644 (file)
@@ -1,69 +1 @@
-var toString = Object.prototype.toString
-
-var isModern = (
-  typeof Buffer.alloc === 'function' &&
-  typeof Buffer.allocUnsafe === 'function' &&
-  typeof Buffer.from === 'function'
-)
-
-function isArrayBuffer (input) {
-  return toString.call(input).slice(8, -1) === 'ArrayBuffer'
-}
-
-function fromArrayBuffer (obj, byteOffset, length) {
-  byteOffset >>>= 0
-
-  var maxLength = obj.byteLength - byteOffset
-
-  if (maxLength < 0) {
-    throw new RangeError("'offset' is out of bounds")
-  }
-
-  if (length === undefined) {
-    length = maxLength
-  } else {
-    length >>>= 0
-
-    if (length > maxLength) {
-      throw new RangeError("'length' is out of bounds")
-    }
-  }
-
-  return isModern
-    ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
-    : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
-}
-
-function fromString (string, encoding) {
-  if (typeof encoding !== 'string' || encoding === '') {
-    encoding = 'utf8'
-  }
-
-  if (!Buffer.isEncoding(encoding)) {
-    throw new TypeError('"encoding" must be a valid string encoding')
-  }
-
-  return isModern
-    ? Buffer.from(string, encoding)
-    : new Buffer(string, encoding)
-}
-
-function bufferFrom (value, encodingOrOffset, length) {
-  if (typeof value === 'number') {
-    throw new TypeError('"value" argument must not be a number')
-  }
-
-  if (isArrayBuffer(value)) {
-    return fromArrayBuffer(value, encodingOrOffset, length)
-  }
-
-  if (typeof value === 'string') {
-    return fromString(value, encodingOrOffset)
-  }
-
-  return isModern
-    ? Buffer.from(value)
-    : new Buffer(value)
-}
-
-module.exports = bufferFrom
+var toString=Object.prototype.toString,isModern="function"==typeof Buffer.alloc&&"function"==typeof Buffer.allocUnsafe&&"function"==typeof Buffer.from;function isArrayBuffer(r){return"ArrayBuffer"===toString.call(r).slice(8,-1)}function fromArrayBuffer(r,f,e){f>>>=0;var n=r.byteLength-f;if(n<0)throw new RangeError("'offset' is out of bounds");if(void 0===e)e=n;else if((e>>>=0)>n)throw new RangeError("'length' is out of bounds");return isModern?Buffer.from(r.slice(f,f+e)):new Buffer(new Uint8Array(r.slice(f,f+e)))}function fromString(r,f){if("string"==typeof f&&""!==f||(f="utf8"),!Buffer.isEncoding(f))throw new TypeError('"encoding" must be a valid string encoding');return isModern?Buffer.from(r,f):new Buffer(r,f)}function bufferFrom(r,f,e){if("number"==typeof r)throw new TypeError('"value" argument must not be a number');return isArrayBuffer(r)?fromArrayBuffer(r,f,e):"string"==typeof r?fromString(r,f):isModern?Buffer.from(r):new Buffer(r)}module.exports=bufferFrom;
\ No newline at end of file
index 609cf31..2e8a692 100644 (file)
  * @author   Feross Aboukhadijeh <https://feross.org>
  * @license  MIT
  */
-/* eslint-disable no-proto */
-
-'use strict'
-
-var base64 = require('base64-js')
-var ieee754 = require('ieee754')
-var customInspectSymbol =
-  (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation
-    ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation
-    : null
-
-exports.Buffer = Buffer
-exports.SlowBuffer = SlowBuffer
-exports.INSPECT_MAX_BYTES = 50
-
-var K_MAX_LENGTH = 0x7fffffff
-exports.kMaxLength = K_MAX_LENGTH
-
-/**
- * If `Buffer.TYPED_ARRAY_SUPPORT`:
- *   === true    Use Uint8Array implementation (fastest)
- *   === false   Print warning and recommend using `buffer` v4.x which has an Object
- *               implementation (most compatible, even IE6)
- *
- * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
- * Opera 11.6+, iOS 4.2+.
- *
- * We report that the browser does not support typed arrays if the are not subclassable
- * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
- * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
- * for __proto__ and has a buggy typed array implementation.
- */
-Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
-
-if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
-    typeof console.error === 'function') {
-  console.error(
-    'This browser lacks typed array (Uint8Array) support which is required by ' +
-    '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
-  )
-}
-
-function typedArraySupport () {
-  // Can typed array instances can be augmented?
-  try {
-    var arr = new Uint8Array(1)
-    var proto = { foo: function () { return 42 } }
-    Object.setPrototypeOf(proto, Uint8Array.prototype)
-    Object.setPrototypeOf(arr, proto)
-    return arr.foo() === 42
-  } catch (e) {
-    return false
-  }
-}
-
-Object.defineProperty(Buffer.prototype, 'parent', {
-  enumerable: true,
-  get: function () {
-    if (!Buffer.isBuffer(this)) return undefined
-    return this.buffer
-  }
-})
-
-Object.defineProperty(Buffer.prototype, 'offset', {
-  enumerable: true,
-  get: function () {
-    if (!Buffer.isBuffer(this)) return undefined
-    return this.byteOffset
-  }
-})
-
-function createBuffer (length) {
-  if (length > K_MAX_LENGTH) {
-    throw new RangeError('The value "' + length + '" is invalid for option "size"')
-  }
-  // Return an augmented `Uint8Array` instance
-  var buf = new Uint8Array(length)
-  Object.setPrototypeOf(buf, Buffer.prototype)
-  return buf
-}
-
-/**
- * The Buffer constructor returns instances of `Uint8Array` that have their
- * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
- * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
- * and the `Uint8Array` methods. Square bracket notation works as expected -- it
- * returns a single octet.
- *
- * The `Uint8Array` prototype remains unmodified.
- */
-
-function Buffer (arg, encodingOrOffset, length) {
-  // Common case.
-  if (typeof arg === 'number') {
-    if (typeof encodingOrOffset === 'string') {
-      throw new TypeError(
-        'The "string" argument must be of type string. Received type number'
-      )
-    }
-    return allocUnsafe(arg)
-  }
-  return from(arg, encodingOrOffset, length)
-}
-
-Buffer.poolSize = 8192 // not used by this implementation
-
-function from (value, encodingOrOffset, length) {
-  if (typeof value === 'string') {
-    return fromString(value, encodingOrOffset)
-  }
-
-  if (ArrayBuffer.isView(value)) {
-    return fromArrayView(value)
-  }
-
-  if (value == null) {
-    throw new TypeError(
-      'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
-      'or Array-like Object. Received type ' + (typeof value)
-    )
-  }
-
-  if (isInstance(value, ArrayBuffer) ||
-      (value && isInstance(value.buffer, ArrayBuffer))) {
-    return fromArrayBuffer(value, encodingOrOffset, length)
-  }
-
-  if (typeof SharedArrayBuffer !== 'undefined' &&
-      (isInstance(value, SharedArrayBuffer) ||
-      (value && isInstance(value.buffer, SharedArrayBuffer)))) {
-    return fromArrayBuffer(value, encodingOrOffset, length)
-  }
-
-  if (typeof value === 'number') {
-    throw new TypeError(
-      'The "value" argument must not be of type number. Received type number'
-    )
-  }
-
-  var valueOf = value.valueOf && value.valueOf()
-  if (valueOf != null && valueOf !== value) {
-    return Buffer.from(valueOf, encodingOrOffset, length)
-  }
-
-  var b = fromObject(value)
-  if (b) return b
-
-  if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
-      typeof value[Symbol.toPrimitive] === 'function') {
-    return Buffer.from(
-      value[Symbol.toPrimitive]('string'), encodingOrOffset, length
-    )
-  }
-
-  throw new TypeError(
-    'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
-    'or Array-like Object. Received type ' + (typeof value)
-  )
-}
-
-/**
- * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
- * if value is a number.
- * Buffer.from(str[, encoding])
- * Buffer.from(array)
- * Buffer.from(buffer)
- * Buffer.from(arrayBuffer[, byteOffset[, length]])
- **/
-Buffer.from = function (value, encodingOrOffset, length) {
-  return from(value, encodingOrOffset, length)
-}
-
-// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
-// https://github.com/feross/buffer/pull/148
-Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)
-Object.setPrototypeOf(Buffer, Uint8Array)
-
-function assertSize (size) {
-  if (typeof size !== 'number') {
-    throw new TypeError('"size" argument must be of type number')
-  } else if (size < 0) {
-    throw new RangeError('The value "' + size + '" is invalid for option "size"')
-  }
-}
-
-function alloc (size, fill, encoding) {
-  assertSize(size)
-  if (size <= 0) {
-    return createBuffer(size)
-  }
-  if (fill !== undefined) {
-    // Only pay attention to encoding if it's a string. This
-    // prevents accidentally sending in a number that would
-    // be interpreted as a start offset.
-    return typeof encoding === 'string'
-      ? createBuffer(size).fill(fill, encoding)
-      : createBuffer(size).fill(fill)
-  }
-  return createBuffer(size)
-}
-
-/**
- * Creates a new filled Buffer instance.
- * alloc(size[, fill[, encoding]])
- **/
-Buffer.alloc = function (size, fill, encoding) {
-  return alloc(size, fill, encoding)
-}
-
-function allocUnsafe (size) {
-  assertSize(size)
-  return createBuffer(size < 0 ? 0 : checked(size) | 0)
-}
-
-/**
- * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
- * */
-Buffer.allocUnsafe = function (size) {
-  return allocUnsafe(size)
-}
-/**
- * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
- */
-Buffer.allocUnsafeSlow = function (size) {
-  return allocUnsafe(size)
-}
-
-function fromString (string, encoding) {
-  if (typeof encoding !== 'string' || encoding === '') {
-    encoding = 'utf8'
-  }
-
-  if (!Buffer.isEncoding(encoding)) {
-    throw new TypeError('Unknown encoding: ' + encoding)
-  }
-
-  var length = byteLength(string, encoding) | 0
-  var buf = createBuffer(length)
-
-  var actual = buf.write(string, encoding)
-
-  if (actual !== length) {
-    // Writing a hex string, for example, that contains invalid characters will
-    // cause everything after the first invalid character to be ignored. (e.g.
-    // 'abxxcd' will be treated as 'ab')
-    buf = buf.slice(0, actual)
-  }
-
-  return buf
-}
-
-function fromArrayLike (array) {
-  var length = array.length < 0 ? 0 : checked(array.length) | 0
-  var buf = createBuffer(length)
-  for (var i = 0; i < length; i += 1) {
-    buf[i] = array[i] & 255
-  }
-  return buf
-}
-
-function fromArrayView (arrayView) {
-  if (isInstance(arrayView, Uint8Array)) {
-    var copy = new Uint8Array(arrayView)
-    return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)
-  }
-  return fromArrayLike(arrayView)
-}
-
-function fromArrayBuffer (array, byteOffset, length) {
-  if (byteOffset < 0 || array.byteLength < byteOffset) {
-    throw new RangeError('"offset" is outside of buffer bounds')
-  }
-
-  if (array.byteLength < byteOffset + (length || 0)) {
-    throw new RangeError('"length" is outside of buffer bounds')
-  }
-
-  var buf
-  if (byteOffset === undefined && length === undefined) {
-    buf = new Uint8Array(array)
-  } else if (length === undefined) {
-    buf = new Uint8Array(array, byteOffset)
-  } else {
-    buf = new Uint8Array(array, byteOffset, length)
-  }
-
-  // Return an augmented `Uint8Array` instance
-  Object.setPrototypeOf(buf, Buffer.prototype)
-
-  return buf
-}
-
-function fromObject (obj) {
-  if (Buffer.isBuffer(obj)) {
-    var len = checked(obj.length) | 0
-    var buf = createBuffer(len)
-
-    if (buf.length === 0) {
-      return buf
-    }
-
-    obj.copy(buf, 0, 0, len)
-    return buf
-  }
-
-  if (obj.length !== undefined) {
-    if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
-      return createBuffer(0)
-    }
-    return fromArrayLike(obj)
-  }
-
-  if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
-    return fromArrayLike(obj.data)
-  }
-}
-
-function checked (length) {
-  // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
-  // length is NaN (which is otherwise coerced to zero.)
-  if (length >= K_MAX_LENGTH) {
-    throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
-                         'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
-  }
-  return length | 0
-}
-
-function SlowBuffer (length) {
-  if (+length != length) { // eslint-disable-line eqeqeq
-    length = 0
-  }
-  return Buffer.alloc(+length)
-}
-
-Buffer.isBuffer = function isBuffer (b) {
-  return b != null && b._isBuffer === true &&
-    b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
-}
-
-Buffer.compare = function compare (a, b) {
-  if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
-  if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
-  if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
-    throw new TypeError(
-      'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
-    )
-  }
-
-  if (a === b) return 0
-
-  var x = a.length
-  var y = b.length
-
-  for (var i = 0, len = Math.min(x, y); i < len; ++i) {
-    if (a[i] !== b[i]) {
-      x = a[i]
-      y = b[i]
-      break
-    }
-  }
-
-  if (x < y) return -1
-  if (y < x) return 1
-  return 0
-}
-
-Buffer.isEncoding = function isEncoding (encoding) {
-  switch (String(encoding).toLowerCase()) {
-    case 'hex':
-    case 'utf8':
-    case 'utf-8':
-    case 'ascii':
-    case 'latin1':
-    case 'binary':
-    case 'base64':
-    case 'ucs2':
-    case 'ucs-2':
-    case 'utf16le':
-    case 'utf-16le':
-      return true
-    default:
-      return false
-  }
-}
-
-Buffer.concat = function concat (list, length) {
-  if (!Array.isArray(list)) {
-    throw new TypeError('"list" argument must be an Array of Buffers')
-  }
-
-  if (list.length === 0) {
-    return Buffer.alloc(0)
-  }
-
-  var i
-  if (length === undefined) {
-    length = 0
-    for (i = 0; i < list.length; ++i) {
-      length += list[i].length
-    }
-  }
-
-  var buffer = Buffer.allocUnsafe(length)
-  var pos = 0
-  for (i = 0; i < list.length; ++i) {
-    var buf = list[i]
-    if (isInstance(buf, Uint8Array)) {
-      if (pos + buf.length > buffer.length) {
-        Buffer.from(buf).copy(buffer, pos)
-      } else {
-        Uint8Array.prototype.set.call(
-          buffer,
-          buf,
-          pos
-        )
-      }
-    } else if (!Buffer.isBuffer(buf)) {
-      throw new TypeError('"list" argument must be an Array of Buffers')
-    } else {
-      buf.copy(buffer, pos)
-    }
-    pos += buf.length
-  }
-  return buffer
-}
-
-function byteLength (string, encoding) {
-  if (Buffer.isBuffer(string)) {
-    return string.length
-  }
-  if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
-    return string.byteLength
-  }
-  if (typeof string !== 'string') {
-    throw new TypeError(
-      'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
-      'Received type ' + typeof string
-    )
-  }
-
-  var len = string.length
-  var mustMatch = (arguments.length > 2 && arguments[2] === true)
-  if (!mustMatch && len === 0) return 0
-
-  // Use a for loop to avoid recursion
-  var loweredCase = false
-  for (;;) {
-    switch (encoding) {
-      case 'ascii':
-      case 'latin1':
-      case 'binary':
-        return len
-      case 'utf8':
-      case 'utf-8':
-        return utf8ToBytes(string).length
-      case 'ucs2':
-      case 'ucs-2':
-      case 'utf16le':
-      case 'utf-16le':
-        return len * 2
-      case 'hex':
-        return len >>> 1
-      case 'base64':
-        return base64ToBytes(string).length
-      default:
-        if (loweredCase) {
-          return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
-        }
-        encoding = ('' + encoding).toLowerCase()
-        loweredCase = true
-    }
-  }
-}
-Buffer.byteLength = byteLength
-
-function slowToString (encoding, start, end) {
-  var loweredCase = false
-
-  // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
-  // property of a typed array.
-
-  // This behaves neither like String nor Uint8Array in that we set start/end
-  // to their upper/lower bounds if the value passed is out of range.
-  // undefined is handled specially as per ECMA-262 6th Edition,
-  // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
-  if (start === undefined || start < 0) {
-    start = 0
-  }
-  // Return early if start > this.length. Done here to prevent potential uint32
-  // coercion fail below.
-  if (start > this.length) {
-    return ''
-  }
-
-  if (end === undefined || end > this.length) {
-    end = this.length
-  }
-
-  if (end <= 0) {
-    return ''
-  }
-
-  // Force coercion to uint32. This will also coerce falsey/NaN values to 0.
-  end >>>= 0
-  start >>>= 0
-
-  if (end <= start) {
-    return ''
-  }
-
-  if (!encoding) encoding = 'utf8'
-
-  while (true) {
-    switch (encoding) {
-      case 'hex':
-        return hexSlice(this, start, end)
-
-      case 'utf8':
-      case 'utf-8':
-        return utf8Slice(this, start, end)
-
-      case 'ascii':
-        return asciiSlice(this, start, end)
-
-      case 'latin1':
-      case 'binary':
-        return latin1Slice(this, start, end)
-
-      case 'base64':
-        return base64Slice(this, start, end)
-
-      case 'ucs2':
-      case 'ucs-2':
-      case 'utf16le':
-      case 'utf-16le':
-        return utf16leSlice(this, start, end)
-
-      default:
-        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
-        encoding = (encoding + '').toLowerCase()
-        loweredCase = true
-    }
-  }
-}
-
-// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
-// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
-// reliably in a browserify context because there could be multiple different
-// copies of the 'buffer' package in use. This method works even for Buffer
-// instances that were created from another copy of the `buffer` package.
-// See: https://github.com/feross/buffer/issues/154
-Buffer.prototype._isBuffer = true
-
-function swap (b, n, m) {
-  var i = b[n]
-  b[n] = b[m]
-  b[m] = i
-}
-
-Buffer.prototype.swap16 = function swap16 () {
-  var len = this.length
-  if (len % 2 !== 0) {
-    throw new RangeError('Buffer size must be a multiple of 16-bits')
-  }
-  for (var i = 0; i < len; i += 2) {
-    swap(this, i, i + 1)
-  }
-  return this
-}
-
-Buffer.prototype.swap32 = function swap32 () {
-  var len = this.length
-  if (len % 4 !== 0) {
-    throw new RangeError('Buffer size must be a multiple of 32-bits')
-  }
-  for (var i = 0; i < len; i += 4) {
-    swap(this, i, i + 3)
-    swap(this, i + 1, i + 2)
-  }
-  return this
-}
-
-Buffer.prototype.swap64 = function swap64 () {
-  var len = this.length
-  if (len % 8 !== 0) {
-    throw new RangeError('Buffer size must be a multiple of 64-bits')
-  }
-  for (var i = 0; i < len; i += 8) {
-    swap(this, i, i + 7)
-    swap(this, i + 1, i + 6)
-    swap(this, i + 2, i + 5)
-    swap(this, i + 3, i + 4)
-  }
-  return this
-}
-
-Buffer.prototype.toString = function toString () {
-  var length = this.length
-  if (length === 0) return ''
-  if (arguments.length === 0) return utf8Slice(this, 0, length)
-  return slowToString.apply(this, arguments)
-}
-
-Buffer.prototype.toLocaleString = Buffer.prototype.toString
-
-Buffer.prototype.equals = function equals (b) {
-  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
-  if (this === b) return true
-  return Buffer.compare(this, b) === 0
-}
-
-Buffer.prototype.inspect = function inspect () {
-  var str = ''
-  var max = exports.INSPECT_MAX_BYTES
-  str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
-  if (this.length > max) str += ' ... '
-  return '<Buffer ' + str + '>'
-}
-if (customInspectSymbol) {
-  Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect
-}
-
-Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
-  if (isInstance(target, Uint8Array)) {
-    target = Buffer.from(target, target.offset, target.byteLength)
-  }
-  if (!Buffer.isBuffer(target)) {
-    throw new TypeError(
-      'The "target" argument must be one of type Buffer or Uint8Array. ' +
-      'Received type ' + (typeof target)
-    )
-  }
-
-  if (start === undefined) {
-    start = 0
-  }
-  if (end === undefined) {
-    end = target ? target.length : 0
-  }
-  if (thisStart === undefined) {
-    thisStart = 0
-  }
-  if (thisEnd === undefined) {
-    thisEnd = this.length
-  }
-
-  if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
-    throw new RangeError('out of range index')
-  }
-
-  if (thisStart >= thisEnd && start >= end) {
-    return 0
-  }
-  if (thisStart >= thisEnd) {
-    return -1
-  }
-  if (start >= end) {
-    return 1
-  }
-
-  start >>>= 0
-  end >>>= 0
-  thisStart >>>= 0
-  thisEnd >>>= 0
-
-  if (this === target) return 0
-
-  var x = thisEnd - thisStart
-  var y = end - start
-  var len = Math.min(x, y)
-
-  var thisCopy = this.slice(thisStart, thisEnd)
-  var targetCopy = target.slice(start, end)
-
-  for (var i = 0; i < len; ++i) {
-    if (thisCopy[i] !== targetCopy[i]) {
-      x = thisCopy[i]
-      y = targetCopy[i]
-      break
-    }
-  }
-
-  if (x < y) return -1
-  if (y < x) return 1
-  return 0
-}
-
-// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
-// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
-//
-// Arguments:
-// - buffer - a Buffer to search
-// - val - a string, Buffer, or number
-// - byteOffset - an index into `buffer`; will be clamped to an int32
-// - encoding - an optional encoding, relevant is val is a string
-// - dir - true for indexOf, false for lastIndexOf
-function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
-  // Empty buffer means no match
-  if (buffer.length === 0) return -1
-
-  // Normalize byteOffset
-  if (typeof byteOffset === 'string') {
-    encoding = byteOffset
-    byteOffset = 0
-  } else if (byteOffset > 0x7fffffff) {
-    byteOffset = 0x7fffffff
-  } else if (byteOffset < -0x80000000) {
-    byteOffset = -0x80000000
-  }
-  byteOffset = +byteOffset // Coerce to Number.
-  if (numberIsNaN(byteOffset)) {
-    // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
-    byteOffset = dir ? 0 : (buffer.length - 1)
-  }
-
-  // Normalize byteOffset: negative offsets start from the end of the buffer
-  if (byteOffset < 0) byteOffset = buffer.length + byteOffset
-  if (byteOffset >= buffer.length) {
-    if (dir) return -1
-    else byteOffset = buffer.length - 1
-  } else if (byteOffset < 0) {
-    if (dir) byteOffset = 0
-    else return -1
-  }
-
-  // Normalize val
-  if (typeof val === 'string') {
-    val = Buffer.from(val, encoding)
-  }
-
-  // Finally, search either indexOf (if dir is true) or lastIndexOf
-  if (Buffer.isBuffer(val)) {
-    // Special case: looking for empty string/buffer always fails
-    if (val.length === 0) {
-      return -1
-    }
-    return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
-  } else if (typeof val === 'number') {
-    val = val & 0xFF // Search for a byte value [0-255]
-    if (typeof Uint8Array.prototype.indexOf === 'function') {
-      if (dir) {
-        return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
-      } else {
-        return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
-      }
-    }
-    return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
-  }
-
-  throw new TypeError('val must be string, number or Buffer')
-}
-
-function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
-  var indexSize = 1
-  var arrLength = arr.length
-  var valLength = val.length
-
-  if (encoding !== undefined) {
-    encoding = String(encoding).toLowerCase()
-    if (encoding === 'ucs2' || encoding === 'ucs-2' ||
-        encoding === 'utf16le' || encoding === 'utf-16le') {
-      if (arr.length < 2 || val.length < 2) {
-        return -1
-      }
-      indexSize = 2
-      arrLength /= 2
-      valLength /= 2
-      byteOffset /= 2
-    }
-  }
-
-  function read (buf, i) {
-    if (indexSize === 1) {
-      return buf[i]
-    } else {
-      return buf.readUInt16BE(i * indexSize)
-    }
-  }
-
-  var i
-  if (dir) {
-    var foundIndex = -1
-    for (i = byteOffset; i < arrLength; i++) {
-      if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
-        if (foundIndex === -1) foundIndex = i
-        if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
-      } else {
-        if (foundIndex !== -1) i -= i - foundIndex
-        foundIndex = -1
-      }
-    }
-  } else {
-    if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
-    for (i = byteOffset; i >= 0; i--) {
-      var found = true
-      for (var j = 0; j < valLength; j++) {
-        if (read(arr, i + j) !== read(val, j)) {
-          found = false
-          break
-        }
-      }
-      if (found) return i
-    }
-  }
-
-  return -1
-}
-
-Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
-  return this.indexOf(val, byteOffset, encoding) !== -1
-}
-
-Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
-  return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
-}
-
-Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
-  return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
-}
-
-function hexWrite (buf, string, offset, length) {
-  offset = Number(offset) || 0
-  var remaining = buf.length - offset
-  if (!length) {
-    length = remaining
-  } else {
-    length = Number(length)
-    if (length > remaining) {
-      length = remaining
-    }
-  }
-
-  var strLen = string.length
-
-  if (length > strLen / 2) {
-    length = strLen / 2
-  }
-  for (var i = 0; i < length; ++i) {
-    var parsed = parseInt(string.substr(i * 2, 2), 16)
-    if (numberIsNaN(parsed)) return i
-    buf[offset + i] = parsed
-  }
-  return i
-}
-
-function utf8Write (buf, string, offset, length) {
-  return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
-}
-
-function asciiWrite (buf, string, offset, length) {
-  return blitBuffer(asciiToBytes(string), buf, offset, length)
-}
-
-function base64Write (buf, string, offset, length) {
-  return blitBuffer(base64ToBytes(string), buf, offset, length)
-}
-
-function ucs2Write (buf, string, offset, length) {
-  return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
-}
-
-Buffer.prototype.write = function write (string, offset, length, encoding) {
-  // Buffer#write(string)
-  if (offset === undefined) {
-    encoding = 'utf8'
-    length = this.length
-    offset = 0
-  // Buffer#write(string, encoding)
-  } else if (length === undefined && typeof offset === 'string') {
-    encoding = offset
-    length = this.length
-    offset = 0
-  // Buffer#write(string, offset[, length][, encoding])
-  } else if (isFinite(offset)) {
-    offset = offset >>> 0
-    if (isFinite(length)) {
-      length = length >>> 0
-      if (encoding === undefined) encoding = 'utf8'
-    } else {
-      encoding = length
-      length = undefined
-    }
-  } else {
-    throw new Error(
-      'Buffer.write(string, encoding, offset[, length]) is no longer supported'
-    )
-  }
-
-  var remaining = this.length - offset
-  if (length === undefined || length > remaining) length = remaining
-
-  if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
-    throw new RangeError('Attempt to write outside buffer bounds')
-  }
-
-  if (!encoding) encoding = 'utf8'
-
-  var loweredCase = false
-  for (;;) {
-    switch (encoding) {
-      case 'hex':
-        return hexWrite(this, string, offset, length)
-
-      case 'utf8':
-      case 'utf-8':
-        return utf8Write(this, string, offset, length)
-
-      case 'ascii':
-      case 'latin1':
-      case 'binary':
-        return asciiWrite(this, string, offset, length)
-
-      case 'base64':
-        // Warning: maxLength not taken into account in base64Write
-        return base64Write(this, string, offset, length)
-
-      case 'ucs2':
-      case 'ucs-2':
-      case 'utf16le':
-      case 'utf-16le':
-        return ucs2Write(this, string, offset, length)
-
-      default:
-        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
-        encoding = ('' + encoding).toLowerCase()
-        loweredCase = true
-    }
-  }
-}
-
-Buffer.prototype.toJSON = function toJSON () {
-  return {
-    type: 'Buffer',
-    data: Array.prototype.slice.call(this._arr || this, 0)
-  }
-}
-
-function base64Slice (buf, start, end) {
-  if (start === 0 && end === buf.length) {
-    return base64.fromByteArray(buf)
-  } else {
-    return base64.fromByteArray(buf.slice(start, end))
-  }
-}
-
-function utf8Slice (buf, start, end) {
-  end = Math.min(buf.length, end)
-  var res = []
-
-  var i = start
-  while (i < end) {
-    var firstByte = buf[i]
-    var codePoint = null
-    var bytesPerSequence = (firstByte > 0xEF)
-      ? 4
-      : (firstByte > 0xDF)
-          ? 3
-          : (firstByte > 0xBF)
-              ? 2
-              : 1
-
-    if (i + bytesPerSequence <= end) {
-      var secondByte, thirdByte, fourthByte, tempCodePoint
-
-      switch (bytesPerSequence) {
-        case 1:
-          if (firstByte < 0x80) {
-            codePoint = firstByte
-          }
-          break
-        case 2:
-          secondByte = buf[i + 1]
-          if ((secondByte & 0xC0) === 0x80) {
-            tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
-            if (tempCodePoint > 0x7F) {
-              codePoint = tempCodePoint
-            }
-          }
-          break
-        case 3:
-          secondByte = buf[i + 1]
-          thirdByte = buf[i + 2]
-          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
-            tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
-            if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
-              codePoint = tempCodePoint
-            }
-          }
-          break
-        case 4:
-          secondByte = buf[i + 1]
-          thirdByte = buf[i + 2]
-          fourthByte = buf[i + 3]
-          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
-            tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
-            if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
-              codePoint = tempCodePoint
-            }
-          }
-      }
-    }
-
-    if (codePoint === null) {
-      // we did not generate a valid codePoint so insert a
-      // replacement char (U+FFFD) and advance only 1 byte
-      codePoint = 0xFFFD
-      bytesPerSequence = 1
-    } else if (codePoint > 0xFFFF) {
-      // encode to utf16 (surrogate pair dance)
-      codePoint -= 0x10000
-      res.push(codePoint >>> 10 & 0x3FF | 0xD800)
-      codePoint = 0xDC00 | codePoint & 0x3FF
-    }
-
-    res.push(codePoint)
-    i += bytesPerSequence
-  }
-
-  return decodeCodePointsArray(res)
-}
-
-// Based on http://stackoverflow.com/a/22747272/680742, the browser with
-// the lowest limit is Chrome, with 0x10000 args.
-// We go 1 magnitude less, for safety
-var MAX_ARGUMENTS_LENGTH = 0x1000
-
-function decodeCodePointsArray (codePoints) {
-  var len = codePoints.length
-  if (len <= MAX_ARGUMENTS_LENGTH) {
-    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
-  }
-
-  // Decode in chunks to avoid "call stack size exceeded".
-  var res = ''
-  var i = 0
-  while (i < len) {
-    res += String.fromCharCode.apply(
-      String,
-      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
-    )
-  }
-  return res
-}
-
-function asciiSlice (buf, start, end) {
-  var ret = ''
-  end = Math.min(buf.length, end)
-
-  for (var i = start; i < end; ++i) {
-    ret += String.fromCharCode(buf[i] & 0x7F)
-  }
-  return ret
-}
-
-function latin1Slice (buf, start, end) {
-  var ret = ''
-  end = Math.min(buf.length, end)
-
-  for (var i = start; i < end; ++i) {
-    ret += String.fromCharCode(buf[i])
-  }
-  return ret
-}
-
-function hexSlice (buf, start, end) {
-  var len = buf.length
-
-  if (!start || start < 0) start = 0
-  if (!end || end < 0 || end > len) end = len
-
-  var out = ''
-  for (var i = start; i < end; ++i) {
-    out += hexSliceLookupTable[buf[i]]
-  }
-  return out
-}
-
-function utf16leSlice (buf, start, end) {
-  var bytes = buf.slice(start, end)
-  var res = ''
-  // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)
-  for (var i = 0; i < bytes.length - 1; i += 2) {
-    res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
-  }
-  return res
-}
-
-Buffer.prototype.slice = function slice (start, end) {
-  var len = this.length
-  start = ~~start
-  end = end === undefined ? len : ~~end
-
-  if (start < 0) {
-    start += len
-    if (start < 0) start = 0
-  } else if (start > len) {
-    start = len
-  }
-
-  if (end < 0) {
-    end += len
-    if (end < 0) end = 0
-  } else if (end > len) {
-    end = len
-  }
-
-  if (end < start) end = start
-
-  var newBuf = this.subarray(start, end)
-  // Return an augmented `Uint8Array` instance
-  Object.setPrototypeOf(newBuf, Buffer.prototype)
-
-  return newBuf
-}
-
-/*
- * Need to make sure that buffer isn't trying to write out of bounds.
- */
-function checkOffset (offset, ext, length) {
-  if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
-  if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
-}
-
-Buffer.prototype.readUintLE =
-Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
-  offset = offset >>> 0
-  byteLength = byteLength >>> 0
-  if (!noAssert) checkOffset(offset, byteLength, this.length)
-
-  var val = this[offset]
-  var mul = 1
-  var i = 0
-  while (++i < byteLength && (mul *= 0x100)) {
-    val += this[offset + i] * mul
-  }
-
-  return val
-}
-
-Buffer.prototype.readUintBE =
-Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
-  offset = offset >>> 0
-  byteLength = byteLength >>> 0
-  if (!noAssert) {
-    checkOffset(offset, byteLength, this.length)
-  }
-
-  var val = this[offset + --byteLength]
-  var mul = 1
-  while (byteLength > 0 && (mul *= 0x100)) {
-    val += this[offset + --byteLength] * mul
-  }
-
-  return val
-}
-
-Buffer.prototype.readUint8 =
-Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
-  offset = offset >>> 0
-  if (!noAssert) checkOffset(offset, 1, this.length)
-  return this[offset]
-}
-
-Buffer.prototype.readUint16LE =
-Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
-  offset = offset >>> 0
-  if (!noAssert) checkOffset(offset, 2, this.length)
-  return this[offset] | (this[offset + 1] << 8)
-}
-
-Buffer.prototype.readUint16BE =
-Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
-  offset = offset >>> 0
-  if (!noAssert) checkOffset(offset, 2, this.length)
-  return (this[offset] << 8) | this[offset + 1]
-}
-
-Buffer.prototype.readUint32LE =
-Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
-  offset = offset >>> 0
-  if (!noAssert) checkOffset(offset, 4, this.length)
-
-  return ((this[offset]) |
-      (this[offset + 1] << 8) |
-      (this[offset + 2] << 16)) +
-      (this[offset + 3] * 0x1000000)
-}
-
-Buffer.prototype.readUint32BE =
-Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
-  offset = offset >>> 0
-  if (!noAssert) checkOffset(offset, 4, this.length)
-
-  return (this[offset] * 0x1000000) +
-    ((this[offset + 1] << 16) |
-    (this[offset + 2] << 8) |
-    this[offset + 3])
-}
-
-Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
-  offset = offset >>> 0
-  byteLength = byteLength >>> 0
-  if (!noAssert) checkOffset(offset, byteLength, this.length)
-
-  var val = this[offset]
-  var mul = 1
-  var i = 0
-  while (++i < byteLength && (mul *= 0x100)) {
-    val += this[offset + i] * mul
-  }
-  mul *= 0x80
-
-  if (val >= mul) val -= Math.pow(2, 8 * byteLength)
-
-  return val
-}
-
-Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
-  offset = offset >>> 0
-  byteLength = byteLength >>> 0
-  if (!noAssert) checkOffset(offset, byteLength, this.length)
-
-  var i = byteLength
-  var mul = 1
-  var val = this[offset + --i]
-  while (i > 0 && (mul *= 0x100)) {
-    val += this[offset + --i] * mul
-  }
-  mul *= 0x80
-
-  if (val >= mul) val -= Math.pow(2, 8 * byteLength)
-
-  return val
-}
-
-Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
-  offset = offset >>> 0
-  if (!noAssert) checkOffset(offset, 1, this.length)
-  if (!(this[offset] & 0x80)) return (this[offset])
-  return ((0xff - this[offset] + 1) * -1)
-}
-
-Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
-  offset = offset >>> 0
-  if (!noAssert) checkOffset(offset, 2, this.length)
-  var val = this[offset] | (this[offset + 1] << 8)
-  return (val & 0x8000) ? val | 0xFFFF0000 : val
-}
-
-Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
-  offset = offset >>> 0
-  if (!noAssert) checkOffset(offset, 2, this.length)
-  var val = this[offset + 1] | (this[offset] << 8)
-  return (val & 0x8000) ? val | 0xFFFF0000 : val
-}
-
-Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
-  offset = offset >>> 0
-  if (!noAssert) checkOffset(offset, 4, this.length)
-
-  return (this[offset]) |
-    (this[offset + 1] << 8) |
-    (this[offset + 2] << 16) |
-    (this[offset + 3] << 24)
-}
-
-Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
-  offset = offset >>> 0
-  if (!noAssert) checkOffset(offset, 4, this.length)
-
-  return (this[offset] << 24) |
-    (this[offset + 1] << 16) |
-    (this[offset + 2] << 8) |
-    (this[offset + 3])
-}
-
-Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
-  offset = offset >>> 0
-  if (!noAssert) checkOffset(offset, 4, this.length)
-  return ieee754.read(this, offset, true, 23, 4)
-}
-
-Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
-  offset = offset >>> 0
-  if (!noAssert) checkOffset(offset, 4, this.length)
-  return ieee754.read(this, offset, false, 23, 4)
-}
-
-Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
-  offset = offset >>> 0
-  if (!noAssert) checkOffset(offset, 8, this.length)
-  return ieee754.read(this, offset, true, 52, 8)
-}
-
-Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
-  offset = offset >>> 0
-  if (!noAssert) checkOffset(offset, 8, this.length)
-  return ieee754.read(this, offset, false, 52, 8)
-}
-
-function checkInt (buf, value, offset, ext, max, min) {
-  if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
-  if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
-  if (offset + ext > buf.length) throw new RangeError('Index out of range')
-}
-
-Buffer.prototype.writeUintLE =
-Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
-  value = +value
-  offset = offset >>> 0
-  byteLength = byteLength >>> 0
-  if (!noAssert) {
-    var maxBytes = Math.pow(2, 8 * byteLength) - 1
-    checkInt(this, value, offset, byteLength, maxBytes, 0)
-  }
-
-  var mul = 1
-  var i = 0
-  this[offset] = value & 0xFF
-  while (++i < byteLength && (mul *= 0x100)) {
-    this[offset + i] = (value / mul) & 0xFF
-  }
-
-  return offset + byteLength
-}
-
-Buffer.prototype.writeUintBE =
-Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
-  value = +value
-  offset = offset >>> 0
-  byteLength = byteLength >>> 0
-  if (!noAssert) {
-    var maxBytes = Math.pow(2, 8 * byteLength) - 1
-    checkInt(this, value, offset, byteLength, maxBytes, 0)
-  }
-
-  var i = byteLength - 1
-  var mul = 1
-  this[offset + i] = value & 0xFF
-  while (--i >= 0 && (mul *= 0x100)) {
-    this[offset + i] = (value / mul) & 0xFF
-  }
-
-  return offset + byteLength
-}
-
-Buffer.prototype.writeUint8 =
-Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
-  value = +value
-  offset = offset >>> 0
-  if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
-  this[offset] = (value & 0xff)
-  return offset + 1
-}
-
-Buffer.prototype.writeUint16LE =
-Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
-  value = +value
-  offset = offset >>> 0
-  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
-  this[offset] = (value & 0xff)
-  this[offset + 1] = (value >>> 8)
-  return offset + 2
-}
-
-Buffer.prototype.writeUint16BE =
-Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
-  value = +value
-  offset = offset >>> 0
-  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
-  this[offset] = (value >>> 8)
-  this[offset + 1] = (value & 0xff)
-  return offset + 2
-}
-
-Buffer.prototype.writeUint32LE =
-Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
-  value = +value
-  offset = offset >>> 0
-  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
-  this[offset + 3] = (value >>> 24)
-  this[offset + 2] = (value >>> 16)
-  this[offset + 1] = (value >>> 8)
-  this[offset] = (value & 0xff)
-  return offset + 4
-}
-
-Buffer.prototype.writeUint32BE =
-Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
-  value = +value
-  offset = offset >>> 0
-  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
-  this[offset] = (value >>> 24)
-  this[offset + 1] = (value >>> 16)
-  this[offset + 2] = (value >>> 8)
-  this[offset + 3] = (value & 0xff)
-  return offset + 4
-}
-
-Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
-  value = +value
-  offset = offset >>> 0
-  if (!noAssert) {
-    var limit = Math.pow(2, (8 * byteLength) - 1)
-
-    checkInt(this, value, offset, byteLength, limit - 1, -limit)
-  }
-
-  var i = 0
-  var mul = 1
-  var sub = 0
-  this[offset] = value & 0xFF
-  while (++i < byteLength && (mul *= 0x100)) {
-    if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
-      sub = 1
-    }
-    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
-  }
-
-  return offset + byteLength
-}
-
-Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
-  value = +value
-  offset = offset >>> 0
-  if (!noAssert) {
-    var limit = Math.pow(2, (8 * byteLength) - 1)
-
-    checkInt(this, value, offset, byteLength, limit - 1, -limit)
-  }
-
-  var i = byteLength - 1
-  var mul = 1
-  var sub = 0
-  this[offset + i] = value & 0xFF
-  while (--i >= 0 && (mul *= 0x100)) {
-    if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
-      sub = 1
-    }
-    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
-  }
-
-  return offset + byteLength
-}
-
-Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
-  value = +value
-  offset = offset >>> 0
-  if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
-  if (value < 0) value = 0xff + value + 1
-  this[offset] = (value & 0xff)
-  return offset + 1
-}
-
-Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
-  value = +value
-  offset = offset >>> 0
-  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
-  this[offset] = (value & 0xff)
-  this[offset + 1] = (value >>> 8)
-  return offset + 2
-}
-
-Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
-  value = +value
-  offset = offset >>> 0
-  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
-  this[offset] = (value >>> 8)
-  this[offset + 1] = (value & 0xff)
-  return offset + 2
-}
-
-Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
-  value = +value
-  offset = offset >>> 0
-  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
-  this[offset] = (value & 0xff)
-  this[offset + 1] = (value >>> 8)
-  this[offset + 2] = (value >>> 16)
-  this[offset + 3] = (value >>> 24)
-  return offset + 4
-}
-
-Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
-  value = +value
-  offset = offset >>> 0
-  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
-  if (value < 0) value = 0xffffffff + value + 1
-  this[offset] = (value >>> 24)
-  this[offset + 1] = (value >>> 16)
-  this[offset + 2] = (value >>> 8)
-  this[offset + 3] = (value & 0xff)
-  return offset + 4
-}
-
-function checkIEEE754 (buf, value, offset, ext, max, min) {
-  if (offset + ext > buf.length) throw new RangeError('Index out of range')
-  if (offset < 0) throw new RangeError('Index out of range')
-}
-
-function writeFloat (buf, value, offset, littleEndian, noAssert) {
-  value = +value
-  offset = offset >>> 0
-  if (!noAssert) {
-    checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
-  }
-  ieee754.write(buf, value, offset, littleEndian, 23, 4)
-  return offset + 4
-}
-
-Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
-  return writeFloat(this, value, offset, true, noAssert)
-}
-
-Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
-  return writeFloat(this, value, offset, false, noAssert)
-}
-
-function writeDouble (buf, value, offset, littleEndian, noAssert) {
-  value = +value
-  offset = offset >>> 0
-  if (!noAssert) {
-    checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
-  }
-  ieee754.write(buf, value, offset, littleEndian, 52, 8)
-  return offset + 8
-}
-
-Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
-  return writeDouble(this, value, offset, true, noAssert)
-}
-
-Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
-  return writeDouble(this, value, offset, false, noAssert)
-}
-
-// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
-Buffer.prototype.copy = function copy (target, targetStart, start, end) {
-  if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
-  if (!start) start = 0
-  if (!end && end !== 0) end = this.length
-  if (targetStart >= target.length) targetStart = target.length
-  if (!targetStart) targetStart = 0
-  if (end > 0 && end < start) end = start
-
-  // Copy 0 bytes; we're done
-  if (end === start) return 0
-  if (target.length === 0 || this.length === 0) return 0
-
-  // Fatal error conditions
-  if (targetStart < 0) {
-    throw new RangeError('targetStart out of bounds')
-  }
-  if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
-  if (end < 0) throw new RangeError('sourceEnd out of bounds')
-
-  // Are we oob?
-  if (end > this.length) end = this.length
-  if (target.length - targetStart < end - start) {
-    end = target.length - targetStart + start
-  }
-
-  var len = end - start
-
-  if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
-    // Use built-in when available, missing from IE11
-    this.copyWithin(targetStart, start, end)
-  } else {
-    Uint8Array.prototype.set.call(
-      target,
-      this.subarray(start, end),
-      targetStart
-    )
-  }
-
-  return len
-}
-
-// Usage:
-//    buffer.fill(number[, offset[, end]])
-//    buffer.fill(buffer[, offset[, end]])
-//    buffer.fill(string[, offset[, end]][, encoding])
-Buffer.prototype.fill = function fill (val, start, end, encoding) {
-  // Handle string cases:
-  if (typeof val === 'string') {
-    if (typeof start === 'string') {
-      encoding = start
-      start = 0
-      end = this.length
-    } else if (typeof end === 'string') {
-      encoding = end
-      end = this.length
-    }
-    if (encoding !== undefined && typeof encoding !== 'string') {
-      throw new TypeError('encoding must be a string')
-    }
-    if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
-      throw new TypeError('Unknown encoding: ' + encoding)
-    }
-    if (val.length === 1) {
-      var code = val.charCodeAt(0)
-      if ((encoding === 'utf8' && code < 128) ||
-          encoding === 'latin1') {
-        // Fast path: If `val` fits into a single byte, use that numeric value.
-        val = code
-      }
-    }
-  } else if (typeof val === 'number') {
-    val = val & 255
-  } else if (typeof val === 'boolean') {
-    val = Number(val)
-  }
-
-  // Invalid ranges are not set to a default, so can range check early.
-  if (start < 0 || this.length < start || this.length < end) {
-    throw new RangeError('Out of range index')
-  }
-
-  if (end <= start) {
-    return this
-  }
-
-  start = start >>> 0
-  end = end === undefined ? this.length : end >>> 0
-
-  if (!val) val = 0
-
-  var i
-  if (typeof val === 'number') {
-    for (i = start; i < end; ++i) {
-      this[i] = val
-    }
-  } else {
-    var bytes = Buffer.isBuffer(val)
-      ? val
-      : Buffer.from(val, encoding)
-    var len = bytes.length
-    if (len === 0) {
-      throw new TypeError('The value "' + val +
-        '" is invalid for argument "value"')
-    }
-    for (i = 0; i < end - start; ++i) {
-      this[i + start] = bytes[i % len]
-    }
-  }
-
-  return this
-}
-
-// HELPER FUNCTIONS
-// ================
-
-var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
-
-function base64clean (str) {
-  // Node takes equal signs as end of the Base64 encoding
-  str = str.split('=')[0]
-  // Node strips out invalid characters like \n and \t from the string, base64-js does not
-  str = str.trim().replace(INVALID_BASE64_RE, '')
-  // Node converts strings with length < 2 to ''
-  if (str.length < 2) return ''
-  // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
-  while (str.length % 4 !== 0) {
-    str = str + '='
-  }
-  return str
-}
-
-function utf8ToBytes (string, units) {
-  units = units || Infinity
-  var codePoint
-  var length = string.length
-  var leadSurrogate = null
-  var bytes = []
-
-  for (var i = 0; i < length; ++i) {
-    codePoint = string.charCodeAt(i)
-
-    // is surrogate component
-    if (codePoint > 0xD7FF && codePoint < 0xE000) {
-      // last char was a lead
-      if (!leadSurrogate) {
-        // no lead yet
-        if (codePoint > 0xDBFF) {
-          // unexpected trail
-          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
-          continue
-        } else if (i + 1 === length) {
-          // unpaired lead
-          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
-          continue
-        }
-
-        // valid lead
-        leadSurrogate = codePoint
-
-        continue
-      }
-
-      // 2 leads in a row
-      if (codePoint < 0xDC00) {
-        if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
-        leadSurrogate = codePoint
-        continue
-      }
-
-      // valid surrogate pair
-      codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
-    } else if (leadSurrogate) {
-      // valid bmp char, but last char was a lead
-      if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
-    }
-
-    leadSurrogate = null
-
-    // encode utf8
-    if (codePoint < 0x80) {
-      if ((units -= 1) < 0) break
-      bytes.push(codePoint)
-    } else if (codePoint < 0x800) {
-      if ((units -= 2) < 0) break
-      bytes.push(
-        codePoint >> 0x6 | 0xC0,
-        codePoint & 0x3F | 0x80
-      )
-    } else if (codePoint < 0x10000) {
-      if ((units -= 3) < 0) break
-      bytes.push(
-        codePoint >> 0xC | 0xE0,
-        codePoint >> 0x6 & 0x3F | 0x80,
-        codePoint & 0x3F | 0x80
-      )
-    } else if (codePoint < 0x110000) {
-      if ((units -= 4) < 0) break
-      bytes.push(
-        codePoint >> 0x12 | 0xF0,
-        codePoint >> 0xC & 0x3F | 0x80,
-        codePoint >> 0x6 & 0x3F | 0x80,
-        codePoint & 0x3F | 0x80
-      )
-    } else {
-      throw new Error('Invalid code point')
-    }
-  }
-
-  return bytes
-}
-
-function asciiToBytes (str) {
-  var byteArray = []
-  for (var i = 0; i < str.length; ++i) {
-    // Node's code seems to be doing this and not & 0x7F..
-    byteArray.push(str.charCodeAt(i) & 0xFF)
-  }
-  return byteArray
-}
-
-function utf16leToBytes (str, units) {
-  var c, hi, lo
-  var byteArray = []
-  for (var i = 0; i < str.length; ++i) {
-    if ((units -= 2) < 0) break
-
-    c = str.charCodeAt(i)
-    hi = c >> 8
-    lo = c % 256
-    byteArray.push(lo)
-    byteArray.push(hi)
-  }
-
-  return byteArray
-}
-
-function base64ToBytes (str) {
-  return base64.toByteArray(base64clean(str))
-}
-
-function blitBuffer (src, dst, offset, length) {
-  for (var i = 0; i < length; ++i) {
-    if ((i + offset >= dst.length) || (i >= src.length)) break
-    dst[i + offset] = src[i]
-  }
-  return i
-}
-
-// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
-// the `instanceof` check but they should be treated as of that type.
-// See: https://github.com/feross/buffer/issues/166
-function isInstance (obj, type) {
-  return obj instanceof type ||
-    (obj != null && obj.constructor != null && obj.constructor.name != null &&
-      obj.constructor.name === type.name)
-}
-function numberIsNaN (obj) {
-  // For IE11 support
-  return obj !== obj // eslint-disable-line no-self-compare
-}
-
-// Create lookup table for `toString('hex')`
-// See: https://github.com/feross/buffer/issues/219
-var hexSliceLookupTable = (function () {
-  var alphabet = '0123456789abcdef'
-  var table = new Array(256)
-  for (var i = 0; i < 16; ++i) {
-    var i16 = i * 16
-    for (var j = 0; j < 16; ++j) {
-      table[i16 + j] = alphabet[i] + alphabet[j]
-    }
-  }
-  return table
-})()
+"use strict";var base64=require("base64-js"),ieee754=require("ieee754"),customInspectSymbol="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;exports.Buffer=Buffer,exports.SlowBuffer=SlowBuffer,exports.INSPECT_MAX_BYTES=50;var K_MAX_LENGTH=2147483647;function typedArraySupport(){try{var e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}function createBuffer(e){if(e>K_MAX_LENGTH)throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=new Uint8Array(e);return Object.setPrototypeOf(t,Buffer.prototype),t}function Buffer(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 allocUnsafe(e)}return from(e,t,r)}function from(e,t,r){if("string"==typeof e)return fromString(e,t);if(ArrayBuffer.isView(e))return fromArrayView(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(isInstance(e,ArrayBuffer)||e&&isInstance(e.buffer,ArrayBuffer))return fromArrayBuffer(e,t,r);if("undefined"!=typeof SharedArrayBuffer&&(isInstance(e,SharedArrayBuffer)||e&&isInstance(e.buffer,SharedArrayBuffer)))return fromArrayBuffer(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');var n=e.valueOf&&e.valueOf();if(null!=n&&n!==e)return Buffer.from(n,t,r);var f=fromObject(e);if(f)return f;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return Buffer.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function assertSize(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function alloc(e,t,r){return assertSize(e),e<=0?createBuffer(e):void 0!==t?"string"==typeof r?createBuffer(e).fill(t,r):createBuffer(e).fill(t):createBuffer(e)}function allocUnsafe(e){return assertSize(e),createBuffer(e<0?0:0|checked(e))}function fromString(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!Buffer.isEncoding(t))throw new TypeError("Unknown encoding: "+t);var r=0|byteLength(e,t),n=createBuffer(r),f=n.write(e,t);return f!==r&&(n=n.slice(0,f)),n}function fromArrayLike(e){for(var t=e.length<0?0:0|checked(e.length),r=createBuffer(t),n=0;n<t;n+=1)r[n]=255&e[n];return r}function fromArrayView(e){if(isInstance(e,Uint8Array)){var t=new Uint8Array(e);return fromArrayBuffer(t.buffer,t.byteOffset,t.byteLength)}return fromArrayLike(e)}function fromArrayBuffer(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');var n;return n=void 0===t&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,t):new Uint8Array(e,t,r),Object.setPrototypeOf(n,Buffer.prototype),n}function fromObject(e){if(Buffer.isBuffer(e)){var t=0|checked(e.length),r=createBuffer(t);return 0===r.length||e.copy(r,0,0,t),r}return void 0!==e.length?"number"!=typeof e.length||numberIsNaN(e.length)?createBuffer(0):fromArrayLike(e):"Buffer"===e.type&&Array.isArray(e.data)?fromArrayLike(e.data):void 0}function checked(e){if(e>=K_MAX_LENGTH)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+K_MAX_LENGTH.toString(16)+" bytes");return 0|e}function SlowBuffer(e){return+e!=e&&(e=0),Buffer.alloc(+e)}function byteLength(e,t){if(Buffer.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||isInstance(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 f=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return utf8ToBytes(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return base64ToBytes(e).length;default:if(f)return n?-1:utf8ToBytes(e).length;t=(""+t).toLowerCase(),f=!0}}function slowToString(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.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 hexSlice(this,t,r);case"utf8":case"utf-8":return utf8Slice(this,t,r);case"ascii":return asciiSlice(this,t,r);case"latin1":case"binary":return latin1Slice(this,t,r);case"base64":return base64Slice(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function swap(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function bidirectionalIndexOf(e,t,r,n,f){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),numberIsNaN(r=+r)&&(r=f?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(f)return-1;r=e.length-1}else if(r<0){if(!f)return-1;r=0}if("string"==typeof t&&(t=Buffer.from(t,n)),Buffer.isBuffer(t))return 0===t.length?-1:arrayIndexOf(e,t,r,n,f);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?f?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):arrayIndexOf(e,[t],r,n,f);throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(e,t,r,n,f){var i,o=1,u=e.length,s=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;o=2,u/=2,s/=2,r/=2}function a(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(f){var h=-1;for(i=r;i<u;i++)if(a(e,i)===a(t,-1===h?0:i-h)){if(-1===h&&(h=i),i-h+1===s)return h*o}else-1!==h&&(i-=i-h),h=-1}else for(r+s>u&&(r=u-s),i=r;i>=0;i--){for(var c=!0,p=0;p<s;p++)if(a(e,i+p)!==a(t,p)){c=!1;break}if(c)return i}return-1}function hexWrite(e,t,r,n){r=Number(r)||0;var f=e.length-r;n?(n=Number(n))>f&&(n=f):n=f;var i=t.length;n>i/2&&(n=i/2);for(var o=0;o<n;++o){var u=parseInt(t.substr(2*o,2),16);if(numberIsNaN(u))return o;e[r+o]=u}return o}function utf8Write(e,t,r,n){return blitBuffer(utf8ToBytes(t,e.length-r),e,r,n)}function asciiWrite(e,t,r,n){return blitBuffer(asciiToBytes(t),e,r,n)}function base64Write(e,t,r,n){return blitBuffer(base64ToBytes(t),e,r,n)}function ucs2Write(e,t,r,n){return blitBuffer(utf16leToBytes(t,e.length-r),e,r,n)}function base64Slice(e,t,r){return 0===t&&r===e.length?base64.fromByteArray(e):base64.fromByteArray(e.slice(t,r))}function utf8Slice(e,t,r){r=Math.min(e.length,r);for(var n=[],f=t;f<r;){var i,o,u,s,a=e[f],h=null,c=a>239?4:a>223?3:a>191?2:1;if(f+c<=r)switch(c){case 1:a<128&&(h=a);break;case 2:128==(192&(i=e[f+1]))&&(s=(31&a)<<6|63&i)>127&&(h=s);break;case 3:i=e[f+1],o=e[f+2],128==(192&i)&&128==(192&o)&&(s=(15&a)<<12|(63&i)<<6|63&o)>2047&&(s<55296||s>57343)&&(h=s);break;case 4:i=e[f+1],o=e[f+2],u=e[f+3],128==(192&i)&&128==(192&o)&&128==(192&u)&&(s=(15&a)<<18|(63&i)<<12|(63&o)<<6|63&u)>65535&&s<1114112&&(h=s)}null===h?(h=65533,c=1):h>65535&&(h-=65536,n.push(h>>>10&1023|55296),h=56320|1023&h),n.push(h),f+=c}return decodeCodePointsArray(n)}exports.kMaxLength=K_MAX_LENGTH,Buffer.TYPED_ARRAY_SUPPORT=typedArraySupport(),Buffer.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||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."),Object.defineProperty(Buffer.prototype,"parent",{enumerable:!0,get:function(){if(Buffer.isBuffer(this))return this.buffer}}),Object.defineProperty(Buffer.prototype,"offset",{enumerable:!0,get:function(){if(Buffer.isBuffer(this))return this.byteOffset}}),Buffer.poolSize=8192,Buffer.from=function(e,t,r){return from(e,t,r)},Object.setPrototypeOf(Buffer.prototype,Uint8Array.prototype),Object.setPrototypeOf(Buffer,Uint8Array),Buffer.alloc=function(e,t,r){return alloc(e,t,r)},Buffer.allocUnsafe=function(e){return allocUnsafe(e)},Buffer.allocUnsafeSlow=function(e){return allocUnsafe(e)},Buffer.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==Buffer.prototype},Buffer.compare=function(e,t){if(isInstance(e,Uint8Array)&&(e=Buffer.from(e,e.offset,e.byteLength)),isInstance(t,Uint8Array)&&(t=Buffer.from(t,t.offset,t.byteLength)),!Buffer.isBuffer(e)||!Buffer.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;for(var r=e.length,n=t.length,f=0,i=Math.min(r,n);f<i;++f)if(e[f]!==t[f]){r=e[f],n=t[f];break}return r<n?-1:n<r?1:0},Buffer.isEncoding=function(e){switch(String(e).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!0;default:return!1}},Buffer.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return Buffer.alloc(0);var r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;var n=Buffer.allocUnsafe(t),f=0;for(r=0;r<e.length;++r){var i=e[r];if(isInstance(i,Uint8Array))f+i.length>n.length?Buffer.from(i).copy(n,f):Uint8Array.prototype.set.call(n,i,f);else{if(!Buffer.isBuffer(i))throw new TypeError('"list" argument must be an Array of Buffers');i.copy(n,f)}f+=i.length}return n},Buffer.byteLength=byteLength,Buffer.prototype._isBuffer=!0,Buffer.prototype.swap16=function(){var e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)swap(this,t,t+1);return this},Buffer.prototype.swap32=function(){var e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)swap(this,t,t+3),swap(this,t+1,t+2);return this},Buffer.prototype.swap64=function(){var e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)swap(this,t,t+7),swap(this,t+1,t+6),swap(this,t+2,t+5),swap(this,t+3,t+4);return this},Buffer.prototype.toString=function(){var e=this.length;return 0===e?"":0===arguments.length?utf8Slice(this,0,e):slowToString.apply(this,arguments)},Buffer.prototype.toLocaleString=Buffer.prototype.toString,Buffer.prototype.equals=function(e){if(!Buffer.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===Buffer.compare(this,e)},Buffer.prototype.inspect=function(){var e="",t=exports.INSPECT_MAX_BYTES;return e=this.toString("hex",0,t).replace(/(.{2})/g,"$1 ").trim(),this.length>t&&(e+=" ... "),"<Buffer "+e+">"},customInspectSymbol&&(Buffer.prototype[customInspectSymbol]=Buffer.prototype.inspect),Buffer.prototype.compare=function(e,t,r,n,f){if(isInstance(e,Uint8Array)&&(e=Buffer.from(e,e.offset,e.byteLength)),!Buffer.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===f&&(f=this.length),t<0||r>e.length||n<0||f>this.length)throw new RangeError("out of range index");if(n>=f&&t>=r)return 0;if(n>=f)return-1;if(t>=r)return 1;if(this===e)return 0;for(var i=(f>>>=0)-(n>>>=0),o=(r>>>=0)-(t>>>=0),u=Math.min(i,o),s=this.slice(n,f),a=e.slice(t,r),h=0;h<u;++h)if(s[h]!==a[h]){i=s[h],o=a[h];break}return i<o?-1:o<i?1:0},Buffer.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},Buffer.prototype.indexOf=function(e,t,r){return bidirectionalIndexOf(this,e,t,r,!0)},Buffer.prototype.lastIndexOf=function(e,t,r){return bidirectionalIndexOf(this,e,t,r,!1)},Buffer.prototype.write=function(e,t,r,n){if(void 0===t)n="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)n=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var f=this.length-t;if((void 0===r||r>f)&&(r=f),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return hexWrite(this,e,t,r);case"utf8":case"utf-8":return utf8Write(this,e,t,r);case"ascii":case"latin1":case"binary":return asciiWrite(this,e,t,r);case"base64":return base64Write(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,e,t,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(e){var t=e.length;if(t<=MAX_ARGUMENTS_LENGTH)return String.fromCharCode.apply(String,e);for(var r="",n=0;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=MAX_ARGUMENTS_LENGTH));return r}function asciiSlice(e,t,r){var n="";r=Math.min(e.length,r);for(var f=t;f<r;++f)n+=String.fromCharCode(127&e[f]);return n}function latin1Slice(e,t,r){var n="";r=Math.min(e.length,r);for(var f=t;f<r;++f)n+=String.fromCharCode(e[f]);return n}function hexSlice(e,t,r){var n=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>n)&&(r=n);for(var f="",i=t;i<r;++i)f+=hexSliceLookupTable[e[i]];return f}function utf16leSlice(e,t,r){for(var n=e.slice(t,r),f="",i=0;i<n.length-1;i+=2)f+=String.fromCharCode(n[i]+256*n[i+1]);return f}function checkOffset(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function checkInt(e,t,r,n,f,i){if(!Buffer.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>f||t<i)throw new RangeError('"value" argument is out of bounds');if(r+n>e.length)throw new RangeError("Index out of range")}function checkIEEE754(e,t,r,n,f,i){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function writeFloat(e,t,r,n,f){return t=+t,r>>>=0,f||checkIEEE754(e,t,r,4,34028234663852886e22,-34028234663852886e22),ieee754.write(e,t,r,n,23,4),r+4}function writeDouble(e,t,r,n,f){return t=+t,r>>>=0,f||checkIEEE754(e,t,r,8,17976931348623157e292,-17976931348623157e292),ieee754.write(e,t,r,n,52,8),r+8}Buffer.prototype.slice=function(e,t){var r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e);var n=this.subarray(e,t);return Object.setPrototypeOf(n,Buffer.prototype),n},Buffer.prototype.readUintLE=Buffer.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||checkOffset(e,t,this.length);for(var n=this[e],f=1,i=0;++i<t&&(f*=256);)n+=this[e+i]*f;return n},Buffer.prototype.readUintBE=Buffer.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||checkOffset(e,t,this.length);for(var n=this[e+--t],f=1;t>0&&(f*=256);)n+=this[e+--t]*f;return n},Buffer.prototype.readUint8=Buffer.prototype.readUInt8=function(e,t){return e>>>=0,t||checkOffset(e,1,this.length),this[e]},Buffer.prototype.readUint16LE=Buffer.prototype.readUInt16LE=function(e,t){return e>>>=0,t||checkOffset(e,2,this.length),this[e]|this[e+1]<<8},Buffer.prototype.readUint16BE=Buffer.prototype.readUInt16BE=function(e,t){return e>>>=0,t||checkOffset(e,2,this.length),this[e]<<8|this[e+1]},Buffer.prototype.readUint32LE=Buffer.prototype.readUInt32LE=function(e,t){return e>>>=0,t||checkOffset(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},Buffer.prototype.readUint32BE=Buffer.prototype.readUInt32BE=function(e,t){return e>>>=0,t||checkOffset(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},Buffer.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||checkOffset(e,t,this.length);for(var n=this[e],f=1,i=0;++i<t&&(f*=256);)n+=this[e+i]*f;return n>=(f*=128)&&(n-=Math.pow(2,8*t)),n},Buffer.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||checkOffset(e,t,this.length);for(var n=t,f=1,i=this[e+--n];n>0&&(f*=256);)i+=this[e+--n]*f;return i>=(f*=128)&&(i-=Math.pow(2,8*t)),i},Buffer.prototype.readInt8=function(e,t){return e>>>=0,t||checkOffset(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},Buffer.prototype.readInt16LE=function(e,t){e>>>=0,t||checkOffset(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},Buffer.prototype.readInt16BE=function(e,t){e>>>=0,t||checkOffset(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},Buffer.prototype.readInt32LE=function(e,t){return e>>>=0,t||checkOffset(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},Buffer.prototype.readInt32BE=function(e,t){return e>>>=0,t||checkOffset(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},Buffer.prototype.readFloatLE=function(e,t){return e>>>=0,t||checkOffset(e,4,this.length),ieee754.read(this,e,!0,23,4)},Buffer.prototype.readFloatBE=function(e,t){return e>>>=0,t||checkOffset(e,4,this.length),ieee754.read(this,e,!1,23,4)},Buffer.prototype.readDoubleLE=function(e,t){return e>>>=0,t||checkOffset(e,8,this.length),ieee754.read(this,e,!0,52,8)},Buffer.prototype.readDoubleBE=function(e,t){return e>>>=0,t||checkOffset(e,8,this.length),ieee754.read(this,e,!1,52,8)},Buffer.prototype.writeUintLE=Buffer.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t>>>=0,r>>>=0,n)||checkInt(this,e,t,r,Math.pow(2,8*r)-1,0);var f=1,i=0;for(this[t]=255&e;++i<r&&(f*=256);)this[t+i]=e/f&255;return t+r},Buffer.prototype.writeUintBE=Buffer.prototype.writeUIntBE=function(e,t,r,n){(e=+e,t>>>=0,r>>>=0,n)||checkInt(this,e,t,r,Math.pow(2,8*r)-1,0);var f=r-1,i=1;for(this[t+f]=255&e;--f>=0&&(i*=256);)this[t+f]=e/i&255;return t+r},Buffer.prototype.writeUint8=Buffer.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||checkInt(this,e,t,1,255,0),this[t]=255&e,t+1},Buffer.prototype.writeUint16LE=Buffer.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||checkInt(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},Buffer.prototype.writeUint16BE=Buffer.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||checkInt(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},Buffer.prototype.writeUint32LE=Buffer.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||checkInt(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},Buffer.prototype.writeUint32BE=Buffer.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||checkInt(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},Buffer.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var f=Math.pow(2,8*r-1);checkInt(this,e,t,r,f-1,-f)}var i=0,o=1,u=0;for(this[t]=255&e;++i<r&&(o*=256);)e<0&&0===u&&0!==this[t+i-1]&&(u=1),this[t+i]=(e/o>>0)-u&255;return t+r},Buffer.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t>>>=0,!n){var f=Math.pow(2,8*r-1);checkInt(this,e,t,r,f-1,-f)}var i=r-1,o=1,u=0;for(this[t+i]=255&e;--i>=0&&(o*=256);)e<0&&0===u&&0!==this[t+i+1]&&(u=1),this[t+i]=(e/o>>0)-u&255;return t+r},Buffer.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||checkInt(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},Buffer.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||checkInt(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},Buffer.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||checkInt(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},Buffer.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||checkInt(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},Buffer.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||checkInt(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},Buffer.prototype.writeFloatLE=function(e,t,r){return writeFloat(this,e,t,!0,r)},Buffer.prototype.writeFloatBE=function(e,t,r){return writeFloat(this,e,t,!1,r)},Buffer.prototype.writeDoubleLE=function(e,t,r){return writeDouble(this,e,t,!0,r)},Buffer.prototype.writeDoubleBE=function(e,t,r){return writeDouble(this,e,t,!1,r)},Buffer.prototype.copy=function(e,t,r,n){if(!Buffer.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<r&&(n=r),n===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=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<n-r&&(n=e.length-t+r);var f=n-r;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,r,n):Uint8Array.prototype.set.call(e,this.subarray(r,n),t),f},Buffer.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&&!Buffer.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===e.length){var f=e.charCodeAt(0);("utf8"===n&&f<128||"latin1"===n)&&(e=f)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;var i;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(i=t;i<r;++i)this[i]=e;else{var o=Buffer.isBuffer(e)?e:Buffer.from(e,n),u=o.length;if(0===u)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<r-t;++i)this[i+t]=o[i%u]}return this};var INVALID_BASE64_RE=/[^+/0-9A-Za-z-_]/g;function base64clean(e){if((e=(e=e.split("=")[0]).trim().replace(INVALID_BASE64_RE,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}function utf8ToBytes(e,t){var r;t=t||1/0;for(var n=e.length,f=null,i=[],o=0;o<n;++o){if((r=e.charCodeAt(o))>55295&&r<57344){if(!f){if(r>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(o+1===n){(t-=3)>-1&&i.push(239,191,189);continue}f=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),f=r;continue}r=65536+(f-55296<<10|r-56320)}else f&&(t-=3)>-1&&i.push(239,191,189);if(f=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function asciiToBytes(e){for(var t=[],r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}function utf16leToBytes(e,t){for(var r,n,f,i=[],o=0;o<e.length&&!((t-=2)<0);++o)n=(r=e.charCodeAt(o))>>8,f=r%256,i.push(f),i.push(n);return i}function base64ToBytes(e){return base64.toByteArray(base64clean(e))}function blitBuffer(e,t,r,n){for(var f=0;f<n&&!(f+r>=t.length||f>=e.length);++f)t[f+r]=e[f];return f}function isInstance(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function numberIsNaN(e){return e!=e}var hexSliceLookupTable=function(){for(var e="0123456789abcdef",t=new Array(256),r=0;r<16;++r)for(var n=16*r,f=0;f<16;++f)t[n+f]=e[r]+e[f];return t}();
\ No newline at end of file
index 4975bfb..073d697 100644 (file)
@@ -4,159 +4,4 @@
  * Copyright(c) 2015 Jed Watson
  * MIT Licensed
  */
-
-'use strict';
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = bytes;
-module.exports.format = format;
-module.exports.parse = parse;
-
-/**
- * Module variables.
- * @private
- */
-
-var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g;
-
-var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/;
-
-var map = {
-  b:  1,
-  kb: 1 << 10,
-  mb: 1 << 20,
-  gb: 1 << 30,
-  tb: Math.pow(1024, 4),
-  pb: Math.pow(1024, 5),
-};
-
-var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;
-
-/**
- * Convert the given value in bytes into a string or parse to string to an integer in bytes.
- *
- * @param {string|number} value
- * @param {{
- *  case: [string],
- *  decimalPlaces: [number]
- *  fixedDecimals: [boolean]
- *  thousandsSeparator: [string]
- *  unitSeparator: [string]
- *  }} [options] bytes options.
- *
- * @returns {string|number|null}
- */
-
-function bytes(value, options) {
-  if (typeof value === 'string') {
-    return parse(value);
-  }
-
-  if (typeof value === 'number') {
-    return format(value, options);
-  }
-
-  return null;
-}
-
-/**
- * Format the given value in bytes into a string.
- *
- * If the value is negative, it is kept as such. If it is a float,
- * it is rounded.
- *
- * @param {number} value
- * @param {object} [options]
- * @param {number} [options.decimalPlaces=2]
- * @param {number} [options.fixedDecimals=false]
- * @param {string} [options.thousandsSeparator=]
- * @param {string} [options.unit=]
- * @param {string} [options.unitSeparator=]
- *
- * @returns {string|null}
- * @public
- */
-
-function format(value, options) {
-  if (!Number.isFinite(value)) {
-    return null;
-  }
-
-  var mag = Math.abs(value);
-  var thousandsSeparator = (options && options.thousandsSeparator) || '';
-  var unitSeparator = (options && options.unitSeparator) || '';
-  var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2;
-  var fixedDecimals = Boolean(options && options.fixedDecimals);
-  var unit = (options && options.unit) || '';
-
-  if (!unit || !map[unit.toLowerCase()]) {
-    if (mag >= map.pb) {
-      unit = 'PB';
-    } else if (mag >= map.tb) {
-      unit = 'TB';
-    } else if (mag >= map.gb) {
-      unit = 'GB';
-    } else if (mag >= map.mb) {
-      unit = 'MB';
-    } else if (mag >= map.kb) {
-      unit = 'KB';
-    } else {
-      unit = 'B';
-    }
-  }
-
-  var val = value / map[unit.toLowerCase()];
-  var str = val.toFixed(decimalPlaces);
-
-  if (!fixedDecimals) {
-    str = str.replace(formatDecimalsRegExp, '$1');
-  }
-
-  if (thousandsSeparator) {
-    str = str.replace(formatThousandsRegExp, thousandsSeparator);
-  }
-
-  return str + unitSeparator + unit;
-}
-
-/**
- * Parse the string value into an integer in bytes.
- *
- * If no unit is given, it is assumed the value is in bytes.
- *
- * @param {number|string} val
- *
- * @returns {number|null}
- * @public
- */
-
-function parse(val) {
-  if (typeof val === 'number' && !isNaN(val)) {
-    return val;
-  }
-
-  if (typeof val !== 'string') {
-    return null;
-  }
-
-  // Test if the string passed is valid
-  var results = parseRegExp.exec(val);
-  var floatValue;
-  var unit = 'b';
-
-  if (!results) {
-    // Nothing could be extracted from the given string
-    floatValue = parseInt(val, 10);
-    unit = 'b'
-  } else {
-    // Retrieve the value and the unit
-    floatValue = parseFloat(results[1]);
-    unit = results[4].toLowerCase();
-  }
-
-  return Math.floor(map[unit] * floatValue);
-}
+"use strict";module.exports=bytes,module.exports.format=format,module.exports.parse=parse;var formatThousandsRegExp=/\B(?=(\d{3})+(?!\d))/g,formatDecimalsRegExp=/(?:\.0*|(\.[^0]+)0+)$/,map={b:1,kb:1024,mb:1<<20,gb:1<<30,tb:Math.pow(1024,4),pb:Math.pow(1024,5)},parseRegExp=/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;function bytes(e,a){return"string"==typeof e?parse(e):"number"==typeof e?format(e,a):null}function format(e,a){if(!Number.isFinite(e))return null;var r=Math.abs(e),t=a&&a.thousandsSeparator||"",o=a&&a.unitSeparator||"",p=a&&void 0!==a.decimalPlaces?a.decimalPlaces:2,s=Boolean(a&&a.fixedDecimals),m=a&&a.unit||"";m&&map[m.toLowerCase()]||(m=r>=map.pb?"PB":r>=map.tb?"TB":r>=map.gb?"GB":r>=map.mb?"MB":r>=map.kb?"KB":"B");var n=(e/map[m.toLowerCase()]).toFixed(p);return s||(n=n.replace(formatDecimalsRegExp,"$1")),t&&(n=n.replace(formatThousandsRegExp,t)),n+o+m}function parse(e){if("number"==typeof e&&!isNaN(e))return e;if("string"!=typeof e)return null;var a,r=parseRegExp.exec(e),t="b";return r?(a=parseFloat(r[1]),t=r[4].toLowerCase()):(a=parseInt(e,10),t="b"),Math.floor(map[t]*a)}
\ No newline at end of file
index 579f99b..73a903b 100644 (file)
@@ -1,76 +1 @@
-'use strict';
-
-const preserveCamelCase = string => {
-       let isLastCharLower = false;
-       let isLastCharUpper = false;
-       let isLastLastCharUpper = false;
-
-       for (let i = 0; i < string.length; i++) {
-               const character = string[i];
-
-               if (isLastCharLower && /[a-zA-Z]/.test(character) && character.toUpperCase() === character) {
-                       string = string.slice(0, i) + '-' + string.slice(i);
-                       isLastCharLower = false;
-                       isLastLastCharUpper = isLastCharUpper;
-                       isLastCharUpper = true;
-                       i++;
-               } else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(character) && character.toLowerCase() === character) {
-                       string = string.slice(0, i - 1) + '-' + string.slice(i - 1);
-                       isLastLastCharUpper = isLastCharUpper;
-                       isLastCharUpper = false;
-                       isLastCharLower = true;
-               } else {
-                       isLastCharLower = character.toLowerCase() === character && character.toUpperCase() !== character;
-                       isLastLastCharUpper = isLastCharUpper;
-                       isLastCharUpper = character.toUpperCase() === character && character.toLowerCase() !== character;
-               }
-       }
-
-       return string;
-};
-
-const camelCase = (input, options) => {
-       if (!(typeof input === 'string' || Array.isArray(input))) {
-               throw new TypeError('Expected the input to be `string | string[]`');
-       }
-
-       options = Object.assign({
-               pascalCase: false
-       }, options);
-
-       const postProcess = x => options.pascalCase ? x.charAt(0).toUpperCase() + x.slice(1) : x;
-
-       if (Array.isArray(input)) {
-               input = input.map(x => x.trim())
-                       .filter(x => x.length)
-                       .join('-');
-       } else {
-               input = input.trim();
-       }
-
-       if (input.length === 0) {
-               return '';
-       }
-
-       if (input.length === 1) {
-               return options.pascalCase ? input.toUpperCase() : input.toLowerCase();
-       }
-
-       const hasUpperCase = input !== input.toLowerCase();
-
-       if (hasUpperCase) {
-               input = preserveCamelCase(input);
-       }
-
-       input = input
-               .replace(/^[_.\- ]+/, '')
-               .toLowerCase()
-               .replace(/[_.\- ]+(\w|$)/g, (_, p1) => p1.toUpperCase())
-               .replace(/\d+(\w|$)/g, m => m.toUpperCase());
-
-       return postProcess(input);
-};
-
-module.exports = camelCase;
-// TODO: Remove this for the next major release
-module.exports.default = camelCase;
+"use strict";const preserveCamelCase=e=>{let r=!1,t=!1,a=!1;for(let s=0;s<e.length;s++){const o=e[s];r&&/[a-zA-Z]/.test(o)&&o.toUpperCase()===o?(e=e.slice(0,s)+"-"+e.slice(s),r=!1,a=t,t=!0,s++):t&&a&&/[a-zA-Z]/.test(o)&&o.toLowerCase()===o?(e=e.slice(0,s-1)+"-"+e.slice(s-1),a=t,t=!1,r=!0):(r=o.toLowerCase()===o&&o.toUpperCase()!==o,a=t,t=o.toUpperCase()===o&&o.toLowerCase()!==o)}return e},camelCase=(e,r)=>{if("string"!=typeof e&&!Array.isArray(e))throw new TypeError("Expected the input to be `string | string[]`");r=Object.assign({pascalCase:!1},r);if(0===(e=Array.isArray(e)?e.map((e=>e.trim())).filter((e=>e.length)).join("-"):e.trim()).length)return"";if(1===e.length)return r.pascalCase?e.toUpperCase():e.toLowerCase();return e!==e.toLowerCase()&&(e=preserveCamelCase(e)),e=e.replace(/^[_.\- ]+/,"").toLowerCase().replace(/[_.\- ]+(\w|$)/g,((e,r)=>r.toUpperCase())).replace(/\d+(\w|$)/g,(e=>e.toUpperCase())),t=e,r.pascalCase?t.charAt(0).toUpperCase()+t.slice(1):t;var t};module.exports=camelCase,module.exports.default=camelCase;
\ No newline at end of file
index 1cc5fa8..dcc1aae 100644 (file)
@@ -1,228 +1 @@
-'use strict';
-const escapeStringRegexp = require('escape-string-regexp');
-const ansiStyles = require('ansi-styles');
-const stdoutColor = require('supports-color').stdout;
-
-const template = require('./templates.js');
-
-const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm');
-
-// `supportsColor.level` → `ansiStyles.color[name]` mapping
-const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m'];
-
-// `color-convert` models to exclude from the Chalk API due to conflicts and such
-const skipModels = new Set(['gray']);
-
-const styles = Object.create(null);
-
-function applyOptions(obj, options) {
-       options = options || {};
-
-       // Detect level if not set manually
-       const scLevel = stdoutColor ? stdoutColor.level : 0;
-       obj.level = options.level === undefined ? scLevel : options.level;
-       obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0;
-}
-
-function Chalk(options) {
-       // We check for this.template here since calling `chalk.constructor()`
-       // by itself will have a `this` of a previously constructed chalk object
-       if (!this || !(this instanceof Chalk) || this.template) {
-               const chalk = {};
-               applyOptions(chalk, options);
-
-               chalk.template = function () {
-                       const args = [].slice.call(arguments);
-                       return chalkTag.apply(null, [chalk.template].concat(args));
-               };
-
-               Object.setPrototypeOf(chalk, Chalk.prototype);
-               Object.setPrototypeOf(chalk.template, chalk);
-
-               chalk.template.constructor = Chalk;
-
-               return chalk.template;
-       }
-
-       applyOptions(this, options);
-}
-
-// Use bright blue on Windows as the normal blue color is illegible
-if (isSimpleWindowsTerm) {
-       ansiStyles.blue.open = '\u001B[94m';
-}
-
-for (const key of Object.keys(ansiStyles)) {
-       ansiStyles[key].closeRe = new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g');
-
-       styles[key] = {
-               get() {
-                       const codes = ansiStyles[key];
-                       return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key);
-               }
-       };
-}
-
-styles.visible = {
-       get() {
-               return build.call(this, this._styles || [], true, 'visible');
-       }
-};
-
-ansiStyles.color.closeRe = new RegExp(escapeStringRegexp(ansiStyles.color.close), 'g');
-for (const model of Object.keys(ansiStyles.color.ansi)) {
-       if (skipModels.has(model)) {
-               continue;
-       }
-
-       styles[model] = {
-               get() {
-                       const level = this.level;
-                       return function () {
-                               const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments);
-                               const codes = {
-                                       open,
-                                       close: ansiStyles.color.close,
-                                       closeRe: ansiStyles.color.closeRe
-                               };
-                               return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
-                       };
-               }
-       };
-}
-
-ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp(ansiStyles.bgColor.close), 'g');
-for (const model of Object.keys(ansiStyles.bgColor.ansi)) {
-       if (skipModels.has(model)) {
-               continue;
-       }
-
-       const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
-       styles[bgModel] = {
-               get() {
-                       const level = this.level;
-                       return function () {
-                               const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments);
-                               const codes = {
-                                       open,
-                                       close: ansiStyles.bgColor.close,
-                                       closeRe: ansiStyles.bgColor.closeRe
-                               };
-                               return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model);
-                       };
-               }
-       };
-}
-
-const proto = Object.defineProperties(() => {}, styles);
-
-function build(_styles, _empty, key) {
-       const builder = function () {
-               return applyStyle.apply(builder, arguments);
-       };
-
-       builder._styles = _styles;
-       builder._empty = _empty;
-
-       const self = this;
-
-       Object.defineProperty(builder, 'level', {
-               enumerable: true,
-               get() {
-                       return self.level;
-               },
-               set(level) {
-                       self.level = level;
-               }
-       });
-
-       Object.defineProperty(builder, 'enabled', {
-               enumerable: true,
-               get() {
-                       return self.enabled;
-               },
-               set(enabled) {
-                       self.enabled = enabled;
-               }
-       });
-
-       // See below for fix regarding invisible grey/dim combination on Windows
-       builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey';
-
-       // `__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; // eslint-disable-line no-proto
-
-       return builder;
-}
-
-function applyStyle() {
-       // Support varags, but simply cast to string in case there's only one arg
-       const args = arguments;
-       const argsLen = args.length;
-       let str = String(arguments[0]);
-
-       if (argsLen === 0) {
-               return '';
-       }
-
-       if (argsLen > 1) {
-               // Don't slice `arguments`, it prevents V8 optimizations
-               for (let a = 1; a < argsLen; a++) {
-                       str += ' ' + args[a];
-               }
-       }
-
-       if (!this.enabled || this.level <= 0 || !str) {
-               return this._empty ? '' : str;
-       }
-
-       // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe,
-       // see https://github.com/chalk/chalk/issues/58
-       // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop.
-       const originalDim = ansiStyles.dim.open;
-       if (isSimpleWindowsTerm && this.hasGrey) {
-               ansiStyles.dim.open = '';
-       }
-
-       for (const code of this._styles.slice().reverse()) {
-               // Replace any instances already present with a re-opening code
-               // otherwise only the part of the string until said closing code
-               // will be colored, and the rest will simply be 'plain'.
-               str = code.open + str.replace(code.closeRe, code.open) + code.close;
-
-               // Close the styling before a linebreak and reopen
-               // after next line to fix a bleed issue on macOS
-               // https://github.com/chalk/chalk/pull/92
-               str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`);
-       }
-
-       // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue
-       ansiStyles.dim.open = originalDim;
-
-       return str;
-}
-
-function chalkTag(chalk, strings) {
-       if (!Array.isArray(strings)) {
-               // If chalk() was called by itself or with a string,
-               // return the string itself as a string.
-               return [].slice.call(arguments, 1).join(' ');
-       }
-
-       const args = [].slice.call(arguments, 2);
-       const parts = [strings.raw[0]];
-
-       for (let i = 1; i < strings.length; i++) {
-               parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&'));
-               parts.push(String(strings.raw[i]));
-       }
-
-       return template(chalk, parts.join(''));
-}
-
-Object.defineProperties(Chalk.prototype, styles);
-
-module.exports = Chalk(); // eslint-disable-line new-cap
-module.exports.supportsColor = stdoutColor;
-module.exports.default = module.exports; // For TypeScript
+"use strict";const escapeStringRegexp=require("escape-string-regexp"),ansiStyles=require("ansi-styles"),stdoutColor=require("supports-color").stdout,template=require("./templates.js"),isSimpleWindowsTerm="win32"===process.platform&&!(process.env.TERM||"").toLowerCase().startsWith("xterm"),levelMapping=["ansi","ansi","ansi256","ansi16m"],skipModels=new Set(["gray"]),styles=Object.create(null);function applyOptions(e,t){t=t||{};const s=stdoutColor?stdoutColor.level:0;e.level=void 0===t.level?s:t.level,e.enabled="enabled"in t?t.enabled:e.level>0}function Chalk(e){if(!this||!(this instanceof Chalk)||this.template){const t={};return applyOptions(t,e),t.template=function(){const e=[].slice.call(arguments);return chalkTag.apply(null,[t.template].concat(e))},Object.setPrototypeOf(t,Chalk.prototype),Object.setPrototypeOf(t.template,t),t.template.constructor=Chalk,t.template}applyOptions(this,e)}isSimpleWindowsTerm&&(ansiStyles.blue.open="\e[94m");for(const e of Object.keys(ansiStyles))ansiStyles[e].closeRe=new RegExp(escapeStringRegexp(ansiStyles[e].close),"g"),styles[e]={get(){const t=ansiStyles[e];return build.call(this,this._styles?this._styles.concat(t):[t],this._empty,e)}};styles.visible={get(){return build.call(this,this._styles||[],!0,"visible")}},ansiStyles.color.closeRe=new RegExp(escapeStringRegexp(ansiStyles.color.close),"g");for(const e of Object.keys(ansiStyles.color.ansi))skipModels.has(e)||(styles[e]={get(){const t=this.level;return function(){const s=ansiStyles.color[levelMapping[t]][e].apply(null,arguments),l={open:s,close:ansiStyles.color.close,closeRe:ansiStyles.color.closeRe};return build.call(this,this._styles?this._styles.concat(l):[l],this._empty,e)}}});ansiStyles.bgColor.closeRe=new RegExp(escapeStringRegexp(ansiStyles.bgColor.close),"g");for(const e of Object.keys(ansiStyles.bgColor.ansi)){if(skipModels.has(e))continue;styles["bg"+e[0].toUpperCase()+e.slice(1)]={get(){const t=this.level;return function(){const s=ansiStyles.bgColor[levelMapping[t]][e].apply(null,arguments),l={open:s,close:ansiStyles.bgColor.close,closeRe:ansiStyles.bgColor.closeRe};return build.call(this,this._styles?this._styles.concat(l):[l],this._empty,e)}}}}const proto=Object.defineProperties((()=>{}),styles);function build(e,t,s){const l=function(){return applyStyle.apply(l,arguments)};l._styles=e,l._empty=t;const o=this;return Object.defineProperty(l,"level",{enumerable:!0,get:()=>o.level,set(e){o.level=e}}),Object.defineProperty(l,"enabled",{enumerable:!0,get:()=>o.enabled,set(e){o.enabled=e}}),l.hasGrey=this.hasGrey||"gray"===s||"grey"===s,l.__proto__=proto,l}function applyStyle(){const e=arguments,t=e.length;let s=String(arguments[0]);if(0===t)return"";if(t>1)for(let l=1;l<t;l++)s+=" "+e[l];if(!this.enabled||this.level<=0||!s)return this._empty?"":s;const l=ansiStyles.dim.open;isSimpleWindowsTerm&&this.hasGrey&&(ansiStyles.dim.open="");for(const e of this._styles.slice().reverse())s=e.open+s.replace(e.closeRe,e.open)+e.close,s=s.replace(/\r?\n/g,`${e.close}$&${e.open}`);return ansiStyles.dim.open=l,s}function chalkTag(e,t){if(!Array.isArray(t))return[].slice.call(arguments,1).join(" ");const s=[].slice.call(arguments,2),l=[t.raw[0]];for(let e=1;e<t.length;e++)l.push(String(s[e-1]).replace(/[{}\\]/g,"\\$&")),l.push(String(t.raw[e]));return template(e,l.join(""))}Object.defineProperties(Chalk.prototype,styles),module.exports=Chalk(),module.exports.supportsColor=stdoutColor,module.exports.default=module.exports;
\ No newline at end of file
index dbdf9b2..346e49e 100644 (file)
@@ -1,128 +1 @@
-'use strict';
-const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
-const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
-const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
-const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi;
-
-const ESCAPES = new Map([
-       ['n', '\n'],
-       ['r', '\r'],
-       ['t', '\t'],
-       ['b', '\b'],
-       ['f', '\f'],
-       ['v', '\v'],
-       ['0', '\0'],
-       ['\\', '\\'],
-       ['e', '\u001B'],
-       ['a', '\u0007']
-]);
-
-function unescape(c) {
-       if ((c[0] === 'u' && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
-               return String.fromCharCode(parseInt(c.slice(1), 16));
-       }
-
-       return ESCAPES.get(c) || c;
-}
-
-function parseArguments(name, args) {
-       const results = [];
-       const chunks = args.trim().split(/\s*,\s*/g);
-       let matches;
-
-       for (const chunk of chunks) {
-               if (!isNaN(chunk)) {
-                       results.push(Number(chunk));
-               } else if ((matches = chunk.match(STRING_REGEX))) {
-                       results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr));
-               } else {
-                       throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
-               }
-       }
-
-       return results;
-}
-
-function parseStyle(style) {
-       STYLE_REGEX.lastIndex = 0;
-
-       const results = [];
-       let matches;
-
-       while ((matches = STYLE_REGEX.exec(style)) !== null) {
-               const name = matches[1];
-
-               if (matches[2]) {
-                       const args = parseArguments(name, matches[2]);
-                       results.push([name].concat(args));
-               } else {
-                       results.push([name]);
-               }
-       }
-
-       return results;
-}
-
-function buildStyle(chalk, styles) {
-       const enabled = {};
-
-       for (const layer of styles) {
-               for (const style of layer.styles) {
-                       enabled[style[0]] = layer.inverse ? null : style.slice(1);
-               }
-       }
-
-       let current = chalk;
-       for (const styleName of Object.keys(enabled)) {
-               if (Array.isArray(enabled[styleName])) {
-                       if (!(styleName in current)) {
-                               throw new Error(`Unknown Chalk style: ${styleName}`);
-                       }
-
-                       if (enabled[styleName].length > 0) {
-                               current = current[styleName].apply(current, enabled[styleName]);
-                       } else {
-                               current = current[styleName];
-                       }
-               }
-       }
-
-       return current;
-}
-
-module.exports = (chalk, tmp) => {
-       const styles = [];
-       const chunks = [];
-       let chunk = [];
-
-       // eslint-disable-next-line max-params
-       tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => {
-               if (escapeChar) {
-                       chunk.push(unescape(escapeChar));
-               } else if (style) {
-                       const str = chunk.join('');
-                       chunk = [];
-                       chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str));
-                       styles.push({inverse, styles: parseStyle(style)});
-               } else if (close) {
-                       if (styles.length === 0) {
-                               throw new Error('Found extraneous } in Chalk template literal');
-                       }
-
-                       chunks.push(buildStyle(chalk, styles)(chunk.join('')));
-                       chunk = [];
-                       styles.pop();
-               } else {
-                       chunk.push(chr);
-               }
-       });
-
-       chunks.push(chunk.join(''));
-
-       if (styles.length > 0) {
-               const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
-               throw new Error(errMsg);
-       }
-
-       return chunks.join('');
-};
+"use strict";const TEMPLATE_REGEX=/(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi,STYLE_REGEX=/(?:^|\.)(\w+)(?:\(([^)]*)\))?/g,STRING_REGEX=/^(['"])((?:\\.|(?!\1)[^\\])*)\1$/,ESCAPE_REGEX=/\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi,ESCAPES=new Map([["n","\n"],["r","\r"],["t","\t"],["b","\b"],["f","\f"],["v","\v"],["0","\0"],["\\","\\"],["e","\e"],["a","\a"]]);function unescape(e){return"u"===e[0]&&5===e.length||"x"===e[0]&&3===e.length?String.fromCharCode(parseInt(e.slice(1),16)):ESCAPES.get(e)||e}function parseArguments(e,t){const n=[],s=t.trim().split(/\s*,\s*/g);let r;for(const t of s)if(isNaN(t)){if(!(r=t.match(STRING_REGEX)))throw new Error(`Invalid Chalk template style argument: ${t} (in style '${e}')`);n.push(r[2].replace(ESCAPE_REGEX,((e,t,n)=>t?unescape(t):n)))}else n.push(Number(t));return n}function parseStyle(e){STYLE_REGEX.lastIndex=0;const t=[];let n;for(;null!==(n=STYLE_REGEX.exec(e));){const e=n[1];if(n[2]){const s=parseArguments(e,n[2]);t.push([e].concat(s))}else t.push([e])}return t}function buildStyle(e,t){const n={};for(const e of t)for(const t of e.styles)n[t[0]]=e.inverse?null:t.slice(1);let s=e;for(const e of Object.keys(n))if(Array.isArray(n[e])){if(!(e in s))throw new Error(`Unknown Chalk style: ${e}`);s=n[e].length>0?s[e].apply(s,n[e]):s[e]}return s}module.exports=(e,t)=>{const n=[],s=[];let r=[];if(t.replace(TEMPLATE_REGEX,((t,l,o,i,u,a)=>{if(l)r.push(unescape(l));else if(i){const t=r.join("");r=[],s.push(0===n.length?t:buildStyle(e,n)(t)),n.push({inverse:o,styles:parseStyle(i)})}else if(u){if(0===n.length)throw new Error("Found extraneous } in Chalk template literal");s.push(buildStyle(e,n)(r.join(""))),r=[],n.pop()}else r.push(a)})),s.push(r.join("")),n.length>0){const e=`Chalk template literal is missing ${n.length} closing bracket${1===n.length?"":"s"} (\`}\`)`;throw new Error(e)}return s.join("")};
\ No newline at end of file
index b42d982..4070f98 100644 (file)
@@ -1,324 +1 @@
-var stringWidth = require('string-width')
-var stripAnsi = require('strip-ansi')
-var wrap = require('wrap-ansi')
-var align = {
-  right: alignRight,
-  center: alignCenter
-}
-var top = 0
-var right = 1
-var bottom = 2
-var left = 3
-
-function UI (opts) {
-  this.width = opts.width
-  this.wrap = opts.wrap
-  this.rows = []
-}
-
-UI.prototype.span = function () {
-  var cols = this.div.apply(this, arguments)
-  cols.span = true
-}
-
-UI.prototype.resetOutput = function () {
-  this.rows = []
-}
-
-UI.prototype.div = function () {
-  if (arguments.length === 0) this.div('')
-  if (this.wrap && this._shouldApplyLayoutDSL.apply(this, arguments)) {
-    return this._applyLayoutDSL(arguments[0])
-  }
-
-  var cols = []
-
-  for (var i = 0, arg; (arg = arguments[i]) !== undefined; i++) {
-    if (typeof arg === 'string') cols.push(this._colFromString(arg))
-    else cols.push(arg)
-  }
-
-  this.rows.push(cols)
-  return cols
-}
-
-UI.prototype._shouldApplyLayoutDSL = function () {
-  return arguments.length === 1 && typeof arguments[0] === 'string' &&
-    /[\t\n]/.test(arguments[0])
-}
-
-UI.prototype._applyLayoutDSL = function (str) {
-  var _this = this
-  var rows = str.split('\n')
-  var leftColumnWidth = 0
-
-  // simple heuristic for layout, make sure the
-  // second column lines up along the left-hand.
-  // don't allow the first column to take up more
-  // than 50% of the screen.
-  rows.forEach(function (row) {
-    var columns = row.split('\t')
-    if (columns.length > 1 && stringWidth(columns[0]) > leftColumnWidth) {
-      leftColumnWidth = Math.min(
-        Math.floor(_this.width * 0.5),
-        stringWidth(columns[0])
-      )
-    }
-  })
-
-  // generate a table:
-  //  replacing ' ' with padding calculations.
-  //  using the algorithmically generated width.
-  rows.forEach(function (row) {
-    var columns = row.split('\t')
-    _this.div.apply(_this, columns.map(function (r, i) {
-      return {
-        text: r.trim(),
-        padding: _this._measurePadding(r),
-        width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined
-      }
-    }))
-  })
-
-  return this.rows[this.rows.length - 1]
-}
-
-UI.prototype._colFromString = function (str) {
-  return {
-    text: str,
-    padding: this._measurePadding(str)
-  }
-}
-
-UI.prototype._measurePadding = function (str) {
-  // measure padding without ansi escape codes
-  var noAnsi = stripAnsi(str)
-  return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length]
-}
-
-UI.prototype.toString = function () {
-  var _this = this
-  var lines = []
-
-  _this.rows.forEach(function (row, i) {
-    _this.rowToString(row, lines)
-  })
-
-  // don't display any lines with the
-  // hidden flag set.
-  lines = lines.filter(function (line) {
-    return !line.hidden
-  })
-
-  return lines.map(function (line) {
-    return line.text
-  }).join('\n')
-}
-
-UI.prototype.rowToString = function (row, lines) {
-  var _this = this
-  var padding
-  var rrows = this._rasterize(row)
-  var str = ''
-  var ts
-  var width
-  var wrapWidth
-
-  rrows.forEach(function (rrow, r) {
-    str = ''
-    rrow.forEach(function (col, c) {
-      ts = '' // temporary string used during alignment/padding.
-      width = row[c].width // the width with padding.
-      wrapWidth = _this._negatePadding(row[c]) // the width without padding.
-
-      ts += col
-
-      for (var i = 0; i < wrapWidth - stringWidth(col); i++) {
-        ts += ' '
-      }
-
-      // align the string within its column.
-      if (row[c].align && row[c].align !== 'left' && _this.wrap) {
-        ts = align[row[c].align](ts, wrapWidth)
-        if (stringWidth(ts) < wrapWidth) ts += new Array(width - stringWidth(ts)).join(' ')
-      }
-
-      // apply border and padding to string.
-      padding = row[c].padding || [0, 0, 0, 0]
-      if (padding[left]) str += new Array(padding[left] + 1).join(' ')
-      str += addBorder(row[c], ts, '| ')
-      str += ts
-      str += addBorder(row[c], ts, ' |')
-      if (padding[right]) str += new Array(padding[right] + 1).join(' ')
-
-      // if prior row is span, try to render the
-      // current row on the prior line.
-      if (r === 0 && lines.length > 0) {
-        str = _this._renderInline(str, lines[lines.length - 1])
-      }
-    })
-
-    // remove trailing whitespace.
-    lines.push({
-      text: str.replace(/ +$/, ''),
-      span: row.span
-    })
-  })
-
-  return lines
-}
-
-function addBorder (col, ts, style) {
-  if (col.border) {
-    if (/[.']-+[.']/.test(ts)) return ''
-    else if (ts.trim().length) return style
-    else return '  '
-  }
-  return ''
-}
-
-// if the full 'source' can render in
-// the target line, do so.
-UI.prototype._renderInline = function (source, previousLine) {
-  var leadingWhitespace = source.match(/^ */)[0].length
-  var target = previousLine.text
-  var targetTextWidth = stringWidth(target.trimRight())
-
-  if (!previousLine.span) return source
-
-  // if we're not applying wrapping logic,
-  // just always append to the span.
-  if (!this.wrap) {
-    previousLine.hidden = true
-    return target + source
-  }
-
-  if (leadingWhitespace < targetTextWidth) return source
-
-  previousLine.hidden = true
-
-  return target.trimRight() + new Array(leadingWhitespace - targetTextWidth + 1).join(' ') + source.trimLeft()
-}
-
-UI.prototype._rasterize = function (row) {
-  var _this = this
-  var i
-  var rrow
-  var rrows = []
-  var widths = this._columnWidths(row)
-  var wrapped
-
-  // word wrap all columns, and create
-  // a data-structure that is easy to rasterize.
-  row.forEach(function (col, c) {
-    // leave room for left and right padding.
-    col.width = widths[c]
-    if (_this.wrap) wrapped = wrap(col.text, _this._negatePadding(col), { hard: true }).split('\n')
-    else wrapped = col.text.split('\n')
-
-    if (col.border) {
-      wrapped.unshift('.' + new Array(_this._negatePadding(col) + 3).join('-') + '.')
-      wrapped.push("'" + new Array(_this._negatePadding(col) + 3).join('-') + "'")
-    }
-
-    // add top and bottom padding.
-    if (col.padding) {
-      for (i = 0; i < (col.padding[top] || 0); i++) wrapped.unshift('')
-      for (i = 0; i < (col.padding[bottom] || 0); i++) wrapped.push('')
-    }
-
-    wrapped.forEach(function (str, r) {
-      if (!rrows[r]) rrows.push([])
-
-      rrow = rrows[r]
-
-      for (var i = 0; i < c; i++) {
-        if (rrow[i] === undefined) rrow.push('')
-      }
-      rrow.push(str)
-    })
-  })
-
-  return rrows
-}
-
-UI.prototype._negatePadding = function (col) {
-  var wrapWidth = col.width
-  if (col.padding) wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0)
-  if (col.border) wrapWidth -= 4
-  return wrapWidth
-}
-
-UI.prototype._columnWidths = function (row) {
-  var _this = this
-  var widths = []
-  var unset = row.length
-  var unsetWidth
-  var remainingWidth = this.width
-
-  // column widths can be set in config.
-  row.forEach(function (col, i) {
-    if (col.width) {
-      unset--
-      widths[i] = col.width
-      remainingWidth -= col.width
-    } else {
-      widths[i] = undefined
-    }
-  })
-
-  // any unset widths should be calculated.
-  if (unset) unsetWidth = Math.floor(remainingWidth / unset)
-  widths.forEach(function (w, i) {
-    if (!_this.wrap) widths[i] = row[i].width || stringWidth(row[i].text)
-    else if (w === undefined) widths[i] = Math.max(unsetWidth, _minWidth(row[i]))
-  })
-
-  return widths
-}
-
-// calculates the minimum width of
-// a column, based on padding preferences.
-function _minWidth (col) {
-  var padding = col.padding || []
-  var minWidth = 1 + (padding[left] || 0) + (padding[right] || 0)
-  if (col.border) minWidth += 4
-  return minWidth
-}
-
-function getWindowWidth () {
-  if (typeof process === 'object' && process.stdout && process.stdout.columns) return process.stdout.columns
-}
-
-function alignRight (str, width) {
-  str = str.trim()
-  var padding = ''
-  var strWidth = stringWidth(str)
-
-  if (strWidth < width) {
-    padding = new Array(width - strWidth + 1).join(' ')
-  }
-
-  return padding + str
-}
-
-function alignCenter (str, width) {
-  str = str.trim()
-  var padding = ''
-  var strWidth = stringWidth(str.trim())
-
-  if (strWidth < width) {
-    padding = new Array(parseInt((width - strWidth) / 2, 10) + 1).join(' ')
-  }
-
-  return padding + str
-}
-
-module.exports = function (opts) {
-  opts = opts || {}
-
-  return new UI({
-    width: (opts || {}).width || getWindowWidth() || 80,
-    wrap: typeof opts.wrap === 'boolean' ? opts.wrap : true
-  })
-}
+var stringWidth=require("string-width"),stripAnsi=require("strip-ansi"),wrap=require("wrap-ansi"),align={right:alignRight,center:alignCenter},top=0,right=1,bottom=2,left=3;function UI(t){this.width=t.width,this.wrap=t.wrap,this.rows=[]}function addBorder(t,r,n){return t.border?/[.']-+[.']/.test(r)?"":r.trim().length?n:"  ":""}function _minWidth(t){var r=t.padding||[],n=1+(r[left]||0)+(r[right]||0);return t.border&&(n+=4),n}function getWindowWidth(){if("object"==typeof process&&process.stdout&&process.stdout.columns)return process.stdout.columns}function alignRight(t,r){t=t.trim();var n="",i=stringWidth(t);return i<r&&(n=new Array(r-i+1).join(" ")),n+t}function alignCenter(t,r){t=t.trim();var n="",i=stringWidth(t.trim());return i<r&&(n=new Array(parseInt((r-i)/2,10)+1).join(" ")),n+t}UI.prototype.span=function(){var t=this.div.apply(this,arguments);t.span=!0},UI.prototype.resetOutput=function(){this.rows=[]},UI.prototype.div=function(){if(0===arguments.length&&this.div(""),this.wrap&&this._shouldApplyLayoutDSL.apply(this,arguments))return this._applyLayoutDSL(arguments[0]);for(var t,r=[],n=0;void 0!==(t=arguments[n]);n++)"string"==typeof t?r.push(this._colFromString(t)):r.push(t);return this.rows.push(r),r},UI.prototype._shouldApplyLayoutDSL=function(){return 1===arguments.length&&"string"==typeof arguments[0]&&/[\t\n]/.test(arguments[0])},UI.prototype._applyLayoutDSL=function(t){var r=this,n=t.split("\n"),i=0;return n.forEach((function(t){var n=t.split("\t");n.length>1&&stringWidth(n[0])>i&&(i=Math.min(Math.floor(.5*r.width),stringWidth(n[0])))})),n.forEach((function(t){var n=t.split("\t");r.div.apply(r,n.map((function(t,o){return{text:t.trim(),padding:r._measurePadding(t),width:0===o&&n.length>1?i:void 0}})))})),this.rows[this.rows.length-1]},UI.prototype._colFromString=function(t){return{text:t,padding:this._measurePadding(t)}},UI.prototype._measurePadding=function(t){var r=stripAnsi(t);return[0,r.match(/\s*$/)[0].length,0,r.match(/^\s*/)[0].length]},UI.prototype.toString=function(){var t=this,r=[];return t.rows.forEach((function(n,i){t.rowToString(n,r)})),(r=r.filter((function(t){return!t.hidden}))).map((function(t){return t.text})).join("\n")},UI.prototype.rowToString=function(t,r){var n,i,o,e,a=this,h=this._rasterize(t),d="";return h.forEach((function(h,p){d="",h.forEach((function(h,s){i="",o=t[s].width,e=a._negatePadding(t[s]),i+=h;for(var u=0;u<e-stringWidth(h);u++)i+=" ";t[s].align&&"left"!==t[s].align&&a.wrap&&(i=align[t[s].align](i,e),stringWidth(i)<e&&(i+=new Array(o-stringWidth(i)).join(" "))),(n=t[s].padding||[0,0,0,0])[left]&&(d+=new Array(n[left]+1).join(" ")),d+=addBorder(t[s],i,"| "),d+=i,d+=addBorder(t[s],i," |"),n[right]&&(d+=new Array(n[right]+1).join(" ")),0===p&&r.length>0&&(d=a._renderInline(d,r[r.length-1]))})),r.push({text:d.replace(/ +$/,""),span:t.span})})),r},UI.prototype._renderInline=function(t,r){var n=t.match(/^ */)[0].length,i=r.text,o=stringWidth(i.trimRight());return r.span?this.wrap?n<o?t:(r.hidden=!0,i.trimRight()+new Array(n-o+1).join(" ")+t.trimLeft()):(r.hidden=!0,i+t):t},UI.prototype._rasterize=function(t){var r,n,i,o=this,e=[],a=this._columnWidths(t);return t.forEach((function(t,h){if(t.width=a[h],i=o.wrap?wrap(t.text,o._negatePadding(t),{hard:!0}).split("\n"):t.text.split("\n"),t.border&&(i.unshift("."+new Array(o._negatePadding(t)+3).join("-")+"."),i.push("'"+new Array(o._negatePadding(t)+3).join("-")+"'")),t.padding){for(r=0;r<(t.padding[top]||0);r++)i.unshift("");for(r=0;r<(t.padding[bottom]||0);r++)i.push("")}i.forEach((function(t,r){e[r]||e.push([]),n=e[r];for(var i=0;i<h;i++)void 0===n[i]&&n.push("");n.push(t)}))})),e},UI.prototype._negatePadding=function(t){var r=t.width;return t.padding&&(r-=(t.padding[left]||0)+(t.padding[right]||0)),t.border&&(r-=4),r},UI.prototype._columnWidths=function(t){var r,n=this,i=[],o=t.length,e=this.width;return t.forEach((function(t,r){t.width?(o--,i[r]=t.width,e-=t.width):i[r]=void 0})),o&&(r=Math.floor(e/o)),i.forEach((function(o,e){n.wrap?void 0===o&&(i[e]=Math.max(r,_minWidth(t[e]))):i[e]=t[e].width||stringWidth(t[e].text)})),i},module.exports=function(t){return new UI({width:((t=t||{})||{}).width||getWindowWidth()||80,wrap:"boolean"!=typeof t.wrap||t.wrap})};
\ No newline at end of file
index 3217200..5dc32aa 100644 (file)
@@ -1,868 +1 @@
-/* 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];
-};
+var cssKeywords=require("color-name"),reverseKeywords={};for(var key in cssKeywords)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"]}};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,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})}function comparativeDistance(r,n){return Math.pow(r[0]-n[0],2)+Math.pow(r[1]-n[1],2)+Math.pow(r[2]-n[2],2)}convert.rgb.hsl=function(r){var n,e,t=r[0]/255,a=r[1]/255,o=r[2]/255,c=Math.min(t,a,o),h=Math.max(t,a,o),s=h-c;return h===c?n=0:t===h?n=(a-o)/s:a===h?n=2+(o-t)/s:o===h&&(n=4+(t-a)/s),(n=Math.min(60*n,360))<0&&(n+=360),e=(c+h)/2,[n,100*(h===c?0:e<=.5?s/(h+c):s/(2-h-c)),100*e]},convert.rgb.hsv=function(r){var n,e,t,a,o,c=r[0]/255,h=r[1]/255,s=r[2]/255,l=Math.max(c,h,s),v=l-Math.min(c,h,s),u=function(r){return(l-r)/6/v+.5};return 0===v?a=o=0:(o=v/l,n=u(c),e=u(h),t=u(s),c===l?a=t-e:h===l?a=1/3+n-t:s===l&&(a=2/3+e-n),a<0?a+=1:a>1&&(a-=1)),[360*a,100*o,100*l]},convert.rgb.hwb=function(r){var n=r[0],e=r[1],t=r[2];return[convert.rgb.hsl(r)[0],100*(1/255*Math.min(n,Math.min(e,t))),100*(t=1-1/255*Math.max(n,Math.max(e,t)))]},convert.rgb.cmyk=function(r){var n,e=r[0]/255,t=r[1]/255,a=r[2]/255;return[100*((1-e-(n=Math.min(1-e,1-t,1-a)))/(1-n)||0),100*((1-t-n)/(1-n)||0),100*((1-a-n)/(1-n)||0),100*n]},convert.rgb.keyword=function(r){var n=reverseKeywords[r];if(n)return n;var e,t=1/0;for(var a in cssKeywords)if(cssKeywords.hasOwnProperty(a)){var o=comparativeDistance(r,cssKeywords[a]);o<t&&(t=o,e=a)}return e},convert.keyword.rgb=function(r){return cssKeywords[r]},convert.rgb.xyz=function(r){var n=r[0]/255,e=r[1]/255,t=r[2]/255;return[100*(.4124*(n=n>.04045?Math.pow((n+.055)/1.055,2.4):n/12.92)+.3576*(e=e>.04045?Math.pow((e+.055)/1.055,2.4):e/12.92)+.1805*(t=t>.04045?Math.pow((t+.055)/1.055,2.4):t/12.92)),100*(.2126*n+.7152*e+.0722*t),100*(.0193*n+.1192*e+.9505*t)]},convert.rgb.lab=function(r){var n=convert.rgb.xyz(r),e=n[0],t=n[1],a=n[2];return t/=100,a/=108.883,e=(e/=95.047)>.008856?Math.pow(e,1/3):7.787*e+16/116,[116*(t=t>.008856?Math.pow(t,1/3):7.787*t+16/116)-16,500*(e-t),200*(t-(a=a>.008856?Math.pow(a,1/3):7.787*a+16/116))]},convert.hsl.rgb=function(r){var n,e,t,a,o,c=r[0]/360,h=r[1]/100,s=r[2]/100;if(0===h)return[o=255*s,o,o];n=2*s-(e=s<.5?s*(1+h):s+h-s*h),a=[0,0,0];for(var l=0;l<3;l++)(t=c+1/3*-(l-1))<0&&t++,t>1&&t--,o=6*t<1?n+6*(e-n)*t:2*t<1?e:3*t<2?n+(e-n)*(2/3-t)*6:n,a[l]=255*o;return a},convert.hsl.hsv=function(r){var n=r[0],e=r[1]/100,t=r[2]/100,a=e,o=Math.max(t,.01);return e*=(t*=2)<=1?t:2-t,a*=o<=1?o:2-o,[n,100*(0===t?2*a/(o+a):2*e/(t+e)),100*((t+e)/2)]},convert.hsv.rgb=function(r){var n=r[0]/60,e=r[1]/100,t=r[2]/100,a=Math.floor(n)%6,o=n-Math.floor(n),c=255*t*(1-e),h=255*t*(1-e*o),s=255*t*(1-e*(1-o));switch(t*=255,a){case 0:return[t,s,c];case 1:return[h,t,c];case 2:return[c,t,s];case 3:return[c,h,t];case 4:return[s,c,t];case 5:return[t,c,h]}},convert.hsv.hsl=function(r){var n,e,t,a=r[0],o=r[1]/100,c=r[2]/100,h=Math.max(c,.01);return t=(2-o)*c,e=o*h,[a,100*(e=(e/=(n=(2-o)*h)<=1?n:2-n)||0),100*(t/=2)]},convert.hwb.rgb=function(r){var n,e,t,a,o,c,h,s=r[0]/360,l=r[1]/100,v=r[2]/100,u=l+v;switch(u>1&&(l/=u,v/=u),t=6*s-(n=Math.floor(6*s)),0!=(1&n)&&(t=1-t),a=l+t*((e=1-v)-l),n){default:case 6:case 0:o=e,c=a,h=l;break;case 1:o=a,c=e,h=l;break;case 2:o=l,c=e,h=a;break;case 3:o=l,c=a,h=e;break;case 4:o=a,c=l,h=e;break;case 5:o=e,c=l,h=a}return[255*o,255*c,255*h]},convert.cmyk.rgb=function(r){var n=r[0]/100,e=r[1]/100,t=r[2]/100,a=r[3]/100;return[255*(1-Math.min(1,n*(1-a)+a)),255*(1-Math.min(1,e*(1-a)+a)),255*(1-Math.min(1,t*(1-a)+a))]},convert.xyz.rgb=function(r){var n,e,t,a=r[0]/100,o=r[1]/100,c=r[2]/100;return e=-.9689*a+1.8758*o+.0415*c,t=.0557*a+-.204*o+1.057*c,n=(n=3.2406*a+-1.5372*o+-.4986*c)>.0031308?1.055*Math.pow(n,1/2.4)-.055:12.92*n,e=e>.0031308?1.055*Math.pow(e,1/2.4)-.055:12.92*e,t=t>.0031308?1.055*Math.pow(t,1/2.4)-.055:12.92*t,[255*(n=Math.min(Math.max(0,n),1)),255*(e=Math.min(Math.max(0,e),1)),255*(t=Math.min(Math.max(0,t),1))]},convert.xyz.lab=function(r){var n=r[0],e=r[1],t=r[2];return e/=100,t/=108.883,n=(n/=95.047)>.008856?Math.pow(n,1/3):7.787*n+16/116,[116*(e=e>.008856?Math.pow(e,1/3):7.787*e+16/116)-16,500*(n-e),200*(e-(t=t>.008856?Math.pow(t,1/3):7.787*t+16/116))]},convert.lab.xyz=function(r){var n,e,t,a=r[0];n=r[1]/500+(e=(a+16)/116),t=e-r[2]/200;var o=Math.pow(e,3),c=Math.pow(n,3),h=Math.pow(t,3);return e=o>.008856?o:(e-16/116)/7.787,n=c>.008856?c:(n-16/116)/7.787,t=h>.008856?h:(t-16/116)/7.787,[n*=95.047,e*=100,t*=108.883]},convert.lab.lch=function(r){var n,e=r[0],t=r[1],a=r[2];return(n=360*Math.atan2(a,t)/2/Math.PI)<0&&(n+=360),[e,Math.sqrt(t*t+a*a),n]},convert.lch.lab=function(r){var n,e=r[0],t=r[1];return n=r[2]/360*2*Math.PI,[e,t*Math.cos(n),t*Math.sin(n)]},convert.rgb.ansi16=function(r){var n=r[0],e=r[1],t=r[2],a=1 in arguments?arguments[1]:convert.rgb.hsv(r)[2];if(0===(a=Math.round(a/50)))return 30;var o=30+(Math.round(t/255)<<2|Math.round(e/255)<<1|Math.round(n/255));return 2===a&&(o+=60),o},convert.hsv.ansi16=function(r){return convert.rgb.ansi16(convert.hsv.rgb(r),r[2])},convert.rgb.ansi256=function(r){var n=r[0],e=r[1],t=r[2];return n===e&&e===t?n<8?16:n>248?231:Math.round((n-8)/247*24)+232:16+36*Math.round(n/255*5)+6*Math.round(e/255*5)+Math.round(t/255*5)},convert.ansi16.rgb=function(r){var n=r%10;if(0===n||7===n)return r>50&&(n+=3.5),[n=n/10.5*255,n,n];var e=.5*(1+~~(r>50));return[(1&n)*e*255,(n>>1&1)*e*255,(n>>2&1)*e*255]},convert.ansi256.rgb=function(r){if(r>=232){var n=10*(r-232)+8;return[n,n,n]}var e;return r-=16,[Math.floor(r/36)/5*255,Math.floor((e=r%36)/6)/5*255,e%6/5*255]},convert.rgb.hex=function(r){var n=(((255&Math.round(r[0]))<<16)+((255&Math.round(r[1]))<<8)+(255&Math.round(r[2]))).toString(16).toUpperCase();return"000000".substring(n.length)+n},convert.hex.rgb=function(r){var n=r.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!n)return[0,0,0];var e=n[0];3===n[0].length&&(e=e.split("").map((function(r){return r+r})).join(""));var t=parseInt(e,16);return[t>>16&255,t>>8&255,255&t]},convert.rgb.hcg=function(r){var n,e=r[0]/255,t=r[1]/255,a=r[2]/255,o=Math.max(Math.max(e,t),a),c=Math.min(Math.min(e,t),a),h=o-c;return n=h<=0?0:o===e?(t-a)/h%6:o===t?2+(a-e)/h:4+(e-t)/h+4,n/=6,[360*(n%=1),100*h,100*(h<1?c/(1-h):0)]},convert.hsl.hcg=function(r){var n=r[1]/100,e=r[2]/100,t=1,a=0;return(t=e<.5?2*n*e:2*n*(1-e))<1&&(a=(e-.5*t)/(1-t)),[r[0],100*t,100*a]},convert.hsv.hcg=function(r){var n=r[1]/100,e=r[2]/100,t=n*e,a=0;return t<1&&(a=(e-t)/(1-t)),[r[0],100*t,100*a]},convert.hcg.rgb=function(r){var n=r[0]/360,e=r[1]/100,t=r[2]/100;if(0===e)return[255*t,255*t,255*t];var a,o=[0,0,0],c=n%1*6,h=c%1,s=1-h;switch(Math.floor(c)){case 0:o[0]=1,o[1]=h,o[2]=0;break;case 1:o[0]=s,o[1]=1,o[2]=0;break;case 2:o[0]=0,o[1]=1,o[2]=h;break;case 3:o[0]=0,o[1]=s,o[2]=1;break;case 4:o[0]=h,o[1]=0,o[2]=1;break;default:o[0]=1,o[1]=0,o[2]=s}return a=(1-e)*t,[255*(e*o[0]+a),255*(e*o[1]+a),255*(e*o[2]+a)]},convert.hcg.hsv=function(r){var n=r[1]/100,e=n+r[2]/100*(1-n),t=0;return e>0&&(t=n/e),[r[0],100*t,100*e]},convert.hcg.hsl=function(r){var n=r[1]/100,e=r[2]/100*(1-n)+.5*n,t=0;return e>0&&e<.5?t=n/(2*e):e>=.5&&e<1&&(t=n/(2*(1-e))),[r[0],100*t,100*e]},convert.hcg.hwb=function(r){var n=r[1]/100,e=n+r[2]/100*(1-n);return[r[0],100*(e-n),100*(1-e)]},convert.hwb.hcg=function(r){var n=r[1]/100,e=1-r[2]/100,t=e-n,a=0;return t<1&&(a=(e-t)/(1-t)),[r[0],100*t,100*a]},convert.apple.rgb=function(r){return[r[0]/65535*255,r[1]/65535*255,r[2]/65535*255]},convert.rgb.apple=function(r){return[r[0]/255*65535,r[1]/255*65535,r[2]/255*65535]},convert.gray.rgb=function(r){return[r[0]/100*255,r[0]/100*255,r[0]/100*255]},convert.gray.hsl=convert.gray.hsv=function(r){return[0,0,r[0]]},convert.gray.hwb=function(r){return[0,100,r[0]]},convert.gray.cmyk=function(r){return[0,0,0,r[0]]},convert.gray.lab=function(r){return[r[0],0,0]},convert.gray.hex=function(r){var n=255&Math.round(r[0]/100*255),e=((n<<16)+(n<<8)+n).toString(16).toUpperCase();return"000000".substring(e.length)+e},convert.rgb.gray=function(r){return[(r[0]+r[1]+r[2])/3/255*100]};
\ No newline at end of file
index e65b5d7..2f481ec 100644 (file)
@@ -1,78 +1 @@
-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;
+var conversions=require("./conversions"),route=require("./route"),convert={},models=Object.keys(conversions);function wrapRaw(e){var n=function(n){return null==n?n:(arguments.length>1&&(n=Array.prototype.slice.call(arguments)),e(n))};return"conversion"in e&&(n.conversion=e.conversion),n}function wrapRounded(e){var n=function(n){if(null==n)return n;arguments.length>1&&(n=Array.prototype.slice.call(arguments));var r=e(n);if("object"==typeof r)for(var o=r.length,t=0;t<o;t++)r[t]=Math.round(r[t]);return r};return"conversion"in e&&(n.conversion=e.conversion),n}models.forEach((function(e){convert[e]={},Object.defineProperty(convert[e],"channels",{value:conversions[e].channels}),Object.defineProperty(convert[e],"labels",{value:conversions[e].labels});var n=route(e);Object.keys(n).forEach((function(r){var o=n[r];convert[e][r]=wrapRounded(o),convert[e][r].raw=wrapRaw(o)}))})),module.exports=convert;
\ No newline at end of file
index 0a1fdea..d843e94 100644 (file)
@@ -1,97 +1 @@
-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;
-};
-
+var conversions=require("./conversions");function buildGraph(){for(var n={},r=Object.keys(conversions),e=r.length,t=0;t<e;t++)n[r[t]]={distance:-1,parent:null};return n}function deriveBFS(n){var r=buildGraph(),e=[n];for(r[n].distance=0;e.length;)for(var t=e.pop(),o=Object.keys(conversions[t]),i=o.length,a=0;a<i;a++){var s=o[a],c=r[s];-1===c.distance&&(c.distance=r[t].distance+1,c.parent=t,e.unshift(s))}return r}function link(n,r){return function(e){return r(n(e))}}function wrapConversion(n,r){for(var e=[r[n].parent,n],t=conversions[r[n].parent][n],o=r[n].parent;r[o].parent;)e.unshift(r[o].parent),t=link(conversions[r[o].parent][o],t),o=r[o].parent;return t.conversion=e,t}module.exports=function(n){for(var r=deriveBFS(n),e={},t=Object.keys(r),o=t.length,i=0;i<o;i++){var a=t[i];null!==r[a].parent&&(e[a]=wrapConversion(a,r))}return e};
\ No newline at end of file
index b7c198a..80290bc 100644 (file)
@@ -1,152 +1 @@
-'use strict'\r
-\r
-module.exports = {\r
-       "aliceblue": [240, 248, 255],\r
-       "antiquewhite": [250, 235, 215],\r
-       "aqua": [0, 255, 255],\r
-       "aquamarine": [127, 255, 212],\r
-       "azure": [240, 255, 255],\r
-       "beige": [245, 245, 220],\r
-       "bisque": [255, 228, 196],\r
-       "black": [0, 0, 0],\r
-       "blanchedalmond": [255, 235, 205],\r
-       "blue": [0, 0, 255],\r
-       "blueviolet": [138, 43, 226],\r
-       "brown": [165, 42, 42],\r
-       "burlywood": [222, 184, 135],\r
-       "cadetblue": [95, 158, 160],\r
-       "chartreuse": [127, 255, 0],\r
-       "chocolate": [210, 105, 30],\r
-       "coral": [255, 127, 80],\r
-       "cornflowerblue": [100, 149, 237],\r
-       "cornsilk": [255, 248, 220],\r
-       "crimson": [220, 20, 60],\r
-       "cyan": [0, 255, 255],\r
-       "darkblue": [0, 0, 139],\r
-       "darkcyan": [0, 139, 139],\r
-       "darkgoldenrod": [184, 134, 11],\r
-       "darkgray": [169, 169, 169],\r
-       "darkgreen": [0, 100, 0],\r
-       "darkgrey": [169, 169, 169],\r
-       "darkkhaki": [189, 183, 107],\r
-       "darkmagenta": [139, 0, 139],\r
-       "darkolivegreen": [85, 107, 47],\r
-       "darkorange": [255, 140, 0],\r
-       "darkorchid": [153, 50, 204],\r
-       "darkred": [139, 0, 0],\r
-       "darksalmon": [233, 150, 122],\r
-       "darkseagreen": [143, 188, 143],\r
-       "darkslateblue": [72, 61, 139],\r
-       "darkslategray": [47, 79, 79],\r
-       "darkslategrey": [47, 79, 79],\r
-       "darkturquoise": [0, 206, 209],\r
-       "darkviolet": [148, 0, 211],\r
-       "deeppink": [255, 20, 147],\r
-       "deepskyblue": [0, 191, 255],\r
-       "dimgray": [105, 105, 105],\r
-       "dimgrey": [105, 105, 105],\r
-       "dodgerblue": [30, 144, 255],\r
-       "firebrick": [178, 34, 34],\r
-       "floralwhite": [255, 250, 240],\r
-       "forestgreen": [34, 139, 34],\r
-       "fuchsia": [255, 0, 255],\r
-       "gainsboro": [220, 220, 220],\r
-       "ghostwhite": [248, 248, 255],\r
-       "gold": [255, 215, 0],\r
-       "goldenrod": [218, 165, 32],\r
-       "gray": [128, 128, 128],\r
-       "green": [0, 128, 0],\r
-       "greenyellow": [173, 255, 47],\r
-       "grey": [128, 128, 128],\r
-       "honeydew": [240, 255, 240],\r
-       "hotpink": [255, 105, 180],\r
-       "indianred": [205, 92, 92],\r
-       "indigo": [75, 0, 130],\r
-       "ivory": [255, 255, 240],\r
-       "khaki": [240, 230, 140],\r
-       "lavender": [230, 230, 250],\r
-       "lavenderblush": [255, 240, 245],\r
-       "lawngreen": [124, 252, 0],\r
-       "lemonchiffon": [255, 250, 205],\r
-       "lightblue": [173, 216, 230],\r
-       "lightcoral": [240, 128, 128],\r
-       "lightcyan": [224, 255, 255],\r
-       "lightgoldenrodyellow": [250, 250, 210],\r
-       "lightgray": [211, 211, 211],\r
-       "lightgreen": [144, 238, 144],\r
-       "lightgrey": [211, 211, 211],\r
-       "lightpink": [255, 182, 193],\r
-       "lightsalmon": [255, 160, 122],\r
-       "lightseagreen": [32, 178, 170],\r
-       "lightskyblue": [135, 206, 250],\r
-       "lightslategray": [119, 136, 153],\r
-       "lightslategrey": [119, 136, 153],\r
-       "lightsteelblue": [176, 196, 222],\r
-       "lightyellow": [255, 255, 224],\r
-       "lime": [0, 255, 0],\r
-       "limegreen": [50, 205, 50],\r
-       "linen": [250, 240, 230],\r
-       "magenta": [255, 0, 255],\r
-       "maroon": [128, 0, 0],\r
-       "mediumaquamarine": [102, 205, 170],\r
-       "mediumblue": [0, 0, 205],\r
-       "mediumorchid": [186, 85, 211],\r
-       "mediumpurple": [147, 112, 219],\r
-       "mediumseagreen": [60, 179, 113],\r
-       "mediumslateblue": [123, 104, 238],\r
-       "mediumspringgreen": [0, 250, 154],\r
-       "mediumturquoise": [72, 209, 204],\r
-       "mediumvioletred": [199, 21, 133],\r
-       "midnightblue": [25, 25, 112],\r
-       "mintcream": [245, 255, 250],\r
-       "mistyrose": [255, 228, 225],\r
-       "moccasin": [255, 228, 181],\r
-       "navajowhite": [255, 222, 173],\r
-       "navy": [0, 0, 128],\r
-       "oldlace": [253, 245, 230],\r
-       "olive": [128, 128, 0],\r
-       "olivedrab": [107, 142, 35],\r
-       "orange": [255, 165, 0],\r
-       "orangered": [255, 69, 0],\r
-       "orchid": [218, 112, 214],\r
-       "palegoldenrod": [238, 232, 170],\r
-       "palegreen": [152, 251, 152],\r
-       "paleturquoise": [175, 238, 238],\r
-       "palevioletred": [219, 112, 147],\r
-       "papayawhip": [255, 239, 213],\r
-       "peachpuff": [255, 218, 185],\r
-       "peru": [205, 133, 63],\r
-       "pink": [255, 192, 203],\r
-       "plum": [221, 160, 221],\r
-       "powderblue": [176, 224, 230],\r
-       "purple": [128, 0, 128],\r
-       "rebeccapurple": [102, 51, 153],\r
-       "red": [255, 0, 0],\r
-       "rosybrown": [188, 143, 143],\r
-       "royalblue": [65, 105, 225],\r
-       "saddlebrown": [139, 69, 19],\r
-       "salmon": [250, 128, 114],\r
-       "sandybrown": [244, 164, 96],\r
-       "seagreen": [46, 139, 87],\r
-       "seashell": [255, 245, 238],\r
-       "sienna": [160, 82, 45],\r
-       "silver": [192, 192, 192],\r
-       "skyblue": [135, 206, 235],\r
-       "slateblue": [106, 90, 205],\r
-       "slategray": [112, 128, 144],\r
-       "slategrey": [112, 128, 144],\r
-       "snow": [255, 250, 250],\r
-       "springgreen": [0, 255, 127],\r
-       "steelblue": [70, 130, 180],\r
-       "tan": [210, 180, 140],\r
-       "teal": [0, 128, 128],\r
-       "thistle": [216, 191, 216],\r
-       "tomato": [255, 99, 71],\r
-       "turquoise": [64, 224, 208],\r
-       "violet": [238, 130, 238],\r
-       "wheat": [245, 222, 179],\r
-       "white": [255, 255, 255],\r
-       "whitesmoke": [245, 245, 245],\r
-       "yellow": [255, 255, 0],\r
-       "yellowgreen": [154, 205, 50]\r
-};\r
+"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]};
\ No newline at end of file
index 6e6bf30..6131857 100644 (file)
@@ -1,7 +1 @@
-'use strict'\r
-\r
-var names = require('./');\r
-var assert = require('assert');\r
-\r
-assert.deepEqual(names.red, [255,0,0]);\r
-assert.deepEqual(names.aliceblue, [240,248,255]);\r
+"use strict";var names=require("./"),assert=require("assert");assert.deepEqual(names.red,[255,0,0]),assert.deepEqual(names.aliceblue,[240,248,255]);
\ No newline at end of file
index 4eeb2c0..d4bca0c 100644 (file)
@@ -1,23 +1 @@
-/**
- * Slice reference.
- */
-
-var slice = [].slice;
-
-/**
- * Bind `obj` to `fn`.
- *
- * @param {Object} obj
- * @param {Function|String} fn or string
- * @return {Function}
- * @api public
- */
-
-module.exports = function(obj, fn){
-  if ('string' == typeof fn) fn = obj[fn];
-  if ('function' != typeof fn) throw new Error('bind() requires a function');
-  var args = slice.call(arguments, 2);
-  return function(){
-    return fn.apply(obj, args.concat(slice.call(arguments)));
-  }
-};
+var slice=[].slice;module.exports=function(n,r){if("string"==typeof r&&(r=n[r]),"function"!=typeof r)throw new Error("bind() requires a function");var e=slice.call(arguments,2);return function(){return r.apply(n,e.concat(slice.call(arguments)))}};
\ No newline at end of file
index 7e375c2..2e72fae 100644 (file)
@@ -1,175 +1 @@
-\r
-/**\r
- * Expose `Emitter`.\r
- */\r
-\r
-if (typeof module !== 'undefined') {\r
-  module.exports = Emitter;\r
-}\r
-\r
-/**\r
- * Initialize a new `Emitter`.\r
- *\r
- * @api public\r
- */\r
-\r
-function Emitter(obj) {\r
-  if (obj) return mixin(obj);\r
-};\r
-\r
-/**\r
- * Mixin the emitter properties.\r
- *\r
- * @param {Object} obj\r
- * @return {Object}\r
- * @api private\r
- */\r
-\r
-function mixin(obj) {\r
-  for (var key in Emitter.prototype) {\r
-    obj[key] = Emitter.prototype[key];\r
-  }\r
-  return obj;\r
-}\r
-\r
-/**\r
- * Listen on the given `event` with `fn`.\r
- *\r
- * @param {String} event\r
- * @param {Function} fn\r
- * @return {Emitter}\r
- * @api public\r
- */\r
-\r
-Emitter.prototype.on =\r
-Emitter.prototype.addEventListener = function(event, fn){\r
-  this._callbacks = this._callbacks || {};\r
-  (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\r
-    .push(fn);\r
-  return this;\r
-};\r
-\r
-/**\r
- * Adds an `event` listener that will be invoked a single\r
- * time then automatically removed.\r
- *\r
- * @param {String} event\r
- * @param {Function} fn\r
- * @return {Emitter}\r
- * @api public\r
- */\r
-\r
-Emitter.prototype.once = function(event, fn){\r
-  function on() {\r
-    this.off(event, on);\r
-    fn.apply(this, arguments);\r
-  }\r
-\r
-  on.fn = fn;\r
-  this.on(event, on);\r
-  return this;\r
-};\r
-\r
-/**\r
- * Remove the given callback for `event` or all\r
- * registered callbacks.\r
- *\r
- * @param {String} event\r
- * @param {Function} fn\r
- * @return {Emitter}\r
- * @api public\r
- */\r
-\r
-Emitter.prototype.off =\r
-Emitter.prototype.removeListener =\r
-Emitter.prototype.removeAllListeners =\r
-Emitter.prototype.removeEventListener = function(event, fn){\r
-  this._callbacks = this._callbacks || {};\r
-\r
-  // all\r
-  if (0 == arguments.length) {\r
-    this._callbacks = {};\r
-    return this;\r
-  }\r
-\r
-  // specific event\r
-  var callbacks = this._callbacks['$' + event];\r
-  if (!callbacks) return this;\r
-\r
-  // remove all handlers\r
-  if (1 == arguments.length) {\r
-    delete this._callbacks['$' + event];\r
-    return this;\r
-  }\r
-\r
-  // remove specific handler\r
-  var cb;\r
-  for (var i = 0; i < callbacks.length; i++) {\r
-    cb = callbacks[i];\r
-    if (cb === fn || cb.fn === fn) {\r
-      callbacks.splice(i, 1);\r
-      break;\r
-    }\r
-  }\r
-\r
-  // Remove event specific arrays for event types that no\r
-  // one is subscribed for to avoid memory leak.\r
-  if (callbacks.length === 0) {\r
-    delete this._callbacks['$' + event];\r
-  }\r
-\r
-  return this;\r
-};\r
-\r
-/**\r
- * Emit `event` with the given args.\r
- *\r
- * @param {String} event\r
- * @param {Mixed} ...\r
- * @return {Emitter}\r
- */\r
-\r
-Emitter.prototype.emit = function(event){\r
-  this._callbacks = this._callbacks || {};\r
-\r
-  var args = new Array(arguments.length - 1)\r
-    , callbacks = this._callbacks['$' + event];\r
-\r
-  for (var i = 1; i < arguments.length; i++) {\r
-    args[i - 1] = arguments[i];\r
-  }\r
-\r
-  if (callbacks) {\r
-    callbacks = callbacks.slice(0);\r
-    for (var i = 0, len = callbacks.length; i < len; ++i) {\r
-      callbacks[i].apply(this, args);\r
-    }\r
-  }\r
-\r
-  return this;\r
-};\r
-\r
-/**\r
- * Return array of callbacks for `event`.\r
- *\r
- * @param {String} event\r
- * @return {Array}\r
- * @api public\r
- */\r
-\r
-Emitter.prototype.listeners = function(event){\r
-  this._callbacks = this._callbacks || {};\r
-  return this._callbacks['$' + event] || [];\r
-};\r
-\r
-/**\r
- * Check if this emitter has `event` handlers.\r
- *\r
- * @param {String} event\r
- * @return {Boolean}\r
- * @api public\r
- */\r
-\r
-Emitter.prototype.hasListeners = function(event){\r
-  return !! this.listeners(event).length;\r
-};\r
+function Emitter(t){if(t)return mixin(t)}function mixin(t){for(var e in Emitter.prototype)t[e]=Emitter.prototype[e];return t}"undefined"!=typeof module&&(module.exports=Emitter),Emitter.prototype.on=Emitter.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},Emitter.prototype.once=function(t,e){function i(){this.off(t,i),e.apply(this,arguments)}return i.fn=e,this.on(t,i),this},Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var i,r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var s=0;s<r.length;s++)if((i=r[s])===e||i.fn===e){r.splice(s,1);break}return 0===r.length&&delete this._callbacks["$"+t],this},Emitter.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),i=this._callbacks["$"+t],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(i){r=0;for(var s=(i=i.slice(0)).length;r<s;++r)i[r].apply(this,e)}return this},Emitter.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},Emitter.prototype.hasListeners=function(t){return!!this.listeners(t).length};
\ No newline at end of file
index aaebc03..ba88bdf 100644 (file)
@@ -1,7 +1 @@
-
-module.exports = function(a, b){
-  var fn = function(){};
-  fn.prototype = b.prototype;
-  a.prototype = new fn;
-  a.prototype.constructor = a;
-};
\ No newline at end of file
+module.exports=function(o,t){var p=function(){};p.prototype=t.prototype,o.prototype=new p,o.prototype.constructor=o};
\ No newline at end of file
index 14852f2..44beefe 100644 (file)
@@ -1,21 +1 @@
-
-/**
- * Module dependencies.
- */
-
-var inherit = require('..');
-
-describe('inherit(a, b)', function(){
-  it('should inherit b\'s prototype', function(){
-    function Loki(){}
-    function Animal(){}
-
-    Animal.prototype.species = 'unknown';
-
-    inherit(Loki, Animal);
-
-    var loki = new Loki;
-    loki.species.should.equal('unknown');
-    loki.constructor.should.equal(Loki);
-  })
-})
\ No newline at end of file
+var inherit=require("..");describe("inherit(a, b)",(function(){it("should inherit b's prototype",(function(){function n(){}function e(){}e.prototype.species="unknown",inherit(n,e);var i=new n;i.species.should.equal("unknown"),i.constructor.should.equal(n)}))}));
\ No newline at end of file
index 3365621..02e8e26 100755 (executable)
@@ -1,6 +1 @@
-var concatMap = require('../');
-var xs = [ 1, 2, 3, 4, 5, 6 ];
-var ys = concatMap(xs, function (x) {
-    return x % 2 ? [ x - 0.1, x, x + 0.1 ] : [];
-});
-console.dir(ys);
+var concatMap=require("../"),xs=[1,2,3,4,5,6],ys=concatMap(xs,(function(c){return c%2?[c-.1,c,c+.1]:[]}));console.dir(ys);
\ No newline at end of file
index b29a781..18752ea 100755 (executable)
@@ -1,13 +1 @@
-module.exports = function (xs, fn) {
-    var res = [];
-    for (var i = 0; i < xs.length; i++) {
-        var x = fn(xs[i], i);
-        if (isArray(x)) res.push.apply(res, x);
-        else res.push(x);
-    }
-    return res;
-};
-
-var isArray = Array.isArray || function (xs) {
-    return Object.prototype.toString.call(xs) === '[object Array]';
-};
+module.exports=function(r,t){for(var a=[],o=0;o<r.length;o++){var e=t(r[o],o);isArray(e)?a.push.apply(a,e):a.push(e)}return a};var isArray=Array.isArray||function(r){return"[object Array]"===Object.prototype.toString.call(r)};
\ No newline at end of file
index fdbd702..86f6b84 100755 (executable)
@@ -1,39 +1 @@
-var concatMap = require('../');
-var test = require('tape');
-
-test('empty or not', function (t) {
-    var xs = [ 1, 2, 3, 4, 5, 6 ];
-    var ixes = [];
-    var ys = concatMap(xs, function (x, ix) {
-        ixes.push(ix);
-        return x % 2 ? [ x - 0.1, x, x + 0.1 ] : [];
-    });
-    t.same(ys, [ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ]);
-    t.same(ixes, [ 0, 1, 2, 3, 4, 5 ]);
-    t.end();
-});
-
-test('always something', function (t) {
-    var xs = [ 'a', 'b', 'c', 'd' ];
-    var ys = concatMap(xs, function (x) {
-        return x === 'b' ? [ 'B', 'B', 'B' ] : [ x ];
-    });
-    t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]);
-    t.end();
-});
-
-test('scalars', function (t) {
-    var xs = [ 'a', 'b', 'c', 'd' ];
-    var ys = concatMap(xs, function (x) {
-        return x === 'b' ? [ 'B', 'B', 'B' ] : x;
-    });
-    t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]);
-    t.end();
-});
-
-test('undefs', function (t) {
-    var xs = [ 'a', 'b', 'c', 'd' ];
-    var ys = concatMap(xs, function () {});
-    t.same(ys, [ undefined, undefined, undefined, undefined ]);
-    t.end();
-});
+var concatMap=require("../"),test=require("tape");test("empty or not",(function(n){var a=[],t=concatMap([1,2,3,4,5,6],(function(n,t){return a.push(t),n%2?[n-.1,n,n+.1]:[]}));n.same(t,[.9,1,1.1,2.9,3,3.1,4.9,5,5.1]),n.same(a,[0,1,2,3,4,5]),n.end()})),test("always something",(function(n){var a=concatMap(["a","b","c","d"],(function(n){return"b"===n?["B","B","B"]:[n]}));n.same(a,["a","B","B","B","c","d"]),n.end()})),test("scalars",(function(n){var a=concatMap(["a","b","c","d"],(function(n){return"b"===n?["B","B","B"]:n}));n.same(a,["a","B","B","B","c","d"]),n.end()})),test("undefs",(function(n){var a=concatMap(["a","b","c","d"],(function(){}));n.same(a,[void 0,void 0,void 0,void 0]),n.end()}));
\ No newline at end of file
index 3092a4d..c244679 100644 (file)
@@ -3,456 +3,4 @@
  * Copyright(c) 2014-2017 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = contentDisposition
-module.exports.parse = parse
-
-/**
- * Module dependencies.
- * @private
- */
-
-var basename = require('path').basename
-var Buffer = require('safe-buffer').Buffer
-
-/**
- * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%")
- * @private
- */
-
-var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex
-
-/**
- * RegExp to match percent encoding escape.
- * @private
- */
-
-var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/
-var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g
-
-/**
- * RegExp to match non-latin1 characters.
- * @private
- */
-
-var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g
-
-/**
- * RegExp to match quoted-pair in RFC 2616
- *
- * quoted-pair = "\" CHAR
- * CHAR        = <any US-ASCII character (octets 0 - 127)>
- * @private
- */
-
-var QESC_REGEXP = /\\([\u0000-\u007f])/g // eslint-disable-line no-control-regex
-
-/**
- * RegExp to match chars that must be quoted-pair in RFC 2616
- * @private
- */
-
-var QUOTE_REGEXP = /([\\"])/g
-
-/**
- * RegExp for various RFC 2616 grammar
- *
- * parameter     = token "=" ( token | quoted-string )
- * token         = 1*<any CHAR except CTLs or separators>
- * separators    = "(" | ")" | "<" | ">" | "@"
- *               | "," | ";" | ":" | "\" | <">
- *               | "/" | "[" | "]" | "?" | "="
- *               | "{" | "}" | SP | HT
- * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
- * qdtext        = <any TEXT except <">>
- * quoted-pair   = "\" CHAR
- * CHAR          = <any US-ASCII character (octets 0 - 127)>
- * TEXT          = <any OCTET except CTLs, but including LWS>
- * LWS           = [CRLF] 1*( SP | HT )
- * CRLF          = CR LF
- * CR            = <US-ASCII CR, carriage return (13)>
- * LF            = <US-ASCII LF, linefeed (10)>
- * SP            = <US-ASCII SP, space (32)>
- * HT            = <US-ASCII HT, horizontal-tab (9)>
- * CTL           = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
- * OCTET         = <any 8-bit sequence of data>
- * @private
- */
-
-var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex
-var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/
-var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/
-
-/**
- * RegExp for various RFC 5987 grammar
- *
- * ext-value     = charset  "'" [ language ] "'" value-chars
- * charset       = "UTF-8" / "ISO-8859-1" / mime-charset
- * mime-charset  = 1*mime-charsetc
- * mime-charsetc = ALPHA / DIGIT
- *               / "!" / "#" / "$" / "%" / "&"
- *               / "+" / "-" / "^" / "_" / "`"
- *               / "{" / "}" / "~"
- * language      = ( 2*3ALPHA [ extlang ] )
- *               / 4ALPHA
- *               / 5*8ALPHA
- * extlang       = *3( "-" 3ALPHA )
- * value-chars   = *( pct-encoded / attr-char )
- * pct-encoded   = "%" HEXDIG HEXDIG
- * attr-char     = ALPHA / DIGIT
- *               / "!" / "#" / "$" / "&" / "+" / "-" / "."
- *               / "^" / "_" / "`" / "|" / "~"
- * @private
- */
-
-var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/
-
-/**
- * RegExp for various RFC 6266 grammar
- *
- * disposition-type = "inline" | "attachment" | disp-ext-type
- * disp-ext-type    = token
- * disposition-parm = filename-parm | disp-ext-parm
- * filename-parm    = "filename" "=" value
- *                  | "filename*" "=" ext-value
- * disp-ext-parm    = token "=" value
- *                  | ext-token "=" ext-value
- * ext-token        = <the characters in token, followed by "*">
- * @private
- */
-
-var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex
-
-/**
- * Create an attachment Content-Disposition header.
- *
- * @param {string} [filename]
- * @param {object} [options]
- * @param {string} [options.type=attachment]
- * @param {string|boolean} [options.fallback=true]
- * @return {string}
- * @public
- */
-
-function contentDisposition (filename, options) {
-  var opts = options || {}
-
-  // get type
-  var type = opts.type || 'attachment'
-
-  // get parameters
-  var params = createparams(filename, opts.fallback)
-
-  // format into string
-  return format(new ContentDisposition(type, params))
-}
-
-/**
- * Create parameters object from filename and fallback.
- *
- * @param {string} [filename]
- * @param {string|boolean} [fallback=true]
- * @return {object}
- * @private
- */
-
-function createparams (filename, fallback) {
-  if (filename === undefined) {
-    return
-  }
-
-  var params = {}
-
-  if (typeof filename !== 'string') {
-    throw new TypeError('filename must be a string')
-  }
-
-  // fallback defaults to true
-  if (fallback === undefined) {
-    fallback = true
-  }
-
-  if (typeof fallback !== 'string' && typeof fallback !== 'boolean') {
-    throw new TypeError('fallback must be a string or boolean')
-  }
-
-  if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) {
-    throw new TypeError('fallback must be ISO-8859-1 string')
-  }
-
-  // restrict to file base name
-  var name = basename(filename)
-
-  // determine if name is suitable for quoted string
-  var isQuotedString = TEXT_REGEXP.test(name)
-
-  // generate fallback name
-  var fallbackName = typeof fallback !== 'string'
-    ? fallback && getlatin1(name)
-    : basename(fallback)
-  var hasFallback = typeof fallbackName === 'string' && fallbackName !== name
-
-  // set extended filename parameter
-  if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) {
-    params['filename*'] = name
-  }
-
-  // set filename parameter
-  if (isQuotedString || hasFallback) {
-    params.filename = hasFallback
-      ? fallbackName
-      : name
-  }
-
-  return params
-}
-
-/**
- * Format object to Content-Disposition header.
- *
- * @param {object} obj
- * @param {string} obj.type
- * @param {object} [obj.parameters]
- * @return {string}
- * @private
- */
-
-function format (obj) {
-  var parameters = obj.parameters
-  var type = obj.type
-
-  if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) {
-    throw new TypeError('invalid type')
-  }
-
-  // start with normalized type
-  var string = String(type).toLowerCase()
-
-  // append parameters
-  if (parameters && typeof parameters === 'object') {
-    var param
-    var params = Object.keys(parameters).sort()
-
-    for (var i = 0; i < params.length; i++) {
-      param = params[i]
-
-      var val = param.substr(-1) === '*'
-        ? ustring(parameters[param])
-        : qstring(parameters[param])
-
-      string += '; ' + param + '=' + val
-    }
-  }
-
-  return string
-}
-
-/**
- * Decode a RFC 6987 field value (gracefully).
- *
- * @param {string} str
- * @return {string}
- * @private
- */
-
-function decodefield (str) {
-  var match = EXT_VALUE_REGEXP.exec(str)
-
-  if (!match) {
-    throw new TypeError('invalid extended field value')
-  }
-
-  var charset = match[1].toLowerCase()
-  var encoded = match[2]
-  var value
-
-  // to binary string
-  var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode)
-
-  switch (charset) {
-    case 'iso-8859-1':
-      value = getlatin1(binary)
-      break
-    case 'utf-8':
-      value = Buffer.from(binary, 'binary').toString('utf8')
-      break
-    default:
-      throw new TypeError('unsupported charset in extended field')
-  }
-
-  return value
-}
-
-/**
- * Get ISO-8859-1 version of string.
- *
- * @param {string} val
- * @return {string}
- * @private
- */
-
-function getlatin1 (val) {
-  // simple Unicode -> ISO-8859-1 transformation
-  return String(val).replace(NON_LATIN1_REGEXP, '?')
-}
-
-/**
- * Parse Content-Disposition header string.
- *
- * @param {string} string
- * @return {object}
- * @public
- */
-
-function parse (string) {
-  if (!string || typeof string !== 'string') {
-    throw new TypeError('argument string is required')
-  }
-
-  var match = DISPOSITION_TYPE_REGEXP.exec(string)
-
-  if (!match) {
-    throw new TypeError('invalid type format')
-  }
-
-  // normalize type
-  var index = match[0].length
-  var type = match[1].toLowerCase()
-
-  var key
-  var names = []
-  var params = {}
-  var value
-
-  // calculate index to start at
-  index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';'
-    ? index - 1
-    : index
-
-  // match parameters
-  while ((match = PARAM_REGEXP.exec(string))) {
-    if (match.index !== index) {
-      throw new TypeError('invalid parameter format')
-    }
-
-    index += match[0].length
-    key = match[1].toLowerCase()
-    value = match[2]
-
-    if (names.indexOf(key) !== -1) {
-      throw new TypeError('invalid duplicate parameter')
-    }
-
-    names.push(key)
-
-    if (key.indexOf('*') + 1 === key.length) {
-      // decode extended value
-      key = key.slice(0, -1)
-      value = decodefield(value)
-
-      // overwrite existing value
-      params[key] = value
-      continue
-    }
-
-    if (typeof params[key] === 'string') {
-      continue
-    }
-
-    if (value[0] === '"') {
-      // remove quotes and escapes
-      value = value
-        .substr(1, value.length - 2)
-        .replace(QESC_REGEXP, '$1')
-    }
-
-    params[key] = value
-  }
-
-  if (index !== -1 && index !== string.length) {
-    throw new TypeError('invalid parameter format')
-  }
-
-  return new ContentDisposition(type, params)
-}
-
-/**
- * Percent decode a single character.
- *
- * @param {string} str
- * @param {string} hex
- * @return {string}
- * @private
- */
-
-function pdecode (str, hex) {
-  return String.fromCharCode(parseInt(hex, 16))
-}
-
-/**
- * Percent encode a single character.
- *
- * @param {string} char
- * @return {string}
- * @private
- */
-
-function pencode (char) {
-  return '%' + String(char)
-    .charCodeAt(0)
-    .toString(16)
-    .toUpperCase()
-}
-
-/**
- * Quote a string for HTTP.
- *
- * @param {string} val
- * @return {string}
- * @private
- */
-
-function qstring (val) {
-  var str = String(val)
-
-  return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"'
-}
-
-/**
- * Encode a Unicode string for HTTP (RFC 5987).
- *
- * @param {string} val
- * @return {string}
- * @private
- */
-
-function ustring (val) {
-  var str = String(val)
-
-  // percent encode as UTF-8
-  var encoded = encodeURIComponent(str)
-    .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode)
-
-  return 'UTF-8\'\'' + encoded
-}
-
-/**
- * Class for parsed Content-Disposition header for v8 optimization
- *
- * @public
- * @param {string} type
- * @param {object} parameters
- * @constructor
- */
-
-function ContentDisposition (type, parameters) {
-  this.type = type
-  this.parameters = parameters
-}
+"use strict";module.exports=contentDisposition,module.exports.parse=parse;var basename=require("path").basename,Buffer=require("safe-buffer").Buffer,ENCODE_URL_ATTR_CHAR_REGEXP=/[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g,HEX_ESCAPE_REGEXP=/%[0-9A-Fa-f]{2}/,HEX_ESCAPE_REPLACE_REGEXP=/%([0-9A-Fa-f]{2})/g,NON_LATIN1_REGEXP=/[^\x20-\x7e\xa0-\xff]/g,QESC_REGEXP=/\\([\u0000-\u007f])/g,QUOTE_REGEXP=/([\\"])/g,PARAM_REGEXP=/;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g,TEXT_REGEXP=/^[\x20-\x7e\x80-\xff]+$/,TOKEN_REGEXP=/^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/,EXT_VALUE_REGEXP=/^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/,DISPOSITION_TYPE_REGEXP=/^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/;function contentDisposition(e,r){var t=r||{};return format(new ContentDisposition(t.type||"attachment",createparams(e,t.fallback)))}function createparams(e,r){if(void 0!==e){var t={};if("string"!=typeof e)throw new TypeError("filename must be a string");if(void 0===r&&(r=!0),"string"!=typeof r&&"boolean"!=typeof r)throw new TypeError("fallback must be a string or boolean");if("string"==typeof r&&NON_LATIN1_REGEXP.test(r))throw new TypeError("fallback must be ISO-8859-1 string");var n=basename(e),a=TEXT_REGEXP.test(n),o="string"!=typeof r?r&&getlatin1(n):basename(r),i="string"==typeof o&&o!==n;return(i||!a||HEX_ESCAPE_REGEXP.test(n))&&(t["filename*"]=n),(a||i)&&(t.filename=i?o:n),t}}function format(e){var r=e.parameters,t=e.type;if(!t||"string"!=typeof t||!TOKEN_REGEXP.test(t))throw new TypeError("invalid type");var n=String(t).toLowerCase();if(r&&"object"==typeof r)for(var a,o=Object.keys(r).sort(),i=0;i<o.length;i++){var E="*"===(a=o[i]).substr(-1)?ustring(r[a]):qstring(r[a]);n+="; "+a+"="+E}return n}function decodefield(e){var r=EXT_VALUE_REGEXP.exec(e);if(!r)throw new TypeError("invalid extended field value");var t,n=r[1].toLowerCase(),a=r[2].replace(HEX_ESCAPE_REPLACE_REGEXP,pdecode);switch(n){case"iso-8859-1":t=getlatin1(a);break;case"utf-8":t=Buffer.from(a,"binary").toString("utf8");break;default:throw new TypeError("unsupported charset in extended field")}return t}function getlatin1(e){return String(e).replace(NON_LATIN1_REGEXP,"?")}function parse(e){if(!e||"string"!=typeof e)throw new TypeError("argument string is required");var r=DISPOSITION_TYPE_REGEXP.exec(e);if(!r)throw new TypeError("invalid type format");var t,n,a=r[0].length,o=r[1].toLowerCase(),i=[],E={};for(a=PARAM_REGEXP.lastIndex=";"===r[0].substr(-1)?a-1:a;r=PARAM_REGEXP.exec(e);){if(r.index!==a)throw new TypeError("invalid parameter format");if(a+=r[0].length,t=r[1].toLowerCase(),n=r[2],-1!==i.indexOf(t))throw new TypeError("invalid duplicate parameter");i.push(t),t.indexOf("*")+1!==t.length?"string"!=typeof E[t]&&('"'===n[0]&&(n=n.substr(1,n.length-2).replace(QESC_REGEXP,"$1")),E[t]=n):(t=t.slice(0,-1),n=decodefield(n),E[t]=n)}if(-1!==a&&a!==e.length)throw new TypeError("invalid parameter format");return new ContentDisposition(o,E)}function pdecode(e,r){return String.fromCharCode(parseInt(r,16))}function pencode(e){return"%"+String(e).charCodeAt(0).toString(16).toUpperCase()}function qstring(e){return'"'+String(e).replace(QUOTE_REGEXP,"\\$1")+'"'}function ustring(e){var r=String(e);return"UTF-8''"+encodeURIComponent(r).replace(ENCODE_URL_ATTR_CHAR_REGEXP,pencode)}function ContentDisposition(e,r){this.type=e,this.parameters=r}
\ No newline at end of file
index 6ce03f2..19a253a 100644 (file)
@@ -3,220 +3,4 @@
  * Copyright(c) 2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1
- *
- * parameter     = token "=" ( token / quoted-string )
- * token         = 1*tchar
- * tchar         = "!" / "#" / "$" / "%" / "&" / "'" / "*"
- *               / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
- *               / DIGIT / ALPHA
- *               ; any VCHAR, except delimiters
- * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
- * qdtext        = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text
- * obs-text      = %x80-FF
- * quoted-pair   = "\" ( HTAB / SP / VCHAR / obs-text )
- */
-var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g
-var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/
-var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/
-
-/**
- * RegExp to match quoted-pair in RFC 7230 sec 3.2.6
- *
- * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
- * obs-text    = %x80-FF
- */
-var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g
-
-/**
- * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6
- */
-var QUOTE_REGEXP = /([\\"])/g
-
-/**
- * RegExp to match type in RFC 7231 sec 3.1.1.1
- *
- * media-type = type "/" subtype
- * type       = token
- * subtype    = token
- */
-var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/
-
-/**
- * Module exports.
- * @public
- */
-
-exports.format = format
-exports.parse = parse
-
-/**
- * Format object to media type.
- *
- * @param {object} obj
- * @return {string}
- * @public
- */
-
-function format (obj) {
-  if (!obj || typeof obj !== 'object') {
-    throw new TypeError('argument obj is required')
-  }
-
-  var parameters = obj.parameters
-  var type = obj.type
-
-  if (!type || !TYPE_REGEXP.test(type)) {
-    throw new TypeError('invalid type')
-  }
-
-  var string = type
-
-  // append parameters
-  if (parameters && typeof parameters === 'object') {
-    var param
-    var params = Object.keys(parameters).sort()
-
-    for (var i = 0; i < params.length; i++) {
-      param = params[i]
-
-      if (!TOKEN_REGEXP.test(param)) {
-        throw new TypeError('invalid parameter name')
-      }
-
-      string += '; ' + param + '=' + qstring(parameters[param])
-    }
-  }
-
-  return string
-}
-
-/**
- * Parse media type to object.
- *
- * @param {string|object} string
- * @return {Object}
- * @public
- */
-
-function parse (string) {
-  if (!string) {
-    throw new TypeError('argument string is required')
-  }
-
-  // support req/res-like objects as argument
-  var header = typeof string === 'object'
-    ? getcontenttype(string)
-    : string
-
-  if (typeof header !== 'string') {
-    throw new TypeError('argument string is required to be a string')
-  }
-
-  var index = header.indexOf(';')
-  var type = index !== -1
-    ? header.substr(0, index).trim()
-    : header.trim()
-
-  if (!TYPE_REGEXP.test(type)) {
-    throw new TypeError('invalid media type')
-  }
-
-  var obj = new ContentType(type.toLowerCase())
-
-  // parse parameters
-  if (index !== -1) {
-    var key
-    var match
-    var value
-
-    PARAM_REGEXP.lastIndex = index
-
-    while ((match = PARAM_REGEXP.exec(header))) {
-      if (match.index !== index) {
-        throw new TypeError('invalid parameter format')
-      }
-
-      index += match[0].length
-      key = match[1].toLowerCase()
-      value = match[2]
-
-      if (value[0] === '"') {
-        // remove quotes and escapes
-        value = value
-          .substr(1, value.length - 2)
-          .replace(QESC_REGEXP, '$1')
-      }
-
-      obj.parameters[key] = value
-    }
-
-    if (index !== header.length) {
-      throw new TypeError('invalid parameter format')
-    }
-  }
-
-  return obj
-}
-
-/**
- * Get content-type from req/res objects.
- *
- * @param {object}
- * @return {Object}
- * @private
- */
-
-function getcontenttype (obj) {
-  var header
-
-  if (typeof obj.getHeader === 'function') {
-    // res-like
-    header = obj.getHeader('content-type')
-  } else if (typeof obj.headers === 'object') {
-    // req-like
-    header = obj.headers && obj.headers['content-type']
-  }
-
-  if (typeof header !== 'string') {
-    throw new TypeError('content-type header is missing from object')
-  }
-
-  return header
-}
-
-/**
- * Quote a string if necessary.
- *
- * @param {string} val
- * @return {string}
- * @private
- */
-
-function qstring (val) {
-  var str = String(val)
-
-  // no need to quote tokens
-  if (TOKEN_REGEXP.test(str)) {
-    return str
-  }
-
-  if (str.length > 0 && !TEXT_REGEXP.test(str)) {
-    throw new TypeError('invalid parameter value')
-  }
-
-  return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"'
-}
-
-/**
- * Class to represent a content type.
- * @private
- */
-function ContentType (type) {
-  this.parameters = Object.create(null)
-  this.type = type
-}
+"use strict";var PARAM_REGEXP=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,TEXT_REGEXP=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,TOKEN_REGEXP=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,QESC_REGEXP=/\\([\u000b\u0020-\u00ff])/g,QUOTE_REGEXP=/([\\"])/g,TYPE_REGEXP=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;function format(e){if(!e||"object"!=typeof e)throw new TypeError("argument obj is required");var r=e.parameters,t=e.type;if(!t||!TYPE_REGEXP.test(t))throw new TypeError("invalid type");var n=t;if(r&&"object"==typeof r)for(var a,o=Object.keys(r).sort(),i=0;i<o.length;i++){if(a=o[i],!TOKEN_REGEXP.test(a))throw new TypeError("invalid parameter name");n+="; "+a+"="+qstring(r[a])}return n}function parse(e){if(!e)throw new TypeError("argument string is required");var r="object"==typeof e?getcontenttype(e):e;if("string"!=typeof r)throw new TypeError("argument string is required to be a string");var t=r.indexOf(";"),n=-1!==t?r.substr(0,t).trim():r.trim();if(!TYPE_REGEXP.test(n))throw new TypeError("invalid media type");var a=new ContentType(n.toLowerCase());if(-1!==t){var o,i,E;for(PARAM_REGEXP.lastIndex=t;i=PARAM_REGEXP.exec(r);){if(i.index!==t)throw new TypeError("invalid parameter format");t+=i[0].length,o=i[1].toLowerCase(),'"'===(E=i[2])[0]&&(E=E.substr(1,E.length-2).replace(QESC_REGEXP,"$1")),a.parameters[o]=E}if(t!==r.length)throw new TypeError("invalid parameter format")}return a}function getcontenttype(e){var r;if("function"==typeof e.getHeader?r=e.getHeader("content-type"):"object"==typeof e.headers&&(r=e.headers&&e.headers["content-type"]),"string"!=typeof r)throw new TypeError("content-type header is missing from object");return r}function qstring(e){var r=String(e);if(TOKEN_REGEXP.test(r))return r;if(r.length>0&&!TEXT_REGEXP.test(r))throw new TypeError("invalid parameter value");return'"'+r.replace(QUOTE_REGEXP,"\\$1")+'"'}function ContentType(e){this.parameters=Object.create(null),this.type=e}exports.format=format,exports.parse=parse;
\ No newline at end of file
index b8c9463..e753ce5 100644 (file)
@@ -1,51 +1 @@
-/**
- * Module dependencies.
- */
-
-var crypto = require('crypto');
-
-/**
- * Sign the given `val` with `secret`.
- *
- * @param {String} val
- * @param {String} secret
- * @return {String}
- * @api private
- */
-
-exports.sign = function(val, secret){
-  if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string.");
-  if ('string' != typeof secret) throw new TypeError("Secret string must be provided.");
-  return val + '.' + crypto
-    .createHmac('sha256', secret)
-    .update(val)
-    .digest('base64')
-    .replace(/\=+$/, '');
-};
-
-/**
- * Unsign and decode the given `val` with `secret`,
- * returning `false` if the signature is invalid.
- *
- * @param {String} val
- * @param {String} secret
- * @return {String|Boolean}
- * @api private
- */
-
-exports.unsign = function(val, secret){
-  if ('string' != typeof val) throw new TypeError("Signed cookie string must be provided.");
-  if ('string' != typeof secret) throw new TypeError("Secret string must be provided.");
-  var str = val.slice(0, val.lastIndexOf('.'))
-    , mac = exports.sign(str, secret);
-  
-  return sha1(mac) == sha1(val) ? str : false;
-};
-
-/**
- * Private
- */
-
-function sha1(str){
-  return crypto.createHash('sha1').update(str).digest('hex');
-}
+var crypto=require("crypto");function sha1(e){return crypto.createHash("sha1").update(e).digest("hex")}exports.sign=function(e,r){if("string"!=typeof e)throw new TypeError("Cookie value must be provided as a string.");if("string"!=typeof r)throw new TypeError("Secret string must be provided.");return e+"."+crypto.createHmac("sha256",r).update(e).digest("base64").replace(/\=+$/,"")},exports.unsign=function(e,r){if("string"!=typeof e)throw new TypeError("Signed cookie string must be provided.");if("string"!=typeof r)throw new TypeError("Secret string must be provided.");var t=e.slice(0,e.lastIndexOf("."));return sha1(exports.sign(t,r))==sha1(e)&&t};
\ No newline at end of file
index 16f56c0..8addef0 100644 (file)
@@ -4,195 +4,4 @@
  * Copyright(c) 2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict';
-
-/**
- * Module exports.
- * @public
- */
-
-exports.parse = parse;
-exports.serialize = serialize;
-
-/**
- * Module variables.
- * @private
- */
-
-var decode = decodeURIComponent;
-var encode = encodeURIComponent;
-var pairSplitRegExp = /; */;
-
-/**
- * RegExp to match field-content in RFC 7230 sec 3.2
- *
- * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
- * field-vchar   = VCHAR / obs-text
- * obs-text      = %x80-FF
- */
-
-var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
-
-/**
- * Parse a cookie header.
- *
- * Parse the given cookie header string into an object
- * The object has the various cookies as keys(names) => values
- *
- * @param {string} str
- * @param {object} [options]
- * @return {object}
- * @public
- */
-
-function parse(str, options) {
-  if (typeof str !== 'string') {
-    throw new TypeError('argument str must be a string');
-  }
-
-  var obj = {}
-  var opt = options || {};
-  var pairs = str.split(pairSplitRegExp);
-  var dec = opt.decode || decode;
-
-  for (var i = 0; i < pairs.length; i++) {
-    var pair = pairs[i];
-    var eq_idx = pair.indexOf('=');
-
-    // skip things that don't look like key=value
-    if (eq_idx < 0) {
-      continue;
-    }
-
-    var key = pair.substr(0, eq_idx).trim()
-    var val = pair.substr(++eq_idx, pair.length).trim();
-
-    // quoted values
-    if ('"' == val[0]) {
-      val = val.slice(1, -1);
-    }
-
-    // only assign once
-    if (undefined == obj[key]) {
-      obj[key] = tryDecode(val, dec);
-    }
-  }
-
-  return obj;
-}
-
-/**
- * Serialize data into a cookie header.
- *
- * Serialize the a name value pair into a cookie string suitable for
- * http headers. An optional options object specified cookie parameters.
- *
- * serialize('foo', 'bar', { httpOnly: true })
- *   => "foo=bar; httpOnly"
- *
- * @param {string} name
- * @param {string} val
- * @param {object} [options]
- * @return {string}
- * @public
- */
-
-function serialize(name, val, options) {
-  var opt = options || {};
-  var enc = opt.encode || encode;
-
-  if (typeof enc !== 'function') {
-    throw new TypeError('option encode is invalid');
-  }
-
-  if (!fieldContentRegExp.test(name)) {
-    throw new TypeError('argument name is invalid');
-  }
-
-  var value = enc(val);
-
-  if (value && !fieldContentRegExp.test(value)) {
-    throw new TypeError('argument val is invalid');
-  }
-
-  var str = name + '=' + value;
-
-  if (null != opt.maxAge) {
-    var maxAge = opt.maxAge - 0;
-    if (isNaN(maxAge)) throw new Error('maxAge should be a Number');
-    str += '; Max-Age=' + Math.floor(maxAge);
-  }
-
-  if (opt.domain) {
-    if (!fieldContentRegExp.test(opt.domain)) {
-      throw new TypeError('option domain is invalid');
-    }
-
-    str += '; Domain=' + opt.domain;
-  }
-
-  if (opt.path) {
-    if (!fieldContentRegExp.test(opt.path)) {
-      throw new TypeError('option path is invalid');
-    }
-
-    str += '; Path=' + opt.path;
-  }
-
-  if (opt.expires) {
-    if (typeof opt.expires.toUTCString !== 'function') {
-      throw new TypeError('option expires is invalid');
-    }
-
-    str += '; Expires=' + opt.expires.toUTCString();
-  }
-
-  if (opt.httpOnly) {
-    str += '; HttpOnly';
-  }
-
-  if (opt.secure) {
-    str += '; Secure';
-  }
-
-  if (opt.sameSite) {
-    var sameSite = typeof opt.sameSite === 'string'
-      ? opt.sameSite.toLowerCase() : opt.sameSite;
-
-    switch (sameSite) {
-      case true:
-        str += '; SameSite=Strict';
-        break;
-      case 'lax':
-        str += '; SameSite=Lax';
-        break;
-      case 'strict':
-        str += '; SameSite=Strict';
-        break;
-      case 'none':
-        str += '; SameSite=None';
-        break;
-      default:
-        throw new TypeError('option sameSite is invalid');
-    }
-  }
-
-  return str;
-}
-
-/**
- * Try decoding a string using a decoding function.
- *
- * @param {string} str
- * @param {function} decode
- * @private
- */
-
-function tryDecode(str, decode) {
-  try {
-    return decode(str);
-  } catch (e) {
-    return str;
-  }
-}
+"use strict";exports.parse=parse,exports.serialize=serialize;var decode=decodeURIComponent,encode=encodeURIComponent,pairSplitRegExp=/; */,fieldContentRegExp=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function parse(e,t){if("string"!=typeof e)throw new TypeError("argument str must be a string");for(var r={},i=t||{},n=e.split(pairSplitRegExp),o=i.decode||decode,a=0;a<n.length;a++){var s=n[a],p=s.indexOf("=");if(!(p<0)){var d=s.substr(0,p).trim(),f=s.substr(++p,s.length).trim();'"'==f[0]&&(f=f.slice(1,-1)),null==r[d]&&(r[d]=tryDecode(f,o))}}return r}function serialize(e,t,r){var i=r||{},n=i.encode||encode;if("function"!=typeof n)throw new TypeError("option encode is invalid");if(!fieldContentRegExp.test(e))throw new TypeError("argument name is invalid");var o=n(t);if(o&&!fieldContentRegExp.test(o))throw new TypeError("argument val is invalid");var a=e+"="+o;if(null!=i.maxAge){var s=i.maxAge-0;if(isNaN(s))throw new Error("maxAge should be a Number");a+="; Max-Age="+Math.floor(s)}if(i.domain){if(!fieldContentRegExp.test(i.domain))throw new TypeError("option domain is invalid");a+="; Domain="+i.domain}if(i.path){if(!fieldContentRegExp.test(i.path))throw new TypeError("option path is invalid");a+="; Path="+i.path}if(i.expires){if("function"!=typeof i.expires.toUTCString)throw new TypeError("option expires is invalid");a+="; Expires="+i.expires.toUTCString()}if(i.httpOnly&&(a+="; HttpOnly"),i.secure&&(a+="; Secure"),i.sameSite)switch("string"==typeof i.sameSite?i.sameSite.toLowerCase():i.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return a}function tryDecode(e,t){try{return t(e)}catch(t){return e}}
\ No newline at end of file
index 103a82d..cedc227 100755 (executable)
@@ -1,70 +1 @@
-// Karma configuration
-// Generated on Fri Dec 16 2016 13:09:51 GMT+0000 (UTC)
-
-module.exports = function(config) {
-  config.set({
-
-    // base path that will be used to resolve all patterns (eg. files, exclude)
-    basePath: '',
-
-
-    // frameworks to use
-    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
-    frameworks: ['mocha', 'chai', 'sinon'],
-
-
-    // list of files / patterns to load in the browser
-    files: [
-      'dist/debug.js',
-      'test/*spec.js'
-    ],
-
-
-    // list of files to exclude
-    exclude: [
-      'src/node.js'
-    ],
-
-
-    // preprocess matching files before serving them to the browser
-    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
-    preprocessors: {
-    },
-
-    // test results reporter to use
-    // possible values: 'dots', 'progress'
-    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
-    reporters: ['progress'],
-
-
-    // web server port
-    port: 9876,
-
-
-    // enable / disable colors in the output (reporters and logs)
-    colors: true,
-
-
-    // level of logging
-    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
-    logLevel: config.LOG_INFO,
-
-
-    // enable / disable watching file and executing tests whenever any file changes
-    autoWatch: true,
-
-
-    // start these browsers
-    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
-    browsers: ['PhantomJS'],
-
-
-    // Continuous Integration mode
-    // if true, Karma captures browsers, runs the tests and exits
-    singleRun: false,
-
-    // Concurrency level
-    // how many browser should be started simultaneous
-    concurrency: Infinity
-  })
-}
+module.exports=function(s){s.set({basePath:"",frameworks:["mocha","chai","sinon"],files:["dist/debug.js","test/*spec.js"],exclude:["src/node.js"],preprocessors:{},reporters:["progress"],port:9876,colors:!0,logLevel:s.LOG_INFO,autoWatch:!0,browsers:["PhantomJS"],singleRun:!1,concurrency:1/0})};
\ No newline at end of file
index 7fc36fe..6c0c263 100755 (executable)
@@ -1 +1 @@
-module.exports = require('./src/node');
+module.exports=require("./src/node");
\ No newline at end of file
index 7106924..7bb5111 100755 (executable)
@@ -1,185 +1 @@
-/**
- * This is the web browser implementation of `debug()`.
- *
- * Expose `debug()` as the module.
- */
-
-exports = module.exports = require('./debug');
-exports.log = log;
-exports.formatArgs = formatArgs;
-exports.save = save;
-exports.load = load;
-exports.useColors = useColors;
-exports.storage = 'undefined' != typeof chrome
-               && 'undefined' != typeof chrome.storage
-                  ? chrome.storage.local
-                  : localstorage();
-
-/**
- * Colors.
- */
-
-exports.colors = [
-  'lightseagreen',
-  'forestgreen',
-  'goldenrod',
-  'dodgerblue',
-  'darkorchid',
-  'crimson'
-];
-
-/**
- * Currently only WebKit-based Web Inspectors, Firefox >= v31,
- * and the Firebug extension (any Firefox version) are known
- * to support "%c" CSS customizations.
- *
- * TODO: add a `localStorage` variable to explicitly enable/disable colors
- */
-
-function useColors() {
-  // NB: In an Electron preload script, document will be defined but not fully
-  // initialized. Since we know we're in Chrome, we'll just detect this case
-  // explicitly
-  if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
-    return true;
-  }
-
-  // is webkit? http://stackoverflow.com/a/16459606/376773
-  // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
-  return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
-    // is firebug? http://stackoverflow.com/a/398120/376773
-    (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
-    // is firefox >= v31?
-    // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
-    (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
-    // double check webkit in userAgent just in case we are in a worker
-    (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
-}
-
-/**
- * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
- */
-
-exports.formatters.j = function(v) {
-  try {
-    return JSON.stringify(v);
-  } catch (err) {
-    return '[UnexpectedJSONParseError]: ' + err.message;
-  }
-};
-
-
-/**
- * Colorize log arguments if enabled.
- *
- * @api public
- */
-
-function formatArgs(args) {
-  var useColors = this.useColors;
-
-  args[0] = (useColors ? '%c' : '')
-    + this.namespace
-    + (useColors ? ' %c' : ' ')
-    + args[0]
-    + (useColors ? '%c ' : ' ')
-    + '+' + exports.humanize(this.diff);
-
-  if (!useColors) return;
-
-  var c = 'color: ' + this.color;
-  args.splice(1, 0, c, 'color: inherit')
-
-  // the final "%c" is somewhat tricky, because there could be other
-  // arguments passed either before or after the %c, so we need to
-  // figure out the correct index to insert the CSS into
-  var index = 0;
-  var lastC = 0;
-  args[0].replace(/%[a-zA-Z%]/g, function(match) {
-    if ('%%' === match) return;
-    index++;
-    if ('%c' === match) {
-      // we only are interested in the *last* %c
-      // (the user may have provided their own)
-      lastC = index;
-    }
-  });
-
-  args.splice(lastC, 0, c);
-}
-
-/**
- * Invokes `console.log()` when available.
- * No-op when `console.log` is not a "function".
- *
- * @api public
- */
-
-function log() {
-  // this hackery is required for IE8/9, where
-  // the `console.log` function doesn't have 'apply'
-  return 'object' === typeof console
-    && console.log
-    && Function.prototype.apply.call(console.log, console, arguments);
-}
-
-/**
- * Save `namespaces`.
- *
- * @param {String} namespaces
- * @api private
- */
-
-function save(namespaces) {
-  try {
-    if (null == namespaces) {
-      exports.storage.removeItem('debug');
-    } else {
-      exports.storage.debug = namespaces;
-    }
-  } catch(e) {}
-}
-
-/**
- * Load `namespaces`.
- *
- * @return {String} returns the previously persisted debug modes
- * @api private
- */
-
-function load() {
-  var r;
-  try {
-    r = exports.storage.debug;
-  } catch(e) {}
-
-  // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
-  if (!r && typeof process !== 'undefined' && 'env' in process) {
-    r = process.env.DEBUG;
-  }
-
-  return r;
-}
-
-/**
- * Enable namespaces listed in `localStorage.debug` initially.
- */
-
-exports.enable(load());
-
-/**
- * Localstorage attempts to return the localstorage.
- *
- * This is necessary because safari throws
- * when a user disables cookies/localstorage
- * and you attempt to access it.
- *
- * @return {LocalStorage}
- * @api private
- */
-
-function localstorage() {
-  try {
-    return window.localStorage;
-  } catch (e) {}
-}
+function useColors(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type)||("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))}function formatArgs(e){var o=this.useColors;if(e[0]=(o?"%c":"")+this.namespace+(o?" %c":" ")+e[0]+(o?"%c ":" ")+"+"+exports.humanize(this.diff),o){var r="color: "+this.color;e.splice(1,0,r,"color: inherit");var t=0,n=0;e[0].replace(/%[a-zA-Z%]/g,(function(e){"%%"!==e&&(t++,"%c"===e&&(n=t))})),e.splice(n,0,r)}}function log(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function save(e){try{null==e?exports.storage.removeItem("debug"):exports.storage.debug=e}catch(e){}}function load(){var e;try{e=exports.storage.debug}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e}function localstorage(){try{return window.localStorage}catch(e){}}exports=module.exports=require("./debug"),exports.log=log,exports.formatArgs=formatArgs,exports.save=save,exports.load=load,exports.useColors=useColors,exports.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:localstorage(),exports.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],exports.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},exports.enable(load());
\ No newline at end of file
index 6a5e3fc..cc122d9 100755 (executable)
@@ -1,202 +1 @@
-
-/**
- * This is the common logic for both the Node.js and web browser
- * implementations of `debug()`.
- *
- * Expose `debug()` as the module.
- */
-
-exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
-exports.coerce = coerce;
-exports.disable = disable;
-exports.enable = enable;
-exports.enabled = enabled;
-exports.humanize = require('ms');
-
-/**
- * The currently active debug mode names, and names to skip.
- */
-
-exports.names = [];
-exports.skips = [];
-
-/**
- * Map of special "%n" handling functions, for the debug "format" argument.
- *
- * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
- */
-
-exports.formatters = {};
-
-/**
- * Previous log timestamp.
- */
-
-var prevTime;
-
-/**
- * Select a color.
- * @param {String} namespace
- * @return {Number}
- * @api private
- */
-
-function selectColor(namespace) {
-  var hash = 0, i;
-
-  for (i in namespace) {
-    hash  = ((hash << 5) - hash) + namespace.charCodeAt(i);
-    hash |= 0; // Convert to 32bit integer
-  }
-
-  return exports.colors[Math.abs(hash) % exports.colors.length];
-}
-
-/**
- * Create a debugger with the given `namespace`.
- *
- * @param {String} namespace
- * @return {Function}
- * @api public
- */
-
-function createDebug(namespace) {
-
-  function debug() {
-    // disabled?
-    if (!debug.enabled) return;
-
-    var self = debug;
-
-    // set `diff` timestamp
-    var curr = +new Date();
-    var ms = curr - (prevTime || curr);
-    self.diff = ms;
-    self.prev = prevTime;
-    self.curr = curr;
-    prevTime = curr;
-
-    // turn the `arguments` into a proper Array
-    var args = new Array(arguments.length);
-    for (var i = 0; i < args.length; i++) {
-      args[i] = arguments[i];
-    }
-
-    args[0] = exports.coerce(args[0]);
-
-    if ('string' !== typeof args[0]) {
-      // anything else let's inspect with %O
-      args.unshift('%O');
-    }
-
-    // apply any `formatters` transformations
-    var index = 0;
-    args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
-      // if we encounter an escaped % then don't increase the array index
-      if (match === '%%') return match;
-      index++;
-      var formatter = exports.formatters[format];
-      if ('function' === typeof formatter) {
-        var val = args[index];
-        match = formatter.call(self, val);
-
-        // now we need to remove `args[index]` since it's inlined in the `format`
-        args.splice(index, 1);
-        index--;
-      }
-      return match;
-    });
-
-    // apply env-specific formatting (colors, etc.)
-    exports.formatArgs.call(self, args);
-
-    var logFn = debug.log || exports.log || console.log.bind(console);
-    logFn.apply(self, args);
-  }
-
-  debug.namespace = namespace;
-  debug.enabled = exports.enabled(namespace);
-  debug.useColors = exports.useColors();
-  debug.color = selectColor(namespace);
-
-  // env-specific initialization logic for debug instances
-  if ('function' === typeof exports.init) {
-    exports.init(debug);
-  }
-
-  return debug;
-}
-
-/**
- * Enables a debug mode by namespaces. This can include modes
- * separated by a colon and wildcards.
- *
- * @param {String} namespaces
- * @api public
- */
-
-function enable(namespaces) {
-  exports.save(namespaces);
-
-  exports.names = [];
-  exports.skips = [];
-
-  var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
-  var len = split.length;
-
-  for (var i = 0; i < len; i++) {
-    if (!split[i]) continue; // ignore empty strings
-    namespaces = split[i].replace(/\*/g, '.*?');
-    if (namespaces[0] === '-') {
-      exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
-    } else {
-      exports.names.push(new RegExp('^' + namespaces + '$'));
-    }
-  }
-}
-
-/**
- * Disable debug output.
- *
- * @api public
- */
-
-function disable() {
-  exports.enable('');
-}
-
-/**
- * Returns true if the given mode name is enabled, false otherwise.
- *
- * @param {String} name
- * @return {Boolean}
- * @api public
- */
-
-function enabled(name) {
-  var i, len;
-  for (i = 0, len = exports.skips.length; i < len; i++) {
-    if (exports.skips[i].test(name)) {
-      return false;
-    }
-  }
-  for (i = 0, len = exports.names.length; i < len; i++) {
-    if (exports.names[i].test(name)) {
-      return true;
-    }
-  }
-  return false;
-}
-
-/**
- * Coerce `val`.
- *
- * @param {Mixed} val
- * @return {Mixed}
- * @api private
- */
-
-function coerce(val) {
-  if (val instanceof Error) return val.stack || val.message;
-  return val;
-}
+var prevTime;function selectColor(e){var r,t=0;for(r in e)t=(t<<5)-t+e.charCodeAt(r),t|=0;return exports.colors[Math.abs(t)%exports.colors.length]}function createDebug(e){function r(){if(r.enabled){var e=r,t=+new Date,o=t-(prevTime||t);e.diff=o,e.prev=prevTime,e.curr=t,prevTime=t;for(var s=new Array(arguments.length),n=0;n<s.length;n++)s[n]=arguments[n];s[0]=exports.coerce(s[0]),"string"!=typeof s[0]&&s.unshift("%O");var p=0;s[0]=s[0].replace(/%([a-zA-Z%])/g,(function(r,t){if("%%"===r)return r;p++;var o=exports.formatters[t];if("function"==typeof o){var n=s[p];r=o.call(e,n),s.splice(p,1),p--}return r})),exports.formatArgs.call(e,s);var a=r.log||exports.log||console.log.bind(console);a.apply(e,s)}}return r.namespace=e,r.enabled=exports.enabled(e),r.useColors=exports.useColors(),r.color=selectColor(e),"function"==typeof exports.init&&exports.init(r),r}function enable(e){exports.save(e),exports.names=[],exports.skips=[];for(var r=("string"==typeof e?e:"").split(/[\s,]+/),t=r.length,o=0;o<t;o++)r[o]&&("-"===(e=r[o].replace(/\*/g,".*?"))[0]?exports.skips.push(new RegExp("^"+e.substr(1)+"$")):exports.names.push(new RegExp("^"+e+"$")))}function disable(){exports.enable("")}function enabled(e){var r,t;for(r=0,t=exports.skips.length;r<t;r++)if(exports.skips[r].test(e))return!1;for(r=0,t=exports.names.length;r<t;r++)if(exports.names[r].test(e))return!0;return!1}function coerce(e){return e instanceof Error?e.stack||e.message:e}exports=module.exports=createDebug.debug=createDebug.default=createDebug,exports.coerce=coerce,exports.disable=disable,exports.enable=enable,exports.enabled=enabled,exports.humanize=require("ms"),exports.names=[],exports.skips=[],exports.formatters={};
\ No newline at end of file
index e12cf4d..ab05315 100755 (executable)
@@ -1,10 +1 @@
-/**
- * Detect Electron renderer process, which is node, but we should
- * treat as a browser.
- */
-
-if (typeof process !== 'undefined' && process.type === 'renderer') {
-  module.exports = require('./browser.js');
-} else {
-  module.exports = require('./node.js');
-}
+"undefined"!=typeof process&&"renderer"===process.type?module.exports=require("./browser.js"):module.exports=require("./node.js");
\ No newline at end of file
index 60ea6c0..205da94 100755 (executable)
@@ -1,15 +1 @@
-module.exports = inspectorLog;
-
-// black hole
-const nullStream = new (require('stream').Writable)();
-nullStream._write = () => {};
-
-/**
- * Outputs a `console.log()` to the Node.js Inspector console *only*.
- */
-function inspectorLog() {
-  const stdout = console._stdout;
-  console._stdout = nullStream;
-  console.log.apply(console, arguments);
-  console._stdout = stdout;
-}
+module.exports=inspectorLog;const nullStream=new(require("stream").Writable);function inspectorLog(){const o=console._stdout;console._stdout=nullStream,console.log.apply(console,arguments),console._stdout=o}nullStream._write=()=>{};
\ No newline at end of file
index b15109c..e722227 100755 (executable)
@@ -1,248 +1 @@
-/**
- * Module dependencies.
- */
-
-var tty = require('tty');
-var util = require('util');
-
-/**
- * This is the Node.js implementation of `debug()`.
- *
- * Expose `debug()` as the module.
- */
-
-exports = module.exports = require('./debug');
-exports.init = init;
-exports.log = log;
-exports.formatArgs = formatArgs;
-exports.save = save;
-exports.load = load;
-exports.useColors = useColors;
-
-/**
- * Colors.
- */
-
-exports.colors = [6, 2, 3, 4, 5, 1];
-
-/**
- * Build up the default `inspectOpts` object from the environment variables.
- *
- *   $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
- */
-
-exports.inspectOpts = Object.keys(process.env).filter(function (key) {
-  return /^debug_/i.test(key);
-}).reduce(function (obj, key) {
-  // camel-case
-  var prop = key
-    .substring(6)
-    .toLowerCase()
-    .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });
-
-  // coerce string value into JS value
-  var val = process.env[key];
-  if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
-  else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
-  else if (val === 'null') val = null;
-  else val = Number(val);
-
-  obj[prop] = val;
-  return obj;
-}, {});
-
-/**
- * The file descriptor to write the `debug()` calls to.
- * Set the `DEBUG_FD` env variable to override with another value. i.e.:
- *
- *   $ DEBUG_FD=3 node script.js 3>debug.log
- */
-
-var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
-
-if (1 !== fd && 2 !== fd) {
-  util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')()
-}
-
-var stream = 1 === fd ? process.stdout :
-             2 === fd ? process.stderr :
-             createWritableStdioStream(fd);
-
-/**
- * Is stdout a TTY? Colored output is enabled when `true`.
- */
-
-function useColors() {
-  return 'colors' in exports.inspectOpts
-    ? Boolean(exports.inspectOpts.colors)
-    : tty.isatty(fd);
-}
-
-/**
- * Map %o to `util.inspect()`, all on a single line.
- */
-
-exports.formatters.o = function(v) {
-  this.inspectOpts.colors = this.useColors;
-  return util.inspect(v, this.inspectOpts)
-    .split('\n').map(function(str) {
-      return str.trim()
-    }).join(' ');
-};
-
-/**
- * Map %o to `util.inspect()`, allowing multiple lines if needed.
- */
-
-exports.formatters.O = function(v) {
-  this.inspectOpts.colors = this.useColors;
-  return util.inspect(v, this.inspectOpts);
-};
-
-/**
- * Adds ANSI color escape codes if enabled.
- *
- * @api public
- */
-
-function formatArgs(args) {
-  var name = this.namespace;
-  var useColors = this.useColors;
-
-  if (useColors) {
-    var c = this.color;
-    var prefix = '  \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m';
-
-    args[0] = prefix + args[0].split('\n').join('\n' + prefix);
-    args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
-  } else {
-    args[0] = new Date().toUTCString()
-      + ' ' + name + ' ' + args[0];
-  }
-}
-
-/**
- * Invokes `util.format()` with the specified arguments and writes to `stream`.
- */
-
-function log() {
-  return stream.write(util.format.apply(util, arguments) + '\n');
-}
-
-/**
- * Save `namespaces`.
- *
- * @param {String} namespaces
- * @api private
- */
-
-function save(namespaces) {
-  if (null == namespaces) {
-    // If you set a process.env field to null or undefined, it gets cast to the
-    // string 'null' or 'undefined'. Just delete instead.
-    delete process.env.DEBUG;
-  } else {
-    process.env.DEBUG = namespaces;
-  }
-}
-
-/**
- * Load `namespaces`.
- *
- * @return {String} returns the previously persisted debug modes
- * @api private
- */
-
-function load() {
-  return process.env.DEBUG;
-}
-
-/**
- * Copied from `node/src/node.js`.
- *
- * XXX: It's lame that node doesn't expose this API out-of-the-box. It also
- * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
- */
-
-function createWritableStdioStream (fd) {
-  var stream;
-  var tty_wrap = process.binding('tty_wrap');
-
-  // Note stream._type is used for test-module-load-list.js
-
-  switch (tty_wrap.guessHandleType(fd)) {
-    case 'TTY':
-      stream = new tty.WriteStream(fd);
-      stream._type = 'tty';
-
-      // Hack to have stream not keep the event loop alive.
-      // See https://github.com/joyent/node/issues/1726
-      if (stream._handle && stream._handle.unref) {
-        stream._handle.unref();
-      }
-      break;
-
-    case 'FILE':
-      var fs = require('fs');
-      stream = new fs.SyncWriteStream(fd, { autoClose: false });
-      stream._type = 'fs';
-      break;
-
-    case 'PIPE':
-    case 'TCP':
-      var net = require('net');
-      stream = new net.Socket({
-        fd: fd,
-        readable: false,
-        writable: true
-      });
-
-      // FIXME Should probably have an option in net.Socket to create a
-      // stream from an existing fd which is writable only. But for now
-      // we'll just add this hack and set the `readable` member to false.
-      // Test: ./node test/fixtures/echo.js < /etc/passwd
-      stream.readable = false;
-      stream.read = null;
-      stream._type = 'pipe';
-
-      // FIXME Hack to have stream not keep the event loop alive.
-      // See https://github.com/joyent/node/issues/1726
-      if (stream._handle && stream._handle.unref) {
-        stream._handle.unref();
-      }
-      break;
-
-    default:
-      // Probably an error on in uv_guess_handle()
-      throw new Error('Implement me. Unknown stream file type!');
-  }
-
-  // For supporting legacy API we put the FD here.
-  stream.fd = fd;
-
-  stream._isStdio = true;
-
-  return stream;
-}
-
-/**
- * Init logic for `debug` instances.
- *
- * Create a new `inspectOpts` object in case `useColors` is set
- * differently for a particular `debug` instance.
- */
-
-function init (debug) {
-  debug.inspectOpts = {};
-
-  var keys = Object.keys(exports.inspectOpts);
-  for (var i = 0; i < keys.length; i++) {
-    debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
-  }
-}
-
-/**
- * Enable namespaces listed in `process.env.DEBUG` initially.
- */
-
-exports.enable(load());
+var tty=require("tty"),util=require("util");exports=module.exports=require("./debug"),exports.init=init,exports.log=log,exports.formatArgs=formatArgs,exports.save=save,exports.load=load,exports.useColors=useColors,exports.colors=[6,2,3,4,5,1],exports.inspectOpts=Object.keys(process.env).filter((function(e){return/^debug_/i.test(e)})).reduce((function(e,t){var r=t.substring(6).toLowerCase().replace(/_([a-z])/g,(function(e,t){return t.toUpperCase()})),s=process.env[t];return s=!!/^(yes|on|true|enabled)$/i.test(s)||!/^(no|off|false|disabled)$/i.test(s)&&("null"===s?null:Number(s)),e[r]=s,e}),{});var fd=parseInt(process.env.DEBUG_FD,10)||2;1!==fd&&2!==fd&&util.deprecate((function(){}),"except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)")();var stream=1===fd?process.stdout:2===fd?process.stderr:createWritableStdioStream(fd);function useColors(){return"colors"in exports.inspectOpts?Boolean(exports.inspectOpts.colors):tty.isatty(fd)}function formatArgs(e){var t=this.namespace;if(this.useColors){var r=this.color,s="  \e[3"+r+";1m"+t+" \e[0m";e[0]=s+e[0].split("\n").join("\n"+s),e.push("\e[3"+r+"m+"+exports.humanize(this.diff)+"\e[0m")}else e[0]=(new Date).toUTCString()+" "+t+" "+e[0]}function log(){return stream.write(util.format.apply(util,arguments)+"\n")}function save(e){null==e?delete process.env.DEBUG:process.env.DEBUG=e}function load(){return process.env.DEBUG}function createWritableStdioStream(e){var t;switch(process.binding("tty_wrap").guessHandleType(e)){case"TTY":(t=new tty.WriteStream(e))._type="tty",t._handle&&t._handle.unref&&t._handle.unref();break;case"FILE":(t=new(require("fs").SyncWriteStream)(e,{autoClose:!1}))._type="fs";break;case"PIPE":case"TCP":(t=new(require("net").Socket)({fd:e,readable:!1,writable:!0})).readable=!1,t.read=null,t._type="pipe",t._handle&&t._handle.unref&&t._handle.unref();break;default:throw new Error("Implement me. Unknown stream file type!")}return t.fd=e,t._isStdio=!0,t}function init(e){e.inspectOpts={};for(var t=Object.keys(exports.inspectOpts),r=0;r<t.length;r++)e.inspectOpts[t[r]]=exports.inspectOpts[t[r]]}exports.formatters.o=function(e){return this.inspectOpts.colors=this.useColors,util.inspect(e,this.inspectOpts).split("\n").map((function(e){return e.trim()})).join(" ")},exports.formatters.O=function(e){return this.inspectOpts.colors=this.useColors,util.inspect(e,this.inspectOpts)},exports.enable(load());
\ No newline at end of file
index 8d5bab7..68d901c 100644 (file)
@@ -1,13 +1 @@
-'use strict';
-module.exports = function (str, sep) {
-       if (typeof str !== 'string') {
-               throw new TypeError('Expected a string');
-       }
-
-       sep = typeof sep === 'undefined' ? '_' : sep;
-
-       return str
-               .replace(/([a-z\d])([A-Z])/g, '$1' + sep + '$2')
-               .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + sep + '$2')
-               .toLowerCase();
-};
+"use strict";module.exports=function(e,r){if("string"!=typeof e)throw new TypeError("Expected a string");return r=void 0===r?"_":r,e.replace(/([a-z\d])([A-Z])/g,"$1"+r+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+r+"$2").toLowerCase()};
\ No newline at end of file
index d758d3c..1ca3e2a 100644 (file)
@@ -3,520 +3,4 @@
  * Copyright(c) 2014-2017 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-/**
- * Module dependencies.
- */
-
-var callSiteToString = require('./lib/compat').callSiteToString
-var eventListenerCount = require('./lib/compat').eventListenerCount
-var relative = require('path').relative
-
-/**
- * Module exports.
- */
-
-module.exports = depd
-
-/**
- * Get the path to base files on.
- */
-
-var basePath = process.cwd()
-
-/**
- * Determine if namespace is contained in the string.
- */
-
-function containsNamespace (str, namespace) {
-  var vals = str.split(/[ ,]+/)
-  var ns = String(namespace).toLowerCase()
-
-  for (var i = 0; i < vals.length; i++) {
-    var val = vals[i]
-
-    // namespace contained
-    if (val && (val === '*' || val.toLowerCase() === ns)) {
-      return true
-    }
-  }
-
-  return false
-}
-
-/**
- * Convert a data descriptor to accessor descriptor.
- */
-
-function convertDataDescriptorToAccessor (obj, prop, message) {
-  var descriptor = Object.getOwnPropertyDescriptor(obj, prop)
-  var value = descriptor.value
-
-  descriptor.get = function getter () { return value }
-
-  if (descriptor.writable) {
-    descriptor.set = function setter (val) { return (value = val) }
-  }
-
-  delete descriptor.value
-  delete descriptor.writable
-
-  Object.defineProperty(obj, prop, descriptor)
-
-  return descriptor
-}
-
-/**
- * Create arguments string to keep arity.
- */
-
-function createArgumentsString (arity) {
-  var str = ''
-
-  for (var i = 0; i < arity; i++) {
-    str += ', arg' + i
-  }
-
-  return str.substr(2)
-}
-
-/**
- * Create stack string from stack.
- */
-
-function createStackString (stack) {
-  var str = this.name + ': ' + this.namespace
-
-  if (this.message) {
-    str += ' deprecated ' + this.message
-  }
-
-  for (var i = 0; i < stack.length; i++) {
-    str += '\n    at ' + callSiteToString(stack[i])
-  }
-
-  return str
-}
-
-/**
- * Create deprecate for namespace in caller.
- */
-
-function depd (namespace) {
-  if (!namespace) {
-    throw new TypeError('argument namespace is required')
-  }
-
-  var stack = getStack()
-  var site = callSiteLocation(stack[1])
-  var file = site[0]
-
-  function deprecate (message) {
-    // call to self as log
-    log.call(deprecate, message)
-  }
-
-  deprecate._file = file
-  deprecate._ignored = isignored(namespace)
-  deprecate._namespace = namespace
-  deprecate._traced = istraced(namespace)
-  deprecate._warned = Object.create(null)
-
-  deprecate.function = wrapfunction
-  deprecate.property = wrapproperty
-
-  return deprecate
-}
-
-/**
- * Determine if namespace is ignored.
- */
-
-function isignored (namespace) {
-  /* istanbul ignore next: tested in a child processs */
-  if (process.noDeprecation) {
-    // --no-deprecation support
-    return true
-  }
-
-  var str = process.env.NO_DEPRECATION || ''
-
-  // namespace ignored
-  return containsNamespace(str, namespace)
-}
-
-/**
- * Determine if namespace is traced.
- */
-
-function istraced (namespace) {
-  /* istanbul ignore next: tested in a child processs */
-  if (process.traceDeprecation) {
-    // --trace-deprecation support
-    return true
-  }
-
-  var str = process.env.TRACE_DEPRECATION || ''
-
-  // namespace traced
-  return containsNamespace(str, namespace)
-}
-
-/**
- * Display deprecation message.
- */
-
-function log (message, site) {
-  var haslisteners = eventListenerCount(process, 'deprecation') !== 0
-
-  // abort early if no destination
-  if (!haslisteners && this._ignored) {
-    return
-  }
-
-  var caller
-  var callFile
-  var callSite
-  var depSite
-  var i = 0
-  var seen = false
-  var stack = getStack()
-  var file = this._file
-
-  if (site) {
-    // provided site
-    depSite = site
-    callSite = callSiteLocation(stack[1])
-    callSite.name = depSite.name
-    file = callSite[0]
-  } else {
-    // get call site
-    i = 2
-    depSite = callSiteLocation(stack[i])
-    callSite = depSite
-  }
-
-  // get caller of deprecated thing in relation to file
-  for (; i < stack.length; i++) {
-    caller = callSiteLocation(stack[i])
-    callFile = caller[0]
-
-    if (callFile === file) {
-      seen = true
-    } else if (callFile === this._file) {
-      file = this._file
-    } else if (seen) {
-      break
-    }
-  }
-
-  var key = caller
-    ? depSite.join(':') + '__' + caller.join(':')
-    : undefined
-
-  if (key !== undefined && key in this._warned) {
-    // already warned
-    return
-  }
-
-  this._warned[key] = true
-
-  // generate automatic message from call site
-  var msg = message
-  if (!msg) {
-    msg = callSite === depSite || !callSite.name
-      ? defaultMessage(depSite)
-      : defaultMessage(callSite)
-  }
-
-  // emit deprecation if listeners exist
-  if (haslisteners) {
-    var err = DeprecationError(this._namespace, msg, stack.slice(i))
-    process.emit('deprecation', err)
-    return
-  }
-
-  // format and write message
-  var format = process.stderr.isTTY
-    ? formatColor
-    : formatPlain
-  var output = format.call(this, msg, caller, stack.slice(i))
-  process.stderr.write(output + '\n', 'utf8')
-}
-
-/**
- * Get call site location as array.
- */
-
-function callSiteLocation (callSite) {
-  var file = callSite.getFileName() || '<anonymous>'
-  var line = callSite.getLineNumber()
-  var colm = callSite.getColumnNumber()
-
-  if (callSite.isEval()) {
-    file = callSite.getEvalOrigin() + ', ' + file
-  }
-
-  var site = [file, line, colm]
-
-  site.callSite = callSite
-  site.name = callSite.getFunctionName()
-
-  return site
-}
-
-/**
- * Generate a default message from the site.
- */
-
-function defaultMessage (site) {
-  var callSite = site.callSite
-  var funcName = site.name
-
-  // make useful anonymous name
-  if (!funcName) {
-    funcName = '<anonymous@' + formatLocation(site) + '>'
-  }
-
-  var context = callSite.getThis()
-  var typeName = context && callSite.getTypeName()
-
-  // ignore useless type name
-  if (typeName === 'Object') {
-    typeName = undefined
-  }
-
-  // make useful type name
-  if (typeName === 'Function') {
-    typeName = context.name || typeName
-  }
-
-  return typeName && callSite.getMethodName()
-    ? typeName + '.' + funcName
-    : funcName
-}
-
-/**
- * Format deprecation message without color.
- */
-
-function formatPlain (msg, caller, stack) {
-  var timestamp = new Date().toUTCString()
-
-  var formatted = timestamp +
-    ' ' + this._namespace +
-    ' deprecated ' + msg
-
-  // add stack trace
-  if (this._traced) {
-    for (var i = 0; i < stack.length; i++) {
-      formatted += '\n    at ' + callSiteToString(stack[i])
-    }
-
-    return formatted
-  }
-
-  if (caller) {
-    formatted += ' at ' + formatLocation(caller)
-  }
-
-  return formatted
-}
-
-/**
- * Format deprecation message with color.
- */
-
-function formatColor (msg, caller, stack) {
-  var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan
-    ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow
-    ' \x1b[0m' + msg + '\x1b[39m' // reset
-
-  // add stack trace
-  if (this._traced) {
-    for (var i = 0; i < stack.length; i++) {
-      formatted += '\n    \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan
-    }
-
-    return formatted
-  }
-
-  if (caller) {
-    formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan
-  }
-
-  return formatted
-}
-
-/**
- * Format call site location.
- */
-
-function formatLocation (callSite) {
-  return relative(basePath, callSite[0]) +
-    ':' + callSite[1] +
-    ':' + callSite[2]
-}
-
-/**
- * Get the stack as array of call sites.
- */
-
-function getStack () {
-  var limit = Error.stackTraceLimit
-  var obj = {}
-  var prep = Error.prepareStackTrace
-
-  Error.prepareStackTrace = prepareObjectStackTrace
-  Error.stackTraceLimit = Math.max(10, limit)
-
-  // capture the stack
-  Error.captureStackTrace(obj)
-
-  // slice this function off the top
-  var stack = obj.stack.slice(1)
-
-  Error.prepareStackTrace = prep
-  Error.stackTraceLimit = limit
-
-  return stack
-}
-
-/**
- * Capture call site stack from v8.
- */
-
-function prepareObjectStackTrace (obj, stack) {
-  return stack
-}
-
-/**
- * Return a wrapped function in a deprecation message.
- */
-
-function wrapfunction (fn, message) {
-  if (typeof fn !== 'function') {
-    throw new TypeError('argument fn must be a function')
-  }
-
-  var args = createArgumentsString(fn.length)
-  var deprecate = this // eslint-disable-line no-unused-vars
-  var stack = getStack()
-  var site = callSiteLocation(stack[1])
-
-  site.name = fn.name
-
-   // eslint-disable-next-line no-eval
-  var deprecatedfn = eval('(function (' + args + ') {\n' +
-    '"use strict"\n' +
-    'log.call(deprecate, message, site)\n' +
-    'return fn.apply(this, arguments)\n' +
-    '})')
-
-  return deprecatedfn
-}
-
-/**
- * Wrap property in a deprecation message.
- */
-
-function wrapproperty (obj, prop, message) {
-  if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) {
-    throw new TypeError('argument obj must be object')
-  }
-
-  var descriptor = Object.getOwnPropertyDescriptor(obj, prop)
-
-  if (!descriptor) {
-    throw new TypeError('must call property on owner object')
-  }
-
-  if (!descriptor.configurable) {
-    throw new TypeError('property must be configurable')
-  }
-
-  var deprecate = this
-  var stack = getStack()
-  var site = callSiteLocation(stack[1])
-
-  // set site name
-  site.name = prop
-
-  // convert data descriptor
-  if ('value' in descriptor) {
-    descriptor = convertDataDescriptorToAccessor(obj, prop, message)
-  }
-
-  var get = descriptor.get
-  var set = descriptor.set
-
-  // wrap getter
-  if (typeof get === 'function') {
-    descriptor.get = function getter () {
-      log.call(deprecate, message, site)
-      return get.apply(this, arguments)
-    }
-  }
-
-  // wrap setter
-  if (typeof set === 'function') {
-    descriptor.set = function setter () {
-      log.call(deprecate, message, site)
-      return set.apply(this, arguments)
-    }
-  }
-
-  Object.defineProperty(obj, prop, descriptor)
-}
-
-/**
- * Create DeprecationError for deprecation
- */
-
-function DeprecationError (namespace, message, stack) {
-  var error = new Error()
-  var stackString
-
-  Object.defineProperty(error, 'constructor', {
-    value: DeprecationError
-  })
-
-  Object.defineProperty(error, 'message', {
-    configurable: true,
-    enumerable: false,
-    value: message,
-    writable: true
-  })
-
-  Object.defineProperty(error, 'name', {
-    enumerable: false,
-    configurable: true,
-    value: 'DeprecationError',
-    writable: true
-  })
-
-  Object.defineProperty(error, 'namespace', {
-    configurable: true,
-    enumerable: false,
-    value: namespace,
-    writable: true
-  })
-
-  Object.defineProperty(error, 'stack', {
-    configurable: true,
-    enumerable: false,
-    get: function () {
-      if (stackString !== undefined) {
-        return stackString
-      }
-
-      // prepare stack trace
-      return (stackString = createStackString.call(this, stack))
-    },
-    set: function setter (val) {
-      stackString = val
-    }
-  })
-
-  return error
-}
+var callSiteToString=require("./lib/compat").callSiteToString,eventListenerCount=require("./lib/compat").eventListenerCount,relative=require("path").relative;module.exports=depd;var basePath=process.cwd();function containsNamespace(e,r){for(var t=e.split(/[ ,]+/),a=String(r).toLowerCase(),n=0;n<t.length;n++){var o=t[n];if(o&&("*"===o||o.toLowerCase()===a))return!0}return!1}function convertDataDescriptorToAccessor(e,r,t){var a=Object.getOwnPropertyDescriptor(e,r),n=a.value;return a.get=function(){return n},a.writable&&(a.set=function(e){return n=e}),delete a.value,delete a.writable,Object.defineProperty(e,r,a),a}function createArgumentsString(e){for(var r="",t=0;t<e;t++)r+=", arg"+t;return r.substr(2)}function createStackString(e){var r=this.name+": "+this.namespace;this.message&&(r+=" deprecated "+this.message);for(var t=0;t<e.length;t++)r+="\n    at "+callSiteToString(e[t]);return r}function depd(e){if(!e)throw new TypeError("argument namespace is required");var r=callSiteLocation(getStack()[1])[0];function t(e){log.call(t,e)}return t._file=r,t._ignored=isignored(e),t._namespace=e,t._traced=istraced(e),t._warned=Object.create(null),t.function=wrapfunction,t.property=wrapproperty,t}function isignored(e){return!!process.noDeprecation||containsNamespace(process.env.NO_DEPRECATION||"",e)}function istraced(e){return!!process.traceDeprecation||containsNamespace(process.env.TRACE_DEPRECATION||"",e)}function log(e,r){var t=0!==eventListenerCount(process,"deprecation");if(t||!this._ignored){var a,n,o,i,c=0,s=!1,l=getStack(),u=this._file;for(r?(i=r,(o=callSiteLocation(l[1])).name=i.name,u=o[0]):o=i=callSiteLocation(l[c=2]);c<l.length;c++)if((n=(a=callSiteLocation(l[c]))[0])===u)s=!0;else if(n===this._file)u=this._file;else if(s)break;var f=a?i.join(":")+"__"+a.join(":"):void 0;if(void 0===f||!(f in this._warned)){this._warned[f]=!0;var p=e;if(p||(p=o!==i&&o.name?defaultMessage(o):defaultMessage(i)),t){var m=DeprecationError(this._namespace,p,l.slice(c));process.emit("deprecation",m)}else{var g=(process.stderr.isTTY?formatColor:formatPlain).call(this,p,a,l.slice(c));process.stderr.write(g+"\n","utf8")}}}}function callSiteLocation(e){var r=e.getFileName()||"<anonymous>",t=e.getLineNumber(),a=e.getColumnNumber();e.isEval()&&(r=e.getEvalOrigin()+", "+r);var n=[r,t,a];return n.callSite=e,n.name=e.getFunctionName(),n}function defaultMessage(e){var r=e.callSite,t=e.name;t||(t="<anonymous@"+formatLocation(e)+">");var a=r.getThis(),n=a&&r.getTypeName();return"Object"===n&&(n=void 0),"Function"===n&&(n=a.name||n),n&&r.getMethodName()?n+"."+t:t}function formatPlain(e,r,t){var a=(new Date).toUTCString()+" "+this._namespace+" deprecated "+e;if(this._traced){for(var n=0;n<t.length;n++)a+="\n    at "+callSiteToString(t[n]);return a}return r&&(a+=" at "+formatLocation(r)),a}function formatColor(e,r,t){var a="\e[36;1m"+this._namespace+"\e[22;39m \e[33;1mdeprecated\e[22;39m \e[0m"+e+"\e[39m";if(this._traced){for(var n=0;n<t.length;n++)a+="\n    \e[36mat "+callSiteToString(t[n])+"\e[39m";return a}return r&&(a+=" \e[36m"+formatLocation(r)+"\e[39m"),a}function formatLocation(e){return relative(basePath,e[0])+":"+e[1]+":"+e[2]}function getStack(){var e=Error.stackTraceLimit,r={},t=Error.prepareStackTrace;Error.prepareStackTrace=prepareObjectStackTrace,Error.stackTraceLimit=Math.max(10,e),Error.captureStackTrace(r);var a=r.stack.slice(1);return Error.prepareStackTrace=t,Error.stackTraceLimit=e,a}function prepareObjectStackTrace(e,r){return r}function wrapfunction(fn,message){if("function"!=typeof fn)throw new TypeError("argument fn must be a function");var args=createArgumentsString(fn.length),deprecate=this,stack=getStack(),site=callSiteLocation(stack[1]);site.name=fn.name;var deprecatedfn=eval("(function ("+args+') {\n"use strict"\nlog.call(deprecate, message, site)\nreturn fn.apply(this, arguments)\n})');return deprecatedfn}function wrapproperty(e,r,t){if(!e||"object"!=typeof e&&"function"!=typeof e)throw new TypeError("argument obj must be object");var a=Object.getOwnPropertyDescriptor(e,r);if(!a)throw new TypeError("must call property on owner object");if(!a.configurable)throw new TypeError("property must be configurable");var n=this,o=callSiteLocation(getStack()[1]);o.name=r,"value"in a&&(a=convertDataDescriptorToAccessor(e,r,t));var i=a.get,c=a.set;"function"==typeof i&&(a.get=function(){return log.call(n,t,o),i.apply(this,arguments)}),"function"==typeof c&&(a.set=function(){return log.call(n,t,o),c.apply(this,arguments)}),Object.defineProperty(e,r,a)}function DeprecationError(e,r,t){var a,n=new Error;return Object.defineProperty(n,"constructor",{value:DeprecationError}),Object.defineProperty(n,"message",{configurable:!0,enumerable:!1,value:r,writable:!0}),Object.defineProperty(n,"name",{enumerable:!1,configurable:!0,value:"DeprecationError",writable:!0}),Object.defineProperty(n,"namespace",{configurable:!0,enumerable:!1,value:e,writable:!0}),Object.defineProperty(n,"stack",{configurable:!0,enumerable:!1,get:function(){return void 0!==a?a:a=createStackString.call(this,t)},set:function(e){a=e}}),n}
\ No newline at end of file
index 6be45cc..612fab5 100644 (file)
@@ -3,75 +3,4 @@
  * Copyright(c) 2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = depd
-
-/**
- * Create deprecate for namespace in caller.
- */
-
-function depd (namespace) {
-  if (!namespace) {
-    throw new TypeError('argument namespace is required')
-  }
-
-  function deprecate (message) {
-    // no-op in browser
-  }
-
-  deprecate._file = undefined
-  deprecate._ignored = true
-  deprecate._namespace = namespace
-  deprecate._traced = false
-  deprecate._warned = Object.create(null)
-
-  deprecate.function = wrapfunction
-  deprecate.property = wrapproperty
-
-  return deprecate
-}
-
-/**
- * Return a wrapped function in a deprecation message.
- *
- * This is a no-op version of the wrapper, which does nothing but call
- * validation.
- */
-
-function wrapfunction (fn, message) {
-  if (typeof fn !== 'function') {
-    throw new TypeError('argument fn must be a function')
-  }
-
-  return fn
-}
-
-/**
- * Wrap property in a deprecation message.
- *
- * This is a no-op version of the wrapper, which does nothing but call
- * validation.
- */
-
-function wrapproperty (obj, prop, message) {
-  if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) {
-    throw new TypeError('argument obj must be object')
-  }
-
-  var descriptor = Object.getOwnPropertyDescriptor(obj, prop)
-
-  if (!descriptor) {
-    throw new TypeError('must call property on owner object')
-  }
-
-  if (!descriptor.configurable) {
-    throw new TypeError('property must be configurable')
-  }
-}
+"use strict";function depd(r){if(!r)throw new TypeError("argument namespace is required");function e(r){}return e._file=void 0,e._ignored=!0,e._namespace=r,e._traced=!1,e._warned=Object.create(null),e.function=wrapfunction,e.property=wrapproperty,e}function wrapfunction(r,e){if("function"!=typeof r)throw new TypeError("argument fn must be a function");return r}function wrapproperty(r,e,t){if(!r||"object"!=typeof r&&"function"!=typeof r)throw new TypeError("argument obj must be object");var o=Object.getOwnPropertyDescriptor(r,e);if(!o)throw new TypeError("must call property on owner object");if(!o.configurable)throw new TypeError("property must be configurable")}module.exports=depd;
\ No newline at end of file
index 73186dc..637ee98 100644 (file)
@@ -3,101 +3,4 @@
  * Copyright(c) 2014 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module exports.
- */
-
-module.exports = callSiteToString
-
-/**
- * Format a CallSite file location to a string.
- */
-
-function callSiteFileLocation (callSite) {
-  var fileName
-  var fileLocation = ''
-
-  if (callSite.isNative()) {
-    fileLocation = 'native'
-  } else if (callSite.isEval()) {
-    fileName = callSite.getScriptNameOrSourceURL()
-    if (!fileName) {
-      fileLocation = callSite.getEvalOrigin()
-    }
-  } else {
-    fileName = callSite.getFileName()
-  }
-
-  if (fileName) {
-    fileLocation += fileName
-
-    var lineNumber = callSite.getLineNumber()
-    if (lineNumber != null) {
-      fileLocation += ':' + lineNumber
-
-      var columnNumber = callSite.getColumnNumber()
-      if (columnNumber) {
-        fileLocation += ':' + columnNumber
-      }
-    }
-  }
-
-  return fileLocation || 'unknown source'
-}
-
-/**
- * Format a CallSite to a string.
- */
-
-function callSiteToString (callSite) {
-  var addSuffix = true
-  var fileLocation = callSiteFileLocation(callSite)
-  var functionName = callSite.getFunctionName()
-  var isConstructor = callSite.isConstructor()
-  var isMethodCall = !(callSite.isToplevel() || isConstructor)
-  var line = ''
-
-  if (isMethodCall) {
-    var methodName = callSite.getMethodName()
-    var typeName = getConstructorName(callSite)
-
-    if (functionName) {
-      if (typeName && functionName.indexOf(typeName) !== 0) {
-        line += typeName + '.'
-      }
-
-      line += functionName
-
-      if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) {
-        line += ' [as ' + methodName + ']'
-      }
-    } else {
-      line += typeName + '.' + (methodName || '<anonymous>')
-    }
-  } else if (isConstructor) {
-    line += 'new ' + (functionName || '<anonymous>')
-  } else if (functionName) {
-    line += functionName
-  } else {
-    addSuffix = false
-    line += fileLocation
-  }
-
-  if (addSuffix) {
-    line += ' (' + fileLocation + ')'
-  }
-
-  return line
-}
-
-/**
- * Get constructor name of reviver.
- */
-
-function getConstructorName (obj) {
-  var receiver = obj.receiver
-  return (receiver.constructor && receiver.constructor.name) || null
-}
+"use strict";function callSiteFileLocation(e){var t,n="";if(e.isNative()?n="native":e.isEval()?(t=e.getScriptNameOrSourceURL())||(n=e.getEvalOrigin()):t=e.getFileName(),t){n+=t;var r=e.getLineNumber();if(null!=r){n+=":"+r;var o=e.getColumnNumber();o&&(n+=":"+o)}}return n||"unknown source"}function callSiteToString(e){var t=!0,n=callSiteFileLocation(e),r=e.getFunctionName(),o=e.isConstructor(),i="";if(!(e.isToplevel()||o)){var a=e.getMethodName(),l=getConstructorName(e);r?(l&&0!==r.indexOf(l)&&(i+=l+"."),i+=r,a&&r.lastIndexOf("."+a)!==r.length-a.length-1&&(i+=" [as "+a+"]")):i+=l+"."+(a||"<anonymous>")}else o?i+="new "+(r||"<anonymous>"):r?i+=r:(t=!1,i+=n);return t&&(i+=" ("+n+")"),i}function getConstructorName(e){var t=e.receiver;return t.constructor&&t.constructor.name||null}module.exports=callSiteToString;
\ No newline at end of file
index 3a8925d..ff0ac9f 100644 (file)
@@ -3,20 +3,4 @@
  * Copyright(c) 2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = eventListenerCount
-
-/**
- * Get the count of listeners on an event emitter of a specific type.
- */
-
-function eventListenerCount (emitter, type) {
-  return emitter.listeners(type).length
-}
+"use strict";function eventListenerCount(e,t){return e.listeners(t).length}module.exports=eventListenerCount;
\ No newline at end of file
index 955b333..cacef6b 100644 (file)
@@ -3,77 +3,4 @@
  * Copyright(c) 2014-2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module dependencies.
- * @private
- */
-
-var EventEmitter = require('events').EventEmitter
-
-/**
- * Module exports.
- * @public
- */
-
-lazyProperty(module.exports, 'callSiteToString', function callSiteToString () {
-  var limit = Error.stackTraceLimit
-  var obj = {}
-  var prep = Error.prepareStackTrace
-
-  function prepareObjectStackTrace (obj, stack) {
-    return stack
-  }
-
-  Error.prepareStackTrace = prepareObjectStackTrace
-  Error.stackTraceLimit = 2
-
-  // capture the stack
-  Error.captureStackTrace(obj)
-
-  // slice the stack
-  var stack = obj.stack.slice()
-
-  Error.prepareStackTrace = prep
-  Error.stackTraceLimit = limit
-
-  return stack[0].toString ? toString : require('./callsite-tostring')
-})
-
-lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () {
-  return EventEmitter.listenerCount || require('./event-listener-count')
-})
-
-/**
- * Define a lazy property.
- */
-
-function lazyProperty (obj, prop, getter) {
-  function get () {
-    var val = getter()
-
-    Object.defineProperty(obj, prop, {
-      configurable: true,
-      enumerable: true,
-      value: val
-    })
-
-    return val
-  }
-
-  Object.defineProperty(obj, prop, {
-    configurable: true,
-    enumerable: true,
-    get: get
-  })
-}
-
-/**
- * Call toString() on the obj
- */
-
-function toString (obj) {
-  return obj.toString()
-}
+"use strict";var EventEmitter=require("events").EventEmitter;function lazyProperty(r,e,t){Object.defineProperty(r,e,{configurable:!0,enumerable:!0,get:function(){var n=t();return Object.defineProperty(r,e,{configurable:!0,enumerable:!0,value:n}),n}})}function toString(r){return r.toString()}lazyProperty(module.exports,"callSiteToString",(function(){var r=Error.stackTraceLimit,e={},t=Error.prepareStackTrace;Error.prepareStackTrace=function(r,e){return e},Error.stackTraceLimit=2,Error.captureStackTrace(e);var n=e.stack.slice();return Error.prepareStackTrace=t,Error.stackTraceLimit=r,n[0].toString?toString:require("./callsite-tostring")})),lazyProperty(module.exports,"eventListenerCount",(function(){return EventEmitter.listenerCount||require("./event-listener-count")}));
\ No newline at end of file
index 6da2d26..bebd0f2 100644 (file)
@@ -3,73 +3,4 @@
  * Copyright(c) 2014 Jonathan Ong
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module dependencies.
- * @private
- */
-
-var ReadStream = require('fs').ReadStream
-var Stream = require('stream')
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = destroy
-
-/**
- * Destroy a stream.
- *
- * @param {object} stream
- * @public
- */
-
-function destroy(stream) {
-  if (stream instanceof ReadStream) {
-    return destroyReadStream(stream)
-  }
-
-  if (!(stream instanceof Stream)) {
-    return stream
-  }
-
-  if (typeof stream.destroy === 'function') {
-    stream.destroy()
-  }
-
-  return stream
-}
-
-/**
- * Destroy a ReadStream.
- *
- * @param {object} stream
- * @private
- */
-
-function destroyReadStream(stream) {
-  stream.destroy()
-
-  if (typeof stream.close === 'function') {
-    // node.js core bug work-around
-    stream.on('open', onOpenClose)
-  }
-
-  return stream
-}
-
-/**
- * On open handler to close stream.
- * @private
- */
-
-function onOpenClose() {
-  if (typeof this.fd === 'number') {
-    // actually close down the fd
-    this.close()
-  }
-}
+"use strict";var ReadStream=require("fs").ReadStream,Stream=require("stream");function destroy(e){return e instanceof ReadStream?destroyReadStream(e):e instanceof Stream?("function"==typeof e.destroy&&e.destroy(),e):e}function destroyReadStream(e){return e.destroy(),"function"==typeof e.close&&e.on("open",onOpenClose),e}function onOpenClose(){"number"==typeof this.fd&&this.close()}module.exports=destroy;
\ No newline at end of file
index 4f83f1f..3f2147c 100644 (file)
@@ -1,165 +1 @@
-'use strict';
-
-/******************************************************************************
- * Created 2008-08-19.
- *
- * Dijkstra path-finding functions. Adapted from the Dijkstar Python project.
- *
- * Copyright (C) 2008
- *   Wyatt Baldwin <self@wyattbaldwin.com>
- *   All rights reserved
- *
- * Licensed under the MIT license.
- *
- *   http://www.opensource.org/licenses/mit-license.php
- *
- * 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 dijkstra = {
-  single_source_shortest_paths: function(graph, s, d) {
-    // Predecessor map for each node that has been encountered.
-    // node ID => predecessor node ID
-    var predecessors = {};
-
-    // Costs of shortest paths from s to all nodes encountered.
-    // node ID => cost
-    var costs = {};
-    costs[s] = 0;
-
-    // Costs of shortest paths from s to all nodes encountered; differs from
-    // `costs` in that it provides easy access to the node that currently has
-    // the known shortest path from s.
-    // XXX: Do we actually need both `costs` and `open`?
-    var open = dijkstra.PriorityQueue.make();
-    open.push(s, 0);
-
-    var closest,
-        u, v,
-        cost_of_s_to_u,
-        adjacent_nodes,
-        cost_of_e,
-        cost_of_s_to_u_plus_cost_of_e,
-        cost_of_s_to_v,
-        first_visit;
-    while (!open.empty()) {
-      // In the nodes remaining in graph that have a known cost from s,
-      // find the node, u, that currently has the shortest path from s.
-      closest = open.pop();
-      u = closest.value;
-      cost_of_s_to_u = closest.cost;
-
-      // Get nodes adjacent to u...
-      adjacent_nodes = graph[u] || {};
-
-      // ...and explore the edges that connect u to those nodes, updating
-      // the cost of the shortest paths to any or all of those nodes as
-      // necessary. v is the node across the current edge from u.
-      for (v in adjacent_nodes) {
-        if (adjacent_nodes.hasOwnProperty(v)) {
-          // Get the cost of the edge running from u to v.
-          cost_of_e = adjacent_nodes[v];
-
-          // Cost of s to u plus the cost of u to v across e--this is *a*
-          // cost from s to v that may or may not be less than the current
-          // known cost to v.
-          cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e;
-
-          // If we haven't visited v yet OR if the current known cost from s to
-          // v is greater than the new cost we just found (cost of s to u plus
-          // cost of u to v across e), update v's cost in the cost list and
-          // update v's predecessor in the predecessor list (it's now u).
-          cost_of_s_to_v = costs[v];
-          first_visit = (typeof costs[v] === 'undefined');
-          if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) {
-            costs[v] = cost_of_s_to_u_plus_cost_of_e;
-            open.push(v, cost_of_s_to_u_plus_cost_of_e);
-            predecessors[v] = u;
-          }
-        }
-      }
-    }
-
-    if (typeof d !== 'undefined' && typeof costs[d] === 'undefined') {
-      var msg = ['Could not find a path from ', s, ' to ', d, '.'].join('');
-      throw new Error(msg);
-    }
-
-    return predecessors;
-  },
-
-  extract_shortest_path_from_predecessor_list: function(predecessors, d) {
-    var nodes = [];
-    var u = d;
-    var predecessor;
-    while (u) {
-      nodes.push(u);
-      predecessor = predecessors[u];
-      u = predecessors[u];
-    }
-    nodes.reverse();
-    return nodes;
-  },
-
-  find_path: function(graph, s, d) {
-    var predecessors = dijkstra.single_source_shortest_paths(graph, s, d);
-    return dijkstra.extract_shortest_path_from_predecessor_list(
-      predecessors, d);
-  },
-
-  /**
-   * A very naive priority queue implementation.
-   */
-  PriorityQueue: {
-    make: function (opts) {
-      var T = dijkstra.PriorityQueue,
-          t = {},
-          key;
-      opts = opts || {};
-      for (key in T) {
-        if (T.hasOwnProperty(key)) {
-          t[key] = T[key];
-        }
-      }
-      t.queue = [];
-      t.sorter = opts.sorter || T.default_sorter;
-      return t;
-    },
-
-    default_sorter: function (a, b) {
-      return a.cost - b.cost;
-    },
-
-    /**
-     * Add a new item to the queue and ensure the highest priority element
-     * is at the front of the queue.
-     */
-    push: function (value, cost) {
-      var item = {value: value, cost: cost};
-      this.queue.push(item);
-      this.queue.sort(this.sorter);
-    },
-
-    /**
-     * Return the highest priority element in the queue.
-     */
-    pop: function () {
-      return this.queue.shift();
-    },
-
-    empty: function () {
-      return this.queue.length === 0;
-    }
-  }
-};
-
-
-// node.js module exports
-if (typeof module !== 'undefined') {
-  module.exports = dijkstra;
-}
+"use strict";var dijkstra={single_source_shortest_paths:function(r,t,e){var o={},s={};s[t]=0;var u,i,n,a,h,f,p,d=dijkstra.PriorityQueue.make();for(d.push(t,0);!d.empty();)for(n in i=(u=d.pop()).value,a=u.cost,h=r[i]||{})h.hasOwnProperty(n)&&(f=a+h[n],p=s[n],(void 0===s[n]||p>f)&&(s[n]=f,d.push(n,f),o[n]=i));if(void 0!==e&&void 0===s[e]){var c=["Could not find a path from ",t," to ",e,"."].join("");throw new Error(c)}return o},extract_shortest_path_from_predecessor_list:function(r,t){for(var e=[],o=t;o;)e.push(o),r[o],o=r[o];return e.reverse(),e},find_path:function(r,t,e){var o=dijkstra.single_source_shortest_paths(r,t,e);return dijkstra.extract_shortest_path_from_predecessor_list(o,e)},PriorityQueue:{make:function(r){var t,e=dijkstra.PriorityQueue,o={};for(t in r=r||{},e)e.hasOwnProperty(t)&&(o[t]=e[t]);return o.queue=[],o.sorter=r.sorter||e.default_sorter,o},default_sorter:function(r,t){return r.cost-t.cost},push:function(r,t){var e={value:r,cost:t};this.queue.push(e),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return 0===this.queue.length}}};"undefined"!=typeof module&&(module.exports=dijkstra);
\ No newline at end of file
index 865c5a0..5a6817a 100644 (file)
@@ -1,96 +1 @@
-'use strict';
-
-var expect = require('expect.js');
-var dijkstra = require('../dijkstra.js');
-var find_path = dijkstra.find_path;
-
-describe('dijkstra.js', function () {
-
-    describe('.find_path()', function () {
-
-        it('should find the path between two points, all edges have weight 1', function () {
-            // A B C
-            // D E F
-            // G H I
-            var graph = {
-                a: {b: 10, d: 1},
-                b: {a: 1, c: 1, e: 1},
-                c: {b: 1, f: 1},
-                d: {a: 1, e: 1, g: 1},
-                e: {b: 1, d: 1, f: 1, h: 1},
-                f: {c: 1, e: 1, i: 1},
-                g: {d: 1, h: 1},
-                h: {e: 1, g: 1, i: 1},
-                i: {f: 1, h: 1}
-            };
-            var path = find_path(graph, 'a', 'i');
-            expect(path).to.eql(['a', 'd', 'e', 'f', 'i']);
-        });
-
-        it('should find the path between two points, weighted edges', function () {
-            var graph = {
-                a: {b: 10, c: 100, d: 1},
-                b: {c: 10},
-                d: {b: 1, e: 1},
-                e: {f: 1},
-                f: {c: 1},
-                g: {b: 1}
-            };
-
-            var path = find_path(graph, 'a', 'c');
-            expect(path).to.eql(['a', 'd', 'e', 'f', 'c']);
-            path = find_path(graph, 'd', 'b');
-            expect(path).to.eql(['d', 'b']);
-        });
-
-        it('should throw on unreachable destination', function () {
-            var graph = {
-                a: {b: 10, c: 100, d: 1},
-                b: {c: 10},
-                d: {b: 1, e: 1},
-                e: {f: 1},
-                f: {c: 1},
-                g: {b: 1}
-            };
-
-            expect(function () { find_path(graph, 'c', 'a'); }).to.throwException();
-            expect(function () { find_path(graph, 'a', 'g'); }).to.throwException();
-        });
-
-        it('should throw on non-existent destination', function () {
-            var graph = {
-                a: {b: 10, c: 100, d: 1},
-                b: {c: 10},
-                d: {b: 1, e: 1},
-                e: {f: 1},
-                f: {c: 1},
-                g: {b: 1}
-            };
-
-            expect(function () { find_path(graph, 'a', 'z'); }).to.throwException();
-        });
-    });
-
-    describe('.single_source_shortest_paths()', function () {
-        it('should find all paths from a node', function () {
-            var graph = {
-                a: {b: 10, c: 100, d: 1},
-                b: {c: 10},
-                d: {b: 1, e: 1},
-                e: {f: 1},
-                f: {c: 1},
-                g: {b: 1}
-            };
-
-            // All paths from 'a'
-            var paths = dijkstra.single_source_shortest_paths(graph, 'a');
-            expect(paths).to.eql({
-                d: 'a',
-                b: 'd',
-                e: 'd',
-                f: 'e',
-                c: 'f'
-            });
-        });
-    });
-});
+"use strict";var expect=require("expect.js"),dijkstra=require("../dijkstra.js"),find_path=dijkstra.find_path;describe("dijkstra.js",(function(){describe(".find_path()",(function(){it("should find the path between two points, all edges have weight 1",(function(){var e=find_path({a:{b:10,d:1},b:{a:1,c:1,e:1},c:{b:1,f:1},d:{a:1,e:1,g:1},e:{b:1,d:1,f:1,h:1},f:{c:1,e:1,i:1},g:{d:1,h:1},h:{e:1,g:1,i:1},i:{f:1,h:1}},"a","i");expect(e).to.eql(["a","d","e","f","i"])})),it("should find the path between two points, weighted edges",(function(){var e={a:{b:10,c:100,d:1},b:{c:10},d:{b:1,e:1},e:{f:1},f:{c:1},g:{b:1}},t=find_path(e,"a","c");expect(t).to.eql(["a","d","e","f","c"]),t=find_path(e,"d","b"),expect(t).to.eql(["d","b"])})),it("should throw on unreachable destination",(function(){var e={a:{b:10,c:100,d:1},b:{c:10},d:{b:1,e:1},e:{f:1},f:{c:1},g:{b:1}};expect((function(){find_path(e,"c","a")})).to.throwException(),expect((function(){find_path(e,"a","g")})).to.throwException()})),it("should throw on non-existent destination",(function(){var e={a:{b:10,c:100,d:1},b:{c:10},d:{b:1,e:1},e:{f:1},f:{c:1},g:{b:1}};expect((function(){find_path(e,"a","z")})).to.throwException()}))})),describe(".single_source_shortest_paths()",(function(){it("should find all paths from a node",(function(){var e=dijkstra.single_source_shortest_paths({a:{b:10,c:100,d:1},b:{c:10},d:{b:1,e:1},e:{f:1},f:{c:1},g:{b:1}},"a");expect(e).to.eql({d:"a",b:"d",e:"d",f:"e",c:"f"})}))}))}));
\ No newline at end of file
index 501287c..9496d47 100644 (file)
@@ -3,93 +3,4 @@
  * Copyright(c) 2014 Jonathan Ong
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = first
-
-/**
- * Get the first event in a set of event emitters and event pairs.
- *
- * @param {array} stuff
- * @param {function} done
- * @public
- */
-
-function first(stuff, done) {
-  if (!Array.isArray(stuff))
-    throw new TypeError('arg must be an array of [ee, events...] arrays')
-
-  var cleanups = []
-
-  for (var i = 0; i < stuff.length; i++) {
-    var arr = stuff[i]
-
-    if (!Array.isArray(arr) || arr.length < 2)
-      throw new TypeError('each array member must be [ee, events...]')
-
-    var ee = arr[0]
-
-    for (var j = 1; j < arr.length; j++) {
-      var event = arr[j]
-      var fn = listener(event, callback)
-
-      // listen to the event
-      ee.on(event, fn)
-      // push this listener to the list of cleanups
-      cleanups.push({
-        ee: ee,
-        event: event,
-        fn: fn,
-      })
-    }
-  }
-
-  function callback() {
-    cleanup()
-    done.apply(null, arguments)
-  }
-
-  function cleanup() {
-    var x
-    for (var i = 0; i < cleanups.length; i++) {
-      x = cleanups[i]
-      x.ee.removeListener(x.event, x.fn)
-    }
-  }
-
-  function thunk(fn) {
-    done = fn
-  }
-
-  thunk.cancel = cleanup
-
-  return thunk
-}
-
-/**
- * Create the event listener.
- * @private
- */
-
-function listener(event, done) {
-  return function onevent(arg1) {
-    var args = new Array(arguments.length)
-    var ee = this
-    var err = event === 'error'
-      ? arg1
-      : null
-
-    // copy args to prevent arguments escaping scope
-    for (var i = 0; i < args.length; i++) {
-      args[i] = arguments[i]
-    }
-
-    done(err, ee, event, args)
-  }
-}
+"use strict";function first(r,e){if(!Array.isArray(r))throw new TypeError("arg must be an array of [ee, events...] arrays");for(var n=[],t=0;t<r.length;t++){var a=r[t];if(!Array.isArray(a)||a.length<2)throw new TypeError("each array member must be [ee, events...]");for(var o=a[0],f=1;f<a.length;f++){var i=a[f],s=listener(i,l);o.on(i,s),n.push({ee:o,event:i,fn:s})}}function l(){u(),e.apply(null,arguments)}function u(){for(var r,e=0;e<n.length;e++)(r=n[e]).ee.removeListener(r.event,r.fn)}function h(r){e=r}return h.cancel=u,h}function listener(r,e){return function(n){for(var t=new Array(arguments.length),a=this,o="error"===r?n:null,f=0;f<t.length;f++)t[f]=arguments[f];e(o,a,r,t)}}module.exports=first;
\ No newline at end of file
index 0feab0b..d297ef3 100755 (executable)
@@ -1,212 +1,2 @@
 #!/usr/bin/env node
-/*
- * EJS Embedded JavaScript templates
- * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-*/
-
-
-let program = require('jake').program;
-delete global.jake; // NO NOT WANT
-program.setTaskNames = function (n) { this.taskNames = n; };
-
-let ejs = require('../lib/ejs');
-let { hyphenToCamel } = require('../lib/utils');
-let fs = require('fs');
-let args = process.argv.slice(2);
-let usage = fs.readFileSync(`${__dirname}/../usage.txt`).toString();
-
-const CLI_OPTS = [
-  { full: 'output-file',
-    abbr: 'o',
-    expectValue: true,
-  },
-  { full: 'data-file',
-    abbr: 'f',
-    expectValue: true,
-  },
-  { full: 'data-input',
-    abbr: 'i',
-    expectValue: true,
-  },
-  { full: 'delimiter',
-    abbr: 'm',
-    expectValue: true,
-    passThrough: true,
-  },
-  { full: 'open-delimiter',
-    abbr: 'p',
-    expectValue: true,
-    passThrough: true,
-  },
-  { full: 'close-delimiter',
-    abbr: 'c',
-    expectValue: true,
-    passThrough: true,
-  },
-  { full: 'strict',
-    abbr: 's',
-    expectValue: false,
-    allowValue: false,
-    passThrough: true,
-  },
-  { full: 'no-with',
-    abbr: 'n',
-    expectValue: false,
-    allowValue: false,
-  },
-  { full: 'locals-name',
-    abbr: 'l',
-    expectValue: true,
-    passThrough: true,
-  },
-  { full: 'rm-whitespace',
-    abbr: 'w',
-    expectValue: false,
-    allowValue: false,
-    passThrough: true,
-  },
-  { full: 'debug',
-    abbr: 'd',
-    expectValue: false,
-    allowValue: false,
-    passThrough: true,
-  },
-  { full: 'help',
-    abbr: 'h',
-    passThrough: true,
-  },
-  { full: 'version',
-    abbr: 'V',
-    passThrough: true,
-  },
-  // Alias lowercase v
-  { full: 'version',
-    abbr: 'v',
-    passThrough: true,
-  },
-];
-
-let preempts = {
-  version: function () {
-    program.die(ejs.VERSION);
-  },
-  help: function () {
-    program.die(usage);
-  }
-};
-
-let stdin = '';
-process.stdin.setEncoding('utf8');
-process.stdin.on('readable', () => {
-  let chunk;
-  while ((chunk = process.stdin.read()) !== null) {
-    stdin += chunk;
-  }
-});
-
-function run() {
-
-  program.availableOpts = CLI_OPTS;
-  program.parseArgs(args);
-
-  let templatePath = program.taskNames[0];
-  let pVals = program.envVars;
-  let pOpts = {};
-
-  for (let p in program.opts) {
-    let name = hyphenToCamel(p);
-    pOpts[name] = program.opts[p];
-  }
-
-  let opts = {};
-  let vals = {};
-
-  // Same-named 'passthrough' opts
-  CLI_OPTS.forEach((opt) => {
-    let optName = hyphenToCamel(opt.full);
-    if (opt.passThrough && typeof pOpts[optName] != 'undefined') {
-      opts[optName] = pOpts[optName];
-    }
-  });
-
-  // Bail out for help/version
-  for (let p in opts) {
-    if (preempts[p]) {
-      return preempts[p]();
-    }
-  }
-
-  // Default to having views relative from the current working directory
-  opts.views = ['.'];
-
-  // Ensure there's a template to render
-  if (!templatePath) {
-    throw new Error('Please provide a template path. (Run ejs -h for help)');
-  }
-
-  if (opts.strict) {
-    pOpts.noWith = true;
-  }
-  if (pOpts.noWith) {
-    opts._with = false;
-  }
-
-  // Grab and parse any input data, in order of precedence:
-  // 1. Stdin
-  // 2. CLI arg via -i
-  // 3. Data file via -f
-  // Any individual vals passed at the end (e.g., foo=bar) will override
-  // any vals previously set
-  let input;
-  let err = new Error('Please do not pass data multiple ways. Pick one of stdin, -f, or -i.');
-  if (stdin) {
-    input = stdin;
-  }
-  else if (pOpts.dataInput) {
-    if (input) {
-      throw err;
-    }
-    input = decodeURIComponent(pOpts.dataInput);
-  }
-  else if (pOpts.dataFile) {
-    if (input) {
-      throw err;
-    }
-    input = fs.readFileSync(pOpts.dataFile).toString();
-  }
-
-  if (input) {
-    vals = JSON.parse(input);
-  }
-
-  // Override / set any individual values passed from the command line
-  for (let p in pVals) {
-    vals[p] = pVals[p];
-  }
-
-  let template = fs.readFileSync(templatePath).toString();
-  let output = ejs.render(template, vals, opts);
-  if (pOpts.outputFile) {
-    fs.writeFileSync(pOpts.outputFile, output);
-  }
-  else {
-    process.stdout.write(output);
-  }
-  process.exit();
-}
-
-// Defer execution so that stdin can be read if necessary
-setImmediate(run);
+let program=require("jake").program;delete global.jake,program.setTaskNames=function(e){this.taskNames=e};let ejs=require("../lib/ejs"),{hyphenToCamel:hyphenToCamel}=require("../lib/utils"),fs=require("fs"),args=process.argv.slice(2),usage=fs.readFileSync(`${__dirname}/../usage.txt`).toString();const CLI_OPTS=[{full:"output-file",abbr:"o",expectValue:!0},{full:"data-file",abbr:"f",expectValue:!0},{full:"data-input",abbr:"i",expectValue:!0},{full:"delimiter",abbr:"m",expectValue:!0,passThrough:!0},{full:"open-delimiter",abbr:"p",expectValue:!0,passThrough:!0},{full:"close-delimiter",abbr:"c",expectValue:!0,passThrough:!0},{full:"strict",abbr:"s",expectValue:!1,allowValue:!1,passThrough:!0},{full:"no-with",abbr:"n",expectValue:!1,allowValue:!1},{full:"locals-name",abbr:"l",expectValue:!0,passThrough:!0},{full:"rm-whitespace",abbr:"w",expectValue:!1,allowValue:!1,passThrough:!0},{full:"debug",abbr:"d",expectValue:!1,allowValue:!1,passThrough:!0},{full:"help",abbr:"h",passThrough:!0},{full:"version",abbr:"V",passThrough:!0},{full:"version",abbr:"v",passThrough:!0}];let preempts={version:function(){program.die(ejs.VERSION)},help:function(){program.die(usage)}},stdin="";function run(){program.availableOpts=CLI_OPTS,program.parseArgs(args);let e=program.taskNames[0],r=program.envVars,a={};for(let e in program.opts){let r=hyphenToCamel(e);a[r]=program.opts[e]}let l,t={},s={};CLI_OPTS.forEach((e=>{let r=hyphenToCamel(e.full);e.passThrough&&void 0!==a[r]&&(t[r]=a[r])}));for(let e in t)if(preempts[e])return preempts[e]();if(t.views=["."],!e)throw new Error("Please provide a template path. (Run ejs -h for help)");t.strict&&(a.noWith=!0),a.noWith&&(t._with=!1);let o=new Error("Please do not pass data multiple ways. Pick one of stdin, -f, or -i.");if(stdin)l=stdin;else if(a.dataInput){if(l)throw o;l=decodeURIComponent(a.dataInput)}else if(a.dataFile){if(l)throw o;l=fs.readFileSync(a.dataFile).toString()}l&&(s=JSON.parse(l));for(let e in r)s[e]=r[e];let i=fs.readFileSync(e).toString(),p=ejs.render(i,s,t);a.outputFile?fs.writeFileSync(a.outputFile,p):process.stdout.write(p),process.exit()}process.stdin.setEncoding("utf8"),process.stdin.on("readable",(()=>{let e;for(;null!==(e=process.stdin.read());)stdin+=e})),setImmediate(run);
\ No newline at end of file
index 5310e76..a3b741f 100755 (executable)
-(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.ejs = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
-/*
- * EJS Embedded JavaScript templates
- * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-*/
-
-'use strict';
-
+!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).ejs=e()}}((function(){return function e(t,n,r){function i(s,c){if(!n[s]){if(!t[s]){var a="function"==typeof require&&require;if(!c&&a)return a(s,!0);if(o)return o(s,!0);var l=new Error("Cannot find module '"+s+"'");throw l.code="MODULE_NOT_FOUND",l}var u=n[s]={exports:{}};t[s][0].call(u.exports,(function(e){return i(t[s][1][e]||e)}),u,u.exports,e,t,n,r)}return n[s].exports}for(var o="function"==typeof require&&require,s=0;s<r.length;s++)i(r[s]);return i}({1:[function(e,t,n){"use strict";
 /**
  * @file Embedded JavaScript templating engine. {@link http://ejs.co}
  * @author Matthew Eernisse <mde@fleegix.org>
  * @author Tiancheng "Timothy" Gu <timothygu99@gmail.com>
  * @project EJS
  * @license {@link http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0}
- */
-
-/**
- * EJS internal functions.
- *
- * Technically this "module" lies in the same file as {@link module:ejs}, for
- * the sake of organization all the private functions re grouped into this
- * module.
- *
- * @module ejs-internal
- * @private
- */
-
-/**
- * Embedded JavaScript templating engine.
- *
- * @module ejs
- * @public
- */
-
-var fs = require('fs');
-var path = require('path');
-var utils = require('./utils');
-
-var scopeOptionWarned = false;
-/** @type {string} */
-var _VERSION_STRING = require('../package.json').version;
-var _DEFAULT_OPEN_DELIMITER = '<';
-var _DEFAULT_CLOSE_DELIMITER = '>';
-var _DEFAULT_DELIMITER = '%';
-var _DEFAULT_LOCALS_NAME = 'locals';
-var _NAME = 'ejs';
-var _REGEX_STRING = '(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)';
-var _OPTS_PASSABLE_WITH_DATA = ['delimiter', 'scope', 'context', 'debug', 'compileDebug',
-  'client', '_with', 'rmWhitespace', 'strict', 'filename', 'async'];
-// We don't allow 'cache' option to be passed in the data obj for
-// the normal `render` call, but this is where Express 2 & 3 put it
-// so we make an exception for `renderFile`
-var _OPTS_PASSABLE_WITH_DATA_EXPRESS = _OPTS_PASSABLE_WITH_DATA.concat('cache');
-var _BOM = /^\uFEFF/;
-
-/**
- * EJS template function cache. This can be a LRU object from lru-cache NPM
- * module. By default, it is {@link module:utils.cache}, a simple in-process
- * cache that grows continuously.
- *
- * @type {Cache}
- */
-
-exports.cache = utils.cache;
-
-/**
- * Custom file loader. Useful for template preprocessing or restricting access
- * to a certain part of the filesystem.
- *
- * @type {fileLoader}
- */
-
-exports.fileLoader = fs.readFileSync;
-
-/**
- * Name of the object containing the locals.
- *
- * This variable is overridden by {@link Options}`.localsName` if it is not
- * `undefined`.
- *
- * @type {String}
- * @public
- */
-
-exports.localsName = _DEFAULT_LOCALS_NAME;
-
-/**
- * Promise implementation -- defaults to the native implementation if available
- * This is mostly just for testability
- *
- * @type {PromiseConstructorLike}
- * @public
- */
-
-exports.promiseImpl = (new Function('return this;'))().Promise;
-
-/**
- * Get the path to the included file from the parent file path and the
- * specified path.
- *
- * @param {String}  name     specified path
- * @param {String}  filename parent file path
- * @param {Boolean} [isDir=false] whether the parent file path is a directory
- * @return {String}
- */
-exports.resolveInclude = function(name, filename, isDir) {
-  var dirname = path.dirname;
-  var extname = path.extname;
-  var resolve = path.resolve;
-  var includePath = resolve(isDir ? filename : dirname(filename), name);
-  var ext = extname(name);
-  if (!ext) {
-    includePath += '.ejs';
-  }
-  return includePath;
-};
-
-/**
- * Try to resolve file path on multiple directories
- *
- * @param  {String}        name  specified path
- * @param  {Array<String>} paths list of possible parent directory paths
- * @return {String}
- */
-function resolvePaths(name, paths) {
-  var filePath;
-  if (paths.some(function (v) {
-    filePath = exports.resolveInclude(name, v, true);
-    return fs.existsSync(filePath);
-  })) {
-    return filePath;
-  }
-}
-
-/**
- * Get the path to the included file by Options
- *
- * @param  {String}  path    specified path
- * @param  {Options} options compilation options
- * @return {String}
- */
-function getIncludePath(path, options) {
-  var includePath;
-  var filePath;
-  var views = options.views;
-  var match = /^[A-Za-z]+:\\|^\//.exec(path);
-
-  // Abs path
-  if (match && match.length) {
-    path = path.replace(/^\/*/, '');
-    if (Array.isArray(options.root)) {
-      includePath = resolvePaths(path, options.root);
-    } else {
-      includePath = exports.resolveInclude(path, options.root || '/', true);
-    }
-  }
-  // Relative paths
-  else {
-    // Look relative to a passed filename first
-    if (options.filename) {
-      filePath = exports.resolveInclude(path, options.filename);
-      if (fs.existsSync(filePath)) {
-        includePath = filePath;
-      }
-    }
-    // Then look in any views directories
-    if (!includePath && Array.isArray(views)) {
-      includePath = resolvePaths(path, views);
-    }
-    if (!includePath && typeof options.includer !== 'function') {
-      throw new Error('Could not find the include file "' +
-          options.escapeFunction(path) + '"');
-    }
-  }
-  return includePath;
-}
-
-/**
- * Get the template from a string or a file, either compiled on-the-fly or
- * read from cache (if enabled), and cache the template if needed.
- *
- * If `template` is not set, the file specified in `options.filename` will be
- * read.
- *
- * If `options.cache` is true, this function reads the file from
- * `options.filename` so it must be set prior to calling this function.
- *
- * @memberof module:ejs-internal
- * @param {Options} options   compilation options
- * @param {String} [template] template source
- * @return {(TemplateFunction|ClientFunction)}
- * Depending on the value of `options.client`, either type might be returned.
- * @static
- */
-
-function handleCache(options, template) {
-  var func;
-  var filename = options.filename;
-  var hasTemplate = arguments.length > 1;
-
-  if (options.cache) {
-    if (!filename) {
-      throw new Error('cache option requires a filename');
-    }
-    func = exports.cache.get(filename);
-    if (func) {
-      return func;
-    }
-    if (!hasTemplate) {
-      template = fileLoader(filename).toString().replace(_BOM, '');
-    }
-  }
-  else if (!hasTemplate) {
-    // istanbul ignore if: should not happen at all
-    if (!filename) {
-      throw new Error('Internal EJS error: no file name or template '
-                    + 'provided');
-    }
-    template = fileLoader(filename).toString().replace(_BOM, '');
-  }
-  func = exports.compile(template, options);
-  if (options.cache) {
-    exports.cache.set(filename, func);
-  }
-  return func;
-}
-
-/**
- * Try calling handleCache with the given options and data and call the
- * callback with the result. If an error occurs, call the callback with
- * the error. Used by renderFile().
- *
- * @memberof module:ejs-internal
- * @param {Options} options    compilation options
- * @param {Object} data        template data
- * @param {RenderFileCallback} cb callback
- * @static
- */
-
-function tryHandleCache(options, data, cb) {
-  var result;
-  if (!cb) {
-    if (typeof exports.promiseImpl == 'function') {
-      return new exports.promiseImpl(function (resolve, reject) {
-        try {
-          result = handleCache(options)(data);
-          resolve(result);
-        }
-        catch (err) {
-          reject(err);
-        }
-      });
-    }
-    else {
-      throw new Error('Please provide a callback function');
-    }
-  }
-  else {
-    try {
-      result = handleCache(options)(data);
-    }
-    catch (err) {
-      return cb(err);
-    }
-
-    cb(null, result);
-  }
-}
-
-/**
- * fileLoader is independent
- *
- * @param {String} filePath ejs file path.
- * @return {String} The contents of the specified file.
- * @static
- */
-
-function fileLoader(filePath){
-  return exports.fileLoader(filePath);
-}
-
-/**
- * Get the template function.
- *
- * If `options.cache` is `true`, then the template is cached.
- *
- * @memberof module:ejs-internal
- * @param {String}  path    path for the specified file
- * @param {Options} options compilation options
- * @return {(TemplateFunction|ClientFunction)}
- * Depending on the value of `options.client`, either type might be returned
- * @static
- */
-
-function includeFile(path, options) {
-  var opts = utils.shallowCopy({}, options);
-  opts.filename = getIncludePath(path, opts);
-  if (typeof options.includer === 'function') {
-    var includerResult = options.includer(path, opts.filename);
-    if (includerResult) {
-      if (includerResult.filename) {
-        opts.filename = includerResult.filename;
-      }
-      if (includerResult.template) {
-        return handleCache(opts, includerResult.template);
-      }
-    }
-  }
-  return handleCache(opts);
-}
-
-/**
- * Re-throw the given `err` in context to the `str` of ejs, `filename`, and
- * `lineno`.
- *
- * @implements {RethrowCallback}
- * @memberof module:ejs-internal
- * @param {Error}  err      Error object
- * @param {String} str      EJS source
- * @param {String} flnm     file name of the EJS file
- * @param {Number} lineno   line number of the error
- * @param {EscapeCallback} esc
- * @static
- */
-
-function rethrow(err, str, flnm, lineno, esc) {
-  var lines = str.split('\n');
-  var start = Math.max(lineno - 3, 0);
-  var end = Math.min(lines.length, lineno + 3);
-  var filename = esc(flnm);
-  // Error context
-  var context = lines.slice(start, end).map(function (line, i){
-    var curr = i + start + 1;
-    return (curr == lineno ? ' >> ' : '    ')
-      + curr
-      + '| '
-      + line;
-  }).join('\n');
-
-  // Alter exception message
-  err.path = filename;
-  err.message = (filename || 'ejs') + ':'
-    + lineno + '\n'
-    + context + '\n\n'
-    + err.message;
-
-  throw err;
-}
-
-function stripSemi(str){
-  return str.replace(/;(\s*$)/, '$1');
-}
-
-/**
- * Compile the given `str` of ejs into a template function.
- *
- * @param {String}  template EJS template
- *
- * @param {Options} [opts] compilation options
- *
- * @return {(TemplateFunction|ClientFunction)}
- * Depending on the value of `opts.client`, either type might be returned.
- * Note that the return type of the function also depends on the value of `opts.async`.
- * @public
- */
-
-exports.compile = function compile(template, opts) {
-  var templ;
-
-  // v1 compat
-  // 'scope' is 'context'
-  // FIXME: Remove this in a future version
-  if (opts && opts.scope) {
-    if (!scopeOptionWarned){
-      console.warn('`scope` option is deprecated and will be removed in EJS 3');
-      scopeOptionWarned = true;
-    }
-    if (!opts.context) {
-      opts.context = opts.scope;
-    }
-    delete opts.scope;
-  }
-  templ = new Template(template, opts);
-  return templ.compile();
-};
-
-/**
- * Render the given `template` of ejs.
- *
- * If you would like to include options but not data, you need to explicitly
- * call this function with `data` being an empty object or `null`.
- *
- * @param {String}   template EJS template
- * @param {Object}  [data={}] template data
- * @param {Options} [opts={}] compilation and rendering options
- * @return {(String|Promise<String>)}
- * Return value type depends on `opts.async`.
- * @public
- */
-
-exports.render = function (template, d, o) {
-  var data = d || {};
-  var opts = o || {};
-
-  // No options object -- if there are optiony names
-  // in the data, copy them to options
-  if (arguments.length == 2) {
-    utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA);
-  }
-
-  return handleCache(opts, template)(data);
-};
-
-/**
- * Render an EJS file at the given `path` and callback `cb(err, str)`.
- *
- * If you would like to include options but not data, you need to explicitly
- * call this function with `data` being an empty object or `null`.
- *
- * @param {String}             path     path to the EJS file
- * @param {Object}            [data={}] template data
- * @param {Options}           [opts={}] compilation and rendering options
- * @param {RenderFileCallback} cb callback
- * @public
- */
-
-exports.renderFile = function () {
-  var args = Array.prototype.slice.call(arguments);
-  var filename = args.shift();
-  var cb;
-  var opts = {filename: filename};
-  var data;
-  var viewOpts;
-
-  // Do we have a callback?
-  if (typeof arguments[arguments.length - 1] == 'function') {
-    cb = args.pop();
-  }
-  // Do we have data/opts?
-  if (args.length) {
-    // Should always have data obj
-    data = args.shift();
-    // Normal passed opts (data obj + opts obj)
-    if (args.length) {
-      // Use shallowCopy so we don't pollute passed in opts obj with new vals
-      utils.shallowCopy(opts, args.pop());
-    }
-    // Special casing for Express (settings + opts-in-data)
-    else {
-      // Express 3 and 4
-      if (data.settings) {
-        // Pull a few things from known locations
-        if (data.settings.views) {
-          opts.views = data.settings.views;
-        }
-        if (data.settings['view cache']) {
-          opts.cache = true;
-        }
-        // Undocumented after Express 2, but still usable, esp. for
-        // items that are unsafe to be passed along with data, like `root`
-        viewOpts = data.settings['view options'];
-        if (viewOpts) {
-          utils.shallowCopy(opts, viewOpts);
-        }
-      }
-      // Express 2 and lower, values set in app.locals, or people who just
-      // want to pass options in their data. NOTE: These values will override
-      // anything previously set in settings  or settings['view options']
-      utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA_EXPRESS);
-    }
-    opts.filename = filename;
-  }
-  else {
-    data = {};
-  }
-
-  return tryHandleCache(opts, data, cb);
-};
-
-/**
- * Clear intermediate JavaScript cache. Calls {@link Cache#reset}.
- * @public
- */
-
-/**
- * EJS template class
- * @public
- */
-exports.Template = Template;
-
-exports.clearCache = function () {
-  exports.cache.reset();
-};
-
-function Template(text, opts) {
-  opts = opts || {};
-  var options = {};
-  this.templateText = text;
-  /** @type {string | null} */
-  this.mode = null;
-  this.truncate = false;
-  this.currentLine = 1;
-  this.source = '';
-  options.client = opts.client || false;
-  options.escapeFunction = opts.escape || opts.escapeFunction || utils.escapeXML;
-  options.compileDebug = opts.compileDebug !== false;
-  options.debug = !!opts.debug;
-  options.filename = opts.filename;
-  options.openDelimiter = opts.openDelimiter || exports.openDelimiter || _DEFAULT_OPEN_DELIMITER;
-  options.closeDelimiter = opts.closeDelimiter || exports.closeDelimiter || _DEFAULT_CLOSE_DELIMITER;
-  options.delimiter = opts.delimiter || exports.delimiter || _DEFAULT_DELIMITER;
-  options.strict = opts.strict || false;
-  options.context = opts.context;
-  options.cache = opts.cache || false;
-  options.rmWhitespace = opts.rmWhitespace;
-  options.root = opts.root;
-  options.includer = opts.includer;
-  options.outputFunctionName = opts.outputFunctionName;
-  options.localsName = opts.localsName || exports.localsName || _DEFAULT_LOCALS_NAME;
-  options.views = opts.views;
-  options.async = opts.async;
-  options.destructuredLocals = opts.destructuredLocals;
-  options.legacyInclude = typeof opts.legacyInclude != 'undefined' ? !!opts.legacyInclude : true;
-
-  if (options.strict) {
-    options._with = false;
-  }
-  else {
-    options._with = typeof opts._with != 'undefined' ? opts._with : true;
-  }
-
-  this.opts = options;
-
-  this.regex = this.createRegex();
-}
-
-Template.modes = {
-  EVAL: 'eval',
-  ESCAPED: 'escaped',
-  RAW: 'raw',
-  COMMENT: 'comment',
-  LITERAL: 'literal'
-};
-
-Template.prototype = {
-  createRegex: function () {
-    var str = _REGEX_STRING;
-    var delim = utils.escapeRegExpChars(this.opts.delimiter);
-    var open = utils.escapeRegExpChars(this.opts.openDelimiter);
-    var close = utils.escapeRegExpChars(this.opts.closeDelimiter);
-    str = str.replace(/%/g, delim)
-      .replace(/</g, open)
-      .replace(/>/g, close);
-    return new RegExp(str);
-  },
-
-  compile: function () {
-    /** @type {string} */
-    var src;
-    /** @type {ClientFunction} */
-    var fn;
-    var opts = this.opts;
-    var prepended = '';
-    var appended = '';
-    /** @type {EscapeCallback} */
-    var escapeFn = opts.escapeFunction;
-    /** @type {FunctionConstructor} */
-    var ctor;
-    /** @type {string} */
-    var sanitizedFilename = opts.filename ? JSON.stringify(opts.filename) : 'undefined';
-
-    if (!this.source) {
-      this.generateSource();
-      prepended +=
-        '  var __output = "";\n' +
-        '  function __append(s) { if (s !== undefined && s !== null) __output += s }\n';
-      if (opts.outputFunctionName) {
-        prepended += '  var ' + opts.outputFunctionName + ' = __append;' + '\n';
-      }
-      if (opts.destructuredLocals && opts.destructuredLocals.length) {
-        var destructuring = '  var __locals = (' + opts.localsName + ' || {}),\n';
-        for (var i = 0; i < opts.destructuredLocals.length; i++) {
-          var name = opts.destructuredLocals[i];
-          if (i > 0) {
-            destructuring += ',\n  ';
-          }
-          destructuring += name + ' = __locals.' + name;
-        }
-        prepended += destructuring + ';\n';
-      }
-      if (opts._with !== false) {
-        prepended +=  '  with (' + opts.localsName + ' || {}) {' + '\n';
-        appended += '  }' + '\n';
-      }
-      appended += '  return __output;' + '\n';
-      this.source = prepended + this.source + appended;
-    }
-
-    if (opts.compileDebug) {
-      src = 'var __line = 1' + '\n'
-        + '  , __lines = ' + JSON.stringify(this.templateText) + '\n'
-        + '  , __filename = ' + sanitizedFilename + ';' + '\n'
-        + 'try {' + '\n'
-        + this.source
-        + '} catch (e) {' + '\n'
-        + '  rethrow(e, __lines, __filename, __line, escapeFn);' + '\n'
-        + '}' + '\n';
-    }
-    else {
-      src = this.source;
-    }
-
-    if (opts.client) {
-      src = 'escapeFn = escapeFn || ' + escapeFn.toString() + ';' + '\n' + src;
-      if (opts.compileDebug) {
-        src = 'rethrow = rethrow || ' + rethrow.toString() + ';' + '\n' + src;
-      }
-    }
-
-    if (opts.strict) {
-      src = '"use strict";\n' + src;
-    }
-    if (opts.debug) {
-      console.log(src);
-    }
-    if (opts.compileDebug && opts.filename) {
-      src = src + '\n'
-        + '//# sourceURL=' + sanitizedFilename + '\n';
-    }
-
-    try {
-      if (opts.async) {
-        // Have to use generated function for this, since in envs without support,
-        // it breaks in parsing
-        try {
-          ctor = (new Function('return (async function(){}).constructor;'))();
-        }
-        catch(e) {
-          if (e instanceof SyntaxError) {
-            throw new Error('This environment does not support async/await');
-          }
-          else {
-            throw e;
-          }
-        }
-      }
-      else {
-        ctor = Function;
-      }
-      fn = new ctor(opts.localsName + ', escapeFn, include, rethrow', src);
-    }
-    catch(e) {
-      // istanbul ignore else
-      if (e instanceof SyntaxError) {
-        if (opts.filename) {
-          e.message += ' in ' + opts.filename;
-        }
-        e.message += ' while compiling ejs\n\n';
-        e.message += 'If the above error is not helpful, you may want to try EJS-Lint:\n';
-        e.message += 'https://github.com/RyanZim/EJS-Lint';
-        if (!opts.async) {
-          e.message += '\n';
-          e.message += 'Or, if you meant to create an async function, pass `async: true` as an option.';
-        }
-      }
-      throw e;
-    }
-
-    // Return a callable function which will execute the function
-    // created by the source-code, with the passed data as locals
-    // Adds a local `include` function which allows full recursive include
-    var returnedFn = opts.client ? fn : function anonymous(data) {
-      var include = function (path, includeData) {
-        var d = utils.shallowCopy({}, data);
-        if (includeData) {
-          d = utils.shallowCopy(d, includeData);
-        }
-        return includeFile(path, opts)(d);
-      };
-      return fn.apply(opts.context, [data || {}, escapeFn, include, rethrow]);
-    };
-    if (opts.filename && typeof Object.defineProperty === 'function') {
-      var filename = opts.filename;
-      var basename = path.basename(filename, path.extname(filename));
-      try {
-        Object.defineProperty(returnedFn, 'name', {
-          value: basename,
-          writable: false,
-          enumerable: false,
-          configurable: true
-        });
-      } catch (e) {/* ignore */}
-    }
-    return returnedFn;
-  },
-
-  generateSource: function () {
-    var opts = this.opts;
-
-    if (opts.rmWhitespace) {
-      // Have to use two separate replace here as `^` and `$` operators don't
-      // work well with `\r` and empty lines don't work well with the `m` flag.
-      this.templateText =
-        this.templateText.replace(/[\r\n]+/g, '\n').replace(/^\s+|\s+$/gm, '');
-    }
-
-    // Slurp spaces and tabs before <%_ and after _%>
-    this.templateText =
-      this.templateText.replace(/[ \t]*<%_/gm, '<%_').replace(/_%>[ \t]*/gm, '_%>');
-
-    var self = this;
-    var matches = this.parseTemplateText();
-    var d = this.opts.delimiter;
-    var o = this.opts.openDelimiter;
-    var c = this.opts.closeDelimiter;
-
-    if (matches && matches.length) {
-      matches.forEach(function (line, index) {
-        var closing;
-        // If this is an opening tag, check for closing tags
-        // FIXME: May end up with some false positives here
-        // Better to store modes as k/v with openDelimiter + delimiter as key
-        // Then this can simply check against the map
-        if ( line.indexOf(o + d) === 0        // If it is a tag
-          && line.indexOf(o + d + d) !== 0) { // and is not escaped
-          closing = matches[index + 2];
-          if (!(closing == d + c || closing == '-' + d + c || closing == '_' + d + c)) {
-            throw new Error('Could not find matching close tag for "' + line + '".');
-          }
-        }
-        self.scanLine(line);
-      });
-    }
-
-  },
-
-  parseTemplateText: function () {
-    var str = this.templateText;
-    var pat = this.regex;
-    var result = pat.exec(str);
-    var arr = [];
-    var firstPos;
-
-    while (result) {
-      firstPos = result.index;
-
-      if (firstPos !== 0) {
-        arr.push(str.substring(0, firstPos));
-        str = str.slice(firstPos);
-      }
-
-      arr.push(result[0]);
-      str = str.slice(result[0].length);
-      result = pat.exec(str);
-    }
-
-    if (str) {
-      arr.push(str);
-    }
-
-    return arr;
-  },
-
-  _addOutput: function (line) {
-    if (this.truncate) {
-      // Only replace single leading linebreak in the line after
-      // -%> tag -- this is the single, trailing linebreak
-      // after the tag that the truncation mode replaces
-      // Handle Win / Unix / old Mac linebreaks -- do the \r\n
-      // combo first in the regex-or
-      line = line.replace(/^(?:\r\n|\r|\n)/, '');
-      this.truncate = false;
-    }
-    if (!line) {
-      return line;
-    }
-
-    // Preserve literal slashes
-    line = line.replace(/\\/g, '\\\\');
-
-    // Convert linebreaks
-    line = line.replace(/\n/g, '\\n');
-    line = line.replace(/\r/g, '\\r');
-
-    // Escape double-quotes
-    // - this will be the delimiter during execution
-    line = line.replace(/"/g, '\\"');
-    this.source += '    ; __append("' + line + '")' + '\n';
-  },
-
-  scanLine: function (line) {
-    var self = this;
-    var d = this.opts.delimiter;
-    var o = this.opts.openDelimiter;
-    var c = this.opts.closeDelimiter;
-    var newLineCount = 0;
-
-    newLineCount = (line.split('\n').length - 1);
-
-    switch (line) {
-    case o + d:
-    case o + d + '_':
-      this.mode = Template.modes.EVAL;
-      break;
-    case o + d + '=':
-      this.mode = Template.modes.ESCAPED;
-      break;
-    case o + d + '-':
-      this.mode = Template.modes.RAW;
-      break;
-    case o + d + '#':
-      this.mode = Template.modes.COMMENT;
-      break;
-    case o + d + d:
-      this.mode = Template.modes.LITERAL;
-      this.source += '    ; __append("' + line.replace(o + d + d, o + d) + '")' + '\n';
-      break;
-    case d + d + c:
-      this.mode = Template.modes.LITERAL;
-      this.source += '    ; __append("' + line.replace(d + d + c, d + c) + '")' + '\n';
-      break;
-    case d + c:
-    case '-' + d + c:
-    case '_' + d + c:
-      if (this.mode == Template.modes.LITERAL) {
-        this._addOutput(line);
-      }
-
-      this.mode = null;
-      this.truncate = line.indexOf('-') === 0 || line.indexOf('_') === 0;
-      break;
-    default:
-      // In script mode, depends on type of tag
-      if (this.mode) {
-        // If '//' is found without a line break, add a line break.
-        switch (this.mode) {
-        case Template.modes.EVAL:
-        case Template.modes.ESCAPED:
-        case Template.modes.RAW:
-          if (line.lastIndexOf('//') > line.lastIndexOf('\n')) {
-            line += '\n';
-          }
-        }
-        switch (this.mode) {
-        // Just executing code
-        case Template.modes.EVAL:
-          this.source += '    ; ' + line + '\n';
-          break;
-          // Exec, esc, and output
-        case Template.modes.ESCAPED:
-          this.source += '    ; __append(escapeFn(' + stripSemi(line) + '))' + '\n';
-          break;
-          // Exec and output
-        case Template.modes.RAW:
-          this.source += '    ; __append(' + stripSemi(line) + ')' + '\n';
-          break;
-        case Template.modes.COMMENT:
-          // Do nothing
-          break;
-          // Literal <%% mode, append as raw output
-        case Template.modes.LITERAL:
-          this._addOutput(line);
-          break;
-        }
-      }
-      // In string mode, just add the output
-      else {
-        this._addOutput(line);
-      }
-    }
-
-    if (self.opts.compileDebug && newLineCount) {
-      this.currentLine += newLineCount;
-      this.source += '    ; __line = ' + this.currentLine + '\n';
-    }
-  }
-};
-
-/**
- * Escape characters reserved in XML.
- *
- * This is simply an export of {@link module:utils.escapeXML}.
- *
- * If `markup` is `undefined` or `null`, the empty string is returned.
- *
- * @param {String} markup Input string
- * @return {String} Escaped string
- * @public
- * @func
- * */
-exports.escapeXML = utils.escapeXML;
-
-/**
- * Express.js support.
- *
- * This is an alias for {@link module:ejs.renderFile}, in order to support
- * Express.js out-of-the-box.
- *
- * @func
- */
-
-exports.__express = exports.renderFile;
-
-/**
- * Version of EJS.
- *
- * @readonly
- * @type {String}
- * @public
- */
-
-exports.VERSION = _VERSION_STRING;
-
-/**
- * Name for detection of EJS.
- *
- * @readonly
- * @type {String}
- * @public
- */
-
-exports.name = _NAME;
-
-/* istanbul ignore if */
-if (typeof window != 'undefined') {
-  window.ejs = exports;
-}
-
-},{"../package.json":6,"./utils":2,"fs":3,"path":4}],2:[function(require,module,exports){
-/*
- * EJS Embedded JavaScript templates
- * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-*/
-
-/**
- * Private utility functions
- * @module utils
- * @private
- */
-
-'use strict';
-
-var regExpChars = /[|\\{}()[\]^$+*?.]/g;
-
-/**
- * Escape characters reserved in regular expressions.
- *
- * If `string` is `undefined` or `null`, the empty string is returned.
- *
- * @param {String} string Input string
- * @return {String} Escaped string
- * @static
- * @private
- */
-exports.escapeRegExpChars = function (string) {
-  // istanbul ignore if
-  if (!string) {
-    return '';
-  }
-  return String(string).replace(regExpChars, '\\$&');
-};
-
-var _ENCODE_HTML_RULES = {
-  '&': '&amp;',
-  '<': '&lt;',
-  '>': '&gt;',
-  '"': '&#34;',
-  "'": '&#39;'
-};
-var _MATCH_HTML = /[&<>'"]/g;
-
-function encode_char(c) {
-  return _ENCODE_HTML_RULES[c] || c;
-}
-
-/**
- * Stringified version of constants used by {@link module:utils.escapeXML}.
- *
- * It is used in the process of generating {@link ClientFunction}s.
- *
- * @readonly
- * @type {String}
- */
-
-var escapeFuncStr =
-  'var _ENCODE_HTML_RULES = {\n'
-+ '      "&": "&amp;"\n'
-+ '    , "<": "&lt;"\n'
-+ '    , ">": "&gt;"\n'
-+ '    , \'"\': "&#34;"\n'
-+ '    , "\'": "&#39;"\n'
-+ '    }\n'
-+ '  , _MATCH_HTML = /[&<>\'"]/g;\n'
-+ 'function encode_char(c) {\n'
-+ '  return _ENCODE_HTML_RULES[c] || c;\n'
-+ '};\n';
-
-/**
- * Escape characters reserved in XML.
- *
- * If `markup` is `undefined` or `null`, the empty string is returned.
- *
- * @implements {EscapeCallback}
- * @param {String} markup Input string
- * @return {String} Escaped string
- * @static
- * @private
- */
-
-exports.escapeXML = function (markup) {
-  return markup == undefined
-    ? ''
-    : String(markup)
-      .replace(_MATCH_HTML, encode_char);
-};
-exports.escapeXML.toString = function () {
-  return Function.prototype.toString.call(this) + ';\n' + escapeFuncStr;
-};
-
-/**
- * Naive copy of properties from one object to another.
- * Does not recurse into non-scalar properties
- * Does not check to see if the property has a value before copying
- *
- * @param  {Object} to   Destination object
- * @param  {Object} from Source object
- * @return {Object}      Destination object
- * @static
- * @private
- */
-exports.shallowCopy = function (to, from) {
-  from = from || {};
-  for (var p in from) {
-    to[p] = from[p];
-  }
-  return to;
-};
-
-/**
- * Naive copy of a list of key names, from one object to another.
- * Only copies property if it is actually defined
- * Does not recurse into non-scalar properties
- *
- * @param  {Object} to   Destination object
- * @param  {Object} from Source object
- * @param  {Array} list List of properties to copy
- * @return {Object}      Destination object
- * @static
- * @private
- */
-exports.shallowCopyFromList = function (to, from, list) {
-  for (var i = 0; i < list.length; i++) {
-    var p = list[i];
-    if (typeof from[p] != 'undefined') {
-      to[p] = from[p];
-    }
-  }
-  return to;
-};
-
-/**
- * Simple in-process cache implementation. Does not implement limits of any
- * sort.
- *
- * @implements {Cache}
- * @static
- * @private
- */
-exports.cache = {
-  _data: {},
-  set: function (key, val) {
-    this._data[key] = val;
-  },
-  get: function (key) {
-    return this._data[key];
-  },
-  remove: function (key) {
-    delete this._data[key];
-  },
-  reset: function () {
-    this._data = {};
-  }
-};
-
-/**
- * Transforms hyphen case variable into camel case.
- *
- * @param {String} string Hyphen case string
- * @return {String} Camel case string
- * @static
- * @private
- */
-exports.hyphenToCamel = function (str) {
-  return str.replace(/-[a-z]/g, function (match) { return match[1].toUpperCase(); });
-};
-
-},{}],3:[function(require,module,exports){
-
-},{}],4:[function(require,module,exports){
-(function (process){
-// .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,require('_process'))
-},{"_process":5}],5:[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; };
-
-},{}],6:[function(require,module,exports){
-module.exports={
-  "name": "ejs",
-  "description": "Embedded JavaScript templates",
-  "keywords": [
-    "template",
-    "engine",
-    "ejs"
-  ],
-  "version": "3.1.6",
-  "author": "Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)",
-  "license": "Apache-2.0",
-  "bin": {
-    "ejs": "./bin/cli.js"
-  },
-  "main": "./lib/ejs.js",
-  "jsdelivr": "ejs.min.js",
-  "unpkg": "ejs.min.js",
-  "repository": {
-    "type": "git",
-    "url": "git://github.com/mde/ejs.git"
-  },
-  "bugs": "https://github.com/mde/ejs/issues",
-  "homepage": "https://github.com/mde/ejs",
-  "dependencies": {
-    "jake": "^10.6.1"
-  },
-  "devDependencies": {
-    "browserify": "^16.5.1",
-    "eslint": "^6.8.0",
-    "git-directory-deploy": "^1.5.1",
-    "jsdoc": "^3.6.4",
-    "lru-cache": "^4.0.1",
-    "mocha": "^7.1.1",
-    "uglify-js": "^3.3.16"
-  },
-  "engines": {
-    "node": ">=0.10.0"
-  },
-  "scripts": {
-    "test": "mocha"
-  }
-}
-
-},{}]},{},[1])(1)
-});
+ */var r=e("fs"),i=e("path"),o=e("./utils"),s=!1,c=e("../package.json").version,a="locals",l=["delimiter","scope","context","debug","compileDebug","client","_with","rmWhitespace","strict","filename","async"],u=l.concat("cache"),p=/^\uFEFF/;function f(e,t){var i;if(t.some((function(t){return i=n.resolveInclude(e,t,!0),r.existsSync(i)})))return i}function h(e,t){var r,i=e.filename,o=arguments.length>1;if(e.cache){if(!i)throw new Error("cache option requires a filename");if(r=n.cache.get(i))return r;o||(t=d(i).toString().replace(p,""))}else if(!o){if(!i)throw new Error("Internal EJS error: no file name or template provided");t=d(i).toString().replace(p,"")}return r=n.compile(t,e),e.cache&&n.cache.set(i,r),r}function m(e,t,r){var i;if(!r){if("function"==typeof n.promiseImpl)return new n.promiseImpl((function(n,r){try{n(i=h(e)(t))}catch(e){r(e)}}));throw new Error("Please provide a callback function")}try{i=h(e)(t)}catch(e){return r(e)}r(null,i)}function d(e){return n.fileLoader(e)}function g(e,t){var i=o.shallowCopy({},t);if(i.filename=function(e,t){var i,o,s=t.views,c=/^[A-Za-z]+:\\|^\//.exec(e);if(c&&c.length)e=e.replace(/^\/*/,""),i=Array.isArray(t.root)?f(e,t.root):n.resolveInclude(e,t.root||"/",!0);else if(t.filename&&(o=n.resolveInclude(e,t.filename),r.existsSync(o)&&(i=o)),!i&&Array.isArray(s)&&(i=f(e,s)),!i&&"function"!=typeof t.includer)throw new Error('Could not find the include file "'+t.escapeFunction(e)+'"');return i}(e,i),"function"==typeof t.includer){var s=t.includer(e,i.filename);if(s&&(s.filename&&(i.filename=s.filename),s.template))return h(i,s.template)}return h(i)}function v(e,t,n,r,i){var o=t.split("\n"),s=Math.max(r-3,0),c=Math.min(o.length,r+3),a=i(n),l=o.slice(s,c).map((function(e,t){var n=t+s+1;return(n==r?" >> ":"    ")+n+"| "+e})).join("\n");throw e.path=a,e.message=(a||"ejs")+":"+r+"\n"+l+"\n\n"+e.message,e}function y(e){return e.replace(/;(\s*$)/,"$1")}function w(e,t){t=t||{};var r={};this.templateText=e,this.mode=null,this.truncate=!1,this.currentLine=1,this.source="",r.client=t.client||!1,r.escapeFunction=t.escape||t.escapeFunction||o.escapeXML,r.compileDebug=!1!==t.compileDebug,r.debug=!!t.debug,r.filename=t.filename,r.openDelimiter=t.openDelimiter||n.openDelimiter||"<",r.closeDelimiter=t.closeDelimiter||n.closeDelimiter||">",r.delimiter=t.delimiter||n.delimiter||"%",r.strict=t.strict||!1,r.context=t.context,r.cache=t.cache||!1,r.rmWhitespace=t.rmWhitespace,r.root=t.root,r.includer=t.includer,r.outputFunctionName=t.outputFunctionName,r.localsName=t.localsName||n.localsName||a,r.views=t.views,r.async=t.async,r.destructuredLocals=t.destructuredLocals,r.legacyInclude=void 0===t.legacyInclude||!!t.legacyInclude,r.strict?r._with=!1:r._with=void 0===t._with||t._with,this.opts=r,this.regex=this.createRegex()}n.cache=o.cache,n.fileLoader=r.readFileSync,n.localsName=a,n.promiseImpl=new Function("return this;")().Promise,n.resolveInclude=function(e,t,n){var r=i.dirname,o=i.extname,s=(0,i.resolve)(n?t:r(t),e);return o(e)||(s+=".ejs"),s},n.compile=function(e,t){return t&&t.scope&&(s||(console.warn("`scope` option is deprecated and will be removed in EJS 3"),s=!0),t.context||(t.context=t.scope),delete t.scope),new w(e,t).compile()},n.render=function(e,t,n){var r=t||{},i=n||{};return 2==arguments.length&&o.shallowCopyFromList(i,r,l),h(i,e)(r)},n.renderFile=function(){var e,t,n,r=Array.prototype.slice.call(arguments),i=r.shift(),s={filename:i};return"function"==typeof arguments[arguments.length-1]&&(e=r.pop()),r.length?(t=r.shift(),r.length?o.shallowCopy(s,r.pop()):(t.settings&&(t.settings.views&&(s.views=t.settings.views),t.settings["view cache"]&&(s.cache=!0),(n=t.settings["view options"])&&o.shallowCopy(s,n)),o.shallowCopyFromList(s,t,u)),s.filename=i):t={},m(s,t,e)},n.Template=w,n.clearCache=function(){n.cache.reset()},w.modes={EVAL:"eval",ESCAPED:"escaped",RAW:"raw",COMMENT:"comment",LITERAL:"literal"},w.prototype={createRegex:function(){var e="(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)",t=o.escapeRegExpChars(this.opts.delimiter),n=o.escapeRegExpChars(this.opts.openDelimiter),r=o.escapeRegExpChars(this.opts.closeDelimiter);return e=e.replace(/%/g,t).replace(/</g,n).replace(/>/g,r),new RegExp(e)},compile:function(){var e,t,n,r=this.opts,s="",c="",a=r.escapeFunction,l=r.filename?JSON.stringify(r.filename):"undefined";if(!this.source){if(this.generateSource(),s+='  var __output = "";\n  function __append(s) { if (s !== undefined && s !== null) __output += s }\n',r.outputFunctionName&&(s+="  var "+r.outputFunctionName+" = __append;\n"),r.destructuredLocals&&r.destructuredLocals.length){for(var u="  var __locals = ("+r.localsName+" || {}),\n",p=0;p<r.destructuredLocals.length;p++){var f=r.destructuredLocals[p];p>0&&(u+=",\n  "),u+=f+" = __locals."+f}s+=u+";\n"}!1!==r._with&&(s+="  with ("+r.localsName+" || {}) {\n",c+="  }\n"),c+="  return __output;\n",this.source=s+this.source+c}e=r.compileDebug?"var __line = 1\n  , __lines = "+JSON.stringify(this.templateText)+"\n  , __filename = "+l+";\ntry {\n"+this.source+"} catch (e) {\n  rethrow(e, __lines, __filename, __line, escapeFn);\n}\n":this.source,r.client&&(e="escapeFn = escapeFn || "+a.toString()+";\n"+e,r.compileDebug&&(e="rethrow = rethrow || "+v.toString()+";\n"+e)),r.strict&&(e='"use strict";\n'+e),r.debug&&console.log(e),r.compileDebug&&r.filename&&(e=e+"\n//# sourceURL="+l+"\n");try{if(r.async)try{n=new Function("return (async function(){}).constructor;")()}catch(e){throw e instanceof SyntaxError?new Error("This environment does not support async/await"):e}else n=Function;t=new n(r.localsName+", escapeFn, include, rethrow",e)}catch(e){throw e instanceof SyntaxError&&(r.filename&&(e.message+=" in "+r.filename),e.message+=" while compiling ejs\n\n",e.message+="If the above error is not helpful, you may want to try EJS-Lint:\n",e.message+="https://github.com/RyanZim/EJS-Lint",r.async||(e.message+="\n",e.message+="Or, if you meant to create an async function, pass `async: true` as an option.")),e}var h=r.client?t:function(e){return t.apply(r.context,[e||{},a,function(t,n){var i=o.shallowCopy({},e);return n&&(i=o.shallowCopy(i,n)),g(t,r)(i)},v])};if(r.filename&&"function"==typeof Object.defineProperty){var m=r.filename,d=i.basename(m,i.extname(m));try{Object.defineProperty(h,"name",{value:d,writable:!1,enumerable:!1,configurable:!0})}catch(e){}}return h},generateSource:function(){this.opts.rmWhitespace&&(this.templateText=this.templateText.replace(/[\r\n]+/g,"\n").replace(/^\s+|\s+$/gm,"")),this.templateText=this.templateText.replace(/[ \t]*<%_/gm,"<%_").replace(/_%>[ \t]*/gm,"_%>");var e=this,t=this.parseTemplateText(),n=this.opts.delimiter,r=this.opts.openDelimiter,i=this.opts.closeDelimiter;t&&t.length&&t.forEach((function(o,s){var c;if(0===o.indexOf(r+n)&&0!==o.indexOf(r+n+n)&&(c=t[s+2])!=n+i&&c!="-"+n+i&&c!="_"+n+i)throw new Error('Could not find matching close tag for "'+o+'".');e.scanLine(o)}))},parseTemplateText:function(){for(var e,t=this.templateText,n=this.regex,r=n.exec(t),i=[];r;)0!==(e=r.index)&&(i.push(t.substring(0,e)),t=t.slice(e)),i.push(r[0]),t=t.slice(r[0].length),r=n.exec(t);return t&&i.push(t),i},_addOutput:function(e){if(this.truncate&&(e=e.replace(/^(?:\r\n|\r|\n)/,""),this.truncate=!1),!e)return e;e=(e=(e=(e=e.replace(/\\/g,"\\\\")).replace(/\n/g,"\\n")).replace(/\r/g,"\\r")).replace(/"/g,'\\"'),this.source+='    ; __append("'+e+'")\n'},scanLine:function(e){var t,n=this.opts.delimiter,r=this.opts.openDelimiter,i=this.opts.closeDelimiter;switch(t=e.split("\n").length-1,e){case r+n:case r+n+"_":this.mode=w.modes.EVAL;break;case r+n+"=":this.mode=w.modes.ESCAPED;break;case r+n+"-":this.mode=w.modes.RAW;break;case r+n+"#":this.mode=w.modes.COMMENT;break;case r+n+n:this.mode=w.modes.LITERAL,this.source+='    ; __append("'+e.replace(r+n+n,r+n)+'")\n';break;case n+n+i:this.mode=w.modes.LITERAL,this.source+='    ; __append("'+e.replace(n+n+i,n+i)+'")\n';break;case n+i:case"-"+n+i:case"_"+n+i:this.mode==w.modes.LITERAL&&this._addOutput(e),this.mode=null,this.truncate=0===e.indexOf("-")||0===e.indexOf("_");break;default:if(this.mode){switch(this.mode){case w.modes.EVAL:case w.modes.ESCAPED:case w.modes.RAW:e.lastIndexOf("//")>e.lastIndexOf("\n")&&(e+="\n")}switch(this.mode){case w.modes.EVAL:this.source+="    ; "+e+"\n";break;case w.modes.ESCAPED:this.source+="    ; __append(escapeFn("+y(e)+"))\n";break;case w.modes.RAW:this.source+="    ; __append("+y(e)+")\n";break;case w.modes.COMMENT:break;case w.modes.LITERAL:this._addOutput(e)}}else this._addOutput(e)}this.opts.compileDebug&&t&&(this.currentLine+=t,this.source+="    ; __line = "+this.currentLine+"\n")}},n.escapeXML=o.escapeXML,n.__express=n.renderFile,n.VERSION=c,n.name="ejs","undefined"!=typeof window&&(window.ejs=n)},{"../package.json":6,"./utils":2,fs:3,path:4}],2:[function(e,t,n){"use strict";var r=/[|\\{}()[\]^$+*?.]/g;n.escapeRegExpChars=function(e){return e?String(e).replace(r,"\\$&"):""};var i={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&#34;","'":"&#39;"},o=/[&<>'"]/g;function s(e){return i[e]||e}n.escapeXML=function(e){return null==e?"":String(e).replace(o,s)},n.escapeXML.toString=function(){return Function.prototype.toString.call(this)+';\nvar _ENCODE_HTML_RULES = {\n      "&": "&amp;"\n    , "<": "&lt;"\n    , ">": "&gt;"\n    , \'"\': "&#34;"\n    , "\'": "&#39;"\n    }\n  , _MATCH_HTML = /[&<>\'"]/g;\nfunction encode_char(c) {\n  return _ENCODE_HTML_RULES[c] || c;\n};\n'},n.shallowCopy=function(e,t){for(var n in t=t||{})e[n]=t[n];return e},n.shallowCopyFromList=function(e,t,n){for(var r=0;r<n.length;r++){var i=n[r];void 0!==t[i]&&(e[i]=t[i])}return e},n.cache={_data:{},set:function(e,t){this._data[e]=t},get:function(e){return this._data[e]},remove:function(e){delete this._data[e]},reset:function(){this._data={}}},n.hyphenToCamel=function(e){return e.replace(/-[a-z]/g,(function(e){return e[1].toUpperCase()}))}},{}],3:[function(e,t,n){},{}],4:[function(e,t,n){(function(e){function t(e,t){for(var n=0,r=e.length-1;r>=0;r--){var i=e[r];"."===i?e.splice(r,1):".."===i?(e.splice(r,1),n++):n&&(e.splice(r,1),n--)}if(t)for(;n--;n)e.unshift("..");return e}function r(e,t){if(e.filter)return e.filter(t);for(var n=[],r=0;r<e.length;r++)t(e[r],r,e)&&n.push(e[r]);return n}n.resolve=function(){for(var n="",i=!1,o=arguments.length-1;o>=-1&&!i;o--){var s=o>=0?arguments[o]:e.cwd();if("string"!=typeof s)throw new TypeError("Arguments to path.resolve must be strings");s&&(n=s+"/"+n,i="/"===s.charAt(0))}return(i?"/":"")+(n=t(r(n.split("/"),(function(e){return!!e})),!i).join("/"))||"."},n.normalize=function(e){var o=n.isAbsolute(e),s="/"===i(e,-1);return(e=t(r(e.split("/"),(function(e){return!!e})),!o).join("/"))||o||(e="."),e&&s&&(e+="/"),(o?"/":"")+e},n.isAbsolute=function(e){return"/"===e.charAt(0)},n.join=function(){var e=Array.prototype.slice.call(arguments,0);return n.normalize(r(e,(function(e,t){if("string"!=typeof e)throw new TypeError("Arguments to path.join must be strings");return e})).join("/"))},n.relative=function(e,t){function r(e){for(var t=0;t<e.length&&""===e[t];t++);for(var n=e.length-1;n>=0&&""===e[n];n--);return t>n?[]:e.slice(t,n-t+1)}e=n.resolve(e).substr(1),t=n.resolve(t).substr(1);for(var i=r(e.split("/")),o=r(t.split("/")),s=Math.min(i.length,o.length),c=s,a=0;a<s;a++)if(i[a]!==o[a]){c=a;break}var l=[];for(a=c;a<i.length;a++)l.push("..");return(l=l.concat(o.slice(c))).join("/")},n.sep="/",n.delimiter=":",n.dirname=function(e){if("string"!=typeof e&&(e+=""),0===e.length)return".";for(var t=e.charCodeAt(0),n=47===t,r=-1,i=!0,o=e.length-1;o>=1;--o)if(47===(t=e.charCodeAt(o))){if(!i){r=o;break}}else i=!1;return-1===r?n?"/":".":n&&1===r?"/":e.slice(0,r)},n.basename=function(e,t){var n=function(e){"string"!=typeof e&&(e+="");var t,n=0,r=-1,i=!0;for(t=e.length-1;t>=0;--t)if(47===e.charCodeAt(t)){if(!i){n=t+1;break}}else-1===r&&(i=!1,r=t+1);return-1===r?"":e.slice(n,r)}(e);return t&&n.substr(-1*t.length)===t&&(n=n.substr(0,n.length-t.length)),n},n.extname=function(e){"string"!=typeof e&&(e+="");for(var t=-1,n=0,r=-1,i=!0,o=0,s=e.length-1;s>=0;--s){var c=e.charCodeAt(s);if(47!==c)-1===r&&(i=!1,r=s+1),46===c?-1===t?t=s:1!==o&&(o=1):-1!==t&&(o=-1);else if(!i){n=s+1;break}}return-1===t||-1===r||0===o||1===o&&t===r-1&&t===n+1?"":e.slice(t,r)};var i="b"==="ab".substr(-1)?function(e,t,n){return e.substr(t,n)}:function(e,t,n){return t<0&&(t=e.length+t),e.substr(t,n)}}).call(this,e("_process"))},{_process:5}],5:[function(e,t,n){var r,i,o=t.exports={};function s(){throw new Error("setTimeout has not been defined")}function c(){throw new Error("clearTimeout has not been defined")}function a(e){if(r===setTimeout)return setTimeout(e,0);if((r===s||!r)&&setTimeout)return r=setTimeout,setTimeout(e,0);try{return r(e,0)}catch(t){try{return r.call(null,e,0)}catch(t){return r.call(this,e,0)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:s}catch(e){r=s}try{i="function"==typeof clearTimeout?clearTimeout:c}catch(e){i=c}}();var l,u=[],p=!1,f=-1;function h(){p&&l&&(p=!1,l.length?u=l.concat(u):f=-1,u.length&&m())}function m(){if(!p){var e=a(h);p=!0;for(var t=u.length;t;){for(l=u,u=[];++f<t;)l&&l[f].run();f=-1,t=u.length}l=null,p=!1,function(e){if(i===clearTimeout)return clearTimeout(e);if((i===c||!i)&&clearTimeout)return i=clearTimeout,clearTimeout(e);try{i(e)}catch(t){try{return i.call(null,e)}catch(t){return i.call(this,e)}}}(e)}}function d(e,t){this.fun=e,this.array=t}function g(){}o.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];u.push(new d(e,t)),1!==u.length||p||a(m)},d.prototype.run=function(){this.fun.apply(null,this.array)},o.title="browser",o.browser=!0,o.env={},o.argv=[],o.version="",o.versions={},o.on=g,o.addListener=g,o.once=g,o.off=g,o.removeListener=g,o.removeAllListeners=g,o.emit=g,o.prependListener=g,o.prependOnceListener=g,o.listeners=function(e){return[]},o.binding=function(e){throw new Error("process.binding is not supported")},o.cwd=function(){return"/"},o.chdir=function(e){throw new Error("process.chdir is not supported")},o.umask=function(){return 0}},{}],6:[function(e,t,n){t.exports={name:"ejs",description:"Embedded JavaScript templates",keywords:["template","engine","ejs"],version:"3.1.6",author:"Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)",license:"Apache-2.0",bin:{ejs:"./bin/cli.js"},main:"./lib/ejs.js",jsdelivr:"ejs.min.js",unpkg:"ejs.min.js",repository:{type:"git",url:"git://github.com/mde/ejs.git"},bugs:"https://github.com/mde/ejs/issues",homepage:"https://github.com/mde/ejs",dependencies:{jake:"^10.6.1"},devDependencies:{browserify:"^16.5.1",eslint:"^6.8.0","git-directory-deploy":"^1.5.1",jsdoc:"^3.6.4","lru-cache":"^4.0.1",mocha:"^7.1.1","uglify-js":"^3.3.16"},engines:{node:">=0.10.0"},scripts:{test:"mocha"}}},{}]},{},[1])(1)}));
\ No newline at end of file
index e40628c..f799002 100755 (executable)
@@ -1 +1 @@
-(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.ejs=f()}})(function(){var define,module,exports;return function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r}()({1:[function(require,module,exports){"use strict";var fs=require("fs");var path=require("path");var utils=require("./utils");var scopeOptionWarned=false;var _VERSION_STRING=require("../package.json").version;var _DEFAULT_OPEN_DELIMITER="<";var _DEFAULT_CLOSE_DELIMITER=">";var _DEFAULT_DELIMITER="%";var _DEFAULT_LOCALS_NAME="locals";var _NAME="ejs";var _REGEX_STRING="(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)";var _OPTS_PASSABLE_WITH_DATA=["delimiter","scope","context","debug","compileDebug","client","_with","rmWhitespace","strict","filename","async"];var _OPTS_PASSABLE_WITH_DATA_EXPRESS=_OPTS_PASSABLE_WITH_DATA.concat("cache");var _BOM=/^\uFEFF/;exports.cache=utils.cache;exports.fileLoader=fs.readFileSync;exports.localsName=_DEFAULT_LOCALS_NAME;exports.promiseImpl=new Function("return this;")().Promise;exports.resolveInclude=function(name,filename,isDir){var dirname=path.dirname;var extname=path.extname;var resolve=path.resolve;var includePath=resolve(isDir?filename:dirname(filename),name);var ext=extname(name);if(!ext){includePath+=".ejs"}return includePath};function resolvePaths(name,paths){var filePath;if(paths.some(function(v){filePath=exports.resolveInclude(name,v,true);return fs.existsSync(filePath)})){return filePath}}function getIncludePath(path,options){var includePath;var filePath;var views=options.views;var match=/^[A-Za-z]+:\\|^\//.exec(path);if(match&&match.length){path=path.replace(/^\/*/,"");if(Array.isArray(options.root)){includePath=resolvePaths(path,options.root)}else{includePath=exports.resolveInclude(path,options.root||"/",true)}}else{if(options.filename){filePath=exports.resolveInclude(path,options.filename);if(fs.existsSync(filePath)){includePath=filePath}}if(!includePath&&Array.isArray(views)){includePath=resolvePaths(path,views)}if(!includePath&&typeof options.includer!=="function"){throw new Error('Could not find the include file "'+options.escapeFunction(path)+'"')}}return includePath}function handleCache(options,template){var func;var filename=options.filename;var hasTemplate=arguments.length>1;if(options.cache){if(!filename){throw new Error("cache option requires a filename")}func=exports.cache.get(filename);if(func){return func}if(!hasTemplate){template=fileLoader(filename).toString().replace(_BOM,"")}}else if(!hasTemplate){if(!filename){throw new Error("Internal EJS error: no file name or template "+"provided")}template=fileLoader(filename).toString().replace(_BOM,"")}func=exports.compile(template,options);if(options.cache){exports.cache.set(filename,func)}return func}function tryHandleCache(options,data,cb){var result;if(!cb){if(typeof exports.promiseImpl=="function"){return new exports.promiseImpl(function(resolve,reject){try{result=handleCache(options)(data);resolve(result)}catch(err){reject(err)}})}else{throw new Error("Please provide a callback function")}}else{try{result=handleCache(options)(data)}catch(err){return cb(err)}cb(null,result)}}function fileLoader(filePath){return exports.fileLoader(filePath)}function includeFile(path,options){var opts=utils.shallowCopy({},options);opts.filename=getIncludePath(path,opts);if(typeof options.includer==="function"){var includerResult=options.includer(path,opts.filename);if(includerResult){if(includerResult.filename){opts.filename=includerResult.filename}if(includerResult.template){return handleCache(opts,includerResult.template)}}}return handleCache(opts)}function rethrow(err,str,flnm,lineno,esc){var lines=str.split("\n");var start=Math.max(lineno-3,0);var end=Math.min(lines.length,lineno+3);var filename=esc(flnm);var context=lines.slice(start,end).map(function(line,i){var curr=i+start+1;return(curr==lineno?" >> ":"    ")+curr+"| "+line}).join("\n");err.path=filename;err.message=(filename||"ejs")+":"+lineno+"\n"+context+"\n\n"+err.message;throw err}function stripSemi(str){return str.replace(/;(\s*$)/,"$1")}exports.compile=function compile(template,opts){var templ;if(opts&&opts.scope){if(!scopeOptionWarned){console.warn("`scope` option is deprecated and will be removed in EJS 3");scopeOptionWarned=true}if(!opts.context){opts.context=opts.scope}delete opts.scope}templ=new Template(template,opts);return templ.compile()};exports.render=function(template,d,o){var data=d||{};var opts=o||{};if(arguments.length==2){utils.shallowCopyFromList(opts,data,_OPTS_PASSABLE_WITH_DATA)}return handleCache(opts,template)(data)};exports.renderFile=function(){var args=Array.prototype.slice.call(arguments);var filename=args.shift();var cb;var opts={filename:filename};var data;var viewOpts;if(typeof arguments[arguments.length-1]=="function"){cb=args.pop()}if(args.length){data=args.shift();if(args.length){utils.shallowCopy(opts,args.pop())}else{if(data.settings){if(data.settings.views){opts.views=data.settings.views}if(data.settings["view cache"]){opts.cache=true}viewOpts=data.settings["view options"];if(viewOpts){utils.shallowCopy(opts,viewOpts)}}utils.shallowCopyFromList(opts,data,_OPTS_PASSABLE_WITH_DATA_EXPRESS)}opts.filename=filename}else{data={}}return tryHandleCache(opts,data,cb)};exports.Template=Template;exports.clearCache=function(){exports.cache.reset()};function Template(text,opts){opts=opts||{};var options={};this.templateText=text;this.mode=null;this.truncate=false;this.currentLine=1;this.source="";options.client=opts.client||false;options.escapeFunction=opts.escape||opts.escapeFunction||utils.escapeXML;options.compileDebug=opts.compileDebug!==false;options.debug=!!opts.debug;options.filename=opts.filename;options.openDelimiter=opts.openDelimiter||exports.openDelimiter||_DEFAULT_OPEN_DELIMITER;options.closeDelimiter=opts.closeDelimiter||exports.closeDelimiter||_DEFAULT_CLOSE_DELIMITER;options.delimiter=opts.delimiter||exports.delimiter||_DEFAULT_DELIMITER;options.strict=opts.strict||false;options.context=opts.context;options.cache=opts.cache||false;options.rmWhitespace=opts.rmWhitespace;options.root=opts.root;options.includer=opts.includer;options.outputFunctionName=opts.outputFunctionName;options.localsName=opts.localsName||exports.localsName||_DEFAULT_LOCALS_NAME;options.views=opts.views;options.async=opts.async;options.destructuredLocals=opts.destructuredLocals;options.legacyInclude=typeof opts.legacyInclude!="undefined"?!!opts.legacyInclude:true;if(options.strict){options._with=false}else{options._with=typeof opts._with!="undefined"?opts._with:true}this.opts=options;this.regex=this.createRegex()}Template.modes={EVAL:"eval",ESCAPED:"escaped",RAW:"raw",COMMENT:"comment",LITERAL:"literal"};Template.prototype={createRegex:function(){var str=_REGEX_STRING;var delim=utils.escapeRegExpChars(this.opts.delimiter);var open=utils.escapeRegExpChars(this.opts.openDelimiter);var close=utils.escapeRegExpChars(this.opts.closeDelimiter);str=str.replace(/%/g,delim).replace(/</g,open).replace(/>/g,close);return new RegExp(str)},compile:function(){var src;var fn;var opts=this.opts;var prepended="";var appended="";var escapeFn=opts.escapeFunction;var ctor;var sanitizedFilename=opts.filename?JSON.stringify(opts.filename):"undefined";if(!this.source){this.generateSource();prepended+='  var __output = "";\n'+"  function __append(s) { if (s !== undefined && s !== null) __output += s }\n";if(opts.outputFunctionName){prepended+="  var "+opts.outputFunctionName+" = __append;"+"\n"}if(opts.destructuredLocals&&opts.destructuredLocals.length){var destructuring="  var __locals = ("+opts.localsName+" || {}),\n";for(var i=0;i<opts.destructuredLocals.length;i++){var name=opts.destructuredLocals[i];if(i>0){destructuring+=",\n  "}destructuring+=name+" = __locals."+name}prepended+=destructuring+";\n"}if(opts._with!==false){prepended+="  with ("+opts.localsName+" || {}) {"+"\n";appended+="  }"+"\n"}appended+="  return __output;"+"\n";this.source=prepended+this.source+appended}if(opts.compileDebug){src="var __line = 1"+"\n"+"  , __lines = "+JSON.stringify(this.templateText)+"\n"+"  , __filename = "+sanitizedFilename+";"+"\n"+"try {"+"\n"+this.source+"} catch (e) {"+"\n"+"  rethrow(e, __lines, __filename, __line, escapeFn);"+"\n"+"}"+"\n"}else{src=this.source}if(opts.client){src="escapeFn = escapeFn || "+escapeFn.toString()+";"+"\n"+src;if(opts.compileDebug){src="rethrow = rethrow || "+rethrow.toString()+";"+"\n"+src}}if(opts.strict){src='"use strict";\n'+src}if(opts.debug){console.log(src)}if(opts.compileDebug&&opts.filename){src=src+"\n"+"//# sourceURL="+sanitizedFilename+"\n"}try{if(opts.async){try{ctor=new Function("return (async function(){}).constructor;")()}catch(e){if(e instanceof SyntaxError){throw new Error("This environment does not support async/await")}else{throw e}}}else{ctor=Function}fn=new ctor(opts.localsName+", escapeFn, include, rethrow",src)}catch(e){if(e instanceof SyntaxError){if(opts.filename){e.message+=" in "+opts.filename}e.message+=" while compiling ejs\n\n";e.message+="If the above error is not helpful, you may want to try EJS-Lint:\n";e.message+="https://github.com/RyanZim/EJS-Lint";if(!opts.async){e.message+="\n";e.message+="Or, if you meant to create an async function, pass `async: true` as an option."}}throw e}var returnedFn=opts.client?fn:function anonymous(data){var include=function(path,includeData){var d=utils.shallowCopy({},data);if(includeData){d=utils.shallowCopy(d,includeData)}return includeFile(path,opts)(d)};return fn.apply(opts.context,[data||{},escapeFn,include,rethrow])};if(opts.filename&&typeof Object.defineProperty==="function"){var filename=opts.filename;var basename=path.basename(filename,path.extname(filename));try{Object.defineProperty(returnedFn,"name",{value:basename,writable:false,enumerable:false,configurable:true})}catch(e){}}return returnedFn},generateSource:function(){var opts=this.opts;if(opts.rmWhitespace){this.templateText=this.templateText.replace(/[\r\n]+/g,"\n").replace(/^\s+|\s+$/gm,"")}this.templateText=this.templateText.replace(/[ \t]*<%_/gm,"<%_").replace(/_%>[ \t]*/gm,"_%>");var self=this;var matches=this.parseTemplateText();var d=this.opts.delimiter;var o=this.opts.openDelimiter;var c=this.opts.closeDelimiter;if(matches&&matches.length){matches.forEach(function(line,index){var closing;if(line.indexOf(o+d)===0&&line.indexOf(o+d+d)!==0){closing=matches[index+2];if(!(closing==d+c||closing=="-"+d+c||closing=="_"+d+c)){throw new Error('Could not find matching close tag for "'+line+'".')}}self.scanLine(line)})}},parseTemplateText:function(){var str=this.templateText;var pat=this.regex;var result=pat.exec(str);var arr=[];var firstPos;while(result){firstPos=result.index;if(firstPos!==0){arr.push(str.substring(0,firstPos));str=str.slice(firstPos)}arr.push(result[0]);str=str.slice(result[0].length);result=pat.exec(str)}if(str){arr.push(str)}return arr},_addOutput:function(line){if(this.truncate){line=line.replace(/^(?:\r\n|\r|\n)/,"");this.truncate=false}if(!line){return line}line=line.replace(/\\/g,"\\\\");line=line.replace(/\n/g,"\\n");line=line.replace(/\r/g,"\\r");line=line.replace(/"/g,'\\"');this.source+='    ; __append("'+line+'")'+"\n"},scanLine:function(line){var self=this;var d=this.opts.delimiter;var o=this.opts.openDelimiter;var c=this.opts.closeDelimiter;var newLineCount=0;newLineCount=line.split("\n").length-1;switch(line){case o+d:case o+d+"_":this.mode=Template.modes.EVAL;break;case o+d+"=":this.mode=Template.modes.ESCAPED;break;case o+d+"-":this.mode=Template.modes.RAW;break;case o+d+"#":this.mode=Template.modes.COMMENT;break;case o+d+d:this.mode=Template.modes.LITERAL;this.source+='    ; __append("'+line.replace(o+d+d,o+d)+'")'+"\n";break;case d+d+c:this.mode=Template.modes.LITERAL;this.source+='    ; __append("'+line.replace(d+d+c,d+c)+'")'+"\n";break;case d+c:case"-"+d+c:case"_"+d+c:if(this.mode==Template.modes.LITERAL){this._addOutput(line)}this.mode=null;this.truncate=line.indexOf("-")===0||line.indexOf("_")===0;break;default:if(this.mode){switch(this.mode){case Template.modes.EVAL:case Template.modes.ESCAPED:case Template.modes.RAW:if(line.lastIndexOf("//")>line.lastIndexOf("\n")){line+="\n"}}switch(this.mode){case Template.modes.EVAL:this.source+="    ; "+line+"\n";break;case Template.modes.ESCAPED:this.source+="    ; __append(escapeFn("+stripSemi(line)+"))"+"\n";break;case Template.modes.RAW:this.source+="    ; __append("+stripSemi(line)+")"+"\n";break;case Template.modes.COMMENT:break;case Template.modes.LITERAL:this._addOutput(line);break}}else{this._addOutput(line)}}if(self.opts.compileDebug&&newLineCount){this.currentLine+=newLineCount;this.source+="    ; __line = "+this.currentLine+"\n"}}};exports.escapeXML=utils.escapeXML;exports.__express=exports.renderFile;exports.VERSION=_VERSION_STRING;exports.name=_NAME;if(typeof window!="undefined"){window.ejs=exports}},{"../package.json":6,"./utils":2,fs:3,path:4}],2:[function(require,module,exports){"use strict";var regExpChars=/[|\\{}()[\]^$+*?.]/g;exports.escapeRegExpChars=function(string){if(!string){return""}return String(string).replace(regExpChars,"\\$&")};var _ENCODE_HTML_RULES={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&#34;","'":"&#39;"};var _MATCH_HTML=/[&<>'"]/g;function encode_char(c){return _ENCODE_HTML_RULES[c]||c}var escapeFuncStr="var _ENCODE_HTML_RULES = {\n"+'      "&": "&amp;"\n'+'    , "<": "&lt;"\n'+'    , ">": "&gt;"\n'+'    , \'"\': "&#34;"\n'+'    , "\'": "&#39;"\n'+"    }\n"+"  , _MATCH_HTML = /[&<>'\"]/g;\n"+"function encode_char(c) {\n"+"  return _ENCODE_HTML_RULES[c] || c;\n"+"};\n";exports.escapeXML=function(markup){return markup==undefined?"":String(markup).replace(_MATCH_HTML,encode_char)};exports.escapeXML.toString=function(){return Function.prototype.toString.call(this)+";\n"+escapeFuncStr};exports.shallowCopy=function(to,from){from=from||{};for(var p in from){to[p]=from[p]}return to};exports.shallowCopyFromList=function(to,from,list){for(var i=0;i<list.length;i++){var p=list[i];if(typeof from[p]!="undefined"){to[p]=from[p]}}return to};exports.cache={_data:{},set:function(key,val){this._data[key]=val},get:function(key){return this._data[key]},remove:function(key){delete this._data[key]},reset:function(){this._data={}}};exports.hyphenToCamel=function(str){return str.replace(/-[a-z]/g,function(match){return match[1].toUpperCase()})}},{}],3:[function(require,module,exports){},{}],4:[function(require,module,exports){(function(process){function normalizeArray(parts,allowAboveRoot){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(allowAboveRoot){for(;up--;up){parts.unshift("..")}}return parts}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();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)==="/"}resolvedPath=normalizeArray(filter(resolvedPath.split("/"),function(p){return!!p}),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."};exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash=substr(path,-1)==="/";path=normalizeArray(filter(path.split("/"),function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path};exports.isAbsolute=function(path){return path.charAt(0)==="/"};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("/"))};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{matchedSlash=false}}if(end===-1)return hasRoot?"/":".";if(hasRoot&&end===1){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(!matchedSlash){start=i+1;break}}else if(end===-1){matchedSlash=false;end=i+1}}if(end===-1)return"";return path.slice(start,end)}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;var preDotState=0;for(var i=path.length-1;i>=0;--i){var code=path.charCodeAt(i);if(code===47){if(!matchedSlash){startPart=i+1;break}continue}if(end===-1){matchedSlash=false;end=i+1}if(code===46){if(startDot===-1)startDot=i;else if(preDotState!==1)preDotState=1}else if(startDot!==-1){preDotState=-1}}if(startDot===-1||end===-1||preDotState===0||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}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,require("_process"))},{_process:5}],5:[function(require,module,exports){var process=module.exports={};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){return setTimeout(fun,0)}if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0)}try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){return clearTimeout(marker)}if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker)}try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){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)}};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="";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}},{}],6:[function(require,module,exports){module.exports={name:"ejs",description:"Embedded JavaScript templates",keywords:["template","engine","ejs"],version:"3.1.6",author:"Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)",license:"Apache-2.0",bin:{ejs:"./bin/cli.js"},main:"./lib/ejs.js",jsdelivr:"ejs.min.js",unpkg:"ejs.min.js",repository:{type:"git",url:"git://github.com/mde/ejs.git"},bugs:"https://github.com/mde/ejs/issues",homepage:"https://github.com/mde/ejs",dependencies:{jake:"^10.6.1"},devDependencies:{browserify:"^16.5.1",eslint:"^6.8.0","git-directory-deploy":"^1.5.1",jsdoc:"^3.6.4","lru-cache":"^4.0.1",mocha:"^7.1.1","uglify-js":"^3.3.16"},engines:{node:">=0.10.0"},scripts:{test:"mocha"}}},{}]},{},[1])(1)});
+!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).ejs=e()}}((function(){return function e(t,n,r){function i(s,c){if(!n[s]){if(!t[s]){var a="function"==typeof require&&require;if(!c&&a)return a(s,!0);if(o)return o(s,!0);var l=new Error("Cannot find module '"+s+"'");throw l.code="MODULE_NOT_FOUND",l}var u=n[s]={exports:{}};t[s][0].call(u.exports,(function(e){return i(t[s][1][e]||e)}),u,u.exports,e,t,n,r)}return n[s].exports}for(var o="function"==typeof require&&require,s=0;s<r.length;s++)i(r[s]);return i}({1:[function(e,t,n){"use strict";var r=e("fs"),i=e("path"),o=e("./utils"),s=!1,c=e("../package.json").version,a="locals",l=["delimiter","scope","context","debug","compileDebug","client","_with","rmWhitespace","strict","filename","async"],u=l.concat("cache"),p=/^\uFEFF/;function f(e,t){var i;if(t.some((function(t){return i=n.resolveInclude(e,t,!0),r.existsSync(i)})))return i}function h(e,t){var r,i=e.filename,o=arguments.length>1;if(e.cache){if(!i)throw new Error("cache option requires a filename");if(r=n.cache.get(i))return r;o||(t=d(i).toString().replace(p,""))}else if(!o){if(!i)throw new Error("Internal EJS error: no file name or template provided");t=d(i).toString().replace(p,"")}return r=n.compile(t,e),e.cache&&n.cache.set(i,r),r}function m(e,t,r){var i;if(!r){if("function"==typeof n.promiseImpl)return new n.promiseImpl((function(n,r){try{n(i=h(e)(t))}catch(e){r(e)}}));throw new Error("Please provide a callback function")}try{i=h(e)(t)}catch(e){return r(e)}r(null,i)}function d(e){return n.fileLoader(e)}function g(e,t){var i=o.shallowCopy({},t);if(i.filename=function(e,t){var i,o,s=t.views,c=/^[A-Za-z]+:\\|^\//.exec(e);if(c&&c.length)e=e.replace(/^\/*/,""),i=Array.isArray(t.root)?f(e,t.root):n.resolveInclude(e,t.root||"/",!0);else if(t.filename&&(o=n.resolveInclude(e,t.filename),r.existsSync(o)&&(i=o)),!i&&Array.isArray(s)&&(i=f(e,s)),!i&&"function"!=typeof t.includer)throw new Error('Could not find the include file "'+t.escapeFunction(e)+'"');return i}(e,i),"function"==typeof t.includer){var s=t.includer(e,i.filename);if(s&&(s.filename&&(i.filename=s.filename),s.template))return h(i,s.template)}return h(i)}function v(e,t,n,r,i){var o=t.split("\n"),s=Math.max(r-3,0),c=Math.min(o.length,r+3),a=i(n),l=o.slice(s,c).map((function(e,t){var n=t+s+1;return(n==r?" >> ":"    ")+n+"| "+e})).join("\n");throw e.path=a,e.message=(a||"ejs")+":"+r+"\n"+l+"\n\n"+e.message,e}function y(e){return e.replace(/;(\s*$)/,"$1")}function w(e,t){t=t||{};var r={};this.templateText=e,this.mode=null,this.truncate=!1,this.currentLine=1,this.source="",r.client=t.client||!1,r.escapeFunction=t.escape||t.escapeFunction||o.escapeXML,r.compileDebug=!1!==t.compileDebug,r.debug=!!t.debug,r.filename=t.filename,r.openDelimiter=t.openDelimiter||n.openDelimiter||"<",r.closeDelimiter=t.closeDelimiter||n.closeDelimiter||">",r.delimiter=t.delimiter||n.delimiter||"%",r.strict=t.strict||!1,r.context=t.context,r.cache=t.cache||!1,r.rmWhitespace=t.rmWhitespace,r.root=t.root,r.includer=t.includer,r.outputFunctionName=t.outputFunctionName,r.localsName=t.localsName||n.localsName||a,r.views=t.views,r.async=t.async,r.destructuredLocals=t.destructuredLocals,r.legacyInclude=void 0===t.legacyInclude||!!t.legacyInclude,r.strict?r._with=!1:r._with=void 0===t._with||t._with,this.opts=r,this.regex=this.createRegex()}n.cache=o.cache,n.fileLoader=r.readFileSync,n.localsName=a,n.promiseImpl=new Function("return this;")().Promise,n.resolveInclude=function(e,t,n){var r=i.dirname,o=i.extname,s=(0,i.resolve)(n?t:r(t),e);return o(e)||(s+=".ejs"),s},n.compile=function(e,t){return t&&t.scope&&(s||(console.warn("`scope` option is deprecated and will be removed in EJS 3"),s=!0),t.context||(t.context=t.scope),delete t.scope),new w(e,t).compile()},n.render=function(e,t,n){var r=t||{},i=n||{};return 2==arguments.length&&o.shallowCopyFromList(i,r,l),h(i,e)(r)},n.renderFile=function(){var e,t,n,r=Array.prototype.slice.call(arguments),i=r.shift(),s={filename:i};return"function"==typeof arguments[arguments.length-1]&&(e=r.pop()),r.length?(t=r.shift(),r.length?o.shallowCopy(s,r.pop()):(t.settings&&(t.settings.views&&(s.views=t.settings.views),t.settings["view cache"]&&(s.cache=!0),(n=t.settings["view options"])&&o.shallowCopy(s,n)),o.shallowCopyFromList(s,t,u)),s.filename=i):t={},m(s,t,e)},n.Template=w,n.clearCache=function(){n.cache.reset()},w.modes={EVAL:"eval",ESCAPED:"escaped",RAW:"raw",COMMENT:"comment",LITERAL:"literal"},w.prototype={createRegex:function(){var e="(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)",t=o.escapeRegExpChars(this.opts.delimiter),n=o.escapeRegExpChars(this.opts.openDelimiter),r=o.escapeRegExpChars(this.opts.closeDelimiter);return e=e.replace(/%/g,t).replace(/</g,n).replace(/>/g,r),new RegExp(e)},compile:function(){var e,t,n,r=this.opts,s="",c="",a=r.escapeFunction,l=r.filename?JSON.stringify(r.filename):"undefined";if(!this.source){if(this.generateSource(),s+='  var __output = "";\n  function __append(s) { if (s !== undefined && s !== null) __output += s }\n',r.outputFunctionName&&(s+="  var "+r.outputFunctionName+" = __append;\n"),r.destructuredLocals&&r.destructuredLocals.length){for(var u="  var __locals = ("+r.localsName+" || {}),\n",p=0;p<r.destructuredLocals.length;p++){var f=r.destructuredLocals[p];p>0&&(u+=",\n  "),u+=f+" = __locals."+f}s+=u+";\n"}!1!==r._with&&(s+="  with ("+r.localsName+" || {}) {\n",c+="  }\n"),c+="  return __output;\n",this.source=s+this.source+c}e=r.compileDebug?"var __line = 1\n  , __lines = "+JSON.stringify(this.templateText)+"\n  , __filename = "+l+";\ntry {\n"+this.source+"} catch (e) {\n  rethrow(e, __lines, __filename, __line, escapeFn);\n}\n":this.source,r.client&&(e="escapeFn = escapeFn || "+a.toString()+";\n"+e,r.compileDebug&&(e="rethrow = rethrow || "+v.toString()+";\n"+e)),r.strict&&(e='"use strict";\n'+e),r.debug&&console.log(e),r.compileDebug&&r.filename&&(e=e+"\n//# sourceURL="+l+"\n");try{if(r.async)try{n=new Function("return (async function(){}).constructor;")()}catch(e){throw e instanceof SyntaxError?new Error("This environment does not support async/await"):e}else n=Function;t=new n(r.localsName+", escapeFn, include, rethrow",e)}catch(e){throw e instanceof SyntaxError&&(r.filename&&(e.message+=" in "+r.filename),e.message+=" while compiling ejs\n\n",e.message+="If the above error is not helpful, you may want to try EJS-Lint:\n",e.message+="https://github.com/RyanZim/EJS-Lint",r.async||(e.message+="\n",e.message+="Or, if you meant to create an async function, pass `async: true` as an option.")),e}var h=r.client?t:function(e){return t.apply(r.context,[e||{},a,function(t,n){var i=o.shallowCopy({},e);return n&&(i=o.shallowCopy(i,n)),g(t,r)(i)},v])};if(r.filename&&"function"==typeof Object.defineProperty){var m=r.filename,d=i.basename(m,i.extname(m));try{Object.defineProperty(h,"name",{value:d,writable:!1,enumerable:!1,configurable:!0})}catch(e){}}return h},generateSource:function(){this.opts.rmWhitespace&&(this.templateText=this.templateText.replace(/[\r\n]+/g,"\n").replace(/^\s+|\s+$/gm,"")),this.templateText=this.templateText.replace(/[ \t]*<%_/gm,"<%_").replace(/_%>[ \t]*/gm,"_%>");var e=this,t=this.parseTemplateText(),n=this.opts.delimiter,r=this.opts.openDelimiter,i=this.opts.closeDelimiter;t&&t.length&&t.forEach((function(o,s){var c;if(0===o.indexOf(r+n)&&0!==o.indexOf(r+n+n)&&(c=t[s+2])!=n+i&&c!="-"+n+i&&c!="_"+n+i)throw new Error('Could not find matching close tag for "'+o+'".');e.scanLine(o)}))},parseTemplateText:function(){for(var e,t=this.templateText,n=this.regex,r=n.exec(t),i=[];r;)0!==(e=r.index)&&(i.push(t.substring(0,e)),t=t.slice(e)),i.push(r[0]),t=t.slice(r[0].length),r=n.exec(t);return t&&i.push(t),i},_addOutput:function(e){if(this.truncate&&(e=e.replace(/^(?:\r\n|\r|\n)/,""),this.truncate=!1),!e)return e;e=(e=(e=(e=e.replace(/\\/g,"\\\\")).replace(/\n/g,"\\n")).replace(/\r/g,"\\r")).replace(/"/g,'\\"'),this.source+='    ; __append("'+e+'")\n'},scanLine:function(e){var t,n=this.opts.delimiter,r=this.opts.openDelimiter,i=this.opts.closeDelimiter;switch(t=e.split("\n").length-1,e){case r+n:case r+n+"_":this.mode=w.modes.EVAL;break;case r+n+"=":this.mode=w.modes.ESCAPED;break;case r+n+"-":this.mode=w.modes.RAW;break;case r+n+"#":this.mode=w.modes.COMMENT;break;case r+n+n:this.mode=w.modes.LITERAL,this.source+='    ; __append("'+e.replace(r+n+n,r+n)+'")\n';break;case n+n+i:this.mode=w.modes.LITERAL,this.source+='    ; __append("'+e.replace(n+n+i,n+i)+'")\n';break;case n+i:case"-"+n+i:case"_"+n+i:this.mode==w.modes.LITERAL&&this._addOutput(e),this.mode=null,this.truncate=0===e.indexOf("-")||0===e.indexOf("_");break;default:if(this.mode){switch(this.mode){case w.modes.EVAL:case w.modes.ESCAPED:case w.modes.RAW:e.lastIndexOf("//")>e.lastIndexOf("\n")&&(e+="\n")}switch(this.mode){case w.modes.EVAL:this.source+="    ; "+e+"\n";break;case w.modes.ESCAPED:this.source+="    ; __append(escapeFn("+y(e)+"))\n";break;case w.modes.RAW:this.source+="    ; __append("+y(e)+")\n";break;case w.modes.COMMENT:break;case w.modes.LITERAL:this._addOutput(e)}}else this._addOutput(e)}this.opts.compileDebug&&t&&(this.currentLine+=t,this.source+="    ; __line = "+this.currentLine+"\n")}},n.escapeXML=o.escapeXML,n.__express=n.renderFile,n.VERSION=c,n.name="ejs","undefined"!=typeof window&&(window.ejs=n)},{"../package.json":6,"./utils":2,fs:3,path:4}],2:[function(e,t,n){"use strict";var r=/[|\\{}()[\]^$+*?.]/g;n.escapeRegExpChars=function(e){return e?String(e).replace(r,"\\$&"):""};var i={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&#34;","'":"&#39;"},o=/[&<>'"]/g;function s(e){return i[e]||e}n.escapeXML=function(e){return null==e?"":String(e).replace(o,s)},n.escapeXML.toString=function(){return Function.prototype.toString.call(this)+';\nvar _ENCODE_HTML_RULES = {\n      "&": "&amp;"\n    , "<": "&lt;"\n    , ">": "&gt;"\n    , \'"\': "&#34;"\n    , "\'": "&#39;"\n    }\n  , _MATCH_HTML = /[&<>\'"]/g;\nfunction encode_char(c) {\n  return _ENCODE_HTML_RULES[c] || c;\n};\n'},n.shallowCopy=function(e,t){for(var n in t=t||{})e[n]=t[n];return e},n.shallowCopyFromList=function(e,t,n){for(var r=0;r<n.length;r++){var i=n[r];void 0!==t[i]&&(e[i]=t[i])}return e},n.cache={_data:{},set:function(e,t){this._data[e]=t},get:function(e){return this._data[e]},remove:function(e){delete this._data[e]},reset:function(){this._data={}}},n.hyphenToCamel=function(e){return e.replace(/-[a-z]/g,(function(e){return e[1].toUpperCase()}))}},{}],3:[function(e,t,n){},{}],4:[function(e,t,n){(function(e){function t(e,t){for(var n=0,r=e.length-1;r>=0;r--){var i=e[r];"."===i?e.splice(r,1):".."===i?(e.splice(r,1),n++):n&&(e.splice(r,1),n--)}if(t)for(;n--;n)e.unshift("..");return e}function r(e,t){if(e.filter)return e.filter(t);for(var n=[],r=0;r<e.length;r++)t(e[r],r,e)&&n.push(e[r]);return n}n.resolve=function(){for(var n="",i=!1,o=arguments.length-1;o>=-1&&!i;o--){var s=o>=0?arguments[o]:e.cwd();if("string"!=typeof s)throw new TypeError("Arguments to path.resolve must be strings");s&&(n=s+"/"+n,i="/"===s.charAt(0))}return(i?"/":"")+(n=t(r(n.split("/"),(function(e){return!!e})),!i).join("/"))||"."},n.normalize=function(e){var o=n.isAbsolute(e),s="/"===i(e,-1);return(e=t(r(e.split("/"),(function(e){return!!e})),!o).join("/"))||o||(e="."),e&&s&&(e+="/"),(o?"/":"")+e},n.isAbsolute=function(e){return"/"===e.charAt(0)},n.join=function(){var e=Array.prototype.slice.call(arguments,0);return n.normalize(r(e,(function(e,t){if("string"!=typeof e)throw new TypeError("Arguments to path.join must be strings");return e})).join("/"))},n.relative=function(e,t){function r(e){for(var t=0;t<e.length&&""===e[t];t++);for(var n=e.length-1;n>=0&&""===e[n];n--);return t>n?[]:e.slice(t,n-t+1)}e=n.resolve(e).substr(1),t=n.resolve(t).substr(1);for(var i=r(e.split("/")),o=r(t.split("/")),s=Math.min(i.length,o.length),c=s,a=0;a<s;a++)if(i[a]!==o[a]){c=a;break}var l=[];for(a=c;a<i.length;a++)l.push("..");return(l=l.concat(o.slice(c))).join("/")},n.sep="/",n.delimiter=":",n.dirname=function(e){if("string"!=typeof e&&(e+=""),0===e.length)return".";for(var t=e.charCodeAt(0),n=47===t,r=-1,i=!0,o=e.length-1;o>=1;--o)if(47===(t=e.charCodeAt(o))){if(!i){r=o;break}}else i=!1;return-1===r?n?"/":".":n&&1===r?"/":e.slice(0,r)},n.basename=function(e,t){var n=function(e){"string"!=typeof e&&(e+="");var t,n=0,r=-1,i=!0;for(t=e.length-1;t>=0;--t)if(47===e.charCodeAt(t)){if(!i){n=t+1;break}}else-1===r&&(i=!1,r=t+1);return-1===r?"":e.slice(n,r)}(e);return t&&n.substr(-1*t.length)===t&&(n=n.substr(0,n.length-t.length)),n},n.extname=function(e){"string"!=typeof e&&(e+="");for(var t=-1,n=0,r=-1,i=!0,o=0,s=e.length-1;s>=0;--s){var c=e.charCodeAt(s);if(47!==c)-1===r&&(i=!1,r=s+1),46===c?-1===t?t=s:1!==o&&(o=1):-1!==t&&(o=-1);else if(!i){n=s+1;break}}return-1===t||-1===r||0===o||1===o&&t===r-1&&t===n+1?"":e.slice(t,r)};var i="b"==="ab".substr(-1)?function(e,t,n){return e.substr(t,n)}:function(e,t,n){return t<0&&(t=e.length+t),e.substr(t,n)}}).call(this,e("_process"))},{_process:5}],5:[function(e,t,n){var r,i,o=t.exports={};function s(){throw new Error("setTimeout has not been defined")}function c(){throw new Error("clearTimeout has not been defined")}function a(e){if(r===setTimeout)return setTimeout(e,0);if((r===s||!r)&&setTimeout)return r=setTimeout,setTimeout(e,0);try{return r(e,0)}catch(t){try{return r.call(null,e,0)}catch(t){return r.call(this,e,0)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:s}catch(e){r=s}try{i="function"==typeof clearTimeout?clearTimeout:c}catch(e){i=c}}();var l,u=[],p=!1,f=-1;function h(){p&&l&&(p=!1,l.length?u=l.concat(u):f=-1,u.length&&m())}function m(){if(!p){var e=a(h);p=!0;for(var t=u.length;t;){for(l=u,u=[];++f<t;)l&&l[f].run();f=-1,t=u.length}l=null,p=!1,function(e){if(i===clearTimeout)return clearTimeout(e);if((i===c||!i)&&clearTimeout)return i=clearTimeout,clearTimeout(e);try{i(e)}catch(t){try{return i.call(null,e)}catch(t){return i.call(this,e)}}}(e)}}function d(e,t){this.fun=e,this.array=t}function g(){}o.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];u.push(new d(e,t)),1!==u.length||p||a(m)},d.prototype.run=function(){this.fun.apply(null,this.array)},o.title="browser",o.browser=!0,o.env={},o.argv=[],o.version="",o.versions={},o.on=g,o.addListener=g,o.once=g,o.off=g,o.removeListener=g,o.removeAllListeners=g,o.emit=g,o.prependListener=g,o.prependOnceListener=g,o.listeners=function(e){return[]},o.binding=function(e){throw new Error("process.binding is not supported")},o.cwd=function(){return"/"},o.chdir=function(e){throw new Error("process.chdir is not supported")},o.umask=function(){return 0}},{}],6:[function(e,t,n){t.exports={name:"ejs",description:"Embedded JavaScript templates",keywords:["template","engine","ejs"],version:"3.1.6",author:"Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)",license:"Apache-2.0",bin:{ejs:"./bin/cli.js"},main:"./lib/ejs.js",jsdelivr:"ejs.min.js",unpkg:"ejs.min.js",repository:{type:"git",url:"git://github.com/mde/ejs.git"},bugs:"https://github.com/mde/ejs/issues",homepage:"https://github.com/mde/ejs",dependencies:{jake:"^10.6.1"},devDependencies:{browserify:"^16.5.1",eslint:"^6.8.0","git-directory-deploy":"^1.5.1",jsdoc:"^3.6.4","lru-cache":"^4.0.1",mocha:"^7.1.1","uglify-js":"^3.3.16"},engines:{node:">=0.10.0"},scripts:{test:"mocha"}}},{}]},{},[1])(1)}));
\ No newline at end of file
index 3953160..82033b8 100755 (executable)
@@ -1,81 +1 @@
-var fs = require('fs');
-var execSync = require('child_process').execSync;
-var exec = function (cmd) {
-  execSync(cmd, {stdio: 'inherit'});
-};
-
-/* global jake, task, desc, publishTask */
-
-task('build', ['lint', 'clean', 'browserify', 'minify'], function () {
-  console.log('Build completed.');
-});
-
-desc('Cleans browerified/minified files and package files');
-task('clean', ['clobber'], function () {
-  jake.rmRf('./ejs.js');
-  jake.rmRf('./ejs.min.js');
-  console.log('Cleaned up compiled files.');
-});
-
-desc('Lints the source code');
-task('lint', ['clean'], function () {
-  exec('./node_modules/.bin/eslint "**/*.js"');
-  console.log('Linting completed.');
-});
-
-task('browserify', function () {
-  exec('./node_modules/browserify/bin/cmd.js --standalone ejs lib/ejs.js > ejs.js');
-  console.log('Browserification completed.');
-});
-
-task('minify', function () {
-  exec('./node_modules/uglify-js/bin/uglifyjs ejs.js > ejs.min.js');
-  console.log('Minification completed.');
-});
-
-desc('Generates the EJS API docs for the public API');
-task('doc', function () {
-  jake.rmRf('out');
-  exec('./node_modules/.bin/jsdoc --verbose -c jsdoc.json lib/* docs/jsdoc/*');
-  console.log('Documentation generated in ./out.');
-});
-
-desc('Generates the EJS API docs for the public and private API');
-task('devdoc', function () {
-  jake.rmRf('out');
-  exec('./node_modules/.bin/jsdoc --verbose -p -c jsdoc.json lib/* docs/jsdoc/*');
-  console.log('Documentation generated in ./out.');
-});
-
-desc('Publishes the EJS API docs');
-task('docPublish', ['doc'], function () {
-  fs.writeFileSync('out/CNAME', 'api.ejs.co');
-  console.log('Pushing docs to gh-pages...');
-  exec('./node_modules/.bin/git-directory-deploy --directory out/');
-  console.log('Docs published to gh-pages.');
-});
-
-desc('Runs the EJS test suite');
-task('test', ['lint'], function () {
-  exec('./node_modules/.bin/mocha');
-});
-
-publishTask('ejs', ['build'], function () {
-  this.packageFiles.include([
-    'jakefile.js',
-    'README.md',
-    'LICENSE',
-    'package.json',
-    'ejs.js',
-    'ejs.min.js',
-    'lib/**',
-    'bin/**',
-    'usage.txt'
-  ]);
-});
-
-jake.Task.publish.on('complete', function () {
-  console.log('Updating hosted docs...');
-  console.log('If this fails, run jake docPublish to re-try.');
-  jake.Task.docPublish.invoke();
-});
+var fs=require("fs"),execSync=require("child_process").execSync,exec=function(e){execSync(e,{stdio:"inherit"})};task("build",["lint","clean","browserify","minify"],(function(){console.log("Build completed.")})),desc("Cleans browerified/minified files and package files"),task("clean",["clobber"],(function(){jake.rmRf("./ejs.js"),jake.rmRf("./ejs.min.js"),console.log("Cleaned up compiled files.")})),desc("Lints the source code"),task("lint",["clean"],(function(){exec('./node_modules/.bin/eslint "**/*.js"'),console.log("Linting completed.")})),task("browserify",(function(){exec("./node_modules/browserify/bin/cmd.js --standalone ejs lib/ejs.js > ejs.js"),console.log("Browserification completed.")})),task("minify",(function(){exec("./node_modules/uglify-js/bin/uglifyjs ejs.js > ejs.min.js"),console.log("Minification completed.")})),desc("Generates the EJS API docs for the public API"),task("doc",(function(){jake.rmRf("out"),exec("./node_modules/.bin/jsdoc --verbose -c jsdoc.json lib/* docs/jsdoc/*"),console.log("Documentation generated in ./out.")})),desc("Generates the EJS API docs for the public and private API"),task("devdoc",(function(){jake.rmRf("out"),exec("./node_modules/.bin/jsdoc --verbose -p -c jsdoc.json lib/* docs/jsdoc/*"),console.log("Documentation generated in ./out.")})),desc("Publishes the EJS API docs"),task("docPublish",["doc"],(function(){fs.writeFileSync("out/CNAME","api.ejs.co"),console.log("Pushing docs to gh-pages..."),exec("./node_modules/.bin/git-directory-deploy --directory out/"),console.log("Docs published to gh-pages.")})),desc("Runs the EJS test suite"),task("test",["lint"],(function(){exec("./node_modules/.bin/mocha")})),publishTask("ejs",["build"],(function(){this.packageFiles.include(["jakefile.js","README.md","LICENSE","package.json","ejs.js","ejs.min.js","lib/**","bin/**","usage.txt"])})),jake.Task.publish.on("complete",(function(){console.log("Updating hosted docs..."),console.log("If this fails, run jake docPublish to re-try."),jake.Task.docPublish.invoke()}));
\ No newline at end of file
index aa6322e..b4f8e80 100755 (executable)
@@ -1,939 +1,8 @@
-/*
- * EJS Embedded JavaScript templates
- * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-*/
-
-'use strict';
-
+"use strict";
 /**
  * @file Embedded JavaScript templating engine. {@link http://ejs.co}
  * @author Matthew Eernisse <mde@fleegix.org>
  * @author Tiancheng "Timothy" Gu <timothygu99@gmail.com>
  * @project EJS
  * @license {@link http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0}
- */
-
-/**
- * EJS internal functions.
- *
- * Technically this "module" lies in the same file as {@link module:ejs}, for
- * the sake of organization all the private functions re grouped into this
- * module.
- *
- * @module ejs-internal
- * @private
- */
-
-/**
- * Embedded JavaScript templating engine.
- *
- * @module ejs
- * @public
- */
-
-var fs = require('fs');
-var path = require('path');
-var utils = require('./utils');
-
-var scopeOptionWarned = false;
-/** @type {string} */
-var _VERSION_STRING = require('../package.json').version;
-var _DEFAULT_OPEN_DELIMITER = '<';
-var _DEFAULT_CLOSE_DELIMITER = '>';
-var _DEFAULT_DELIMITER = '%';
-var _DEFAULT_LOCALS_NAME = 'locals';
-var _NAME = 'ejs';
-var _REGEX_STRING = '(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)';
-var _OPTS_PASSABLE_WITH_DATA = ['delimiter', 'scope', 'context', 'debug', 'compileDebug',
-  'client', '_with', 'rmWhitespace', 'strict', 'filename', 'async'];
-// We don't allow 'cache' option to be passed in the data obj for
-// the normal `render` call, but this is where Express 2 & 3 put it
-// so we make an exception for `renderFile`
-var _OPTS_PASSABLE_WITH_DATA_EXPRESS = _OPTS_PASSABLE_WITH_DATA.concat('cache');
-var _BOM = /^\uFEFF/;
-
-/**
- * EJS template function cache. This can be a LRU object from lru-cache NPM
- * module. By default, it is {@link module:utils.cache}, a simple in-process
- * cache that grows continuously.
- *
- * @type {Cache}
- */
-
-exports.cache = utils.cache;
-
-/**
- * Custom file loader. Useful for template preprocessing or restricting access
- * to a certain part of the filesystem.
- *
- * @type {fileLoader}
- */
-
-exports.fileLoader = fs.readFileSync;
-
-/**
- * Name of the object containing the locals.
- *
- * This variable is overridden by {@link Options}`.localsName` if it is not
- * `undefined`.
- *
- * @type {String}
- * @public
- */
-
-exports.localsName = _DEFAULT_LOCALS_NAME;
-
-/**
- * Promise implementation -- defaults to the native implementation if available
- * This is mostly just for testability
- *
- * @type {PromiseConstructorLike}
- * @public
- */
-
-exports.promiseImpl = (new Function('return this;'))().Promise;
-
-/**
- * Get the path to the included file from the parent file path and the
- * specified path.
- *
- * @param {String}  name     specified path
- * @param {String}  filename parent file path
- * @param {Boolean} [isDir=false] whether the parent file path is a directory
- * @return {String}
- */
-exports.resolveInclude = function(name, filename, isDir) {
-  var dirname = path.dirname;
-  var extname = path.extname;
-  var resolve = path.resolve;
-  var includePath = resolve(isDir ? filename : dirname(filename), name);
-  var ext = extname(name);
-  if (!ext) {
-    includePath += '.ejs';
-  }
-  return includePath;
-};
-
-/**
- * Try to resolve file path on multiple directories
- *
- * @param  {String}        name  specified path
- * @param  {Array<String>} paths list of possible parent directory paths
- * @return {String}
- */
-function resolvePaths(name, paths) {
-  var filePath;
-  if (paths.some(function (v) {
-    filePath = exports.resolveInclude(name, v, true);
-    return fs.existsSync(filePath);
-  })) {
-    return filePath;
-  }
-}
-
-/**
- * Get the path to the included file by Options
- *
- * @param  {String}  path    specified path
- * @param  {Options} options compilation options
- * @return {String}
- */
-function getIncludePath(path, options) {
-  var includePath;
-  var filePath;
-  var views = options.views;
-  var match = /^[A-Za-z]+:\\|^\//.exec(path);
-
-  // Abs path
-  if (match && match.length) {
-    path = path.replace(/^\/*/, '');
-    if (Array.isArray(options.root)) {
-      includePath = resolvePaths(path, options.root);
-    } else {
-      includePath = exports.resolveInclude(path, options.root || '/', true);
-    }
-  }
-  // Relative paths
-  else {
-    // Look relative to a passed filename first
-    if (options.filename) {
-      filePath = exports.resolveInclude(path, options.filename);
-      if (fs.existsSync(filePath)) {
-        includePath = filePath;
-      }
-    }
-    // Then look in any views directories
-    if (!includePath && Array.isArray(views)) {
-      includePath = resolvePaths(path, views);
-    }
-    if (!includePath && typeof options.includer !== 'function') {
-      throw new Error('Could not find the include file "' +
-          options.escapeFunction(path) + '"');
-    }
-  }
-  return includePath;
-}
-
-/**
- * Get the template from a string or a file, either compiled on-the-fly or
- * read from cache (if enabled), and cache the template if needed.
- *
- * If `template` is not set, the file specified in `options.filename` will be
- * read.
- *
- * If `options.cache` is true, this function reads the file from
- * `options.filename` so it must be set prior to calling this function.
- *
- * @memberof module:ejs-internal
- * @param {Options} options   compilation options
- * @param {String} [template] template source
- * @return {(TemplateFunction|ClientFunction)}
- * Depending on the value of `options.client`, either type might be returned.
- * @static
- */
-
-function handleCache(options, template) {
-  var func;
-  var filename = options.filename;
-  var hasTemplate = arguments.length > 1;
-
-  if (options.cache) {
-    if (!filename) {
-      throw new Error('cache option requires a filename');
-    }
-    func = exports.cache.get(filename);
-    if (func) {
-      return func;
-    }
-    if (!hasTemplate) {
-      template = fileLoader(filename).toString().replace(_BOM, '');
-    }
-  }
-  else if (!hasTemplate) {
-    // istanbul ignore if: should not happen at all
-    if (!filename) {
-      throw new Error('Internal EJS error: no file name or template '
-                    + 'provided');
-    }
-    template = fileLoader(filename).toString().replace(_BOM, '');
-  }
-  func = exports.compile(template, options);
-  if (options.cache) {
-    exports.cache.set(filename, func);
-  }
-  return func;
-}
-
-/**
- * Try calling handleCache with the given options and data and call the
- * callback with the result. If an error occurs, call the callback with
- * the error. Used by renderFile().
- *
- * @memberof module:ejs-internal
- * @param {Options} options    compilation options
- * @param {Object} data        template data
- * @param {RenderFileCallback} cb callback
- * @static
- */
-
-function tryHandleCache(options, data, cb) {
-  var result;
-  if (!cb) {
-    if (typeof exports.promiseImpl == 'function') {
-      return new exports.promiseImpl(function (resolve, reject) {
-        try {
-          result = handleCache(options)(data);
-          resolve(result);
-        }
-        catch (err) {
-          reject(err);
-        }
-      });
-    }
-    else {
-      throw new Error('Please provide a callback function');
-    }
-  }
-  else {
-    try {
-      result = handleCache(options)(data);
-    }
-    catch (err) {
-      return cb(err);
-    }
-
-    cb(null, result);
-  }
-}
-
-/**
- * fileLoader is independent
- *
- * @param {String} filePath ejs file path.
- * @return {String} The contents of the specified file.
- * @static
- */
-
-function fileLoader(filePath){
-  return exports.fileLoader(filePath);
-}
-
-/**
- * Get the template function.
- *
- * If `options.cache` is `true`, then the template is cached.
- *
- * @memberof module:ejs-internal
- * @param {String}  path    path for the specified file
- * @param {Options} options compilation options
- * @return {(TemplateFunction|ClientFunction)}
- * Depending on the value of `options.client`, either type might be returned
- * @static
- */
-
-function includeFile(path, options) {
-  var opts = utils.shallowCopy({}, options);
-  opts.filename = getIncludePath(path, opts);
-  if (typeof options.includer === 'function') {
-    var includerResult = options.includer(path, opts.filename);
-    if (includerResult) {
-      if (includerResult.filename) {
-        opts.filename = includerResult.filename;
-      }
-      if (includerResult.template) {
-        return handleCache(opts, includerResult.template);
-      }
-    }
-  }
-  return handleCache(opts);
-}
-
-/**
- * Re-throw the given `err` in context to the `str` of ejs, `filename`, and
- * `lineno`.
- *
- * @implements {RethrowCallback}
- * @memberof module:ejs-internal
- * @param {Error}  err      Error object
- * @param {String} str      EJS source
- * @param {String} flnm     file name of the EJS file
- * @param {Number} lineno   line number of the error
- * @param {EscapeCallback} esc
- * @static
- */
-
-function rethrow(err, str, flnm, lineno, esc) {
-  var lines = str.split('\n');
-  var start = Math.max(lineno - 3, 0);
-  var end = Math.min(lines.length, lineno + 3);
-  var filename = esc(flnm);
-  // Error context
-  var context = lines.slice(start, end).map(function (line, i){
-    var curr = i + start + 1;
-    return (curr == lineno ? ' >> ' : '    ')
-      + curr
-      + '| '
-      + line;
-  }).join('\n');
-
-  // Alter exception message
-  err.path = filename;
-  err.message = (filename || 'ejs') + ':'
-    + lineno + '\n'
-    + context + '\n\n'
-    + err.message;
-
-  throw err;
-}
-
-function stripSemi(str){
-  return str.replace(/;(\s*$)/, '$1');
-}
-
-/**
- * Compile the given `str` of ejs into a template function.
- *
- * @param {String}  template EJS template
- *
- * @param {Options} [opts] compilation options
- *
- * @return {(TemplateFunction|ClientFunction)}
- * Depending on the value of `opts.client`, either type might be returned.
- * Note that the return type of the function also depends on the value of `opts.async`.
- * @public
- */
-
-exports.compile = function compile(template, opts) {
-  var templ;
-
-  // v1 compat
-  // 'scope' is 'context'
-  // FIXME: Remove this in a future version
-  if (opts && opts.scope) {
-    if (!scopeOptionWarned){
-      console.warn('`scope` option is deprecated and will be removed in EJS 3');
-      scopeOptionWarned = true;
-    }
-    if (!opts.context) {
-      opts.context = opts.scope;
-    }
-    delete opts.scope;
-  }
-  templ = new Template(template, opts);
-  return templ.compile();
-};
-
-/**
- * Render the given `template` of ejs.
- *
- * If you would like to include options but not data, you need to explicitly
- * call this function with `data` being an empty object or `null`.
- *
- * @param {String}   template EJS template
- * @param {Object}  [data={}] template data
- * @param {Options} [opts={}] compilation and rendering options
- * @return {(String|Promise<String>)}
- * Return value type depends on `opts.async`.
- * @public
- */
-
-exports.render = function (template, d, o) {
-  var data = d || {};
-  var opts = o || {};
-
-  // No options object -- if there are optiony names
-  // in the data, copy them to options
-  if (arguments.length == 2) {
-    utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA);
-  }
-
-  return handleCache(opts, template)(data);
-};
-
-/**
- * Render an EJS file at the given `path` and callback `cb(err, str)`.
- *
- * If you would like to include options but not data, you need to explicitly
- * call this function with `data` being an empty object or `null`.
- *
- * @param {String}             path     path to the EJS file
- * @param {Object}            [data={}] template data
- * @param {Options}           [opts={}] compilation and rendering options
- * @param {RenderFileCallback} cb callback
- * @public
- */
-
-exports.renderFile = function () {
-  var args = Array.prototype.slice.call(arguments);
-  var filename = args.shift();
-  var cb;
-  var opts = {filename: filename};
-  var data;
-  var viewOpts;
-
-  // Do we have a callback?
-  if (typeof arguments[arguments.length - 1] == 'function') {
-    cb = args.pop();
-  }
-  // Do we have data/opts?
-  if (args.length) {
-    // Should always have data obj
-    data = args.shift();
-    // Normal passed opts (data obj + opts obj)
-    if (args.length) {
-      // Use shallowCopy so we don't pollute passed in opts obj with new vals
-      utils.shallowCopy(opts, args.pop());
-    }
-    // Special casing for Express (settings + opts-in-data)
-    else {
-      // Express 3 and 4
-      if (data.settings) {
-        // Pull a few things from known locations
-        if (data.settings.views) {
-          opts.views = data.settings.views;
-        }
-        if (data.settings['view cache']) {
-          opts.cache = true;
-        }
-        // Undocumented after Express 2, but still usable, esp. for
-        // items that are unsafe to be passed along with data, like `root`
-        viewOpts = data.settings['view options'];
-        if (viewOpts) {
-          utils.shallowCopy(opts, viewOpts);
-        }
-      }
-      // Express 2 and lower, values set in app.locals, or people who just
-      // want to pass options in their data. NOTE: These values will override
-      // anything previously set in settings  or settings['view options']
-      utils.shallowCopyFromList(opts, data, _OPTS_PASSABLE_WITH_DATA_EXPRESS);
-    }
-    opts.filename = filename;
-  }
-  else {
-    data = {};
-  }
-
-  return tryHandleCache(opts, data, cb);
-};
-
-/**
- * Clear intermediate JavaScript cache. Calls {@link Cache#reset}.
- * @public
- */
-
-/**
- * EJS template class
- * @public
- */
-exports.Template = Template;
-
-exports.clearCache = function () {
-  exports.cache.reset();
-};
-
-function Template(text, opts) {
-  opts = opts || {};
-  var options = {};
-  this.templateText = text;
-  /** @type {string | null} */
-  this.mode = null;
-  this.truncate = false;
-  this.currentLine = 1;
-  this.source = '';
-  options.client = opts.client || false;
-  options.escapeFunction = opts.escape || opts.escapeFunction || utils.escapeXML;
-  options.compileDebug = opts.compileDebug !== false;
-  options.debug = !!opts.debug;
-  options.filename = opts.filename;
-  options.openDelimiter = opts.openDelimiter || exports.openDelimiter || _DEFAULT_OPEN_DELIMITER;
-  options.closeDelimiter = opts.closeDelimiter || exports.closeDelimiter || _DEFAULT_CLOSE_DELIMITER;
-  options.delimiter = opts.delimiter || exports.delimiter || _DEFAULT_DELIMITER;
-  options.strict = opts.strict || false;
-  options.context = opts.context;
-  options.cache = opts.cache || false;
-  options.rmWhitespace = opts.rmWhitespace;
-  options.root = opts.root;
-  options.includer = opts.includer;
-  options.outputFunctionName = opts.outputFunctionName;
-  options.localsName = opts.localsName || exports.localsName || _DEFAULT_LOCALS_NAME;
-  options.views = opts.views;
-  options.async = opts.async;
-  options.destructuredLocals = opts.destructuredLocals;
-  options.legacyInclude = typeof opts.legacyInclude != 'undefined' ? !!opts.legacyInclude : true;
-
-  if (options.strict) {
-    options._with = false;
-  }
-  else {
-    options._with = typeof opts._with != 'undefined' ? opts._with : true;
-  }
-
-  this.opts = options;
-
-  this.regex = this.createRegex();
-}
-
-Template.modes = {
-  EVAL: 'eval',
-  ESCAPED: 'escaped',
-  RAW: 'raw',
-  COMMENT: 'comment',
-  LITERAL: 'literal'
-};
-
-Template.prototype = {
-  createRegex: function () {
-    var str = _REGEX_STRING;
-    var delim = utils.escapeRegExpChars(this.opts.delimiter);
-    var open = utils.escapeRegExpChars(this.opts.openDelimiter);
-    var close = utils.escapeRegExpChars(this.opts.closeDelimiter);
-    str = str.replace(/%/g, delim)
-      .replace(/</g, open)
-      .replace(/>/g, close);
-    return new RegExp(str);
-  },
-
-  compile: function () {
-    /** @type {string} */
-    var src;
-    /** @type {ClientFunction} */
-    var fn;
-    var opts = this.opts;
-    var prepended = '';
-    var appended = '';
-    /** @type {EscapeCallback} */
-    var escapeFn = opts.escapeFunction;
-    /** @type {FunctionConstructor} */
-    var ctor;
-    /** @type {string} */
-    var sanitizedFilename = opts.filename ? JSON.stringify(opts.filename) : 'undefined';
-
-    if (!this.source) {
-      this.generateSource();
-      prepended +=
-        '  var __output = "";\n' +
-        '  function __append(s) { if (s !== undefined && s !== null) __output += s }\n';
-      if (opts.outputFunctionName) {
-        prepended += '  var ' + opts.outputFunctionName + ' = __append;' + '\n';
-      }
-      if (opts.destructuredLocals && opts.destructuredLocals.length) {
-        var destructuring = '  var __locals = (' + opts.localsName + ' || {}),\n';
-        for (var i = 0; i < opts.destructuredLocals.length; i++) {
-          var name = opts.destructuredLocals[i];
-          if (i > 0) {
-            destructuring += ',\n  ';
-          }
-          destructuring += name + ' = __locals.' + name;
-        }
-        prepended += destructuring + ';\n';
-      }
-      if (opts._with !== false) {
-        prepended +=  '  with (' + opts.localsName + ' || {}) {' + '\n';
-        appended += '  }' + '\n';
-      }
-      appended += '  return __output;' + '\n';
-      this.source = prepended + this.source + appended;
-    }
-
-    if (opts.compileDebug) {
-      src = 'var __line = 1' + '\n'
-        + '  , __lines = ' + JSON.stringify(this.templateText) + '\n'
-        + '  , __filename = ' + sanitizedFilename + ';' + '\n'
-        + 'try {' + '\n'
-        + this.source
-        + '} catch (e) {' + '\n'
-        + '  rethrow(e, __lines, __filename, __line, escapeFn);' + '\n'
-        + '}' + '\n';
-    }
-    else {
-      src = this.source;
-    }
-
-    if (opts.client) {
-      src = 'escapeFn = escapeFn || ' + escapeFn.toString() + ';' + '\n' + src;
-      if (opts.compileDebug) {
-        src = 'rethrow = rethrow || ' + rethrow.toString() + ';' + '\n' + src;
-      }
-    }
-
-    if (opts.strict) {
-      src = '"use strict";\n' + src;
-    }
-    if (opts.debug) {
-      console.log(src);
-    }
-    if (opts.compileDebug && opts.filename) {
-      src = src + '\n'
-        + '//# sourceURL=' + sanitizedFilename + '\n';
-    }
-
-    try {
-      if (opts.async) {
-        // Have to use generated function for this, since in envs without support,
-        // it breaks in parsing
-        try {
-          ctor = (new Function('return (async function(){}).constructor;'))();
-        }
-        catch(e) {
-          if (e instanceof SyntaxError) {
-            throw new Error('This environment does not support async/await');
-          }
-          else {
-            throw e;
-          }
-        }
-      }
-      else {
-        ctor = Function;
-      }
-      fn = new ctor(opts.localsName + ', escapeFn, include, rethrow', src);
-    }
-    catch(e) {
-      // istanbul ignore else
-      if (e instanceof SyntaxError) {
-        if (opts.filename) {
-          e.message += ' in ' + opts.filename;
-        }
-        e.message += ' while compiling ejs\n\n';
-        e.message += 'If the above error is not helpful, you may want to try EJS-Lint:\n';
-        e.message += 'https://github.com/RyanZim/EJS-Lint';
-        if (!opts.async) {
-          e.message += '\n';
-          e.message += 'Or, if you meant to create an async function, pass `async: true` as an option.';
-        }
-      }
-      throw e;
-    }
-
-    // Return a callable function which will execute the function
-    // created by the source-code, with the passed data as locals
-    // Adds a local `include` function which allows full recursive include
-    var returnedFn = opts.client ? fn : function anonymous(data) {
-      var include = function (path, includeData) {
-        var d = utils.shallowCopy({}, data);
-        if (includeData) {
-          d = utils.shallowCopy(d, includeData);
-        }
-        return includeFile(path, opts)(d);
-      };
-      return fn.apply(opts.context, [data || {}, escapeFn, include, rethrow]);
-    };
-    if (opts.filename && typeof Object.defineProperty === 'function') {
-      var filename = opts.filename;
-      var basename = path.basename(filename, path.extname(filename));
-      try {
-        Object.defineProperty(returnedFn, 'name', {
-          value: basename,
-          writable: false,
-          enumerable: false,
-          configurable: true
-        });
-      } catch (e) {/* ignore */}
-    }
-    return returnedFn;
-  },
-
-  generateSource: function () {
-    var opts = this.opts;
-
-    if (opts.rmWhitespace) {
-      // Have to use two separate replace here as `^` and `$` operators don't
-      // work well with `\r` and empty lines don't work well with the `m` flag.
-      this.templateText =
-        this.templateText.replace(/[\r\n]+/g, '\n').replace(/^\s+|\s+$/gm, '');
-    }
-
-    // Slurp spaces and tabs before <%_ and after _%>
-    this.templateText =
-      this.templateText.replace(/[ \t]*<%_/gm, '<%_').replace(/_%>[ \t]*/gm, '_%>');
-
-    var self = this;
-    var matches = this.parseTemplateText();
-    var d = this.opts.delimiter;
-    var o = this.opts.openDelimiter;
-    var c = this.opts.closeDelimiter;
-
-    if (matches && matches.length) {
-      matches.forEach(function (line, index) {
-        var closing;
-        // If this is an opening tag, check for closing tags
-        // FIXME: May end up with some false positives here
-        // Better to store modes as k/v with openDelimiter + delimiter as key
-        // Then this can simply check against the map
-        if ( line.indexOf(o + d) === 0        // If it is a tag
-          && line.indexOf(o + d + d) !== 0) { // and is not escaped
-          closing = matches[index + 2];
-          if (!(closing == d + c || closing == '-' + d + c || closing == '_' + d + c)) {
-            throw new Error('Could not find matching close tag for "' + line + '".');
-          }
-        }
-        self.scanLine(line);
-      });
-    }
-
-  },
-
-  parseTemplateText: function () {
-    var str = this.templateText;
-    var pat = this.regex;
-    var result = pat.exec(str);
-    var arr = [];
-    var firstPos;
-
-    while (result) {
-      firstPos = result.index;
-
-      if (firstPos !== 0) {
-        arr.push(str.substring(0, firstPos));
-        str = str.slice(firstPos);
-      }
-
-      arr.push(result[0]);
-      str = str.slice(result[0].length);
-      result = pat.exec(str);
-    }
-
-    if (str) {
-      arr.push(str);
-    }
-
-    return arr;
-  },
-
-  _addOutput: function (line) {
-    if (this.truncate) {
-      // Only replace single leading linebreak in the line after
-      // -%> tag -- this is the single, trailing linebreak
-      // after the tag that the truncation mode replaces
-      // Handle Win / Unix / old Mac linebreaks -- do the \r\n
-      // combo first in the regex-or
-      line = line.replace(/^(?:\r\n|\r|\n)/, '');
-      this.truncate = false;
-    }
-    if (!line) {
-      return line;
-    }
-
-    // Preserve literal slashes
-    line = line.replace(/\\/g, '\\\\');
-
-    // Convert linebreaks
-    line = line.replace(/\n/g, '\\n');
-    line = line.replace(/\r/g, '\\r');
-
-    // Escape double-quotes
-    // - this will be the delimiter during execution
-    line = line.replace(/"/g, '\\"');
-    this.source += '    ; __append("' + line + '")' + '\n';
-  },
-
-  scanLine: function (line) {
-    var self = this;
-    var d = this.opts.delimiter;
-    var o = this.opts.openDelimiter;
-    var c = this.opts.closeDelimiter;
-    var newLineCount = 0;
-
-    newLineCount = (line.split('\n').length - 1);
-
-    switch (line) {
-    case o + d:
-    case o + d + '_':
-      this.mode = Template.modes.EVAL;
-      break;
-    case o + d + '=':
-      this.mode = Template.modes.ESCAPED;
-      break;
-    case o + d + '-':
-      this.mode = Template.modes.RAW;
-      break;
-    case o + d + '#':
-      this.mode = Template.modes.COMMENT;
-      break;
-    case o + d + d:
-      this.mode = Template.modes.LITERAL;
-      this.source += '    ; __append("' + line.replace(o + d + d, o + d) + '")' + '\n';
-      break;
-    case d + d + c:
-      this.mode = Template.modes.LITERAL;
-      this.source += '    ; __append("' + line.replace(d + d + c, d + c) + '")' + '\n';
-      break;
-    case d + c:
-    case '-' + d + c:
-    case '_' + d + c:
-      if (this.mode == Template.modes.LITERAL) {
-        this._addOutput(line);
-      }
-
-      this.mode = null;
-      this.truncate = line.indexOf('-') === 0 || line.indexOf('_') === 0;
-      break;
-    default:
-      // In script mode, depends on type of tag
-      if (this.mode) {
-        // If '//' is found without a line break, add a line break.
-        switch (this.mode) {
-        case Template.modes.EVAL:
-        case Template.modes.ESCAPED:
-        case Template.modes.RAW:
-          if (line.lastIndexOf('//') > line.lastIndexOf('\n')) {
-            line += '\n';
-          }
-        }
-        switch (this.mode) {
-        // Just executing code
-        case Template.modes.EVAL:
-          this.source += '    ; ' + line + '\n';
-          break;
-          // Exec, esc, and output
-        case Template.modes.ESCAPED:
-          this.source += '    ; __append(escapeFn(' + stripSemi(line) + '))' + '\n';
-          break;
-          // Exec and output
-        case Template.modes.RAW:
-          this.source += '    ; __append(' + stripSemi(line) + ')' + '\n';
-          break;
-        case Template.modes.COMMENT:
-          // Do nothing
-          break;
-          // Literal <%% mode, append as raw output
-        case Template.modes.LITERAL:
-          this._addOutput(line);
-          break;
-        }
-      }
-      // In string mode, just add the output
-      else {
-        this._addOutput(line);
-      }
-    }
-
-    if (self.opts.compileDebug && newLineCount) {
-      this.currentLine += newLineCount;
-      this.source += '    ; __line = ' + this.currentLine + '\n';
-    }
-  }
-};
-
-/**
- * Escape characters reserved in XML.
- *
- * This is simply an export of {@link module:utils.escapeXML}.
- *
- * If `markup` is `undefined` or `null`, the empty string is returned.
- *
- * @param {String} markup Input string
- * @return {String} Escaped string
- * @public
- * @func
- * */
-exports.escapeXML = utils.escapeXML;
-
-/**
- * Express.js support.
- *
- * This is an alias for {@link module:ejs.renderFile}, in order to support
- * Express.js out-of-the-box.
- *
- * @func
- */
-
-exports.__express = exports.renderFile;
-
-/**
- * Version of EJS.
- *
- * @readonly
- * @type {String}
- * @public
- */
-
-exports.VERSION = _VERSION_STRING;
-
-/**
- * Name for detection of EJS.
- *
- * @readonly
- * @type {String}
- * @public
- */
-
-exports.name = _NAME;
-
-/* istanbul ignore if */
-if (typeof window != 'undefined') {
-  window.ejs = exports;
-}
+ */var fs=require("fs"),path=require("path"),utils=require("./utils"),scopeOptionWarned=!1,_VERSION_STRING=require("../package.json").version,_DEFAULT_OPEN_DELIMITER="<",_DEFAULT_CLOSE_DELIMITER=">",_DEFAULT_DELIMITER="%",_DEFAULT_LOCALS_NAME="locals",_NAME="ejs",_REGEX_STRING="(<%%|%%>|<%=|<%-|<%_|<%#|<%|%>|-%>|_%>)",_OPTS_PASSABLE_WITH_DATA=["delimiter","scope","context","debug","compileDebug","client","_with","rmWhitespace","strict","filename","async"],_OPTS_PASSABLE_WITH_DATA_EXPRESS=_OPTS_PASSABLE_WITH_DATA.concat("cache"),_BOM=/^\uFEFF/;function resolvePaths(e,t){var n;if(t.some((function(t){return n=exports.resolveInclude(e,t,!0),fs.existsSync(n)})))return n}function getIncludePath(e,t){var n,r,s=t.views,i=/^[A-Za-z]+:\\|^\//.exec(e);if(i&&i.length)e=e.replace(/^\/*/,""),n=Array.isArray(t.root)?resolvePaths(e,t.root):exports.resolveInclude(e,t.root||"/",!0);else if(t.filename&&(r=exports.resolveInclude(e,t.filename),fs.existsSync(r)&&(n=r)),!n&&Array.isArray(s)&&(n=resolvePaths(e,s)),!n&&"function"!=typeof t.includer)throw new Error('Could not find the include file "'+t.escapeFunction(e)+'"');return n}function handleCache(e,t){var n,r=e.filename,s=arguments.length>1;if(e.cache){if(!r)throw new Error("cache option requires a filename");if(n=exports.cache.get(r))return n;s||(t=fileLoader(r).toString().replace(_BOM,""))}else if(!s){if(!r)throw new Error("Internal EJS error: no file name or template provided");t=fileLoader(r).toString().replace(_BOM,"")}return n=exports.compile(t,e),e.cache&&exports.cache.set(r,n),n}function tryHandleCache(e,t,n){var r;if(!n){if("function"==typeof exports.promiseImpl)return new exports.promiseImpl((function(n,s){try{n(r=handleCache(e)(t))}catch(e){s(e)}}));throw new Error("Please provide a callback function")}try{r=handleCache(e)(t)}catch(e){return n(e)}n(null,r)}function fileLoader(e){return exports.fileLoader(e)}function includeFile(e,t){var n=utils.shallowCopy({},t);if(n.filename=getIncludePath(e,n),"function"==typeof t.includer){var r=t.includer(e,n.filename);if(r&&(r.filename&&(n.filename=r.filename),r.template))return handleCache(n,r.template)}return handleCache(n)}function rethrow(e,t,n,r,s){var i=t.split("\n"),a=Math.max(r-3,0),o=Math.min(i.length,r+3),c=s(n),l=i.slice(a,o).map((function(e,t){var n=t+a+1;return(n==r?" >> ":"    ")+n+"| "+e})).join("\n");throw e.path=c,e.message=(c||"ejs")+":"+r+"\n"+l+"\n\n"+e.message,e}function stripSemi(e){return e.replace(/;(\s*$)/,"$1")}function Template(e,t){t=t||{};var n={};this.templateText=e,this.mode=null,this.truncate=!1,this.currentLine=1,this.source="",n.client=t.client||!1,n.escapeFunction=t.escape||t.escapeFunction||utils.escapeXML,n.compileDebug=!1!==t.compileDebug,n.debug=!!t.debug,n.filename=t.filename,n.openDelimiter=t.openDelimiter||exports.openDelimiter||_DEFAULT_OPEN_DELIMITER,n.closeDelimiter=t.closeDelimiter||exports.closeDelimiter||_DEFAULT_CLOSE_DELIMITER,n.delimiter=t.delimiter||exports.delimiter||_DEFAULT_DELIMITER,n.strict=t.strict||!1,n.context=t.context,n.cache=t.cache||!1,n.rmWhitespace=t.rmWhitespace,n.root=t.root,n.includer=t.includer,n.outputFunctionName=t.outputFunctionName,n.localsName=t.localsName||exports.localsName||_DEFAULT_LOCALS_NAME,n.views=t.views,n.async=t.async,n.destructuredLocals=t.destructuredLocals,n.legacyInclude=void 0===t.legacyInclude||!!t.legacyInclude,n.strict?n._with=!1:n._with=void 0===t._with||t._with,this.opts=n,this.regex=this.createRegex()}exports.cache=utils.cache,exports.fileLoader=fs.readFileSync,exports.localsName=_DEFAULT_LOCALS_NAME,exports.promiseImpl=new Function("return this;")().Promise,exports.resolveInclude=function(e,t,n){var r=path.dirname,s=path.extname,i=(0,path.resolve)(n?t:r(t),e);return s(e)||(i+=".ejs"),i},exports.compile=function(e,t){return t&&t.scope&&(scopeOptionWarned||(console.warn("`scope` option is deprecated and will be removed in EJS 3"),scopeOptionWarned=!0),t.context||(t.context=t.scope),delete t.scope),new Template(e,t).compile()},exports.render=function(e,t,n){var r=t||{},s=n||{};return 2==arguments.length&&utils.shallowCopyFromList(s,r,_OPTS_PASSABLE_WITH_DATA),handleCache(s,e)(r)},exports.renderFile=function(){var e,t,n,r=Array.prototype.slice.call(arguments),s=r.shift(),i={filename:s};return"function"==typeof arguments[arguments.length-1]&&(e=r.pop()),r.length?(t=r.shift(),r.length?utils.shallowCopy(i,r.pop()):(t.settings&&(t.settings.views&&(i.views=t.settings.views),t.settings["view cache"]&&(i.cache=!0),(n=t.settings["view options"])&&utils.shallowCopy(i,n)),utils.shallowCopyFromList(i,t,_OPTS_PASSABLE_WITH_DATA_EXPRESS)),i.filename=s):t={},tryHandleCache(i,t,e)},exports.Template=Template,exports.clearCache=function(){exports.cache.reset()},Template.modes={EVAL:"eval",ESCAPED:"escaped",RAW:"raw",COMMENT:"comment",LITERAL:"literal"},Template.prototype={createRegex:function(){var e=_REGEX_STRING,t=utils.escapeRegExpChars(this.opts.delimiter),n=utils.escapeRegExpChars(this.opts.openDelimiter),r=utils.escapeRegExpChars(this.opts.closeDelimiter);return e=e.replace(/%/g,t).replace(/</g,n).replace(/>/g,r),new RegExp(e)},compile:function(){var e,t,n,r=this.opts,s="",i="",a=r.escapeFunction,o=r.filename?JSON.stringify(r.filename):"undefined";if(!this.source){if(this.generateSource(),s+='  var __output = "";\n  function __append(s) { if (s !== undefined && s !== null) __output += s }\n',r.outputFunctionName&&(s+="  var "+r.outputFunctionName+" = __append;\n"),r.destructuredLocals&&r.destructuredLocals.length){for(var c="  var __locals = ("+r.localsName+" || {}),\n",l=0;l<r.destructuredLocals.length;l++){var p=r.destructuredLocals[l];l>0&&(c+=",\n  "),c+=p+" = __locals."+p}s+=c+";\n"}!1!==r._with&&(s+="  with ("+r.localsName+" || {}) {\n",i+="  }\n"),i+="  return __output;\n",this.source=s+this.source+i}e=r.compileDebug?"var __line = 1\n  , __lines = "+JSON.stringify(this.templateText)+"\n  , __filename = "+o+";\ntry {\n"+this.source+"} catch (e) {\n  rethrow(e, __lines, __filename, __line, escapeFn);\n}\n":this.source,r.client&&(e="escapeFn = escapeFn || "+a.toString()+";\n"+e,r.compileDebug&&(e="rethrow = rethrow || "+rethrow.toString()+";\n"+e)),r.strict&&(e='"use strict";\n'+e),r.debug&&console.log(e),r.compileDebug&&r.filename&&(e=e+"\n//# sourceURL="+o+"\n");try{if(r.async)try{n=new Function("return (async function(){}).constructor;")()}catch(e){throw e instanceof SyntaxError?new Error("This environment does not support async/await"):e}else n=Function;t=new n(r.localsName+", escapeFn, include, rethrow",e)}catch(e){throw e instanceof SyntaxError&&(r.filename&&(e.message+=" in "+r.filename),e.message+=" while compiling ejs\n\n",e.message+="If the above error is not helpful, you may want to try EJS-Lint:\n",e.message+="https://github.com/RyanZim/EJS-Lint",r.async||(e.message+="\n",e.message+="Or, if you meant to create an async function, pass `async: true` as an option.")),e}var u=r.client?t:function(e){return t.apply(r.context,[e||{},a,function(t,n){var s=utils.shallowCopy({},e);return n&&(s=utils.shallowCopy(s,n)),includeFile(t,r)(s)},rethrow])};if(r.filename&&"function"==typeof Object.defineProperty){var h=r.filename,m=path.basename(h,path.extname(h));try{Object.defineProperty(u,"name",{value:m,writable:!1,enumerable:!1,configurable:!0})}catch(e){}}return u},generateSource:function(){this.opts.rmWhitespace&&(this.templateText=this.templateText.replace(/[\r\n]+/g,"\n").replace(/^\s+|\s+$/gm,"")),this.templateText=this.templateText.replace(/[ \t]*<%_/gm,"<%_").replace(/_%>[ \t]*/gm,"_%>");var e=this,t=this.parseTemplateText(),n=this.opts.delimiter,r=this.opts.openDelimiter,s=this.opts.closeDelimiter;t&&t.length&&t.forEach((function(i,a){var o;if(0===i.indexOf(r+n)&&0!==i.indexOf(r+n+n)&&(o=t[a+2])!=n+s&&o!="-"+n+s&&o!="_"+n+s)throw new Error('Could not find matching close tag for "'+i+'".');e.scanLine(i)}))},parseTemplateText:function(){for(var e,t=this.templateText,n=this.regex,r=n.exec(t),s=[];r;)0!==(e=r.index)&&(s.push(t.substring(0,e)),t=t.slice(e)),s.push(r[0]),t=t.slice(r[0].length),r=n.exec(t);return t&&s.push(t),s},_addOutput:function(e){if(this.truncate&&(e=e.replace(/^(?:\r\n|\r|\n)/,""),this.truncate=!1),!e)return e;e=(e=(e=(e=e.replace(/\\/g,"\\\\")).replace(/\n/g,"\\n")).replace(/\r/g,"\\r")).replace(/"/g,'\\"'),this.source+='    ; __append("'+e+'")\n'},scanLine:function(e){var t,n=this.opts.delimiter,r=this.opts.openDelimiter,s=this.opts.closeDelimiter;switch(t=e.split("\n").length-1,e){case r+n:case r+n+"_":this.mode=Template.modes.EVAL;break;case r+n+"=":this.mode=Template.modes.ESCAPED;break;case r+n+"-":this.mode=Template.modes.RAW;break;case r+n+"#":this.mode=Template.modes.COMMENT;break;case r+n+n:this.mode=Template.modes.LITERAL,this.source+='    ; __append("'+e.replace(r+n+n,r+n)+'")\n';break;case n+n+s:this.mode=Template.modes.LITERAL,this.source+='    ; __append("'+e.replace(n+n+s,n+s)+'")\n';break;case n+s:case"-"+n+s:case"_"+n+s:this.mode==Template.modes.LITERAL&&this._addOutput(e),this.mode=null,this.truncate=0===e.indexOf("-")||0===e.indexOf("_");break;default:if(this.mode){switch(this.mode){case Template.modes.EVAL:case Template.modes.ESCAPED:case Template.modes.RAW:e.lastIndexOf("//")>e.lastIndexOf("\n")&&(e+="\n")}switch(this.mode){case Template.modes.EVAL:this.source+="    ; "+e+"\n";break;case Template.modes.ESCAPED:this.source+="    ; __append(escapeFn("+stripSemi(e)+"))\n";break;case Template.modes.RAW:this.source+="    ; __append("+stripSemi(e)+")\n";break;case Template.modes.COMMENT:break;case Template.modes.LITERAL:this._addOutput(e)}}else this._addOutput(e)}this.opts.compileDebug&&t&&(this.currentLine+=t,this.source+="    ; __line = "+this.currentLine+"\n")}},exports.escapeXML=utils.escapeXML,exports.__express=exports.renderFile,exports.VERSION=_VERSION_STRING,exports.name=_NAME,"undefined"!=typeof window&&(window.ejs=exports);
\ No newline at end of file
index 284de06..9bbc77f 100755 (executable)
@@ -1,179 +1 @@
-/*
- * EJS Embedded JavaScript templates
- * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-*/
-
-/**
- * Private utility functions
- * @module utils
- * @private
- */
-
-'use strict';
-
-var regExpChars = /[|\\{}()[\]^$+*?.]/g;
-
-/**
- * Escape characters reserved in regular expressions.
- *
- * If `string` is `undefined` or `null`, the empty string is returned.
- *
- * @param {String} string Input string
- * @return {String} Escaped string
- * @static
- * @private
- */
-exports.escapeRegExpChars = function (string) {
-  // istanbul ignore if
-  if (!string) {
-    return '';
-  }
-  return String(string).replace(regExpChars, '\\$&');
-};
-
-var _ENCODE_HTML_RULES = {
-  '&': '&amp;',
-  '<': '&lt;',
-  '>': '&gt;',
-  '"': '&#34;',
-  "'": '&#39;'
-};
-var _MATCH_HTML = /[&<>'"]/g;
-
-function encode_char(c) {
-  return _ENCODE_HTML_RULES[c] || c;
-}
-
-/**
- * Stringified version of constants used by {@link module:utils.escapeXML}.
- *
- * It is used in the process of generating {@link ClientFunction}s.
- *
- * @readonly
- * @type {String}
- */
-
-var escapeFuncStr =
-  'var _ENCODE_HTML_RULES = {\n'
-+ '      "&": "&amp;"\n'
-+ '    , "<": "&lt;"\n'
-+ '    , ">": "&gt;"\n'
-+ '    , \'"\': "&#34;"\n'
-+ '    , "\'": "&#39;"\n'
-+ '    }\n'
-+ '  , _MATCH_HTML = /[&<>\'"]/g;\n'
-+ 'function encode_char(c) {\n'
-+ '  return _ENCODE_HTML_RULES[c] || c;\n'
-+ '};\n';
-
-/**
- * Escape characters reserved in XML.
- *
- * If `markup` is `undefined` or `null`, the empty string is returned.
- *
- * @implements {EscapeCallback}
- * @param {String} markup Input string
- * @return {String} Escaped string
- * @static
- * @private
- */
-
-exports.escapeXML = function (markup) {
-  return markup == undefined
-    ? ''
-    : String(markup)
-      .replace(_MATCH_HTML, encode_char);
-};
-exports.escapeXML.toString = function () {
-  return Function.prototype.toString.call(this) + ';\n' + escapeFuncStr;
-};
-
-/**
- * Naive copy of properties from one object to another.
- * Does not recurse into non-scalar properties
- * Does not check to see if the property has a value before copying
- *
- * @param  {Object} to   Destination object
- * @param  {Object} from Source object
- * @return {Object}      Destination object
- * @static
- * @private
- */
-exports.shallowCopy = function (to, from) {
-  from = from || {};
-  for (var p in from) {
-    to[p] = from[p];
-  }
-  return to;
-};
-
-/**
- * Naive copy of a list of key names, from one object to another.
- * Only copies property if it is actually defined
- * Does not recurse into non-scalar properties
- *
- * @param  {Object} to   Destination object
- * @param  {Object} from Source object
- * @param  {Array} list List of properties to copy
- * @return {Object}      Destination object
- * @static
- * @private
- */
-exports.shallowCopyFromList = function (to, from, list) {
-  for (var i = 0; i < list.length; i++) {
-    var p = list[i];
-    if (typeof from[p] != 'undefined') {
-      to[p] = from[p];
-    }
-  }
-  return to;
-};
-
-/**
- * Simple in-process cache implementation. Does not implement limits of any
- * sort.
- *
- * @implements {Cache}
- * @static
- * @private
- */
-exports.cache = {
-  _data: {},
-  set: function (key, val) {
-    this._data[key] = val;
-  },
-  get: function (key) {
-    return this._data[key];
-  },
-  remove: function (key) {
-    delete this._data[key];
-  },
-  reset: function () {
-    this._data = {};
-  }
-};
-
-/**
- * Transforms hyphen case variable into camel case.
- *
- * @param {String} string Hyphen case string
- * @return {String} Camel case string
- * @static
- * @private
- */
-exports.hyphenToCamel = function (str) {
-  return str.replace(/-[a-z]/g, function (match) { return match[1].toUpperCase(); });
-};
+"use strict";var regExpChars=/[|\\{}()[\]^$+*?.]/g;exports.escapeRegExpChars=function(t){return t?String(t).replace(regExpChars,"\\$&"):""};var _ENCODE_HTML_RULES={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&#34;","'":"&#39;"},_MATCH_HTML=/[&<>'"]/g;function encode_char(t){return _ENCODE_HTML_RULES[t]||t}var escapeFuncStr='var _ENCODE_HTML_RULES = {\n      "&": "&amp;"\n    , "<": "&lt;"\n    , ">": "&gt;"\n    , \'"\': "&#34;"\n    , "\'": "&#39;"\n    }\n  , _MATCH_HTML = /[&<>\'"]/g;\nfunction encode_char(c) {\n  return _ENCODE_HTML_RULES[c] || c;\n};\n';exports.escapeXML=function(t){return null==t?"":String(t).replace(_MATCH_HTML,encode_char)},exports.escapeXML.toString=function(){return Function.prototype.toString.call(this)+";\n"+escapeFuncStr},exports.shallowCopy=function(t,n){for(var e in n=n||{})t[e]=n[e];return t},exports.shallowCopyFromList=function(t,n,e){for(var r=0;r<e.length;r++){var a=e[r];void 0!==n[a]&&(t[a]=n[a])}return t},exports.cache={_data:{},set:function(t,n){this._data[t]=n},get:function(t){return this._data[t]},remove:function(t){delete this._data[t]},reset:function(){this._data={}}},exports.hyphenToCamel=function(t){return t.replace(/-[a-z]/g,(function(t){return t[1].toUpperCase()}))};
\ No newline at end of file
index 0216db9..ccf38ca 100644 (file)
@@ -1,6 +1 @@
-"use strict";
-
-module.exports = () => {
-  // https://mths.be/emoji
-  return /\u{1F3F4}(?:\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0077}\u{E006C}\u{E0073}|\u{E0073}\u{E0063}\u{E0074})\u{E007F}|\u200D\u2620\uFE0F)|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F468}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9B0}-\u{1F9B3}])|[\u{1F3FB}-\u{1F3FF}]\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9B0}-\u{1F9B3}])|\u{1F469}\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9B0}-\u{1F9B3}])|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F469}[\u{1F3FB}-\u{1F3FF}]\u200D[\u2695\u2696\u2708]|\u{1F468}(?:[\u{1F3FB}-\u{1F3FF}]\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}]\uFE0F|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9D6}-\u{1F9DD}](?:[\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\u{1F469}\u200D[\u2695\u2696\u2708])\uFE0F|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|\u{1F468}(?:\u200D(?:[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u{1F466}\u{1F467}])|[\u{1F3FB}-\u{1F3FF}])|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F469}\u200D\u{1F467}|\u{1F469}[\u{1F3FB}-\u{1F3FF}]\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}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{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270A-\u270D\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F470}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F4AA}\u{1F574}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F936}\u{1F9B5}\u{1F9B6}\u{1F9D1}-\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6F9}\u{1F910}-\u{1F93A}\u{1F93C}-\u{1F93E}\u{1F940}-\u{1F945}\u{1F947}-\u{1F970}\u{1F973}-\u{1F976}\u{1F97A}\u{1F97C}-\u{1F9A2}\u{1F9B0}-\u{1F9B9}\u{1F9C0}-\u{1F9C2}\u{1F9D0}-\u{1F9FF}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6F9}\u{1F910}-\u{1F93A}\u{1F93C}-\u{1F93E}\u{1F940}-\u{1F945}\u{1F947}-\u{1F970}\u{1F973}-\u{1F976}\u{1F97A}\u{1F97C}-\u{1F9A2}\u{1F9B0}-\u{1F9B9}\u{1F9C0}-\u{1F9C2}\u{1F9D0}-\u{1F9FF}]\uFE0F|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F469}\u{1F46E}\u{1F470}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9D1}-\u{1F9DD}]/gu;
-};
+"use strict";module.exports=()=>/\u{1F3F4}(?:\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0077}\u{E006C}\u{E0073}|\u{E0073}\u{E0063}\u{E0074})\u{E007F}|\u200D\u2620\uFE0F)|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F468}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9B0}-\u{1F9B3}])|[\u{1F3FB}-\u{1F3FF}]\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9B0}-\u{1F9B3}])|\u{1F469}\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9B0}-\u{1F9B3}])|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F469}[\u{1F3FB}-\u{1F3FF}]\u200D[\u2695\u2696\u2708]|\u{1F468}(?:[\u{1F3FB}-\u{1F3FF}]\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}]\uFE0F|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9D6}-\u{1F9DD}](?:[\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\u{1F469}\u200D[\u2695\u2696\u2708])\uFE0F|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|\u{1F468}(?:\u200D(?:[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u{1F466}\u{1F467}])|[\u{1F3FB}-\u{1F3FF}])|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F469}\u200D\u{1F467}|\u{1F469}[\u{1F3FB}-\u{1F3FF}]\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}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}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270A-\u270D\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F470}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F4AA}\u{1F574}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F936}\u{1F9B5}\u{1F9B6}\u{1F9D1}-\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6F9}\u{1F910}-\u{1F93A}\u{1F93C}-\u{1F93E}\u{1F940}-\u{1F945}\u{1F947}-\u{1F970}\u{1F973}-\u{1F976}\u{1F97A}\u{1F97C}-\u{1F9A2}\u{1F9B0}-\u{1F9B9}\u{1F9C0}-\u{1F9C2}\u{1F9D0}-\u{1F9FF}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6F9}\u{1F910}-\u{1F93A}\u{1F93C}-\u{1F93E}\u{1F940}-\u{1F945}\u{1F947}-\u{1F970}\u{1F973}-\u{1F976}\u{1F97A}\u{1F97C}-\u{1F9A2}\u{1F9B0}-\u{1F9B9}\u{1F9C0}-\u{1F9C2}\u{1F9D0}-\u{1F9FF}]\uFE0F|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F469}\u{1F46E}\u{1F470}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9D1}-\u{1F9DD}]/gu;
\ No newline at end of file
index d0a771d..935977b 100644 (file)
@@ -1,6 +1 @@
-"use strict";
-
-module.exports = () => {
-  // https://mths.be/emoji
-  return /\u{1F3F4}(?:\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0077}\u{E006C}\u{E0073}|\u{E0073}\u{E0063}\u{E0074})\u{E007F}|\u200D\u2620\uFE0F)|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F468}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9B0}-\u{1F9B3}])|[\u{1F3FB}-\u{1F3FF}]\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9B0}-\u{1F9B3}])|\u{1F469}\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9B0}-\u{1F9B3}])|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F469}[\u{1F3FB}-\u{1F3FF}]\u200D[\u2695\u2696\u2708]|\u{1F468}(?:[\u{1F3FB}-\u{1F3FF}]\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}]\uFE0F|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9D6}-\u{1F9DD}](?:[\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\u{1F469}\u200D[\u2695\u2696\u2708])\uFE0F|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|\u{1F468}(?:\u200D(?:[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u{1F466}\u{1F467}])|[\u{1F3FB}-\u{1F3FF}])|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F469}\u200D\u{1F467}|\u{1F469}[\u{1F3FB}-\u{1F3FF}]\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u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u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270A-\u270D\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F470}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F4AA}\u{1F574}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F936}\u{1F9B5}\u{1F9B6}\u{1F9D1}-\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6F9}\u{1F910}-\u{1F93A}\u{1F93C}-\u{1F93E}\u{1F940}-\u{1F945}\u{1F947}-\u{1F970}\u{1F973}-\u{1F976}\u{1F97A}\u{1F97C}-\u{1F9A2}\u{1F9B0}-\u{1F9B9}\u{1F9C0}-\u{1F9C2}\u{1F9D0}-\u{1F9FF}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6F9}\u{1F910}-\u{1F93A}\u{1F93C}-\u{1F93E}\u{1F940}-\u{1F945}\u{1F947}-\u{1F970}\u{1F973}-\u{1F976}\u{1F97A}\u{1F97C}-\u{1F9A2}\u{1F9B0}-\u{1F9B9}\u{1F9C0}-\u{1F9C2}\u{1F9D0}-\u{1F9FF}]\uFE0F?|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F469}\u{1F46E}\u{1F470}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9D1}-\u{1F9DD}]/gu;
-};
+"use strict";module.exports=()=>/\u{1F3F4}(?:\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0077}\u{E006C}\u{E0073}|\u{E0073}\u{E0063}\u{E0074})\u{E007F}|\u200D\u2620\uFE0F)|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F468}(?:\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9B0}-\u{1F9B3}])|[\u{1F3FB}-\u{1F3FF}]\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9B0}-\u{1F9B3}])|\u{1F469}\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9B0}-\u{1F9B3}])|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F469}[\u{1F3FB}-\u{1F3FF}]\u200D[\u2695\u2696\u2708]|\u{1F468}(?:[\u{1F3FB}-\u{1F3FF}]\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}]\uFE0F|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9D6}-\u{1F9DD}](?:[\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\u{1F469}\u200D[\u2695\u2696\u2708])\uFE0F|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|\u{1F468}(?:\u200D(?:[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u{1F466}\u{1F467}])|[\u{1F3FB}-\u{1F3FF}])|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F469}\u200D\u{1F467}|\u{1F469}[\u{1F3FB}-\u{1F3FF}]\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\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u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270A-\u270D\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F470}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F4AA}\u{1F574}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F936}\u{1F9B5}\u{1F9B6}\u{1F9D1}-\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6F9}\u{1F910}-\u{1F93A}\u{1F93C}-\u{1F93E}\u{1F940}-\u{1F945}\u{1F947}-\u{1F970}\u{1F973}-\u{1F976}\u{1F97A}\u{1F97C}-\u{1F9A2}\u{1F9B0}-\u{1F9B9}\u{1F9C0}-\u{1F9C2}\u{1F9D0}-\u{1F9FF}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6F9}\u{1F910}-\u{1F93A}\u{1F93C}-\u{1F93E}\u{1F940}-\u{1F945}\u{1F947}-\u{1F970}\u{1F973}-\u{1F976}\u{1F97A}\u{1F97C}-\u{1F9A2}\u{1F9B0}-\u{1F9B9}\u{1F9C0}-\u{1F9C2}\u{1F9D0}-\u{1F9FF}]\uFE0F?|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F469}\u{1F46E}\u{1F470}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9D1}-\u{1F9DD}]/gu;
\ No newline at end of file
index e2237a4..df28a34 100644 (file)
@@ -1,6 +1 @@
-"use strict";
-
-module.exports = function () {
-  // https://mths.be/emoji
-  return /\uD83C\uDFF4(?:\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74)\uDB40\uDC7F|\u200D\u2620\uFE0F)|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC68(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3]))|\uD83D\uDC69\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\uD83D\uDC68(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83D\uDC69\u200D[\u2695\u2696\u2708])\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC68(?:\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\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D37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDD1-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDEEB\uDEEC\uDEF4-\uDEF9]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD70\uDD73-\uDD76\uDD7A\uDD7C-\uDDA2\uDDB0-\uDDB9\uDDC0-\uDDC2\uDDD0-\uDDFF])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEF9]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD70\uDD73-\uDD76\uDD7A\uDD7C-\uDDA2\uDDB0-\uDDB9\uDDC0-\uDDC2\uDDD0-\uDDFF])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC69\uDC6E\uDC70-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD26\uDD30-\uDD39\uDD3D\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDD1-\uDDDD])/g;
-};
+"use strict";module.exports=function(){return/\uD83C\uDFF4(?:\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74)\uDB40\uDC7F|\u200D\u2620\uFE0F)|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC68(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3]))|\uD83D\uDC69\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\uD83D\uDC68(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83D\uDC69\u200D[\u2695\u2696\u2708])\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC68(?:\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uD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F2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDD1-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDEEB\uDEEC\uDEF4-\uDEF9]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD70\uDD73-\uDD76\uDD7A\uDD7C-\uDDA2\uDDB0-\uDDB9\uDDC0-\uDDC2\uDDD0-\uDDFF])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEF9]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD70\uDD73-\uDD76\uDD7A\uDD7C-\uDDA2\uDDB0-\uDDB9\uDDC0-\uDDC2\uDDD0-\uDDFF])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC69\uDC6E\uDC70-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD26\uDD30-\uDD39\uDD3D\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDD1-\uDDDD])/g};
\ No newline at end of file
index 199ae3b..84bed14 100644 (file)
@@ -1,6 +1 @@
-"use strict";
-
-module.exports = function () {
-  // https://mths.be/emoji
-  return /\uD83C\uDFF4(?:\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74)\uDB40\uDC7F|\u200D\u2620\uFE0F)|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC68(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3]))|\uD83D\uDC69\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\uD83D\uDC68(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83D\uDC69\u200D[\u2695\u2696\u2708])\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC68(?:\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D[\uDC66\uDC67])|\uD83C[\uDFFB-\uDFFF])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83C\uDDF6\uD83C\uDDE6|\uD83C\uDDFD\uD83C\uDDF0|\uD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F\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDD1-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDEEB\uDEEC\uDEF4-\uDEF9]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD70\uDD73-\uDD76\uDD7A\uDD7C-\uDDA2\uDDB0-\uDDB9\uDDC0-\uDDC2\uDDD0-\uDDFF])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEF9]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD70\uDD73-\uDD76\uDD7A\uDD7C-\uDDA2\uDDB0-\uDDB9\uDDC0-\uDDC2\uDDD0-\uDDFF])\uFE0F?|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC69\uDC6E\uDC70-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD26\uDD30-\uDD39\uDD3D\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDD1-\uDDDD])/g;
-};
+"use strict";module.exports=function(){return/\uD83C\uDFF4(?:\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74)\uDB40\uDC7F|\u200D\u2620\uFE0F)|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC68(?:\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|(?:\uD83C[\uDFFB-\uDFFF])\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3]))|\uD83D\uDC69\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDB0-\uDDB3])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\uD83D\uDC68(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83D\uDC69\u200D[\u2695\u2696\u2708])\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|\uD83D\uDC68(?:\u200D(?:(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D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EA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDD1-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDEEB\uDEEC\uDEF4-\uDEF9]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD70\uDD73-\uDD76\uDD7A\uDD7C-\uDDA2\uDDB0-\uDDB9\uDDC0-\uDDC2\uDDD0-\uDDFF])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEF9]|\uD83E[\uDD10-\uDD3A\uDD3C-\uDD3E\uDD40-\uDD45\uDD47-\uDD70\uDD73-\uDD76\uDD7A\uDD7C-\uDDA2\uDDB0-\uDDB9\uDDC0-\uDDC2\uDDD0-\uDDFF])\uFE0F?|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC69\uDC6E\uDC70-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD18-\uDD1C\uDD1E\uDD1F\uDD26\uDD30-\uDD39\uDD3D\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDD1-\uDDDD])/g};
\ No newline at end of file
index fc4906c..35de331 100644 (file)
@@ -3,58 +3,4 @@
  * Copyright(c) 2016 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = encodeUrl
-
-/**
- * RegExp to match non-URL code points, *after* encoding (i.e. not including "%")
- * and including invalid escape sequences.
- * @private
- */
-
-var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g
-
-/**
- * RegExp to match unmatched surrogate pair.
- * @private
- */
-
-var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g
-
-/**
- * String to replace unmatched surrogate pair with.
- * @private
- */
-
-var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2'
-
-/**
- * Encode a URL to a percent-encoded form, excluding already-encoded sequences.
- *
- * This function will take an already-encoded URL and encode all the non-URL
- * code points. This function will not encode the "%" character unless it is
- * not part of a valid sequence (`%20` will be left as-is, but `%foo` will
- * be encoded as `%25foo`).
- *
- * This encode is meant to be "safe" and does not throw errors. It will try as
- * hard as it can to properly encode the given URL, including replacing any raw,
- * unpaired surrogate pairs with the Unicode replacement character prior to
- * encoding.
- *
- * @param {string} url
- * @return {string}
- * @public
- */
-
-function encodeUrl (url) {
-  return String(url)
-    .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE)
-    .replace(ENCODE_CHARS_REGEXP, encodeURI)
-}
+"use strict";module.exports=encodeUrl;var ENCODE_CHARS_REGEXP=/(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g,UNMATCHED_SURROGATE_PAIR_REGEXP=/(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g,UNMATCHED_SURROGATE_PAIR_REPLACE="$1�$2";function encodeUrl(E){return String(E).replace(UNMATCHED_SURROGATE_PAIR_REGEXP,UNMATCHED_SURROGATE_PAIR_REPLACE).replace(ENCODE_CHARS_REGEXP,encodeURI)}
\ No newline at end of file
index 1a3e81d..61462ad 100644 (file)
-(function webpackUniversalModuleDefinition(root, factory) {
-       if(typeof exports === 'object' && typeof module === 'object')
-               module.exports = factory();
-       else if(typeof define === 'function' && define.amd)
-               define([], factory);
-       else if(typeof exports === 'object')
-               exports["eio"] = factory();
-       else
-               root["eio"] = factory();
-})(this, function() {
-return /******/ (function(modules) { // webpackBootstrap
-/******/       // The module cache
-/******/       var installedModules = {};
-
-/******/       // The require function
-/******/       function __webpack_require__(moduleId) {
-
-/******/               // Check if module is in cache
-/******/               if(installedModules[moduleId])
-/******/                       return installedModules[moduleId].exports;
-
-/******/               // Create a new module (and put it into the cache)
-/******/               var module = installedModules[moduleId] = {
-/******/                       exports: {},
-/******/                       id: moduleId,
-/******/                       loaded: false
-/******/               };
-
-/******/               // Execute the module function
-/******/               modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
-
-/******/               // Flag the module as loaded
-/******/               module.loaded = true;
-
-/******/               // Return the exports of the module
-/******/               return module.exports;
-/******/       }
-
-
-/******/       // expose the modules object (__webpack_modules__)
-/******/       __webpack_require__.m = modules;
-
-/******/       // expose the module cache
-/******/       __webpack_require__.c = installedModules;
-
-/******/       // __webpack_public_path__
-/******/       __webpack_require__.p = "";
-
-/******/       // Load entry module and return exports
-/******/       return __webpack_require__(0);
-/******/ })
-/************************************************************************/
-/******/ ([
-/* 0 */
-/***/ function(module, exports, __webpack_require__) {
-
-       
-       module.exports = __webpack_require__(1);
-
-       /**
-        * Exports parser
-        *
-        * @api public
-        *
-        */
-       module.exports.parser = __webpack_require__(9);
-
-
-/***/ },
-/* 1 */
-/***/ function(module, exports, __webpack_require__) {
-
-       /**
-        * Module dependencies.
-        */
-
-       var transports = __webpack_require__(2);
-       var Emitter = __webpack_require__(18);
-       var debug = __webpack_require__(22)('engine.io-client:socket');
-       var index = __webpack_require__(29);
-       var parser = __webpack_require__(9);
-       var parseuri = __webpack_require__(30);
-       var parseqs = __webpack_require__(19);
-
-       /**
-        * Module exports.
-        */
-
-       module.exports = Socket;
-
-       /**
-        * Socket constructor.
-        *
-        * @param {String|Object} uri or options
-        * @param {Object} options
-        * @api public
-        */
-
-       function Socket (uri, opts) {
-         if (!(this instanceof Socket)) return new Socket(uri, opts);
-
-         opts = opts || {};
-
-         if (uri && 'object' === typeof uri) {
-           opts = uri;
-           uri = null;
-         }
-
-         if (uri) {
-           uri = parseuri(uri);
-           opts.hostname = uri.host;
-           opts.secure = uri.protocol === 'https' || uri.protocol === 'wss';
-           opts.port = uri.port;
-           if (uri.query) opts.query = uri.query;
-         } else if (opts.host) {
-           opts.hostname = parseuri(opts.host).host;
-         }
-
-         this.secure = null != opts.secure ? opts.secure
-           : (typeof location !== 'undefined' && 'https:' === location.protocol);
-
-         if (opts.hostname && !opts.port) {
-           // if no port is specified manually, use the protocol default
-           opts.port = this.secure ? '443' : '80';
-         }
-
-         this.agent = opts.agent || false;
-         this.hostname = opts.hostname ||
-           (typeof location !== 'undefined' ? location.hostname : 'localhost');
-         this.port = opts.port || (typeof location !== 'undefined' && location.port
-             ? location.port
-             : (this.secure ? 443 : 80));
-         this.query = opts.query || {};
-         if ('string' === typeof this.query) this.query = parseqs.decode(this.query);
-         this.upgrade = false !== opts.upgrade;
-         this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
-         this.forceJSONP = !!opts.forceJSONP;
-         this.jsonp = false !== opts.jsonp;
-         this.forceBase64 = !!opts.forceBase64;
-         this.enablesXDR = !!opts.enablesXDR;
-         this.withCredentials = false !== opts.withCredentials;
-         this.timestampParam = opts.timestampParam || 't';
-         this.timestampRequests = opts.timestampRequests;
-         this.transports = opts.transports || ['polling', 'websocket'];
-         this.transportOptions = opts.transportOptions || {};
-         this.readyState = '';
-         this.writeBuffer = [];
-         this.prevBufferLen = 0;
-         this.policyPort = opts.policyPort || 843;
-         this.rememberUpgrade = opts.rememberUpgrade || false;
-         this.binaryType = null;
-         this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
-         this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false;
-
-         if (true === this.perMessageDeflate) this.perMessageDeflate = {};
-         if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) {
-           this.perMessageDeflate.threshold = 1024;
-         }
-
-         // SSL options for Node.js client
-         this.pfx = opts.pfx || undefined;
-         this.key = opts.key || undefined;
-         this.passphrase = opts.passphrase || undefined;
-         this.cert = opts.cert || undefined;
-         this.ca = opts.ca || undefined;
-         this.ciphers = opts.ciphers || undefined;
-         this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? true : opts.rejectUnauthorized;
-         this.forceNode = !!opts.forceNode;
-
-         // detect ReactNative environment
-         this.isReactNative = (typeof navigator !== 'undefined' && typeof navigator.product === 'string' && navigator.product.toLowerCase() === 'reactnative');
-
-         // other options for Node.js or ReactNative client
-         if (typeof self === 'undefined' || this.isReactNative) {
-           if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) {
-             this.extraHeaders = opts.extraHeaders;
-           }
-
-           if (opts.localAddress) {
-             this.localAddress = opts.localAddress;
-           }
-         }
-
-         // set on handshake
-         this.id = null;
-         this.upgrades = null;
-         this.pingInterval = null;
-         this.pingTimeout = null;
-
-         // set on heartbeat
-         this.pingIntervalTimer = null;
-         this.pingTimeoutTimer = null;
-
-         this.open();
-       }
-
-       Socket.priorWebsocketSuccess = false;
-
-       /**
-        * Mix in `Emitter`.
-        */
-
-       Emitter(Socket.prototype);
-
-       /**
-        * Protocol version.
-        *
-        * @api public
-        */
-
-       Socket.protocol = parser.protocol; // this is an int
-
-       /**
-        * Expose deps for legacy compatibility
-        * and standalone browser access.
-        */
-
-       Socket.Socket = Socket;
-       Socket.Transport = __webpack_require__(8);
-       Socket.transports = __webpack_require__(2);
-       Socket.parser = __webpack_require__(9);
-
-       /**
-        * Creates transport of the given type.
-        *
-        * @param {String} transport name
-        * @return {Transport}
-        * @api private
-        */
-
-       Socket.prototype.createTransport = function (name) {
-         debug('creating transport "%s"', name);
-         var query = clone(this.query);
-
-         // append engine.io protocol identifier
-         query.EIO = parser.protocol;
-
-         // transport name
-         query.transport = name;
-
-         // per-transport options
-         var options = this.transportOptions[name] || {};
-
-         // session id if we already have one
-         if (this.id) query.sid = this.id;
-
-         var transport = new transports[name]({
-           query: query,
-           socket: this,
-           agent: options.agent || this.agent,
-           hostname: options.hostname || this.hostname,
-           port: options.port || this.port,
-           secure: options.secure || this.secure,
-           path: options.path || this.path,
-           forceJSONP: options.forceJSONP || this.forceJSONP,
-           jsonp: options.jsonp || this.jsonp,
-           forceBase64: options.forceBase64 || this.forceBase64,
-           enablesXDR: options.enablesXDR || this.enablesXDR,
-           withCredentials: options.withCredentials || this.withCredentials,
-           timestampRequests: options.timestampRequests || this.timestampRequests,
-           timestampParam: options.timestampParam || this.timestampParam,
-           policyPort: options.policyPort || this.policyPort,
-           pfx: options.pfx || this.pfx,
-           key: options.key || this.key,
-           passphrase: options.passphrase || this.passphrase,
-           cert: options.cert || this.cert,
-           ca: options.ca || this.ca,
-           ciphers: options.ciphers || this.ciphers,
-           rejectUnauthorized: options.rejectUnauthorized || this.rejectUnauthorized,
-           perMessageDeflate: options.perMessageDeflate || this.perMessageDeflate,
-           extraHeaders: options.extraHeaders || this.extraHeaders,
-           forceNode: options.forceNode || this.forceNode,
-           localAddress: options.localAddress || this.localAddress,
-           requestTimeout: options.requestTimeout || this.requestTimeout,
-           protocols: options.protocols || void (0),
-           isReactNative: this.isReactNative
-         });
-
-         return transport;
-       };
-
-       function clone (obj) {
-         var o = {};
-         for (var i in obj) {
-           if (obj.hasOwnProperty(i)) {
-             o[i] = obj[i];
-           }
-         }
-         return o;
-       }
-
-       /**
-        * Initializes transport to use and starts probe.
-        *
-        * @api private
-        */
-       Socket.prototype.open = function () {
-         var transport;
-         if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) {
-           transport = 'websocket';
-         } else if (0 === this.transports.length) {
-           // Emit error on next tick so it can be listened to
-           var self = this;
-           setTimeout(function () {
-             self.emit('error', 'No transports available');
-           }, 0);
-           return;
-         } else {
-           transport = this.transports[0];
-         }
-         this.readyState = 'opening';
-
-         // Retry with the next transport if the transport is disabled (jsonp: false)
-         try {
-           transport = this.createTransport(transport);
-         } catch (e) {
-           this.transports.shift();
-           this.open();
-           return;
-         }
-
-         transport.open();
-         this.setTransport(transport);
-       };
-
-       /**
-        * Sets the current transport. Disables the existing one (if any).
-        *
-        * @api private
-        */
-
-       Socket.prototype.setTransport = function (transport) {
-         debug('setting transport %s', transport.name);
-         var self = this;
-
-         if (this.transport) {
-           debug('clearing existing transport %s', this.transport.name);
-           this.transport.removeAllListeners();
-         }
-
-         // set up transport
-         this.transport = transport;
-
-         // set up transport listeners
-         transport
-         .on('drain', function () {
-           self.onDrain();
-         })
-         .on('packet', function (packet) {
-           self.onPacket(packet);
-         })
-         .on('error', function (e) {
-           self.onError(e);
-         })
-         .on('close', function () {
-           self.onClose('transport close');
-         });
-       };
-
-       /**
-        * Probes a transport.
-        *
-        * @param {String} transport name
-        * @api private
-        */
-
-       Socket.prototype.probe = function (name) {
-         debug('probing transport "%s"', name);
-         var transport = this.createTransport(name, { probe: 1 });
-         var failed = false;
-         var self = this;
-
-         Socket.priorWebsocketSuccess = false;
-
-         function onTransportOpen () {
-           if (self.onlyBinaryUpgrades) {
-             var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
-             failed = failed || upgradeLosesBinary;
-           }
-           if (failed) return;
-
-           debug('probe transport "%s" opened', name);
-           transport.send([{ type: 'ping', data: 'probe' }]);
-           transport.once('packet', function (msg) {
-             if (failed) return;
-             if ('pong' === msg.type && 'probe' === msg.data) {
-               debug('probe transport "%s" pong', name);
-               self.upgrading = true;
-               self.emit('upgrading', transport);
-               if (!transport) return;
-               Socket.priorWebsocketSuccess = 'websocket' === transport.name;
-
-               debug('pausing current transport "%s"', self.transport.name);
-               self.transport.pause(function () {
-                 if (failed) return;
-                 if ('closed' === self.readyState) return;
-                 debug('changing transport and sending upgrade packet');
-
-                 cleanup();
-
-                 self.setTransport(transport);
-                 transport.send([{ type: 'upgrade' }]);
-                 self.emit('upgrade', transport);
-                 transport = null;
-                 self.upgrading = false;
-                 self.flush();
-               });
-             } else {
-               debug('probe transport "%s" failed', name);
-               var err = new Error('probe error');
-               err.transport = transport.name;
-               self.emit('upgradeError', err);
-             }
-           });
-         }
-
-         function freezeTransport () {
-           if (failed) return;
-
-           // Any callback called by transport should be ignored since now
-           failed = true;
-
-           cleanup();
-
-           transport.close();
-           transport = null;
-         }
-
-         // Handle any error that happens while probing
-         function onerror (err) {
-           var error = new Error('probe error: ' + err);
-           error.transport = transport.name;
-
-           freezeTransport();
-
-           debug('probe transport "%s" failed because of error: %s', name, err);
-
-           self.emit('upgradeError', error);
-         }
-
-         function onTransportClose () {
-           onerror('transport closed');
-         }
-
-         // When the socket is closed while we're probing
-         function onclose () {
-           onerror('socket closed');
-         }
-
-         // When the socket is upgraded while we're probing
-         function onupgrade (to) {
-           if (transport && to.name !== transport.name) {
-             debug('"%s" works - aborting "%s"', to.name, transport.name);
-             freezeTransport();
-           }
-         }
-
-         // Remove all listeners on the transport and on self
-         function cleanup () {
-           transport.removeListener('open', onTransportOpen);
-           transport.removeListener('error', onerror);
-           transport.removeListener('close', onTransportClose);
-           self.removeListener('close', onclose);
-           self.removeListener('upgrading', onupgrade);
-         }
-
-         transport.once('open', onTransportOpen);
-         transport.once('error', onerror);
-         transport.once('close', onTransportClose);
-
-         this.once('close', onclose);
-         this.once('upgrading', onupgrade);
-
-         transport.open();
-       };
-
-       /**
-        * Called when connection is deemed open.
-        *
-        * @api public
-        */
-
-       Socket.prototype.onOpen = function () {
-         debug('socket open');
-         this.readyState = 'open';
-         Socket.priorWebsocketSuccess = 'websocket' === this.transport.name;
-         this.emit('open');
-         this.flush();
-
-         // we check for `readyState` in case an `open`
-         // listener already closed the socket
-         if ('open' === this.readyState && this.upgrade && this.transport.pause) {
-           debug('starting upgrade probes');
-           for (var i = 0, l = this.upgrades.length; i < l; i++) {
-             this.probe(this.upgrades[i]);
-           }
-         }
-       };
-
-       /**
-        * Handles a packet.
-        *
-        * @api private
-        */
-
-       Socket.prototype.onPacket = function (packet) {
-         if ('opening' === this.readyState || 'open' === this.readyState ||
-             'closing' === this.readyState) {
-           debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
-
-           this.emit('packet', packet);
-
-           // Socket is live - any packet counts
-           this.emit('heartbeat');
-
-           switch (packet.type) {
-             case 'open':
-               this.onHandshake(JSON.parse(packet.data));
-               break;
-
-             case 'pong':
-               this.setPing();
-               this.emit('pong');
-               break;
-
-             case 'error':
-               var err = new Error('server error');
-               err.code = packet.data;
-               this.onError(err);
-               break;
-
-             case 'message':
-               this.emit('data', packet.data);
-               this.emit('message', packet.data);
-               break;
-           }
-         } else {
-           debug('packet received with socket readyState "%s"', this.readyState);
-         }
-       };
-
-       /**
-        * Called upon handshake completion.
-        *
-        * @param {Object} handshake obj
-        * @api private
-        */
-
-       Socket.prototype.onHandshake = function (data) {
-         this.emit('handshake', data);
-         this.id = data.sid;
-         this.transport.query.sid = data.sid;
-         this.upgrades = this.filterUpgrades(data.upgrades);
-         this.pingInterval = data.pingInterval;
-         this.pingTimeout = data.pingTimeout;
-         this.onOpen();
-         // In case open handler closes socket
-         if ('closed' === this.readyState) return;
-         this.setPing();
-
-         // Prolong liveness of socket on heartbeat
-         this.removeListener('heartbeat', this.onHeartbeat);
-         this.on('heartbeat', this.onHeartbeat);
-       };
-
-       /**
-        * Resets ping timeout.
-        *
-        * @api private
-        */
-
-       Socket.prototype.onHeartbeat = function (timeout) {
-         clearTimeout(this.pingTimeoutTimer);
-         var self = this;
-         self.pingTimeoutTimer = setTimeout(function () {
-           if ('closed' === self.readyState) return;
-           self.onClose('ping timeout');
-         }, timeout || (self.pingInterval + self.pingTimeout));
-       };
-
-       /**
-        * Pings server every `this.pingInterval` and expects response
-        * within `this.pingTimeout` or closes connection.
-        *
-        * @api private
-        */
-
-       Socket.prototype.setPing = function () {
-         var self = this;
-         clearTimeout(self.pingIntervalTimer);
-         self.pingIntervalTimer = setTimeout(function () {
-           debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
-           self.ping();
-           self.onHeartbeat(self.pingTimeout);
-         }, self.pingInterval);
-       };
-
-       /**
-       * Sends a ping packet.
-       *
-       * @api private
-       */
-
-       Socket.prototype.ping = function () {
-         var self = this;
-         this.sendPacket('ping', function () {
-           self.emit('ping');
-         });
-       };
-
-       /**
-        * Called on `drain` event
-        *
-        * @api private
-        */
-
-       Socket.prototype.onDrain = function () {
-         this.writeBuffer.splice(0, this.prevBufferLen);
-
-         // setting prevBufferLen = 0 is very important
-         // for example, when upgrading, upgrade packet is sent over,
-         // and a nonzero prevBufferLen could cause problems on `drain`
-         this.prevBufferLen = 0;
-
-         if (0 === this.writeBuffer.length) {
-           this.emit('drain');
-         } else {
-           this.flush();
-         }
-       };
-
-       /**
-        * Flush write buffers.
-        *
-        * @api private
-        */
-
-       Socket.prototype.flush = function () {
-         if ('closed' !== this.readyState && this.transport.writable &&
-           !this.upgrading && this.writeBuffer.length) {
-           debug('flushing %d packets in socket', this.writeBuffer.length);
-           this.transport.send(this.writeBuffer);
-           // keep track of current length of writeBuffer
-           // splice writeBuffer and callbackBuffer on `drain`
-           this.prevBufferLen = this.writeBuffer.length;
-           this.emit('flush');
-         }
-       };
-
-       /**
-        * Sends a message.
-        *
-        * @param {String} message.
-        * @param {Function} callback function.
-        * @param {Object} options.
-        * @return {Socket} for chaining.
-        * @api public
-        */
-
-       Socket.prototype.write =
-       Socket.prototype.send = function (msg, options, fn) {
-         this.sendPacket('message', msg, options, fn);
-         return this;
-       };
-
-       /**
-        * Sends a packet.
-        *
-        * @param {String} packet type.
-        * @param {String} data.
-        * @param {Object} options.
-        * @param {Function} callback function.
-        * @api private
-        */
-
-       Socket.prototype.sendPacket = function (type, data, options, fn) {
-         if ('function' === typeof data) {
-           fn = data;
-           data = undefined;
-         }
-
-         if ('function' === typeof options) {
-           fn = options;
-           options = null;
-         }
-
-         if ('closing' === this.readyState || 'closed' === this.readyState) {
-           return;
-         }
-
-         options = options || {};
-         options.compress = false !== options.compress;
-
-         var packet = {
-           type: type,
-           data: data,
-           options: options
-         };
-         this.emit('packetCreate', packet);
-         this.writeBuffer.push(packet);
-         if (fn) this.once('flush', fn);
-         this.flush();
-       };
-
-       /**
-        * Closes the connection.
-        *
-        * @api private
-        */
-
-       Socket.prototype.close = function () {
-         if ('opening' === this.readyState || 'open' === this.readyState) {
-           this.readyState = 'closing';
-
-           var self = this;
-
-           if (this.writeBuffer.length) {
-             this.once('drain', function () {
-               if (this.upgrading) {
-                 waitForUpgrade();
-               } else {
-                 close();
-               }
-             });
-           } else if (this.upgrading) {
-             waitForUpgrade();
-           } else {
-             close();
-           }
-         }
-
-         function close () {
-           self.onClose('forced close');
-           debug('socket closing - telling transport to close');
-           self.transport.close();
-         }
-
-         function cleanupAndClose () {
-           self.removeListener('upgrade', cleanupAndClose);
-           self.removeListener('upgradeError', cleanupAndClose);
-           close();
-         }
-
-         function waitForUpgrade () {
-           // wait for upgrade to finish since we can't send packets while pausing a transport
-           self.once('upgrade', cleanupAndClose);
-           self.once('upgradeError', cleanupAndClose);
-         }
-
-         return this;
-       };
-
-       /**
-        * Called upon transport error
-        *
-        * @api private
-        */
-
-       Socket.prototype.onError = function (err) {
-         debug('socket error %j', err);
-         Socket.priorWebsocketSuccess = false;
-         this.emit('error', err);
-         this.onClose('transport error', err);
-       };
-
-       /**
-        * Called upon transport close.
-        *
-        * @api private
-        */
-
-       Socket.prototype.onClose = function (reason, desc) {
-         if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) {
-           debug('socket close with reason: "%s"', reason);
-           var self = this;
-
-           // clear timers
-           clearTimeout(this.pingIntervalTimer);
-           clearTimeout(this.pingTimeoutTimer);
-
-           // stop event from firing again for transport
-           this.transport.removeAllListeners('close');
-
-           // ensure transport won't stay open
-           this.transport.close();
-
-           // ignore further transport communication
-           this.transport.removeAllListeners();
-
-           // set ready state
-           this.readyState = 'closed';
-
-           // clear session id
-           this.id = null;
-
-           // emit close event
-           this.emit('close', reason, desc);
-
-           // clean buffers after, so users can still
-           // grab the buffers on `close` event
-           self.writeBuffer = [];
-           self.prevBufferLen = 0;
-         }
-       };
-
-       /**
-        * Filters upgrades, returning only those matching client transports.
-        *
-        * @param {Array} server upgrades
-        * @api private
-        *
-        */
-
-       Socket.prototype.filterUpgrades = function (upgrades) {
-         var filteredUpgrades = [];
-         for (var i = 0, j = upgrades.length; i < j; i++) {
-           if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
-         }
-         return filteredUpgrades;
-       };
-
-
-/***/ },
-/* 2 */
-/***/ function(module, exports, __webpack_require__) {
-
-       /**
-        * Module dependencies
-        */
-
-       var XMLHttpRequest = __webpack_require__(3);
-       var XHR = __webpack_require__(6);
-       var JSONP = __webpack_require__(26);
-       var websocket = __webpack_require__(27);
-
-       /**
-        * Export transports.
-        */
-
-       exports.polling = polling;
-       exports.websocket = websocket;
-
-       /**
-        * Polling transport polymorphic constructor.
-        * Decides on xhr vs jsonp based on feature detection.
-        *
-        * @api private
-        */
-
-       function polling (opts) {
-         var xhr;
-         var xd = false;
-         var xs = false;
-         var jsonp = false !== opts.jsonp;
-
-         if (typeof location !== 'undefined') {
-           var isSSL = 'https:' === location.protocol;
-           var port = location.port;
-
-           // some user agents have empty `location.port`
-           if (!port) {
-             port = isSSL ? 443 : 80;
-           }
-
-           xd = opts.hostname !== location.hostname || port !== opts.port;
-           xs = opts.secure !== isSSL;
-         }
-
-         opts.xdomain = xd;
-         opts.xscheme = xs;
-         xhr = new XMLHttpRequest(opts);
-
-         if ('open' in xhr && !opts.forceJSONP) {
-           return new XHR(opts);
-         } else {
-           if (!jsonp) throw new Error('JSONP disabled');
-           return new JSONP(opts);
-         }
-       }
-
-
-/***/ },
-/* 3 */
-/***/ function(module, exports, __webpack_require__) {
-
-       // browser shim for xmlhttprequest module
-
-       var hasCORS = __webpack_require__(4);
-       var globalThis = __webpack_require__(5);
-
-       module.exports = function (opts) {
-         var xdomain = opts.xdomain;
-
-         // scheme must be same when usign XDomainRequest
-         // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
-         var xscheme = opts.xscheme;
-
-         // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
-         // https://github.com/Automattic/engine.io-client/pull/217
-         var enablesXDR = opts.enablesXDR;
-
-         // XMLHttpRequest can be disabled on IE
-         try {
-           if ('undefined' !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
-             return new XMLHttpRequest();
-           }
-         } catch (e) { }
-
-         // Use XDomainRequest for IE8 if enablesXDR is true
-         // because loading bar keeps flashing when using jsonp-polling
-         // https://github.com/yujiosaka/socke.io-ie8-loading-example
-         try {
-           if ('undefined' !== typeof XDomainRequest && !xscheme && enablesXDR) {
-             return new XDomainRequest();
-           }
-         } catch (e) { }
-
-         if (!xdomain) {
-           try {
-             return new globalThis[['Active'].concat('Object').join('X')]('Microsoft.XMLHTTP');
-           } catch (e) { }
-         }
-       };
-
-
-/***/ },
-/* 4 */
-/***/ function(module, exports) {
-
-       
-       /**
-        * Module exports.
-        *
-        * Logic borrowed from Modernizr:
-        *
-        *   - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
-        */
-
-       try {
-         module.exports = typeof XMLHttpRequest !== 'undefined' &&
-           'withCredentials' in new XMLHttpRequest();
-       } catch (err) {
-         // if XMLHttp support is disabled in IE then it will throw
-         // when trying to create
-         module.exports = false;
-       }
-
-
-/***/ },
-/* 5 */
-/***/ function(module, exports) {
-
-       module.exports = (function () {
-         if (typeof self !== 'undefined') {
-           return self;
-         } else if (typeof window !== 'undefined') {
-           return window;
-         } else {
-           return Function('return this')(); // eslint-disable-line no-new-func
-         }
-       })();
-
-
-/***/ },
-/* 6 */
-/***/ function(module, exports, __webpack_require__) {
-
-       /* global attachEvent */
-
-       /**
-        * Module requirements.
-        */
-
-       var XMLHttpRequest = __webpack_require__(3);
-       var Polling = __webpack_require__(7);
-       var Emitter = __webpack_require__(18);
-       var inherit = __webpack_require__(20);
-       var debug = __webpack_require__(22)('engine.io-client:polling-xhr');
-       var globalThis = __webpack_require__(5);
-
-       /**
-        * Module exports.
-        */
-
-       module.exports = XHR;
-       module.exports.Request = Request;
-
-       /**
-        * Empty function
-        */
-
-       function empty () {}
-
-       /**
-        * XHR Polling constructor.
-        *
-        * @param {Object} opts
-        * @api public
-        */
-
-       function XHR (opts) {
-         Polling.call(this, opts);
-         this.requestTimeout = opts.requestTimeout;
-         this.extraHeaders = opts.extraHeaders;
-
-         if (typeof location !== 'undefined') {
-           var isSSL = 'https:' === location.protocol;
-           var port = location.port;
-
-           // some user agents have empty `location.port`
-           if (!port) {
-             port = isSSL ? 443 : 80;
-           }
-
-           this.xd = (typeof location !== 'undefined' && opts.hostname !== location.hostname) ||
-             port !== opts.port;
-           this.xs = opts.secure !== isSSL;
-         }
-       }
-
-       /**
-        * Inherits from Polling.
-        */
-
-       inherit(XHR, Polling);
-
-       /**
-        * XHR supports binary
-        */
-
-       XHR.prototype.supportsBinary = true;
-
-       /**
-        * Creates a request.
-        *
-        * @param {String} method
-        * @api private
-        */
-
-       XHR.prototype.request = function (opts) {
-         opts = opts || {};
-         opts.uri = this.uri();
-         opts.xd = this.xd;
-         opts.xs = this.xs;
-         opts.agent = this.agent || false;
-         opts.supportsBinary = this.supportsBinary;
-         opts.enablesXDR = this.enablesXDR;
-         opts.withCredentials = this.withCredentials;
-
-         // SSL options for Node.js client
-         opts.pfx = this.pfx;
-         opts.key = this.key;
-         opts.passphrase = this.passphrase;
-         opts.cert = this.cert;
-         opts.ca = this.ca;
-         opts.ciphers = this.ciphers;
-         opts.rejectUnauthorized = this.rejectUnauthorized;
-         opts.requestTimeout = this.requestTimeout;
-
-         // other options for Node.js client
-         opts.extraHeaders = this.extraHeaders;
-
-         return new Request(opts);
-       };
-
-       /**
-        * Sends data.
-        *
-        * @param {String} data to send.
-        * @param {Function} called upon flush.
-        * @api private
-        */
-
-       XHR.prototype.doWrite = function (data, fn) {
-         var isBinary = typeof data !== 'string' && data !== undefined;
-         var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
-         var self = this;
-         req.on('success', fn);
-         req.on('error', function (err) {
-           self.onError('xhr post error', err);
-         });
-         this.sendXhr = req;
-       };
-
-       /**
-        * Starts a poll cycle.
-        *
-        * @api private
-        */
-
-       XHR.prototype.doPoll = function () {
-         debug('xhr poll');
-         var req = this.request();
-         var self = this;
-         req.on('data', function (data) {
-           self.onData(data);
-         });
-         req.on('error', function (err) {
-           self.onError('xhr poll error', err);
-         });
-         this.pollXhr = req;
-       };
-
-       /**
-        * Request constructor
-        *
-        * @param {Object} options
-        * @api public
-        */
-
-       function Request (opts) {
-         this.method = opts.method || 'GET';
-         this.uri = opts.uri;
-         this.xd = !!opts.xd;
-         this.xs = !!opts.xs;
-         this.async = false !== opts.async;
-         this.data = undefined !== opts.data ? opts.data : null;
-         this.agent = opts.agent;
-         this.isBinary = opts.isBinary;
-         this.supportsBinary = opts.supportsBinary;
-         this.enablesXDR = opts.enablesXDR;
-         this.withCredentials = opts.withCredentials;
-         this.requestTimeout = opts.requestTimeout;
-
-         // SSL options for Node.js client
-         this.pfx = opts.pfx;
-         this.key = opts.key;
-         this.passphrase = opts.passphrase;
-         this.cert = opts.cert;
-         this.ca = opts.ca;
-         this.ciphers = opts.ciphers;
-         this.rejectUnauthorized = opts.rejectUnauthorized;
-
-         // other options for Node.js client
-         this.extraHeaders = opts.extraHeaders;
-
-         this.create();
-       }
-
-       /**
-        * Mix in `Emitter`.
-        */
-
-       Emitter(Request.prototype);
-
-       /**
-        * Creates the XHR object and sends the request.
-        *
-        * @api private
-        */
-
-       Request.prototype.create = function () {
-         var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
-
-         // SSL options for Node.js client
-         opts.pfx = this.pfx;
-         opts.key = this.key;
-         opts.passphrase = this.passphrase;
-         opts.cert = this.cert;
-         opts.ca = this.ca;
-         opts.ciphers = this.ciphers;
-         opts.rejectUnauthorized = this.rejectUnauthorized;
-
-         var xhr = this.xhr = new XMLHttpRequest(opts);
-         var self = this;
-
-         try {
-           debug('xhr open %s: %s', this.method, this.uri);
-           xhr.open(this.method, this.uri, this.async);
-           try {
-             if (this.extraHeaders) {
-               xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
-               for (var i in this.extraHeaders) {
-                 if (this.extraHeaders.hasOwnProperty(i)) {
-                   xhr.setRequestHeader(i, this.extraHeaders[i]);
-                 }
-               }
-             }
-           } catch (e) {}
-
-           if ('POST' === this.method) {
-             try {
-               if (this.isBinary) {
-                 xhr.setRequestHeader('Content-type', 'application/octet-stream');
-               } else {
-                 xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
-               }
-             } catch (e) {}
-           }
-
-           try {
-             xhr.setRequestHeader('Accept', '*/*');
-           } catch (e) {}
-
-           // ie6 check
-           if ('withCredentials' in xhr) {
-             xhr.withCredentials = this.withCredentials;
-           }
-
-           if (this.requestTimeout) {
-             xhr.timeout = this.requestTimeout;
-           }
-
-           if (this.hasXDR()) {
-             xhr.onload = function () {
-               self.onLoad();
-             };
-             xhr.onerror = function () {
-               self.onError(xhr.responseText);
-             };
-           } else {
-             xhr.onreadystatechange = function () {
-               if (xhr.readyState === 2) {
-                 try {
-                   var contentType = xhr.getResponseHeader('Content-Type');
-                   if (self.supportsBinary && contentType === 'application/octet-stream' || contentType === 'application/octet-stream; charset=UTF-8') {
-                     xhr.responseType = 'arraybuffer';
-                   }
-                 } catch (e) {}
-               }
-               if (4 !== xhr.readyState) return;
-               if (200 === xhr.status || 1223 === xhr.status) {
-                 self.onLoad();
-               } else {
-                 // make sure the `error` event handler that's user-set
-                 // does not throw in the same tick and gets caught here
-                 setTimeout(function () {
-                   self.onError(typeof xhr.status === 'number' ? xhr.status : 0);
-                 }, 0);
-               }
-             };
-           }
-
-           debug('xhr data %s', this.data);
-           xhr.send(this.data);
-         } catch (e) {
-           // Need to defer since .create() is called directly fhrom the constructor
-           // and thus the 'error' event can only be only bound *after* this exception
-           // occurs.  Therefore, also, we cannot throw here at all.
-           setTimeout(function () {
-             self.onError(e);
-           }, 0);
-           return;
-         }
-
-         if (typeof document !== 'undefined') {
-           this.index = Request.requestsCount++;
-           Request.requests[this.index] = this;
-         }
-       };
-
-       /**
-        * Called upon successful response.
-        *
-        * @api private
-        */
-
-       Request.prototype.onSuccess = function () {
-         this.emit('success');
-         this.cleanup();
-       };
-
-       /**
-        * Called if we have data.
-        *
-        * @api private
-        */
-
-       Request.prototype.onData = function (data) {
-         this.emit('data', data);
-         this.onSuccess();
-       };
-
-       /**
-        * Called upon error.
-        *
-        * @api private
-        */
-
-       Request.prototype.onError = function (err) {
-         this.emit('error', err);
-         this.cleanup(true);
-       };
-
-       /**
-        * Cleans up house.
-        *
-        * @api private
-        */
-
-       Request.prototype.cleanup = function (fromError) {
-         if ('undefined' === typeof this.xhr || null === this.xhr) {
-           return;
-         }
-         // xmlhttprequest
-         if (this.hasXDR()) {
-           this.xhr.onload = this.xhr.onerror = empty;
-         } else {
-           this.xhr.onreadystatechange = empty;
-         }
-
-         if (fromError) {
-           try {
-             this.xhr.abort();
-           } catch (e) {}
-         }
-
-         if (typeof document !== 'undefined') {
-           delete Request.requests[this.index];
-         }
-
-         this.xhr = null;
-       };
-
-       /**
-        * Called upon load.
-        *
-        * @api private
-        */
-
-       Request.prototype.onLoad = function () {
-         var data;
-         try {
-           var contentType;
-           try {
-             contentType = this.xhr.getResponseHeader('Content-Type');
-           } catch (e) {}
-           if (contentType === 'application/octet-stream' || contentType === 'application/octet-stream; charset=UTF-8') {
-             data = this.xhr.response || this.xhr.responseText;
-           } else {
-             data = this.xhr.responseText;
-           }
-         } catch (e) {
-           this.onError(e);
-         }
-         if (null != data) {
-           this.onData(data);
-         }
-       };
-
-       /**
-        * Check if it has XDomainRequest.
-        *
-        * @api private
-        */
-
-       Request.prototype.hasXDR = function () {
-         return typeof XDomainRequest !== 'undefined' && !this.xs && this.enablesXDR;
-       };
-
-       /**
-        * Aborts the request.
-        *
-        * @api public
-        */
-
-       Request.prototype.abort = function () {
-         this.cleanup();
-       };
-
-       /**
-        * Aborts pending requests when unloading the window. This is needed to prevent
-        * memory leaks (e.g. when using IE) and to ensure that no spurious error is
-        * emitted.
-        */
-
-       Request.requestsCount = 0;
-       Request.requests = {};
-
-       if (typeof document !== 'undefined') {
-         if (typeof attachEvent === 'function') {
-           attachEvent('onunload', unloadHandler);
-         } else if (typeof addEventListener === 'function') {
-           var terminationEvent = 'onpagehide' in globalThis ? 'pagehide' : 'unload';
-           addEventListener(terminationEvent, unloadHandler, false);
-         }
-       }
-
-       function unloadHandler () {
-         for (var i in Request.requests) {
-           if (Request.requests.hasOwnProperty(i)) {
-             Request.requests[i].abort();
-           }
-         }
-       }
-
-
-/***/ },
-/* 7 */
-/***/ function(module, exports, __webpack_require__) {
-
-       /**
-        * Module dependencies.
-        */
-
-       var Transport = __webpack_require__(8);
-       var parseqs = __webpack_require__(19);
-       var parser = __webpack_require__(9);
-       var inherit = __webpack_require__(20);
-       var yeast = __webpack_require__(21);
-       var debug = __webpack_require__(22)('engine.io-client:polling');
-
-       /**
-        * Module exports.
-        */
-
-       module.exports = Polling;
-
-       /**
-        * Is XHR2 supported?
-        */
-
-       var hasXHR2 = (function () {
-         var XMLHttpRequest = __webpack_require__(3);
-         var xhr = new XMLHttpRequest({ xdomain: false });
-         return null != xhr.responseType;
-       })();
-
-       /**
-        * Polling interface.
-        *
-        * @param {Object} opts
-        * @api private
-        */
-
-       function Polling (opts) {
-         var forceBase64 = (opts && opts.forceBase64);
-         if (!hasXHR2 || forceBase64) {
-           this.supportsBinary = false;
-         }
-         Transport.call(this, opts);
-       }
-
-       /**
-        * Inherits from Transport.
-        */
-
-       inherit(Polling, Transport);
-
-       /**
-        * Transport name.
-        */
-
-       Polling.prototype.name = 'polling';
-
-       /**
-        * Opens the socket (triggers polling). We write a PING message to determine
-        * when the transport is open.
-        *
-        * @api private
-        */
-
-       Polling.prototype.doOpen = function () {
-         this.poll();
-       };
-
-       /**
-        * Pauses polling.
-        *
-        * @param {Function} callback upon buffers are flushed and transport is paused
-        * @api private
-        */
-
-       Polling.prototype.pause = function (onPause) {
-         var self = this;
-
-         this.readyState = 'pausing';
-
-         function pause () {
-           debug('paused');
-           self.readyState = 'paused';
-           onPause();
-         }
-
-         if (this.polling || !this.writable) {
-           var total = 0;
-
-           if (this.polling) {
-             debug('we are currently polling - waiting to pause');
-             total++;
-             this.once('pollComplete', function () {
-               debug('pre-pause polling complete');
-               --total || pause();
-             });
-           }
-
-           if (!this.writable) {
-             debug('we are currently writing - waiting to pause');
-             total++;
-             this.once('drain', function () {
-               debug('pre-pause writing complete');
-               --total || pause();
-             });
-           }
-         } else {
-           pause();
-         }
-       };
-
-       /**
-        * Starts polling cycle.
-        *
-        * @api public
-        */
-
-       Polling.prototype.poll = function () {
-         debug('polling');
-         this.polling = true;
-         this.doPoll();
-         this.emit('poll');
-       };
-
-       /**
-        * Overloads onData to detect payloads.
-        *
-        * @api private
-        */
-
-       Polling.prototype.onData = function (data) {
-         var self = this;
-         debug('polling got data %s', data);
-         var callback = function (packet, index, total) {
-           // if its the first message we consider the transport open
-           if ('opening' === self.readyState && packet.type === 'open') {
-             self.onOpen();
-           }
-
-           // if its a close packet, we close the ongoing requests
-           if ('close' === packet.type) {
-             self.onClose();
-             return false;
-           }
-
-           // otherwise bypass onData and handle the message
-           self.onPacket(packet);
-         };
-
-         // decode payload
-         parser.decodePayload(data, this.socket.binaryType, callback);
-
-         // if an event did not trigger closing
-         if ('closed' !== this.readyState) {
-           // if we got data we're not polling
-           this.polling = false;
-           this.emit('pollComplete');
-
-           if ('open' === this.readyState) {
-             this.poll();
-           } else {
-             debug('ignoring poll - transport state "%s"', this.readyState);
-           }
-         }
-       };
-
-       /**
-        * For polling, send a close packet.
-        *
-        * @api private
-        */
-
-       Polling.prototype.doClose = function () {
-         var self = this;
-
-         function close () {
-           debug('writing close packet');
-           self.write([{ type: 'close' }]);
-         }
-
-         if ('open' === this.readyState) {
-           debug('transport open - closing');
-           close();
-         } else {
-           // in case we're trying to close while
-           // handshaking is in progress (GH-164)
-           debug('transport not open - deferring close');
-           this.once('open', close);
-         }
-       };
-
-       /**
-        * Writes a packets payload.
-        *
-        * @param {Array} data packets
-        * @param {Function} drain callback
-        * @api private
-        */
-
-       Polling.prototype.write = function (packets) {
-         var self = this;
-         this.writable = false;
-         var callbackfn = function () {
-           self.writable = true;
-           self.emit('drain');
-         };
-
-         parser.encodePayload(packets, this.supportsBinary, function (data) {
-           self.doWrite(data, callbackfn);
-         });
-       };
-
-       /**
-        * Generates uri for connection.
-        *
-        * @api private
-        */
-
-       Polling.prototype.uri = function () {
-         var query = this.query || {};
-         var schema = this.secure ? 'https' : 'http';
-         var port = '';
-
-         // cache busting is forced
-         if (false !== this.timestampRequests) {
-           query[this.timestampParam] = yeast();
-         }
-
-         if (!this.supportsBinary && !query.sid) {
-           query.b64 = 1;
-         }
-
-         query = parseqs.encode(query);
-
-         // avoid port if default for schema
-         if (this.port && (('https' === schema && Number(this.port) !== 443) ||
-            ('http' === schema && Number(this.port) !== 80))) {
-           port = ':' + this.port;
-         }
-
-         // prepend ? to query
-         if (query.length) {
-           query = '?' + query;
-         }
-
-         var ipv6 = this.hostname.indexOf(':') !== -1;
-         return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
-       };
-
-
-/***/ },
-/* 8 */
-/***/ function(module, exports, __webpack_require__) {
-
-       /**
-        * Module dependencies.
-        */
-
-       var parser = __webpack_require__(9);
-       var Emitter = __webpack_require__(18);
-
-       /**
-        * Module exports.
-        */
-
-       module.exports = Transport;
-
-       /**
-        * Transport abstract constructor.
-        *
-        * @param {Object} options.
-        * @api private
-        */
-
-       function Transport (opts) {
-         this.path = opts.path;
-         this.hostname = opts.hostname;
-         this.port = opts.port;
-         this.secure = opts.secure;
-         this.query = opts.query;
-         this.timestampParam = opts.timestampParam;
-         this.timestampRequests = opts.timestampRequests;
-         this.readyState = '';
-         this.agent = opts.agent || false;
-         this.socket = opts.socket;
-         this.enablesXDR = opts.enablesXDR;
-         this.withCredentials = opts.withCredentials;
-
-         // SSL options for Node.js client
-         this.pfx = opts.pfx;
-         this.key = opts.key;
-         this.passphrase = opts.passphrase;
-         this.cert = opts.cert;
-         this.ca = opts.ca;
-         this.ciphers = opts.ciphers;
-         this.rejectUnauthorized = opts.rejectUnauthorized;
-         this.forceNode = opts.forceNode;
-
-         // results of ReactNative environment detection
-         this.isReactNative = opts.isReactNative;
-
-         // other options for Node.js client
-         this.extraHeaders = opts.extraHeaders;
-         this.localAddress = opts.localAddress;
-       }
-
-       /**
-        * Mix in `Emitter`.
-        */
-
-       Emitter(Transport.prototype);
-
-       /**
-        * Emits an error.
-        *
-        * @param {String} str
-        * @return {Transport} for chaining
-        * @api public
-        */
-
-       Transport.prototype.onError = function (msg, desc) {
-         var err = new Error(msg);
-         err.type = 'TransportError';
-         err.description = desc;
-         this.emit('error', err);
-         return this;
-       };
-
-       /**
-        * Opens the transport.
-        *
-        * @api public
-        */
-
-       Transport.prototype.open = function () {
-         if ('closed' === this.readyState || '' === this.readyState) {
-           this.readyState = 'opening';
-           this.doOpen();
-         }
-
-         return this;
-       };
-
-       /**
-        * Closes the transport.
-        *
-        * @api private
-        */
-
-       Transport.prototype.close = function () {
-         if ('opening' === this.readyState || 'open' === this.readyState) {
-           this.doClose();
-           this.onClose();
-         }
-
-         return this;
-       };
-
-       /**
-        * Sends multiple packets.
-        *
-        * @param {Array} packets
-        * @api private
-        */
-
-       Transport.prototype.send = function (packets) {
-         if ('open' === this.readyState) {
-           this.write(packets);
-         } else {
-           throw new Error('Transport not open');
-         }
-       };
-
-       /**
-        * Called upon open
-        *
-        * @api private
-        */
-
-       Transport.prototype.onOpen = function () {
-         this.readyState = 'open';
-         this.writable = true;
-         this.emit('open');
-       };
-
-       /**
-        * Called with data.
-        *
-        * @param {String} data
-        * @api private
-        */
-
-       Transport.prototype.onData = function (data) {
-         var packet = parser.decodePacket(data, this.socket.binaryType);
-         this.onPacket(packet);
-       };
-
-       /**
-        * Called with a decoded packet.
-        */
-
-       Transport.prototype.onPacket = function (packet) {
-         this.emit('packet', packet);
-       };
-
-       /**
-        * Called upon close.
-        *
-        * @api private
-        */
-
-       Transport.prototype.onClose = function () {
-         this.readyState = 'closed';
-         this.emit('close');
-       };
-
-
-/***/ },
-/* 9 */
-/***/ function(module, exports, __webpack_require__) {
-
-       /**
-        * Module dependencies.
-        */
-
-       var keys = __webpack_require__(10);
-       var hasBinary = __webpack_require__(11);
-       var sliceBuffer = __webpack_require__(13);
-       var after = __webpack_require__(14);
-       var utf8 = __webpack_require__(15);
-
-       var base64encoder;
-       if (typeof ArrayBuffer !== 'undefined') {
-         base64encoder = __webpack_require__(16);
-       }
-
-       /**
-        * Check if we are running an android browser. That requires us to use
-        * ArrayBuffer with polling transports...
-        *
-        * http://ghinda.net/jpeg-blob-ajax-android/
-        */
-
-       var isAndroid = typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent);
-
-       /**
-        * Check if we are running in PhantomJS.
-        * Uploading a Blob with PhantomJS does not work correctly, as reported here:
-        * https://github.com/ariya/phantomjs/issues/11395
-        * @type boolean
-        */
-       var isPhantomJS = typeof navigator !== 'undefined' && /PhantomJS/i.test(navigator.userAgent);
-
-       /**
-        * When true, avoids using Blobs to encode payloads.
-        * @type boolean
-        */
-       var dontSendBlobs = isAndroid || isPhantomJS;
-
-       /**
-        * Current protocol version.
-        */
-
-       exports.protocol = 3;
-
-       /**
-        * Packet types.
-        */
-
-       var packets = exports.packets = {
-           open:     0    // non-ws
-         , close:    1    // non-ws
-         , ping:     2
-         , pong:     3
-         , message:  4
-         , upgrade:  5
-         , noop:     6
-       };
-
-       var packetslist = keys(packets);
-
-       /**
-        * Premade error packet.
-        */
-
-       var err = { type: 'error', data: 'parser error' };
-
-       /**
-        * Create a blob api even for blob builder when vendor prefixes exist
-        */
-
-       var Blob = __webpack_require__(17);
-
-       /**
-        * Encodes a packet.
-        *
-        *     <packet type id> [ <data> ]
-        *
-        * Example:
-        *
-        *     5hello world
-        *     3
-        *     4
-        *
-        * Binary is encoded in an identical principle
-        *
-        * @api private
-        */
-
-       exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
-         if (typeof supportsBinary === 'function') {
-           callback = supportsBinary;
-           supportsBinary = false;
-         }
-
-         if (typeof utf8encode === 'function') {
-           callback = utf8encode;
-           utf8encode = null;
-         }
-
-         var data = (packet.data === undefined)
-           ? undefined
-           : packet.data.buffer || packet.data;
-
-         if (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer) {
-           return encodeArrayBuffer(packet, supportsBinary, callback);
-         } else if (typeof Blob !== 'undefined' && data instanceof Blob) {
-           return encodeBlob(packet, supportsBinary, callback);
-         }
-
-         // might be an object with { base64: true, data: dataAsBase64String }
-         if (data && data.base64) {
-           return encodeBase64Object(packet, callback);
-         }
-
-         // Sending data as a utf-8 string
-         var encoded = packets[packet.type];
-
-         // data fragment is optional
-         if (undefined !== packet.data) {
-           encoded += utf8encode ? utf8.encode(String(packet.data), { strict: false }) : String(packet.data);
-         }
-
-         return callback('' + encoded);
-
-       };
-
-       function encodeBase64Object(packet, callback) {
-         // packet data is an object { base64: true, data: dataAsBase64String }
-         var message = 'b' + exports.packets[packet.type] + packet.data.data;
-         return callback(message);
-       }
-
-       /**
-        * Encode packet helpers for binary types
-        */
-
-       function encodeArrayBuffer(packet, supportsBinary, callback) {
-         if (!supportsBinary) {
-           return exports.encodeBase64Packet(packet, callback);
-         }
-
-         var data = packet.data;
-         var contentArray = new Uint8Array(data);
-         var resultBuffer = new Uint8Array(1 + data.byteLength);
-
-         resultBuffer[0] = packets[packet.type];
-         for (var i = 0; i < contentArray.length; i++) {
-           resultBuffer[i+1] = contentArray[i];
-         }
-
-         return callback(resultBuffer.buffer);
-       }
-
-       function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
-         if (!supportsBinary) {
-           return exports.encodeBase64Packet(packet, callback);
-         }
-
-         var fr = new FileReader();
-         fr.onload = function() {
-           exports.encodePacket({ type: packet.type, data: fr.result }, supportsBinary, true, callback);
-         };
-         return fr.readAsArrayBuffer(packet.data);
-       }
-
-       function encodeBlob(packet, supportsBinary, callback) {
-         if (!supportsBinary) {
-           return exports.encodeBase64Packet(packet, callback);
-         }
-
-         if (dontSendBlobs) {
-           return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
-         }
-
-         var length = new Uint8Array(1);
-         length[0] = packets[packet.type];
-         var blob = new Blob([length.buffer, packet.data]);
-
-         return callback(blob);
-       }
-
-       /**
-        * Encodes a packet with binary data in a base64 string
-        *
-        * @param {Object} packet, has `type` and `data`
-        * @return {String} base64 encoded message
-        */
-
-       exports.encodeBase64Packet = function(packet, callback) {
-         var message = 'b' + exports.packets[packet.type];
-         if (typeof Blob !== 'undefined' && packet.data instanceof Blob) {
-           var fr = new FileReader();
-           fr.onload = function() {
-             var b64 = fr.result.split(',')[1];
-             callback(message + b64);
-           };
-           return fr.readAsDataURL(packet.data);
-         }
-
-         var b64data;
-         try {
-           b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
-         } catch (e) {
-           // iPhone Safari doesn't let you apply with typed arrays
-           var typed = new Uint8Array(packet.data);
-           var basic = new Array(typed.length);
-           for (var i = 0; i < typed.length; i++) {
-             basic[i] = typed[i];
-           }
-           b64data = String.fromCharCode.apply(null, basic);
-         }
-         message += btoa(b64data);
-         return callback(message);
-       };
-
-       /**
-        * Decodes a packet. Changes format to Blob if requested.
-        *
-        * @return {Object} with `type` and `data` (if any)
-        * @api private
-        */
-
-       exports.decodePacket = function (data, binaryType, utf8decode) {
-         if (data === undefined) {
-           return err;
-         }
-         // String data
-         if (typeof data === 'string') {
-           if (data.charAt(0) === 'b') {
-             return exports.decodeBase64Packet(data.substr(1), binaryType);
-           }
-
-           if (utf8decode) {
-             data = tryDecode(data);
-             if (data === false) {
-               return err;
-             }
-           }
-           var type = data.charAt(0);
-
-           if (Number(type) != type || !packetslist[type]) {
-             return err;
-           }
-
-           if (data.length > 1) {
-             return { type: packetslist[type], data: data.substring(1) };
-           } else {
-             return { type: packetslist[type] };
-           }
-         }
-
-         var asArray = new Uint8Array(data);
-         var type = asArray[0];
-         var rest = sliceBuffer(data, 1);
-         if (Blob && binaryType === 'blob') {
-           rest = new Blob([rest]);
-         }
-         return { type: packetslist[type], data: rest };
-       };
-
-       function tryDecode(data) {
-         try {
-           data = utf8.decode(data, { strict: false });
-         } catch (e) {
-           return false;
-         }
-         return data;
-       }
-
-       /**
-        * Decodes a packet encoded in a base64 string
-        *
-        * @param {String} base64 encoded message
-        * @return {Object} with `type` and `data` (if any)
-        */
-
-       exports.decodeBase64Packet = function(msg, binaryType) {
-         var type = packetslist[msg.charAt(0)];
-         if (!base64encoder) {
-           return { type: type, data: { base64: true, data: msg.substr(1) } };
-         }
-
-         var data = base64encoder.decode(msg.substr(1));
-
-         if (binaryType === 'blob' && Blob) {
-           data = new Blob([data]);
-         }
-
-         return { type: type, data: data };
-       };
-
-       /**
-        * Encodes multiple messages (payload).
-        *
-        *     <length>:data
-        *
-        * Example:
-        *
-        *     11:hello world2:hi
-        *
-        * If any contents are binary, they will be encoded as base64 strings. Base64
-        * encoded strings are marked with a b before the length specifier
-        *
-        * @param {Array} packets
-        * @api private
-        */
-
-       exports.encodePayload = function (packets, supportsBinary, callback) {
-         if (typeof supportsBinary === 'function') {
-           callback = supportsBinary;
-           supportsBinary = null;
-         }
-
-         var isBinary = hasBinary(packets);
-
-         if (supportsBinary && isBinary) {
-           if (Blob && !dontSendBlobs) {
-             return exports.encodePayloadAsBlob(packets, callback);
-           }
-
-           return exports.encodePayloadAsArrayBuffer(packets, callback);
-         }
-
-         if (!packets.length) {
-           return callback('0:');
-         }
-
-         function setLengthHeader(message) {
-           return message.length + ':' + message;
-         }
-
-         function encodeOne(packet, doneCallback) {
-           exports.encodePacket(packet, !isBinary ? false : supportsBinary, false, function(message) {
-             doneCallback(null, setLengthHeader(message));
-           });
-         }
-
-         map(packets, encodeOne, function(err, results) {
-           return callback(results.join(''));
-         });
-       };
-
-       /**
-        * Async array map using after
-        */
-
-       function map(ary, each, done) {
-         var result = new Array(ary.length);
-         var next = after(ary.length, done);
-
-         var eachWithIndex = function(i, el, cb) {
-           each(el, function(error, msg) {
-             result[i] = msg;
-             cb(error, result);
-           });
-         };
-
-         for (var i = 0; i < ary.length; i++) {
-           eachWithIndex(i, ary[i], next);
-         }
-       }
-
-       /*
-        * Decodes data when a payload is maybe expected. Possible binary contents are
-        * decoded from their base64 representation
-        *
-        * @param {String} data, callback method
-        * @api public
-        */
-
-       exports.decodePayload = function (data, binaryType, callback) {
-         if (typeof data !== 'string') {
-           return exports.decodePayloadAsBinary(data, binaryType, callback);
-         }
-
-         if (typeof binaryType === 'function') {
-           callback = binaryType;
-           binaryType = null;
-         }
-
-         var packet;
-         if (data === '') {
-           // parser error - ignoring payload
-           return callback(err, 0, 1);
-         }
-
-         var length = '', n, msg;
-
-         for (var i = 0, l = data.length; i < l; i++) {
-           var chr = data.charAt(i);
-
-           if (chr !== ':') {
-             length += chr;
-             continue;
-           }
-
-           if (length === '' || (length != (n = Number(length)))) {
-             // parser error - ignoring payload
-             return callback(err, 0, 1);
-           }
-
-           msg = data.substr(i + 1, n);
-
-           if (length != msg.length) {
-             // parser error - ignoring payload
-             return callback(err, 0, 1);
-           }
-
-           if (msg.length) {
-             packet = exports.decodePacket(msg, binaryType, false);
-
-             if (err.type === packet.type && err.data === packet.data) {
-               // parser error in individual packet - ignoring payload
-               return callback(err, 0, 1);
-             }
-
-             var ret = callback(packet, i + n, l);
-             if (false === ret) return;
-           }
-
-           // advance cursor
-           i += n;
-           length = '';
-         }
-
-         if (length !== '') {
-           // parser error - ignoring payload
-           return callback(err, 0, 1);
-         }
-
-       };
-
-       /**
-        * Encodes multiple messages (payload) as binary.
-        *
-        * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
-        * 255><data>
-        *
-        * Example:
-        * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
-        *
-        * @param {Array} packets
-        * @return {ArrayBuffer} encoded payload
-        * @api private
-        */
-
-       exports.encodePayloadAsArrayBuffer = function(packets, callback) {
-         if (!packets.length) {
-           return callback(new ArrayBuffer(0));
-         }
-
-         function encodeOne(packet, doneCallback) {
-           exports.encodePacket(packet, true, true, function(data) {
-             return doneCallback(null, data);
-           });
-         }
-
-         map(packets, encodeOne, function(err, encodedPackets) {
-           var totalLength = encodedPackets.reduce(function(acc, p) {
-             var len;
-             if (typeof p === 'string'){
-               len = p.length;
-             } else {
-               len = p.byteLength;
-             }
-             return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
-           }, 0);
-
-           var resultArray = new Uint8Array(totalLength);
-
-           var bufferIndex = 0;
-           encodedPackets.forEach(function(p) {
-             var isString = typeof p === 'string';
-             var ab = p;
-             if (isString) {
-               var view = new Uint8Array(p.length);
-               for (var i = 0; i < p.length; i++) {
-                 view[i] = p.charCodeAt(i);
-               }
-               ab = view.buffer;
-             }
-
-             if (isString) { // not true binary
-               resultArray[bufferIndex++] = 0;
-             } else { // true binary
-               resultArray[bufferIndex++] = 1;
-             }
-
-             var lenStr = ab.byteLength.toString();
-             for (var i = 0; i < lenStr.length; i++) {
-               resultArray[bufferIndex++] = parseInt(lenStr[i]);
-             }
-             resultArray[bufferIndex++] = 255;
-
-             var view = new Uint8Array(ab);
-             for (var i = 0; i < view.length; i++) {
-               resultArray[bufferIndex++] = view[i];
-             }
-           });
-
-           return callback(resultArray.buffer);
-         });
-       };
-
-       /**
-        * Encode as Blob
-        */
-
-       exports.encodePayloadAsBlob = function(packets, callback) {
-         function encodeOne(packet, doneCallback) {
-           exports.encodePacket(packet, true, true, function(encoded) {
-             var binaryIdentifier = new Uint8Array(1);
-             binaryIdentifier[0] = 1;
-             if (typeof encoded === 'string') {
-               var view = new Uint8Array(encoded.length);
-               for (var i = 0; i < encoded.length; i++) {
-                 view[i] = encoded.charCodeAt(i);
-               }
-               encoded = view.buffer;
-               binaryIdentifier[0] = 0;
-             }
-
-             var len = (encoded instanceof ArrayBuffer)
-               ? encoded.byteLength
-               : encoded.size;
-
-             var lenStr = len.toString();
-             var lengthAry = new Uint8Array(lenStr.length + 1);
-             for (var i = 0; i < lenStr.length; i++) {
-               lengthAry[i] = parseInt(lenStr[i]);
-             }
-             lengthAry[lenStr.length] = 255;
-
-             if (Blob) {
-               var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
-               doneCallback(null, blob);
-             }
-           });
-         }
-
-         map(packets, encodeOne, function(err, results) {
-           return callback(new Blob(results));
-         });
-       };
-
-       /*
-        * Decodes data when a payload is maybe expected. Strings are decoded by
-        * interpreting each byte as a key code for entries marked to start with 0. See
-        * description of encodePayloadAsBinary
-        *
-        * @param {ArrayBuffer} data, callback method
-        * @api public
-        */
-
-       exports.decodePayloadAsBinary = function (data, binaryType, callback) {
-         if (typeof binaryType === 'function') {
-           callback = binaryType;
-           binaryType = null;
-         }
-
-         var bufferTail = data;
-         var buffers = [];
-
-         while (bufferTail.byteLength > 0) {
-           var tailArray = new Uint8Array(bufferTail);
-           var isString = tailArray[0] === 0;
-           var msgLength = '';
-
-           for (var i = 1; ; i++) {
-             if (tailArray[i] === 255) break;
-
-             // 310 = char length of Number.MAX_VALUE
-             if (msgLength.length > 310) {
-               return callback(err, 0, 1);
-             }
-
-             msgLength += tailArray[i];
-           }
-
-           bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
-           msgLength = parseInt(msgLength);
-
-           var msg = sliceBuffer(bufferTail, 0, msgLength);
-           if (isString) {
-             try {
-               msg = String.fromCharCode.apply(null, new Uint8Array(msg));
-             } catch (e) {
-               // iPhone Safari doesn't let you apply to typed arrays
-               var typed = new Uint8Array(msg);
-               msg = '';
-               for (var i = 0; i < typed.length; i++) {
-                 msg += String.fromCharCode(typed[i]);
-               }
-             }
-           }
-
-           buffers.push(msg);
-           bufferTail = sliceBuffer(bufferTail, msgLength);
-         }
-
-         var total = buffers.length;
-         buffers.forEach(function(buffer, i) {
-           callback(exports.decodePacket(buffer, binaryType, true), i, total);
-         });
-       };
-
-
-/***/ },
-/* 10 */
-/***/ function(module, exports) {
-
-       
-       /**
-        * Gets the keys for an object.
-        *
-        * @return {Array} keys
-        * @api private
-        */
-
-       module.exports = Object.keys || function keys (obj){
-         var arr = [];
-         var has = Object.prototype.hasOwnProperty;
-
-         for (var i in obj) {
-           if (has.call(obj, i)) {
-             arr.push(i);
-           }
-         }
-         return arr;
-       };
-
-
-/***/ },
-/* 11 */
-/***/ function(module, exports, __webpack_require__) {
-
-       /* global Blob File */
-
-       /*
-        * Module requirements.
-        */
-
-       var isArray = __webpack_require__(12);
-
-       var toString = Object.prototype.toString;
-       var withNativeBlob = typeof Blob === 'function' ||
-                               typeof Blob !== 'undefined' && toString.call(Blob) === '[object BlobConstructor]';
-       var withNativeFile = typeof File === 'function' ||
-                               typeof File !== 'undefined' && toString.call(File) === '[object FileConstructor]';
-
-       /**
-        * Module exports.
-        */
-
-       module.exports = hasBinary;
-
-       /**
-        * Checks for binary data.
-        *
-        * Supports Buffer, ArrayBuffer, Blob and File.
-        *
-        * @param {Object} anything
-        * @api public
-        */
-
-       function hasBinary (obj) {
-         if (!obj || typeof obj !== 'object') {
-           return false;
-         }
-
-         if (isArray(obj)) {
-           for (var i = 0, l = obj.length; i < l; i++) {
-             if (hasBinary(obj[i])) {
-               return true;
-             }
-           }
-           return false;
-         }
-
-         if ((typeof Buffer === 'function' && Buffer.isBuffer && Buffer.isBuffer(obj)) ||
-           (typeof ArrayBuffer === 'function' && obj instanceof ArrayBuffer) ||
-           (withNativeBlob && obj instanceof Blob) ||
-           (withNativeFile && obj instanceof File)
-         ) {
-           return true;
-         }
-
-         // see: https://github.com/Automattic/has-binary/pull/4
-         if (obj.toJSON && typeof obj.toJSON === 'function' && arguments.length === 1) {
-           return hasBinary(obj.toJSON(), true);
-         }
-
-         for (var key in obj) {
-           if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
-             return true;
-           }
-         }
-
-         return false;
-       }
-
-
-/***/ },
-/* 12 */
-/***/ function(module, exports) {
-
-       var toString = {}.toString;
-
-       module.exports = Array.isArray || function (arr) {
-         return toString.call(arr) == '[object Array]';
-       };
-
-
-/***/ },
-/* 13 */
-/***/ function(module, exports) {
-
-       /**
-        * An abstraction for slicing an arraybuffer even when
-        * ArrayBuffer.prototype.slice is not supported
-        *
-        * @api public
-        */
-
-       module.exports = function(arraybuffer, start, end) {
-         var bytes = arraybuffer.byteLength;
-         start = start || 0;
-         end = end || bytes;
-
-         if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
-
-         if (start < 0) { start += bytes; }
-         if (end < 0) { end += bytes; }
-         if (end > bytes) { end = bytes; }
-
-         if (start >= bytes || start >= end || bytes === 0) {
-           return new ArrayBuffer(0);
-         }
-
-         var abv = new Uint8Array(arraybuffer);
-         var result = new Uint8Array(end - start);
-         for (var i = start, ii = 0; i < end; i++, ii++) {
-           result[ii] = abv[i];
-         }
-         return result.buffer;
-       };
-
-
-/***/ },
-/* 14 */
-/***/ function(module, exports) {
-
-       module.exports = after
-
-       function after(count, callback, err_cb) {
-           var bail = false
-           err_cb = err_cb || noop
-           proxy.count = count
-
-           return (count === 0) ? callback() : proxy
-
-           function proxy(err, result) {
-               if (proxy.count <= 0) {
-                   throw new Error('after called too many times')
-               }
-               --proxy.count
-
-               // after first error, rest are passed to err_cb
-               if (err) {
-                   bail = true
-                   callback(err)
-                   // future error callbacks will go to error handler
-                   callback = err_cb
-               } else if (proxy.count === 0 && !bail) {
-                   callback(null, result)
-               }
-           }
-       }
-
-       function noop() {}
-
-
-/***/ },
-/* 15 */
-/***/ function(module, exports) {
-
-       /*! https://mths.be/utf8js v2.1.2 by @mathias */
-
-       var stringFromCharCode = String.fromCharCode;
-
-       // Taken from https://mths.be/punycode
-       function ucs2decode(string) {
-               var output = [];
-               var counter = 0;
-               var length = string.length;
-               var value;
-               var 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;
-       }
-
-       // Taken from https://mths.be/punycode
-       function ucs2encode(array) {
-               var length = array.length;
-               var index = -1;
-               var value;
-               var output = '';
-               while (++index < length) {
-                       value = array[index];
-                       if (value > 0xFFFF) {
-                               value -= 0x10000;
-                               output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
-                               value = 0xDC00 | value & 0x3FF;
-                       }
-                       output += stringFromCharCode(value);
-               }
-               return output;
-       }
-
-       function checkScalarValue(codePoint, strict) {
-               if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {
-                       if (strict) {
-                               throw Error(
-                                       'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +
-                                       ' is not a scalar value'
-                               );
-                       }
-                       return false;
-               }
-               return true;
-       }
-       /*--------------------------------------------------------------------------*/
-
-       function createByte(codePoint, shift) {
-               return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
-       }
-
-       function encodeCodePoint(codePoint, strict) {
-               if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
-                       return stringFromCharCode(codePoint);
-               }
-               var symbol = '';
-               if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
-                       symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
-               }
-               else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
-                       if (!checkScalarValue(codePoint, strict)) {
-                               codePoint = 0xFFFD;
-                       }
-                       symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
-                       symbol += createByte(codePoint, 6);
-               }
-               else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
-                       symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
-                       symbol += createByte(codePoint, 12);
-                       symbol += createByte(codePoint, 6);
-               }
-               symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
-               return symbol;
-       }
-
-       function utf8encode(string, opts) {
-               opts = opts || {};
-               var strict = false !== opts.strict;
-
-               var codePoints = ucs2decode(string);
-               var length = codePoints.length;
-               var index = -1;
-               var codePoint;
-               var byteString = '';
-               while (++index < length) {
-                       codePoint = codePoints[index];
-                       byteString += encodeCodePoint(codePoint, strict);
-               }
-               return byteString;
-       }
-
-       /*--------------------------------------------------------------------------*/
-
-       function readContinuationByte() {
-               if (byteIndex >= byteCount) {
-                       throw Error('Invalid byte index');
-               }
-
-               var continuationByte = byteArray[byteIndex] & 0xFF;
-               byteIndex++;
-
-               if ((continuationByte & 0xC0) == 0x80) {
-                       return continuationByte & 0x3F;
-               }
-
-               // If we end up here, it’s not a continuation byte
-               throw Error('Invalid continuation byte');
-       }
-
-       function decodeSymbol(strict) {
-               var byte1;
-               var byte2;
-               var byte3;
-               var byte4;
-               var codePoint;
-
-               if (byteIndex > byteCount) {
-                       throw Error('Invalid byte index');
-               }
-
-               if (byteIndex == byteCount) {
-                       return false;
-               }
-
-               // Read first byte
-               byte1 = byteArray[byteIndex] & 0xFF;
-               byteIndex++;
-
-               // 1-byte sequence (no continuation bytes)
-               if ((byte1 & 0x80) == 0) {
-                       return byte1;
-               }
-
-               // 2-byte sequence
-               if ((byte1 & 0xE0) == 0xC0) {
-                       byte2 = readContinuationByte();
-                       codePoint = ((byte1 & 0x1F) << 6) | byte2;
-                       if (codePoint >= 0x80) {
-                               return codePoint;
-                       } else {
-                               throw Error('Invalid continuation byte');
-                       }
-               }
-
-               // 3-byte sequence (may include unpaired surrogates)
-               if ((byte1 & 0xF0) == 0xE0) {
-                       byte2 = readContinuationByte();
-                       byte3 = readContinuationByte();
-                       codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
-                       if (codePoint >= 0x0800) {
-                               return checkScalarValue(codePoint, strict) ? codePoint : 0xFFFD;
-                       } else {
-                               throw Error('Invalid continuation byte');
-                       }
-               }
-
-               // 4-byte sequence
-               if ((byte1 & 0xF8) == 0xF0) {
-                       byte2 = readContinuationByte();
-                       byte3 = readContinuationByte();
-                       byte4 = readContinuationByte();
-                       codePoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0C) |
-                               (byte3 << 0x06) | byte4;
-                       if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
-                               return codePoint;
-                       }
-               }
-
-               throw Error('Invalid UTF-8 detected');
-       }
-
-       var byteArray;
-       var byteCount;
-       var byteIndex;
-       function utf8decode(byteString, opts) {
-               opts = opts || {};
-               var strict = false !== opts.strict;
-
-               byteArray = ucs2decode(byteString);
-               byteCount = byteArray.length;
-               byteIndex = 0;
-               var codePoints = [];
-               var tmp;
-               while ((tmp = decodeSymbol(strict)) !== false) {
-                       codePoints.push(tmp);
-               }
-               return ucs2encode(codePoints);
-       }
-
-       module.exports = {
-               version: '2.1.2',
-               encode: utf8encode,
-               decode: utf8decode
-       };
-
-
-/***/ },
-/* 16 */
-/***/ function(module, exports) {
-
-       /*
-        * base64-arraybuffer
-        * https://github.com/niklasvh/base64-arraybuffer
-        *
-        * Copyright (c) 2012 Niklas von Hertzen
-        * Licensed under the MIT license.
-        */
-       (function(){
-         "use strict";
-
-         var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
-
-         // Use a lookup table to find the index.
-         var lookup = new Uint8Array(256);
-         for (var i = 0; i < chars.length; i++) {
-           lookup[chars.charCodeAt(i)] = i;
-         }
-
-         exports.encode = function(arraybuffer) {
-           var bytes = new Uint8Array(arraybuffer),
-           i, len = bytes.length, base64 = "";
-
-           for (i = 0; i < len; i+=3) {
-             base64 += chars[bytes[i] >> 2];
-             base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
-             base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
-             base64 += chars[bytes[i + 2] & 63];
-           }
-
-           if ((len % 3) === 2) {
-             base64 = base64.substring(0, base64.length - 1) + "=";
-           } else if (len % 3 === 1) {
-             base64 = base64.substring(0, base64.length - 2) + "==";
-           }
-
-           return base64;
-         };
-
-         exports.decode =  function(base64) {
-           var bufferLength = base64.length * 0.75,
-           len = base64.length, i, p = 0,
-           encoded1, encoded2, encoded3, encoded4;
-
-           if (base64[base64.length - 1] === "=") {
-             bufferLength--;
-             if (base64[base64.length - 2] === "=") {
-               bufferLength--;
-             }
-           }
-
-           var arraybuffer = new ArrayBuffer(bufferLength),
-           bytes = new Uint8Array(arraybuffer);
-
-           for (i = 0; i < len; i+=4) {
-             encoded1 = lookup[base64.charCodeAt(i)];
-             encoded2 = lookup[base64.charCodeAt(i+1)];
-             encoded3 = lookup[base64.charCodeAt(i+2)];
-             encoded4 = lookup[base64.charCodeAt(i+3)];
-
-             bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
-             bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
-             bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
-           }
-
-           return arraybuffer;
-         };
-       })();
-
-
-/***/ },
-/* 17 */
-/***/ function(module, exports) {
-
-       /**\r
-        * Create a blob builder even when vendor prefixes exist\r
-        */\r
-\r
-       var BlobBuilder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :\r
-         typeof WebKitBlobBuilder !== 'undefined' ? WebKitBlobBuilder :\r
-         typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :\r
-         typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : \r
-         false;\r
-\r
-       /**\r
-        * Check if Blob constructor is supported\r
-        */\r
-\r
-       var blobSupported = (function() {\r
-         try {\r
-           var a = new Blob(['hi']);\r
-           return a.size === 2;\r
-         } catch(e) {\r
-           return false;\r
-         }\r
-       })();\r
-\r
-       /**\r
-        * Check if Blob constructor supports ArrayBufferViews\r
-        * Fails in Safari 6, so we need to map to ArrayBuffers there.\r
-        */\r
-\r
-       var blobSupportsArrayBufferView = blobSupported && (function() {\r
-         try {\r
-           var b = new Blob([new Uint8Array([1,2])]);\r
-           return b.size === 2;\r
-         } catch(e) {\r
-           return false;\r
-         }\r
-       })();\r
-\r
-       /**\r
-        * Check if BlobBuilder is supported\r
-        */\r
-\r
-       var blobBuilderSupported = BlobBuilder\r
-         && BlobBuilder.prototype.append\r
-         && BlobBuilder.prototype.getBlob;\r
-\r
-       /**\r
-        * Helper function that maps ArrayBufferViews to ArrayBuffers\r
-        * Used by BlobBuilder constructor and old browsers that didn't\r
-        * support it in the Blob constructor.\r
-        */\r
-\r
-       function mapArrayBufferViews(ary) {\r
-         return ary.map(function(chunk) {\r
-           if (chunk.buffer instanceof ArrayBuffer) {\r
-             var buf = chunk.buffer;\r
-\r
-             // if this is a subarray, make a copy so we only\r
-             // include the subarray region from the underlying buffer\r
-             if (chunk.byteLength !== buf.byteLength) {\r
-               var copy = new Uint8Array(chunk.byteLength);\r
-               copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));\r
-               buf = copy.buffer;\r
-             }\r
-\r
-             return buf;\r
-           }\r
-\r
-           return chunk;\r
-         });\r
-       }\r
-\r
-       function BlobBuilderConstructor(ary, options) {\r
-         options = options || {};\r
-\r
-         var bb = new BlobBuilder();\r
-         mapArrayBufferViews(ary).forEach(function(part) {\r
-           bb.append(part);\r
-         });\r
-\r
-         return (options.type) ? bb.getBlob(options.type) : bb.getBlob();\r
-       };\r
-\r
-       function BlobConstructor(ary, options) {\r
-         return new Blob(mapArrayBufferViews(ary), options || {});\r
-       };\r
-\r
-       if (typeof Blob !== 'undefined') {\r
-         BlobBuilderConstructor.prototype = Blob.prototype;\r
-         BlobConstructor.prototype = Blob.prototype;\r
-       }\r
-\r
-       module.exports = (function() {\r
-         if (blobSupported) {\r
-           return blobSupportsArrayBufferView ? Blob : BlobConstructor;\r
-         } else if (blobBuilderSupported) {\r
-           return BlobBuilderConstructor;\r
-         } else {\r
-           return undefined;\r
-         }\r
-       })();\r
-
-
-/***/ },
-/* 18 */
-/***/ function(module, exports, __webpack_require__) {
-
-       \r
-       /**\r
-        * Expose `Emitter`.\r
-        */\r
-\r
-       if (true) {\r
-         module.exports = Emitter;\r
-       }\r
-\r
-       /**\r
-        * Initialize a new `Emitter`.\r
-        *\r
-        * @api public\r
-        */\r
-\r
-       function Emitter(obj) {\r
-         if (obj) return mixin(obj);\r
-       };\r
-\r
-       /**\r
-        * Mixin the emitter properties.\r
-        *\r
-        * @param {Object} obj\r
-        * @return {Object}\r
-        * @api private\r
-        */\r
-\r
-       function mixin(obj) {\r
-         for (var key in Emitter.prototype) {\r
-           obj[key] = Emitter.prototype[key];\r
-         }\r
-         return obj;\r
-       }\r
-\r
-       /**\r
-        * Listen on the given `event` with `fn`.\r
-        *\r
-        * @param {String} event\r
-        * @param {Function} fn\r
-        * @return {Emitter}\r
-        * @api public\r
-        */\r
-\r
-       Emitter.prototype.on =\r
-       Emitter.prototype.addEventListener = function(event, fn){\r
-         this._callbacks = this._callbacks || {};\r
-         (this._callbacks['$' + event] = this._callbacks['$' + event] || [])\r
-           .push(fn);\r
-         return this;\r
-       };\r
-\r
-       /**\r
-        * Adds an `event` listener that will be invoked a single\r
-        * time then automatically removed.\r
-        *\r
-        * @param {String} event\r
-        * @param {Function} fn\r
-        * @return {Emitter}\r
-        * @api public\r
-        */\r
-\r
-       Emitter.prototype.once = function(event, fn){\r
-         function on() {\r
-           this.off(event, on);\r
-           fn.apply(this, arguments);\r
-         }\r
-\r
-         on.fn = fn;\r
-         this.on(event, on);\r
-         return this;\r
-       };\r
-\r
-       /**\r
-        * Remove the given callback for `event` or all\r
-        * registered callbacks.\r
-        *\r
-        * @param {String} event\r
-        * @param {Function} fn\r
-        * @return {Emitter}\r
-        * @api public\r
-        */\r
-\r
-       Emitter.prototype.off =\r
-       Emitter.prototype.removeListener =\r
-       Emitter.prototype.removeAllListeners =\r
-       Emitter.prototype.removeEventListener = function(event, fn){\r
-         this._callbacks = this._callbacks || {};\r
-\r
-         // all\r
-         if (0 == arguments.length) {\r
-           this._callbacks = {};\r
-           return this;\r
-         }\r
-\r
-         // specific event\r
-         var callbacks = this._callbacks['$' + event];\r
-         if (!callbacks) return this;\r
-\r
-         // remove all handlers\r
-         if (1 == arguments.length) {\r
-           delete this._callbacks['$' + event];\r
-           return this;\r
-         }\r
-\r
-         // remove specific handler\r
-         var cb;\r
-         for (var i = 0; i < callbacks.length; i++) {\r
-           cb = callbacks[i];\r
-           if (cb === fn || cb.fn === fn) {\r
-             callbacks.splice(i, 1);\r
-             break;\r
-           }\r
-         }\r
-\r
-         // Remove event specific arrays for event types that no\r
-         // one is subscribed for to avoid memory leak.\r
-         if (callbacks.length === 0) {\r
-           delete this._callbacks['$' + event];\r
-         }\r
-\r
-         return this;\r
-       };\r
-\r
-       /**\r
-        * Emit `event` with the given args.\r
-        *\r
-        * @param {String} event\r
-        * @param {Mixed} ...\r
-        * @return {Emitter}\r
-        */\r
-\r
-       Emitter.prototype.emit = function(event){\r
-         this._callbacks = this._callbacks || {};\r
-\r
-         var args = new Array(arguments.length - 1)\r
-           , callbacks = this._callbacks['$' + event];\r
-\r
-         for (var i = 1; i < arguments.length; i++) {\r
-           args[i - 1] = arguments[i];\r
-         }\r
-\r
-         if (callbacks) {\r
-           callbacks = callbacks.slice(0);\r
-           for (var i = 0, len = callbacks.length; i < len; ++i) {\r
-             callbacks[i].apply(this, args);\r
-           }\r
-         }\r
-\r
-         return this;\r
-       };\r
-\r
-       /**\r
-        * Return array of callbacks for `event`.\r
-        *\r
-        * @param {String} event\r
-        * @return {Array}\r
-        * @api public\r
-        */\r
-\r
-       Emitter.prototype.listeners = function(event){\r
-         this._callbacks = this._callbacks || {};\r
-         return this._callbacks['$' + event] || [];\r
-       };\r
-\r
-       /**\r
-        * Check if this emitter has `event` handlers.\r
-        *\r
-        * @param {String} event\r
-        * @return {Boolean}\r
-        * @api public\r
-        */\r
-\r
-       Emitter.prototype.hasListeners = function(event){\r
-         return !! this.listeners(event).length;\r
-       };\r
-
-
-/***/ },
-/* 19 */
-/***/ function(module, exports) {
-
-       /**
-        * Compiles a querystring
-        * Returns string representation of the object
-        *
-        * @param {Object}
-        * @api private
-        */
-
-       exports.encode = function (obj) {
-         var str = '';
-
-         for (var i in obj) {
-           if (obj.hasOwnProperty(i)) {
-             if (str.length) str += '&';
-             str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
-           }
-         }
-
-         return str;
-       };
-
-       /**
-        * Parses a simple querystring into an object
-        *
-        * @param {String} qs
-        * @api private
-        */
-
-       exports.decode = function(qs){
-         var qry = {};
-         var pairs = qs.split('&');
-         for (var i = 0, l = pairs.length; i < l; i++) {
-           var pair = pairs[i].split('=');
-           qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
-         }
-         return qry;
-       };
-
-
-/***/ },
-/* 20 */
-/***/ function(module, exports) {
-
-       
-       module.exports = function(a, b){
-         var fn = function(){};
-         fn.prototype = b.prototype;
-         a.prototype = new fn;
-         a.prototype.constructor = a;
-       };
-
-/***/ },
-/* 21 */
-/***/ function(module, exports) {
-
-       'use strict';
-
-       var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('')
-         , length = 64
-         , map = {}
-         , seed = 0
-         , i = 0
-         , prev;
-
-       /**
-        * Return a string representing the specified number.
-        *
-        * @param {Number} num The number to convert.
-        * @returns {String} The string representation of the number.
-        * @api public
-        */
-       function encode(num) {
-         var encoded = '';
-
-         do {
-           encoded = alphabet[num % length] + encoded;
-           num = Math.floor(num / length);
-         } while (num > 0);
-
-         return encoded;
-       }
-
-       /**
-        * Return the integer value specified by the given string.
-        *
-        * @param {String} str The string to convert.
-        * @returns {Number} The integer value represented by the string.
-        * @api public
-        */
-       function decode(str) {
-         var decoded = 0;
-
-         for (i = 0; i < str.length; i++) {
-           decoded = decoded * length + map[str.charAt(i)];
-         }
-
-         return decoded;
-       }
-
-       /**
-        * Yeast: A tiny growing id generator.
-        *
-        * @returns {String} A unique id.
-        * @api public
-        */
-       function yeast() {
-         var now = encode(+new Date());
-
-         if (now !== prev) return seed = 0, prev = now;
-         return now +'.'+ encode(seed++);
-       }
-
-       //
-       // Map each character to its index.
-       //
-       for (; i < length; i++) map[alphabet[i]] = i;
-
-       //
-       // Expose the `yeast`, `encode` and `decode` functions.
-       //
-       yeast.encode = encode;
-       yeast.decode = decode;
-       module.exports = yeast;
-
-
-/***/ },
-/* 22 */
-/***/ function(module, exports, __webpack_require__) {
-
-       /* WEBPACK VAR INJECTION */(function(process) {'use strict';
-
-       var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
-
-       /**
-        * This is the web browser implementation of `debug()`.
-        *
-        * Expose `debug()` as the module.
-        */
-
-       exports = module.exports = __webpack_require__(24);
-       exports.log = log;
-       exports.formatArgs = formatArgs;
-       exports.save = save;
-       exports.load = load;
-       exports.useColors = useColors;
-       exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage();
-
-       /**
-        * Colors.
-        */
-
-       exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
-
-       /**
-        * Currently only WebKit-based Web Inspectors, Firefox >= v31,
-        * and the Firebug extension (any Firefox version) are known
-        * to support "%c" CSS customizations.
-        *
-        * TODO: add a `localStorage` variable to explicitly enable/disable colors
-        */
-
-       function useColors() {
-         // NB: In an Electron preload script, document will be defined but not fully
-         // initialized. Since we know we're in Chrome, we'll just detect this case
-         // explicitly
-         if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
-           return true;
-         }
-
-         // Internet Explorer and Edge do not support colors.
-         if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
-           return false;
-         }
-
-         // is webkit? http://stackoverflow.com/a/16459606/376773
-         // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
-         return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance ||
-         // is firebug? http://stackoverflow.com/a/398120/376773
-         typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) ||
-         // is firefox >= v31?
-         // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
-         typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 ||
-         // double check webkit in userAgent just in case we are in a worker
-         typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
-       }
-
-       /**
-        * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
-        */
-
-       exports.formatters.j = function (v) {
-         try {
-           return JSON.stringify(v);
-         } catch (err) {
-           return '[UnexpectedJSONParseError]: ' + err.message;
-         }
-       };
-
-       /**
-        * Colorize log arguments if enabled.
-        *
-        * @api public
-        */
-
-       function formatArgs(args) {
-         var useColors = this.useColors;
-
-         args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff);
-
-         if (!useColors) return;
-
-         var c = 'color: ' + this.color;
-         args.splice(1, 0, c, 'color: inherit');
-
-         // the final "%c" is somewhat tricky, because there could be other
-         // arguments passed either before or after the %c, so we need to
-         // figure out the correct index to insert the CSS into
-         var index = 0;
-         var lastC = 0;
-         args[0].replace(/%[a-zA-Z%]/g, function (match) {
-           if ('%%' === match) return;
-           index++;
-           if ('%c' === match) {
-             // we only are interested in the *last* %c
-             // (the user may have provided their own)
-             lastC = index;
-           }
-         });
-
-         args.splice(lastC, 0, c);
-       }
-
-       /**
-        * Invokes `console.log()` when available.
-        * No-op when `console.log` is not a "function".
-        *
-        * @api public
-        */
-
-       function log() {
-         // this hackery is required for IE8/9, where
-         // the `console.log` function doesn't have 'apply'
-         return 'object' === (typeof console === 'undefined' ? 'undefined' : _typeof(console)) && console.log && Function.prototype.apply.call(console.log, console, arguments);
-       }
-
-       /**
-        * Save `namespaces`.
-        *
-        * @param {String} namespaces
-        * @api private
-        */
-
-       function save(namespaces) {
-         try {
-           if (null == namespaces) {
-             exports.storage.removeItem('debug');
-           } else {
-             exports.storage.debug = namespaces;
-           }
-         } catch (e) {}
-       }
-
-       /**
-        * Load `namespaces`.
-        *
-        * @return {String} returns the previously persisted debug modes
-        * @api private
-        */
-
-       function load() {
-         var r;
-         try {
-           r = exports.storage.debug;
-         } catch (e) {}
-
-         // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
-         if (!r && typeof process !== 'undefined' && 'env' in process) {
-           r = process.env.DEBUG;
-         }
-
-         return r;
-       }
-
-       /**
-        * Enable namespaces listed in `localStorage.debug` initially.
-        */
-
-       exports.enable(load());
-
-       /**
-        * Localstorage attempts to return the localstorage.
-        *
-        * This is necessary because safari throws
-        * when a user disables cookies/localstorage
-        * and you attempt to access it.
-        *
-        * @return {LocalStorage}
-        * @api private
-        */
-
-       function localstorage() {
-         try {
-           return window.localStorage;
-         } catch (e) {}
-       }
-       /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(23)))
-
-/***/ },
-/* 23 */
-/***/ function(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; };
-
-
-/***/ },
-/* 24 */
-/***/ function(module, exports, __webpack_require__) {
-
-       'use strict';
-
-       /**
-        * This is the common logic for both the Node.js and web browser
-        * implementations of `debug()`.
-        *
-        * Expose `debug()` as the module.
-        */
-
-       exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
-       exports.coerce = coerce;
-       exports.disable = disable;
-       exports.enable = enable;
-       exports.enabled = enabled;
-       exports.humanize = __webpack_require__(25);
-
-       /**
-        * Active `debug` instances.
-        */
-       exports.instances = [];
-
-       /**
-        * The currently active debug mode names, and names to skip.
-        */
-
-       exports.names = [];
-       exports.skips = [];
-
-       /**
-        * Map of special "%n" handling functions, for the debug "format" argument.
-        *
-        * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
-        */
-
-       exports.formatters = {};
-
-       /**
-        * Select a color.
-        * @param {String} namespace
-        * @return {Number}
-        * @api private
-        */
-
-       function selectColor(namespace) {
-         var hash = 0,
-             i;
-
-         for (i in namespace) {
-           hash = (hash << 5) - hash + namespace.charCodeAt(i);
-           hash |= 0; // Convert to 32bit integer
-         }
-
-         return exports.colors[Math.abs(hash) % exports.colors.length];
-       }
-
-       /**
-        * Create a debugger with the given `namespace`.
-        *
-        * @param {String} namespace
-        * @return {Function}
-        * @api public
-        */
-
-       function createDebug(namespace) {
-
-         var prevTime;
-
-         function debug() {
-           // disabled?
-           if (!debug.enabled) return;
-
-           var self = debug;
-
-           // set `diff` timestamp
-           var curr = +new Date();
-           var ms = curr - (prevTime || curr);
-           self.diff = ms;
-           self.prev = prevTime;
-           self.curr = curr;
-           prevTime = curr;
-
-           // turn the `arguments` into a proper Array
-           var args = new Array(arguments.length);
-           for (var i = 0; i < args.length; i++) {
-             args[i] = arguments[i];
-           }
-
-           args[0] = exports.coerce(args[0]);
-
-           if ('string' !== typeof args[0]) {
-             // anything else let's inspect with %O
-             args.unshift('%O');
-           }
-
-           // apply any `formatters` transformations
-           var index = 0;
-           args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
-             // if we encounter an escaped % then don't increase the array index
-             if (match === '%%') return match;
-             index++;
-             var formatter = exports.formatters[format];
-             if ('function' === typeof formatter) {
-               var val = args[index];
-               match = formatter.call(self, val);
-
-               // now we need to remove `args[index]` since it's inlined in the `format`
-               args.splice(index, 1);
-               index--;
-             }
-             return match;
-           });
-
-           // apply env-specific formatting (colors, etc.)
-           exports.formatArgs.call(self, args);
-
-           var logFn = debug.log || exports.log || console.log.bind(console);
-           logFn.apply(self, args);
-         }
-
-         debug.namespace = namespace;
-         debug.enabled = exports.enabled(namespace);
-         debug.useColors = exports.useColors();
-         debug.color = selectColor(namespace);
-         debug.destroy = destroy;
-
-         // env-specific initialization logic for debug instances
-         if ('function' === typeof exports.init) {
-           exports.init(debug);
-         }
-
-         exports.instances.push(debug);
-
-         return debug;
-       }
-
-       function destroy() {
-         var index = exports.instances.indexOf(this);
-         if (index !== -1) {
-           exports.instances.splice(index, 1);
-           return true;
-         } else {
-           return false;
-         }
-       }
-
-       /**
-        * Enables a debug mode by namespaces. This can include modes
-        * separated by a colon and wildcards.
-        *
-        * @param {String} namespaces
-        * @api public
-        */
-
-       function enable(namespaces) {
-         exports.save(namespaces);
-
-         exports.names = [];
-         exports.skips = [];
-
-         var i;
-         var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
-         var len = split.length;
-
-         for (i = 0; i < len; i++) {
-           if (!split[i]) continue; // ignore empty strings
-           namespaces = split[i].replace(/\*/g, '.*?');
-           if (namespaces[0] === '-') {
-             exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
-           } else {
-             exports.names.push(new RegExp('^' + namespaces + '$'));
-           }
-         }
-
-         for (i = 0; i < exports.instances.length; i++) {
-           var instance = exports.instances[i];
-           instance.enabled = exports.enabled(instance.namespace);
-         }
-       }
-
-       /**
-        * Disable debug output.
-        *
-        * @api public
-        */
-
-       function disable() {
-         exports.enable('');
-       }
-
-       /**
-        * Returns true if the given mode name is enabled, false otherwise.
-        *
-        * @param {String} name
-        * @return {Boolean}
-        * @api public
-        */
-
-       function enabled(name) {
-         if (name[name.length - 1] === '*') {
-           return true;
-         }
-         var i, len;
-         for (i = 0, len = exports.skips.length; i < len; i++) {
-           if (exports.skips[i].test(name)) {
-             return false;
-           }
-         }
-         for (i = 0, len = exports.names.length; i < len; i++) {
-           if (exports.names[i].test(name)) {
-             return true;
-           }
-         }
-         return false;
-       }
-
-       /**
-        * Coerce `val`.
-        *
-        * @param {Mixed} val
-        * @return {Mixed}
-        * @api private
-        */
-
-       function coerce(val) {
-         if (val instanceof Error) return val.stack || val.message;
-         return val;
-       }
-
-/***/ },
-/* 25 */
-/***/ function(module, exports) {
-
-       /**
-        * Helpers.
-        */
-
-       var s = 1000;
-       var m = s * 60;
-       var h = m * 60;
-       var d = h * 24;
-       var y = d * 365.25;
-
-       /**
-        * Parse or format the given `val`.
-        *
-        * Options:
-        *
-        *  - `long` verbose formatting [false]
-        *
-        * @param {String|Number} val
-        * @param {Object} [options]
-        * @throws {Error} throw an error if val is not a non-empty string or a number
-        * @return {String|Number}
-        * @api public
-        */
-
-       module.exports = function(val, options) {
-         options = options || {};
-         var type = typeof val;
-         if (type === 'string' && val.length > 0) {
-           return parse(val);
-         } else if (type === 'number' && isNaN(val) === false) {
-           return options.long ? fmtLong(val) : fmtShort(val);
-         }
-         throw new Error(
-           'val is not a non-empty string or a valid number. val=' +
-             JSON.stringify(val)
-         );
-       };
-
-       /**
-        * Parse the given `str` and return milliseconds.
-        *
-        * @param {String} str
-        * @return {Number}
-        * @api private
-        */
-
-       function parse(str) {
-         str = String(str);
-         if (str.length > 100) {
-           return;
-         }
-         var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
-           str
-         );
-         if (!match) {
-           return;
-         }
-         var n = parseFloat(match[1]);
-         var type = (match[2] || 'ms').toLowerCase();
-         switch (type) {
-           case 'years':
-           case 'year':
-           case 'yrs':
-           case 'yr':
-           case 'y':
-             return n * y;
-           case 'days':
-           case 'day':
-           case 'd':
-             return n * d;
-           case 'hours':
-           case 'hour':
-           case 'hrs':
-           case 'hr':
-           case 'h':
-             return n * h;
-           case 'minutes':
-           case 'minute':
-           case 'mins':
-           case 'min':
-           case 'm':
-             return n * m;
-           case 'seconds':
-           case 'second':
-           case 'secs':
-           case 'sec':
-           case 's':
-             return n * s;
-           case 'milliseconds':
-           case 'millisecond':
-           case 'msecs':
-           case 'msec':
-           case 'ms':
-             return n;
-           default:
-             return undefined;
-         }
-       }
-
-       /**
-        * Short format for `ms`.
-        *
-        * @param {Number} ms
-        * @return {String}
-        * @api private
-        */
-
-       function fmtShort(ms) {
-         if (ms >= d) {
-           return Math.round(ms / d) + 'd';
-         }
-         if (ms >= h) {
-           return Math.round(ms / h) + 'h';
-         }
-         if (ms >= m) {
-           return Math.round(ms / m) + 'm';
-         }
-         if (ms >= s) {
-           return Math.round(ms / s) + 's';
-         }
-         return ms + 'ms';
-       }
-
-       /**
-        * Long format for `ms`.
-        *
-        * @param {Number} ms
-        * @return {String}
-        * @api private
-        */
-
-       function fmtLong(ms) {
-         return plural(ms, d, 'day') ||
-           plural(ms, h, 'hour') ||
-           plural(ms, m, 'minute') ||
-           plural(ms, s, 'second') ||
-           ms + ' ms';
-       }
-
-       /**
-        * Pluralization helper.
-        */
-
-       function plural(ms, n, name) {
-         if (ms < n) {
-           return;
-         }
-         if (ms < n * 1.5) {
-           return Math.floor(ms / n) + ' ' + name;
-         }
-         return Math.ceil(ms / n) + ' ' + name + 's';
-       }
-
-
-/***/ },
-/* 26 */
-/***/ function(module, exports, __webpack_require__) {
-
-       /**
-        * Module requirements.
-        */
-
-       var Polling = __webpack_require__(7);
-       var inherit = __webpack_require__(20);
-       var globalThis = __webpack_require__(5);
-
-       /**
-        * Module exports.
-        */
-
-       module.exports = JSONPPolling;
-
-       /**
-        * Cached regular expressions.
-        */
-
-       var rNewline = /\n/g;
-       var rEscapedNewline = /\\n/g;
-
-       /**
-        * Global JSONP callbacks.
-        */
-
-       var callbacks;
-
-       /**
-        * Noop.
-        */
-
-       function empty () { }
-
-       /**
-        * JSONP Polling constructor.
-        *
-        * @param {Object} opts.
-        * @api public
-        */
-
-       function JSONPPolling (opts) {
-         Polling.call(this, opts);
-
-         this.query = this.query || {};
-
-         // define global callbacks array if not present
-         // we do this here (lazily) to avoid unneeded global pollution
-         if (!callbacks) {
-           // we need to consider multiple engines in the same page
-           callbacks = globalThis.___eio = (globalThis.___eio || []);
-         }
-
-         // callback identifier
-         this.index = callbacks.length;
-
-         // add callback to jsonp global
-         var self = this;
-         callbacks.push(function (msg) {
-           self.onData(msg);
-         });
-
-         // append to query string
-         this.query.j = this.index;
-
-         // prevent spurious errors from being emitted when the window is unloaded
-         if (typeof addEventListener === 'function') {
-           addEventListener('beforeunload', function () {
-             if (self.script) self.script.onerror = empty;
-           }, false);
-         }
-       }
-
-       /**
-        * Inherits from Polling.
-        */
-
-       inherit(JSONPPolling, Polling);
-
-       /*
-        * JSONP only supports binary as base64 encoded strings
-        */
-
-       JSONPPolling.prototype.supportsBinary = false;
-
-       /**
-        * Closes the socket.
-        *
-        * @api private
-        */
-
-       JSONPPolling.prototype.doClose = function () {
-         if (this.script) {
-           this.script.parentNode.removeChild(this.script);
-           this.script = null;
-         }
-
-         if (this.form) {
-           this.form.parentNode.removeChild(this.form);
-           this.form = null;
-           this.iframe = null;
-         }
-
-         Polling.prototype.doClose.call(this);
-       };
-
-       /**
-        * Starts a poll cycle.
-        *
-        * @api private
-        */
-
-       JSONPPolling.prototype.doPoll = function () {
-         var self = this;
-         var script = document.createElement('script');
-
-         if (this.script) {
-           this.script.parentNode.removeChild(this.script);
-           this.script = null;
-         }
-
-         script.async = true;
-         script.src = this.uri();
-         script.onerror = function (e) {
-           self.onError('jsonp poll error', e);
-         };
-
-         var insertAt = document.getElementsByTagName('script')[0];
-         if (insertAt) {
-           insertAt.parentNode.insertBefore(script, insertAt);
-         } else {
-           (document.head || document.body).appendChild(script);
-         }
-         this.script = script;
-
-         var isUAgecko = 'undefined' !== typeof navigator && /gecko/i.test(navigator.userAgent);
-
-         if (isUAgecko) {
-           setTimeout(function () {
-             var iframe = document.createElement('iframe');
-             document.body.appendChild(iframe);
-             document.body.removeChild(iframe);
-           }, 100);
-         }
-       };
-
-       /**
-        * Writes with a hidden iframe.
-        *
-        * @param {String} data to send
-        * @param {Function} called upon flush.
-        * @api private
-        */
-
-       JSONPPolling.prototype.doWrite = function (data, fn) {
-         var self = this;
-
-         if (!this.form) {
-           var form = document.createElement('form');
-           var area = document.createElement('textarea');
-           var id = this.iframeId = 'eio_iframe_' + this.index;
-           var iframe;
-
-           form.className = 'socketio';
-           form.style.position = 'absolute';
-           form.style.top = '-1000px';
-           form.style.left = '-1000px';
-           form.target = id;
-           form.method = 'POST';
-           form.setAttribute('accept-charset', 'utf-8');
-           area.name = 'd';
-           form.appendChild(area);
-           document.body.appendChild(form);
-
-           this.form = form;
-           this.area = area;
-         }
-
-         this.form.action = this.uri();
-
-         function complete () {
-           initIframe();
-           fn();
-         }
-
-         function initIframe () {
-           if (self.iframe) {
-             try {
-               self.form.removeChild(self.iframe);
-             } catch (e) {
-               self.onError('jsonp polling iframe removal error', e);
-             }
-           }
-
-           try {
-             // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
-             var html = '<iframe src="javascript:0" name="' + self.iframeId + '">';
-             iframe = document.createElement(html);
-           } catch (e) {
-             iframe = document.createElement('iframe');
-             iframe.name = self.iframeId;
-             iframe.src = 'javascript:0';
-           }
-
-           iframe.id = self.iframeId;
-
-           self.form.appendChild(iframe);
-           self.iframe = iframe;
-         }
-
-         initIframe();
-
-         // escape \n to prevent it from being converted into \r\n by some UAs
-         // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
-         data = data.replace(rEscapedNewline, '\\\n');
-         this.area.value = data.replace(rNewline, '\\n');
-
-         try {
-           this.form.submit();
-         } catch (e) {}
-
-         if (this.iframe.attachEvent) {
-           this.iframe.onreadystatechange = function () {
-             if (self.iframe.readyState === 'complete') {
-               complete();
-             }
-           };
-         } else {
-           this.iframe.onload = complete;
-         }
-       };
-
-
-/***/ },
-/* 27 */
-/***/ function(module, exports, __webpack_require__) {
-
-       /**
-        * Module dependencies.
-        */
-
-       var Transport = __webpack_require__(8);
-       var parser = __webpack_require__(9);
-       var parseqs = __webpack_require__(19);
-       var inherit = __webpack_require__(20);
-       var yeast = __webpack_require__(21);
-       var debug = __webpack_require__(22)('engine.io-client:websocket');
-
-       var BrowserWebSocket, NodeWebSocket;
-
-       if (typeof WebSocket !== 'undefined') {
-         BrowserWebSocket = WebSocket;
-       } else if (typeof self !== 'undefined') {
-         BrowserWebSocket = self.WebSocket || self.MozWebSocket;
-       }
-
-       if (typeof window === 'undefined') {
-         try {
-           NodeWebSocket = __webpack_require__(28);
-         } catch (e) { }
-       }
-
-       /**
-        * Get either the `WebSocket` or `MozWebSocket` globals
-        * in the browser or try to resolve WebSocket-compatible
-        * interface exposed by `ws` for Node-like environment.
-        */
-
-       var WebSocketImpl = BrowserWebSocket || NodeWebSocket;
-
-       /**
-        * Module exports.
-        */
-
-       module.exports = WS;
-
-       /**
-        * WebSocket transport constructor.
-        *
-        * @api {Object} connection options
-        * @api public
-        */
-
-       function WS (opts) {
-         var forceBase64 = (opts && opts.forceBase64);
-         if (forceBase64) {
-           this.supportsBinary = false;
-         }
-         this.perMessageDeflate = opts.perMessageDeflate;
-         this.usingBrowserWebSocket = BrowserWebSocket && !opts.forceNode;
-         this.protocols = opts.protocols;
-         if (!this.usingBrowserWebSocket) {
-           WebSocketImpl = NodeWebSocket;
-         }
-         Transport.call(this, opts);
-       }
-
-       /**
-        * Inherits from Transport.
-        */
-
-       inherit(WS, Transport);
-
-       /**
-        * Transport name.
-        *
-        * @api public
-        */
-
-       WS.prototype.name = 'websocket';
-
-       /*
-        * WebSockets support binary
-        */
-
-       WS.prototype.supportsBinary = true;
-
-       /**
-        * Opens socket.
-        *
-        * @api private
-        */
-
-       WS.prototype.doOpen = function () {
-         if (!this.check()) {
-           // let probe timeout
-           return;
-         }
-
-         var uri = this.uri();
-         var protocols = this.protocols;
-
-         var opts = {};
-
-         if (!this.isReactNative) {
-           opts.agent = this.agent;
-           opts.perMessageDeflate = this.perMessageDeflate;
-
-           // SSL options for Node.js client
-           opts.pfx = this.pfx;
-           opts.key = this.key;
-           opts.passphrase = this.passphrase;
-           opts.cert = this.cert;
-           opts.ca = this.ca;
-           opts.ciphers = this.ciphers;
-           opts.rejectUnauthorized = this.rejectUnauthorized;
-         }
-
-         if (this.extraHeaders) {
-           opts.headers = this.extraHeaders;
-         }
-         if (this.localAddress) {
-           opts.localAddress = this.localAddress;
-         }
-
-         try {
-           this.ws =
-             this.usingBrowserWebSocket && !this.isReactNative
-               ? protocols
-                 ? new WebSocketImpl(uri, protocols)
-                 : new WebSocketImpl(uri)
-               : new WebSocketImpl(uri, protocols, opts);
-         } catch (err) {
-           return this.emit('error', err);
-         }
-
-         if (this.ws.binaryType === undefined) {
-           this.supportsBinary = false;
-         }
-
-         if (this.ws.supports && this.ws.supports.binary) {
-           this.supportsBinary = true;
-           this.ws.binaryType = 'nodebuffer';
-         } else {
-           this.ws.binaryType = 'arraybuffer';
-         }
-
-         this.addEventListeners();
-       };
-
-       /**
-        * Adds event listeners to the socket
-        *
-        * @api private
-        */
-
-       WS.prototype.addEventListeners = function () {
-         var self = this;
-
-         this.ws.onopen = function () {
-           self.onOpen();
-         };
-         this.ws.onclose = function () {
-           self.onClose();
-         };
-         this.ws.onmessage = function (ev) {
-           self.onData(ev.data);
-         };
-         this.ws.onerror = function (e) {
-           self.onError('websocket error', e);
-         };
-       };
-
-       /**
-        * Writes data to socket.
-        *
-        * @param {Array} array of packets.
-        * @api private
-        */
-
-       WS.prototype.write = function (packets) {
-         var self = this;
-         this.writable = false;
-
-         // encodePacket efficient as it uses WS framing
-         // no need for encodePayload
-         var total = packets.length;
-         for (var i = 0, l = total; i < l; i++) {
-           (function (packet) {
-             parser.encodePacket(packet, self.supportsBinary, function (data) {
-               if (!self.usingBrowserWebSocket) {
-                 // always create a new object (GH-437)
-                 var opts = {};
-                 if (packet.options) {
-                   opts.compress = packet.options.compress;
-                 }
-
-                 if (self.perMessageDeflate) {
-                   var len = 'string' === typeof data ? Buffer.byteLength(data) : data.length;
-                   if (len < self.perMessageDeflate.threshold) {
-                     opts.compress = false;
-                   }
-                 }
-               }
-
-               // Sometimes the websocket has already been closed but the browser didn't
-               // have a chance of informing us about it yet, in that case send will
-               // throw an error
-               try {
-                 if (self.usingBrowserWebSocket) {
-                   // TypeError is thrown when passing the second argument on Safari
-                   self.ws.send(data);
-                 } else {
-                   self.ws.send(data, opts);
-                 }
-               } catch (e) {
-                 debug('websocket closed before onclose event');
-               }
-
-               --total || done();
-             });
-           })(packets[i]);
-         }
-
-         function done () {
-           self.emit('flush');
-
-           // fake drain
-           // defer to next tick to allow Socket to clear writeBuffer
-           setTimeout(function () {
-             self.writable = true;
-             self.emit('drain');
-           }, 0);
-         }
-       };
-
-       /**
-        * Called upon close
-        *
-        * @api private
-        */
-
-       WS.prototype.onClose = function () {
-         Transport.prototype.onClose.call(this);
-       };
-
-       /**
-        * Closes socket.
-        *
-        * @api private
-        */
-
-       WS.prototype.doClose = function () {
-         if (typeof this.ws !== 'undefined') {
-           this.ws.close();
-         }
-       };
-
-       /**
-        * Generates uri for connection.
-        *
-        * @api private
-        */
-
-       WS.prototype.uri = function () {
-         var query = this.query || {};
-         var schema = this.secure ? 'wss' : 'ws';
-         var port = '';
-
-         // avoid port if default for schema
-         if (this.port && (('wss' === schema && Number(this.port) !== 443) ||
-           ('ws' === schema && Number(this.port) !== 80))) {
-           port = ':' + this.port;
-         }
-
-         // append timestamp to URI
-         if (this.timestampRequests) {
-           query[this.timestampParam] = yeast();
-         }
-
-         // communicate binary support capabilities
-         if (!this.supportsBinary) {
-           query.b64 = 1;
-         }
-
-         query = parseqs.encode(query);
-
-         // prepend ? to query
-         if (query.length) {
-           query = '?' + query;
-         }
-
-         var ipv6 = this.hostname.indexOf(':') !== -1;
-         return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
-       };
-
-       /**
-        * Feature detection for WebSocket.
-        *
-        * @return {Boolean} whether this transport is available.
-        * @api public
-        */
-
-       WS.prototype.check = function () {
-         return !!WebSocketImpl && !('__initialize' in WebSocketImpl && this.name === WS.prototype.name);
-       };
-
-
-/***/ },
-/* 28 */
-/***/ function(module, exports) {
-
-       /* (ignored) */
-
-/***/ },
-/* 29 */
-/***/ function(module, exports) {
-
-       
-       var indexOf = [].indexOf;
-
-       module.exports = function(arr, obj){
-         if (indexOf) return arr.indexOf(obj);
-         for (var i = 0; i < arr.length; ++i) {
-           if (arr[i] === obj) return i;
-         }
-         return -1;
-       };
-
-/***/ },
-/* 30 */
-/***/ function(module, exports) {
-
-       /**
-        * Parses an URI
-        *
-        * @author Steven Levithan <stevenlevithan.com> (MIT license)
-        * @api private
-        */
-
-       var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
-
-       var parts = [
-           'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
-       ];
-
-       module.exports = function parseuri(str) {
-           var src = str,
-               b = str.indexOf('['),
-               e = str.indexOf(']');
-
-           if (b != -1 && e != -1) {
-               str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
-           }
-
-           var m = re.exec(str || ''),
-               uri = {},
-               i = 14;
-
-           while (i--) {
-               uri[parts[i]] = m[i] || '';
-           }
-
-           if (b != -1 && e != -1) {
-               uri.source = src;
-               uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
-               uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
-               uri.ipv6uri = true;
-           }
-
-           uri.pathNames = pathNames(uri, uri['path']);
-           uri.queryKey = queryKey(uri, uri['query']);
-
-           return uri;
-       };
-
-       function pathNames(obj, path) {
-           var regx = /\/{2,9}/g,
-               names = path.replace(regx, "/").split("/");
-
-           if (path.substr(0, 1) == '/' || path.length === 0) {
-               names.splice(0, 1);
-           }
-           if (path.substr(path.length - 1, 1) == '/') {
-               names.splice(names.length - 1, 1);
-           }
-
-           return names;
-       }
-
-       function queryKey(uri, query) {
-           var data = {};
-
-           query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
-               if ($1) {
-                   data[$1] = $2;
-               }
-           });
-
-           return data;
-       }
-
-
-/***/ }
-/******/ ])
-});
-;
\ No newline at end of file
+!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.eio=e():t.eio=e()}(this,(function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{},id:n,loaded:!1};return t[n].call(o.exports,o,o.exports,r),o.loaded=!0,o.exports}return r.m=t,r.c=e,r.p="",r(0)}([function(t,e,r){t.exports=r(1),t.exports.parser=r(9)},function(t,e,r){var n=r(2),o=r(18),i=r(22)("engine.io-client:socket"),s=r(29),a=r(9),c=r(30),p=r(19);function u(t,e){if(!(this instanceof u))return new u(t,e);e=e||{},t&&"object"==typeof t&&(e=t,t=null),t?(t=c(t),e.hostname=t.host,e.secure="https"===t.protocol||"wss"===t.protocol,e.port=t.port,t.query&&(e.query=t.query)):e.host&&(e.hostname=c(e.host).host),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.agent=e.agent||!1,this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?443:80),this.query=e.query||{},"string"==typeof this.query&&(this.query=p.decode(this.query)),this.upgrade=!1!==e.upgrade,this.path=(e.path||"/engine.io").replace(/\/$/,"")+"/",this.forceJSONP=!!e.forceJSONP,this.jsonp=!1!==e.jsonp,this.forceBase64=!!e.forceBase64,this.enablesXDR=!!e.enablesXDR,this.withCredentials=!1!==e.withCredentials,this.timestampParam=e.timestampParam||"t",this.timestampRequests=e.timestampRequests,this.transports=e.transports||["polling","websocket"],this.transportOptions=e.transportOptions||{},this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.policyPort=e.policyPort||843,this.rememberUpgrade=e.rememberUpgrade||!1,this.binaryType=null,this.onlyBinaryUpgrades=e.onlyBinaryUpgrades,this.perMessageDeflate=!1!==e.perMessageDeflate&&(e.perMessageDeflate||{}),!0===this.perMessageDeflate&&(this.perMessageDeflate={}),this.perMessageDeflate&&null==this.perMessageDeflate.threshold&&(this.perMessageDeflate.threshold=1024),this.pfx=e.pfx||void 0,this.key=e.key||void 0,this.passphrase=e.passphrase||void 0,this.cert=e.cert||void 0,this.ca=e.ca||void 0,this.ciphers=e.ciphers||void 0,this.rejectUnauthorized=void 0===e.rejectUnauthorized||e.rejectUnauthorized,this.forceNode=!!e.forceNode,this.isReactNative="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),("undefined"==typeof self||this.isReactNative)&&(e.extraHeaders&&Object.keys(e.extraHeaders).length>0&&(this.extraHeaders=e.extraHeaders),e.localAddress&&(this.localAddress=e.localAddress)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingIntervalTimer=null,this.pingTimeoutTimer=null,this.open()}t.exports=u,u.priorWebsocketSuccess=!1,o(u.prototype),u.protocol=a.protocol,u.Socket=u,u.Transport=r(8),u.transports=r(2),u.parser=r(9),u.prototype.createTransport=function(t){i('creating transport "%s"',t);var e=function(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);return e}(this.query);e.EIO=a.protocol,e.transport=t;var r=this.transportOptions[t]||{};return this.id&&(e.sid=this.id),new n[t]({query:e,socket:this,agent:r.agent||this.agent,hostname:r.hostname||this.hostname,port:r.port||this.port,secure:r.secure||this.secure,path:r.path||this.path,forceJSONP:r.forceJSONP||this.forceJSONP,jsonp:r.jsonp||this.jsonp,forceBase64:r.forceBase64||this.forceBase64,enablesXDR:r.enablesXDR||this.enablesXDR,withCredentials:r.withCredentials||this.withCredentials,timestampRequests:r.timestampRequests||this.timestampRequests,timestampParam:r.timestampParam||this.timestampParam,policyPort:r.policyPort||this.policyPort,pfx:r.pfx||this.pfx,key:r.key||this.key,passphrase:r.passphrase||this.passphrase,cert:r.cert||this.cert,ca:r.ca||this.ca,ciphers:r.ciphers||this.ciphers,rejectUnauthorized:r.rejectUnauthorized||this.rejectUnauthorized,perMessageDeflate:r.perMessageDeflate||this.perMessageDeflate,extraHeaders:r.extraHeaders||this.extraHeaders,forceNode:r.forceNode||this.forceNode,localAddress:r.localAddress||this.localAddress,requestTimeout:r.requestTimeout||this.requestTimeout,protocols:r.protocols||void 0,isReactNative:this.isReactNative})},u.prototype.open=function(){var t;if(this.rememberUpgrade&&u.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length){var e=this;return void setTimeout((function(){e.emit("error","No transports available")}),0)}t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(t){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)},u.prototype.setTransport=function(t){i("setting transport %s",t.name);var e=this;this.transport&&(i("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=t,t.on("drain",(function(){e.onDrain()})).on("packet",(function(t){e.onPacket(t)})).on("error",(function(t){e.onError(t)})).on("close",(function(){e.onClose("transport close")}))},u.prototype.probe=function(t){i('probing transport "%s"',t);var e=this.createTransport(t,{probe:1}),r=!1,n=this;function o(){if(n.onlyBinaryUpgrades){var o=!this.supportsBinary&&n.transport.supportsBinary;r=r||o}r||(i('probe transport "%s" opened',t),e.send([{type:"ping",data:"probe"}]),e.once("packet",(function(o){if(!r)if("pong"===o.type&&"probe"===o.data){if(i('probe transport "%s" pong',t),n.upgrading=!0,n.emit("upgrading",e),!e)return;u.priorWebsocketSuccess="websocket"===e.name,i('pausing current transport "%s"',n.transport.name),n.transport.pause((function(){r||"closed"!==n.readyState&&(i("changing transport and sending upgrade packet"),f(),n.setTransport(e),e.send([{type:"upgrade"}]),n.emit("upgrade",e),e=null,n.upgrading=!1,n.flush())}))}else{i('probe transport "%s" failed',t);var s=new Error("probe error");s.transport=e.name,n.emit("upgradeError",s)}})))}function s(){r||(r=!0,f(),e.close(),e=null)}function a(r){var o=new Error("probe error: "+r);o.transport=e.name,s(),i('probe transport "%s" failed because of error: %s',t,r),n.emit("upgradeError",o)}function c(){a("transport closed")}function p(){a("socket closed")}function h(t){e&&t.name!==e.name&&(i('"%s" works - aborting "%s"',t.name,e.name),s())}function f(){e.removeListener("open",o),e.removeListener("error",a),e.removeListener("close",c),n.removeListener("close",p),n.removeListener("upgrading",h)}u.priorWebsocketSuccess=!1,e.once("open",o),e.once("error",a),e.once("close",c),this.once("close",p),this.once("upgrading",h),e.open()},u.prototype.onOpen=function(){if(i("socket open"),this.readyState="open",u.priorWebsocketSuccess="websocket"===this.transport.name,this.emit("open"),this.flush(),"open"===this.readyState&&this.upgrade&&this.transport.pause){i("starting upgrade probes");for(var t=0,e=this.upgrades.length;t<e;t++)this.probe(this.upgrades[t])}},u.prototype.onPacket=function(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(i('socket receive: type "%s", data "%s"',t.type,t.data),this.emit("packet",t),this.emit("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"pong":this.setPing(),this.emit("pong");break;case"error":var e=new Error("server error");e.code=t.data,this.onError(e);break;case"message":this.emit("data",t.data),this.emit("message",t.data)}else i('packet received with socket readyState "%s"',this.readyState)},u.prototype.onHandshake=function(t){this.emit("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this.upgrades=this.filterUpgrades(t.upgrades),this.pingInterval=t.pingInterval,this.pingTimeout=t.pingTimeout,this.onOpen(),"closed"!==this.readyState&&(this.setPing(),this.removeListener("heartbeat",this.onHeartbeat),this.on("heartbeat",this.onHeartbeat))},u.prototype.onHeartbeat=function(t){clearTimeout(this.pingTimeoutTimer);var e=this;e.pingTimeoutTimer=setTimeout((function(){"closed"!==e.readyState&&e.onClose("ping timeout")}),t||e.pingInterval+e.pingTimeout)},u.prototype.setPing=function(){var t=this;clearTimeout(t.pingIntervalTimer),t.pingIntervalTimer=setTimeout((function(){i("writing ping packet - expecting pong within %sms",t.pingTimeout),t.ping(),t.onHeartbeat(t.pingTimeout)}),t.pingInterval)},u.prototype.ping=function(){var t=this;this.sendPacket("ping",(function(){t.emit("ping")}))},u.prototype.onDrain=function(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emit("drain"):this.flush()},u.prototype.flush=function(){"closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length&&(i("flushing %d packets in socket",this.writeBuffer.length),this.transport.send(this.writeBuffer),this.prevBufferLen=this.writeBuffer.length,this.emit("flush"))},u.prototype.write=u.prototype.send=function(t,e,r){return this.sendPacket("message",t,e,r),this},u.prototype.sendPacket=function(t,e,r,n){if("function"==typeof e&&(n=e,e=void 0),"function"==typeof r&&(n=r,r=null),"closing"!==this.readyState&&"closed"!==this.readyState){(r=r||{}).compress=!1!==r.compress;var o={type:t,data:e,options:r};this.emit("packetCreate",o),this.writeBuffer.push(o),n&&this.once("flush",n),this.flush()}},u.prototype.close=function(){if("opening"===this.readyState||"open"===this.readyState){this.readyState="closing";var t=this;this.writeBuffer.length?this.once("drain",(function(){this.upgrading?n():e()})):this.upgrading?n():e()}function e(){t.onClose("forced close"),i("socket closing - telling transport to close"),t.transport.close()}function r(){t.removeListener("upgrade",r),t.removeListener("upgradeError",r),e()}function n(){t.once("upgrade",r),t.once("upgradeError",r)}return this},u.prototype.onError=function(t){i("socket error %j",t),u.priorWebsocketSuccess=!1,this.emit("error",t),this.onClose("transport error",t)},u.prototype.onClose=function(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){i('socket close with reason: "%s"',t);clearTimeout(this.pingIntervalTimer),clearTimeout(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),this.readyState="closed",this.id=null,this.emit("close",t,e),this.writeBuffer=[],this.prevBufferLen=0}},u.prototype.filterUpgrades=function(t){for(var e=[],r=0,n=t.length;r<n;r++)~s(this.transports,t[r])&&e.push(t[r]);return e}},function(t,e,r){var n=r(3),o=r(6),i=r(26),s=r(27);e.polling=function(t){var e=!1,r=!1,s=!1!==t.jsonp;if("undefined"!=typeof location){var a="https:"===location.protocol,c=location.port;c||(c=a?443:80),e=t.hostname!==location.hostname||c!==t.port,r=t.secure!==a}if(t.xdomain=e,t.xscheme=r,"open"in new n(t)&&!t.forceJSONP)return new o(t);if(!s)throw new Error("JSONP disabled");return new i(t)},e.websocket=s},function(t,e,r){var n=r(4),o=r(5);t.exports=function(t){var e=t.xdomain,r=t.xscheme,i=t.enablesXDR;try{if("undefined"!=typeof XMLHttpRequest&&(!e||n))return new XMLHttpRequest}catch(t){}try{if("undefined"!=typeof XDomainRequest&&!r&&i)return new XDomainRequest}catch(t){}if(!e)try{return new(o[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}},function(t,e){try{t.exports="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){t.exports=!1}},function(t,e){t.exports="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")()},function(t,e,r){var n=r(3),o=r(7),i=r(18),s=r(20),a=r(22)("engine.io-client:polling-xhr"),c=r(5);function p(){}function u(t){if(o.call(this,t),this.requestTimeout=t.requestTimeout,this.extraHeaders=t.extraHeaders,"undefined"!=typeof location){var e="https:"===location.protocol,r=location.port;r||(r=e?443:80),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||r!==t.port,this.xs=t.secure!==e}}function h(t){this.method=t.method||"GET",this.uri=t.uri,this.xd=!!t.xd,this.xs=!!t.xs,this.async=!1!==t.async,this.data=void 0!==t.data?t.data:null,this.agent=t.agent,this.isBinary=t.isBinary,this.supportsBinary=t.supportsBinary,this.enablesXDR=t.enablesXDR,this.withCredentials=t.withCredentials,this.requestTimeout=t.requestTimeout,this.pfx=t.pfx,this.key=t.key,this.passphrase=t.passphrase,this.cert=t.cert,this.ca=t.ca,this.ciphers=t.ciphers,this.rejectUnauthorized=t.rejectUnauthorized,this.extraHeaders=t.extraHeaders,this.create()}if(t.exports=u,t.exports.Request=h,s(u,o),u.prototype.supportsBinary=!0,u.prototype.request=function(t){return(t=t||{}).uri=this.uri(),t.xd=this.xd,t.xs=this.xs,t.agent=this.agent||!1,t.supportsBinary=this.supportsBinary,t.enablesXDR=this.enablesXDR,t.withCredentials=this.withCredentials,t.pfx=this.pfx,t.key=this.key,t.passphrase=this.passphrase,t.cert=this.cert,t.ca=this.ca,t.ciphers=this.ciphers,t.rejectUnauthorized=this.rejectUnauthorized,t.requestTimeout=this.requestTimeout,t.extraHeaders=this.extraHeaders,new h(t)},u.prototype.doWrite=function(t,e){var r="string"!=typeof t&&void 0!==t,n=this.request({method:"POST",data:t,isBinary:r}),o=this;n.on("success",e),n.on("error",(function(t){o.onError("xhr post error",t)})),this.sendXhr=n},u.prototype.doPoll=function(){a("xhr poll");var t=this.request(),e=this;t.on("data",(function(t){e.onData(t)})),t.on("error",(function(t){e.onError("xhr poll error",t)})),this.pollXhr=t},i(h.prototype),h.prototype.create=function(){var t={agent:this.agent,xdomain:this.xd,xscheme:this.xs,enablesXDR:this.enablesXDR};t.pfx=this.pfx,t.key=this.key,t.passphrase=this.passphrase,t.cert=this.cert,t.ca=this.ca,t.ciphers=this.ciphers,t.rejectUnauthorized=this.rejectUnauthorized;var e=this.xhr=new n(t),r=this;try{a("xhr open %s: %s",this.method,this.uri),e.open(this.method,this.uri,this.async);try{if(this.extraHeaders)for(var o in e.setDisableHeaderCheck&&e.setDisableHeaderCheck(!0),this.extraHeaders)this.extraHeaders.hasOwnProperty(o)&&e.setRequestHeader(o,this.extraHeaders[o])}catch(t){}if("POST"===this.method)try{this.isBinary?e.setRequestHeader("Content-type","application/octet-stream"):e.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{e.setRequestHeader("Accept","*/*")}catch(t){}"withCredentials"in e&&(e.withCredentials=this.withCredentials),this.requestTimeout&&(e.timeout=this.requestTimeout),this.hasXDR()?(e.onload=function(){r.onLoad()},e.onerror=function(){r.onError(e.responseText)}):e.onreadystatechange=function(){if(2===e.readyState)try{var t=e.getResponseHeader("Content-Type");(r.supportsBinary&&"application/octet-stream"===t||"application/octet-stream; charset=UTF-8"===t)&&(e.responseType="arraybuffer")}catch(t){}4===e.readyState&&(200===e.status||1223===e.status?r.onLoad():setTimeout((function(){r.onError("number"==typeof e.status?e.status:0)}),0))},a("xhr data %s",this.data),e.send(this.data)}catch(t){return void setTimeout((function(){r.onError(t)}),0)}"undefined"!=typeof document&&(this.index=h.requestsCount++,h.requests[this.index]=this)},h.prototype.onSuccess=function(){this.emit("success"),this.cleanup()},h.prototype.onData=function(t){this.emit("data",t),this.onSuccess()},h.prototype.onError=function(t){this.emit("error",t),this.cleanup(!0)},h.prototype.cleanup=function(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.hasXDR()?this.xhr.onload=this.xhr.onerror=p:this.xhr.onreadystatechange=p,t)try{this.xhr.abort()}catch(t){}"undefined"!=typeof document&&delete h.requests[this.index],this.xhr=null}},h.prototype.onLoad=function(){var t;try{var e;try{e=this.xhr.getResponseHeader("Content-Type")}catch(t){}t=("application/octet-stream"===e||"application/octet-stream; charset=UTF-8"===e)&&this.xhr.response||this.xhr.responseText}catch(t){this.onError(t)}null!=t&&this.onData(t)},h.prototype.hasXDR=function(){return"undefined"!=typeof XDomainRequest&&!this.xs&&this.enablesXDR},h.prototype.abort=function(){this.cleanup()},h.requestsCount=0,h.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",f);else if("function"==typeof addEventListener){addEventListener("onpagehide"in c?"pagehide":"unload",f,!1)}function f(){for(var t in h.requests)h.requests.hasOwnProperty(t)&&h.requests[t].abort()}},function(t,e,r){var n=r(8),o=r(19),i=r(9),s=r(20),a=r(21),c=r(22)("engine.io-client:polling");t.exports=u;var p=null!=new(r(3))({xdomain:!1}).responseType;function u(t){var e=t&&t.forceBase64;p&&!e||(this.supportsBinary=!1),n.call(this,t)}s(u,n),u.prototype.name="polling",u.prototype.doOpen=function(){this.poll()},u.prototype.pause=function(t){var e=this;function r(){c("paused"),e.readyState="paused",t()}if(this.readyState="pausing",this.polling||!this.writable){var n=0;this.polling&&(c("we are currently polling - waiting to pause"),n++,this.once("pollComplete",(function(){c("pre-pause polling complete"),--n||r()}))),this.writable||(c("we are currently writing - waiting to pause"),n++,this.once("drain",(function(){c("pre-pause writing complete"),--n||r()})))}else r()},u.prototype.poll=function(){c("polling"),this.polling=!0,this.doPoll(),this.emit("poll")},u.prototype.onData=function(t){var e=this;c("polling got data %s",t);i.decodePayload(t,this.socket.binaryType,(function(t,r,n){if("opening"===e.readyState&&"open"===t.type&&e.onOpen(),"close"===t.type)return e.onClose(),!1;e.onPacket(t)})),"closed"!==this.readyState&&(this.polling=!1,this.emit("pollComplete"),"open"===this.readyState?this.poll():c('ignoring poll - transport state "%s"',this.readyState))},u.prototype.doClose=function(){var t=this;function e(){c("writing close packet"),t.write([{type:"close"}])}"open"===this.readyState?(c("transport open - closing"),e()):(c("transport not open - deferring close"),this.once("open",e))},u.prototype.write=function(t){var e=this;this.writable=!1;var r=function(){e.writable=!0,e.emit("drain")};i.encodePayload(t,this.supportsBinary,(function(t){e.doWrite(t,r)}))},u.prototype.uri=function(){var t=this.query||{},e=this.secure?"https":"http",r="";return!1!==this.timestampRequests&&(t[this.timestampParam]=a()),this.supportsBinary||t.sid||(t.b64=1),t=o.encode(t),this.port&&("https"===e&&443!==Number(this.port)||"http"===e&&80!==Number(this.port))&&(r=":"+this.port),t.length&&(t="?"+t),e+"://"+(-1!==this.hostname.indexOf(":")?"["+this.hostname+"]":this.hostname)+r+this.path+t}},function(t,e,r){var n=r(9),o=r(18);function i(t){this.path=t.path,this.hostname=t.hostname,this.port=t.port,this.secure=t.secure,this.query=t.query,this.timestampParam=t.timestampParam,this.timestampRequests=t.timestampRequests,this.readyState="",this.agent=t.agent||!1,this.socket=t.socket,this.enablesXDR=t.enablesXDR,this.withCredentials=t.withCredentials,this.pfx=t.pfx,this.key=t.key,this.passphrase=t.passphrase,this.cert=t.cert,this.ca=t.ca,this.ciphers=t.ciphers,this.rejectUnauthorized=t.rejectUnauthorized,this.forceNode=t.forceNode,this.isReactNative=t.isReactNative,this.extraHeaders=t.extraHeaders,this.localAddress=t.localAddress}t.exports=i,o(i.prototype),i.prototype.onError=function(t,e){var r=new Error(t);return r.type="TransportError",r.description=e,this.emit("error",r),this},i.prototype.open=function(){return"closed"!==this.readyState&&""!==this.readyState||(this.readyState="opening",this.doOpen()),this},i.prototype.close=function(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this},i.prototype.send=function(t){if("open"!==this.readyState)throw new Error("Transport not open");this.write(t)},i.prototype.onOpen=function(){this.readyState="open",this.writable=!0,this.emit("open")},i.prototype.onData=function(t){var e=n.decodePacket(t,this.socket.binaryType);this.onPacket(e)},i.prototype.onPacket=function(t){this.emit("packet",t)},i.prototype.onClose=function(){this.readyState="closed",this.emit("close")}},function(t,e,r){var n,o=r(10),i=r(11),s=r(13),a=r(14),c=r(15);"undefined"!=typeof ArrayBuffer&&(n=r(16));var p="undefined"!=typeof navigator&&/Android/i.test(navigator.userAgent),u="undefined"!=typeof navigator&&/PhantomJS/i.test(navigator.userAgent),h=p||u;e.protocol=3;var f=e.packets={open:0,close:1,ping:2,pong:3,message:4,upgrade:5,noop:6},l=o(f),d={type:"error",data:"parser error"},y=r(17);function g(t,e,r){for(var n=new Array(t.length),o=a(t.length,r),i=function(t,r,o){e(r,(function(e,r){n[t]=r,o(e,n)}))},s=0;s<t.length;s++)i(s,t[s],o)}e.encodePacket=function(t,r,n,o){"function"==typeof r&&(o=r,r=!1),"function"==typeof n&&(o=n,n=null);var i=void 0===t.data?void 0:t.data.buffer||t.data;if("undefined"!=typeof ArrayBuffer&&i instanceof ArrayBuffer)return function(t,r,n){if(!r)return e.encodeBase64Packet(t,n);var o=t.data,i=new Uint8Array(o),s=new Uint8Array(1+o.byteLength);s[0]=f[t.type];for(var a=0;a<i.length;a++)s[a+1]=i[a];return n(s.buffer)}(t,r,o);if(void 0!==y&&i instanceof y)return function(t,r,n){if(!r)return e.encodeBase64Packet(t,n);if(h)return function(t,r,n){if(!r)return e.encodeBase64Packet(t,n);var o=new FileReader;return o.onload=function(){e.encodePacket({type:t.type,data:o.result},r,!0,n)},o.readAsArrayBuffer(t.data)}(t,r,n);var o=new Uint8Array(1);o[0]=f[t.type];var i=new y([o.buffer,t.data]);return n(i)}(t,r,o);if(i&&i.base64)return function(t,r){var n="b"+e.packets[t.type]+t.data.data;return r(n)}(t,o);var s=f[t.type];return void 0!==t.data&&(s+=n?c.encode(String(t.data),{strict:!1}):String(t.data)),o(""+s)},e.encodeBase64Packet=function(t,r){var n,o="b"+e.packets[t.type];if(void 0!==y&&t.data instanceof y){var i=new FileReader;return i.onload=function(){var t=i.result.split(",")[1];r(o+t)},i.readAsDataURL(t.data)}try{n=String.fromCharCode.apply(null,new Uint8Array(t.data))}catch(e){for(var s=new Uint8Array(t.data),a=new Array(s.length),c=0;c<s.length;c++)a[c]=s[c];n=String.fromCharCode.apply(null,a)}return o+=btoa(n),r(o)},e.decodePacket=function(t,r,n){if(void 0===t)return d;if("string"==typeof t){if("b"===t.charAt(0))return e.decodeBase64Packet(t.substr(1),r);if(n&&!1===(t=function(t){try{t=c.decode(t,{strict:!1})}catch(t){return!1}return t}(t)))return d;var o=t.charAt(0);return Number(o)==o&&l[o]?t.length>1?{type:l[o],data:t.substring(1)}:{type:l[o]}:d}o=new Uint8Array(t)[0];var i=s(t,1);return y&&"blob"===r&&(i=new y([i])),{type:l[o],data:i}},e.decodeBase64Packet=function(t,e){var r=l[t.charAt(0)];if(!n)return{type:r,data:{base64:!0,data:t.substr(1)}};var o=n.decode(t.substr(1));return"blob"===e&&y&&(o=new y([o])),{type:r,data:o}},e.encodePayload=function(t,r,n){"function"==typeof r&&(n=r,r=null);var o=i(t);if(r&&o)return y&&!h?e.encodePayloadAsBlob(t,n):e.encodePayloadAsArrayBuffer(t,n);if(!t.length)return n("0:");g(t,(function(t,n){e.encodePacket(t,!!o&&r,!1,(function(t){n(null,function(t){return t.length+":"+t}(t))}))}),(function(t,e){return n(e.join(""))}))},e.decodePayload=function(t,r,n){if("string"!=typeof t)return e.decodePayloadAsBinary(t,r,n);var o;if("function"==typeof r&&(n=r,r=null),""===t)return n(d,0,1);for(var i,s,a="",c=0,p=t.length;c<p;c++){var u=t.charAt(c);if(":"===u){if(""===a||a!=(i=Number(a)))return n(d,0,1);if(a!=(s=t.substr(c+1,i)).length)return n(d,0,1);if(s.length){if(o=e.decodePacket(s,r,!1),d.type===o.type&&d.data===o.data)return n(d,0,1);if(!1===n(o,c+i,p))return}c+=i,a=""}else a+=u}return""!==a?n(d,0,1):void 0},e.encodePayloadAsArrayBuffer=function(t,r){if(!t.length)return r(new ArrayBuffer(0));g(t,(function(t,r){e.encodePacket(t,!0,!0,(function(t){return r(null,t)}))}),(function(t,e){var n=e.reduce((function(t,e){var r;return t+(r="string"==typeof e?e.length:e.byteLength).toString().length+r+2}),0),o=new Uint8Array(n),i=0;return e.forEach((function(t){var e="string"==typeof t,r=t;if(e){for(var n=new Uint8Array(t.length),s=0;s<t.length;s++)n[s]=t.charCodeAt(s);r=n.buffer}o[i++]=e?0:1;var a=r.byteLength.toString();for(s=0;s<a.length;s++)o[i++]=parseInt(a[s]);o[i++]=255;for(n=new Uint8Array(r),s=0;s<n.length;s++)o[i++]=n[s]})),r(o.buffer)}))},e.encodePayloadAsBlob=function(t,r){g(t,(function(t,r){e.encodePacket(t,!0,!0,(function(t){var e=new Uint8Array(1);if(e[0]=1,"string"==typeof t){for(var n=new Uint8Array(t.length),o=0;o<t.length;o++)n[o]=t.charCodeAt(o);t=n.buffer,e[0]=0}var i=(t instanceof ArrayBuffer?t.byteLength:t.size).toString(),s=new Uint8Array(i.length+1);for(o=0;o<i.length;o++)s[o]=parseInt(i[o]);if(s[i.length]=255,y){var a=new y([e.buffer,s.buffer,t]);r(null,a)}}))}),(function(t,e){return r(new y(e))}))},e.decodePayloadAsBinary=function(t,r,n){"function"==typeof r&&(n=r,r=null);for(var o=t,i=[];o.byteLength>0;){for(var a=new Uint8Array(o),c=0===a[0],p="",u=1;255!==a[u];u++){if(p.length>310)return n(d,0,1);p+=a[u]}o=s(o,2+p.length),p=parseInt(p);var h=s(o,0,p);if(c)try{h=String.fromCharCode.apply(null,new Uint8Array(h))}catch(t){var f=new Uint8Array(h);h="";for(u=0;u<f.length;u++)h+=String.fromCharCode(f[u])}i.push(h),o=s(o,p)}var l=i.length;i.forEach((function(t,o){n(e.decodePacket(t,r,!0),o,l)}))}},function(t,e){t.exports=Object.keys||function(t){var e=[],r=Object.prototype.hasOwnProperty;for(var n in t)r.call(t,n)&&e.push(n);return e}},function(t,e,r){var n=r(12),o=Object.prototype.toString,i="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===o.call(Blob),s="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===o.call(File);t.exports=function t(e){if(!e||"object"!=typeof e)return!1;if(n(e)){for(var r=0,o=e.length;r<o;r++)if(t(e[r]))return!0;return!1}if("function"==typeof Buffer&&Buffer.isBuffer&&Buffer.isBuffer(e)||"function"==typeof ArrayBuffer&&e instanceof ArrayBuffer||i&&e instanceof Blob||s&&e instanceof File)return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return t(e.toJSON(),!0);for(var a in e)if(Object.prototype.hasOwnProperty.call(e,a)&&t(e[a]))return!0;return!1}},function(t,e){var r={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==r.call(t)}},function(t,e){t.exports=function(t,e,r){var n=t.byteLength;if(e=e||0,r=r||n,t.slice)return t.slice(e,r);if(e<0&&(e+=n),r<0&&(r+=n),r>n&&(r=n),e>=n||e>=r||0===n)return new ArrayBuffer(0);for(var o=new Uint8Array(t),i=new Uint8Array(r-e),s=e,a=0;s<r;s++,a++)i[a]=o[s];return i.buffer}},function(t,e){function r(){}t.exports=function(t,e,n){var o=!1;return n=n||r,i.count=t,0===t?e():i;function i(t,r){if(i.count<=0)throw new Error("after called too many times");--i.count,t?(o=!0,e(t),e=n):0!==i.count||o||e(null,r)}}},function(t,e){
+/*! https://mths.be/utf8js v2.1.2 by @mathias */
+var r,n,o,i=String.fromCharCode;function s(t){for(var e,r,n=[],o=0,i=t.length;o<i;)(e=t.charCodeAt(o++))>=55296&&e<=56319&&o<i?56320==(64512&(r=t.charCodeAt(o++)))?n.push(((1023&e)<<10)+(1023&r)+65536):(n.push(e),o--):n.push(e);return n}function a(t,e){if(t>=55296&&t<=57343){if(e)throw Error("Lone surrogate U+"+t.toString(16).toUpperCase()+" is not a scalar value");return!1}return!0}function c(t,e){return i(t>>e&63|128)}function p(t,e){if(0==(4294967168&t))return i(t);var r="";return 0==(4294965248&t)?r=i(t>>6&31|192):0==(4294901760&t)?(a(t,e)||(t=65533),r=i(t>>12&15|224),r+=c(t,6)):0==(4292870144&t)&&(r=i(t>>18&7|240),r+=c(t,12),r+=c(t,6)),r+=i(63&t|128)}function u(){if(o>=n)throw Error("Invalid byte index");var t=255&r[o];if(o++,128==(192&t))return 63&t;throw Error("Invalid continuation byte")}function h(t){var e,i;if(o>n)throw Error("Invalid byte index");if(o==n)return!1;if(e=255&r[o],o++,0==(128&e))return e;if(192==(224&e)){if((i=(31&e)<<6|u())>=128)return i;throw Error("Invalid continuation byte")}if(224==(240&e)){if((i=(15&e)<<12|u()<<6|u())>=2048)return a(i,t)?i:65533;throw Error("Invalid continuation byte")}if(240==(248&e)&&(i=(7&e)<<18|u()<<12|u()<<6|u())>=65536&&i<=1114111)return i;throw Error("Invalid UTF-8 detected")}t.exports={version:"2.1.2",encode:function(t,e){for(var r=!1!==(e=e||{}).strict,n=s(t),o=n.length,i=-1,a="";++i<o;)a+=p(n[i],r);return a},decode:function(t,e){var a=!1!==(e=e||{}).strict;r=s(t),n=r.length,o=0;for(var c,p=[];!1!==(c=h(a));)p.push(c);return function(t){for(var e,r=t.length,n=-1,o="";++n<r;)(e=t[n])>65535&&(o+=i((e-=65536)>>>10&1023|55296),e=56320|1023&e),o+=i(e);return o}(p)}}},function(t,e){!function(){"use strict";for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",r=new Uint8Array(256),n=0;n<t.length;n++)r[t.charCodeAt(n)]=n;e.encode=function(e){var r,n=new Uint8Array(e),o=n.length,i="";for(r=0;r<o;r+=3)i+=t[n[r]>>2],i+=t[(3&n[r])<<4|n[r+1]>>4],i+=t[(15&n[r+1])<<2|n[r+2]>>6],i+=t[63&n[r+2]];return o%3==2?i=i.substring(0,i.length-1)+"=":o%3==1&&(i=i.substring(0,i.length-2)+"=="),i},e.decode=function(t){var e,n,o,i,s,a=.75*t.length,c=t.length,p=0;"="===t[t.length-1]&&(a--,"="===t[t.length-2]&&a--);var u=new ArrayBuffer(a),h=new Uint8Array(u);for(e=0;e<c;e+=4)n=r[t.charCodeAt(e)],o=r[t.charCodeAt(e+1)],i=r[t.charCodeAt(e+2)],s=r[t.charCodeAt(e+3)],h[p++]=n<<2|o>>4,h[p++]=(15&o)<<4|i>>2,h[p++]=(3&i)<<6|63&s;return u}}()},function(t,e){var r=void 0!==r?r:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder&&MozBlobBuilder,n=function(){try{return 2===new Blob(["hi"]).size}catch(t){return!1}}(),o=n&&function(){try{return 2===new Blob([new Uint8Array([1,2])]).size}catch(t){return!1}}(),i=r&&r.prototype.append&&r.prototype.getBlob;function s(t){return t.map((function(t){if(t.buffer instanceof ArrayBuffer){var e=t.buffer;if(t.byteLength!==e.byteLength){var r=new Uint8Array(t.byteLength);r.set(new Uint8Array(e,t.byteOffset,t.byteLength)),e=r.buffer}return e}return t}))}function a(t,e){e=e||{};var n=new r;return s(t).forEach((function(t){n.append(t)})),e.type?n.getBlob(e.type):n.getBlob()}function c(t,e){return new Blob(s(t),e||{})}"undefined"!=typeof Blob&&(a.prototype=Blob.prototype,c.prototype=Blob.prototype),t.exports=n?o?Blob:c:i?a:void 0},function(t,e,r){function n(t){if(t)return function(t){for(var e in n.prototype)t[e]=n.prototype[e];return t}(t)}t.exports=n,n.prototype.on=n.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},n.prototype.once=function(t,e){function r(){this.off(t,r),e.apply(this,arguments)}return r.fn=e,this.on(t,r),this},n.prototype.off=n.prototype.removeListener=n.prototype.removeAllListeners=n.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+t];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var o=0;o<n.length;o++)if((r=n[o])===e||r.fn===e){n.splice(o,1);break}return 0===n.length&&delete this._callbacks["$"+t],this},n.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),r=this._callbacks["$"+t],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(r){n=0;for(var o=(r=r.slice(0)).length;n<o;++n)r[n].apply(this,e)}return this},n.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},n.prototype.hasListeners=function(t){return!!this.listeners(t).length}},function(t,e){e.encode=function(t){var e="";for(var r in t)t.hasOwnProperty(r)&&(e.length&&(e+="&"),e+=encodeURIComponent(r)+"="+encodeURIComponent(t[r]));return e},e.decode=function(t){for(var e={},r=t.split("&"),n=0,o=r.length;n<o;n++){var i=r[n].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}},function(t,e){t.exports=function(t,e){var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}},function(t,e){"use strict";var r,n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),o={},i=0,s=0;function a(t){var e="";do{e=n[t%64]+e,t=Math.floor(t/64)}while(t>0);return e}function c(){var t=a(+new Date);return t!==r?(i=0,r=t):t+"."+a(i++)}for(;s<64;s++)o[n[s]]=s;c.encode=a,c.decode=function(t){var e=0;for(s=0;s<t.length;s++)e=64*e+o[t.charAt(s)];return e},t.exports=c},function(t,e,r){(function(n){"use strict";var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};function i(){var t;try{t=e.storage.debug}catch(t){}return!t&&void 0!==n&&"env"in n&&(t=n.env.DEBUG),t}(e=t.exports=r(24)).log=function(){return"object"===("undefined"==typeof console?"undefined":o(console))&&console.log&&Function.prototype.apply.call(console.log,console,arguments)},e.formatArgs=function(t){var r=this.useColors;if(t[0]=(r?"%c":"")+this.namespace+(r?" %c":" ")+t[0]+(r?"%c ":" ")+"+"+e.humanize(this.diff),!r)return;var n="color: "+this.color;t.splice(1,0,n,"color: inherit");var o=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(function(t){"%%"!==t&&(o++,"%c"===t&&(i=o))})),t.splice(i,0,n)},e.save=function(t){try{null==t?e.storage.removeItem("debug"):e.storage.debug=t}catch(t){}},e.load=i,e.useColors=function(){if("undefined"!=typeof window&&window.process&&"renderer"===window.process.type)return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},e.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(t){}}(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],e.formatters.j=function(t){try{return JSON.stringify(t)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}},e.enable(i())}).call(e,r(23))},function(t,e){var r,n,o=t.exports={};function i(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function a(t){if(r===setTimeout)return setTimeout(t,0);if((r===i||!r)&&setTimeout)return r=setTimeout,setTimeout(t,0);try{return r(t,0)}catch(e){try{return r.call(null,t,0)}catch(e){return r.call(this,t,0)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:i}catch(t){r=i}try{n="function"==typeof clearTimeout?clearTimeout:s}catch(t){n=s}}();var c,p=[],u=!1,h=-1;function f(){u&&c&&(u=!1,c.length?p=c.concat(p):h=-1,p.length&&l())}function l(){if(!u){var t=a(f);u=!0;for(var e=p.length;e;){for(c=p,p=[];++h<e;)c&&c[h].run();h=-1,e=p.length}c=null,u=!1,function(t){if(n===clearTimeout)return clearTimeout(t);if((n===s||!n)&&clearTimeout)return n=clearTimeout,clearTimeout(t);try{n(t)}catch(e){try{return n.call(null,t)}catch(e){return n.call(this,t)}}}(t)}}function d(t,e){this.fun=t,this.array=e}function y(){}o.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)e[r-1]=arguments[r];p.push(new d(t,e)),1!==p.length||u||a(l)},d.prototype.run=function(){this.fun.apply(null,this.array)},o.title="browser",o.browser=!0,o.env={},o.argv=[],o.version="",o.versions={},o.on=y,o.addListener=y,o.once=y,o.off=y,o.removeListener=y,o.removeAllListeners=y,o.emit=y,o.prependListener=y,o.prependOnceListener=y,o.listeners=function(t){return[]},o.binding=function(t){throw new Error("process.binding is not supported")},o.cwd=function(){return"/"},o.chdir=function(t){throw new Error("process.chdir is not supported")},o.umask=function(){return 0}},function(t,e,r){"use strict";function n(t){var r;function n(){if(n.enabled){var t=n,o=+new Date,i=o-(r||o);t.diff=i,t.prev=r,t.curr=o,r=o;for(var s=new Array(arguments.length),a=0;a<s.length;a++)s[a]=arguments[a];s[0]=e.coerce(s[0]),"string"!=typeof s[0]&&s.unshift("%O");var c=0;s[0]=s[0].replace(/%([a-zA-Z%])/g,(function(r,n){if("%%"===r)return r;c++;var o=e.formatters[n];if("function"==typeof o){var i=s[c];r=o.call(t,i),s.splice(c,1),c--}return r})),e.formatArgs.call(t,s);var p=n.log||e.log||console.log.bind(console);p.apply(t,s)}}return n.namespace=t,n.enabled=e.enabled(t),n.useColors=e.useColors(),n.color=function(t){var r,n=0;for(r in t)n=(n<<5)-n+t.charCodeAt(r),n|=0;return e.colors[Math.abs(n)%e.colors.length]}(t),n.destroy=o,"function"==typeof e.init&&e.init(n),e.instances.push(n),n}function o(){var t=e.instances.indexOf(this);return-1!==t&&(e.instances.splice(t,1),!0)}(e=t.exports=n.debug=n.default=n).coerce=function(t){return t instanceof Error?t.stack||t.message:t},e.disable=function(){e.enable("")},e.enable=function(t){var r;e.save(t),e.names=[],e.skips=[];var n=("string"==typeof t?t:"").split(/[\s,]+/),o=n.length;for(r=0;r<o;r++)n[r]&&("-"===(t=n[r].replace(/\*/g,".*?"))[0]?e.skips.push(new RegExp("^"+t.substr(1)+"$")):e.names.push(new RegExp("^"+t+"$")));for(r=0;r<e.instances.length;r++){var i=e.instances[r];i.enabled=e.enabled(i.namespace)}},e.enabled=function(t){if("*"===t[t.length-1])return!0;var r,n;for(r=0,n=e.skips.length;r<n;r++)if(e.skips[r].test(t))return!1;for(r=0,n=e.names.length;r<n;r++)if(e.names[r].test(t))return!0;return!1},e.humanize=r(25),e.instances=[],e.names=[],e.skips=[],e.formatters={}},function(t,e){var r=1e3,n=60*r,o=60*n,i=24*o,s=365.25*i;function a(t,e,r){if(!(t<e))return t<1.5*e?Math.floor(t/e)+" "+r:Math.ceil(t/e)+" "+r+"s"}t.exports=function(t,e){e=e||{};var c,p=typeof t;if("string"===p&&t.length>0)return function(t){if((t=String(t)).length>100)return;var e=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(t);if(!e)return;var a=parseFloat(e[1]);switch((e[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return a*s;case"days":case"day":case"d":return a*i;case"hours":case"hour":case"hrs":case"hr":case"h":return a*o;case"minutes":case"minute":case"mins":case"min":case"m":return a*n;case"seconds":case"second":case"secs":case"sec":case"s":return a*r;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}(t);if("number"===p&&!1===isNaN(t))return e.long?a(c=t,i,"day")||a(c,o,"hour")||a(c,n,"minute")||a(c,r,"second")||c+" ms":function(t){if(t>=i)return Math.round(t/i)+"d";if(t>=o)return Math.round(t/o)+"h";if(t>=n)return Math.round(t/n)+"m";if(t>=r)return Math.round(t/r)+"s";return t+"ms"}(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))}},function(t,e,r){var n=r(7),o=r(20),i=r(5);t.exports=u;var s,a=/\n/g,c=/\\n/g;function p(){}function u(t){n.call(this,t),this.query=this.query||{},s||(s=i.___eio=i.___eio||[]),this.index=s.length;var e=this;s.push((function(t){e.onData(t)})),this.query.j=this.index,"function"==typeof addEventListener&&addEventListener("beforeunload",(function(){e.script&&(e.script.onerror=p)}),!1)}o(u,n),u.prototype.supportsBinary=!1,u.prototype.doClose=function(){this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),this.form&&(this.form.parentNode.removeChild(this.form),this.form=null,this.iframe=null),n.prototype.doClose.call(this)},u.prototype.doPoll=function(){var t=this,e=document.createElement("script");this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),e.async=!0,e.src=this.uri(),e.onerror=function(e){t.onError("jsonp poll error",e)};var r=document.getElementsByTagName("script")[0];r?r.parentNode.insertBefore(e,r):(document.head||document.body).appendChild(e),this.script=e,"undefined"!=typeof navigator&&/gecko/i.test(navigator.userAgent)&&setTimeout((function(){var t=document.createElement("iframe");document.body.appendChild(t),document.body.removeChild(t)}),100)},u.prototype.doWrite=function(t,e){var r=this;if(!this.form){var n,o=document.createElement("form"),i=document.createElement("textarea"),s=this.iframeId="eio_iframe_"+this.index;o.className="socketio",o.style.position="absolute",o.style.top="-1000px",o.style.left="-1000px",o.target=s,o.method="POST",o.setAttribute("accept-charset","utf-8"),i.name="d",o.appendChild(i),document.body.appendChild(o),this.form=o,this.area=i}function p(){u(),e()}function u(){if(r.iframe)try{r.form.removeChild(r.iframe)}catch(t){r.onError("jsonp polling iframe removal error",t)}try{var t='<iframe src="javascript:0" name="'+r.iframeId+'">';n=document.createElement(t)}catch(t){(n=document.createElement("iframe")).name=r.iframeId,n.src="javascript:0"}n.id=r.iframeId,r.form.appendChild(n),r.iframe=n}this.form.action=this.uri(),u(),t=t.replace(c,"\\\n"),this.area.value=t.replace(a,"\\n");try{this.form.submit()}catch(t){}this.iframe.attachEvent?this.iframe.onreadystatechange=function(){"complete"===r.iframe.readyState&&p()}:this.iframe.onload=p}},function(t,e,r){var n,o,i=r(8),s=r(9),a=r(19),c=r(20),p=r(21),u=r(22)("engine.io-client:websocket");if("undefined"!=typeof WebSocket?n=WebSocket:"undefined"!=typeof self&&(n=self.WebSocket||self.MozWebSocket),"undefined"==typeof window)try{o=r(28)}catch(t){}var h=n||o;function f(t){t&&t.forceBase64&&(this.supportsBinary=!1),this.perMessageDeflate=t.perMessageDeflate,this.usingBrowserWebSocket=n&&!t.forceNode,this.protocols=t.protocols,this.usingBrowserWebSocket||(h=o),i.call(this,t)}t.exports=f,c(f,i),f.prototype.name="websocket",f.prototype.supportsBinary=!0,f.prototype.doOpen=function(){if(this.check()){var t=this.uri(),e=this.protocols,r={};this.isReactNative||(r.agent=this.agent,r.perMessageDeflate=this.perMessageDeflate,r.pfx=this.pfx,r.key=this.key,r.passphrase=this.passphrase,r.cert=this.cert,r.ca=this.ca,r.ciphers=this.ciphers,r.rejectUnauthorized=this.rejectUnauthorized),this.extraHeaders&&(r.headers=this.extraHeaders),this.localAddress&&(r.localAddress=this.localAddress);try{this.ws=this.usingBrowserWebSocket&&!this.isReactNative?e?new h(t,e):new h(t):new h(t,e,r)}catch(t){return this.emit("error",t)}void 0===this.ws.binaryType&&(this.supportsBinary=!1),this.ws.supports&&this.ws.supports.binary?(this.supportsBinary=!0,this.ws.binaryType="nodebuffer"):this.ws.binaryType="arraybuffer",this.addEventListeners()}},f.prototype.addEventListeners=function(){var t=this;this.ws.onopen=function(){t.onOpen()},this.ws.onclose=function(){t.onClose()},this.ws.onmessage=function(e){t.onData(e.data)},this.ws.onerror=function(e){t.onError("websocket error",e)}},f.prototype.write=function(t){var e=this;this.writable=!1;for(var r=t.length,n=0,o=r;n<o;n++)!function(t){s.encodePacket(t,e.supportsBinary,(function(n){if(!e.usingBrowserWebSocket){var o={};if(t.options&&(o.compress=t.options.compress),e.perMessageDeflate)("string"==typeof n?Buffer.byteLength(n):n.length)<e.perMessageDeflate.threshold&&(o.compress=!1)}try{e.usingBrowserWebSocket?e.ws.send(n):e.ws.send(n,o)}catch(t){u("websocket closed before onclose event")}--r||i()}))}(t[n]);function i(){e.emit("flush"),setTimeout((function(){e.writable=!0,e.emit("drain")}),0)}},f.prototype.onClose=function(){i.prototype.onClose.call(this)},f.prototype.doClose=function(){void 0!==this.ws&&this.ws.close()},f.prototype.uri=function(){var t=this.query||{},e=this.secure?"wss":"ws",r="";return this.port&&("wss"===e&&443!==Number(this.port)||"ws"===e&&80!==Number(this.port))&&(r=":"+this.port),this.timestampRequests&&(t[this.timestampParam]=p()),this.supportsBinary||(t.b64=1),(t=a.encode(t)).length&&(t="?"+t),e+"://"+(-1!==this.hostname.indexOf(":")?"["+this.hostname+"]":this.hostname)+r+this.path+t},f.prototype.check=function(){return!(!h||"__initialize"in h&&this.name===f.prototype.name)}},function(t,e){},function(t,e){var r=[].indexOf;t.exports=function(t,e){if(r)return t.indexOf(e);for(var n=0;n<t.length;++n)if(t[n]===e)return n;return-1}},function(t,e){var r=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,n=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];t.exports=function(t){var e=t,o=t.indexOf("["),i=t.indexOf("]");-1!=o&&-1!=i&&(t=t.substring(0,o)+t.substring(o,i).replace(/:/g,";")+t.substring(i,t.length));for(var s,a,c=r.exec(t||""),p={},u=14;u--;)p[n[u]]=c[u]||"";return-1!=o&&-1!=i&&(p.source=e,p.host=p.host.substring(1,p.host.length-1).replace(/;/g,":"),p.authority=p.authority.replace("[","").replace("]","").replace(/;/g,":"),p.ipv6uri=!0),p.pathNames=function(t,e){var r=/\/{2,9}/g,n=e.replace(r,"/").split("/");"/"!=e.substr(0,1)&&0!==e.length||n.splice(0,1);"/"==e.substr(e.length-1,1)&&n.splice(n.length-1,1);return n}(0,p.path),p.queryKey=(s=p.query,a={},s.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(t,e,r){e&&(a[e]=r)})),a),p}}])}));
\ No newline at end of file
index 11b0f28..4b36483 100644 (file)
@@ -1,9 +1 @@
-module.exports = (function () {
-  if (typeof self !== 'undefined') {
-    return self;
-  } else if (typeof window !== 'undefined') {
-    return window;
-  } else {
-    return Function('return this')(); // eslint-disable-line no-new-func
-  }
-})();
+module.exports="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();
\ No newline at end of file
index 0bf4058..3c7ab9b 100644 (file)
@@ -1,10 +1 @@
-
-module.exports = require('./socket');
-
-/**
- * Exports parser
- *
- * @api public
- *
- */
-module.exports.parser = require('engine.io-parser');
+module.exports=require("./socket"),module.exports.parser=require("engine.io-parser");
\ No newline at end of file
index 5e52d9b..326cf32 100644 (file)
@@ -1,748 +1 @@
-/**
- * Module dependencies.
- */
-
-var transports = require('./transports/index');
-var Emitter = require('component-emitter');
-var debug = require('debug')('engine.io-client:socket');
-var index = require('indexof');
-var parser = require('engine.io-parser');
-var parseuri = require('parseuri');
-var parseqs = require('parseqs');
-
-/**
- * Module exports.
- */
-
-module.exports = Socket;
-
-/**
- * Socket constructor.
- *
- * @param {String|Object} uri or options
- * @param {Object} options
- * @api public
- */
-
-function Socket (uri, opts) {
-  if (!(this instanceof Socket)) return new Socket(uri, opts);
-
-  opts = opts || {};
-
-  if (uri && 'object' === typeof uri) {
-    opts = uri;
-    uri = null;
-  }
-
-  if (uri) {
-    uri = parseuri(uri);
-    opts.hostname = uri.host;
-    opts.secure = uri.protocol === 'https' || uri.protocol === 'wss';
-    opts.port = uri.port;
-    if (uri.query) opts.query = uri.query;
-  } else if (opts.host) {
-    opts.hostname = parseuri(opts.host).host;
-  }
-
-  this.secure = null != opts.secure ? opts.secure
-    : (typeof location !== 'undefined' && 'https:' === location.protocol);
-
-  if (opts.hostname && !opts.port) {
-    // if no port is specified manually, use the protocol default
-    opts.port = this.secure ? '443' : '80';
-  }
-
-  this.agent = opts.agent || false;
-  this.hostname = opts.hostname ||
-    (typeof location !== 'undefined' ? location.hostname : 'localhost');
-  this.port = opts.port || (typeof location !== 'undefined' && location.port
-      ? location.port
-      : (this.secure ? 443 : 80));
-  this.query = opts.query || {};
-  if ('string' === typeof this.query) this.query = parseqs.decode(this.query);
-  this.upgrade = false !== opts.upgrade;
-  this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
-  this.forceJSONP = !!opts.forceJSONP;
-  this.jsonp = false !== opts.jsonp;
-  this.forceBase64 = !!opts.forceBase64;
-  this.enablesXDR = !!opts.enablesXDR;
-  this.withCredentials = false !== opts.withCredentials;
-  this.timestampParam = opts.timestampParam || 't';
-  this.timestampRequests = opts.timestampRequests;
-  this.transports = opts.transports || ['polling', 'websocket'];
-  this.transportOptions = opts.transportOptions || {};
-  this.readyState = '';
-  this.writeBuffer = [];
-  this.prevBufferLen = 0;
-  this.policyPort = opts.policyPort || 843;
-  this.rememberUpgrade = opts.rememberUpgrade || false;
-  this.binaryType = null;
-  this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
-  this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false;
-
-  if (true === this.perMessageDeflate) this.perMessageDeflate = {};
-  if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) {
-    this.perMessageDeflate.threshold = 1024;
-  }
-
-  // SSL options for Node.js client
-  this.pfx = opts.pfx || undefined;
-  this.key = opts.key || undefined;
-  this.passphrase = opts.passphrase || undefined;
-  this.cert = opts.cert || undefined;
-  this.ca = opts.ca || undefined;
-  this.ciphers = opts.ciphers || undefined;
-  this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? true : opts.rejectUnauthorized;
-  this.forceNode = !!opts.forceNode;
-
-  // detect ReactNative environment
-  this.isReactNative = (typeof navigator !== 'undefined' && typeof navigator.product === 'string' && navigator.product.toLowerCase() === 'reactnative');
-
-  // other options for Node.js or ReactNative client
-  if (typeof self === 'undefined' || this.isReactNative) {
-    if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) {
-      this.extraHeaders = opts.extraHeaders;
-    }
-
-    if (opts.localAddress) {
-      this.localAddress = opts.localAddress;
-    }
-  }
-
-  // set on handshake
-  this.id = null;
-  this.upgrades = null;
-  this.pingInterval = null;
-  this.pingTimeout = null;
-
-  // set on heartbeat
-  this.pingIntervalTimer = null;
-  this.pingTimeoutTimer = null;
-
-  this.open();
-}
-
-Socket.priorWebsocketSuccess = false;
-
-/**
- * Mix in `Emitter`.
- */
-
-Emitter(Socket.prototype);
-
-/**
- * Protocol version.
- *
- * @api public
- */
-
-Socket.protocol = parser.protocol; // this is an int
-
-/**
- * Expose deps for legacy compatibility
- * and standalone browser access.
- */
-
-Socket.Socket = Socket;
-Socket.Transport = require('./transport');
-Socket.transports = require('./transports/index');
-Socket.parser = require('engine.io-parser');
-
-/**
- * Creates transport of the given type.
- *
- * @param {String} transport name
- * @return {Transport}
- * @api private
- */
-
-Socket.prototype.createTransport = function (name) {
-  debug('creating transport "%s"', name);
-  var query = clone(this.query);
-
-  // append engine.io protocol identifier
-  query.EIO = parser.protocol;
-
-  // transport name
-  query.transport = name;
-
-  // per-transport options
-  var options = this.transportOptions[name] || {};
-
-  // session id if we already have one
-  if (this.id) query.sid = this.id;
-
-  var transport = new transports[name]({
-    query: query,
-    socket: this,
-    agent: options.agent || this.agent,
-    hostname: options.hostname || this.hostname,
-    port: options.port || this.port,
-    secure: options.secure || this.secure,
-    path: options.path || this.path,
-    forceJSONP: options.forceJSONP || this.forceJSONP,
-    jsonp: options.jsonp || this.jsonp,
-    forceBase64: options.forceBase64 || this.forceBase64,
-    enablesXDR: options.enablesXDR || this.enablesXDR,
-    withCredentials: options.withCredentials || this.withCredentials,
-    timestampRequests: options.timestampRequests || this.timestampRequests,
-    timestampParam: options.timestampParam || this.timestampParam,
-    policyPort: options.policyPort || this.policyPort,
-    pfx: options.pfx || this.pfx,
-    key: options.key || this.key,
-    passphrase: options.passphrase || this.passphrase,
-    cert: options.cert || this.cert,
-    ca: options.ca || this.ca,
-    ciphers: options.ciphers || this.ciphers,
-    rejectUnauthorized: options.rejectUnauthorized || this.rejectUnauthorized,
-    perMessageDeflate: options.perMessageDeflate || this.perMessageDeflate,
-    extraHeaders: options.extraHeaders || this.extraHeaders,
-    forceNode: options.forceNode || this.forceNode,
-    localAddress: options.localAddress || this.localAddress,
-    requestTimeout: options.requestTimeout || this.requestTimeout,
-    protocols: options.protocols || void (0),
-    isReactNative: this.isReactNative
-  });
-
-  return transport;
-};
-
-function clone (obj) {
-  var o = {};
-  for (var i in obj) {
-    if (obj.hasOwnProperty(i)) {
-      o[i] = obj[i];
-    }
-  }
-  return o;
-}
-
-/**
- * Initializes transport to use and starts probe.
- *
- * @api private
- */
-Socket.prototype.open = function () {
-  var transport;
-  if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) {
-    transport = 'websocket';
-  } else if (0 === this.transports.length) {
-    // Emit error on next tick so it can be listened to
-    var self = this;
-    setTimeout(function () {
-      self.emit('error', 'No transports available');
-    }, 0);
-    return;
-  } else {
-    transport = this.transports[0];
-  }
-  this.readyState = 'opening';
-
-  // Retry with the next transport if the transport is disabled (jsonp: false)
-  try {
-    transport = this.createTransport(transport);
-  } catch (e) {
-    this.transports.shift();
-    this.open();
-    return;
-  }
-
-  transport.open();
-  this.setTransport(transport);
-};
-
-/**
- * Sets the current transport. Disables the existing one (if any).
- *
- * @api private
- */
-
-Socket.prototype.setTransport = function (transport) {
-  debug('setting transport %s', transport.name);
-  var self = this;
-
-  if (this.transport) {
-    debug('clearing existing transport %s', this.transport.name);
-    this.transport.removeAllListeners();
-  }
-
-  // set up transport
-  this.transport = transport;
-
-  // set up transport listeners
-  transport
-  .on('drain', function () {
-    self.onDrain();
-  })
-  .on('packet', function (packet) {
-    self.onPacket(packet);
-  })
-  .on('error', function (e) {
-    self.onError(e);
-  })
-  .on('close', function () {
-    self.onClose('transport close');
-  });
-};
-
-/**
- * Probes a transport.
- *
- * @param {String} transport name
- * @api private
- */
-
-Socket.prototype.probe = function (name) {
-  debug('probing transport "%s"', name);
-  var transport = this.createTransport(name, { probe: 1 });
-  var failed = false;
-  var self = this;
-
-  Socket.priorWebsocketSuccess = false;
-
-  function onTransportOpen () {
-    if (self.onlyBinaryUpgrades) {
-      var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
-      failed = failed || upgradeLosesBinary;
-    }
-    if (failed) return;
-
-    debug('probe transport "%s" opened', name);
-    transport.send([{ type: 'ping', data: 'probe' }]);
-    transport.once('packet', function (msg) {
-      if (failed) return;
-      if ('pong' === msg.type && 'probe' === msg.data) {
-        debug('probe transport "%s" pong', name);
-        self.upgrading = true;
-        self.emit('upgrading', transport);
-        if (!transport) return;
-        Socket.priorWebsocketSuccess = 'websocket' === transport.name;
-
-        debug('pausing current transport "%s"', self.transport.name);
-        self.transport.pause(function () {
-          if (failed) return;
-          if ('closed' === self.readyState) return;
-          debug('changing transport and sending upgrade packet');
-
-          cleanup();
-
-          self.setTransport(transport);
-          transport.send([{ type: 'upgrade' }]);
-          self.emit('upgrade', transport);
-          transport = null;
-          self.upgrading = false;
-          self.flush();
-        });
-      } else {
-        debug('probe transport "%s" failed', name);
-        var err = new Error('probe error');
-        err.transport = transport.name;
-        self.emit('upgradeError', err);
-      }
-    });
-  }
-
-  function freezeTransport () {
-    if (failed) return;
-
-    // Any callback called by transport should be ignored since now
-    failed = true;
-
-    cleanup();
-
-    transport.close();
-    transport = null;
-  }
-
-  // Handle any error that happens while probing
-  function onerror (err) {
-    var error = new Error('probe error: ' + err);
-    error.transport = transport.name;
-
-    freezeTransport();
-
-    debug('probe transport "%s" failed because of error: %s', name, err);
-
-    self.emit('upgradeError', error);
-  }
-
-  function onTransportClose () {
-    onerror('transport closed');
-  }
-
-  // When the socket is closed while we're probing
-  function onclose () {
-    onerror('socket closed');
-  }
-
-  // When the socket is upgraded while we're probing
-  function onupgrade (to) {
-    if (transport && to.name !== transport.name) {
-      debug('"%s" works - aborting "%s"', to.name, transport.name);
-      freezeTransport();
-    }
-  }
-
-  // Remove all listeners on the transport and on self
-  function cleanup () {
-    transport.removeListener('open', onTransportOpen);
-    transport.removeListener('error', onerror);
-    transport.removeListener('close', onTransportClose);
-    self.removeListener('close', onclose);
-    self.removeListener('upgrading', onupgrade);
-  }
-
-  transport.once('open', onTransportOpen);
-  transport.once('error', onerror);
-  transport.once('close', onTransportClose);
-
-  this.once('close', onclose);
-  this.once('upgrading', onupgrade);
-
-  transport.open();
-};
-
-/**
- * Called when connection is deemed open.
- *
- * @api public
- */
-
-Socket.prototype.onOpen = function () {
-  debug('socket open');
-  this.readyState = 'open';
-  Socket.priorWebsocketSuccess = 'websocket' === this.transport.name;
-  this.emit('open');
-  this.flush();
-
-  // we check for `readyState` in case an `open`
-  // listener already closed the socket
-  if ('open' === this.readyState && this.upgrade && this.transport.pause) {
-    debug('starting upgrade probes');
-    for (var i = 0, l = this.upgrades.length; i < l; i++) {
-      this.probe(this.upgrades[i]);
-    }
-  }
-};
-
-/**
- * Handles a packet.
- *
- * @api private
- */
-
-Socket.prototype.onPacket = function (packet) {
-  if ('opening' === this.readyState || 'open' === this.readyState ||
-      'closing' === this.readyState) {
-    debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
-
-    this.emit('packet', packet);
-
-    // Socket is live - any packet counts
-    this.emit('heartbeat');
-
-    switch (packet.type) {
-      case 'open':
-        this.onHandshake(JSON.parse(packet.data));
-        break;
-
-      case 'pong':
-        this.setPing();
-        this.emit('pong');
-        break;
-
-      case 'error':
-        var err = new Error('server error');
-        err.code = packet.data;
-        this.onError(err);
-        break;
-
-      case 'message':
-        this.emit('data', packet.data);
-        this.emit('message', packet.data);
-        break;
-    }
-  } else {
-    debug('packet received with socket readyState "%s"', this.readyState);
-  }
-};
-
-/**
- * Called upon handshake completion.
- *
- * @param {Object} handshake obj
- * @api private
- */
-
-Socket.prototype.onHandshake = function (data) {
-  this.emit('handshake', data);
-  this.id = data.sid;
-  this.transport.query.sid = data.sid;
-  this.upgrades = this.filterUpgrades(data.upgrades);
-  this.pingInterval = data.pingInterval;
-  this.pingTimeout = data.pingTimeout;
-  this.onOpen();
-  // In case open handler closes socket
-  if ('closed' === this.readyState) return;
-  this.setPing();
-
-  // Prolong liveness of socket on heartbeat
-  this.removeListener('heartbeat', this.onHeartbeat);
-  this.on('heartbeat', this.onHeartbeat);
-};
-
-/**
- * Resets ping timeout.
- *
- * @api private
- */
-
-Socket.prototype.onHeartbeat = function (timeout) {
-  clearTimeout(this.pingTimeoutTimer);
-  var self = this;
-  self.pingTimeoutTimer = setTimeout(function () {
-    if ('closed' === self.readyState) return;
-    self.onClose('ping timeout');
-  }, timeout || (self.pingInterval + self.pingTimeout));
-};
-
-/**
- * Pings server every `this.pingInterval` and expects response
- * within `this.pingTimeout` or closes connection.
- *
- * @api private
- */
-
-Socket.prototype.setPing = function () {
-  var self = this;
-  clearTimeout(self.pingIntervalTimer);
-  self.pingIntervalTimer = setTimeout(function () {
-    debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
-    self.ping();
-    self.onHeartbeat(self.pingTimeout);
-  }, self.pingInterval);
-};
-
-/**
-* Sends a ping packet.
-*
-* @api private
-*/
-
-Socket.prototype.ping = function () {
-  var self = this;
-  this.sendPacket('ping', function () {
-    self.emit('ping');
-  });
-};
-
-/**
- * Called on `drain` event
- *
- * @api private
- */
-
-Socket.prototype.onDrain = function () {
-  this.writeBuffer.splice(0, this.prevBufferLen);
-
-  // setting prevBufferLen = 0 is very important
-  // for example, when upgrading, upgrade packet is sent over,
-  // and a nonzero prevBufferLen could cause problems on `drain`
-  this.prevBufferLen = 0;
-
-  if (0 === this.writeBuffer.length) {
-    this.emit('drain');
-  } else {
-    this.flush();
-  }
-};
-
-/**
- * Flush write buffers.
- *
- * @api private
- */
-
-Socket.prototype.flush = function () {
-  if ('closed' !== this.readyState && this.transport.writable &&
-    !this.upgrading && this.writeBuffer.length) {
-    debug('flushing %d packets in socket', this.writeBuffer.length);
-    this.transport.send(this.writeBuffer);
-    // keep track of current length of writeBuffer
-    // splice writeBuffer and callbackBuffer on `drain`
-    this.prevBufferLen = this.writeBuffer.length;
-    this.emit('flush');
-  }
-};
-
-/**
- * Sends a message.
- *
- * @param {String} message.
- * @param {Function} callback function.
- * @param {Object} options.
- * @return {Socket} for chaining.
- * @api public
- */
-
-Socket.prototype.write =
-Socket.prototype.send = function (msg, options, fn) {
-  this.sendPacket('message', msg, options, fn);
-  return this;
-};
-
-/**
- * Sends a packet.
- *
- * @param {String} packet type.
- * @param {String} data.
- * @param {Object} options.
- * @param {Function} callback function.
- * @api private
- */
-
-Socket.prototype.sendPacket = function (type, data, options, fn) {
-  if ('function' === typeof data) {
-    fn = data;
-    data = undefined;
-  }
-
-  if ('function' === typeof options) {
-    fn = options;
-    options = null;
-  }
-
-  if ('closing' === this.readyState || 'closed' === this.readyState) {
-    return;
-  }
-
-  options = options || {};
-  options.compress = false !== options.compress;
-
-  var packet = {
-    type: type,
-    data: data,
-    options: options
-  };
-  this.emit('packetCreate', packet);
-  this.writeBuffer.push(packet);
-  if (fn) this.once('flush', fn);
-  this.flush();
-};
-
-/**
- * Closes the connection.
- *
- * @api private
- */
-
-Socket.prototype.close = function () {
-  if ('opening' === this.readyState || 'open' === this.readyState) {
-    this.readyState = 'closing';
-
-    var self = this;
-
-    if (this.writeBuffer.length) {
-      this.once('drain', function () {
-        if (this.upgrading) {
-          waitForUpgrade();
-        } else {
-          close();
-        }
-      });
-    } else if (this.upgrading) {
-      waitForUpgrade();
-    } else {
-      close();
-    }
-  }
-
-  function close () {
-    self.onClose('forced close');
-    debug('socket closing - telling transport to close');
-    self.transport.close();
-  }
-
-  function cleanupAndClose () {
-    self.removeListener('upgrade', cleanupAndClose);
-    self.removeListener('upgradeError', cleanupAndClose);
-    close();
-  }
-
-  function waitForUpgrade () {
-    // wait for upgrade to finish since we can't send packets while pausing a transport
-    self.once('upgrade', cleanupAndClose);
-    self.once('upgradeError', cleanupAndClose);
-  }
-
-  return this;
-};
-
-/**
- * Called upon transport error
- *
- * @api private
- */
-
-Socket.prototype.onError = function (err) {
-  debug('socket error %j', err);
-  Socket.priorWebsocketSuccess = false;
-  this.emit('error', err);
-  this.onClose('transport error', err);
-};
-
-/**
- * Called upon transport close.
- *
- * @api private
- */
-
-Socket.prototype.onClose = function (reason, desc) {
-  if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) {
-    debug('socket close with reason: "%s"', reason);
-    var self = this;
-
-    // clear timers
-    clearTimeout(this.pingIntervalTimer);
-    clearTimeout(this.pingTimeoutTimer);
-
-    // stop event from firing again for transport
-    this.transport.removeAllListeners('close');
-
-    // ensure transport won't stay open
-    this.transport.close();
-
-    // ignore further transport communication
-    this.transport.removeAllListeners();
-
-    // set ready state
-    this.readyState = 'closed';
-
-    // clear session id
-    this.id = null;
-
-    // emit close event
-    this.emit('close', reason, desc);
-
-    // clean buffers after, so users can still
-    // grab the buffers on `close` event
-    self.writeBuffer = [];
-    self.prevBufferLen = 0;
-  }
-};
-
-/**
- * Filters upgrades, returning only those matching client transports.
- *
- * @param {Array} server upgrades
- * @api private
- *
- */
-
-Socket.prototype.filterUpgrades = function (upgrades) {
-  var filteredUpgrades = [];
-  for (var i = 0, j = upgrades.length; i < j; i++) {
-    if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
-  }
-  return filteredUpgrades;
-};
+var transports=require("./transports/index"),Emitter=require("component-emitter"),debug=require("debug")("engine.io-client:socket"),index=require("indexof"),parser=require("engine.io-parser"),parseuri=require("parseuri"),parseqs=require("parseqs");function Socket(e,t){if(!(this instanceof Socket))return new Socket(e,t);t=t||{},e&&"object"==typeof e&&(t=e,e=null),e?(e=parseuri(e),t.hostname=e.host,t.secure="https"===e.protocol||"wss"===e.protocol,t.port=e.port,e.query&&(t.query=e.query)):t.host&&(t.hostname=parseuri(t.host).host),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.agent=t.agent||!1,this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?443:80),this.query=t.query||{},"string"==typeof this.query&&(this.query=parseqs.decode(this.query)),this.upgrade=!1!==t.upgrade,this.path=(t.path||"/engine.io").replace(/\/$/,"")+"/",this.forceJSONP=!!t.forceJSONP,this.jsonp=!1!==t.jsonp,this.forceBase64=!!t.forceBase64,this.enablesXDR=!!t.enablesXDR,this.withCredentials=!1!==t.withCredentials,this.timestampParam=t.timestampParam||"t",this.timestampRequests=t.timestampRequests,this.transports=t.transports||["polling","websocket"],this.transportOptions=t.transportOptions||{},this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.policyPort=t.policyPort||843,this.rememberUpgrade=t.rememberUpgrade||!1,this.binaryType=null,this.onlyBinaryUpgrades=t.onlyBinaryUpgrades,this.perMessageDeflate=!1!==t.perMessageDeflate&&(t.perMessageDeflate||{}),!0===this.perMessageDeflate&&(this.perMessageDeflate={}),this.perMessageDeflate&&null==this.perMessageDeflate.threshold&&(this.perMessageDeflate.threshold=1024),this.pfx=t.pfx||void 0,this.key=t.key||void 0,this.passphrase=t.passphrase||void 0,this.cert=t.cert||void 0,this.ca=t.ca||void 0,this.ciphers=t.ciphers||void 0,this.rejectUnauthorized=void 0===t.rejectUnauthorized||t.rejectUnauthorized,this.forceNode=!!t.forceNode,this.isReactNative="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),("undefined"==typeof self||this.isReactNative)&&(t.extraHeaders&&Object.keys(t.extraHeaders).length>0&&(this.extraHeaders=t.extraHeaders),t.localAddress&&(this.localAddress=t.localAddress)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingIntervalTimer=null,this.pingTimeoutTimer=null,this.open()}function clone(e){var t={};for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);return t}module.exports=Socket,Socket.priorWebsocketSuccess=!1,Emitter(Socket.prototype),Socket.protocol=parser.protocol,Socket.Socket=Socket,Socket.Transport=require("./transport"),Socket.transports=require("./transports/index"),Socket.parser=require("engine.io-parser"),Socket.prototype.createTransport=function(e){debug('creating transport "%s"',e);var t=clone(this.query);t.EIO=parser.protocol,t.transport=e;var r=this.transportOptions[e]||{};return this.id&&(t.sid=this.id),new transports[e]({query:t,socket:this,agent:r.agent||this.agent,hostname:r.hostname||this.hostname,port:r.port||this.port,secure:r.secure||this.secure,path:r.path||this.path,forceJSONP:r.forceJSONP||this.forceJSONP,jsonp:r.jsonp||this.jsonp,forceBase64:r.forceBase64||this.forceBase64,enablesXDR:r.enablesXDR||this.enablesXDR,withCredentials:r.withCredentials||this.withCredentials,timestampRequests:r.timestampRequests||this.timestampRequests,timestampParam:r.timestampParam||this.timestampParam,policyPort:r.policyPort||this.policyPort,pfx:r.pfx||this.pfx,key:r.key||this.key,passphrase:r.passphrase||this.passphrase,cert:r.cert||this.cert,ca:r.ca||this.ca,ciphers:r.ciphers||this.ciphers,rejectUnauthorized:r.rejectUnauthorized||this.rejectUnauthorized,perMessageDeflate:r.perMessageDeflate||this.perMessageDeflate,extraHeaders:r.extraHeaders||this.extraHeaders,forceNode:r.forceNode||this.forceNode,localAddress:r.localAddress||this.localAddress,requestTimeout:r.requestTimeout||this.requestTimeout,protocols:r.protocols||void 0,isReactNative:this.isReactNative})},Socket.prototype.open=function(){var e;if(this.rememberUpgrade&&Socket.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))e="websocket";else{if(0===this.transports.length){var t=this;return void setTimeout((function(){t.emit("error","No transports available")}),0)}e=this.transports[0]}this.readyState="opening";try{e=this.createTransport(e)}catch(e){return this.transports.shift(),void this.open()}e.open(),this.setTransport(e)},Socket.prototype.setTransport=function(e){debug("setting transport %s",e.name);var t=this;this.transport&&(debug("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",(function(){t.onDrain()})).on("packet",(function(e){t.onPacket(e)})).on("error",(function(e){t.onError(e)})).on("close",(function(){t.onClose("transport close")}))},Socket.prototype.probe=function(e){debug('probing transport "%s"',e);var t=this.createTransport(e,{probe:1}),r=!1,s=this;function o(){if(s.onlyBinaryUpgrades){var o=!this.supportsBinary&&s.transport.supportsBinary;r=r||o}r||(debug('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",(function(o){if(!r)if("pong"===o.type&&"probe"===o.data){if(debug('probe transport "%s" pong',e),s.upgrading=!0,s.emit("upgrading",t),!t)return;Socket.priorWebsocketSuccess="websocket"===t.name,debug('pausing current transport "%s"',s.transport.name),s.transport.pause((function(){r||"closed"!==s.readyState&&(debug("changing transport and sending upgrade packet"),h(),s.setTransport(t),t.send([{type:"upgrade"}]),s.emit("upgrade",t),t=null,s.upgrading=!1,s.flush())}))}else{debug('probe transport "%s" failed',e);var i=new Error("probe error");i.transport=t.name,s.emit("upgradeError",i)}})))}function i(){r||(r=!0,h(),t.close(),t=null)}function n(r){var o=new Error("probe error: "+r);o.transport=t.name,i(),debug('probe transport "%s" failed because of error: %s',e,r),s.emit("upgradeError",o)}function a(){n("transport closed")}function p(){n("socket closed")}function c(e){t&&e.name!==t.name&&(debug('"%s" works - aborting "%s"',e.name,t.name),i())}function h(){t.removeListener("open",o),t.removeListener("error",n),t.removeListener("close",a),s.removeListener("close",p),s.removeListener("upgrading",c)}Socket.priorWebsocketSuccess=!1,t.once("open",o),t.once("error",n),t.once("close",a),this.once("close",p),this.once("upgrading",c),t.open()},Socket.prototype.onOpen=function(){if(debug("socket open"),this.readyState="open",Socket.priorWebsocketSuccess="websocket"===this.transport.name,this.emit("open"),this.flush(),"open"===this.readyState&&this.upgrade&&this.transport.pause){debug("starting upgrade probes");for(var e=0,t=this.upgrades.length;e<t;e++)this.probe(this.upgrades[e])}},Socket.prototype.onPacket=function(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(debug('socket receive: type "%s", data "%s"',e.type,e.data),this.emit("packet",e),this.emit("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"pong":this.setPing(),this.emit("pong");break;case"error":var t=new Error("server error");t.code=e.data,this.onError(t);break;case"message":this.emit("data",e.data),this.emit("message",e.data)}else debug('packet received with socket readyState "%s"',this.readyState)},Socket.prototype.onHandshake=function(e){this.emit("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this.upgrades=this.filterUpgrades(e.upgrades),this.pingInterval=e.pingInterval,this.pingTimeout=e.pingTimeout,this.onOpen(),"closed"!==this.readyState&&(this.setPing(),this.removeListener("heartbeat",this.onHeartbeat),this.on("heartbeat",this.onHeartbeat))},Socket.prototype.onHeartbeat=function(e){clearTimeout(this.pingTimeoutTimer);var t=this;t.pingTimeoutTimer=setTimeout((function(){"closed"!==t.readyState&&t.onClose("ping timeout")}),e||t.pingInterval+t.pingTimeout)},Socket.prototype.setPing=function(){var e=this;clearTimeout(e.pingIntervalTimer),e.pingIntervalTimer=setTimeout((function(){debug("writing ping packet - expecting pong within %sms",e.pingTimeout),e.ping(),e.onHeartbeat(e.pingTimeout)}),e.pingInterval)},Socket.prototype.ping=function(){var e=this;this.sendPacket("ping",(function(){e.emit("ping")}))},Socket.prototype.onDrain=function(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emit("drain"):this.flush()},Socket.prototype.flush=function(){"closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length&&(debug("flushing %d packets in socket",this.writeBuffer.length),this.transport.send(this.writeBuffer),this.prevBufferLen=this.writeBuffer.length,this.emit("flush"))},Socket.prototype.write=Socket.prototype.send=function(e,t,r){return this.sendPacket("message",e,t,r),this},Socket.prototype.sendPacket=function(e,t,r,s){if("function"==typeof t&&(s=t,t=void 0),"function"==typeof r&&(s=r,r=null),"closing"!==this.readyState&&"closed"!==this.readyState){(r=r||{}).compress=!1!==r.compress;var o={type:e,data:t,options:r};this.emit("packetCreate",o),this.writeBuffer.push(o),s&&this.once("flush",s),this.flush()}},Socket.prototype.close=function(){if("opening"===this.readyState||"open"===this.readyState){this.readyState="closing";var e=this;this.writeBuffer.length?this.once("drain",(function(){this.upgrading?s():t()})):this.upgrading?s():t()}function t(){e.onClose("forced close"),debug("socket closing - telling transport to close"),e.transport.close()}function r(){e.removeListener("upgrade",r),e.removeListener("upgradeError",r),t()}function s(){e.once("upgrade",r),e.once("upgradeError",r)}return this},Socket.prototype.onError=function(e){debug("socket error %j",e),Socket.priorWebsocketSuccess=!1,this.emit("error",e),this.onClose("transport error",e)},Socket.prototype.onClose=function(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){debug('socket close with reason: "%s"',e);clearTimeout(this.pingIntervalTimer),clearTimeout(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),this.readyState="closed",this.id=null,this.emit("close",e,t),this.writeBuffer=[],this.prevBufferLen=0}},Socket.prototype.filterUpgrades=function(e){for(var t=[],r=0,s=e.length;r<s;r++)~index(this.transports,e[r])&&t.push(e[r]);return t};
\ No newline at end of file
index 9ed5a35..1c91bf0 100644 (file)
@@ -1,161 +1 @@
-/**
- * Module dependencies.
- */
-
-var parser = require('engine.io-parser');
-var Emitter = require('component-emitter');
-
-/**
- * Module exports.
- */
-
-module.exports = Transport;
-
-/**
- * Transport abstract constructor.
- *
- * @param {Object} options.
- * @api private
- */
-
-function Transport (opts) {
-  this.path = opts.path;
-  this.hostname = opts.hostname;
-  this.port = opts.port;
-  this.secure = opts.secure;
-  this.query = opts.query;
-  this.timestampParam = opts.timestampParam;
-  this.timestampRequests = opts.timestampRequests;
-  this.readyState = '';
-  this.agent = opts.agent || false;
-  this.socket = opts.socket;
-  this.enablesXDR = opts.enablesXDR;
-  this.withCredentials = opts.withCredentials;
-
-  // SSL options for Node.js client
-  this.pfx = opts.pfx;
-  this.key = opts.key;
-  this.passphrase = opts.passphrase;
-  this.cert = opts.cert;
-  this.ca = opts.ca;
-  this.ciphers = opts.ciphers;
-  this.rejectUnauthorized = opts.rejectUnauthorized;
-  this.forceNode = opts.forceNode;
-
-  // results of ReactNative environment detection
-  this.isReactNative = opts.isReactNative;
-
-  // other options for Node.js client
-  this.extraHeaders = opts.extraHeaders;
-  this.localAddress = opts.localAddress;
-}
-
-/**
- * Mix in `Emitter`.
- */
-
-Emitter(Transport.prototype);
-
-/**
- * Emits an error.
- *
- * @param {String} str
- * @return {Transport} for chaining
- * @api public
- */
-
-Transport.prototype.onError = function (msg, desc) {
-  var err = new Error(msg);
-  err.type = 'TransportError';
-  err.description = desc;
-  this.emit('error', err);
-  return this;
-};
-
-/**
- * Opens the transport.
- *
- * @api public
- */
-
-Transport.prototype.open = function () {
-  if ('closed' === this.readyState || '' === this.readyState) {
-    this.readyState = 'opening';
-    this.doOpen();
-  }
-
-  return this;
-};
-
-/**
- * Closes the transport.
- *
- * @api private
- */
-
-Transport.prototype.close = function () {
-  if ('opening' === this.readyState || 'open' === this.readyState) {
-    this.doClose();
-    this.onClose();
-  }
-
-  return this;
-};
-
-/**
- * Sends multiple packets.
- *
- * @param {Array} packets
- * @api private
- */
-
-Transport.prototype.send = function (packets) {
-  if ('open' === this.readyState) {
-    this.write(packets);
-  } else {
-    throw new Error('Transport not open');
-  }
-};
-
-/**
- * Called upon open
- *
- * @api private
- */
-
-Transport.prototype.onOpen = function () {
-  this.readyState = 'open';
-  this.writable = true;
-  this.emit('open');
-};
-
-/**
- * Called with data.
- *
- * @param {String} data
- * @api private
- */
-
-Transport.prototype.onData = function (data) {
-  var packet = parser.decodePacket(data, this.socket.binaryType);
-  this.onPacket(packet);
-};
-
-/**
- * Called with a decoded packet.
- */
-
-Transport.prototype.onPacket = function (packet) {
-  this.emit('packet', packet);
-};
-
-/**
- * Called upon close.
- *
- * @api private
- */
-
-Transport.prototype.onClose = function () {
-  this.readyState = 'closed';
-  this.emit('close');
-};
+var parser=require("engine.io-parser"),Emitter=require("component-emitter");function Transport(t){this.path=t.path,this.hostname=t.hostname,this.port=t.port,this.secure=t.secure,this.query=t.query,this.timestampParam=t.timestampParam,this.timestampRequests=t.timestampRequests,this.readyState="",this.agent=t.agent||!1,this.socket=t.socket,this.enablesXDR=t.enablesXDR,this.withCredentials=t.withCredentials,this.pfx=t.pfx,this.key=t.key,this.passphrase=t.passphrase,this.cert=t.cert,this.ca=t.ca,this.ciphers=t.ciphers,this.rejectUnauthorized=t.rejectUnauthorized,this.forceNode=t.forceNode,this.isReactNative=t.isReactNative,this.extraHeaders=t.extraHeaders,this.localAddress=t.localAddress}module.exports=Transport,Emitter(Transport.prototype),Transport.prototype.onError=function(t,e){var r=new Error(t);return r.type="TransportError",r.description=e,this.emit("error",r),this},Transport.prototype.open=function(){return"closed"!==this.readyState&&""!==this.readyState||(this.readyState="opening",this.doOpen()),this},Transport.prototype.close=function(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this},Transport.prototype.send=function(t){if("open"!==this.readyState)throw new Error("Transport not open");this.write(t)},Transport.prototype.onOpen=function(){this.readyState="open",this.writable=!0,this.emit("open")},Transport.prototype.onData=function(t){var e=parser.decodePacket(t,this.socket.binaryType);this.onPacket(e)},Transport.prototype.onPacket=function(t){this.emit("packet",t)},Transport.prototype.onClose=function(){this.readyState="closed",this.emit("close")};
\ No newline at end of file
index 62a8984..5ba376a 100755 (executable)
@@ -1,53 +1 @@
-/**
- * Module dependencies
- */
-
-var XMLHttpRequest = require('xmlhttprequest-ssl');
-var XHR = require('./polling-xhr');
-var JSONP = require('./polling-jsonp');
-var websocket = require('./websocket');
-
-/**
- * Export transports.
- */
-
-exports.polling = polling;
-exports.websocket = websocket;
-
-/**
- * Polling transport polymorphic constructor.
- * Decides on xhr vs jsonp based on feature detection.
- *
- * @api private
- */
-
-function polling (opts) {
-  var xhr;
-  var xd = false;
-  var xs = false;
-  var jsonp = false !== opts.jsonp;
-
-  if (typeof location !== 'undefined') {
-    var isSSL = 'https:' === location.protocol;
-    var port = location.port;
-
-    // some user agents have empty `location.port`
-    if (!port) {
-      port = isSSL ? 443 : 80;
-    }
-
-    xd = opts.hostname !== location.hostname || port !== opts.port;
-    xs = opts.secure !== isSSL;
-  }
-
-  opts.xdomain = xd;
-  opts.xscheme = xs;
-  xhr = new XMLHttpRequest(opts);
-
-  if ('open' in xhr && !opts.forceJSONP) {
-    return new XHR(opts);
-  } else {
-    if (!jsonp) throw new Error('JSONP disabled');
-    return new JSONP(opts);
-  }
-}
+var XMLHttpRequest=require("xmlhttprequest-ssl"),XHR=require("./polling-xhr"),JSONP=require("./polling-jsonp"),websocket=require("./websocket");function polling(e){var o=!1,t=!1,r=!1!==e.jsonp;if("undefined"!=typeof location){var n="https:"===location.protocol,i=location.port;i||(i=n?443:80),o=e.hostname!==location.hostname||i!==e.port,t=e.secure!==n}if(e.xdomain=o,e.xscheme=t,"open"in new XMLHttpRequest(e)&&!e.forceJSONP)return new XHR(e);if(!r)throw new Error("JSONP disabled");return new JSONP(e)}exports.polling=polling,exports.websocket=websocket;
\ No newline at end of file
index fe65705..2af84dc 100644 (file)
@@ -1,230 +1 @@
-/**
- * Module requirements.
- */
-
-var Polling = require('./polling');
-var inherit = require('component-inherit');
-var globalThis = require('../globalThis');
-
-/**
- * Module exports.
- */
-
-module.exports = JSONPPolling;
-
-/**
- * Cached regular expressions.
- */
-
-var rNewline = /\n/g;
-var rEscapedNewline = /\\n/g;
-
-/**
- * Global JSONP callbacks.
- */
-
-var callbacks;
-
-/**
- * Noop.
- */
-
-function empty () { }
-
-/**
- * JSONP Polling constructor.
- *
- * @param {Object} opts.
- * @api public
- */
-
-function JSONPPolling (opts) {
-  Polling.call(this, opts);
-
-  this.query = this.query || {};
-
-  // define global callbacks array if not present
-  // we do this here (lazily) to avoid unneeded global pollution
-  if (!callbacks) {
-    // we need to consider multiple engines in the same page
-    callbacks = globalThis.___eio = (globalThis.___eio || []);
-  }
-
-  // callback identifier
-  this.index = callbacks.length;
-
-  // add callback to jsonp global
-  var self = this;
-  callbacks.push(function (msg) {
-    self.onData(msg);
-  });
-
-  // append to query string
-  this.query.j = this.index;
-
-  // prevent spurious errors from being emitted when the window is unloaded
-  if (typeof addEventListener === 'function') {
-    addEventListener('beforeunload', function () {
-      if (self.script) self.script.onerror = empty;
-    }, false);
-  }
-}
-
-/**
- * Inherits from Polling.
- */
-
-inherit(JSONPPolling, Polling);
-
-/*
- * JSONP only supports binary as base64 encoded strings
- */
-
-JSONPPolling.prototype.supportsBinary = false;
-
-/**
- * Closes the socket.
- *
- * @api private
- */
-
-JSONPPolling.prototype.doClose = function () {
-  if (this.script) {
-    this.script.parentNode.removeChild(this.script);
-    this.script = null;
-  }
-
-  if (this.form) {
-    this.form.parentNode.removeChild(this.form);
-    this.form = null;
-    this.iframe = null;
-  }
-
-  Polling.prototype.doClose.call(this);
-};
-
-/**
- * Starts a poll cycle.
- *
- * @api private
- */
-
-JSONPPolling.prototype.doPoll = function () {
-  var self = this;
-  var script = document.createElement('script');
-
-  if (this.script) {
-    this.script.parentNode.removeChild(this.script);
-    this.script = null;
-  }
-
-  script.async = true;
-  script.src = this.uri();
-  script.onerror = function (e) {
-    self.onError('jsonp poll error', e);
-  };
-
-  var insertAt = document.getElementsByTagName('script')[0];
-  if (insertAt) {
-    insertAt.parentNode.insertBefore(script, insertAt);
-  } else {
-    (document.head || document.body).appendChild(script);
-  }
-  this.script = script;
-
-  var isUAgecko = 'undefined' !== typeof navigator && /gecko/i.test(navigator.userAgent);
-
-  if (isUAgecko) {
-    setTimeout(function () {
-      var iframe = document.createElement('iframe');
-      document.body.appendChild(iframe);
-      document.body.removeChild(iframe);
-    }, 100);
-  }
-};
-
-/**
- * Writes with a hidden iframe.
- *
- * @param {String} data to send
- * @param {Function} called upon flush.
- * @api private
- */
-
-JSONPPolling.prototype.doWrite = function (data, fn) {
-  var self = this;
-
-  if (!this.form) {
-    var form = document.createElement('form');
-    var area = document.createElement('textarea');
-    var id = this.iframeId = 'eio_iframe_' + this.index;
-    var iframe;
-
-    form.className = 'socketio';
-    form.style.position = 'absolute';
-    form.style.top = '-1000px';
-    form.style.left = '-1000px';
-    form.target = id;
-    form.method = 'POST';
-    form.setAttribute('accept-charset', 'utf-8');
-    area.name = 'd';
-    form.appendChild(area);
-    document.body.appendChild(form);
-
-    this.form = form;
-    this.area = area;
-  }
-
-  this.form.action = this.uri();
-
-  function complete () {
-    initIframe();
-    fn();
-  }
-
-  function initIframe () {
-    if (self.iframe) {
-      try {
-        self.form.removeChild(self.iframe);
-      } catch (e) {
-        self.onError('jsonp polling iframe removal error', e);
-      }
-    }
-
-    try {
-      // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
-      var html = '<iframe src="javascript:0" name="' + self.iframeId + '">';
-      iframe = document.createElement(html);
-    } catch (e) {
-      iframe = document.createElement('iframe');
-      iframe.name = self.iframeId;
-      iframe.src = 'javascript:0';
-    }
-
-    iframe.id = self.iframeId;
-
-    self.form.appendChild(iframe);
-    self.iframe = iframe;
-  }
-
-  initIframe();
-
-  // escape \n to prevent it from being converted into \r\n by some UAs
-  // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
-  data = data.replace(rEscapedNewline, '\\\n');
-  this.area.value = data.replace(rNewline, '\\n');
-
-  try {
-    this.form.submit();
-  } catch (e) {}
-
-  if (this.iframe.attachEvent) {
-    this.iframe.onreadystatechange = function () {
-      if (self.iframe.readyState === 'complete') {
-        complete();
-      }
-    };
-  } else {
-    this.iframe.onload = complete;
-  }
-};
+var Polling=require("./polling"),inherit=require("component-inherit"),globalThis=require("../globalThis");module.exports=JSONPPolling;var callbacks,rNewline=/\n/g,rEscapedNewline=/\\n/g;function empty(){}function JSONPPolling(e){Polling.call(this,e),this.query=this.query||{},callbacks||(callbacks=globalThis.___eio=globalThis.___eio||[]),this.index=callbacks.length;var t=this;callbacks.push((function(e){t.onData(e)})),this.query.j=this.index,"function"==typeof addEventListener&&addEventListener("beforeunload",(function(){t.script&&(t.script.onerror=empty)}),!1)}inherit(JSONPPolling,Polling),JSONPPolling.prototype.supportsBinary=!1,JSONPPolling.prototype.doClose=function(){this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),this.form&&(this.form.parentNode.removeChild(this.form),this.form=null,this.iframe=null),Polling.prototype.doClose.call(this)},JSONPPolling.prototype.doPoll=function(){var e=this,t=document.createElement("script");this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),t.async=!0,t.src=this.uri(),t.onerror=function(t){e.onError("jsonp poll error",t)};var i=document.getElementsByTagName("script")[0];i?i.parentNode.insertBefore(t,i):(document.head||document.body).appendChild(t),this.script=t,"undefined"!=typeof navigator&&/gecko/i.test(navigator.userAgent)&&setTimeout((function(){var e=document.createElement("iframe");document.body.appendChild(e),document.body.removeChild(e)}),100)},JSONPPolling.prototype.doWrite=function(e,t){var i=this;if(!this.form){var r,o=document.createElement("form"),n=document.createElement("textarea"),a=this.iframeId="eio_iframe_"+this.index;o.className="socketio",o.style.position="absolute",o.style.top="-1000px",o.style.left="-1000px",o.target=a,o.method="POST",o.setAttribute("accept-charset","utf-8"),n.name="d",o.appendChild(n),document.body.appendChild(o),this.form=o,this.area=n}function l(){s(),t()}function s(){if(i.iframe)try{i.form.removeChild(i.iframe)}catch(e){i.onError("jsonp polling iframe removal error",e)}try{var e='<iframe src="javascript:0" name="'+i.iframeId+'">';r=document.createElement(e)}catch(e){(r=document.createElement("iframe")).name=i.iframeId,r.src="javascript:0"}r.id=i.iframeId,i.form.appendChild(r),i.iframe=r}this.form.action=this.uri(),s(),e=e.replace(rEscapedNewline,"\\\n"),this.area.value=e.replace(rNewline,"\\n");try{this.form.submit()}catch(e){}this.iframe.attachEvent?this.iframe.onreadystatechange=function(){"complete"===i.iframe.readyState&&l()}:this.iframe.onload=l};
\ No newline at end of file
index 43f529c..3826800 100755 (executable)
@@ -1,418 +1 @@
-/* global attachEvent */
-
-/**
- * Module requirements.
- */
-
-var XMLHttpRequest = require('xmlhttprequest-ssl');
-var Polling = require('./polling');
-var Emitter = require('component-emitter');
-var inherit = require('component-inherit');
-var debug = require('debug')('engine.io-client:polling-xhr');
-var globalThis = require('../globalThis');
-
-/**
- * Module exports.
- */
-
-module.exports = XHR;
-module.exports.Request = Request;
-
-/**
- * Empty function
- */
-
-function empty () {}
-
-/**
- * XHR Polling constructor.
- *
- * @param {Object} opts
- * @api public
- */
-
-function XHR (opts) {
-  Polling.call(this, opts);
-  this.requestTimeout = opts.requestTimeout;
-  this.extraHeaders = opts.extraHeaders;
-
-  if (typeof location !== 'undefined') {
-    var isSSL = 'https:' === location.protocol;
-    var port = location.port;
-
-    // some user agents have empty `location.port`
-    if (!port) {
-      port = isSSL ? 443 : 80;
-    }
-
-    this.xd = (typeof location !== 'undefined' && opts.hostname !== location.hostname) ||
-      port !== opts.port;
-    this.xs = opts.secure !== isSSL;
-  }
-}
-
-/**
- * Inherits from Polling.
- */
-
-inherit(XHR, Polling);
-
-/**
- * XHR supports binary
- */
-
-XHR.prototype.supportsBinary = true;
-
-/**
- * Creates a request.
- *
- * @param {String} method
- * @api private
- */
-
-XHR.prototype.request = function (opts) {
-  opts = opts || {};
-  opts.uri = this.uri();
-  opts.xd = this.xd;
-  opts.xs = this.xs;
-  opts.agent = this.agent || false;
-  opts.supportsBinary = this.supportsBinary;
-  opts.enablesXDR = this.enablesXDR;
-  opts.withCredentials = this.withCredentials;
-
-  // SSL options for Node.js client
-  opts.pfx = this.pfx;
-  opts.key = this.key;
-  opts.passphrase = this.passphrase;
-  opts.cert = this.cert;
-  opts.ca = this.ca;
-  opts.ciphers = this.ciphers;
-  opts.rejectUnauthorized = this.rejectUnauthorized;
-  opts.requestTimeout = this.requestTimeout;
-
-  // other options for Node.js client
-  opts.extraHeaders = this.extraHeaders;
-
-  return new Request(opts);
-};
-
-/**
- * Sends data.
- *
- * @param {String} data to send.
- * @param {Function} called upon flush.
- * @api private
- */
-
-XHR.prototype.doWrite = function (data, fn) {
-  var isBinary = typeof data !== 'string' && data !== undefined;
-  var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
-  var self = this;
-  req.on('success', fn);
-  req.on('error', function (err) {
-    self.onError('xhr post error', err);
-  });
-  this.sendXhr = req;
-};
-
-/**
- * Starts a poll cycle.
- *
- * @api private
- */
-
-XHR.prototype.doPoll = function () {
-  debug('xhr poll');
-  var req = this.request();
-  var self = this;
-  req.on('data', function (data) {
-    self.onData(data);
-  });
-  req.on('error', function (err) {
-    self.onError('xhr poll error', err);
-  });
-  this.pollXhr = req;
-};
-
-/**
- * Request constructor
- *
- * @param {Object} options
- * @api public
- */
-
-function Request (opts) {
-  this.method = opts.method || 'GET';
-  this.uri = opts.uri;
-  this.xd = !!opts.xd;
-  this.xs = !!opts.xs;
-  this.async = false !== opts.async;
-  this.data = undefined !== opts.data ? opts.data : null;
-  this.agent = opts.agent;
-  this.isBinary = opts.isBinary;
-  this.supportsBinary = opts.supportsBinary;
-  this.enablesXDR = opts.enablesXDR;
-  this.withCredentials = opts.withCredentials;
-  this.requestTimeout = opts.requestTimeout;
-
-  // SSL options for Node.js client
-  this.pfx = opts.pfx;
-  this.key = opts.key;
-  this.passphrase = opts.passphrase;
-  this.cert = opts.cert;
-  this.ca = opts.ca;
-  this.ciphers = opts.ciphers;
-  this.rejectUnauthorized = opts.rejectUnauthorized;
-
-  // other options for Node.js client
-  this.extraHeaders = opts.extraHeaders;
-
-  this.create();
-}
-
-/**
- * Mix in `Emitter`.
- */
-
-Emitter(Request.prototype);
-
-/**
- * Creates the XHR object and sends the request.
- *
- * @api private
- */
-
-Request.prototype.create = function () {
-  var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
-
-  // SSL options for Node.js client
-  opts.pfx = this.pfx;
-  opts.key = this.key;
-  opts.passphrase = this.passphrase;
-  opts.cert = this.cert;
-  opts.ca = this.ca;
-  opts.ciphers = this.ciphers;
-  opts.rejectUnauthorized = this.rejectUnauthorized;
-
-  var xhr = this.xhr = new XMLHttpRequest(opts);
-  var self = this;
-
-  try {
-    debug('xhr open %s: %s', this.method, this.uri);
-    xhr.open(this.method, this.uri, this.async);
-    try {
-      if (this.extraHeaders) {
-        xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
-        for (var i in this.extraHeaders) {
-          if (this.extraHeaders.hasOwnProperty(i)) {
-            xhr.setRequestHeader(i, this.extraHeaders[i]);
-          }
-        }
-      }
-    } catch (e) {}
-
-    if ('POST' === this.method) {
-      try {
-        if (this.isBinary) {
-          xhr.setRequestHeader('Content-type', 'application/octet-stream');
-        } else {
-          xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
-        }
-      } catch (e) {}
-    }
-
-    try {
-      xhr.setRequestHeader('Accept', '*/*');
-    } catch (e) {}
-
-    // ie6 check
-    if ('withCredentials' in xhr) {
-      xhr.withCredentials = this.withCredentials;
-    }
-
-    if (this.requestTimeout) {
-      xhr.timeout = this.requestTimeout;
-    }
-
-    if (this.hasXDR()) {
-      xhr.onload = function () {
-        self.onLoad();
-      };
-      xhr.onerror = function () {
-        self.onError(xhr.responseText);
-      };
-    } else {
-      xhr.onreadystatechange = function () {
-        if (xhr.readyState === 2) {
-          try {
-            var contentType = xhr.getResponseHeader('Content-Type');
-            if (self.supportsBinary && contentType === 'application/octet-stream' || contentType === 'application/octet-stream; charset=UTF-8') {
-              xhr.responseType = 'arraybuffer';
-            }
-          } catch (e) {}
-        }
-        if (4 !== xhr.readyState) return;
-        if (200 === xhr.status || 1223 === xhr.status) {
-          self.onLoad();
-        } else {
-          // make sure the `error` event handler that's user-set
-          // does not throw in the same tick and gets caught here
-          setTimeout(function () {
-            self.onError(typeof xhr.status === 'number' ? xhr.status : 0);
-          }, 0);
-        }
-      };
-    }
-
-    debug('xhr data %s', this.data);
-    xhr.send(this.data);
-  } catch (e) {
-    // Need to defer since .create() is called directly fhrom the constructor
-    // and thus the 'error' event can only be only bound *after* this exception
-    // occurs.  Therefore, also, we cannot throw here at all.
-    setTimeout(function () {
-      self.onError(e);
-    }, 0);
-    return;
-  }
-
-  if (typeof document !== 'undefined') {
-    this.index = Request.requestsCount++;
-    Request.requests[this.index] = this;
-  }
-};
-
-/**
- * Called upon successful response.
- *
- * @api private
- */
-
-Request.prototype.onSuccess = function () {
-  this.emit('success');
-  this.cleanup();
-};
-
-/**
- * Called if we have data.
- *
- * @api private
- */
-
-Request.prototype.onData = function (data) {
-  this.emit('data', data);
-  this.onSuccess();
-};
-
-/**
- * Called upon error.
- *
- * @api private
- */
-
-Request.prototype.onError = function (err) {
-  this.emit('error', err);
-  this.cleanup(true);
-};
-
-/**
- * Cleans up house.
- *
- * @api private
- */
-
-Request.prototype.cleanup = function (fromError) {
-  if ('undefined' === typeof this.xhr || null === this.xhr) {
-    return;
-  }
-  // xmlhttprequest
-  if (this.hasXDR()) {
-    this.xhr.onload = this.xhr.onerror = empty;
-  } else {
-    this.xhr.onreadystatechange = empty;
-  }
-
-  if (fromError) {
-    try {
-      this.xhr.abort();
-    } catch (e) {}
-  }
-
-  if (typeof document !== 'undefined') {
-    delete Request.requests[this.index];
-  }
-
-  this.xhr = null;
-};
-
-/**
- * Called upon load.
- *
- * @api private
- */
-
-Request.prototype.onLoad = function () {
-  var data;
-  try {
-    var contentType;
-    try {
-      contentType = this.xhr.getResponseHeader('Content-Type');
-    } catch (e) {}
-    if (contentType === 'application/octet-stream' || contentType === 'application/octet-stream; charset=UTF-8') {
-      data = this.xhr.response || this.xhr.responseText;
-    } else {
-      data = this.xhr.responseText;
-    }
-  } catch (e) {
-    this.onError(e);
-  }
-  if (null != data) {
-    this.onData(data);
-  }
-};
-
-/**
- * Check if it has XDomainRequest.
- *
- * @api private
- */
-
-Request.prototype.hasXDR = function () {
-  return typeof XDomainRequest !== 'undefined' && !this.xs && this.enablesXDR;
-};
-
-/**
- * Aborts the request.
- *
- * @api public
- */
-
-Request.prototype.abort = function () {
-  this.cleanup();
-};
-
-/**
- * Aborts pending requests when unloading the window. This is needed to prevent
- * memory leaks (e.g. when using IE) and to ensure that no spurious error is
- * emitted.
- */
-
-Request.requestsCount = 0;
-Request.requests = {};
-
-if (typeof document !== 'undefined') {
-  if (typeof attachEvent === 'function') {
-    attachEvent('onunload', unloadHandler);
-  } else if (typeof addEventListener === 'function') {
-    var terminationEvent = 'onpagehide' in globalThis ? 'pagehide' : 'unload';
-    addEventListener(terminationEvent, unloadHandler, false);
-  }
-}
-
-function unloadHandler () {
-  for (var i in Request.requests) {
-    if (Request.requests.hasOwnProperty(i)) {
-      Request.requests[i].abort();
-    }
-  }
-}
+var XMLHttpRequest=require("xmlhttprequest-ssl"),Polling=require("./polling"),Emitter=require("component-emitter"),inherit=require("component-inherit"),debug=require("debug")("engine.io-client:polling-xhr"),globalThis=require("../globalThis");function empty(){}function XHR(t){if(Polling.call(this,t),this.requestTimeout=t.requestTimeout,this.extraHeaders=t.extraHeaders,"undefined"!=typeof location){var e="https:"===location.protocol,s=location.port;s||(s=e?443:80),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||s!==t.port,this.xs=t.secure!==e}}function Request(t){this.method=t.method||"GET",this.uri=t.uri,this.xd=!!t.xd,this.xs=!!t.xs,this.async=!1!==t.async,this.data=void 0!==t.data?t.data:null,this.agent=t.agent,this.isBinary=t.isBinary,this.supportsBinary=t.supportsBinary,this.enablesXDR=t.enablesXDR,this.withCredentials=t.withCredentials,this.requestTimeout=t.requestTimeout,this.pfx=t.pfx,this.key=t.key,this.passphrase=t.passphrase,this.cert=t.cert,this.ca=t.ca,this.ciphers=t.ciphers,this.rejectUnauthorized=t.rejectUnauthorized,this.extraHeaders=t.extraHeaders,this.create()}if(module.exports=XHR,module.exports.Request=Request,inherit(XHR,Polling),XHR.prototype.supportsBinary=!0,XHR.prototype.request=function(t){return(t=t||{}).uri=this.uri(),t.xd=this.xd,t.xs=this.xs,t.agent=this.agent||!1,t.supportsBinary=this.supportsBinary,t.enablesXDR=this.enablesXDR,t.withCredentials=this.withCredentials,t.pfx=this.pfx,t.key=this.key,t.passphrase=this.passphrase,t.cert=this.cert,t.ca=this.ca,t.ciphers=this.ciphers,t.rejectUnauthorized=this.rejectUnauthorized,t.requestTimeout=this.requestTimeout,t.extraHeaders=this.extraHeaders,new Request(t)},XHR.prototype.doWrite=function(t,e){var s="string"!=typeof t&&void 0!==t,i=this.request({method:"POST",data:t,isBinary:s}),r=this;i.on("success",e),i.on("error",(function(t){r.onError("xhr post error",t)})),this.sendXhr=i},XHR.prototype.doPoll=function(){debug("xhr poll");var t=this.request(),e=this;t.on("data",(function(t){e.onData(t)})),t.on("error",(function(t){e.onError("xhr poll error",t)})),this.pollXhr=t},Emitter(Request.prototype),Request.prototype.create=function(){var t={agent:this.agent,xdomain:this.xd,xscheme:this.xs,enablesXDR:this.enablesXDR};t.pfx=this.pfx,t.key=this.key,t.passphrase=this.passphrase,t.cert=this.cert,t.ca=this.ca,t.ciphers=this.ciphers,t.rejectUnauthorized=this.rejectUnauthorized;var e=this.xhr=new XMLHttpRequest(t),s=this;try{debug("xhr open %s: %s",this.method,this.uri),e.open(this.method,this.uri,this.async);try{if(this.extraHeaders)for(var i in e.setDisableHeaderCheck&&e.setDisableHeaderCheck(!0),this.extraHeaders)this.extraHeaders.hasOwnProperty(i)&&e.setRequestHeader(i,this.extraHeaders[i])}catch(t){}if("POST"===this.method)try{this.isBinary?e.setRequestHeader("Content-type","application/octet-stream"):e.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{e.setRequestHeader("Accept","*/*")}catch(t){}"withCredentials"in e&&(e.withCredentials=this.withCredentials),this.requestTimeout&&(e.timeout=this.requestTimeout),this.hasXDR()?(e.onload=function(){s.onLoad()},e.onerror=function(){s.onError(e.responseText)}):e.onreadystatechange=function(){if(2===e.readyState)try{var t=e.getResponseHeader("Content-Type");(s.supportsBinary&&"application/octet-stream"===t||"application/octet-stream; charset=UTF-8"===t)&&(e.responseType="arraybuffer")}catch(t){}4===e.readyState&&(200===e.status||1223===e.status?s.onLoad():setTimeout((function(){s.onError("number"==typeof e.status?e.status:0)}),0))},debug("xhr data %s",this.data),e.send(this.data)}catch(t){return void setTimeout((function(){s.onError(t)}),0)}"undefined"!=typeof document&&(this.index=Request.requestsCount++,Request.requests[this.index]=this)},Request.prototype.onSuccess=function(){this.emit("success"),this.cleanup()},Request.prototype.onData=function(t){this.emit("data",t),this.onSuccess()},Request.prototype.onError=function(t){this.emit("error",t),this.cleanup(!0)},Request.prototype.cleanup=function(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.hasXDR()?this.xhr.onload=this.xhr.onerror=empty:this.xhr.onreadystatechange=empty,t)try{this.xhr.abort()}catch(t){}"undefined"!=typeof document&&delete Request.requests[this.index],this.xhr=null}},Request.prototype.onLoad=function(){var t;try{var e;try{e=this.xhr.getResponseHeader("Content-Type")}catch(t){}t=("application/octet-stream"===e||"application/octet-stream; charset=UTF-8"===e)&&this.xhr.response||this.xhr.responseText}catch(t){this.onError(t)}null!=t&&this.onData(t)},Request.prototype.hasXDR=function(){return"undefined"!=typeof XDomainRequest&&!this.xs&&this.enablesXDR},Request.prototype.abort=function(){this.cleanup()},Request.requestsCount=0,Request.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",unloadHandler);else if("function"==typeof addEventListener){var terminationEvent="onpagehide"in globalThis?"pagehide":"unload";addEventListener(terminationEvent,unloadHandler,!1)}function unloadHandler(){for(var t in Request.requests)Request.requests.hasOwnProperty(t)&&Request.requests[t].abort()}
\ No newline at end of file
index 786398b..407cb50 100644 (file)
@@ -1,245 +1 @@
-/**
- * Module dependencies.
- */
-
-var Transport = require('../transport');
-var parseqs = require('parseqs');
-var parser = require('engine.io-parser');
-var inherit = require('component-inherit');
-var yeast = require('yeast');
-var debug = require('debug')('engine.io-client:polling');
-
-/**
- * Module exports.
- */
-
-module.exports = Polling;
-
-/**
- * Is XHR2 supported?
- */
-
-var hasXHR2 = (function () {
-  var XMLHttpRequest = require('xmlhttprequest-ssl');
-  var xhr = new XMLHttpRequest({ xdomain: false });
-  return null != xhr.responseType;
-})();
-
-/**
- * Polling interface.
- *
- * @param {Object} opts
- * @api private
- */
-
-function Polling (opts) {
-  var forceBase64 = (opts && opts.forceBase64);
-  if (!hasXHR2 || forceBase64) {
-    this.supportsBinary = false;
-  }
-  Transport.call(this, opts);
-}
-
-/**
- * Inherits from Transport.
- */
-
-inherit(Polling, Transport);
-
-/**
- * Transport name.
- */
-
-Polling.prototype.name = 'polling';
-
-/**
- * Opens the socket (triggers polling). We write a PING message to determine
- * when the transport is open.
- *
- * @api private
- */
-
-Polling.prototype.doOpen = function () {
-  this.poll();
-};
-
-/**
- * Pauses polling.
- *
- * @param {Function} callback upon buffers are flushed and transport is paused
- * @api private
- */
-
-Polling.prototype.pause = function (onPause) {
-  var self = this;
-
-  this.readyState = 'pausing';
-
-  function pause () {
-    debug('paused');
-    self.readyState = 'paused';
-    onPause();
-  }
-
-  if (this.polling || !this.writable) {
-    var total = 0;
-
-    if (this.polling) {
-      debug('we are currently polling - waiting to pause');
-      total++;
-      this.once('pollComplete', function () {
-        debug('pre-pause polling complete');
-        --total || pause();
-      });
-    }
-
-    if (!this.writable) {
-      debug('we are currently writing - waiting to pause');
-      total++;
-      this.once('drain', function () {
-        debug('pre-pause writing complete');
-        --total || pause();
-      });
-    }
-  } else {
-    pause();
-  }
-};
-
-/**
- * Starts polling cycle.
- *
- * @api public
- */
-
-Polling.prototype.poll = function () {
-  debug('polling');
-  this.polling = true;
-  this.doPoll();
-  this.emit('poll');
-};
-
-/**
- * Overloads onData to detect payloads.
- *
- * @api private
- */
-
-Polling.prototype.onData = function (data) {
-  var self = this;
-  debug('polling got data %s', data);
-  var callback = function (packet, index, total) {
-    // if its the first message we consider the transport open
-    if ('opening' === self.readyState && packet.type === 'open') {
-      self.onOpen();
-    }
-
-    // if its a close packet, we close the ongoing requests
-    if ('close' === packet.type) {
-      self.onClose();
-      return false;
-    }
-
-    // otherwise bypass onData and handle the message
-    self.onPacket(packet);
-  };
-
-  // decode payload
-  parser.decodePayload(data, this.socket.binaryType, callback);
-
-  // if an event did not trigger closing
-  if ('closed' !== this.readyState) {
-    // if we got data we're not polling
-    this.polling = false;
-    this.emit('pollComplete');
-
-    if ('open' === this.readyState) {
-      this.poll();
-    } else {
-      debug('ignoring poll - transport state "%s"', this.readyState);
-    }
-  }
-};
-
-/**
- * For polling, send a close packet.
- *
- * @api private
- */
-
-Polling.prototype.doClose = function () {
-  var self = this;
-
-  function close () {
-    debug('writing close packet');
-    self.write([{ type: 'close' }]);
-  }
-
-  if ('open' === this.readyState) {
-    debug('transport open - closing');
-    close();
-  } else {
-    // in case we're trying to close while
-    // handshaking is in progress (GH-164)
-    debug('transport not open - deferring close');
-    this.once('open', close);
-  }
-};
-
-/**
- * Writes a packets payload.
- *
- * @param {Array} data packets
- * @param {Function} drain callback
- * @api private
- */
-
-Polling.prototype.write = function (packets) {
-  var self = this;
-  this.writable = false;
-  var callbackfn = function () {
-    self.writable = true;
-    self.emit('drain');
-  };
-
-  parser.encodePayload(packets, this.supportsBinary, function (data) {
-    self.doWrite(data, callbackfn);
-  });
-};
-
-/**
- * Generates uri for connection.
- *
- * @api private
- */
-
-Polling.prototype.uri = function () {
-  var query = this.query || {};
-  var schema = this.secure ? 'https' : 'http';
-  var port = '';
-
-  // cache busting is forced
-  if (false !== this.timestampRequests) {
-    query[this.timestampParam] = yeast();
-  }
-
-  if (!this.supportsBinary && !query.sid) {
-    query.b64 = 1;
-  }
-
-  query = parseqs.encode(query);
-
-  // avoid port if default for schema
-  if (this.port && (('https' === schema && Number(this.port) !== 443) ||
-     ('http' === schema && Number(this.port) !== 80))) {
-    port = ':' + this.port;
-  }
-
-  // prepend ? to query
-  if (query.length) {
-    query = '?' + query;
-  }
-
-  var ipv6 = this.hostname.indexOf(':') !== -1;
-  return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
-};
+var Transport=require("../transport"),parseqs=require("parseqs"),parser=require("engine.io-parser"),inherit=require("component-inherit"),yeast=require("yeast"),debug=require("debug")("engine.io-client:polling");module.exports=Polling;var hasXHR2=null!=new(require("xmlhttprequest-ssl"))({xdomain:!1}).responseType;function Polling(t){var e=t&&t.forceBase64;hasXHR2&&!e||(this.supportsBinary=!1),Transport.call(this,t)}inherit(Polling,Transport),Polling.prototype.name="polling",Polling.prototype.doOpen=function(){this.poll()},Polling.prototype.pause=function(t){var e=this;function i(){debug("paused"),e.readyState="paused",t()}if(this.readyState="pausing",this.polling||!this.writable){var o=0;this.polling&&(debug("we are currently polling - waiting to pause"),o++,this.once("pollComplete",(function(){debug("pre-pause polling complete"),--o||i()}))),this.writable||(debug("we are currently writing - waiting to pause"),o++,this.once("drain",(function(){debug("pre-pause writing complete"),--o||i()})))}else i()},Polling.prototype.poll=function(){debug("polling"),this.polling=!0,this.doPoll(),this.emit("poll")},Polling.prototype.onData=function(t){var e=this;debug("polling got data %s",t);parser.decodePayload(t,this.socket.binaryType,(function(t,i,o){if("opening"===e.readyState&&"open"===t.type&&e.onOpen(),"close"===t.type)return e.onClose(),!1;e.onPacket(t)})),"closed"!==this.readyState&&(this.polling=!1,this.emit("pollComplete"),"open"===this.readyState?this.poll():debug('ignoring poll - transport state "%s"',this.readyState))},Polling.prototype.doClose=function(){var t=this;function e(){debug("writing close packet"),t.write([{type:"close"}])}"open"===this.readyState?(debug("transport open - closing"),e()):(debug("transport not open - deferring close"),this.once("open",e))},Polling.prototype.write=function(t){var e=this;this.writable=!1;var i=function(){e.writable=!0,e.emit("drain")};parser.encodePayload(t,this.supportsBinary,(function(t){e.doWrite(t,i)}))},Polling.prototype.uri=function(){var t=this.query||{},e=this.secure?"https":"http",i="";return!1!==this.timestampRequests&&(t[this.timestampParam]=yeast()),this.supportsBinary||t.sid||(t.b64=1),t=parseqs.encode(t),this.port&&("https"===e&&443!==Number(this.port)||"http"===e&&80!==Number(this.port))&&(i=":"+this.port),t.length&&(t="?"+t),e+"://"+(-1!==this.hostname.indexOf(":")?"["+this.hostname+"]":this.hostname)+i+this.path+t};
\ No newline at end of file
index f9c4b7a..dd9ce56 100644 (file)
@@ -1,299 +1 @@
-/**
- * Module dependencies.
- */
-
-var Transport = require('../transport');
-var parser = require('engine.io-parser');
-var parseqs = require('parseqs');
-var inherit = require('component-inherit');
-var yeast = require('yeast');
-var debug = require('debug')('engine.io-client:websocket');
-
-var BrowserWebSocket, NodeWebSocket;
-
-if (typeof WebSocket !== 'undefined') {
-  BrowserWebSocket = WebSocket;
-} else if (typeof self !== 'undefined') {
-  BrowserWebSocket = self.WebSocket || self.MozWebSocket;
-}
-
-if (typeof window === 'undefined') {
-  try {
-    NodeWebSocket = require('ws');
-  } catch (e) { }
-}
-
-/**
- * Get either the `WebSocket` or `MozWebSocket` globals
- * in the browser or try to resolve WebSocket-compatible
- * interface exposed by `ws` for Node-like environment.
- */
-
-var WebSocketImpl = BrowserWebSocket || NodeWebSocket;
-
-/**
- * Module exports.
- */
-
-module.exports = WS;
-
-/**
- * WebSocket transport constructor.
- *
- * @api {Object} connection options
- * @api public
- */
-
-function WS (opts) {
-  var forceBase64 = (opts && opts.forceBase64);
-  if (forceBase64) {
-    this.supportsBinary = false;
-  }
-  this.perMessageDeflate = opts.perMessageDeflate;
-  this.usingBrowserWebSocket = BrowserWebSocket && !opts.forceNode;
-  this.protocols = opts.protocols;
-  if (!this.usingBrowserWebSocket) {
-    WebSocketImpl = NodeWebSocket;
-  }
-  Transport.call(this, opts);
-}
-
-/**
- * Inherits from Transport.
- */
-
-inherit(WS, Transport);
-
-/**
- * Transport name.
- *
- * @api public
- */
-
-WS.prototype.name = 'websocket';
-
-/*
- * WebSockets support binary
- */
-
-WS.prototype.supportsBinary = true;
-
-/**
- * Opens socket.
- *
- * @api private
- */
-
-WS.prototype.doOpen = function () {
-  if (!this.check()) {
-    // let probe timeout
-    return;
-  }
-
-  var uri = this.uri();
-  var protocols = this.protocols;
-
-  var opts = {};
-
-  if (!this.isReactNative) {
-    opts.agent = this.agent;
-    opts.perMessageDeflate = this.perMessageDeflate;
-
-    // SSL options for Node.js client
-    opts.pfx = this.pfx;
-    opts.key = this.key;
-    opts.passphrase = this.passphrase;
-    opts.cert = this.cert;
-    opts.ca = this.ca;
-    opts.ciphers = this.ciphers;
-    opts.rejectUnauthorized = this.rejectUnauthorized;
-  }
-
-  if (this.extraHeaders) {
-    opts.headers = this.extraHeaders;
-  }
-  if (this.localAddress) {
-    opts.localAddress = this.localAddress;
-  }
-
-  try {
-    this.ws =
-      this.usingBrowserWebSocket && !this.isReactNative
-        ? protocols
-          ? new WebSocketImpl(uri, protocols)
-          : new WebSocketImpl(uri)
-        : new WebSocketImpl(uri, protocols, opts);
-  } catch (err) {
-    return this.emit('error', err);
-  }
-
-  if (this.ws.binaryType === undefined) {
-    this.supportsBinary = false;
-  }
-
-  if (this.ws.supports && this.ws.supports.binary) {
-    this.supportsBinary = true;
-    this.ws.binaryType = 'nodebuffer';
-  } else {
-    this.ws.binaryType = 'arraybuffer';
-  }
-
-  this.addEventListeners();
-};
-
-/**
- * Adds event listeners to the socket
- *
- * @api private
- */
-
-WS.prototype.addEventListeners = function () {
-  var self = this;
-
-  this.ws.onopen = function () {
-    self.onOpen();
-  };
-  this.ws.onclose = function () {
-    self.onClose();
-  };
-  this.ws.onmessage = function (ev) {
-    self.onData(ev.data);
-  };
-  this.ws.onerror = function (e) {
-    self.onError('websocket error', e);
-  };
-};
-
-/**
- * Writes data to socket.
- *
- * @param {Array} array of packets.
- * @api private
- */
-
-WS.prototype.write = function (packets) {
-  var self = this;
-  this.writable = false;
-
-  // encodePacket efficient as it uses WS framing
-  // no need for encodePayload
-  var total = packets.length;
-  for (var i = 0, l = total; i < l; i++) {
-    (function (packet) {
-      parser.encodePacket(packet, self.supportsBinary, function (data) {
-        if (!self.usingBrowserWebSocket) {
-          // always create a new object (GH-437)
-          var opts = {};
-          if (packet.options) {
-            opts.compress = packet.options.compress;
-          }
-
-          if (self.perMessageDeflate) {
-            var len = 'string' === typeof data ? Buffer.byteLength(data) : data.length;
-            if (len < self.perMessageDeflate.threshold) {
-              opts.compress = false;
-            }
-          }
-        }
-
-        // Sometimes the websocket has already been closed but the browser didn't
-        // have a chance of informing us about it yet, in that case send will
-        // throw an error
-        try {
-          if (self.usingBrowserWebSocket) {
-            // TypeError is thrown when passing the second argument on Safari
-            self.ws.send(data);
-          } else {
-            self.ws.send(data, opts);
-          }
-        } catch (e) {
-          debug('websocket closed before onclose event');
-        }
-
-        --total || done();
-      });
-    })(packets[i]);
-  }
-
-  function done () {
-    self.emit('flush');
-
-    // fake drain
-    // defer to next tick to allow Socket to clear writeBuffer
-    setTimeout(function () {
-      self.writable = true;
-      self.emit('drain');
-    }, 0);
-  }
-};
-
-/**
- * Called upon close
- *
- * @api private
- */
-
-WS.prototype.onClose = function () {
-  Transport.prototype.onClose.call(this);
-};
-
-/**
- * Closes socket.
- *
- * @api private
- */
-
-WS.prototype.doClose = function () {
-  if (typeof this.ws !== 'undefined') {
-    this.ws.close();
-  }
-};
-
-/**
- * Generates uri for connection.
- *
- * @api private
- */
-
-WS.prototype.uri = function () {
-  var query = this.query || {};
-  var schema = this.secure ? 'wss' : 'ws';
-  var port = '';
-
-  // avoid port if default for schema
-  if (this.port && (('wss' === schema && Number(this.port) !== 443) ||
-    ('ws' === schema && Number(this.port) !== 80))) {
-    port = ':' + this.port;
-  }
-
-  // append timestamp to URI
-  if (this.timestampRequests) {
-    query[this.timestampParam] = yeast();
-  }
-
-  // communicate binary support capabilities
-  if (!this.supportsBinary) {
-    query.b64 = 1;
-  }
-
-  query = parseqs.encode(query);
-
-  // prepend ? to query
-  if (query.length) {
-    query = '?' + query;
-  }
-
-  var ipv6 = this.hostname.indexOf(':') !== -1;
-  return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
-};
-
-/**
- * Feature detection for WebSocket.
- *
- * @return {Boolean} whether this transport is available.
- * @api public
- */
-
-WS.prototype.check = function () {
-  return !!WebSocketImpl && !('__initialize' in WebSocketImpl && this.name === WS.prototype.name);
-};
+var BrowserWebSocket,NodeWebSocket,Transport=require("../transport"),parser=require("engine.io-parser"),parseqs=require("parseqs"),inherit=require("component-inherit"),yeast=require("yeast"),debug=require("debug")("engine.io-client:websocket");if("undefined"!=typeof WebSocket?BrowserWebSocket=WebSocket:"undefined"!=typeof self&&(BrowserWebSocket=self.WebSocket||self.MozWebSocket),"undefined"==typeof window)try{NodeWebSocket=require("ws")}catch(e){}var WebSocketImpl=BrowserWebSocket||NodeWebSocket;function WS(e){e&&e.forceBase64&&(this.supportsBinary=!1),this.perMessageDeflate=e.perMessageDeflate,this.usingBrowserWebSocket=BrowserWebSocket&&!e.forceNode,this.protocols=e.protocols,this.usingBrowserWebSocket||(WebSocketImpl=NodeWebSocket),Transport.call(this,e)}module.exports=WS,inherit(WS,Transport),WS.prototype.name="websocket",WS.prototype.supportsBinary=!0,WS.prototype.doOpen=function(){if(this.check()){var e=this.uri(),t=this.protocols,s={};this.isReactNative||(s.agent=this.agent,s.perMessageDeflate=this.perMessageDeflate,s.pfx=this.pfx,s.key=this.key,s.passphrase=this.passphrase,s.cert=this.cert,s.ca=this.ca,s.ciphers=this.ciphers,s.rejectUnauthorized=this.rejectUnauthorized),this.extraHeaders&&(s.headers=this.extraHeaders),this.localAddress&&(s.localAddress=this.localAddress);try{this.ws=this.usingBrowserWebSocket&&!this.isReactNative?t?new WebSocketImpl(e,t):new WebSocketImpl(e):new WebSocketImpl(e,t,s)}catch(e){return this.emit("error",e)}void 0===this.ws.binaryType&&(this.supportsBinary=!1),this.ws.supports&&this.ws.supports.binary?(this.supportsBinary=!0,this.ws.binaryType="nodebuffer"):this.ws.binaryType="arraybuffer",this.addEventListeners()}},WS.prototype.addEventListeners=function(){var e=this;this.ws.onopen=function(){e.onOpen()},this.ws.onclose=function(){e.onClose()},this.ws.onmessage=function(t){e.onData(t.data)},this.ws.onerror=function(t){e.onError("websocket error",t)}},WS.prototype.write=function(e){var t=this;this.writable=!1;for(var s=e.length,r=0,o=s;r<o;r++)!function(e){parser.encodePacket(e,t.supportsBinary,(function(r){if(!t.usingBrowserWebSocket){var o={};if(e.options&&(o.compress=e.options.compress),t.perMessageDeflate)("string"==typeof r?Buffer.byteLength(r):r.length)<t.perMessageDeflate.threshold&&(o.compress=!1)}try{t.usingBrowserWebSocket?t.ws.send(r):t.ws.send(r,o)}catch(e){debug("websocket closed before onclose event")}--s||i()}))}(e[r]);function i(){t.emit("flush"),setTimeout((function(){t.writable=!0,t.emit("drain")}),0)}},WS.prototype.onClose=function(){Transport.prototype.onClose.call(this)},WS.prototype.doClose=function(){void 0!==this.ws&&this.ws.close()},WS.prototype.uri=function(){var e=this.query||{},t=this.secure?"wss":"ws",s="";return this.port&&("wss"===t&&443!==Number(this.port)||"ws"===t&&80!==Number(this.port))&&(s=":"+this.port),this.timestampRequests&&(e[this.timestampParam]=yeast()),this.supportsBinary||(e.b64=1),(e=parseqs.encode(e)).length&&(e="?"+e),t+"://"+(-1!==this.hostname.indexOf(":")?"["+this.hostname+"]":this.hostname)+s+this.path+e},WS.prototype.check=function(){return!(!WebSocketImpl||"__initialize"in WebSocketImpl&&this.name===WS.prototype.name)};
\ No newline at end of file
index 9d078c1..c9230c6 100644 (file)
@@ -1,38 +1 @@
-// browser shim for xmlhttprequest module
-
-var hasCORS = require('has-cors');
-var globalThis = require('./globalThis');
-
-module.exports = function (opts) {
-  var xdomain = opts.xdomain;
-
-  // scheme must be same when usign XDomainRequest
-  // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
-  var xscheme = opts.xscheme;
-
-  // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
-  // https://github.com/Automattic/engine.io-client/pull/217
-  var enablesXDR = opts.enablesXDR;
-
-  // XMLHttpRequest can be disabled on IE
-  try {
-    if ('undefined' !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
-      return new XMLHttpRequest();
-    }
-  } catch (e) { }
-
-  // Use XDomainRequest for IE8 if enablesXDR is true
-  // because loading bar keeps flashing when using jsonp-polling
-  // https://github.com/yujiosaka/socke.io-ie8-loading-example
-  try {
-    if ('undefined' !== typeof XDomainRequest && !xscheme && enablesXDR) {
-      return new XDomainRequest();
-    }
-  } catch (e) { }
-
-  if (!xdomain) {
-    try {
-      return new globalThis[['Active'].concat('Object').join('X')]('Microsoft.XMLHTTP');
-    } catch (e) { }
-  }
-};
+var hasCORS=require("has-cors"),globalThis=require("./globalThis");module.exports=function(e){var t=e.xdomain,n=e.xscheme,r=e.enablesXDR;try{if("undefined"!=typeof XMLHttpRequest&&(!t||hasCORS))return new XMLHttpRequest}catch(e){}try{if("undefined"!=typeof XDomainRequest&&!n&&r)return new XDomainRequest}catch(e){}if(!t)try{return new(globalThis[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}};
\ No newline at end of file
index 26b0964..1c78450 100644 (file)
@@ -1,605 +1 @@
-/**
- * Module dependencies.
- */
-
-var keys = require('./keys');
-var hasBinary = require('has-binary2');
-var sliceBuffer = require('arraybuffer.slice');
-var after = require('after');
-var utf8 = require('./utf8');
-
-var base64encoder;
-if (typeof ArrayBuffer !== 'undefined') {
-  base64encoder = require('base64-arraybuffer');
-}
-
-/**
- * Check if we are running an android browser. That requires us to use
- * ArrayBuffer with polling transports...
- *
- * http://ghinda.net/jpeg-blob-ajax-android/
- */
-
-var isAndroid = typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent);
-
-/**
- * Check if we are running in PhantomJS.
- * Uploading a Blob with PhantomJS does not work correctly, as reported here:
- * https://github.com/ariya/phantomjs/issues/11395
- * @type boolean
- */
-var isPhantomJS = typeof navigator !== 'undefined' && /PhantomJS/i.test(navigator.userAgent);
-
-/**
- * When true, avoids using Blobs to encode payloads.
- * @type boolean
- */
-var dontSendBlobs = isAndroid || isPhantomJS;
-
-/**
- * Current protocol version.
- */
-
-exports.protocol = 3;
-
-/**
- * Packet types.
- */
-
-var packets = exports.packets = {
-    open:     0    // non-ws
-  , close:    1    // non-ws
-  , ping:     2
-  , pong:     3
-  , message:  4
-  , upgrade:  5
-  , noop:     6
-};
-
-var packetslist = keys(packets);
-
-/**
- * Premade error packet.
- */
-
-var err = { type: 'error', data: 'parser error' };
-
-/**
- * Create a blob api even for blob builder when vendor prefixes exist
- */
-
-var Blob = require('blob');
-
-/**
- * Encodes a packet.
- *
- *     <packet type id> [ <data> ]
- *
- * Example:
- *
- *     5hello world
- *     3
- *     4
- *
- * Binary is encoded in an identical principle
- *
- * @api private
- */
-
-exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
-  if (typeof supportsBinary === 'function') {
-    callback = supportsBinary;
-    supportsBinary = false;
-  }
-
-  if (typeof utf8encode === 'function') {
-    callback = utf8encode;
-    utf8encode = null;
-  }
-
-  var data = (packet.data === undefined)
-    ? undefined
-    : packet.data.buffer || packet.data;
-
-  if (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer) {
-    return encodeArrayBuffer(packet, supportsBinary, callback);
-  } else if (typeof Blob !== 'undefined' && data instanceof Blob) {
-    return encodeBlob(packet, supportsBinary, callback);
-  }
-
-  // might be an object with { base64: true, data: dataAsBase64String }
-  if (data && data.base64) {
-    return encodeBase64Object(packet, callback);
-  }
-
-  // Sending data as a utf-8 string
-  var encoded = packets[packet.type];
-
-  // data fragment is optional
-  if (undefined !== packet.data) {
-    encoded += utf8encode ? utf8.encode(String(packet.data), { strict: false }) : String(packet.data);
-  }
-
-  return callback('' + encoded);
-
-};
-
-function encodeBase64Object(packet, callback) {
-  // packet data is an object { base64: true, data: dataAsBase64String }
-  var message = 'b' + exports.packets[packet.type] + packet.data.data;
-  return callback(message);
-}
-
-/**
- * Encode packet helpers for binary types
- */
-
-function encodeArrayBuffer(packet, supportsBinary, callback) {
-  if (!supportsBinary) {
-    return exports.encodeBase64Packet(packet, callback);
-  }
-
-  var data = packet.data;
-  var contentArray = new Uint8Array(data);
-  var resultBuffer = new Uint8Array(1 + data.byteLength);
-
-  resultBuffer[0] = packets[packet.type];
-  for (var i = 0; i < contentArray.length; i++) {
-    resultBuffer[i+1] = contentArray[i];
-  }
-
-  return callback(resultBuffer.buffer);
-}
-
-function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
-  if (!supportsBinary) {
-    return exports.encodeBase64Packet(packet, callback);
-  }
-
-  var fr = new FileReader();
-  fr.onload = function() {
-    exports.encodePacket({ type: packet.type, data: fr.result }, supportsBinary, true, callback);
-  };
-  return fr.readAsArrayBuffer(packet.data);
-}
-
-function encodeBlob(packet, supportsBinary, callback) {
-  if (!supportsBinary) {
-    return exports.encodeBase64Packet(packet, callback);
-  }
-
-  if (dontSendBlobs) {
-    return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
-  }
-
-  var length = new Uint8Array(1);
-  length[0] = packets[packet.type];
-  var blob = new Blob([length.buffer, packet.data]);
-
-  return callback(blob);
-}
-
-/**
- * Encodes a packet with binary data in a base64 string
- *
- * @param {Object} packet, has `type` and `data`
- * @return {String} base64 encoded message
- */
-
-exports.encodeBase64Packet = function(packet, callback) {
-  var message = 'b' + exports.packets[packet.type];
-  if (typeof Blob !== 'undefined' && packet.data instanceof Blob) {
-    var fr = new FileReader();
-    fr.onload = function() {
-      var b64 = fr.result.split(',')[1];
-      callback(message + b64);
-    };
-    return fr.readAsDataURL(packet.data);
-  }
-
-  var b64data;
-  try {
-    b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
-  } catch (e) {
-    // iPhone Safari doesn't let you apply with typed arrays
-    var typed = new Uint8Array(packet.data);
-    var basic = new Array(typed.length);
-    for (var i = 0; i < typed.length; i++) {
-      basic[i] = typed[i];
-    }
-    b64data = String.fromCharCode.apply(null, basic);
-  }
-  message += btoa(b64data);
-  return callback(message);
-};
-
-/**
- * Decodes a packet. Changes format to Blob if requested.
- *
- * @return {Object} with `type` and `data` (if any)
- * @api private
- */
-
-exports.decodePacket = function (data, binaryType, utf8decode) {
-  if (data === undefined) {
-    return err;
-  }
-  // String data
-  if (typeof data === 'string') {
-    if (data.charAt(0) === 'b') {
-      return exports.decodeBase64Packet(data.substr(1), binaryType);
-    }
-
-    if (utf8decode) {
-      data = tryDecode(data);
-      if (data === false) {
-        return err;
-      }
-    }
-    var type = data.charAt(0);
-
-    if (Number(type) != type || !packetslist[type]) {
-      return err;
-    }
-
-    if (data.length > 1) {
-      return { type: packetslist[type], data: data.substring(1) };
-    } else {
-      return { type: packetslist[type] };
-    }
-  }
-
-  var asArray = new Uint8Array(data);
-  var type = asArray[0];
-  var rest = sliceBuffer(data, 1);
-  if (Blob && binaryType === 'blob') {
-    rest = new Blob([rest]);
-  }
-  return { type: packetslist[type], data: rest };
-};
-
-function tryDecode(data) {
-  try {
-    data = utf8.decode(data, { strict: false });
-  } catch (e) {
-    return false;
-  }
-  return data;
-}
-
-/**
- * Decodes a packet encoded in a base64 string
- *
- * @param {String} base64 encoded message
- * @return {Object} with `type` and `data` (if any)
- */
-
-exports.decodeBase64Packet = function(msg, binaryType) {
-  var type = packetslist[msg.charAt(0)];
-  if (!base64encoder) {
-    return { type: type, data: { base64: true, data: msg.substr(1) } };
-  }
-
-  var data = base64encoder.decode(msg.substr(1));
-
-  if (binaryType === 'blob' && Blob) {
-    data = new Blob([data]);
-  }
-
-  return { type: type, data: data };
-};
-
-/**
- * Encodes multiple messages (payload).
- *
- *     <length>:data
- *
- * Example:
- *
- *     11:hello world2:hi
- *
- * If any contents are binary, they will be encoded as base64 strings. Base64
- * encoded strings are marked with a b before the length specifier
- *
- * @param {Array} packets
- * @api private
- */
-
-exports.encodePayload = function (packets, supportsBinary, callback) {
-  if (typeof supportsBinary === 'function') {
-    callback = supportsBinary;
-    supportsBinary = null;
-  }
-
-  var isBinary = hasBinary(packets);
-
-  if (supportsBinary && isBinary) {
-    if (Blob && !dontSendBlobs) {
-      return exports.encodePayloadAsBlob(packets, callback);
-    }
-
-    return exports.encodePayloadAsArrayBuffer(packets, callback);
-  }
-
-  if (!packets.length) {
-    return callback('0:');
-  }
-
-  function setLengthHeader(message) {
-    return message.length + ':' + message;
-  }
-
-  function encodeOne(packet, doneCallback) {
-    exports.encodePacket(packet, !isBinary ? false : supportsBinary, false, function(message) {
-      doneCallback(null, setLengthHeader(message));
-    });
-  }
-
-  map(packets, encodeOne, function(err, results) {
-    return callback(results.join(''));
-  });
-};
-
-/**
- * Async array map using after
- */
-
-function map(ary, each, done) {
-  var result = new Array(ary.length);
-  var next = after(ary.length, done);
-
-  var eachWithIndex = function(i, el, cb) {
-    each(el, function(error, msg) {
-      result[i] = msg;
-      cb(error, result);
-    });
-  };
-
-  for (var i = 0; i < ary.length; i++) {
-    eachWithIndex(i, ary[i], next);
-  }
-}
-
-/*
- * Decodes data when a payload is maybe expected. Possible binary contents are
- * decoded from their base64 representation
- *
- * @param {String} data, callback method
- * @api public
- */
-
-exports.decodePayload = function (data, binaryType, callback) {
-  if (typeof data !== 'string') {
-    return exports.decodePayloadAsBinary(data, binaryType, callback);
-  }
-
-  if (typeof binaryType === 'function') {
-    callback = binaryType;
-    binaryType = null;
-  }
-
-  var packet;
-  if (data === '') {
-    // parser error - ignoring payload
-    return callback(err, 0, 1);
-  }
-
-  var length = '', n, msg;
-
-  for (var i = 0, l = data.length; i < l; i++) {
-    var chr = data.charAt(i);
-
-    if (chr !== ':') {
-      length += chr;
-      continue;
-    }
-
-    if (length === '' || (length != (n = Number(length)))) {
-      // parser error - ignoring payload
-      return callback(err, 0, 1);
-    }
-
-    msg = data.substr(i + 1, n);
-
-    if (length != msg.length) {
-      // parser error - ignoring payload
-      return callback(err, 0, 1);
-    }
-
-    if (msg.length) {
-      packet = exports.decodePacket(msg, binaryType, false);
-
-      if (err.type === packet.type && err.data === packet.data) {
-        // parser error in individual packet - ignoring payload
-        return callback(err, 0, 1);
-      }
-
-      var ret = callback(packet, i + n, l);
-      if (false === ret) return;
-    }
-
-    // advance cursor
-    i += n;
-    length = '';
-  }
-
-  if (length !== '') {
-    // parser error - ignoring payload
-    return callback(err, 0, 1);
-  }
-
-};
-
-/**
- * Encodes multiple messages (payload) as binary.
- *
- * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
- * 255><data>
- *
- * Example:
- * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
- *
- * @param {Array} packets
- * @return {ArrayBuffer} encoded payload
- * @api private
- */
-
-exports.encodePayloadAsArrayBuffer = function(packets, callback) {
-  if (!packets.length) {
-    return callback(new ArrayBuffer(0));
-  }
-
-  function encodeOne(packet, doneCallback) {
-    exports.encodePacket(packet, true, true, function(data) {
-      return doneCallback(null, data);
-    });
-  }
-
-  map(packets, encodeOne, function(err, encodedPackets) {
-    var totalLength = encodedPackets.reduce(function(acc, p) {
-      var len;
-      if (typeof p === 'string'){
-        len = p.length;
-      } else {
-        len = p.byteLength;
-      }
-      return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
-    }, 0);
-
-    var resultArray = new Uint8Array(totalLength);
-
-    var bufferIndex = 0;
-    encodedPackets.forEach(function(p) {
-      var isString = typeof p === 'string';
-      var ab = p;
-      if (isString) {
-        var view = new Uint8Array(p.length);
-        for (var i = 0; i < p.length; i++) {
-          view[i] = p.charCodeAt(i);
-        }
-        ab = view.buffer;
-      }
-
-      if (isString) { // not true binary
-        resultArray[bufferIndex++] = 0;
-      } else { // true binary
-        resultArray[bufferIndex++] = 1;
-      }
-
-      var lenStr = ab.byteLength.toString();
-      for (var i = 0; i < lenStr.length; i++) {
-        resultArray[bufferIndex++] = parseInt(lenStr[i]);
-      }
-      resultArray[bufferIndex++] = 255;
-
-      var view = new Uint8Array(ab);
-      for (var i = 0; i < view.length; i++) {
-        resultArray[bufferIndex++] = view[i];
-      }
-    });
-
-    return callback(resultArray.buffer);
-  });
-};
-
-/**
- * Encode as Blob
- */
-
-exports.encodePayloadAsBlob = function(packets, callback) {
-  function encodeOne(packet, doneCallback) {
-    exports.encodePacket(packet, true, true, function(encoded) {
-      var binaryIdentifier = new Uint8Array(1);
-      binaryIdentifier[0] = 1;
-      if (typeof encoded === 'string') {
-        var view = new Uint8Array(encoded.length);
-        for (var i = 0; i < encoded.length; i++) {
-          view[i] = encoded.charCodeAt(i);
-        }
-        encoded = view.buffer;
-        binaryIdentifier[0] = 0;
-      }
-
-      var len = (encoded instanceof ArrayBuffer)
-        ? encoded.byteLength
-        : encoded.size;
-
-      var lenStr = len.toString();
-      var lengthAry = new Uint8Array(lenStr.length + 1);
-      for (var i = 0; i < lenStr.length; i++) {
-        lengthAry[i] = parseInt(lenStr[i]);
-      }
-      lengthAry[lenStr.length] = 255;
-
-      if (Blob) {
-        var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
-        doneCallback(null, blob);
-      }
-    });
-  }
-
-  map(packets, encodeOne, function(err, results) {
-    return callback(new Blob(results));
-  });
-};
-
-/*
- * Decodes data when a payload is maybe expected. Strings are decoded by
- * interpreting each byte as a key code for entries marked to start with 0. See
- * description of encodePayloadAsBinary
- *
- * @param {ArrayBuffer} data, callback method
- * @api public
- */
-
-exports.decodePayloadAsBinary = function (data, binaryType, callback) {
-  if (typeof binaryType === 'function') {
-    callback = binaryType;
-    binaryType = null;
-  }
-
-  var bufferTail = data;
-  var buffers = [];
-
-  while (bufferTail.byteLength > 0) {
-    var tailArray = new Uint8Array(bufferTail);
-    var isString = tailArray[0] === 0;
-    var msgLength = '';
-
-    for (var i = 1; ; i++) {
-      if (tailArray[i] === 255) break;
-
-      // 310 = char length of Number.MAX_VALUE
-      if (msgLength.length > 310) {
-        return callback(err, 0, 1);
-      }
-
-      msgLength += tailArray[i];
-    }
-
-    bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
-    msgLength = parseInt(msgLength);
-
-    var msg = sliceBuffer(bufferTail, 0, msgLength);
-    if (isString) {
-      try {
-        msg = String.fromCharCode.apply(null, new Uint8Array(msg));
-      } catch (e) {
-        // iPhone Safari doesn't let you apply to typed arrays
-        var typed = new Uint8Array(msg);
-        msg = '';
-        for (var i = 0; i < typed.length; i++) {
-          msg += String.fromCharCode(typed[i]);
-        }
-      }
-    }
-
-    buffers.push(msg);
-    bufferTail = sliceBuffer(bufferTail, msgLength);
-  }
-
-  var total = buffers.length;
-  buffers.forEach(function(buffer, i) {
-    callback(exports.decodePacket(buffer, binaryType, true), i, total);
-  });
-};
+var base64encoder,keys=require("./keys"),hasBinary=require("has-binary2"),sliceBuffer=require("arraybuffer.slice"),after=require("after"),utf8=require("./utf8");"undefined"!=typeof ArrayBuffer&&(base64encoder=require("base64-arraybuffer"));var isAndroid="undefined"!=typeof navigator&&/Android/i.test(navigator.userAgent),isPhantomJS="undefined"!=typeof navigator&&/PhantomJS/i.test(navigator.userAgent),dontSendBlobs=isAndroid||isPhantomJS;exports.protocol=3;var packets=exports.packets={open:0,close:1,ping:2,pong:3,message:4,upgrade:5,noop:6},packetslist=keys(packets),err={type:"error",data:"parser error"},Blob=require("blob");function encodeBase64Object(e,r){return r("b"+exports.packets[e.type]+e.data.data)}function encodeArrayBuffer(e,r,t){if(!r)return exports.encodeBase64Packet(e,t);var n=e.data,a=new Uint8Array(n),o=new Uint8Array(1+n.byteLength);o[0]=packets[e.type];for(var f=0;f<a.length;f++)o[f+1]=a[f];return t(o.buffer)}function encodeBlobAsArrayBuffer(e,r,t){if(!r)return exports.encodeBase64Packet(e,t);var n=new FileReader;return n.onload=function(){exports.encodePacket({type:e.type,data:n.result},r,!0,t)},n.readAsArrayBuffer(e.data)}function encodeBlob(e,r,t){if(!r)return exports.encodeBase64Packet(e,t);if(dontSendBlobs)return encodeBlobAsArrayBuffer(e,r,t);var n=new Uint8Array(1);return n[0]=packets[e.type],t(new Blob([n.buffer,e.data]))}function tryDecode(e){try{e=utf8.decode(e,{strict:!1})}catch(e){return!1}return e}function map(e,r,t){for(var n=new Array(e.length),a=after(e.length,t),o=function(e,t,a){r(t,(function(r,t){n[e]=t,a(r,n)}))},f=0;f<e.length;f++)o(f,e[f],a)}exports.encodePacket=function(e,r,t,n){"function"==typeof r&&(n=r,r=!1),"function"==typeof t&&(n=t,t=null);var a=void 0===e.data?void 0:e.data.buffer||e.data;if("undefined"!=typeof ArrayBuffer&&a instanceof ArrayBuffer)return encodeArrayBuffer(e,r,n);if(void 0!==Blob&&a instanceof Blob)return encodeBlob(e,r,n);if(a&&a.base64)return encodeBase64Object(e,n);var o=packets[e.type];return void 0!==e.data&&(o+=t?utf8.encode(String(e.data),{strict:!1}):String(e.data)),n(""+o)},exports.encodeBase64Packet=function(e,r){var t,n="b"+exports.packets[e.type];if(void 0!==Blob&&e.data instanceof Blob){var a=new FileReader;return a.onload=function(){var e=a.result.split(",")[1];r(n+e)},a.readAsDataURL(e.data)}try{t=String.fromCharCode.apply(null,new Uint8Array(e.data))}catch(r){for(var o=new Uint8Array(e.data),f=new Array(o.length),i=0;i<o.length;i++)f[i]=o[i];t=String.fromCharCode.apply(null,f)}return n+=btoa(t),r(n)},exports.decodePacket=function(e,r,t){if(void 0===e)return err;if("string"==typeof e){if("b"===e.charAt(0))return exports.decodeBase64Packet(e.substr(1),r);if(t&&!1===(e=tryDecode(e)))return err;var n=e.charAt(0);return Number(n)==n&&packetslist[n]?e.length>1?{type:packetslist[n],data:e.substring(1)}:{type:packetslist[n]}:err}n=new Uint8Array(e)[0];var a=sliceBuffer(e,1);return Blob&&"blob"===r&&(a=new Blob([a])),{type:packetslist[n],data:a}},exports.decodeBase64Packet=function(e,r){var t=packetslist[e.charAt(0)];if(!base64encoder)return{type:t,data:{base64:!0,data:e.substr(1)}};var n=base64encoder.decode(e.substr(1));return"blob"===r&&Blob&&(n=new Blob([n])),{type:t,data:n}},exports.encodePayload=function(e,r,t){"function"==typeof r&&(t=r,r=null);var n=hasBinary(e);if(r&&n)return Blob&&!dontSendBlobs?exports.encodePayloadAsBlob(e,t):exports.encodePayloadAsArrayBuffer(e,t);if(!e.length)return t("0:");map(e,(function(e,t){exports.encodePacket(e,!!n&&r,!1,(function(e){t(null,function(e){return e.length+":"+e}(e))}))}),(function(e,r){return t(r.join(""))}))},exports.decodePayload=function(e,r,t){if("string"!=typeof e)return exports.decodePayloadAsBinary(e,r,t);var n;if("function"==typeof r&&(t=r,r=null),""===e)return t(err,0,1);for(var a,o,f="",i=0,u=e.length;i<u;i++){var c=e.charAt(i);if(":"===c){if(""===f||f!=(a=Number(f)))return t(err,0,1);if(f!=(o=e.substr(i+1,a)).length)return t(err,0,1);if(o.length){if(n=exports.decodePacket(o,r,!1),err.type===n.type&&err.data===n.data)return t(err,0,1);if(!1===t(n,i+a,u))return}i+=a,f=""}else f+=c}return""!==f?t(err,0,1):void 0},exports.encodePayloadAsArrayBuffer=function(e,r){if(!e.length)return r(new ArrayBuffer(0));map(e,(function(e,r){exports.encodePacket(e,!0,!0,(function(e){return r(null,e)}))}),(function(e,t){var n=t.reduce((function(e,r){var t;return e+(t="string"==typeof r?r.length:r.byteLength).toString().length+t+2}),0),a=new Uint8Array(n),o=0;return t.forEach((function(e){var r="string"==typeof e,t=e;if(r){for(var n=new Uint8Array(e.length),f=0;f<e.length;f++)n[f]=e.charCodeAt(f);t=n.buffer}a[o++]=r?0:1;var i=t.byteLength.toString();for(f=0;f<i.length;f++)a[o++]=parseInt(i[f]);a[o++]=255;for(n=new Uint8Array(t),f=0;f<n.length;f++)a[o++]=n[f]})),r(a.buffer)}))},exports.encodePayloadAsBlob=function(e,r){map(e,(function(e,r){exports.encodePacket(e,!0,!0,(function(e){var t=new Uint8Array(1);if(t[0]=1,"string"==typeof e){for(var n=new Uint8Array(e.length),a=0;a<e.length;a++)n[a]=e.charCodeAt(a);e=n.buffer,t[0]=0}var o=(e instanceof ArrayBuffer?e.byteLength:e.size).toString(),f=new Uint8Array(o.length+1);for(a=0;a<o.length;a++)f[a]=parseInt(o[a]);if(f[o.length]=255,Blob){var i=new Blob([t.buffer,f.buffer,e]);r(null,i)}}))}),(function(e,t){return r(new Blob(t))}))},exports.decodePayloadAsBinary=function(e,r,t){"function"==typeof r&&(t=r,r=null);for(var n=e,a=[];n.byteLength>0;){for(var o=new Uint8Array(n),f=0===o[0],i="",u=1;255!==o[u];u++){if(i.length>310)return t(err,0,1);i+=o[u]}n=sliceBuffer(n,2+i.length),i=parseInt(i);var c=sliceBuffer(n,0,i);if(f)try{c=String.fromCharCode.apply(null,new Uint8Array(c))}catch(e){var s=new Uint8Array(c);c="";for(u=0;u<s.length;u++)c+=String.fromCharCode(s[u])}a.push(c),n=sliceBuffer(n,i)}var d=a.length;a.forEach((function(e,n){t(exports.decodePacket(e,r,!0),n,d)}))};
\ No newline at end of file
index 5df4df2..6b6109f 100644 (file)
@@ -1,473 +1 @@
-/**
- * Module dependencies.
- */
-
-var utf8 = require('./utf8');
-var hasBinary = require('has-binary2');
-var after = require('after');
-var keys = require('./keys');
-
-/**
- * Current protocol version.
- */
-exports.protocol = 3;
-
-/**
- * Packet types.
- */
-
-var packets = exports.packets = {
-    open:     0    // non-ws
-  , close:    1    // non-ws
-  , ping:     2
-  , pong:     3
-  , message:  4
-  , upgrade:  5
-  , noop:     6
-};
-
-var packetslist = keys(packets);
-
-/**
- * Premade error packet.
- */
-
-var err = { type: 'error', data: 'parser error' };
-
-const EMPTY_BUFFER = Buffer.concat([]);
-
-/**
- * Encodes a packet.
- *
- *     <packet type id> [ <data> ]
- *
- * Example:
- *
- *     5hello world
- *     3
- *     4
- *
- * Binary is encoded in an identical principle
- *
- * @api private
- */
-
-exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
-  if (typeof supportsBinary === 'function') {
-    callback = supportsBinary;
-    supportsBinary = null;
-  }
-
-  if (typeof utf8encode === 'function') {
-    callback = utf8encode;
-    utf8encode = null;
-  }
-
-  if (Buffer.isBuffer(packet.data)) {
-    return encodeBuffer(packet, supportsBinary, callback);
-  } else if (packet.data && (packet.data.buffer || packet.data) instanceof ArrayBuffer) {
-    return encodeBuffer({ type: packet.type, data: arrayBufferToBuffer(packet.data) }, supportsBinary, callback);
-  }
-
-  // Sending data as a utf-8 string
-  var encoded = packets[packet.type];
-
-  // data fragment is optional
-  if (undefined !== packet.data) {
-    encoded += utf8encode ? utf8.encode(String(packet.data), { strict: false }) : String(packet.data);
-  }
-
-  return callback('' + encoded);
-};
-
-/**
- * Encode Buffer data
- */
-
-function encodeBuffer(packet, supportsBinary, callback) {
-  if (!supportsBinary) {
-    return exports.encodeBase64Packet(packet, callback);
-  }
-
-  var data = packet.data;
-  var typeBuffer = Buffer.allocUnsafe(1);
-  typeBuffer[0] = packets[packet.type];
-  return callback(Buffer.concat([typeBuffer, data]));
-}
-
-/**
- * Encodes a packet with binary data in a base64 string
- *
- * @param {Object} packet, has `type` and `data`
- * @return {String} base64 encoded message
- */
-
-exports.encodeBase64Packet = function(packet, callback){
-  var data = Buffer.isBuffer(packet.data) ? packet.data : arrayBufferToBuffer(packet.data);
-  var message = 'b' + packets[packet.type];
-  message += data.toString('base64');
-  return callback(message);
-};
-
-/**
- * Decodes a packet. Data also available as an ArrayBuffer if requested.
- *
- * @return {Object} with `type` and `data` (if any)
- * @api private
- */
-
-exports.decodePacket = function (data, binaryType, utf8decode) {
-  if (data === undefined) {
-    return err;
-  }
-
-  var type;
-
-  // String data
-  if (typeof data === 'string') {
-
-    type = data.charAt(0);
-
-    if (type === 'b') {
-      return exports.decodeBase64Packet(data.substr(1), binaryType);
-    }
-
-    if (utf8decode) {
-      data = tryDecode(data);
-      if (data === false) {
-        return err;
-      }
-    }
-
-    if (Number(type) != type || !packetslist[type]) {
-      return err;
-    }
-
-    if (data.length > 1) {
-      return { type: packetslist[type], data: data.substring(1) };
-    } else {
-      return { type: packetslist[type] };
-    }
-  }
-
-  // Binary data
-  if (binaryType === 'arraybuffer') {
-    // wrap Buffer/ArrayBuffer data into an Uint8Array
-    var intArray = new Uint8Array(data);
-    type = intArray[0];
-    return { type: packetslist[type], data: intArray.buffer.slice(1) };
-  }
-
-  if (data instanceof ArrayBuffer) {
-    data = arrayBufferToBuffer(data);
-  }
-  type = data[0];
-  return { type: packetslist[type], data: data.slice(1) };
-};
-
-function tryDecode(data) {
-  try {
-    data = utf8.decode(data, { strict: false });
-  } catch (e) {
-    return false;
-  }
-  return data;
-}
-
-/**
- * Decodes a packet encoded in a base64 string.
- *
- * @param {String} base64 encoded message
- * @return {Object} with `type` and `data` (if any)
- */
-
-exports.decodeBase64Packet = function(msg, binaryType) {
-  var type = packetslist[msg.charAt(0)];
-  var data = Buffer.from(msg.substr(1), 'base64');
-  if (binaryType === 'arraybuffer') {
-    var abv = new Uint8Array(data.length);
-    for (var i = 0; i < abv.length; i++){
-      abv[i] = data[i];
-    }
-    data = abv.buffer;
-  }
-  return { type: type, data: data };
-};
-
-/**
- * Encodes multiple messages (payload).
- *
- *     <length>:data
- *
- * Example:
- *
- *     11:hello world2:hi
- *
- * If any contents are binary, they will be encoded as base64 strings. Base64
- * encoded strings are marked with a b before the length specifier
- *
- * @param {Array} packets
- * @api private
- */
-
-exports.encodePayload = function (packets, supportsBinary, callback) {
-  if (typeof supportsBinary === 'function') {
-    callback = supportsBinary;
-    supportsBinary = null;
-  }
-
-  if (supportsBinary && hasBinary(packets)) {
-    return exports.encodePayloadAsBinary(packets, callback);
-  }
-
-  if (!packets.length) {
-    return callback('0:');
-  }
-
-  function encodeOne(packet, doneCallback) {
-    exports.encodePacket(packet, supportsBinary, false, function(message) {
-      doneCallback(null, setLengthHeader(message));
-    });
-  }
-
-  map(packets, encodeOne, function(err, results) {
-    return callback(results.join(''));
-  });
-};
-
-function setLengthHeader(message) {
-  return message.length + ':' + message;
-}
-
-/**
- * Async array map using after
- */
-
-function map(ary, each, done) {
-  var result = new Array(ary.length);
-  var next = after(ary.length, done);
-
-  for (var i = 0; i < ary.length; i++) {
-    each(ary[i], function(error, msg) {
-      result[i] = msg;
-      next(error, result);
-    });
-  }
-}
-
-/*
- * Decodes data when a payload is maybe expected. Possible binary contents are
- * decoded from their base64 representation
- *
- * @param {String} data, callback method
- * @api public
- */
-
-exports.decodePayload = function (data, binaryType, callback) {
-  if (typeof data !== 'string') {
-    return exports.decodePayloadAsBinary(data, binaryType, callback);
-  }
-
-  if (typeof binaryType === 'function') {
-    callback = binaryType;
-    binaryType = null;
-  }
-
-  if (data === '') {
-    // parser error - ignoring payload
-    return callback(err, 0, 1);
-  }
-
-  var length = '', n, msg, packet;
-
-  for (var i = 0, l = data.length; i < l; i++) {
-    var chr = data.charAt(i);
-
-    if (chr !== ':') {
-      length += chr;
-      continue;
-    }
-
-    if (length === '' || (length != (n = Number(length)))) {
-      // parser error - ignoring payload
-      return callback(err, 0, 1);
-    }
-
-    msg = data.substr(i + 1, n);
-
-    if (length != msg.length) {
-      // parser error - ignoring payload
-      return callback(err, 0, 1);
-    }
-
-    if (msg.length) {
-      packet = exports.decodePacket(msg, binaryType, false);
-
-      if (err.type === packet.type && err.data === packet.data) {
-        // parser error in individual packet - ignoring payload
-        return callback(err, 0, 1);
-      }
-
-      var more = callback(packet, i + n, l);
-      if (false === more) return;
-    }
-
-    // advance cursor
-    i += n;
-    length = '';
-  }
-
-  if (length !== '') {
-    // parser error - ignoring payload
-    return callback(err, 0, 1);
-  }
-
-};
-
-/**
- *
- * Converts a buffer to a utf8.js encoded string
- *
- * @api private
- */
-
-function bufferToString(buffer) {
-  var str = '';
-  for (var i = 0, l = buffer.length; i < l; i++) {
-    str += String.fromCharCode(buffer[i]);
-  }
-  return str;
-}
-
-/**
- *
- * Converts a utf8.js encoded string to a buffer
- *
- * @api private
- */
-
-function stringToBuffer(string) {
-  var buf = Buffer.allocUnsafe(string.length);
-  for (var i = 0, l = string.length; i < l; i++) {
-    buf.writeUInt8(string.charCodeAt(i), i);
-  }
-  return buf;
-}
-
-/**
- *
- * Converts an ArrayBuffer to a Buffer
- *
- * @api private
- */
-
-function arrayBufferToBuffer(data) {
-  // data is either an ArrayBuffer or ArrayBufferView.
-  var length = data.byteLength || data.length;
-  var offset = data.byteOffset || 0;
-
-  return Buffer.from(data.buffer || data, offset, length);
-}
-
-/**
- * Encodes multiple messages (payload) as binary.
- *
- * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
- * 255><data>
- *
- * Example:
- * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
- *
- * @param {Array} packets
- * @return {Buffer} encoded payload
- * @api private
- */
-
-exports.encodePayloadAsBinary = function (packets, callback) {
-  if (!packets.length) {
-    return callback(EMPTY_BUFFER);
-  }
-
-  map(packets, encodeOneBinaryPacket, function(err, results) {
-    return callback(Buffer.concat(results));
-  });
-};
-
-function encodeOneBinaryPacket(p, doneCallback) {
-
-  function onBinaryPacketEncode(packet) {
-
-    var encodingLength = '' + packet.length;
-    var sizeBuffer;
-
-    if (typeof packet === 'string') {
-      sizeBuffer = Buffer.allocUnsafe(encodingLength.length + 2);
-      sizeBuffer[0] = 0; // is a string (not true binary = 0)
-      for (var i = 0; i < encodingLength.length; i++) {
-        sizeBuffer[i + 1] = parseInt(encodingLength[i], 10);
-      }
-      sizeBuffer[sizeBuffer.length - 1] = 255;
-      return doneCallback(null, Buffer.concat([sizeBuffer, stringToBuffer(packet)]));
-    }
-
-    sizeBuffer = Buffer.allocUnsafe(encodingLength.length + 2);
-    sizeBuffer[0] = 1; // is binary (true binary = 1)
-    for (var i = 0; i < encodingLength.length; i++) {
-      sizeBuffer[i + 1] = parseInt(encodingLength[i], 10);
-    }
-    sizeBuffer[sizeBuffer.length - 1] = 255;
-
-    doneCallback(null, Buffer.concat([sizeBuffer, packet]));
-  }
-
-  exports.encodePacket(p, true, true, onBinaryPacketEncode);
-
-}
-
-
-/*
- * Decodes data when a payload is maybe expected. Strings are decoded by
- * interpreting each byte as a key code for entries marked to start with 0. See
- * description of encodePayloadAsBinary
-
- * @param {Buffer} data, callback method
- * @api public
- */
-
-exports.decodePayloadAsBinary = function (data, binaryType, callback) {
-  if (typeof binaryType === 'function') {
-    callback = binaryType;
-    binaryType = null;
-  }
-
-  var bufferTail = data;
-  var buffers = [];
-  var i;
-
-  while (bufferTail.length > 0) {
-    var strLen = '';
-    var isString = bufferTail[0] === 0;
-    for (i = 1; ; i++) {
-      if (bufferTail[i] === 255)  break;
-      // 310 = char length of Number.MAX_VALUE
-      if (strLen.length > 310) {
-        return callback(err, 0, 1);
-      }
-      strLen += '' + bufferTail[i];
-    }
-    bufferTail = bufferTail.slice(strLen.length + 1);
-
-    var msgLength = parseInt(strLen, 10);
-
-    var msg = bufferTail.slice(1, msgLength + 1);
-    if (isString) msg = bufferToString(msg);
-    buffers.push(msg);
-    bufferTail = bufferTail.slice(msgLength + 1);
-  }
-
-  var total = buffers.length;
-  for (i = 0; i < total; i++) {
-    var buffer = buffers[i];
-    callback(exports.decodePacket(buffer, binaryType, true), i, total);
-  }
-};
+var utf8=require("./utf8"),hasBinary=require("has-binary2"),after=require("after"),keys=require("./keys");exports.protocol=3;var packets=exports.packets={open:0,close:1,ping:2,pong:3,message:4,upgrade:5,noop:6},packetslist=keys(packets),err={type:"error",data:"parser error"};const EMPTY_BUFFER=Buffer.concat([]);function encodeBuffer(e,r,t){if(!r)return exports.encodeBase64Packet(e,t);var n=e.data,a=Buffer.allocUnsafe(1);return a[0]=packets[e.type],t(Buffer.concat([a,n]))}function tryDecode(e){try{e=utf8.decode(e,{strict:!1})}catch(e){return!1}return e}function setLengthHeader(e){return e.length+":"+e}function map(e,r,t){for(var n=new Array(e.length),a=after(e.length,t),f=0;f<e.length;f++)r(e[f],(function(e,r){n[f]=r,a(e,n)}))}function bufferToString(e){for(var r="",t=0,n=e.length;t<n;t++)r+=String.fromCharCode(e[t]);return r}function stringToBuffer(e){for(var r=Buffer.allocUnsafe(e.length),t=0,n=e.length;t<n;t++)r.writeUInt8(e.charCodeAt(t),t);return r}function arrayBufferToBuffer(e){var r=e.byteLength||e.length,t=e.byteOffset||0;return Buffer.from(e.buffer||e,t,r)}function encodeOneBinaryPacket(e,r){exports.encodePacket(e,!0,!0,(function(e){var t,n=""+e.length;if("string"==typeof e){(t=Buffer.allocUnsafe(n.length+2))[0]=0;for(var a=0;a<n.length;a++)t[a+1]=parseInt(n[a],10);return t[t.length-1]=255,r(null,Buffer.concat([t,stringToBuffer(e)]))}for((t=Buffer.allocUnsafe(n.length+2))[0]=1,a=0;a<n.length;a++)t[a+1]=parseInt(n[a],10);t[t.length-1]=255,r(null,Buffer.concat([t,e]))}))}exports.encodePacket=function(e,r,t,n){if("function"==typeof r&&(n=r,r=null),"function"==typeof t&&(n=t,t=null),Buffer.isBuffer(e.data))return encodeBuffer(e,r,n);if(e.data&&(e.data.buffer||e.data)instanceof ArrayBuffer)return encodeBuffer({type:e.type,data:arrayBufferToBuffer(e.data)},r,n);var a=packets[e.type];return void 0!==e.data&&(a+=t?utf8.encode(String(e.data),{strict:!1}):String(e.data)),n(""+a)},exports.encodeBase64Packet=function(e,r){var t=Buffer.isBuffer(e.data)?e.data:arrayBufferToBuffer(e.data),n="b"+packets[e.type];return r(n+=t.toString("base64"))},exports.decodePacket=function(e,r,t){if(void 0===e)return err;var n;if("string"==typeof e)return"b"===(n=e.charAt(0))?exports.decodeBase64Packet(e.substr(1),r):t&&!1===(e=tryDecode(e))?err:Number(n)==n&&packetslist[n]?e.length>1?{type:packetslist[n],data:e.substring(1)}:{type:packetslist[n]}:err;if("arraybuffer"===r){var a=new Uint8Array(e);return n=a[0],{type:packetslist[n],data:a.buffer.slice(1)}}return e instanceof ArrayBuffer&&(e=arrayBufferToBuffer(e)),n=e[0],{type:packetslist[n],data:e.slice(1)}},exports.decodeBase64Packet=function(e,r){var t=packetslist[e.charAt(0)],n=Buffer.from(e.substr(1),"base64");if("arraybuffer"===r){for(var a=new Uint8Array(n.length),f=0;f<a.length;f++)a[f]=n[f];n=a.buffer}return{type:t,data:n}},exports.encodePayload=function(e,r,t){if("function"==typeof r&&(t=r,r=null),r&&hasBinary(e))return exports.encodePayloadAsBinary(e,t);if(!e.length)return t("0:");map(e,(function(e,t){exports.encodePacket(e,r,!1,(function(e){t(null,setLengthHeader(e))}))}),(function(e,r){return t(r.join(""))}))},exports.decodePayload=function(e,r,t){if("string"!=typeof e)return exports.decodePayloadAsBinary(e,r,t);if("function"==typeof r&&(t=r,r=null),""===e)return t(err,0,1);for(var n,a,f,o="",u=0,c=e.length;u<c;u++){var i=e.charAt(u);if(":"===i){if(""===o||o!=(n=Number(o)))return t(err,0,1);if(o!=(a=e.substr(u+1,n)).length)return t(err,0,1);if(a.length){if(f=exports.decodePacket(a,r,!1),err.type===f.type&&err.data===f.data)return t(err,0,1);if(!1===t(f,u+n,c))return}u+=n,o=""}else o+=i}return""!==o?t(err,0,1):void 0},exports.encodePayloadAsBinary=function(e,r){if(!e.length)return r(EMPTY_BUFFER);map(e,encodeOneBinaryPacket,(function(e,t){return r(Buffer.concat(t))}))},exports.decodePayloadAsBinary=function(e,r,t){"function"==typeof r&&(t=r,r=null);for(var n,a=e,f=[];a.length>0;){var o="",u=0===a[0];for(n=1;255!==a[n];n++){if(o.length>310)return t(err,0,1);o+=""+a[n]}a=a.slice(o.length+1);var c=parseInt(o,10),i=a.slice(1,c+1);u&&(i=bufferToString(i)),f.push(i),a=a.slice(c+1)}var s=f.length;for(n=0;n<s;n++){var l=f[n];t(exports.decodePacket(l,r,!0),n,s)}};
\ No newline at end of file
index 947dafd..c666387 100644 (file)
@@ -1,19 +1 @@
-
-/**
- * Gets the keys for an object.
- *
- * @return {Array} keys
- * @api private
- */
-
-module.exports = Object.keys || function keys (obj){
-  var arr = [];
-  var has = Object.prototype.hasOwnProperty;
-
-  for (var i in obj) {
-    if (has.call(obj, i)) {
-      arr.push(i);
-    }
-  }
-  return arr;
-};
+module.exports=Object.keys||function(r){var e=[],t=Object.prototype.hasOwnProperty;for(var o in r)t.call(r,o)&&e.push(o);return e};
\ No newline at end of file
index b878740..9654099 100644 (file)
@@ -1,210 +1,2 @@
 /*! https://mths.be/utf8js v2.1.2 by @mathias */
-
-var stringFromCharCode = String.fromCharCode;
-
-// Taken from https://mths.be/punycode
-function ucs2decode(string) {
-       var output = [];
-       var counter = 0;
-       var length = string.length;
-       var value;
-       var 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;
-}
-
-// Taken from https://mths.be/punycode
-function ucs2encode(array) {
-       var length = array.length;
-       var index = -1;
-       var value;
-       var output = '';
-       while (++index < length) {
-               value = array[index];
-               if (value > 0xFFFF) {
-                       value -= 0x10000;
-                       output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
-                       value = 0xDC00 | value & 0x3FF;
-               }
-               output += stringFromCharCode(value);
-       }
-       return output;
-}
-
-function checkScalarValue(codePoint, strict) {
-       if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {
-               if (strict) {
-                       throw Error(
-                               'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +
-                               ' is not a scalar value'
-                       );
-               }
-               return false;
-       }
-       return true;
-}
-/*--------------------------------------------------------------------------*/
-
-function createByte(codePoint, shift) {
-       return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
-}
-
-function encodeCodePoint(codePoint, strict) {
-       if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
-               return stringFromCharCode(codePoint);
-       }
-       var symbol = '';
-       if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
-               symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
-       }
-       else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
-               if (!checkScalarValue(codePoint, strict)) {
-                       codePoint = 0xFFFD;
-               }
-               symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
-               symbol += createByte(codePoint, 6);
-       }
-       else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
-               symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
-               symbol += createByte(codePoint, 12);
-               symbol += createByte(codePoint, 6);
-       }
-       symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
-       return symbol;
-}
-
-function utf8encode(string, opts) {
-       opts = opts || {};
-       var strict = false !== opts.strict;
-
-       var codePoints = ucs2decode(string);
-       var length = codePoints.length;
-       var index = -1;
-       var codePoint;
-       var byteString = '';
-       while (++index < length) {
-               codePoint = codePoints[index];
-               byteString += encodeCodePoint(codePoint, strict);
-       }
-       return byteString;
-}
-
-/*--------------------------------------------------------------------------*/
-
-function readContinuationByte() {
-       if (byteIndex >= byteCount) {
-               throw Error('Invalid byte index');
-       }
-
-       var continuationByte = byteArray[byteIndex] & 0xFF;
-       byteIndex++;
-
-       if ((continuationByte & 0xC0) == 0x80) {
-               return continuationByte & 0x3F;
-       }
-
-       // If we end up here, it’s not a continuation byte
-       throw Error('Invalid continuation byte');
-}
-
-function decodeSymbol(strict) {
-       var byte1;
-       var byte2;
-       var byte3;
-       var byte4;
-       var codePoint;
-
-       if (byteIndex > byteCount) {
-               throw Error('Invalid byte index');
-       }
-
-       if (byteIndex == byteCount) {
-               return false;
-       }
-
-       // Read first byte
-       byte1 = byteArray[byteIndex] & 0xFF;
-       byteIndex++;
-
-       // 1-byte sequence (no continuation bytes)
-       if ((byte1 & 0x80) == 0) {
-               return byte1;
-       }
-
-       // 2-byte sequence
-       if ((byte1 & 0xE0) == 0xC0) {
-               byte2 = readContinuationByte();
-               codePoint = ((byte1 & 0x1F) << 6) | byte2;
-               if (codePoint >= 0x80) {
-                       return codePoint;
-               } else {
-                       throw Error('Invalid continuation byte');
-               }
-       }
-
-       // 3-byte sequence (may include unpaired surrogates)
-       if ((byte1 & 0xF0) == 0xE0) {
-               byte2 = readContinuationByte();
-               byte3 = readContinuationByte();
-               codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
-               if (codePoint >= 0x0800) {
-                       return checkScalarValue(codePoint, strict) ? codePoint : 0xFFFD;
-               } else {
-                       throw Error('Invalid continuation byte');
-               }
-       }
-
-       // 4-byte sequence
-       if ((byte1 & 0xF8) == 0xF0) {
-               byte2 = readContinuationByte();
-               byte3 = readContinuationByte();
-               byte4 = readContinuationByte();
-               codePoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0C) |
-                       (byte3 << 0x06) | byte4;
-               if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
-                       return codePoint;
-               }
-       }
-
-       throw Error('Invalid UTF-8 detected');
-}
-
-var byteArray;
-var byteCount;
-var byteIndex;
-function utf8decode(byteString, opts) {
-       opts = opts || {};
-       var strict = false !== opts.strict;
-
-       byteArray = ucs2decode(byteString);
-       byteCount = byteArray.length;
-       byteIndex = 0;
-       var codePoints = [];
-       var tmp;
-       while ((tmp = decodeSymbol(strict)) !== false) {
-               codePoints.push(tmp);
-       }
-       return ucs2encode(codePoints);
-}
-
-module.exports = {
-       version: '2.1.2',
-       encode: utf8encode,
-       decode: utf8decode
-};
+var byteArray,byteCount,byteIndex,stringFromCharCode=String.fromCharCode;function ucs2decode(e){for(var r,t,n=[],o=0,a=e.length;o<a;)(r=e.charCodeAt(o++))>=55296&&r<=56319&&o<a?56320==(64512&(t=e.charCodeAt(o++)))?n.push(((1023&r)<<10)+(1023&t)+65536):(n.push(r),o--):n.push(r);return n}function ucs2encode(e){for(var r,t=e.length,n=-1,o="";++n<t;)(r=e[n])>65535&&(o+=stringFromCharCode((r-=65536)>>>10&1023|55296),r=56320|1023&r),o+=stringFromCharCode(r);return o}function checkScalarValue(e,r){if(e>=55296&&e<=57343){if(r)throw Error("Lone surrogate U+"+e.toString(16).toUpperCase()+" is not a scalar value");return!1}return!0}function createByte(e,r){return stringFromCharCode(e>>r&63|128)}function encodeCodePoint(e,r){if(0==(4294967168&e))return stringFromCharCode(e);var t="";return 0==(4294965248&e)?t=stringFromCharCode(e>>6&31|192):0==(4294901760&e)?(checkScalarValue(e,r)||(e=65533),t=stringFromCharCode(e>>12&15|224),t+=createByte(e,6)):0==(4292870144&e)&&(t=stringFromCharCode(e>>18&7|240),t+=createByte(e,12),t+=createByte(e,6)),t+=stringFromCharCode(63&e|128)}function utf8encode(e,r){for(var t=!1!==(r=r||{}).strict,n=ucs2decode(e),o=n.length,a=-1,i="";++a<o;)i+=encodeCodePoint(n[a],t);return i}function readContinuationByte(){if(byteIndex>=byteCount)throw Error("Invalid byte index");var e=255&byteArray[byteIndex];if(byteIndex++,128==(192&e))return 63&e;throw Error("Invalid continuation byte")}function decodeSymbol(e){var r,t;if(byteIndex>byteCount)throw Error("Invalid byte index");if(byteIndex==byteCount)return!1;if(r=255&byteArray[byteIndex],byteIndex++,0==(128&r))return r;if(192==(224&r)){if((t=(31&r)<<6|readContinuationByte())>=128)return t;throw Error("Invalid continuation byte")}if(224==(240&r)){if((t=(15&r)<<12|readContinuationByte()<<6|readContinuationByte())>=2048)return checkScalarValue(t,e)?t:65533;throw Error("Invalid continuation byte")}if(240==(248&r)&&(t=(7&r)<<18|readContinuationByte()<<12|readContinuationByte()<<6|readContinuationByte())>=65536&&t<=1114111)return t;throw Error("Invalid UTF-8 detected")}function utf8decode(e,r){var t=!1!==(r=r||{}).strict;byteArray=ucs2decode(e),byteCount=byteArray.length,byteIndex=0;for(var n,o=[];!1!==(n=decodeSymbol(t));)o.push(n);return ucs2encode(o)}module.exports={version:"2.1.2",encode:utf8encode,decode:utf8decode};
\ No newline at end of file
index 2a211c2..548f2a2 100644 (file)
@@ -1,126 +1 @@
-/**
- * Module dependencies.
- */
-
-var http = require('http');
-
-/**
- * Invoking the library as a function delegates to attach if the first argument
- * is an `http.Server`.
- *
- * If there are no arguments or the first argument is an options object, then
- * a new Server instance is returned.
- *
- * @param {http.Server} server (if specified, will be attached to by the new Server instance)
- * @param {Object} options
- * @return {Server} engine server
- * @api public
- */
-
-exports = module.exports = function () {
-  // backwards compatible use as `.attach`
-  // if first argument is an http server
-  if (arguments.length && arguments[0] instanceof http.Server) {
-    return attach.apply(this, arguments);
-  }
-
-  // if first argument is not an http server, then just make a regular eio server
-  return exports.Server.apply(null, arguments);
-};
-
-/**
- * Protocol revision number.
- *
- * @api public
- */
-
-exports.protocol = 1;
-
-/**
- * Expose Server constructor.
- *
- * @api public
- */
-
-exports.Server = require('./server');
-
-/**
- * Expose Socket constructor.
- *
- * @api public
- */
-
-exports.Socket = require('./socket');
-
-/**
- * Expose Transport constructor.
- *
- * @api public
- */
-
-exports.Transport = require('./transport');
-
-/**
- * Expose mutable list of available transports.
- *
- * @api public
- */
-
-exports.transports = require('./transports');
-
-/**
- * Exports parser.
- *
- * @api public
- */
-
-exports.parser = require('engine.io-parser');
-
-/**
- * Creates an http.Server exclusively used for WS upgrades.
- *
- * @param {Number} port
- * @param {Function} callback
- * @param {Object} options
- * @return {Server} websocket.io server
- * @api public
- */
-
-exports.listen = listen;
-
-function listen (port, options, fn) {
-  if ('function' === typeof options) {
-    fn = options;
-    options = {};
-  }
-
-  var server = http.createServer(function (req, res) {
-    res.writeHead(501);
-    res.end('Not Implemented');
-  });
-
-  // create engine server
-  var engine = exports.attach(server, options);
-  engine.httpServer = server;
-
-  server.listen(port, fn);
-
-  return engine;
-}
-
-/**
- * Captures upgrade requests for a http.Server.
- *
- * @param {http.Server} server
- * @param {Object} options
- * @return {Server} engine server
- * @api public
- */
-
-exports.attach = attach;
-
-function attach (server, options) {
-  var engine = new exports.Server(options);
-  engine.attach(server, options);
-  return engine;
-}
+var http=require("http");function listen(e,t,r){"function"==typeof t&&(r=t,t={});var o=http.createServer((function(e,t){t.writeHead(501),t.end("Not Implemented")})),p=exports.attach(o,t);return p.httpServer=o,o.listen(e,r),p}function attach(e,t){var r=new exports.Server(t);return r.attach(e,t),r}exports=module.exports=function(){return arguments.length&&arguments[0]instanceof http.Server?attach.apply(this,arguments):exports.Server.apply(null,arguments)},exports.protocol=1,exports.Server=require("./server"),exports.Socket=require("./socket"),exports.Transport=require("./transport"),exports.transports=require("./transports"),exports.parser=require("engine.io-parser"),exports.listen=listen,exports.attach=attach;
\ No newline at end of file
index c691561..500d3f0 100644 (file)
@@ -1,591 +1 @@
-
-/**
- * Module dependencies.
- */
-
-var qs = require('querystring');
-var parse = require('url').parse;
-var base64id = require('base64id');
-var transports = require('./transports');
-var EventEmitter = require('events').EventEmitter;
-var Socket = require('./socket');
-var util = require('util');
-var debug = require('debug')('engine');
-var cookieMod = require('cookie');
-
-/**
- * Module exports.
- */
-
-module.exports = Server;
-
-/**
- * Server constructor.
- *
- * @param {Object} options
- * @api public
- */
-
-function Server (opts) {
-  if (!(this instanceof Server)) {
-    return new Server(opts);
-  }
-
-  this.clients = {};
-  this.clientsCount = 0;
-
-  opts = opts || {};
-
-  this.wsEngine = opts.wsEngine || process.env.EIO_WS_ENGINE || 'ws';
-  this.pingTimeout = opts.pingTimeout || 5000;
-  this.pingInterval = opts.pingInterval || 25000;
-  this.upgradeTimeout = opts.upgradeTimeout || 10000;
-  this.maxHttpBufferSize = opts.maxHttpBufferSize || 10E7;
-  this.transports = opts.transports || Object.keys(transports);
-  this.allowUpgrades = false !== opts.allowUpgrades;
-  this.allowRequest = opts.allowRequest;
-  this.cookie = false !== opts.cookie ? (opts.cookie || 'io') : false;
-  this.cookiePath = false !== opts.cookiePath ? (opts.cookiePath || '/') : false;
-  this.cookieHttpOnly = false !== opts.cookieHttpOnly;
-  this.perMessageDeflate = opts.perMessageDeflate || false;
-  this.httpCompression = false !== opts.httpCompression ? (opts.httpCompression || {}) : false;
-  this.initialPacket = opts.initialPacket;
-
-  var self = this;
-
-  // initialize compression options
-  ['perMessageDeflate', 'httpCompression'].forEach(function (type) {
-    var compression = self[type];
-    if (true === compression) self[type] = compression = {};
-    if (compression && null == compression.threshold) {
-      compression.threshold = 1024;
-    }
-  });
-
-  this.init();
-}
-
-/**
- * Protocol errors mappings.
- */
-
-Server.errors = {
-  UNKNOWN_TRANSPORT: 0,
-  UNKNOWN_SID: 1,
-  BAD_HANDSHAKE_METHOD: 2,
-  BAD_REQUEST: 3,
-  FORBIDDEN: 4
-};
-
-Server.errorMessages = {
-  0: 'Transport unknown',
-  1: 'Session ID unknown',
-  2: 'Bad handshake method',
-  3: 'Bad request',
-  4: 'Forbidden'
-};
-
-/**
- * Inherits from EventEmitter.
- */
-
-util.inherits(Server, EventEmitter);
-
-/**
- * Initialize websocket server
- *
- * @api private
- */
-
-Server.prototype.init = function () {
-  if (!~this.transports.indexOf('websocket')) return;
-
-  if (this.ws) this.ws.close();
-
-  // add explicit require for bundlers like webpack
-  var wsModule = this.wsEngine === 'ws' ? require('ws') : require(this.wsEngine);
-  this.ws = new wsModule.Server({
-    noServer: true,
-    clientTracking: false,
-    perMessageDeflate: this.perMessageDeflate,
-    maxPayload: this.maxHttpBufferSize
-  });
-};
-
-/**
- * Returns a list of available transports for upgrade given a certain transport.
- *
- * @return {Array}
- * @api public
- */
-
-Server.prototype.upgrades = function (transport) {
-  if (!this.allowUpgrades) return [];
-  return transports[transport].upgradesTo || [];
-};
-
-/**
- * Verifies a request.
- *
- * @param {http.IncomingMessage}
- * @return {Boolean} whether the request is valid
- * @api private
- */
-
-Server.prototype.verify = function (req, upgrade, fn) {
-  // transport check
-  var transport = req._query.transport;
-  if (!~this.transports.indexOf(transport)) {
-    debug('unknown transport "%s"', transport);
-    return fn(Server.errors.UNKNOWN_TRANSPORT, false);
-  }
-
-  // 'Origin' header check
-  var isOriginInvalid = checkInvalidHeaderChar(req.headers.origin);
-  if (isOriginInvalid) {
-    req.headers.origin = null;
-    debug('origin header invalid');
-    return fn(Server.errors.BAD_REQUEST, false);
-  }
-
-  // sid check
-  var sid = req._query.sid;
-  if (sid) {
-    if (!this.clients.hasOwnProperty(sid)) {
-      debug('unknown sid "%s"', sid);
-      return fn(Server.errors.UNKNOWN_SID, false);
-    }
-    if (!upgrade && this.clients[sid].transport.name !== transport) {
-      debug('bad request: unexpected transport without upgrade');
-      return fn(Server.errors.BAD_REQUEST, false);
-    }
-  } else {
-    // handshake is GET only
-    if ('GET' !== req.method) return fn(Server.errors.BAD_HANDSHAKE_METHOD, false);
-    if (!this.allowRequest) return fn(null, true);
-    return this.allowRequest(req, fn);
-  }
-
-  fn(null, true);
-};
-
-/**
- * Prepares a request by processing the query string.
- *
- * @api private
- */
-
-Server.prototype.prepare = function (req) {
-  // try to leverage pre-existing `req._query` (e.g: from connect)
-  if (!req._query) {
-    req._query = ~req.url.indexOf('?') ? qs.parse(parse(req.url).query) : {};
-  }
-};
-
-/**
- * Closes all clients.
- *
- * @api public
- */
-
-Server.prototype.close = function () {
-  debug('closing all open clients');
-  for (var i in this.clients) {
-    if (this.clients.hasOwnProperty(i)) {
-      this.clients[i].close(true);
-    }
-  }
-  if (this.ws) {
-    debug('closing webSocketServer');
-    this.ws.close();
-    // don't delete this.ws because it can be used again if the http server starts listening again
-  }
-  return this;
-};
-
-/**
- * Handles an Engine.IO HTTP request.
- *
- * @param {http.IncomingMessage} request
- * @param {http.ServerResponse|http.OutgoingMessage} response
- * @api public
- */
-
-Server.prototype.handleRequest = function (req, res) {
-  debug('handling "%s" http request "%s"', req.method, req.url);
-  this.prepare(req);
-  req.res = res;
-
-  var self = this;
-  this.verify(req, false, function (err, success) {
-    if (!success) {
-      sendErrorMessage(req, res, err);
-      return;
-    }
-
-    if (req._query.sid) {
-      debug('setting new request for existing client');
-      self.clients[req._query.sid].transport.onRequest(req);
-    } else {
-      self.handshake(req._query.transport, req);
-    }
-  });
-};
-
-/**
- * Sends an Engine.IO Error Message
- *
- * @param {http.ServerResponse} response
- * @param {code} error code
- * @api private
- */
-
-function sendErrorMessage (req, res, code) {
-  var headers = { 'Content-Type': 'application/json' };
-
-  var isForbidden = !Server.errorMessages.hasOwnProperty(code);
-  if (isForbidden) {
-    res.writeHead(403, headers);
-    res.end(JSON.stringify({
-      code: Server.errors.FORBIDDEN,
-      message: code || Server.errorMessages[Server.errors.FORBIDDEN]
-    }));
-    return;
-  }
-  if (req.headers.origin) {
-    headers['Access-Control-Allow-Credentials'] = 'true';
-    headers['Access-Control-Allow-Origin'] = req.headers.origin;
-  } else {
-    headers['Access-Control-Allow-Origin'] = '*';
-  }
-  if (res !== undefined) {
-    res.writeHead(400, headers);
-    res.end(JSON.stringify({
-      code: code,
-      message: Server.errorMessages[code]
-    }));
-  }
-}
-
-/**
- * generate a socket id.
- * Overwrite this method to generate your custom socket id
- *
- * @param {Object} request object
- * @api public
- */
-
-Server.prototype.generateId = function (req) {
-  return base64id.generateId();
-};
-
-/**
- * Handshakes a new client.
- *
- * @param {String} transport name
- * @param {Object} request object
- * @api private
- */
-
-Server.prototype.handshake = function (transportName, req) {
-  var id = this.generateId(req);
-
-  debug('handshaking client "%s"', id);
-
-  try {
-    var transport = new transports[transportName](req);
-    if ('polling' === transportName) {
-      transport.maxHttpBufferSize = this.maxHttpBufferSize;
-      transport.httpCompression = this.httpCompression;
-    } else if ('websocket' === transportName) {
-      transport.perMessageDeflate = this.perMessageDeflate;
-    }
-
-    if (req._query && req._query.b64) {
-      transport.supportsBinary = false;
-    } else {
-      transport.supportsBinary = true;
-    }
-  } catch (e) {
-    debug('error handshaking to transport "%s"', transportName);
-    sendErrorMessage(req, req.res, Server.errors.BAD_REQUEST);
-    return;
-  }
-  var socket = new Socket(id, this, transport, req);
-  var self = this;
-
-  if (false !== this.cookie) {
-    transport.on('headers', function (headers) {
-      if (typeof self.cookie === 'object') {
-        headers['Set-Cookie'] = cookieMod.serialize(self.cookie.name, id, self.cookie);
-      } else {
-        headers['Set-Cookie'] = cookieMod.serialize(self.cookie, id,
-          {
-            path: self.cookiePath,
-            httpOnly: self.cookiePath ? self.cookieHttpOnly : false,
-            sameSite: true
-          });
-      }
-    });
-  }
-
-  transport.onRequest(req);
-
-  this.clients[id] = socket;
-  this.clientsCount++;
-
-  socket.once('close', function () {
-    delete self.clients[id];
-    self.clientsCount--;
-  });
-
-  this.emit('connection', socket);
-};
-
-/**
- * Handles an Engine.IO HTTP Upgrade.
- *
- * @api public
- */
-
-Server.prototype.handleUpgrade = function (req, socket, upgradeHead) {
-  this.prepare(req);
-
-  var self = this;
-  this.verify(req, true, function (err, success) {
-    if (!success) {
-      abortConnection(socket, err);
-      return;
-    }
-
-    var head = Buffer.from(upgradeHead); // eslint-disable-line node/no-deprecated-api
-    upgradeHead = null;
-
-    // delegate to ws
-    self.ws.handleUpgrade(req, socket, head, function (conn) {
-      self.onWebSocket(req, conn);
-    });
-  });
-};
-
-/**
- * Called upon a ws.io connection.
- *
- * @param {ws.Socket} websocket
- * @api private
- */
-
-Server.prototype.onWebSocket = function (req, socket) {
-  socket.on('error', onUpgradeError);
-
-  if (transports[req._query.transport] !== undefined && !transports[req._query.transport].prototype.handlesUpgrades) {
-    debug('transport doesnt handle upgraded requests');
-    socket.close();
-    return;
-  }
-
-  // get client id
-  var id = req._query.sid;
-
-  // keep a reference to the ws.Socket
-  req.websocket = socket;
-
-  if (id) {
-    var client = this.clients[id];
-    if (!client) {
-      debug('upgrade attempt for closed client');
-      socket.close();
-    } else if (client.upgrading) {
-      debug('transport has already been trying to upgrade');
-      socket.close();
-    } else if (client.upgraded) {
-      debug('transport had already been upgraded');
-      socket.close();
-    } else {
-      debug('upgrading existing transport');
-
-      // transport error handling takes over
-      socket.removeListener('error', onUpgradeError);
-
-      var transport = new transports[req._query.transport](req);
-      if (req._query && req._query.b64) {
-        transport.supportsBinary = false;
-      } else {
-        transport.supportsBinary = true;
-      }
-      transport.perMessageDeflate = this.perMessageDeflate;
-      client.maybeUpgrade(transport);
-    }
-  } else {
-    // transport error handling takes over
-    socket.removeListener('error', onUpgradeError);
-
-    this.handshake(req._query.transport, req);
-  }
-
-  function onUpgradeError () {
-    debug('websocket error before upgrade');
-    // socket.close() not needed
-  }
-};
-
-/**
- * Captures upgrade requests for a http.Server.
- *
- * @param {http.Server} server
- * @param {Object} options
- * @api public
- */
-
-Server.prototype.attach = function (server, options) {
-  var self = this;
-  options = options || {};
-  var path = (options.path || '/engine.io').replace(/\/$/, '');
-
-  var destroyUpgradeTimeout = options.destroyUpgradeTimeout || 1000;
-
-  // normalize path
-  path += '/';
-
-  function check (req) {
-    if ('OPTIONS' === req.method && false === options.handlePreflightRequest) {
-      return false;
-    }
-    return path === req.url.substr(0, path.length);
-  }
-
-  // cache and clean up listeners
-  var listeners = server.listeners('request').slice(0);
-  server.removeAllListeners('request');
-  server.on('close', self.close.bind(self));
-  server.on('listening', self.init.bind(self));
-
-  // add request handler
-  server.on('request', function (req, res) {
-    if (check(req)) {
-      debug('intercepting request for path "%s"', path);
-      if ('OPTIONS' === req.method && 'function' === typeof options.handlePreflightRequest) {
-        options.handlePreflightRequest.call(server, req, res);
-      } else {
-        self.handleRequest(req, res);
-      }
-    } else {
-      for (var i = 0, l = listeners.length; i < l; i++) {
-        listeners[i].call(server, req, res);
-      }
-    }
-  });
-
-  if (~self.transports.indexOf('websocket')) {
-    server.on('upgrade', function (req, socket, head) {
-      if (check(req)) {
-        self.handleUpgrade(req, socket, head);
-      } else if (false !== options.destroyUpgrade) {
-        // default node behavior is to disconnect when no handlers
-        // but by adding a handler, we prevent that
-        // and if no eio thing handles the upgrade
-        // then the socket needs to die!
-        setTimeout(function () {
-          if (socket.writable && socket.bytesWritten <= 0) {
-            return socket.end();
-          }
-        }, destroyUpgradeTimeout);
-      }
-    });
-  }
-};
-
-/**
- * Closes the connection
- *
- * @param {net.Socket} socket
- * @param {code} error code
- * @api private
- */
-
-function abortConnection (socket, code) {
-  socket.on('error', () => {
-    debug('ignoring error from closed connection');
-  });
-  if (socket.writable) {
-    var message = Server.errorMessages.hasOwnProperty(code) ? Server.errorMessages[code] : String(code || '');
-    var length = Buffer.byteLength(message);
-    socket.write(
-      'HTTP/1.1 400 Bad Request\r\n' +
-      'Connection: close\r\n' +
-      'Content-type: text/html\r\n' +
-      'Content-Length: ' + length + '\r\n' +
-      '\r\n' +
-      message
-    );
-  }
-  socket.destroy();
-}
-
-/* eslint-disable */
-
-/**
- * From https://github.com/nodejs/node/blob/v8.4.0/lib/_http_common.js#L303-L354
- *
- * True if val contains an invalid field-vchar
- *  field-value    = *( field-content / obs-fold )
- *  field-content  = field-vchar [ 1*( SP / HTAB ) field-vchar ]
- *  field-vchar    = VCHAR / obs-text
- *
- * checkInvalidHeaderChar() is currently designed to be inlinable by v8,
- * so take care when making changes to the implementation so that the source
- * code size does not exceed v8's default max_inlined_source_size setting.
- **/
-var validHdrChars = [
-  0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, // 0 - 15
-  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31
-  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 32 - 47
-  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 48 - 63
-  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79
-  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 80 - 95
-  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111
-  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, // 112 - 127
-  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 128 ...
-  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
-  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
-  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
-  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
-  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
-  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
-  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1  // ... 255
-];
-
-function checkInvalidHeaderChar(val) {
-  val += '';
-  if (val.length < 1)
-    return false;
-  if (!validHdrChars[val.charCodeAt(0)]) {
-    debug('invalid header, index 0, char "%s"', val.charCodeAt(0));
-    return true;
-  }
-  if (val.length < 2)
-    return false;
-  if (!validHdrChars[val.charCodeAt(1)]) {
-    debug('invalid header, index 1, char "%s"', val.charCodeAt(1));
-    return true;
-  }
-  if (val.length < 3)
-    return false;
-  if (!validHdrChars[val.charCodeAt(2)]) {
-    debug('invalid header, index 2, char "%s"', val.charCodeAt(2));
-    return true;
-  }
-  if (val.length < 4)
-    return false;
-  if (!validHdrChars[val.charCodeAt(3)]) {
-    debug('invalid header, index 3, char "%s"', val.charCodeAt(3));
-    return true;
-  }
-  for (var i = 4; i < val.length; ++i) {
-    if (!validHdrChars[val.charCodeAt(i)]) {
-      debug('invalid header, index "%i", char "%s"', i, val.charCodeAt(i));
-      return true;
-    }
-  }
-  return false;
-}
+var qs=require("querystring"),parse=require("url").parse,base64id=require("base64id"),transports=require("./transports"),EventEmitter=require("events").EventEmitter,Socket=require("./socket"),util=require("util"),debug=require("debug")("engine"),cookieMod=require("cookie");function Server(e){if(!(this instanceof Server))return new Server(e);this.clients={},this.clientsCount=0,e=e||{},this.wsEngine=e.wsEngine||process.env.EIO_WS_ENGINE||"ws",this.pingTimeout=e.pingTimeout||5e3,this.pingInterval=e.pingInterval||25e3,this.upgradeTimeout=e.upgradeTimeout||1e4,this.maxHttpBufferSize=e.maxHttpBufferSize||1e8,this.transports=e.transports||Object.keys(transports),this.allowUpgrades=!1!==e.allowUpgrades,this.allowRequest=e.allowRequest,this.cookie=!1!==e.cookie&&(e.cookie||"io"),this.cookiePath=!1!==e.cookiePath&&(e.cookiePath||"/"),this.cookieHttpOnly=!1!==e.cookieHttpOnly,this.perMessageDeflate=e.perMessageDeflate||!1,this.httpCompression=!1!==e.httpCompression&&(e.httpCompression||{}),this.initialPacket=e.initialPacket;var r=this;["perMessageDeflate","httpCompression"].forEach((function(e){var t=r[e];!0===t&&(r[e]=t={}),t&&null==t.threshold&&(t.threshold=1024)})),this.init()}function sendErrorMessage(e,r,t){var s={"Content-Type":"application/json"};if(!Server.errorMessages.hasOwnProperty(t))return r.writeHead(403,s),void r.end(JSON.stringify({code:Server.errors.FORBIDDEN,message:t||Server.errorMessages[Server.errors.FORBIDDEN]}));e.headers.origin?(s["Access-Control-Allow-Credentials"]="true",s["Access-Control-Allow-Origin"]=e.headers.origin):s["Access-Control-Allow-Origin"]="*",void 0!==r&&(r.writeHead(400,s),r.end(JSON.stringify({code:t,message:Server.errorMessages[t]})))}function abortConnection(e,r){if(e.on("error",(()=>{debug("ignoring error from closed connection")})),e.writable){var t=Server.errorMessages.hasOwnProperty(r)?Server.errorMessages[r]:String(r||""),s=Buffer.byteLength(t);e.write("HTTP/1.1 400 Bad Request\r\nConnection: close\r\nContent-type: text/html\r\nContent-Length: "+s+"\r\n\r\n"+t)}e.destroy()}module.exports=Server,Server.errors={UNKNOWN_TRANSPORT:0,UNKNOWN_SID:1,BAD_HANDSHAKE_METHOD:2,BAD_REQUEST:3,FORBIDDEN:4},Server.errorMessages={0:"Transport unknown",1:"Session ID unknown",2:"Bad handshake method",3:"Bad request",4:"Forbidden"},util.inherits(Server,EventEmitter),Server.prototype.init=function(){if(~this.transports.indexOf("websocket")){this.ws&&this.ws.close();var e="ws"===this.wsEngine?require("ws"):require(this.wsEngine);this.ws=new e.Server({noServer:!0,clientTracking:!1,perMessageDeflate:this.perMessageDeflate,maxPayload:this.maxHttpBufferSize})}},Server.prototype.upgrades=function(e){return this.allowUpgrades&&transports[e].upgradesTo||[]},Server.prototype.verify=function(e,r,t){var s=e._query.transport;if(!~this.transports.indexOf(s))return debug('unknown transport "%s"',s),t(Server.errors.UNKNOWN_TRANSPORT,!1);if(checkInvalidHeaderChar(e.headers.origin))return e.headers.origin=null,debug("origin header invalid"),t(Server.errors.BAD_REQUEST,!1);var n=e._query.sid;return n?this.clients.hasOwnProperty(n)?r||this.clients[n].transport.name===s?void t(null,!0):(debug("bad request: unexpected transport without upgrade"),t(Server.errors.BAD_REQUEST,!1)):(debug('unknown sid "%s"',n),t(Server.errors.UNKNOWN_SID,!1)):"GET"!==e.method?t(Server.errors.BAD_HANDSHAKE_METHOD,!1):this.allowRequest?this.allowRequest(e,t):t(null,!0)},Server.prototype.prepare=function(e){e._query||(e._query=~e.url.indexOf("?")?qs.parse(parse(e.url).query):{})},Server.prototype.close=function(){for(var e in debug("closing all open clients"),this.clients)this.clients.hasOwnProperty(e)&&this.clients[e].close(!0);return this.ws&&(debug("closing webSocketServer"),this.ws.close()),this},Server.prototype.handleRequest=function(e,r){debug('handling "%s" http request "%s"',e.method,e.url),this.prepare(e),e.res=r;var t=this;this.verify(e,!1,(function(s,n){n?e._query.sid?(debug("setting new request for existing client"),t.clients[e._query.sid].transport.onRequest(e)):t.handshake(e._query.transport,e):sendErrorMessage(e,r,s)}))},Server.prototype.generateId=function(e){return base64id.generateId()},Server.prototype.handshake=function(e,r){var t=this.generateId(r);debug('handshaking client "%s"',t);try{var s=new transports[e](r);"polling"===e?(s.maxHttpBufferSize=this.maxHttpBufferSize,s.httpCompression=this.httpCompression):"websocket"===e&&(s.perMessageDeflate=this.perMessageDeflate),r._query&&r._query.b64?s.supportsBinary=!1:s.supportsBinary=!0}catch(t){return debug('error handshaking to transport "%s"',e),void sendErrorMessage(r,r.res,Server.errors.BAD_REQUEST)}var n=new Socket(t,this,s,r),i=this;!1!==this.cookie&&s.on("headers",(function(e){"object"==typeof i.cookie?e["Set-Cookie"]=cookieMod.serialize(i.cookie.name,t,i.cookie):e["Set-Cookie"]=cookieMod.serialize(i.cookie,t,{path:i.cookiePath,httpOnly:!!i.cookiePath&&i.cookieHttpOnly,sameSite:!0})})),s.onRequest(r),this.clients[t]=n,this.clientsCount++,n.once("close",(function(){delete i.clients[t],i.clientsCount--})),this.emit("connection",n)},Server.prototype.handleUpgrade=function(e,r,t){this.prepare(e);var s=this;this.verify(e,!0,(function(n,i){if(i){var o=Buffer.from(t);t=null,s.ws.handleUpgrade(e,r,o,(function(r){s.onWebSocket(e,r)}))}else abortConnection(r,n)}))},Server.prototype.onWebSocket=function(e,r){if(r.on("error",i),void 0!==transports[e._query.transport]&&!transports[e._query.transport].prototype.handlesUpgrades)return debug("transport doesnt handle upgraded requests"),void r.close();var t=e._query.sid;if(e.websocket=r,t){var s=this.clients[t];if(s)if(s.upgrading)debug("transport has already been trying to upgrade"),r.close();else if(s.upgraded)debug("transport had already been upgraded"),r.close();else{debug("upgrading existing transport"),r.removeListener("error",i);var n=new transports[e._query.transport](e);e._query&&e._query.b64?n.supportsBinary=!1:n.supportsBinary=!0,n.perMessageDeflate=this.perMessageDeflate,s.maybeUpgrade(n)}else debug("upgrade attempt for closed client"),r.close()}else r.removeListener("error",i),this.handshake(e._query.transport,e);function i(){debug("websocket error before upgrade")}},Server.prototype.attach=function(e,r){var t=this,s=((r=r||{}).path||"/engine.io").replace(/\/$/,""),n=r.destroyUpgradeTimeout||1e3;function i(e){return("OPTIONS"!==e.method||!1!==r.handlePreflightRequest)&&s===e.url.substr(0,s.length)}s+="/";var o=e.listeners("request").slice(0);e.removeAllListeners("request"),e.on("close",t.close.bind(t)),e.on("listening",t.init.bind(t)),e.on("request",(function(n,a){if(i(n))debug('intercepting request for path "%s"',s),"OPTIONS"===n.method&&"function"==typeof r.handlePreflightRequest?r.handlePreflightRequest.call(e,n,a):t.handleRequest(n,a);else for(var d=0,u=o.length;d<u;d++)o[d].call(e,n,a)})),~t.transports.indexOf("websocket")&&e.on("upgrade",(function(e,s,o){i(e)?t.handleUpgrade(e,s,o):!1!==r.destroyUpgrade&&setTimeout((function(){if(s.writable&&s.bytesWritten<=0)return s.end()}),n)}))};var validHdrChars=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];function checkInvalidHeaderChar(e){if((e+="").length<1)return!1;if(!validHdrChars[e.charCodeAt(0)])return debug('invalid header, index 0, char "%s"',e.charCodeAt(0)),!0;if(e.length<2)return!1;if(!validHdrChars[e.charCodeAt(1)])return debug('invalid header, index 1, char "%s"',e.charCodeAt(1)),!0;if(e.length<3)return!1;if(!validHdrChars[e.charCodeAt(2)])return debug('invalid header, index 2, char "%s"',e.charCodeAt(2)),!0;if(e.length<4)return!1;if(!validHdrChars[e.charCodeAt(3)])return debug('invalid header, index 3, char "%s"',e.charCodeAt(3)),!0;for(var r=4;r<e.length;++r)if(!validHdrChars[e.charCodeAt(r)])return debug('invalid header, index "%i", char "%s"',r,e.charCodeAt(r)),!0;return!1}
\ No newline at end of file
index 177b25c..1ee0351 100644 (file)
@@ -1,486 +1 @@
-/**
- * Module dependencies.
- */
-
-var EventEmitter = require('events').EventEmitter;
-var util = require('util');
-var debug = require('debug')('engine:socket');
-
-/**
- * Module exports.
- */
-
-module.exports = Socket;
-
-/**
- * Client class (abstract).
- *
- * @api private
- */
-
-function Socket (id, server, transport, req) {
-  this.id = id;
-  this.server = server;
-  this.upgrading = false;
-  this.upgraded = false;
-  this.readyState = 'opening';
-  this.writeBuffer = [];
-  this.packetsFn = [];
-  this.sentCallbackFn = [];
-  this.cleanupFn = [];
-  this.request = req;
-
-  // Cache IP since it might not be in the req later
-  if (req.websocket && req.websocket._socket) {
-    this.remoteAddress = req.websocket._socket.remoteAddress;
-  } else {
-    this.remoteAddress = req.connection.remoteAddress;
-  }
-
-  this.checkIntervalTimer = null;
-  this.upgradeTimeoutTimer = null;
-  this.pingTimeoutTimer = null;
-
-  this.setTransport(transport);
-  this.onOpen();
-}
-
-/**
- * Inherits from EventEmitter.
- */
-
-util.inherits(Socket, EventEmitter);
-
-/**
- * Called upon transport considered open.
- *
- * @api private
- */
-
-Socket.prototype.onOpen = function () {
-  this.readyState = 'open';
-
-  // sends an `open` packet
-  this.transport.sid = this.id;
-  this.sendPacket('open', JSON.stringify({
-    sid: this.id,
-    upgrades: this.getAvailableUpgrades(),
-    pingInterval: this.server.pingInterval,
-    pingTimeout: this.server.pingTimeout
-  }));
-
-  if (this.server.initialPacket) {
-    this.sendPacket('message', this.server.initialPacket);
-  }
-
-  this.emit('open');
-  this.setPingTimeout();
-};
-
-/**
- * Called upon transport packet.
- *
- * @param {Object} packet
- * @api private
- */
-
-Socket.prototype.onPacket = function (packet) {
-  if ('open' === this.readyState) {
-    // export packet event
-    debug('packet');
-    this.emit('packet', packet);
-
-    // Reset ping timeout on any packet, incoming data is a good sign of
-    // other side's liveness
-    this.setPingTimeout();
-
-    switch (packet.type) {
-      case 'ping':
-        debug('got ping');
-        this.sendPacket('pong');
-        this.emit('heartbeat');
-        break;
-
-      case 'error':
-        this.onClose('parse error');
-        break;
-
-      case 'message':
-        this.emit('data', packet.data);
-        this.emit('message', packet.data);
-        break;
-    }
-  } else {
-    debug('packet received with closed socket');
-  }
-};
-
-/**
- * Called upon transport error.
- *
- * @param {Error} error object
- * @api private
- */
-
-Socket.prototype.onError = function (err) {
-  debug('transport error');
-  this.onClose('transport error', err);
-};
-
-/**
- * Sets and resets ping timeout timer based on client pings.
- *
- * @api private
- */
-
-Socket.prototype.setPingTimeout = function () {
-  var self = this;
-  clearTimeout(self.pingTimeoutTimer);
-  self.pingTimeoutTimer = setTimeout(function () {
-    self.onClose('ping timeout');
-  }, self.server.pingInterval + self.server.pingTimeout);
-};
-
-/**
- * Attaches handlers for the given transport.
- *
- * @param {Transport} transport
- * @api private
- */
-
-Socket.prototype.setTransport = function (transport) {
-  var onError = this.onError.bind(this);
-  var onPacket = this.onPacket.bind(this);
-  var flush = this.flush.bind(this);
-  var onClose = this.onClose.bind(this, 'transport close');
-
-  this.transport = transport;
-  this.transport.once('error', onError);
-  this.transport.on('packet', onPacket);
-  this.transport.on('drain', flush);
-  this.transport.once('close', onClose);
-  // this function will manage packet events (also message callbacks)
-  this.setupSendCallback();
-
-  this.cleanupFn.push(function () {
-    transport.removeListener('error', onError);
-    transport.removeListener('packet', onPacket);
-    transport.removeListener('drain', flush);
-    transport.removeListener('close', onClose);
-  });
-};
-
-/**
- * Upgrades socket to the given transport
- *
- * @param {Transport} transport
- * @api private
- */
-
-Socket.prototype.maybeUpgrade = function (transport) {
-  debug('might upgrade socket transport from "%s" to "%s"'
-    , this.transport.name, transport.name);
-
-  this.upgrading = true;
-
-  var self = this;
-
-  // set transport upgrade timer
-  self.upgradeTimeoutTimer = setTimeout(function () {
-    debug('client did not complete upgrade - closing transport');
-    cleanup();
-    if ('open' === transport.readyState) {
-      transport.close();
-    }
-  }, this.server.upgradeTimeout);
-
-  function onPacket (packet) {
-    if ('ping' === packet.type && 'probe' === packet.data) {
-      transport.send([{ type: 'pong', data: 'probe' }]);
-      self.emit('upgrading', transport);
-      clearInterval(self.checkIntervalTimer);
-      self.checkIntervalTimer = setInterval(check, 100);
-    } else if ('upgrade' === packet.type && self.readyState !== 'closed') {
-      debug('got upgrade packet - upgrading');
-      cleanup();
-      self.transport.discard();
-      self.upgraded = true;
-      self.clearTransport();
-      self.setTransport(transport);
-      self.emit('upgrade', transport);
-      self.setPingTimeout();
-      self.flush();
-      if (self.readyState === 'closing') {
-        transport.close(function () {
-          self.onClose('forced close');
-        });
-      }
-    } else {
-      cleanup();
-      transport.close();
-    }
-  }
-
-  // we force a polling cycle to ensure a fast upgrade
-  function check () {
-    if ('polling' === self.transport.name && self.transport.writable) {
-      debug('writing a noop packet to polling for fast upgrade');
-      self.transport.send([{ type: 'noop' }]);
-    }
-  }
-
-  function cleanup () {
-    self.upgrading = false;
-
-    clearInterval(self.checkIntervalTimer);
-    self.checkIntervalTimer = null;
-
-    clearTimeout(self.upgradeTimeoutTimer);
-    self.upgradeTimeoutTimer = null;
-
-    transport.removeListener('packet', onPacket);
-    transport.removeListener('close', onTransportClose);
-    transport.removeListener('error', onError);
-    self.removeListener('close', onClose);
-  }
-
-  function onError (err) {
-    debug('client did not complete upgrade - %s', err);
-    cleanup();
-    transport.close();
-    transport = null;
-  }
-
-  function onTransportClose () {
-    onError('transport closed');
-  }
-
-  function onClose () {
-    onError('socket closed');
-  }
-
-  transport.on('packet', onPacket);
-  transport.once('close', onTransportClose);
-  transport.once('error', onError);
-
-  self.once('close', onClose);
-};
-
-/**
- * Clears listeners and timers associated with current transport.
- *
- * @api private
- */
-
-Socket.prototype.clearTransport = function () {
-  var cleanup;
-
-  var toCleanUp = this.cleanupFn.length;
-
-  for (var i = 0; i < toCleanUp; i++) {
-    cleanup = this.cleanupFn.shift();
-    cleanup();
-  }
-
-  // silence further transport errors and prevent uncaught exceptions
-  this.transport.on('error', function () {
-    debug('error triggered by discarded transport');
-  });
-
-  // ensure transport won't stay open
-  this.transport.close();
-
-  clearTimeout(this.pingTimeoutTimer);
-};
-
-/**
- * Called upon transport considered closed.
- * Possible reasons: `ping timeout`, `client error`, `parse error`,
- * `transport error`, `server close`, `transport close`
- */
-
-Socket.prototype.onClose = function (reason, description) {
-  if ('closed' !== this.readyState) {
-    this.readyState = 'closed';
-    clearTimeout(this.pingTimeoutTimer);
-    clearInterval(this.checkIntervalTimer);
-    this.checkIntervalTimer = null;
-    clearTimeout(this.upgradeTimeoutTimer);
-    var self = this;
-    // clean writeBuffer in next tick, so developers can still
-    // grab the writeBuffer on 'close' event
-    process.nextTick(function () {
-      self.writeBuffer = [];
-    });
-    this.packetsFn = [];
-    this.sentCallbackFn = [];
-    this.clearTransport();
-    this.emit('close', reason, description);
-  }
-};
-
-/**
- * Setup and manage send callback
- *
- * @api private
- */
-
-Socket.prototype.setupSendCallback = function () {
-  var self = this;
-  this.transport.on('drain', onDrain);
-
-  this.cleanupFn.push(function () {
-    self.transport.removeListener('drain', onDrain);
-  });
-
-  // the message was sent successfully, execute the callback
-  function onDrain () {
-    if (self.sentCallbackFn.length > 0) {
-      var seqFn = self.sentCallbackFn.splice(0, 1)[0];
-      if ('function' === typeof seqFn) {
-        debug('executing send callback');
-        seqFn(self.transport);
-      } else if (Array.isArray(seqFn)) {
-        debug('executing batch send callback');
-        for (var l = seqFn.length, i = 0; i < l; i++) {
-          if ('function' === typeof seqFn[i]) {
-            seqFn[i](self.transport);
-          }
-        }
-      }
-    }
-  }
-};
-
-/**
- * Sends a message packet.
- *
- * @param {String} message
- * @param {Object} options
- * @param {Function} callback
- * @return {Socket} for chaining
- * @api public
- */
-
-Socket.prototype.send =
-Socket.prototype.write = function (data, options, callback) {
-  this.sendPacket('message', data, options, callback);
-  return this;
-};
-
-/**
- * Sends a packet.
- *
- * @param {String} packet type
- * @param {String} optional, data
- * @param {Object} options
- * @api private
- */
-
-Socket.prototype.sendPacket = function (type, data, options, callback) {
-  if ('function' === typeof options) {
-    callback = options;
-    options = null;
-  }
-
-  options = options || {};
-  options.compress = false !== options.compress;
-
-  if ('closing' !== this.readyState && 'closed' !== this.readyState) {
-    debug('sending packet "%s" (%s)', type, data);
-
-    var packet = {
-      type: type,
-      options: options
-    };
-    if (data) packet.data = data;
-
-    // exports packetCreate event
-    this.emit('packetCreate', packet);
-
-    this.writeBuffer.push(packet);
-
-    // add send callback to object, if defined
-    if (callback) this.packetsFn.push(callback);
-
-    this.flush();
-  }
-};
-
-/**
- * Attempts to flush the packets buffer.
- *
- * @api private
- */
-
-Socket.prototype.flush = function () {
-  if ('closed' !== this.readyState &&
-                this.transport.writable &&
-                this.writeBuffer.length) {
-    debug('flushing buffer to transport');
-    this.emit('flush', this.writeBuffer);
-    this.server.emit('flush', this, this.writeBuffer);
-    var wbuf = this.writeBuffer;
-    this.writeBuffer = [];
-    if (!this.transport.supportsFraming) {
-      this.sentCallbackFn.push(this.packetsFn);
-    } else {
-      this.sentCallbackFn.push.apply(this.sentCallbackFn, this.packetsFn);
-    }
-    this.packetsFn = [];
-    this.transport.send(wbuf);
-    this.emit('drain');
-    this.server.emit('drain', this);
-  }
-};
-
-/**
- * Get available upgrades for this socket.
- *
- * @api private
- */
-
-Socket.prototype.getAvailableUpgrades = function () {
-  var availableUpgrades = [];
-  var allUpgrades = this.server.upgrades(this.transport.name);
-  for (var i = 0, l = allUpgrades.length; i < l; ++i) {
-    var upg = allUpgrades[i];
-    if (this.server.transports.indexOf(upg) !== -1) {
-      availableUpgrades.push(upg);
-    }
-  }
-  return availableUpgrades;
-};
-
-/**
- * Closes the socket and underlying transport.
- *
- * @param {Boolean} optional, discard
- * @return {Socket} for chaining
- * @api public
- */
-
-Socket.prototype.close = function (discard) {
-  if ('open' !== this.readyState) return;
-
-  this.readyState = 'closing';
-
-  if (this.writeBuffer.length) {
-    this.once('drain', this.closeTransport.bind(this, discard));
-    return;
-  }
-
-  this.closeTransport(discard);
-};
-
-/**
- * Closes the underlying transport.
- *
- * @param {Boolean} discard
- * @api private
- */
-
-Socket.prototype.closeTransport = function (discard) {
-  if (discard) this.transport.discard();
-  this.transport.close(this.onClose.bind(this, 'forced close'));
-};
+var EventEmitter=require("events").EventEmitter,util=require("util"),debug=require("debug")("engine:socket");function Socket(e,t,r,s){this.id=e,this.server=t,this.upgrading=!1,this.upgraded=!1,this.readyState="opening",this.writeBuffer=[],this.packetsFn=[],this.sentCallbackFn=[],this.cleanupFn=[],this.request=s,s.websocket&&s.websocket._socket?this.remoteAddress=s.websocket._socket.remoteAddress:this.remoteAddress=s.connection.remoteAddress,this.checkIntervalTimer=null,this.upgradeTimeoutTimer=null,this.pingTimeoutTimer=null,this.setTransport(r),this.onOpen()}module.exports=Socket,util.inherits(Socket,EventEmitter),Socket.prototype.onOpen=function(){this.readyState="open",this.transport.sid=this.id,this.sendPacket("open",JSON.stringify({sid:this.id,upgrades:this.getAvailableUpgrades(),pingInterval:this.server.pingInterval,pingTimeout:this.server.pingTimeout})),this.server.initialPacket&&this.sendPacket("message",this.server.initialPacket),this.emit("open"),this.setPingTimeout()},Socket.prototype.onPacket=function(e){if("open"===this.readyState)switch(debug("packet"),this.emit("packet",e),this.setPingTimeout(),e.type){case"ping":debug("got ping"),this.sendPacket("pong"),this.emit("heartbeat");break;case"error":this.onClose("parse error");break;case"message":this.emit("data",e.data),this.emit("message",e.data)}else debug("packet received with closed socket")},Socket.prototype.onError=function(e){debug("transport error"),this.onClose("transport error",e)},Socket.prototype.setPingTimeout=function(){var e=this;clearTimeout(e.pingTimeoutTimer),e.pingTimeoutTimer=setTimeout((function(){e.onClose("ping timeout")}),e.server.pingInterval+e.server.pingTimeout)},Socket.prototype.setTransport=function(e){var t=this.onError.bind(this),r=this.onPacket.bind(this),s=this.flush.bind(this),i=this.onClose.bind(this,"transport close");this.transport=e,this.transport.once("error",t),this.transport.on("packet",r),this.transport.on("drain",s),this.transport.once("close",i),this.setupSendCallback(),this.cleanupFn.push((function(){e.removeListener("error",t),e.removeListener("packet",r),e.removeListener("drain",s),e.removeListener("close",i)}))},Socket.prototype.maybeUpgrade=function(e){debug('might upgrade socket transport from "%s" to "%s"',this.transport.name,e.name),this.upgrading=!0;var t=this;function r(r){"ping"===r.type&&"probe"===r.data?(e.send([{type:"pong",data:"probe"}]),t.emit("upgrading",e),clearInterval(t.checkIntervalTimer),t.checkIntervalTimer=setInterval(s,100)):"upgrade"===r.type&&"closed"!==t.readyState?(debug("got upgrade packet - upgrading"),i(),t.transport.discard(),t.upgraded=!0,t.clearTransport(),t.setTransport(e),t.emit("upgrade",e),t.setPingTimeout(),t.flush(),"closing"===t.readyState&&e.close((function(){t.onClose("forced close")}))):(i(),e.close())}function s(){"polling"===t.transport.name&&t.transport.writable&&(debug("writing a noop packet to polling for fast upgrade"),t.transport.send([{type:"noop"}]))}function i(){t.upgrading=!1,clearInterval(t.checkIntervalTimer),t.checkIntervalTimer=null,clearTimeout(t.upgradeTimeoutTimer),t.upgradeTimeoutTimer=null,e.removeListener("packet",r),e.removeListener("close",o),e.removeListener("error",n),t.removeListener("close",a)}function n(t){debug("client did not complete upgrade - %s",t),i(),e.close(),e=null}function o(){n("transport closed")}function a(){n("socket closed")}t.upgradeTimeoutTimer=setTimeout((function(){debug("client did not complete upgrade - closing transport"),i(),"open"===e.readyState&&e.close()}),this.server.upgradeTimeout),e.on("packet",r),e.once("close",o),e.once("error",n),t.once("close",a)},Socket.prototype.clearTransport=function(){for(var e=this.cleanupFn.length,t=0;t<e;t++)this.cleanupFn.shift()();this.transport.on("error",(function(){debug("error triggered by discarded transport")})),this.transport.close(),clearTimeout(this.pingTimeoutTimer)},Socket.prototype.onClose=function(e,t){if("closed"!==this.readyState){this.readyState="closed",clearTimeout(this.pingTimeoutTimer),clearInterval(this.checkIntervalTimer),this.checkIntervalTimer=null,clearTimeout(this.upgradeTimeoutTimer);var r=this;process.nextTick((function(){r.writeBuffer=[]})),this.packetsFn=[],this.sentCallbackFn=[],this.clearTransport(),this.emit("close",e,t)}},Socket.prototype.setupSendCallback=function(){var e=this;function t(){if(e.sentCallbackFn.length>0){var t=e.sentCallbackFn.splice(0,1)[0];if("function"==typeof t)debug("executing send callback"),t(e.transport);else if(Array.isArray(t)){debug("executing batch send callback");for(var r=t.length,s=0;s<r;s++)"function"==typeof t[s]&&t[s](e.transport)}}}this.transport.on("drain",t),this.cleanupFn.push((function(){e.transport.removeListener("drain",t)}))},Socket.prototype.send=Socket.prototype.write=function(e,t,r){return this.sendPacket("message",e,t,r),this},Socket.prototype.sendPacket=function(e,t,r,s){if("function"==typeof r&&(s=r,r=null),(r=r||{}).compress=!1!==r.compress,"closing"!==this.readyState&&"closed"!==this.readyState){debug('sending packet "%s" (%s)',e,t);var i={type:e,options:r};t&&(i.data=t),this.emit("packetCreate",i),this.writeBuffer.push(i),s&&this.packetsFn.push(s),this.flush()}},Socket.prototype.flush=function(){if("closed"!==this.readyState&&this.transport.writable&&this.writeBuffer.length){debug("flushing buffer to transport"),this.emit("flush",this.writeBuffer),this.server.emit("flush",this,this.writeBuffer);var e=this.writeBuffer;this.writeBuffer=[],this.transport.supportsFraming?this.sentCallbackFn.push.apply(this.sentCallbackFn,this.packetsFn):this.sentCallbackFn.push(this.packetsFn),this.packetsFn=[],this.transport.send(e),this.emit("drain"),this.server.emit("drain",this)}},Socket.prototype.getAvailableUpgrades=function(){for(var e=[],t=this.server.upgrades(this.transport.name),r=0,s=t.length;r<s;++r){var i=t[r];-1!==this.server.transports.indexOf(i)&&e.push(i)}return e},Socket.prototype.close=function(e){"open"===this.readyState&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",this.closeTransport.bind(this,e)):this.closeTransport(e))},Socket.prototype.closeTransport=function(e){e&&this.transport.discard(),this.transport.close(this.onClose.bind(this,"forced close"))};
\ No newline at end of file
index 933dad5..545fdbe 100644 (file)
@@ -1,128 +1 @@
-
-/**
- * Module dependencies.
- */
-
-var EventEmitter = require('events').EventEmitter;
-var parser = require('engine.io-parser');
-var util = require('util');
-var debug = require('debug')('engine:transport');
-
-/**
- * Expose the constructor.
- */
-
-module.exports = Transport;
-
-/**
- * Noop function.
- *
- * @api private
- */
-
-function noop () {}
-
-/**
- * Transport constructor.
- *
- * @param {http.IncomingMessage} request
- * @api public
- */
-
-function Transport (req) {
-  this.readyState = 'open';
-  this.discarded = false;
-}
-
-/**
- * Inherits from EventEmitter.
- */
-
-util.inherits(Transport, EventEmitter);
-
-/**
- * Flags the transport as discarded.
- *
- * @api private
- */
-
-Transport.prototype.discard = function () {
-  this.discarded = true;
-};
-
-/**
- * Called with an incoming HTTP request.
- *
- * @param {http.IncomingMessage} request
- * @api private
- */
-
-Transport.prototype.onRequest = function (req) {
-  debug('setting request');
-  this.req = req;
-};
-
-/**
- * Closes the transport.
- *
- * @api private
- */
-
-Transport.prototype.close = function (fn) {
-  if ('closed' === this.readyState || 'closing' === this.readyState) return;
-
-  this.readyState = 'closing';
-  this.doClose(fn || noop);
-};
-
-/**
- * Called with a transport error.
- *
- * @param {String} message error
- * @param {Object} error description
- * @api private
- */
-
-Transport.prototype.onError = function (msg, desc) {
-  if (this.listeners('error').length) {
-    var err = new Error(msg);
-    err.type = 'TransportError';
-    err.description = desc;
-    this.emit('error', err);
-  } else {
-    debug('ignored transport error %s (%s)', msg, desc);
-  }
-};
-
-/**
- * Called with parsed out a packets from the data stream.
- *
- * @param {Object} packet
- * @api private
- */
-
-Transport.prototype.onPacket = function (packet) {
-  this.emit('packet', packet);
-};
-
-/**
- * Called with the encoded packet data.
- *
- * @param {String} data
- * @api private
- */
-
-Transport.prototype.onData = function (data) {
-  this.onPacket(parser.decodePacket(data));
-};
-
-/**
- * Called upon transport close.
- *
- * @api private
- */
-
-Transport.prototype.onClose = function () {
-  this.readyState = 'closed';
-  this.emit('close');
-};
+var EventEmitter=require("events").EventEmitter,parser=require("engine.io-parser"),util=require("util"),debug=require("debug")("engine:transport");function noop(){}function Transport(t){this.readyState="open",this.discarded=!1}module.exports=Transport,util.inherits(Transport,EventEmitter),Transport.prototype.discard=function(){this.discarded=!0},Transport.prototype.onRequest=function(t){debug("setting request"),this.req=t},Transport.prototype.close=function(t){"closed"!==this.readyState&&"closing"!==this.readyState&&(this.readyState="closing",this.doClose(t||noop))},Transport.prototype.onError=function(t,r){if(this.listeners("error").length){var e=new Error(t);e.type="TransportError",e.description=r,this.emit("error",e)}else debug("ignored transport error %s (%s)",t,r)},Transport.prototype.onPacket=function(t){this.emit("packet",t)},Transport.prototype.onData=function(t){this.onPacket(parser.decodePacket(t))},Transport.prototype.onClose=function(){this.readyState="closed",this.emit("close")};
\ No newline at end of file
index fcff322..20db4ab 100644 (file)
@@ -1,36 +1 @@
-
-/**
- * Module dependencies.
- */
-
-var XHR = require('./polling-xhr');
-var JSONP = require('./polling-jsonp');
-
-/**
- * Export transports.
- */
-
-module.exports = exports = {
-  polling: polling,
-  websocket: require('./websocket')
-};
-
-/**
- * Export upgrades map.
- */
-
-exports.polling.upgradesTo = ['websocket'];
-
-/**
- * Polling polymorphic constructor.
- *
- * @api private
- */
-
-function polling (req) {
-  if ('string' === typeof req._query.j) {
-    return new JSONP(req);
-  } else {
-    return new XHR(req);
-  }
-}
+var XHR=require("./polling-xhr"),JSONP=require("./polling-jsonp");function polling(e){return"string"==typeof e._query.j?new JSONP(e):new XHR(e)}module.exports=exports={polling:polling,websocket:require("./websocket")},exports.polling.upgradesTo=["websocket"];
\ No newline at end of file
index 62e66e7..7d52d52 100644 (file)
@@ -1,75 +1 @@
-
-/**
- * Module dependencies.
- */
-
-var Polling = require('./polling');
-var qs = require('querystring');
-var rDoubleSlashes = /\\\\n/g;
-var rSlashes = /(\\)?\\n/g;
-var util = require('util');
-
-/**
- * Module exports.
- */
-
-module.exports = JSONP;
-
-/**
- * JSON-P polling transport.
- *
- * @api public
- */
-
-function JSONP (req) {
-  Polling.call(this, req);
-
-  this.head = '___eio[' + (req._query.j || '').replace(/[^0-9]/g, '') + '](';
-  this.foot = ');';
-}
-
-/**
- * Inherits from Polling.
- */
-
-util.inherits(JSONP, Polling);
-
-/**
- * Handles incoming data.
- * Due to a bug in \n handling by browsers, we expect a escaped string.
- *
- * @api private
- */
-
-JSONP.prototype.onData = function (data) {
-  // we leverage the qs module so that we get built-in DoS protection
-  // and the fast alternative to decodeURIComponent
-  data = qs.parse(data).d;
-  if ('string' === typeof data) {
-    // client will send already escaped newlines as \\\\n and newlines as \\n
-    // \\n must be replaced with \n and \\\\n with \\n
-    data = data.replace(rSlashes, function (match, slashes) {
-      return slashes ? match : '\n';
-    });
-    Polling.prototype.onData.call(this, data.replace(rDoubleSlashes, '\\n'));
-  }
-};
-
-/**
- * Performs the write.
- *
- * @api private
- */
-
-JSONP.prototype.doWrite = function (data, options, callback) {
-  // we must output valid javascript, not valid json
-  // see: http://timelessrepo.com/json-isnt-a-javascript-subset
-  var js = JSON.stringify(data)
-    .replace(/\u2028/g, '\\u2028')
-    .replace(/\u2029/g, '\\u2029');
-
-  // prepare response
-  data = this.head + js + this.foot;
-
-  Polling.prototype.doWrite.call(this, data, options, callback);
-};
+var Polling=require("./polling"),qs=require("querystring"),rDoubleSlashes=/\\\\n/g,rSlashes=/(\\)?\\n/g,util=require("util");function JSONP(e){Polling.call(this,e),this.head="___eio["+(e._query.j||"").replace(/[^0-9]/g,"")+"](",this.foot=");"}module.exports=JSONP,util.inherits(JSONP,Polling),JSONP.prototype.onData=function(e){"string"==typeof(e=qs.parse(e).d)&&(e=e.replace(rSlashes,(function(e,t){return t?e:"\n"})),Polling.prototype.onData.call(this,e.replace(rDoubleSlashes,"\\n")))},JSONP.prototype.doWrite=function(e,t,l){var r=JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029");e=this.head+r+this.foot,Polling.prototype.doWrite.call(this,e,t,l)};
\ No newline at end of file
index 3562524..531f35c 100644 (file)
@@ -1,69 +1 @@
-
-/**
- * Module dependencies.
- */
-
-var Polling = require('./polling');
-var util = require('util');
-
-/**
- * Module exports.
- */
-
-module.exports = XHR;
-
-/**
- * Ajax polling transport.
- *
- * @api public
- */
-
-function XHR (req) {
-  Polling.call(this, req);
-}
-
-/**
- * Inherits from Polling.
- */
-
-util.inherits(XHR, Polling);
-
-/**
- * Overrides `onRequest` to handle `OPTIONS`..
- *
- * @param {http.IncomingMessage}
- * @api private
- */
-
-XHR.prototype.onRequest = function (req) {
-  if ('OPTIONS' === req.method) {
-    var res = req.res;
-    var headers = this.headers(req);
-    headers['Access-Control-Allow-Headers'] = 'Content-Type';
-    res.writeHead(200, headers);
-    res.end();
-  } else {
-    Polling.prototype.onRequest.call(this, req);
-  }
-};
-
-/**
- * Returns headers for a response.
- *
- * @param {http.IncomingMessage} request
- * @param {Object} extra headers
- * @api private
- */
-
-XHR.prototype.headers = function (req, headers) {
-  headers = headers || {};
-
-  if (req.headers.origin) {
-    headers['Access-Control-Allow-Credentials'] = 'true';
-    headers['Access-Control-Allow-Origin'] = req.headers.origin;
-  } else {
-    headers['Access-Control-Allow-Origin'] = '*';
-  }
-
-  return Polling.prototype.headers.call(this, req, headers);
-};
+var Polling=require("./polling"),util=require("util");function XHR(e){Polling.call(this,e)}module.exports=XHR,util.inherits(XHR,Polling),XHR.prototype.onRequest=function(e){if("OPTIONS"===e.method){var o=e.res,l=this.headers(e);l["Access-Control-Allow-Headers"]="Content-Type",o.writeHead(200,l),o.end()}else Polling.prototype.onRequest.call(this,e)},XHR.prototype.headers=function(e,o){return o=o||{},e.headers.origin?(o["Access-Control-Allow-Credentials"]="true",o["Access-Control-Allow-Origin"]=e.headers.origin):o["Access-Control-Allow-Origin"]="*",Polling.prototype.headers.call(this,e,o)};
\ No newline at end of file
index 7c29c29..e61f032 100644 (file)
@@ -1,407 +1 @@
-
-/**
- * Module requirements.
- */
-
-var Transport = require('../transport');
-var parser = require('engine.io-parser');
-var zlib = require('zlib');
-var accepts = require('accepts');
-var util = require('util');
-var debug = require('debug')('engine:polling');
-
-var compressionMethods = {
-  gzip: zlib.createGzip,
-  deflate: zlib.createDeflate
-};
-
-/**
- * Exports the constructor.
- */
-
-module.exports = Polling;
-
-/**
- * HTTP polling constructor.
- *
- * @api public.
- */
-
-function Polling (req) {
-  Transport.call(this, req);
-
-  this.closeTimeout = 30 * 1000;
-  this.maxHttpBufferSize = null;
-  this.httpCompression = null;
-}
-
-/**
- * Inherits from Transport.
- *
- * @api public.
- */
-
-util.inherits(Polling, Transport);
-
-/**
- * Transport name
- *
- * @api public
- */
-
-Polling.prototype.name = 'polling';
-
-/**
- * Overrides onRequest.
- *
- * @param {http.IncomingMessage}
- * @api private
- */
-
-Polling.prototype.onRequest = function (req) {
-  var res = req.res;
-
-  if ('GET' === req.method) {
-    this.onPollRequest(req, res);
-  } else if ('POST' === req.method) {
-    this.onDataRequest(req, res);
-  } else {
-    res.writeHead(500);
-    res.end();
-  }
-};
-
-/**
- * The client sends a request awaiting for us to send data.
- *
- * @api private
- */
-
-Polling.prototype.onPollRequest = function (req, res) {
-  if (this.req) {
-    debug('request overlap');
-    // assert: this.res, '.req and .res should be (un)set together'
-    this.onError('overlap from client');
-    res.writeHead(500);
-    res.end();
-    return;
-  }
-
-  debug('setting request');
-
-  this.req = req;
-  this.res = res;
-
-  var self = this;
-
-  function onClose () {
-    self.onError('poll connection closed prematurely');
-  }
-
-  function cleanup () {
-    req.removeListener('close', onClose);
-    self.req = self.res = null;
-  }
-
-  req.cleanup = cleanup;
-  req.on('close', onClose);
-
-  this.writable = true;
-  this.emit('drain');
-
-  // if we're still writable but had a pending close, trigger an empty send
-  if (this.writable && this.shouldClose) {
-    debug('triggering empty send to append close packet');
-    this.send([{ type: 'noop' }]);
-  }
-};
-
-/**
- * The client sends a request with data.
- *
- * @api private
- */
-
-Polling.prototype.onDataRequest = function (req, res) {
-  if (this.dataReq) {
-    // assert: this.dataRes, '.dataReq and .dataRes should be (un)set together'
-    this.onError('data request overlap from client');
-    res.writeHead(500);
-    res.end();
-    return;
-  }
-
-  var isBinary = 'application/octet-stream' === req.headers['content-type'];
-
-  this.dataReq = req;
-  this.dataRes = res;
-
-  var chunks = isBinary ? Buffer.concat([]) : '';
-  var self = this;
-
-  function cleanup () {
-    req.removeListener('data', onData);
-    req.removeListener('end', onEnd);
-    req.removeListener('close', onClose);
-    self.dataReq = self.dataRes = chunks = null;
-  }
-
-  function onClose () {
-    cleanup();
-    self.onError('data request connection closed prematurely');
-  }
-
-  function onData (data) {
-    var contentLength;
-    if (isBinary) {
-      chunks = Buffer.concat([chunks, data]);
-      contentLength = chunks.length;
-    } else {
-      chunks += data;
-      contentLength = Buffer.byteLength(chunks);
-    }
-
-    if (contentLength > self.maxHttpBufferSize) {
-      chunks = isBinary ? Buffer.concat([]) : '';
-      req.connection.destroy();
-    }
-  }
-
-  function onEnd () {
-    self.onData(chunks);
-
-    var headers = {
-      // text/html is required instead of text/plain to avoid an
-      // unwanted download dialog on certain user-agents (GH-43)
-      'Content-Type': 'text/html',
-      'Content-Length': 2
-    };
-
-    res.writeHead(200, self.headers(req, headers));
-    res.end('ok');
-    cleanup();
-  }
-
-  req.on('close', onClose);
-  if (!isBinary) req.setEncoding('utf8');
-  req.on('data', onData);
-  req.on('end', onEnd);
-};
-
-/**
- * Processes the incoming data payload.
- *
- * @param {String} encoded payload
- * @api private
- */
-
-Polling.prototype.onData = function (data) {
-  debug('received "%s"', data);
-  var self = this;
-  var callback = function (packet) {
-    if ('close' === packet.type) {
-      debug('got xhr close packet');
-      self.onClose();
-      return false;
-    }
-
-    self.onPacket(packet);
-  };
-
-  parser.decodePayload(data, callback);
-};
-
-/**
- * Overrides onClose.
- *
- * @api private
- */
-
-Polling.prototype.onClose = function () {
-  if (this.writable) {
-    // close pending poll request
-    this.send([{ type: 'noop' }]);
-  }
-  Transport.prototype.onClose.call(this);
-};
-
-/**
- * Writes a packet payload.
- *
- * @param {Object} packet
- * @api private
- */
-
-Polling.prototype.send = function (packets) {
-  this.writable = false;
-
-  if (this.shouldClose) {
-    debug('appending close packet to payload');
-    packets.push({ type: 'close' });
-    this.shouldClose();
-    this.shouldClose = null;
-  }
-
-  var self = this;
-  parser.encodePayload(packets, this.supportsBinary, function (data) {
-    var compress = packets.some(function (packet) {
-      return packet.options && packet.options.compress;
-    });
-    self.write(data, { compress: compress });
-  });
-};
-
-/**
- * Writes data as response to poll request.
- *
- * @param {String} data
- * @param {Object} options
- * @api private
- */
-
-Polling.prototype.write = function (data, options) {
-  debug('writing "%s"', data);
-  var self = this;
-  this.doWrite(data, options, function () {
-    self.req.cleanup();
-  });
-};
-
-/**
- * Performs the write.
- *
- * @api private
- */
-
-Polling.prototype.doWrite = function (data, options, callback) {
-  var self = this;
-
-  // explicit UTF-8 is required for pages not served under utf
-  var isString = typeof data === 'string';
-  var contentType = isString
-    ? 'text/plain; charset=UTF-8'
-    : 'application/octet-stream';
-
-  var headers = {
-    'Content-Type': contentType
-  };
-
-  if (!this.httpCompression || !options.compress) {
-    respond(data);
-    return;
-  }
-
-  var len = isString ? Buffer.byteLength(data) : data.length;
-  if (len < this.httpCompression.threshold) {
-    respond(data);
-    return;
-  }
-
-  var encoding = accepts(this.req).encodings(['gzip', 'deflate']);
-  if (!encoding) {
-    respond(data);
-    return;
-  }
-
-  this.compress(data, encoding, function (err, data) {
-    if (err) {
-      self.res.writeHead(500);
-      self.res.end();
-      callback(err);
-      return;
-    }
-
-    headers['Content-Encoding'] = encoding;
-    respond(data);
-  });
-
-  function respond (data) {
-    headers['Content-Length'] = 'string' === typeof data ? Buffer.byteLength(data) : data.length;
-    self.res.writeHead(200, self.headers(self.req, headers));
-    self.res.end(data);
-    callback();
-  }
-};
-
-/**
- * Compresses data.
- *
- * @api private
- */
-
-Polling.prototype.compress = function (data, encoding, callback) {
-  debug('compressing');
-
-  var buffers = [];
-  var nread = 0;
-
-  compressionMethods[encoding](this.httpCompression)
-    .on('error', callback)
-    .on('data', function (chunk) {
-      buffers.push(chunk);
-      nread += chunk.length;
-    })
-    .on('end', function () {
-      callback(null, Buffer.concat(buffers, nread));
-    })
-    .end(data);
-};
-
-/**
- * Closes the transport.
- *
- * @api private
- */
-
-Polling.prototype.doClose = function (fn) {
-  debug('closing');
-
-  var self = this;
-  var closeTimeoutTimer;
-
-  if (this.dataReq) {
-    debug('aborting ongoing data request');
-    this.dataReq.destroy();
-  }
-
-  if (this.writable) {
-    debug('transport writable - closing right away');
-    this.send([{ type: 'close' }]);
-    onClose();
-  } else if (this.discarded) {
-    debug('transport discarded - closing right away');
-    onClose();
-  } else {
-    debug('transport not writable - buffering orderly close');
-    this.shouldClose = onClose;
-    closeTimeoutTimer = setTimeout(onClose, this.closeTimeout);
-  }
-
-  function onClose () {
-    clearTimeout(closeTimeoutTimer);
-    fn();
-    self.onClose();
-  }
-};
-
-/**
- * Returns headers for a response.
- *
- * @param {http.IncomingMessage} request
- * @param {Object} extra headers
- * @api private
- */
-
-Polling.prototype.headers = function (req, headers) {
-  headers = headers || {};
-
-  // prevent XSS warnings on IE
-  // https://github.com/LearnBoost/socket.io/pull/1333
-  var ua = req.headers['user-agent'];
-  if (ua && (~ua.indexOf(';MSIE') || ~ua.indexOf('Trident/'))) {
-    headers['X-XSS-Protection'] = '0';
-  }
-
-  this.emit('headers', headers);
-  return headers;
-};
+var Transport=require("../transport"),parser=require("engine.io-parser"),zlib=require("zlib"),accepts=require("accepts"),util=require("util"),debug=require("debug")("engine:polling"),compressionMethods={gzip:zlib.createGzip,deflate:zlib.createDeflate};function Polling(e){Transport.call(this,e),this.closeTimeout=3e4,this.maxHttpBufferSize=null,this.httpCompression=null}module.exports=Polling,util.inherits(Polling,Transport),Polling.prototype.name="polling",Polling.prototype.onRequest=function(e){var t=e.res;"GET"===e.method?this.onPollRequest(e,t):"POST"===e.method?this.onDataRequest(e,t):(t.writeHead(500),t.end())},Polling.prototype.onPollRequest=function(e,t){if(this.req)return debug("request overlap"),this.onError("overlap from client"),t.writeHead(500),void t.end();debug("setting request"),this.req=e,this.res=t;var o=this;function n(){o.onError("poll connection closed prematurely")}e.cleanup=function(){e.removeListener("close",n),o.req=o.res=null},e.on("close",n),this.writable=!0,this.emit("drain"),this.writable&&this.shouldClose&&(debug("triggering empty send to append close packet"),this.send([{type:"noop"}]))},Polling.prototype.onDataRequest=function(e,t){if(this.dataReq)return this.onError("data request overlap from client"),t.writeHead(500),void t.end();var o="application/octet-stream"===e.headers["content-type"];this.dataReq=e,this.dataRes=t;var n=o?Buffer.concat([]):"",r=this;function i(){e.removeListener("data",a),e.removeListener("end",l),e.removeListener("close",s),r.dataReq=r.dataRes=n=null}function s(){i(),r.onError("data request connection closed prematurely")}function a(t){var i;o?i=(n=Buffer.concat([n,t])).length:(n+=t,i=Buffer.byteLength(n)),i>r.maxHttpBufferSize&&(n=o?Buffer.concat([]):"",e.connection.destroy())}function l(){r.onData(n);t.writeHead(200,r.headers(e,{"Content-Type":"text/html","Content-Length":2})),t.end("ok"),i()}e.on("close",s),o||e.setEncoding("utf8"),e.on("data",a),e.on("end",l)},Polling.prototype.onData=function(e){debug('received "%s"',e);var t=this;parser.decodePayload(e,(function(e){if("close"===e.type)return debug("got xhr close packet"),t.onClose(),!1;t.onPacket(e)}))},Polling.prototype.onClose=function(){this.writable&&this.send([{type:"noop"}]),Transport.prototype.onClose.call(this)},Polling.prototype.send=function(e){this.writable=!1,this.shouldClose&&(debug("appending close packet to payload"),e.push({type:"close"}),this.shouldClose(),this.shouldClose=null);var t=this;parser.encodePayload(e,this.supportsBinary,(function(o){var n=e.some((function(e){return e.options&&e.options.compress}));t.write(o,{compress:n})}))},Polling.prototype.write=function(e,t){debug('writing "%s"',e);var o=this;this.doWrite(e,t,(function(){o.req.cleanup()}))},Polling.prototype.doWrite=function(e,t,o){var n=this,r="string"==typeof e,i={"Content-Type":r?"text/plain; charset=UTF-8":"application/octet-stream"};if(this.httpCompression&&t.compress)if((r?Buffer.byteLength(e):e.length)<this.httpCompression.threshold)a(e);else{var s=accepts(this.req).encodings(["gzip","deflate"]);s?this.compress(e,s,(function(e,t){if(e)return n.res.writeHead(500),n.res.end(),void o(e);i["Content-Encoding"]=s,a(t)})):a(e)}else a(e);function a(e){i["Content-Length"]="string"==typeof e?Buffer.byteLength(e):e.length,n.res.writeHead(200,n.headers(n.req,i)),n.res.end(e),o()}},Polling.prototype.compress=function(e,t,o){debug("compressing");var n=[],r=0;compressionMethods[t](this.httpCompression).on("error",o).on("data",(function(e){n.push(e),r+=e.length})).on("end",(function(){o(null,Buffer.concat(n,r))})).end(e)},Polling.prototype.doClose=function(e){debug("closing");var t,o=this;function n(){clearTimeout(t),e(),o.onClose()}this.dataReq&&(debug("aborting ongoing data request"),this.dataReq.destroy()),this.writable?(debug("transport writable - closing right away"),this.send([{type:"close"}]),n()):this.discarded?(debug("transport discarded - closing right away"),n()):(debug("transport not writable - buffering orderly close"),this.shouldClose=n,t=setTimeout(n,this.closeTimeout))},Polling.prototype.headers=function(e,t){t=t||{};var o=e.headers["user-agent"];return o&&(~o.indexOf(";MSIE")||~o.indexOf("Trident/"))&&(t["X-XSS-Protection"]="0"),this.emit("headers",t),t};
\ No newline at end of file
index 7d5511b..46b180b 100644 (file)
@@ -1,134 +1 @@
-
-/**
- * Module dependencies.
- */
-
-var Transport = require('../transport');
-var parser = require('engine.io-parser');
-var util = require('util');
-var debug = require('debug')('engine:ws');
-
-/**
- * Export the constructor.
- */
-
-module.exports = WebSocket;
-
-/**
- * WebSocket transport
- *
- * @param {http.IncomingMessage}
- * @api public
- */
-
-function WebSocket (req) {
-  Transport.call(this, req);
-  var self = this;
-  this.socket = req.websocket;
-  this.socket.on('message', this.onData.bind(this));
-  this.socket.once('close', this.onClose.bind(this));
-  this.socket.on('error', this.onError.bind(this));
-  this.socket.on('headers', onHeaders);
-  this.writable = true;
-  this.perMessageDeflate = null;
-
-  function onHeaders (headers) {
-    self.emit('headers', headers);
-  }
-}
-
-/**
- * Inherits from Transport.
- */
-
-util.inherits(WebSocket, Transport);
-
-/**
- * Transport name
- *
- * @api public
- */
-
-WebSocket.prototype.name = 'websocket';
-
-/**
- * Advertise upgrade support.
- *
- * @api public
- */
-
-WebSocket.prototype.handlesUpgrades = true;
-
-/**
- * Advertise framing support.
- *
- * @api public
- */
-
-WebSocket.prototype.supportsFraming = true;
-
-/**
- * Processes the incoming data.
- *
- * @param {String} encoded packet
- * @api private
- */
-
-WebSocket.prototype.onData = function (data) {
-  debug('received "%s"', data);
-  Transport.prototype.onData.call(this, data);
-};
-
-/**
- * Writes a packet payload.
- *
- * @param {Array} packets
- * @api private
- */
-
-WebSocket.prototype.send = function (packets) {
-  var self = this;
-
-  for (var i = 0; i < packets.length; i++) {
-    var packet = packets[i];
-    parser.encodePacket(packet, self.supportsBinary, send);
-  }
-
-  function send (data) {
-    debug('writing "%s"', data);
-
-    // always creates a new object since ws modifies it
-    var opts = {};
-    if (packet.options) {
-      opts.compress = packet.options.compress;
-    }
-
-    if (self.perMessageDeflate) {
-      var len = 'string' === typeof data ? Buffer.byteLength(data) : data.length;
-      if (len < self.perMessageDeflate.threshold) {
-        opts.compress = false;
-      }
-    }
-
-    self.writable = false;
-    self.socket.send(data, opts, onEnd);
-  }
-
-  function onEnd (err) {
-    if (err) return self.onError('write error', err.stack);
-    self.writable = true;
-    self.emit('drain');
-  }
-};
-
-/**
- * Closes the transport.
- *
- * @api private
- */
-
-WebSocket.prototype.doClose = function (fn) {
-  debug('closing');
-  this.socket.close();
-  fn && fn();
-};
+var Transport=require("../transport"),parser=require("engine.io-parser"),util=require("util"),debug=require("debug")("engine:ws");function WebSocket(e){Transport.call(this,e);var t=this;this.socket=e.websocket,this.socket.on("message",this.onData.bind(this)),this.socket.once("close",this.onClose.bind(this)),this.socket.on("error",this.onError.bind(this)),this.socket.on("headers",(function(e){t.emit("headers",e)})),this.writable=!0,this.perMessageDeflate=null}module.exports=WebSocket,util.inherits(WebSocket,Transport),WebSocket.prototype.name="websocket",WebSocket.prototype.handlesUpgrades=!0,WebSocket.prototype.supportsFraming=!0,WebSocket.prototype.onData=function(e){debug('received "%s"',e),Transport.prototype.onData.call(this,e)},WebSocket.prototype.send=function(e){for(var t=this,o=0;o<e.length;o++){var r=e[o];parser.encodePacket(r,t.supportsBinary,s)}function s(e){debug('writing "%s"',e);var o={};(r.options&&(o.compress=r.options.compress),t.perMessageDeflate)&&(("string"==typeof e?Buffer.byteLength(e):e.length)<t.perMessageDeflate.threshold&&(o.compress=!1));t.writable=!1,t.socket.send(e,o,i)}function i(e){if(e)return t.onError("write error",e.stack);t.writable=!0,t.emit("drain")}},WebSocket.prototype.doClose=function(e){debug("closing"),this.socket.close(),e&&e()};
\ No newline at end of file
index 15afe74..0a99687 100644 (file)
@@ -1,103 +1,4 @@
 /*!
  * base64id v0.1.0
  */
-
-/**
- * Module dependencies
- */
-
-var crypto = require('crypto');
-
-/**
- * Constructor
- */
-
-var Base64Id = function() { };
-
-/**
- * Get random bytes
- *
- * Uses a buffer if available, falls back to crypto.randomBytes
- */
-
-Base64Id.prototype.getRandomBytes = function(bytes) {
-
-  var BUFFER_SIZE = 4096
-  var self = this;  
-  
-  bytes = bytes || 12;
-
-  if (bytes > BUFFER_SIZE) {
-    return crypto.randomBytes(bytes);
-  }
-  
-  var bytesInBuffer = parseInt(BUFFER_SIZE/bytes);
-  var threshold = parseInt(bytesInBuffer*0.85);
-
-  if (!threshold) {
-    return crypto.randomBytes(bytes);
-  }
-
-  if (this.bytesBufferIndex == null) {
-     this.bytesBufferIndex = -1;
-  }
-
-  if (this.bytesBufferIndex == bytesInBuffer) {
-    this.bytesBuffer = null;
-    this.bytesBufferIndex = -1;
-  }
-
-  // No buffered bytes available or index above threshold
-  if (this.bytesBufferIndex == -1 || this.bytesBufferIndex > threshold) {
-     
-    if (!this.isGeneratingBytes) {
-      this.isGeneratingBytes = true;
-      crypto.randomBytes(BUFFER_SIZE, function(err, bytes) {
-        self.bytesBuffer = bytes;
-        self.bytesBufferIndex = 0;
-        self.isGeneratingBytes = false;
-      }); 
-    }
-    
-    // Fall back to sync call when no buffered bytes are available
-    if (this.bytesBufferIndex == -1) {
-      return crypto.randomBytes(bytes);
-    }
-  }
-  
-  var result = this.bytesBuffer.slice(bytes*this.bytesBufferIndex, bytes*(this.bytesBufferIndex+1)); 
-  this.bytesBufferIndex++; 
-  
-  return result;
-}
-
-/**
- * Generates a base64 id
- *
- * (Original version from socket.io <http://socket.io>)
- */
-
-Base64Id.prototype.generateId = function () {
-  var rand = Buffer.alloc(15); // multiple of 3 for base64
-  if (!rand.writeInt32BE) {
-    return Math.abs(Math.random() * Math.random() * Date.now() | 0).toString()
-      + Math.abs(Math.random() * Math.random() * Date.now() | 0).toString();
-  }
-  this.sequenceNumber = (this.sequenceNumber + 1) | 0;
-  rand.writeInt32BE(this.sequenceNumber, 11);
-  if (crypto.randomBytes) {
-    this.getRandomBytes(12).copy(rand);
-  } else {
-    // not secure for node 0.4
-    [0, 4, 8].forEach(function(i) {
-      rand.writeInt32BE(Math.random() * Math.pow(2, 32) | 0, i);
-    });
-  }
-  return rand.toString('base64').replace(/\//g, '_').replace(/\+/g, '-');
-};
-
-/**
- * Export
- */
-
-exports = module.exports = new Base64Id();
+var crypto=require("crypto"),Base64Id=function(){};Base64Id.prototype.getRandomBytes=function(e){var t=4096,r=this;if((e=e||12)>t)return crypto.randomBytes(e);var n=parseInt(t/e),s=parseInt(.85*n);if(!s)return crypto.randomBytes(e);if(null==this.bytesBufferIndex&&(this.bytesBufferIndex=-1),this.bytesBufferIndex==n&&(this.bytesBuffer=null,this.bytesBufferIndex=-1),(-1==this.bytesBufferIndex||this.bytesBufferIndex>s)&&(this.isGeneratingBytes||(this.isGeneratingBytes=!0,crypto.randomBytes(t,(function(e,t){r.bytesBuffer=t,r.bytesBufferIndex=0,r.isGeneratingBytes=!1}))),-1==this.bytesBufferIndex))return crypto.randomBytes(e);var a=this.bytesBuffer.slice(e*this.bytesBufferIndex,e*(this.bytesBufferIndex+1));return this.bytesBufferIndex++,a},Base64Id.prototype.generateId=function(){var e=Buffer.alloc(15);return e.writeInt32BE?(this.sequenceNumber=this.sequenceNumber+1|0,e.writeInt32BE(this.sequenceNumber,11),crypto.randomBytes?this.getRandomBytes(12).copy(e):[0,4,8].forEach((function(t){e.writeInt32BE(Math.random()*Math.pow(2,32)|0,t)})),e.toString("base64").replace(/\//g,"_").replace(/\+/g,"-")):Math.abs(Math.random()*Math.random()*Date.now()|0).toString()+Math.abs(Math.random()*Math.random()*Date.now()|0).toString()},exports=module.exports=new Base64Id;
\ No newline at end of file
index bf9e226..5a36d48 100644 (file)
@@ -5,74 +5,4 @@
  * Copyright(c) 2015 Tiancheng "Timothy" Gu
  * MIT Licensed
  */
-
-'use strict';
-
-/**
- * Module variables.
- * @private
- */
-
-var matchHtmlRegExp = /["'&<>]/;
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = escapeHtml;
-
-/**
- * Escape special characters in the given string of html.
- *
- * @param  {string} string The string to escape for inserting into HTML
- * @return {string}
- * @public
- */
-
-function escapeHtml(string) {
-  var str = '' + string;
-  var match = matchHtmlRegExp.exec(str);
-
-  if (!match) {
-    return str;
-  }
-
-  var escape;
-  var html = '';
-  var index = 0;
-  var lastIndex = 0;
-
-  for (index = match.index; index < str.length; index++) {
-    switch (str.charCodeAt(index)) {
-      case 34: // "
-        escape = '&quot;';
-        break;
-      case 38: // &
-        escape = '&amp;';
-        break;
-      case 39: // '
-        escape = '&#39;';
-        break;
-      case 60: // <
-        escape = '&lt;';
-        break;
-      case 62: // >
-        escape = '&gt;';
-        break;
-      default:
-        continue;
-    }
-
-    if (lastIndex !== index) {
-      html += str.substring(lastIndex, index);
-    }
-
-    lastIndex = index + 1;
-    html += escape;
-  }
-
-  return lastIndex !== index
-    ? html + str.substring(lastIndex, index)
-    : html;
-}
+"use strict";var matchHtmlRegExp=/["'&<>]/;function escapeHtml(e){var t,a=""+e,r=matchHtmlRegExp.exec(a);if(!r)return a;var c="",s=0,n=0;for(s=r.index;s<a.length;s++){switch(a.charCodeAt(s)){case 34:t="&quot;";break;case 38:t="&amp;";break;case 39:t="&#39;";break;case 60:t="&lt;";break;case 62:t="&gt;";break;default:continue}n!==s&&(c+=a.substring(n,s)),n=s+1,c+=t}return n!==s?c+a.substring(n,s):c}module.exports=escapeHtml;
\ No newline at end of file
index 7834bf9..9d3ff49 100755 (executable)
@@ -1,11 +1 @@
-'use strict';
-
-var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
-
-module.exports = function (str) {
-       if (typeof str !== 'string') {
-               throw new TypeError('Expected a string');
-       }
-
-       return str.replace(matchOperatorsRe, '\\$&');
-};
+"use strict";var matchOperatorsRe=/[|\\{}()[\]^$+*?.]/g;module.exports=function(r){if("string"!=typeof r)throw new TypeError("Expected a string");return r.replace(matchOperatorsRe,"\\$&")};
\ No newline at end of file
index 2a585c9..666a310 100644 (file)
@@ -3,129 +3,4 @@
  * Copyright(c) 2014-2016 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = etag
-
-/**
- * Module dependencies.
- * @private
- */
-
-var crypto = require('crypto')
-var Stats = require('fs').Stats
-
-/**
- * Module variables.
- * @private
- */
-
-var toString = Object.prototype.toString
-
-/**
- * Generate an entity tag.
- *
- * @param {Buffer|string} entity
- * @return {string}
- * @private
- */
-
-function entitytag (entity) {
-  if (entity.length === 0) {
-    // fast-path empty
-    return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"'
-  }
-
-  // compute hash of entity
-  var hash = crypto
-    .createHash('sha1')
-    .update(entity, 'utf8')
-    .digest('base64')
-    .substring(0, 27)
-
-  // compute length of entity
-  var len = typeof entity === 'string'
-    ? Buffer.byteLength(entity, 'utf8')
-    : entity.length
-
-  return '"' + len.toString(16) + '-' + hash + '"'
-}
-
-/**
- * Create a simple ETag.
- *
- * @param {string|Buffer|Stats} entity
- * @param {object} [options]
- * @param {boolean} [options.weak]
- * @return {String}
- * @public
- */
-
-function etag (entity, options) {
-  if (entity == null) {
-    throw new TypeError('argument entity is required')
-  }
-
-  // support fs.Stats object
-  var isStats = isstats(entity)
-  var weak = options && typeof options.weak === 'boolean'
-    ? options.weak
-    : isStats
-
-  // validate argument
-  if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) {
-    throw new TypeError('argument entity must be string, Buffer, or fs.Stats')
-  }
-
-  // generate entity tag
-  var tag = isStats
-    ? stattag(entity)
-    : entitytag(entity)
-
-  return weak
-    ? 'W/' + tag
-    : tag
-}
-
-/**
- * Determine if object is a Stats object.
- *
- * @param {object} obj
- * @return {boolean}
- * @api private
- */
-
-function isstats (obj) {
-  // genuine fs.Stats
-  if (typeof Stats === 'function' && obj instanceof Stats) {
-    return true
-  }
-
-  // quack quack
-  return obj && typeof obj === 'object' &&
-    'ctime' in obj && toString.call(obj.ctime) === '[object Date]' &&
-    'mtime' in obj && toString.call(obj.mtime) === '[object Date]' &&
-    'ino' in obj && typeof obj.ino === 'number' &&
-    'size' in obj && typeof obj.size === 'number'
-}
-
-/**
- * Generate a tag for a stat.
- *
- * @param {object} stat
- * @return {string}
- * @private
- */
-
-function stattag (stat) {
-  var mtime = stat.mtime.getTime().toString(16)
-  var size = stat.size.toString(16)
-
-  return '"' + size + '-' + mtime + '"'
-}
+"use strict";module.exports=etag;var crypto=require("crypto"),Stats=require("fs").Stats,toString=Object.prototype.toString;function entitytag(t){if(0===t.length)return'"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"';var e=crypto.createHash("sha1").update(t,"utf8").digest("base64").substring(0,27);return'"'+("string"==typeof t?Buffer.byteLength(t,"utf8"):t.length).toString(16)+"-"+e+'"'}function etag(t,e){if(null==t)throw new TypeError("argument entity is required");var r=isstats(t),n=e&&"boolean"==typeof e.weak?e.weak:r;if(!r&&"string"!=typeof t&&!Buffer.isBuffer(t))throw new TypeError("argument entity must be string, Buffer, or fs.Stats");var i=r?stattag(t):entitytag(t);return n?"W/"+i:i}function isstats(t){return"function"==typeof Stats&&t instanceof Stats||t&&"object"==typeof t&&"ctime"in t&&"[object Date]"===toString.call(t.ctime)&&"mtime"in t&&"[object Date]"===toString.call(t.mtime)&&"ino"in t&&"number"==typeof t.ino&&"size"in t&&"number"==typeof t.size}function stattag(t){var e=t.mtime.getTime().toString(16);return'"'+t.size.toString(16)+"-"+e+'"'}
\ No newline at end of file
index 9615346..a819df7 100755 (executable)
@@ -5,677 +5,4 @@
  * Copyright(c) 2014-2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict';
-
-/**
- * Module dependencies.
- * @private
- */
-
-var Buffer = require('safe-buffer').Buffer
-var cookie = require('cookie');
-var crypto = require('crypto')
-var debug = require('debug')('express-session');
-var deprecate = require('depd')('express-session');
-var onHeaders = require('on-headers')
-var parseUrl = require('parseurl');
-var signature = require('cookie-signature')
-var uid = require('uid-safe').sync
-
-var Cookie = require('./session/cookie')
-var MemoryStore = require('./session/memory')
-var Session = require('./session/session')
-var Store = require('./session/store')
-
-// environment
-
-var env = process.env.NODE_ENV;
-
-/**
- * Expose the middleware.
- */
-
-exports = module.exports = session;
-
-/**
- * Expose constructors.
- */
-
-exports.Store = Store;
-exports.Cookie = Cookie;
-exports.Session = Session;
-exports.MemoryStore = MemoryStore;
-
-/**
- * Warning message for `MemoryStore` usage in production.
- * @private
- */
-
-var warning = 'Warning: connect.session() MemoryStore is not\n'
-  + 'designed for a production environment, as it will leak\n'
-  + 'memory, and will not scale past a single process.';
-
-/**
- * Node.js 0.8+ async implementation.
- * @private
- */
-
-/* istanbul ignore next */
-var defer = typeof setImmediate === 'function'
-  ? setImmediate
-  : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) }
-
-/**
- * Setup session store with the given `options`.
- *
- * @param {Object} [options]
- * @param {Object} [options.cookie] Options for cookie
- * @param {Function} [options.genid]
- * @param {String} [options.name=connect.sid] Session ID cookie name
- * @param {Boolean} [options.proxy]
- * @param {Boolean} [options.resave] Resave unmodified sessions back to the store
- * @param {Boolean} [options.rolling] Enable/disable rolling session expiration
- * @param {Boolean} [options.saveUninitialized] Save uninitialized sessions to the store
- * @param {String|Array} [options.secret] Secret for signing session ID
- * @param {Object} [options.store=MemoryStore] Session store
- * @param {String} [options.unset]
- * @return {Function} middleware
- * @public
- */
-
-function session(options) {
-  var opts = options || {}
-
-  // get the cookie options
-  var cookieOptions = opts.cookie || {}
-
-  // get the session id generate function
-  var generateId = opts.genid || generateSessionId
-
-  // get the session cookie name
-  var name = opts.name || opts.key || 'connect.sid'
-
-  // get the session store
-  var store = opts.store || new MemoryStore()
-
-  // get the trust proxy setting
-  var trustProxy = opts.proxy
-
-  // get the resave session option
-  var resaveSession = opts.resave;
-
-  // get the rolling session option
-  var rollingSessions = Boolean(opts.rolling)
-
-  // get the save uninitialized session option
-  var saveUninitializedSession = opts.saveUninitialized
-
-  // get the cookie signing secret
-  var secret = opts.secret
-
-  if (typeof generateId !== 'function') {
-    throw new TypeError('genid option must be a function');
-  }
-
-  if (resaveSession === undefined) {
-    deprecate('undefined resave option; provide resave option');
-    resaveSession = true;
-  }
-
-  if (saveUninitializedSession === undefined) {
-    deprecate('undefined saveUninitialized option; provide saveUninitialized option');
-    saveUninitializedSession = true;
-  }
-
-  if (opts.unset && opts.unset !== 'destroy' && opts.unset !== 'keep') {
-    throw new TypeError('unset option must be "destroy" or "keep"');
-  }
-
-  // TODO: switch to "destroy" on next major
-  var unsetDestroy = opts.unset === 'destroy'
-
-  if (Array.isArray(secret) && secret.length === 0) {
-    throw new TypeError('secret option array must contain one or more strings');
-  }
-
-  if (secret && !Array.isArray(secret)) {
-    secret = [secret];
-  }
-
-  if (!secret) {
-    deprecate('req.secret; provide secret option');
-  }
-
-  // notify user that this store is not
-  // meant for a production environment
-  /* istanbul ignore next: not tested */
-  if (env === 'production' && store instanceof MemoryStore) {
-    console.warn(warning);
-  }
-
-  // generates the new session
-  store.generate = function(req){
-    req.sessionID = generateId(req);
-    req.session = new Session(req);
-    req.session.cookie = new Cookie(cookieOptions);
-
-    if (cookieOptions.secure === 'auto') {
-      req.session.cookie.secure = issecure(req, trustProxy);
-    }
-  };
-
-  var storeImplementsTouch = typeof store.touch === 'function';
-
-  // register event listeners for the store to track readiness
-  var storeReady = true
-  store.on('disconnect', function ondisconnect() {
-    storeReady = false
-  })
-  store.on('connect', function onconnect() {
-    storeReady = true
-  })
-
-  return function session(req, res, next) {
-    // self-awareness
-    if (req.session) {
-      next()
-      return
-    }
-
-    // Handle connection as if there is no session if
-    // the store has temporarily disconnected etc
-    if (!storeReady) {
-      debug('store is disconnected')
-      next()
-      return
-    }
-
-    // pathname mismatch
-    var originalPath = parseUrl.original(req).pathname || '/'
-    if (originalPath.indexOf(cookieOptions.path || '/') !== 0) return next();
-
-    // ensure a secret is available or bail
-    if (!secret && !req.secret) {
-      next(new Error('secret option required for sessions'));
-      return;
-    }
-
-    // backwards compatibility for signed cookies
-    // req.secret is passed from the cookie parser middleware
-    var secrets = secret || [req.secret];
-
-    var originalHash;
-    var originalId;
-    var savedHash;
-    var touched = false
-
-    // expose store
-    req.sessionStore = store;
-
-    // get the session ID from the cookie
-    var cookieId = req.sessionID = getcookie(req, name, secrets);
-
-    // set-cookie
-    onHeaders(res, function(){
-      if (!req.session) {
-        debug('no session');
-        return;
-      }
-
-      if (!shouldSetCookie(req)) {
-        return;
-      }
-
-      // only send secure cookies via https
-      if (req.session.cookie.secure && !issecure(req, trustProxy)) {
-        debug('not secured');
-        return;
-      }
-
-      if (!touched) {
-        // touch session
-        req.session.touch()
-        touched = true
-      }
-
-      // set cookie
-      setcookie(res, name, req.sessionID, secrets[0], req.session.cookie.data);
-    });
-
-    // proxy end() to commit the session
-    var _end = res.end;
-    var _write = res.write;
-    var ended = false;
-    res.end = function end(chunk, encoding) {
-      if (ended) {
-        return false;
-      }
-
-      ended = true;
-
-      var ret;
-      var sync = true;
-
-      function writeend() {
-        if (sync) {
-          ret = _end.call(res, chunk, encoding);
-          sync = false;
-          return;
-        }
-
-        _end.call(res);
-      }
-
-      function writetop() {
-        if (!sync) {
-          return ret;
-        }
-
-        if (chunk == null) {
-          ret = true;
-          return ret;
-        }
-
-        var contentLength = Number(res.getHeader('Content-Length'));
-
-        if (!isNaN(contentLength) && contentLength > 0) {
-          // measure chunk
-          chunk = !Buffer.isBuffer(chunk)
-            ? Buffer.from(chunk, encoding)
-            : chunk;
-          encoding = undefined;
-
-          if (chunk.length !== 0) {
-            debug('split response');
-            ret = _write.call(res, chunk.slice(0, chunk.length - 1));
-            chunk = chunk.slice(chunk.length - 1, chunk.length);
-            return ret;
-          }
-        }
-
-        ret = _write.call(res, chunk, encoding);
-        sync = false;
-
-        return ret;
-      }
-
-      if (shouldDestroy(req)) {
-        // destroy session
-        debug('destroying');
-        store.destroy(req.sessionID, function ondestroy(err) {
-          if (err) {
-            defer(next, err);
-          }
-
-          debug('destroyed');
-          writeend();
-        });
-
-        return writetop();
-      }
-
-      // no session to save
-      if (!req.session) {
-        debug('no session');
-        return _end.call(res, chunk, encoding);
-      }
-
-      if (!touched) {
-        // touch session
-        req.session.touch()
-        touched = true
-      }
-
-      if (shouldSave(req)) {
-        req.session.save(function onsave(err) {
-          if (err) {
-            defer(next, err);
-          }
-
-          writeend();
-        });
-
-        return writetop();
-      } else if (storeImplementsTouch && shouldTouch(req)) {
-        // store implements touch method
-        debug('touching');
-        store.touch(req.sessionID, req.session, function ontouch(err) {
-          if (err) {
-            defer(next, err);
-          }
-
-          debug('touched');
-          writeend();
-        });
-
-        return writetop();
-      }
-
-      return _end.call(res, chunk, encoding);
-    };
-
-    // generate the session
-    function generate() {
-      store.generate(req);
-      originalId = req.sessionID;
-      originalHash = hash(req.session);
-      wrapmethods(req.session);
-    }
-
-    // inflate the session
-    function inflate (req, sess) {
-      store.createSession(req, sess)
-      originalId = req.sessionID
-      originalHash = hash(sess)
-
-      if (!resaveSession) {
-        savedHash = originalHash
-      }
-
-      wrapmethods(req.session)
-    }
-
-    function rewrapmethods (sess, callback) {
-      return function () {
-        if (req.session !== sess) {
-          wrapmethods(req.session)
-        }
-
-        callback.apply(this, arguments)
-      }
-    }
-
-    // wrap session methods
-    function wrapmethods(sess) {
-      var _reload = sess.reload
-      var _save = sess.save;
-
-      function reload(callback) {
-        debug('reloading %s', this.id)
-        _reload.call(this, rewrapmethods(this, callback))
-      }
-
-      function save() {
-        debug('saving %s', this.id);
-        savedHash = hash(this);
-        _save.apply(this, arguments);
-      }
-
-      Object.defineProperty(sess, 'reload', {
-        configurable: true,
-        enumerable: false,
-        value: reload,
-        writable: true
-      })
-
-      Object.defineProperty(sess, 'save', {
-        configurable: true,
-        enumerable: false,
-        value: save,
-        writable: true
-      });
-    }
-
-    // check if session has been modified
-    function isModified(sess) {
-      return originalId !== sess.id || originalHash !== hash(sess);
-    }
-
-    // check if session has been saved
-    function isSaved(sess) {
-      return originalId === sess.id && savedHash === hash(sess);
-    }
-
-    // determine if session should be destroyed
-    function shouldDestroy(req) {
-      return req.sessionID && unsetDestroy && req.session == null;
-    }
-
-    // determine if session should be saved to store
-    function shouldSave(req) {
-      // cannot set cookie without a session ID
-      if (typeof req.sessionID !== 'string') {
-        debug('session ignored because of bogus req.sessionID %o', req.sessionID);
-        return false;
-      }
-
-      return !saveUninitializedSession && cookieId !== req.sessionID
-        ? isModified(req.session)
-        : !isSaved(req.session)
-    }
-
-    // determine if session should be touched
-    function shouldTouch(req) {
-      // cannot set cookie without a session ID
-      if (typeof req.sessionID !== 'string') {
-        debug('session ignored because of bogus req.sessionID %o', req.sessionID);
-        return false;
-      }
-
-      return cookieId === req.sessionID && !shouldSave(req);
-    }
-
-    // determine if cookie should be set on response
-    function shouldSetCookie(req) {
-      // cannot set cookie without a session ID
-      if (typeof req.sessionID !== 'string') {
-        return false;
-      }
-
-      return cookieId !== req.sessionID
-        ? saveUninitializedSession || isModified(req.session)
-        : rollingSessions || req.session.cookie.expires != null && isModified(req.session);
-    }
-
-    // generate a session if the browser doesn't send a sessionID
-    if (!req.sessionID) {
-      debug('no SID sent, generating session');
-      generate();
-      next();
-      return;
-    }
-
-    // generate the session object
-    debug('fetching %s', req.sessionID);
-    store.get(req.sessionID, function(err, sess){
-      // error handling
-      if (err && err.code !== 'ENOENT') {
-        debug('error %j', err);
-        next(err)
-        return
-      }
-
-      try {
-        if (err || !sess) {
-          debug('no session found')
-          generate()
-        } else {
-          debug('session found')
-          inflate(req, sess)
-        }
-      } catch (e) {
-        next(e)
-        return
-      }
-
-      next()
-    });
-  };
-};
-
-/**
- * Generate a session ID for a new session.
- *
- * @return {String}
- * @private
- */
-
-function generateSessionId(sess) {
-  return uid(24);
-}
-
-/**
- * Get the session ID cookie from request.
- *
- * @return {string}
- * @private
- */
-
-function getcookie(req, name, secrets) {
-  var header = req.headers.cookie;
-  var raw;
-  var val;
-
-  // read from cookie header
-  if (header) {
-    var cookies = cookie.parse(header);
-
-    raw = cookies[name];
-
-    if (raw) {
-      if (raw.substr(0, 2) === 's:') {
-        val = unsigncookie(raw.slice(2), secrets);
-
-        if (val === false) {
-          debug('cookie signature invalid');
-          val = undefined;
-        }
-      } else {
-        debug('cookie unsigned')
-      }
-    }
-  }
-
-  // back-compat read from cookieParser() signedCookies data
-  if (!val && req.signedCookies) {
-    val = req.signedCookies[name];
-
-    if (val) {
-      deprecate('cookie should be available in req.headers.cookie');
-    }
-  }
-
-  // back-compat read from cookieParser() cookies data
-  if (!val && req.cookies) {
-    raw = req.cookies[name];
-
-    if (raw) {
-      if (raw.substr(0, 2) === 's:') {
-        val = unsigncookie(raw.slice(2), secrets);
-
-        if (val) {
-          deprecate('cookie should be available in req.headers.cookie');
-        }
-
-        if (val === false) {
-          debug('cookie signature invalid');
-          val = undefined;
-        }
-      } else {
-        debug('cookie unsigned')
-      }
-    }
-  }
-
-  return val;
-}
-
-/**
- * Hash the given `sess` object omitting changes to `.cookie`.
- *
- * @param {Object} sess
- * @return {String}
- * @private
- */
-
-function hash(sess) {
-  // serialize
-  var str = JSON.stringify(sess, function (key, val) {
-    // ignore sess.cookie property
-    if (this === sess && key === 'cookie') {
-      return
-    }
-
-    return val
-  })
-
-  // hash
-  return crypto
-    .createHash('sha1')
-    .update(str, 'utf8')
-    .digest('hex')
-}
-
-/**
- * Determine if request is secure.
- *
- * @param {Object} req
- * @param {Boolean} [trustProxy]
- * @return {Boolean}
- * @private
- */
-
-function issecure(req, trustProxy) {
-  // socket is https server
-  if (req.connection && req.connection.encrypted) {
-    return true;
-  }
-
-  // do not trust proxy
-  if (trustProxy === false) {
-    return false;
-  }
-
-  // no explicit trust; try req.secure from express
-  if (trustProxy !== true) {
-    return req.secure === true
-  }
-
-  // read the proto from x-forwarded-proto header
-  var header = req.headers['x-forwarded-proto'] || '';
-  var index = header.indexOf(',');
-  var proto = index !== -1
-    ? header.substr(0, index).toLowerCase().trim()
-    : header.toLowerCase().trim()
-
-  return proto === 'https';
-}
-
-/**
- * Set cookie on response.
- *
- * @private
- */
-
-function setcookie(res, name, val, secret, options) {
-  var signed = 's:' + signature.sign(val, secret);
-  var data = cookie.serialize(name, signed, options);
-
-  debug('set-cookie %s', data);
-
-  var prev = res.getHeader('Set-Cookie') || []
-  var header = Array.isArray(prev) ? prev.concat(data) : [prev, data];
-
-  res.setHeader('Set-Cookie', header)
-}
-
-/**
- * Verify and decode the given `val` with `secrets`.
- *
- * @param {String} val
- * @param {Array} secrets
- * @returns {String|Boolean}
- * @private
- */
-function unsigncookie(val, secrets) {
-  for (var i = 0; i < secrets.length; i++) {
-    var result = signature.unsign(val, secrets[i]);
-
-    if (result !== false) {
-      return result;
-    }
-  }
-
-  return false;
-}
+"use strict";var Buffer=require("safe-buffer").Buffer,cookie=require("cookie"),crypto=require("crypto"),debug=require("debug")("express-session"),deprecate=require("depd")("express-session"),onHeaders=require("on-headers"),parseUrl=require("parseurl"),signature=require("cookie-signature"),uid=require("uid-safe").sync,Cookie=require("./session/cookie"),MemoryStore=require("./session/memory"),Session=require("./session/session"),Store=require("./session/store"),env=process.env.NODE_ENV;exports=module.exports=session,exports.Store=Store,exports.Cookie=Cookie,exports.Session=Session,exports.MemoryStore=MemoryStore;var warning="Warning: connect.session() MemoryStore is not\ndesigned for a production environment, as it will leak\nmemory, and will not scale past a single process.",defer="function"==typeof setImmediate?setImmediate:function(e){process.nextTick(e.bind.apply(e,arguments))};function session(e){var s=e||{},o=s.cookie||{},n=s.genid||generateSessionId,i=s.name||s.key||"connect.sid",r=s.store||new MemoryStore,t=s.proxy,u=s.resave,c=Boolean(s.rolling),a=s.saveUninitialized,d=s.secret;if("function"!=typeof n)throw new TypeError("genid option must be a function");if(void 0===u&&(deprecate("undefined resave option; provide resave option"),u=!0),void 0===a&&(deprecate("undefined saveUninitialized option; provide saveUninitialized option"),a=!0),s.unset&&"destroy"!==s.unset&&"keep"!==s.unset)throw new TypeError('unset option must be "destroy" or "keep"');var f="destroy"===s.unset;if(Array.isArray(d)&&0===d.length)throw new TypeError("secret option array must contain one or more strings");d&&!Array.isArray(d)&&(d=[d]),d||deprecate("req.secret; provide secret option"),"production"===env&&r instanceof MemoryStore&&console.warn(warning),r.generate=function(e){e.sessionID=n(e),e.session=new Session(e),e.session.cookie=new Cookie(o),"auto"===o.secure&&(e.session.cookie.secure=issecure(e,t))};var g="function"==typeof r.touch,l=!0;return r.on("disconnect",(function(){l=!1})),r.on("connect",(function(){l=!0})),function(e,s,n){if(e.session)n();else{if(!l)return debug("store is disconnected"),void n();if(0!==(parseUrl.original(e).pathname||"/").indexOf(o.path||"/"))return n();if(d||e.secret){var p,v,h,b=d||[e.secret],k=!1;e.sessionStore=r;var y=e.sessionID=getcookie(e,i,b);onHeaders(s,(function(){e.session?function(e){if("string"!=typeof e.sessionID)return!1;return y!==e.sessionID?a||q(e.session):c||null!=e.session.cookie.expires&&q(e.session)}(e)&&(!e.session.cookie.secure||issecure(e,t)?(k||(e.session.touch(),k=!0),setcookie(s,i,e.sessionID,b[0],e.session.cookie.data)):debug("not secured")):debug("no session")}));var m=s.end,I=s.write,D=!1;if(s.end=function(o,i){if(D)return!1;var t;D=!0;var u=!0;function c(){if(u)return t=m.call(s,o,i),void(u=!1);m.call(s)}function a(){if(!u)return t;if(null==o)return t=!0;var e=Number(s.getHeader("Content-Length"));return!isNaN(e)&&e>0&&(o=Buffer.isBuffer(o)?o:Buffer.from(o,i),i=void 0,0!==o.length)?(debug("split response"),t=I.call(s,o.slice(0,o.length-1)),o=o.slice(o.length-1,o.length),t):(t=I.call(s,o,i),u=!1,t)}return function(e){return e.sessionID&&f&&null==e.session}(e)?(debug("destroying"),r.destroy(e.sessionID,(function(e){e&&defer(n,e),debug("destroyed"),c()})),a()):e.session?(k||(e.session.touch(),k=!0),x(e)?(e.session.save((function(e){e&&defer(n,e),c()})),a()):g&&function(e){if("string"!=typeof e.sessionID)return debug("session ignored because of bogus req.sessionID %o",e.sessionID),!1;return y===e.sessionID&&!x(e)}(e)?(debug("touching"),r.touch(e.sessionID,e.session,(function(e){e&&defer(n,e),debug("touched"),c()})),a()):m.call(s,o,i)):(debug("no session"),m.call(s,o,i))},!e.sessionID)return debug("no SID sent, generating session"),w(),void n();debug("fetching %s",e.sessionID),r.get(e.sessionID,(function(s,o){if(s&&"ENOENT"!==s.code)return debug("error %j",s),void n(s);try{s||!o?(debug("no session found"),w()):(debug("session found"),function(e,s){r.createSession(e,s),v=e.sessionID,p=hash(s),u||(h=p),S(e.session)}(e,o))}catch(e){return void n(e)}n()}))}else n(new Error("secret option required for sessions"))}function w(){r.generate(e),v=e.sessionID,p=hash(e.session),S(e.session)}function S(s){var o=s.reload,n=s.save;Object.defineProperty(s,"reload",{configurable:!0,enumerable:!1,value:function(s){debug("reloading %s",this.id),o.call(this,function(s,o){return function(){e.session!==s&&S(e.session),o.apply(this,arguments)}}(this,s))},writable:!0}),Object.defineProperty(s,"save",{configurable:!0,enumerable:!1,value:function(){debug("saving %s",this.id),h=hash(this),n.apply(this,arguments)},writable:!0})}function q(e){return v!==e.id||p!==hash(e)}function x(e){return"string"!=typeof e.sessionID?(debug("session ignored because of bogus req.sessionID %o",e.sessionID),!1):a||y===e.sessionID?(s=e.session,!(v===s.id&&h===hash(s))):q(e.session);var s}}}function generateSessionId(e){return uid(24)}function getcookie(e,s,o){var n,i,r=e.headers.cookie;r&&((n=cookie.parse(r)[s])&&("s:"===n.substr(0,2)?!1===(i=unsigncookie(n.slice(2),o))&&(debug("cookie signature invalid"),i=void 0):debug("cookie unsigned")));return!i&&e.signedCookies&&(i=e.signedCookies[s])&&deprecate("cookie should be available in req.headers.cookie"),!i&&e.cookies&&(n=e.cookies[s])&&("s:"===n.substr(0,2)?((i=unsigncookie(n.slice(2),o))&&deprecate("cookie should be available in req.headers.cookie"),!1===i&&(debug("cookie signature invalid"),i=void 0)):debug("cookie unsigned")),i}function hash(e){var s=JSON.stringify(e,(function(s,o){if(this!==e||"cookie"!==s)return o}));return crypto.createHash("sha1").update(s,"utf8").digest("hex")}function issecure(e,s){if(e.connection&&e.connection.encrypted)return!0;if(!1===s)return!1;if(!0!==s)return!0===e.secure;var o=e.headers["x-forwarded-proto"]||"",n=o.indexOf(",");return"https"===(-1!==n?o.substr(0,n).toLowerCase().trim():o.toLowerCase().trim())}function setcookie(e,s,o,n,i){var r="s:"+signature.sign(o,n),t=cookie.serialize(s,r,i);debug("set-cookie %s",t);var u=e.getHeader("Set-Cookie")||[],c=Array.isArray(u)?u.concat(t):[u,t];e.setHeader("Set-Cookie",c)}function unsigncookie(e,s){for(var o=0;o<s.length;o++){var n=signature.unsign(e,s[o]);if(!1!==n)return n}return!1}
\ No newline at end of file
index a8b4e57..b98627a 100755 (executable)
@@ -4,147 +4,8 @@
  * Copyright(c) 2011 TJ Holowaychuk
  * MIT Licensed
  */
-
-'use strict';
-
-/**
- * Module dependencies.
- */
-
-var cookie = require('cookie')
-var deprecate = require('depd')('express-session')
-
-/**
- * Initialize a new `Cookie` with the given `options`.
- *
- * @param {IncomingMessage} req
- * @param {Object} options
- * @api private
- */
-
-var Cookie = module.exports = function Cookie(options) {
-  this.path = '/';
-  this.maxAge = null;
-  this.httpOnly = true;
-
-  if (options) {
-    if (typeof options !== 'object') {
-      throw new TypeError('argument options must be a object')
-    }
-
-    for (var key in options) {
-      if (key !== 'data') {
-        this[key] = options[key]
-      }
-    }
-  }
-
-  if (this.originalMaxAge === undefined || this.originalMaxAge === null) {
-    this.originalMaxAge = this.maxAge
-  }
-};
-
+"use strict";var cookie=require("cookie"),deprecate=require("depd")("express-session"),Cookie=module.exports=function(e){if(this.path="/",this.maxAge=null,this.httpOnly=!0,e){if("object"!=typeof e)throw new TypeError("argument options must be a object");for(var t in e)"data"!==t&&(this[t]=e[t])}void 0!==this.originalMaxAge&&null!==this.originalMaxAge||(this.originalMaxAge=this.maxAge)};
 /*!
  * Prototype.
  */
-
-Cookie.prototype = {
-
-  /**
-   * Set expires `date`.
-   *
-   * @param {Date} date
-   * @api public
-   */
-
-  set expires(date) {
-    this._expires = date;
-    this.originalMaxAge = this.maxAge;
-  },
-
-  /**
-   * Get expires `date`.
-   *
-   * @return {Date}
-   * @api public
-   */
-
-  get expires() {
-    return this._expires;
-  },
-
-  /**
-   * Set expires via max-age in `ms`.
-   *
-   * @param {Number} ms
-   * @api public
-   */
-
-  set maxAge(ms) {
-    if (ms && typeof ms !== 'number' && !(ms instanceof Date)) {
-      throw new TypeError('maxAge must be a number or Date')
-    }
-
-    if (ms instanceof Date) {
-      deprecate('maxAge as Date; pass number of milliseconds instead')
-    }
-
-    this.expires = typeof ms === 'number'
-      ? new Date(Date.now() + ms)
-      : ms;
-  },
-
-  /**
-   * Get expires max-age in `ms`.
-   *
-   * @return {Number}
-   * @api public
-   */
-
-  get maxAge() {
-    return this.expires instanceof Date
-      ? this.expires.valueOf() - Date.now()
-      : this.expires;
-  },
-
-  /**
-   * Return cookie data object.
-   *
-   * @return {Object}
-   * @api private
-   */
-
-  get data() {
-    return {
-      originalMaxAge: this.originalMaxAge
-      , expires: this._expires
-      , secure: this.secure
-      , httpOnly: this.httpOnly
-      , domain: this.domain
-      , path: this.path
-      , sameSite: this.sameSite
-    }
-  },
-
-  /**
-   * Return a serialized cookie string.
-   *
-   * @return {String}
-   * @api public
-   */
-
-  serialize: function(name, val){
-    return cookie.serialize(name, val, this.data);
-  },
-
-  /**
-   * Return JSON representation of this cookie.
-   *
-   * @return {Object}
-   * @api private
-   */
-
-  toJSON: function(){
-    return this.data;
-  }
-};
+Cookie.prototype={set expires(e){this._expires=e,this.originalMaxAge=this.maxAge},get expires(){return this._expires},set maxAge(e){if(e&&"number"!=typeof e&&!(e instanceof Date))throw new TypeError("maxAge must be a number or Date");e instanceof Date&&deprecate("maxAge as Date; pass number of milliseconds instead"),this.expires="number"==typeof e?new Date(Date.now()+e):e},get maxAge(){return this.expires instanceof Date?this.expires.valueOf()-Date.now():this.expires},get data(){return{originalMaxAge:this.originalMaxAge,expires:this._expires,secure:this.secure,httpOnly:this.httpOnly,domain:this.domain,path:this.path,sameSite:this.sameSite}},serialize:function(e,t){return cookie.serialize(e,t,this.data)},toJSON:function(){return this.data}};
\ No newline at end of file
index 11ed686..05bdcf8 100755 (executable)
@@ -5,183 +5,4 @@
  * Copyright(c) 2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict';
-
-/**
- * Module dependencies.
- * @private
- */
-
-var Store = require('./store')
-var util = require('util')
-
-/**
- * Shim setImmediate for node.js < 0.10
- * @private
- */
-
-/* istanbul ignore next */
-var defer = typeof setImmediate === 'function'
-  ? setImmediate
-  : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) }
-
-/**
- * Module exports.
- */
-
-module.exports = MemoryStore
-
-/**
- * A session store in memory.
- * @public
- */
-
-function MemoryStore() {
-  Store.call(this)
-  this.sessions = Object.create(null)
-}
-
-/**
- * Inherit from Store.
- */
-
-util.inherits(MemoryStore, Store)
-
-/**
- * Get all active sessions.
- *
- * @param {function} callback
- * @public
- */
-
-MemoryStore.prototype.all = function all(callback) {
-  var sessionIds = Object.keys(this.sessions)
-  var sessions = Object.create(null)
-
-  for (var i = 0; i < sessionIds.length; i++) {
-    var sessionId = sessionIds[i]
-    var session = getSession.call(this, sessionId)
-
-    if (session) {
-      sessions[sessionId] = session;
-    }
-  }
-
-  callback && defer(callback, null, sessions)
-}
-
-/**
- * Clear all sessions.
- *
- * @param {function} callback
- * @public
- */
-
-MemoryStore.prototype.clear = function clear(callback) {
-  this.sessions = Object.create(null)
-  callback && defer(callback)
-}
-
-/**
- * Destroy the session associated with the given session ID.
- *
- * @param {string} sessionId
- * @public
- */
-
-MemoryStore.prototype.destroy = function destroy(sessionId, callback) {
-  delete this.sessions[sessionId]
-  callback && defer(callback)
-}
-
-/**
- * Fetch session by the given session ID.
- *
- * @param {string} sessionId
- * @param {function} callback
- * @public
- */
-
-MemoryStore.prototype.get = function get(sessionId, callback) {
-  defer(callback, null, getSession.call(this, sessionId))
-}
-
-/**
- * Commit the given session associated with the given sessionId to the store.
- *
- * @param {string} sessionId
- * @param {object} session
- * @param {function} callback
- * @public
- */
-
-MemoryStore.prototype.set = function set(sessionId, session, callback) {
-  this.sessions[sessionId] = JSON.stringify(session)
-  callback && defer(callback)
-}
-
-/**
- * Get number of active sessions.
- *
- * @param {function} callback
- * @public
- */
-
-MemoryStore.prototype.length = function length(callback) {
-  this.all(function (err, sessions) {
-    if (err) return callback(err)
-    callback(null, Object.keys(sessions).length)
-  })
-}
-
-/**
- * Touch the given session object associated with the given session ID.
- *
- * @param {string} sessionId
- * @param {object} session
- * @param {function} callback
- * @public
- */
-
-MemoryStore.prototype.touch = function touch(sessionId, session, callback) {
-  var currentSession = getSession.call(this, sessionId)
-
-  if (currentSession) {
-    // update expiration
-    currentSession.cookie = session.cookie
-    this.sessions[sessionId] = JSON.stringify(currentSession)
-  }
-
-  callback && defer(callback)
-}
-
-/**
- * Get session from the store.
- * @private
- */
-
-function getSession(sessionId) {
-  var sess = this.sessions[sessionId]
-
-  if (!sess) {
-    return
-  }
-
-  // parse
-  sess = JSON.parse(sess)
-
-  if (sess.cookie) {
-    var expires = typeof sess.cookie.expires === 'string'
-      ? new Date(sess.cookie.expires)
-      : sess.cookie.expires
-
-    // destroy expired session
-    if (expires && expires <= Date.now()) {
-      delete this.sessions[sessionId]
-      return
-    }
-  }
-
-  return sess
-}
+"use strict";var Store=require("./store"),util=require("util"),defer="function"==typeof setImmediate?setImmediate:function(e){process.nextTick(e.bind.apply(e,arguments))};function MemoryStore(){Store.call(this),this.sessions=Object.create(null)}function getSession(e){var t=this.sessions[e];if(t){if((t=JSON.parse(t)).cookie){var o="string"==typeof t.cookie.expires?new Date(t.cookie.expires):t.cookie.expires;if(o&&o<=Date.now())return void delete this.sessions[e]}return t}}module.exports=MemoryStore,util.inherits(MemoryStore,Store),MemoryStore.prototype.all=function(e){for(var t=Object.keys(this.sessions),o=Object.create(null),s=0;s<t.length;s++){var r=t[s],i=getSession.call(this,r);i&&(o[r]=i)}e&&defer(e,null,o)},MemoryStore.prototype.clear=function(e){this.sessions=Object.create(null),e&&defer(e)},MemoryStore.prototype.destroy=function(e,t){delete this.sessions[e],t&&defer(t)},MemoryStore.prototype.get=function(e,t){defer(t,null,getSession.call(this,e))},MemoryStore.prototype.set=function(e,t,o){this.sessions[e]=JSON.stringify(t),o&&defer(o)},MemoryStore.prototype.length=function(e){this.all((function(t,o){if(t)return e(t);e(null,Object.keys(o).length)}))},MemoryStore.prototype.touch=function(e,t,o){var s=getSession.call(this,e);s&&(s.cookie=t.cookie,this.sessions[e]=JSON.stringify(s)),o&&defer(o)};
\ No newline at end of file
index fee7608..3eb5409 100755 (executable)
@@ -4,140 +4,4 @@
  * Copyright(c) 2011 TJ Holowaychuk
  * MIT Licensed
  */
-
-'use strict';
-
-/**
- * Expose Session.
- */
-
-module.exports = Session;
-
-/**
- * Create a new `Session` with the given request and `data`.
- *
- * @param {IncomingRequest} req
- * @param {Object} data
- * @api private
- */
-
-function Session(req, data) {
-  Object.defineProperty(this, 'req', { value: req });
-  Object.defineProperty(this, 'id', { value: req.sessionID });
-
-  if (typeof data === 'object' && data !== null) {
-    // merge data into this, ignoring prototype properties
-    for (var prop in data) {
-      if (!(prop in this)) {
-        this[prop] = data[prop]
-      }
-    }
-  }
-}
-
-/**
- * Update reset `.cookie.maxAge` to prevent
- * the cookie from expiring when the
- * session is still active.
- *
- * @return {Session} for chaining
- * @api public
- */
-
-defineMethod(Session.prototype, 'touch', function touch() {
-  return this.resetMaxAge();
-});
-
-/**
- * Reset `.maxAge` to `.originalMaxAge`.
- *
- * @return {Session} for chaining
- * @api public
- */
-
-defineMethod(Session.prototype, 'resetMaxAge', function resetMaxAge() {
-  this.cookie.maxAge = this.cookie.originalMaxAge;
-  return this;
-});
-
-/**
- * Save the session data with optional callback `fn(err)`.
- *
- * @param {Function} fn
- * @return {Session} for chaining
- * @api public
- */
-
-defineMethod(Session.prototype, 'save', function save(fn) {
-  this.req.sessionStore.set(this.id, this, fn || function(){});
-  return this;
-});
-
-/**
- * Re-loads the session data _without_ altering
- * the maxAge properties. Invokes the callback `fn(err)`,
- * after which time if no exception has occurred the
- * `req.session` property will be a new `Session` object,
- * although representing the same session.
- *
- * @param {Function} fn
- * @return {Session} for chaining
- * @api public
- */
-
-defineMethod(Session.prototype, 'reload', function reload(fn) {
-  var req = this.req
-  var store = this.req.sessionStore
-
-  store.get(this.id, function(err, sess){
-    if (err) return fn(err);
-    if (!sess) return fn(new Error('failed to load session'));
-    store.createSession(req, sess);
-    fn();
-  });
-  return this;
-});
-
-/**
- * Destroy `this` session.
- *
- * @param {Function} fn
- * @return {Session} for chaining
- * @api public
- */
-
-defineMethod(Session.prototype, 'destroy', function destroy(fn) {
-  delete this.req.session;
-  this.req.sessionStore.destroy(this.id, fn);
-  return this;
-});
-
-/**
- * Regenerate this request's session.
- *
- * @param {Function} fn
- * @return {Session} for chaining
- * @api public
- */
-
-defineMethod(Session.prototype, 'regenerate', function regenerate(fn) {
-  this.req.sessionStore.regenerate(this.req, fn);
-  return this;
-});
-
-/**
- * Helper function for creating a method on a prototype.
- *
- * @param {Object} obj
- * @param {String} name
- * @param {Function} fn
- * @private
- */
-function defineMethod(obj, name, fn) {
-  Object.defineProperty(obj, name, {
-    configurable: true,
-    enumerable: false,
-    value: fn,
-    writable: true
-  });
-};
+"use strict";function Session(e,t){if(Object.defineProperty(this,"req",{value:e}),Object.defineProperty(this,"id",{value:e.sessionID}),"object"==typeof t&&null!==t)for(var i in t)i in this||(this[i]=t[i])}function defineMethod(e,t,i){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,value:i,writable:!0})}module.exports=Session,defineMethod(Session.prototype,"touch",(function(){return this.resetMaxAge()})),defineMethod(Session.prototype,"resetMaxAge",(function(){return this.cookie.maxAge=this.cookie.originalMaxAge,this})),defineMethod(Session.prototype,"save",(function(e){return this.req.sessionStore.set(this.id,this,e||function(){}),this})),defineMethod(Session.prototype,"reload",(function(e){var t=this.req,i=this.req.sessionStore;return i.get(this.id,(function(o,s){return o?e(o):s?(i.createSession(t,s),void e()):e(new Error("failed to load session"))})),this})),defineMethod(Session.prototype,"destroy",(function(e){return delete this.req.session,this.req.sessionStore.destroy(this.id,e),this})),defineMethod(Session.prototype,"regenerate",(function(e){return this.req.sessionStore.regenerate(this.req,e),this}));
\ No newline at end of file
index 3793877..48cb7fa 100755 (executable)
@@ -4,99 +4,4 @@
  * Copyright(c) 2011 TJ Holowaychuk
  * MIT Licensed
  */
-
-'use strict';
-
-/**
- * Module dependencies.
- * @private
- */
-
-var Cookie = require('./cookie')
-var EventEmitter = require('events').EventEmitter
-var Session = require('./session')
-var util = require('util')
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = Store
-
-/**
- * Abstract base class for session stores.
- * @public
- */
-
-function Store () {
-  EventEmitter.call(this)
-}
-
-/**
- * Inherit from EventEmitter.
- */
-
-util.inherits(Store, EventEmitter)
-
-/**
- * Re-generate the given requests's session.
- *
- * @param {IncomingRequest} req
- * @return {Function} fn
- * @api public
- */
-
-Store.prototype.regenerate = function(req, fn){
-  var self = this;
-  this.destroy(req.sessionID, function(err){
-    self.generate(req);
-    fn(err);
-  });
-};
-
-/**
- * Load a `Session` instance via the given `sid`
- * and invoke the callback `fn(err, sess)`.
- *
- * @param {String} sid
- * @param {Function} fn
- * @api public
- */
-
-Store.prototype.load = function(sid, fn){
-  var self = this;
-  this.get(sid, function(err, sess){
-    if (err) return fn(err);
-    if (!sess) return fn();
-    var req = { sessionID: sid, sessionStore: self };
-    fn(null, self.createSession(req, sess))
-  });
-};
-
-/**
- * Create session from JSON `sess` data.
- *
- * @param {IncomingRequest} req
- * @param {Object} sess
- * @return {Session}
- * @api private
- */
-
-Store.prototype.createSession = function(req, sess){
-  var expires = sess.cookie.expires
-  var originalMaxAge = sess.cookie.originalMaxAge
-
-  sess.cookie = new Cookie(sess.cookie);
-
-  if (typeof expires === 'string') {
-    // convert expires to a Date object
-    sess.cookie.expires = new Date(expires)
-  }
-
-  // keep originalMaxAge intact
-  sess.cookie.originalMaxAge = originalMaxAge
-
-  req.session = new Session(req, sess);
-  return req.session;
-};
+"use strict";var Cookie=require("./cookie"),EventEmitter=require("events").EventEmitter,Session=require("./session"),util=require("util");function Store(){EventEmitter.call(this)}module.exports=Store,util.inherits(Store,EventEmitter),Store.prototype.regenerate=function(e,t){var o=this;this.destroy(e.sessionID,(function(i){o.generate(e),t(i)}))},Store.prototype.load=function(e,t){var o=this;this.get(e,(function(i,r){if(i)return t(i);if(!r)return t();var n={sessionID:e,sessionStore:o};t(null,o.createSession(n,r))}))},Store.prototype.createSession=function(e,t){var o=t.cookie.expires,i=t.cookie.originalMaxAge;return t.cookie=new Cookie(t.cookie),"string"==typeof o&&(t.cookie.expires=new Date(o)),t.cookie.originalMaxAge=i,e.session=new Session(e,t),e.session};
\ No newline at end of file
index d219b0c..82f9595 100644 (file)
@@ -5,7 +5,4 @@
  * Copyright(c) 2014-2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict';
-
-module.exports = require('./lib/express');
+"use strict";module.exports=require("./lib/express");
\ No newline at end of file
index 91f77d2..d005c97 100644 (file)
@@ -5,640 +5,4 @@
  * Copyright(c) 2014-2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict';
-
-/**
- * Module dependencies.
- * @private
- */
-
-var finalhandler = require('finalhandler');
-var Router = require('./router');
-var methods = require('methods');
-var middleware = require('./middleware/init');
-var query = require('./middleware/query');
-var debug = require('debug')('express:application');
-var View = require('./view');
-var http = require('http');
-var compileETag = require('./utils').compileETag;
-var compileQueryParser = require('./utils').compileQueryParser;
-var compileTrust = require('./utils').compileTrust;
-var deprecate = require('depd')('express');
-var flatten = require('array-flatten');
-var merge = require('utils-merge');
-var resolve = require('path').resolve;
-var setPrototypeOf = require('setprototypeof')
-var slice = Array.prototype.slice;
-
-/**
- * Application prototype.
- */
-
-var app = exports = module.exports = {};
-
-/**
- * Variable for trust proxy inheritance back-compat
- * @private
- */
-
-var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default';
-
-/**
- * Initialize the server.
- *
- *   - setup default configuration
- *   - setup default middleware
- *   - setup route reflection methods
- *
- * @private
- */
-
-app.init = function init() {
-  this.cache = {};
-  this.engines = {};
-  this.settings = {};
-
-  this.defaultConfiguration();
-};
-
-/**
- * Initialize application configuration.
- * @private
- */
-
-app.defaultConfiguration = function defaultConfiguration() {
-  var env = process.env.NODE_ENV || 'development';
-
-  // default settings
-  this.enable('x-powered-by');
-  this.set('etag', 'weak');
-  this.set('env', env);
-  this.set('query parser', 'extended');
-  this.set('subdomain offset', 2);
-  this.set('trust proxy', false);
-
-  // trust proxy inherit back-compat
-  Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
-    configurable: true,
-    value: true
-  });
-
-  debug('booting in %s mode', env);
-
-  this.on('mount', function onmount(parent) {
-    // inherit trust proxy
-    if (this.settings[trustProxyDefaultSymbol] === true
-      && typeof parent.settings['trust proxy fn'] === 'function') {
-      delete this.settings['trust proxy'];
-      delete this.settings['trust proxy fn'];
-    }
-
-    // inherit protos
-    setPrototypeOf(this.request, parent.request)
-    setPrototypeOf(this.response, parent.response)
-    setPrototypeOf(this.engines, parent.engines)
-    setPrototypeOf(this.settings, parent.settings)
-  });
-
-  // setup locals
-  this.locals = Object.create(null);
-
-  // top-most app is mounted at /
-  this.mountpath = '/';
-
-  // default locals
-  this.locals.settings = this.settings;
-
-  // default configuration
-  this.set('view', View);
-  this.set('views', resolve('views'));
-  this.set('jsonp callback name', 'callback');
-
-  if (env === 'production') {
-    this.enable('view cache');
-  }
-
-  Object.defineProperty(this, 'router', {
-    get: function() {
-      throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.');
-    }
-  });
-};
-
-/**
- * lazily adds the base router if it has not yet been added.
- *
- * We cannot add the base router in the defaultConfiguration because
- * it reads app settings which might be set after that has run.
- *
- * @private
- */
-app.lazyrouter = function lazyrouter() {
-  if (!this._router) {
-    this._router = new Router({
-      caseSensitive: this.enabled('case sensitive routing'),
-      strict: this.enabled('strict routing')
-    });
-
-    this._router.use(query(this.get('query parser fn')));
-    this._router.use(middleware.init(this));
-  }
-};
-
-/**
- * Dispatch a req, res pair into the application. Starts pipeline processing.
- *
- * If no callback is provided, then default error handlers will respond
- * in the event of an error bubbling through the stack.
- *
- * @private
- */
-
-app.handle = function handle(req, res, callback) {
-  var router = this._router;
-
-  // final handler
-  var done = callback || finalhandler(req, res, {
-    env: this.get('env'),
-    onerror: logerror.bind(this)
-  });
-
-  // no routes
-  if (!router) {
-    debug('no routes defined on app');
-    done();
-    return;
-  }
-
-  router.handle(req, res, done);
-};
-
-/**
- * Proxy `Router#use()` to add middleware to the app router.
- * See Router#use() documentation for details.
- *
- * If the _fn_ parameter is an express app, then it will be
- * mounted at the _route_ specified.
- *
- * @public
- */
-
-app.use = function use(fn) {
-  var offset = 0;
-  var path = '/';
-
-  // default path to '/'
-  // disambiguate app.use([fn])
-  if (typeof fn !== 'function') {
-    var arg = fn;
-
-    while (Array.isArray(arg) && arg.length !== 0) {
-      arg = arg[0];
-    }
-
-    // first arg is the path
-    if (typeof arg !== 'function') {
-      offset = 1;
-      path = fn;
-    }
-  }
-
-  var fns = flatten(slice.call(arguments, offset));
-
-  if (fns.length === 0) {
-    throw new TypeError('app.use() requires a middleware function')
-  }
-
-  // setup router
-  this.lazyrouter();
-  var router = this._router;
-
-  fns.forEach(function (fn) {
-    // non-express app
-    if (!fn || !fn.handle || !fn.set) {
-      return router.use(path, fn);
-    }
-
-    debug('.use app under %s', path);
-    fn.mountpath = path;
-    fn.parent = this;
-
-    // restore .app property on req and res
-    router.use(path, function mounted_app(req, res, next) {
-      var orig = req.app;
-      fn.handle(req, res, function (err) {
-        setPrototypeOf(req, orig.request)
-        setPrototypeOf(res, orig.response)
-        next(err);
-      });
-    });
-
-    // mounted an app
-    fn.emit('mount', this);
-  }, this);
-
-  return this;
-};
-
-/**
- * Proxy to the app `Router#route()`
- * Returns a new `Route` instance for the _path_.
- *
- * Routes are isolated middleware stacks for specific paths.
- * See the Route api docs for details.
- *
- * @public
- */
-
-app.route = function route(path) {
-  this.lazyrouter();
-  return this._router.route(path);
-};
-
-/**
- * Register the given template engine callback `fn`
- * as `ext`.
- *
- * By default will `require()` the engine based on the
- * file extension. For example if you try to render
- * a "foo.ejs" file Express will invoke the following internally:
- *
- *     app.engine('ejs', require('ejs').__express);
- *
- * For engines that do not provide `.__express` out of the box,
- * or if you wish to "map" a different extension to the template engine
- * you may use this method. For example mapping the EJS template engine to
- * ".html" files:
- *
- *     app.engine('html', require('ejs').renderFile);
- *
- * In this case EJS provides a `.renderFile()` method with
- * the same signature that Express expects: `(path, options, callback)`,
- * though note that it aliases this method as `ejs.__express` internally
- * so if you're using ".ejs" extensions you dont need to do anything.
- *
- * Some template engines do not follow this convention, the
- * [Consolidate.js](https://github.com/tj/consolidate.js)
- * library was created to map all of node's popular template
- * engines to follow this convention, thus allowing them to
- * work seamlessly within Express.
- *
- * @param {String} ext
- * @param {Function} fn
- * @return {app} for chaining
- * @public
- */
-
-app.engine = function engine(ext, fn) {
-  if (typeof fn !== 'function') {
-    throw new Error('callback function required');
-  }
-
-  // get file extension
-  var extension = ext[0] !== '.'
-    ? '.' + ext
-    : ext;
-
-  // store engine
-  this.engines[extension] = fn;
-
-  return this;
-};
-
-/**
- * Proxy to `Router#param()` with one added api feature. The _name_ parameter
- * can be an array of names.
- *
- * See the Router#param() docs for more details.
- *
- * @param {String|Array} name
- * @param {Function} fn
- * @return {app} for chaining
- * @public
- */
-
-app.param = function param(name, fn) {
-  this.lazyrouter();
-
-  if (Array.isArray(name)) {
-    for (var i = 0; i < name.length; i++) {
-      this.param(name[i], fn);
-    }
-
-    return this;
-  }
-
-  this._router.param(name, fn);
-
-  return this;
-};
-
-/**
- * Assign `setting` to `val`, or return `setting`'s value.
- *
- *    app.set('foo', 'bar');
- *    app.set('foo');
- *    // => "bar"
- *
- * Mounted servers inherit their parent server's settings.
- *
- * @param {String} setting
- * @param {*} [val]
- * @return {Server} for chaining
- * @public
- */
-
-app.set = function set(setting, val) {
-  if (arguments.length === 1) {
-    // app.get(setting)
-    return this.settings[setting];
-  }
-
-  debug('set "%s" to %o', setting, val);
-
-  // set value
-  this.settings[setting] = val;
-
-  // trigger matched settings
-  switch (setting) {
-    case 'etag':
-      this.set('etag fn', compileETag(val));
-      break;
-    case 'query parser':
-      this.set('query parser fn', compileQueryParser(val));
-      break;
-    case 'trust proxy':
-      this.set('trust proxy fn', compileTrust(val));
-
-      // trust proxy inherit back-compat
-      Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
-        configurable: true,
-        value: false
-      });
-
-      break;
-  }
-
-  return this;
-};
-
-/**
- * Return the app's absolute pathname
- * based on the parent(s) that have
- * mounted it.
- *
- * For example if the application was
- * mounted as "/admin", which itself
- * was mounted as "/blog" then the
- * return value would be "/blog/admin".
- *
- * @return {String}
- * @private
- */
-
-app.path = function path() {
-  return this.parent
-    ? this.parent.path() + this.mountpath
-    : '';
-};
-
-/**
- * Check if `setting` is enabled (truthy).
- *
- *    app.enabled('foo')
- *    // => false
- *
- *    app.enable('foo')
- *    app.enabled('foo')
- *    // => true
- *
- * @param {String} setting
- * @return {Boolean}
- * @public
- */
-
-app.enabled = function enabled(setting) {
-  return Boolean(this.set(setting));
-};
-
-/**
- * Check if `setting` is disabled.
- *
- *    app.disabled('foo')
- *    // => true
- *
- *    app.enable('foo')
- *    app.disabled('foo')
- *    // => false
- *
- * @param {String} setting
- * @return {Boolean}
- * @public
- */
-
-app.disabled = function disabled(setting) {
-  return !this.set(setting);
-};
-
-/**
- * Enable `setting`.
- *
- * @param {String} setting
- * @return {app} for chaining
- * @public
- */
-
-app.enable = function enable(setting) {
-  return this.set(setting, true);
-};
-
-/**
- * Disable `setting`.
- *
- * @param {String} setting
- * @return {app} for chaining
- * @public
- */
-
-app.disable = function disable(setting) {
-  return this.set(setting, false);
-};
-
-/**
- * Delegate `.VERB(...)` calls to `router.VERB(...)`.
- */
-
-methods.forEach(function(method){
-  app[method] = function(path){
-    if (method === 'get' && arguments.length === 1) {
-      // app.get(setting)
-      return this.set(path);
-    }
-
-    this.lazyrouter();
-
-    var route = this._router.route(path);
-    route[method].apply(route, slice.call(arguments, 1));
-    return this;
-  };
-});
-
-/**
- * Special-cased "all" method, applying the given route `path`,
- * middleware, and callback to _every_ HTTP method.
- *
- * @param {String} path
- * @param {Function} ...
- * @return {app} for chaining
- * @public
- */
-
-app.all = function all(path) {
-  this.lazyrouter();
-
-  var route = this._router.route(path);
-  var args = slice.call(arguments, 1);
-
-  for (var i = 0; i < methods.length; i++) {
-    route[methods[i]].apply(route, args);
-  }
-
-  return this;
-};
-
-// del -> delete alias
-
-app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead');
-
-/**
- * Render the given view `name` name with `options`
- * and a callback accepting an error and the
- * rendered template string.
- *
- * Example:
- *
- *    app.render('email', { name: 'Tobi' }, function(err, html){
- *      // ...
- *    })
- *
- * @param {String} name
- * @param {Object|Function} options or fn
- * @param {Function} callback
- * @public
- */
-
-app.render = function render(name, options, callback) {
-  var cache = this.cache;
-  var done = callback;
-  var engines = this.engines;
-  var opts = options;
-  var renderOptions = {};
-  var view;
-
-  // support callback function as second arg
-  if (typeof options === 'function') {
-    done = options;
-    opts = {};
-  }
-
-  // merge app.locals
-  merge(renderOptions, this.locals);
-
-  // merge options._locals
-  if (opts._locals) {
-    merge(renderOptions, opts._locals);
-  }
-
-  // merge options
-  merge(renderOptions, opts);
-
-  // set .cache unless explicitly provided
-  if (renderOptions.cache == null) {
-    renderOptions.cache = this.enabled('view cache');
-  }
-
-  // primed cache
-  if (renderOptions.cache) {
-    view = cache[name];
-  }
-
-  // view
-  if (!view) {
-    var View = this.get('view');
-
-    view = new View(name, {
-      defaultEngine: this.get('view engine'),
-      root: this.get('views'),
-      engines: engines
-    });
-
-    if (!view.path) {
-      var dirs = Array.isArray(view.root) && view.root.length > 1
-        ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"'
-        : 'directory "' + view.root + '"'
-      var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);
-      err.view = view;
-      return done(err);
-    }
-
-    // prime the cache
-    if (renderOptions.cache) {
-      cache[name] = view;
-    }
-  }
-
-  // render
-  tryRender(view, renderOptions, done);
-};
-
-/**
- * Listen for connections.
- *
- * A node `http.Server` is returned, with this
- * application (which is a `Function`) as its
- * callback. If you wish to create both an HTTP
- * and HTTPS server you may do so with the "http"
- * and "https" modules as shown here:
- *
- *    var http = require('http')
- *      , https = require('https')
- *      , express = require('express')
- *      , app = express();
- *
- *    http.createServer(app).listen(80);
- *    https.createServer({ ... }, app).listen(443);
- *
- * @return {http.Server}
- * @public
- */
-
-app.listen = function listen() {
-  var server = http.createServer(this);
-  return server.listen.apply(server, arguments);
-};
-
-/**
- * Log error using console.error.
- *
- * @param {Error} err
- * @private
- */
-
-function logerror(err) {
-  /* istanbul ignore next */
-  if (this.get('env') !== 'test') console.error(err.stack || err.toString());
-}
-
-/**
- * Try rendering a view.
- * @private
- */
-
-function tryRender(view, options, callback) {
-  try {
-    view.render(options, callback);
-  } catch (err) {
-    callback(err);
-  }
-}
+"use strict";var finalhandler=require("finalhandler"),Router=require("./router"),methods=require("methods"),middleware=require("./middleware/init"),query=require("./middleware/query"),debug=require("debug")("express:application"),View=require("./view"),http=require("http"),compileETag=require("./utils").compileETag,compileQueryParser=require("./utils").compileQueryParser,compileTrust=require("./utils").compileTrust,deprecate=require("depd")("express"),flatten=require("array-flatten"),merge=require("utils-merge"),resolve=require("path").resolve,setPrototypeOf=require("setprototypeof"),slice=Array.prototype.slice,app=exports=module.exports={},trustProxyDefaultSymbol="@@symbol:trust_proxy_default";function logerror(e){"test"!==this.get("env")&&console.error(e.stack||e.toString())}function tryRender(e,t,r){try{e.render(t,r)}catch(e){r(e)}}app.init=function(){this.cache={},this.engines={},this.settings={},this.defaultConfiguration()},app.defaultConfiguration=function(){var e=process.env.NODE_ENV||"development";this.enable("x-powered-by"),this.set("etag","weak"),this.set("env",e),this.set("query parser","extended"),this.set("subdomain offset",2),this.set("trust proxy",!1),Object.defineProperty(this.settings,trustProxyDefaultSymbol,{configurable:!0,value:!0}),debug("booting in %s mode",e),this.on("mount",(function(e){!0===this.settings[trustProxyDefaultSymbol]&&"function"==typeof e.settings["trust proxy fn"]&&(delete this.settings["trust proxy"],delete this.settings["trust proxy fn"]),setPrototypeOf(this.request,e.request),setPrototypeOf(this.response,e.response),setPrototypeOf(this.engines,e.engines),setPrototypeOf(this.settings,e.settings)})),this.locals=Object.create(null),this.mountpath="/",this.locals.settings=this.settings,this.set("view",View),this.set("views",resolve("views")),this.set("jsonp callback name","callback"),"production"===e&&this.enable("view cache"),Object.defineProperty(this,"router",{get:function(){throw new Error("'app.router' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.")}})},app.lazyrouter=function(){this._router||(this._router=new Router({caseSensitive:this.enabled("case sensitive routing"),strict:this.enabled("strict routing")}),this._router.use(query(this.get("query parser fn"))),this._router.use(middleware.init(this)))},app.handle=function(e,t,r){var i=this._router,s=r||finalhandler(e,t,{env:this.get("env"),onerror:logerror.bind(this)});if(!i)return debug("no routes defined on app"),void s();i.handle(e,t,s)},app.use=function(e){var t=0,r="/";if("function"!=typeof e){for(var i=e;Array.isArray(i)&&0!==i.length;)i=i[0];"function"!=typeof i&&(t=1,r=e)}var s=flatten(slice.call(arguments,t));if(0===s.length)throw new TypeError("app.use() requires a middleware function");this.lazyrouter();var n=this._router;return s.forEach((function(e){if(!e||!e.handle||!e.set)return n.use(r,e);debug(".use app under %s",r),e.mountpath=r,e.parent=this,n.use(r,(function(t,r,i){var s=t.app;e.handle(t,r,(function(e){setPrototypeOf(t,s.request),setPrototypeOf(r,s.response),i(e)}))})),e.emit("mount",this)}),this),this},app.route=function(e){return this.lazyrouter(),this._router.route(e)},app.engine=function(e,t){if("function"!=typeof t)throw new Error("callback function required");var r="."!==e[0]?"."+e:e;return this.engines[r]=t,this},app.param=function(e,t){if(this.lazyrouter(),Array.isArray(e)){for(var r=0;r<e.length;r++)this.param(e[r],t);return this}return this._router.param(e,t),this},app.set=function(e,t){if(1===arguments.length)return this.settings[e];switch(debug('set "%s" to %o',e,t),this.settings[e]=t,e){case"etag":this.set("etag fn",compileETag(t));break;case"query parser":this.set("query parser fn",compileQueryParser(t));break;case"trust proxy":this.set("trust proxy fn",compileTrust(t)),Object.defineProperty(this.settings,trustProxyDefaultSymbol,{configurable:!0,value:!1})}return this},app.path=function(){return this.parent?this.parent.path()+this.mountpath:""},app.enabled=function(e){return Boolean(this.set(e))},app.disabled=function(e){return!this.set(e)},app.enable=function(e){return this.set(e,!0)},app.disable=function(e){return this.set(e,!1)},methods.forEach((function(e){app[e]=function(t){if("get"===e&&1===arguments.length)return this.set(t);this.lazyrouter();var r=this._router.route(t);return r[e].apply(r,slice.call(arguments,1)),this}})),app.all=function(e){this.lazyrouter();for(var t=this._router.route(e),r=slice.call(arguments,1),i=0;i<methods.length;i++)t[methods[i]].apply(t,r);return this},app.del=deprecate.function(app.delete,"app.del: Use app.delete instead"),app.render=function(e,t,r){var i,s=this.cache,n=r,o=this.engines,a=t,u={};if("function"==typeof t&&(n=t,a={}),merge(u,this.locals),a._locals&&merge(u,a._locals),merge(u,a),null==u.cache&&(u.cache=this.enabled("view cache")),u.cache&&(i=s[e]),!i){if(!(i=new(this.get("view"))(e,{defaultEngine:this.get("view engine"),root:this.get("views"),engines:o})).path){var p=Array.isArray(i.root)&&i.root.length>1?'directories "'+i.root.slice(0,-1).join('", "')+'" or "'+i.root[i.root.length-1]+'"':'directory "'+i.root+'"',h=new Error('Failed to lookup view "'+e+'" in views '+p);return h.view=i,n(h)}u.cache&&(s[e]=i)}tryRender(i,u,n)},app.listen=function(){var e=http.createServer(this);return e.listen.apply(e,arguments)};
\ No newline at end of file
index d188a16..412482d 100644 (file)
@@ -5,112 +5,4 @@
  * Copyright(c) 2014-2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict';
-
-/**
- * Module dependencies.
- */
-
-var bodyParser = require('body-parser')
-var EventEmitter = require('events').EventEmitter;
-var mixin = require('merge-descriptors');
-var proto = require('./application');
-var Route = require('./router/route');
-var Router = require('./router');
-var req = require('./request');
-var res = require('./response');
-
-/**
- * Expose `createApplication()`.
- */
-
-exports = module.exports = createApplication;
-
-/**
- * Create an express application.
- *
- * @return {Function}
- * @api public
- */
-
-function createApplication() {
-  var app = function(req, res, next) {
-    app.handle(req, res, next);
-  };
-
-  mixin(app, EventEmitter.prototype, false);
-  mixin(app, proto, false);
-
-  // expose the prototype that will get set on requests
-  app.request = Object.create(req, {
-    app: { configurable: true, enumerable: true, writable: true, value: app }
-  })
-
-  // expose the prototype that will get set on responses
-  app.response = Object.create(res, {
-    app: { configurable: true, enumerable: true, writable: true, value: app }
-  })
-
-  app.init();
-  return app;
-}
-
-/**
- * Expose the prototypes.
- */
-
-exports.application = proto;
-exports.request = req;
-exports.response = res;
-
-/**
- * Expose constructors.
- */
-
-exports.Route = Route;
-exports.Router = Router;
-
-/**
- * Expose middleware
- */
-
-exports.json = bodyParser.json
-exports.query = require('./middleware/query');
-exports.raw = bodyParser.raw
-exports.static = require('serve-static');
-exports.text = bodyParser.text
-exports.urlencoded = bodyParser.urlencoded
-
-/**
- * Replace removed middleware with an appropriate error message.
- */
-
-var removedMiddlewares = [
-  'bodyParser',
-  'compress',
-  'cookieSession',
-  'session',
-  'logger',
-  'cookieParser',
-  'favicon',
-  'responseTime',
-  'errorHandler',
-  'timeout',
-  'methodOverride',
-  'vhost',
-  'csrf',
-  'directory',
-  'limit',
-  'multipart',
-  'staticCache'
-]
-
-removedMiddlewares.forEach(function (name) {
-  Object.defineProperty(exports, name, {
-    get: function () {
-      throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.');
-    },
-    configurable: true
-  });
-});
+"use strict";var bodyParser=require("body-parser"),EventEmitter=require("events").EventEmitter,mixin=require("merge-descriptors"),proto=require("./application"),Route=require("./router/route"),Router=require("./router"),req=require("./request"),res=require("./response");function createApplication(){var e=function(r,t,o){e.handle(r,t,o)};return mixin(e,EventEmitter.prototype,!1),mixin(e,proto,!1),e.request=Object.create(req,{app:{configurable:!0,enumerable:!0,writable:!0,value:e}}),e.response=Object.create(res,{app:{configurable:!0,enumerable:!0,writable:!0,value:e}}),e.init(),e}exports=module.exports=createApplication,exports.application=proto,exports.request=req,exports.response=res,exports.Route=Route,exports.Router=Router,exports.json=bodyParser.json,exports.query=require("./middleware/query"),exports.raw=bodyParser.raw,exports.static=require("serve-static"),exports.text=bodyParser.text,exports.urlencoded=bodyParser.urlencoded;var removedMiddlewares=["bodyParser","compress","cookieSession","session","logger","cookieParser","favicon","responseTime","errorHandler","timeout","methodOverride","vhost","csrf","directory","limit","multipart","staticCache"];removedMiddlewares.forEach((function(e){Object.defineProperty(exports,e,{get:function(){throw new Error("Most middleware (like "+e+") is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.")},configurable:!0})}));
\ No newline at end of file
index dfd0427..7d3250e 100644 (file)
@@ -5,39 +5,4 @@
  * Copyright(c) 2014-2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict';
-
-/**
- * Module dependencies.
- * @private
- */
-
-var setPrototypeOf = require('setprototypeof')
-
-/**
- * Initialization middleware, exposing the
- * request and response to each other, as well
- * as defaulting the X-Powered-By header field.
- *
- * @param {Function} app
- * @return {Function}
- * @api private
- */
-
-exports.init = function(app){
-  return function expressInit(req, res, next){
-    if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express');
-    req.res = res;
-    res.req = req;
-    req.next = next;
-
-    setPrototypeOf(req, app.request)
-    setPrototypeOf(res, app.response)
-
-    res.locals = res.locals || Object.create(null);
-
-    next();
-  };
-};
-
+"use strict";var setPrototypeOf=require("setprototypeof");exports.init=function(e){return function(t,r,o){e.enabled("x-powered-by")&&r.setHeader("X-Powered-By","Express"),t.res=r,r.req=t,t.next=o,setPrototypeOf(t,e.request),setPrototypeOf(r,e.response),r.locals=r.locals||Object.create(null),o()}};
\ No newline at end of file
index 7e91669..8533a68 100644 (file)
@@ -5,43 +5,4 @@
  * Copyright(c) 2014-2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict';
-
-/**
- * Module dependencies.
- */
-
-var merge = require('utils-merge')
-var parseUrl = require('parseurl');
-var qs = require('qs');
-
-/**
- * @param {Object} options
- * @return {Function}
- * @api public
- */
-
-module.exports = function query(options) {
-  var opts = merge({}, options)
-  var queryparse = qs.parse;
-
-  if (typeof options === 'function') {
-    queryparse = options;
-    opts = undefined;
-  }
-
-  if (opts !== undefined && opts.allowPrototypes === undefined) {
-    // back-compat for qs module
-    opts.allowPrototypes = true;
-  }
-
-  return function query(req, res, next){
-    if (!req.query) {
-      var val = parseUrl(req).query;
-      req.query = queryparse(val, opts);
-    }
-
-    next();
-  };
-};
+"use strict";var merge=require("utils-merge"),parseUrl=require("parseurl"),qs=require("qs");module.exports=function(r){var e=merge({},r),o=qs.parse;return"function"==typeof r&&(o=r,e=void 0),void 0!==e&&void 0===e.allowPrototypes&&(e.allowPrototypes=!0),function(r,u,s){if(!r.query){var t=parseUrl(r).query;r.query=o(t,e)}s()}};
\ No newline at end of file
index a9400ef..67a689b 100644 (file)
@@ -5,521 +5,4 @@
  * Copyright(c) 2014-2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict';
-
-/**
- * Module dependencies.
- * @private
- */
-
-var accepts = require('accepts');
-var deprecate = require('depd')('express');
-var isIP = require('net').isIP;
-var typeis = require('type-is');
-var http = require('http');
-var fresh = require('fresh');
-var parseRange = require('range-parser');
-var parse = require('parseurl');
-var proxyaddr = require('proxy-addr');
-
-/**
- * Request prototype.
- * @public
- */
-
-var req = Object.create(http.IncomingMessage.prototype)
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = req
-
-/**
- * Return request header.
- *
- * The `Referrer` header field is special-cased,
- * both `Referrer` and `Referer` are interchangeable.
- *
- * Examples:
- *
- *     req.get('Content-Type');
- *     // => "text/plain"
- *
- *     req.get('content-type');
- *     // => "text/plain"
- *
- *     req.get('Something');
- *     // => undefined
- *
- * Aliased as `req.header()`.
- *
- * @param {String} name
- * @return {String}
- * @public
- */
-
-req.get =
-req.header = function header(name) {
-  if (!name) {
-    throw new TypeError('name argument is required to req.get');
-  }
-
-  if (typeof name !== 'string') {
-    throw new TypeError('name must be a string to req.get');
-  }
-
-  var lc = name.toLowerCase();
-
-  switch (lc) {
-    case 'referer':
-    case 'referrer':
-      return this.headers.referrer
-        || this.headers.referer;
-    default:
-      return this.headers[lc];
-  }
-};
-
-/**
- * To do: update docs.
- *
- * Check if the given `type(s)` is acceptable, returning
- * the best match when true, otherwise `undefined`, in which
- * case you should respond with 406 "Not Acceptable".
- *
- * The `type` value may be a single MIME type string
- * such as "application/json", an extension name
- * such as "json", a comma-delimited list such as "json, html, text/plain",
- * an argument list such as `"json", "html", "text/plain"`,
- * or an array `["json", "html", "text/plain"]`. When a list
- * or array is given, the _best_ match, if any is returned.
- *
- * Examples:
- *
- *     // Accept: text/html
- *     req.accepts('html');
- *     // => "html"
- *
- *     // Accept: text/*, application/json
- *     req.accepts('html');
- *     // => "html"
- *     req.accepts('text/html');
- *     // => "text/html"
- *     req.accepts('json, text');
- *     // => "json"
- *     req.accepts('application/json');
- *     // => "application/json"
- *
- *     // Accept: text/*, application/json
- *     req.accepts('image/png');
- *     req.accepts('png');
- *     // => undefined
- *
- *     // Accept: text/*;q=.5, application/json
- *     req.accepts(['html', 'json']);
- *     req.accepts('html', 'json');
- *     req.accepts('html, json');
- *     // => "json"
- *
- * @param {String|Array} type(s)
- * @return {String|Array|Boolean}
- * @public
- */
-
-req.accepts = function(){
-  var accept = accepts(this);
-  return accept.types.apply(accept, arguments);
-};
-
-/**
- * Check if the given `encoding`s are accepted.
- *
- * @param {String} ...encoding
- * @return {String|Array}
- * @public
- */
-
-req.acceptsEncodings = function(){
-  var accept = accepts(this);
-  return accept.encodings.apply(accept, arguments);
-};
-
-req.acceptsEncoding = deprecate.function(req.acceptsEncodings,
-  'req.acceptsEncoding: Use acceptsEncodings instead');
-
-/**
- * Check if the given `charset`s are acceptable,
- * otherwise you should respond with 406 "Not Acceptable".
- *
- * @param {String} ...charset
- * @return {String|Array}
- * @public
- */
-
-req.acceptsCharsets = function(){
-  var accept = accepts(this);
-  return accept.charsets.apply(accept, arguments);
-};
-
-req.acceptsCharset = deprecate.function(req.acceptsCharsets,
-  'req.acceptsCharset: Use acceptsCharsets instead');
-
-/**
- * Check if the given `lang`s are acceptable,
- * otherwise you should respond with 406 "Not Acceptable".
- *
- * @param {String} ...lang
- * @return {String|Array}
- * @public
- */
-
-req.acceptsLanguages = function(){
-  var accept = accepts(this);
-  return accept.languages.apply(accept, arguments);
-};
-
-req.acceptsLanguage = deprecate.function(req.acceptsLanguages,
-  'req.acceptsLanguage: Use acceptsLanguages instead');
-
-/**
- * Parse Range header field, capping to the given `size`.
- *
- * Unspecified ranges such as "0-" require knowledge of your resource length. In
- * the case of a byte range this is of course the total number of bytes. If the
- * Range header field is not given `undefined` is returned, `-1` when unsatisfiable,
- * and `-2` when syntactically invalid.
- *
- * When ranges are returned, the array has a "type" property which is the type of
- * range that is required (most commonly, "bytes"). Each array element is an object
- * with a "start" and "end" property for the portion of the range.
- *
- * The "combine" option can be set to `true` and overlapping & adjacent ranges
- * will be combined into a single range.
- *
- * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3"
- * should respond with 4 users when available, not 3.
- *
- * @param {number} size
- * @param {object} [options]
- * @param {boolean} [options.combine=false]
- * @return {number|array}
- * @public
- */
-
-req.range = function range(size, options) {
-  var range = this.get('Range');
-  if (!range) return;
-  return parseRange(size, range, options);
-};
-
-/**
- * Return the value of param `name` when present or `defaultValue`.
- *
- *  - Checks route placeholders, ex: _/user/:id_
- *  - Checks body params, ex: id=12, {"id":12}
- *  - Checks query string params, ex: ?id=12
- *
- * To utilize request bodies, `req.body`
- * should be an object. This can be done by using
- * the `bodyParser()` middleware.
- *
- * @param {String} name
- * @param {Mixed} [defaultValue]
- * @return {String}
- * @public
- */
-
-req.param = function param(name, defaultValue) {
-  var params = this.params || {};
-  var body = this.body || {};
-  var query = this.query || {};
-
-  var args = arguments.length === 1
-    ? 'name'
-    : 'name, default';
-  deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead');
-
-  if (null != params[name] && params.hasOwnProperty(name)) return params[name];
-  if (null != body[name]) return body[name];
-  if (null != query[name]) return query[name];
-
-  return defaultValue;
-};
-
-/**
- * Check if the incoming request contains the "Content-Type"
- * header field, and it contains the give mime `type`.
- *
- * Examples:
- *
- *      // With Content-Type: text/html; charset=utf-8
- *      req.is('html');
- *      req.is('text/html');
- *      req.is('text/*');
- *      // => true
- *
- *      // When Content-Type is application/json
- *      req.is('json');
- *      req.is('application/json');
- *      req.is('application/*');
- *      // => true
- *
- *      req.is('html');
- *      // => false
- *
- * @param {String|Array} types...
- * @return {String|false|null}
- * @public
- */
-
-req.is = function is(types) {
-  var arr = types;
-
-  // support flattened arguments
-  if (!Array.isArray(types)) {
-    arr = new Array(arguments.length);
-    for (var i = 0; i < arr.length; i++) {
-      arr[i] = arguments[i];
-    }
-  }
-
-  return typeis(this, arr);
-};
-
-/**
- * Return the protocol string "http" or "https"
- * when requested with TLS. When the "trust proxy"
- * setting trusts the socket address, the
- * "X-Forwarded-Proto" header field will be trusted
- * and used if present.
- *
- * If you're running behind a reverse proxy that
- * supplies https for you this may be enabled.
- *
- * @return {String}
- * @public
- */
-
-defineGetter(req, 'protocol', function protocol(){
-  var proto = this.connection.encrypted
-    ? 'https'
-    : 'http';
-  var trust = this.app.get('trust proxy fn');
-
-  if (!trust(this.connection.remoteAddress, 0)) {
-    return proto;
-  }
-
-  // Note: X-Forwarded-Proto is normally only ever a
-  //       single value, but this is to be safe.
-  var header = this.get('X-Forwarded-Proto') || proto
-  var index = header.indexOf(',')
-
-  return index !== -1
-    ? header.substring(0, index).trim()
-    : header.trim()
-});
-
-/**
- * Short-hand for:
- *
- *    req.protocol === 'https'
- *
- * @return {Boolean}
- * @public
- */
-
-defineGetter(req, 'secure', function secure(){
-  return this.protocol === 'https';
-});
-
-/**
- * Return the remote address from the trusted proxy.
- *
- * The is the remote address on the socket unless
- * "trust proxy" is set.
- *
- * @return {String}
- * @public
- */
-
-defineGetter(req, 'ip', function ip(){
-  var trust = this.app.get('trust proxy fn');
-  return proxyaddr(this, trust);
-});
-
-/**
- * When "trust proxy" is set, trusted proxy addresses + client.
- *
- * For example if the value were "client, proxy1, proxy2"
- * you would receive the array `["client", "proxy1", "proxy2"]`
- * where "proxy2" is the furthest down-stream and "proxy1" and
- * "proxy2" were trusted.
- *
- * @return {Array}
- * @public
- */
-
-defineGetter(req, 'ips', function ips() {
-  var trust = this.app.get('trust proxy fn');
-  var addrs = proxyaddr.all(this, trust);
-
-  // reverse the order (to farthest -> closest)
-  // and remove socket address
-  addrs.reverse().pop()
-
-  return addrs
-});
-
-/**
- * Return subdomains as an array.
- *
- * Subdomains are the dot-separated parts of the host before the main domain of
- * the app. By default, the domain of the app is assumed to be the last two
- * parts of the host. This can be changed by setting "subdomain offset".
- *
- * For example, if the domain is "tobi.ferrets.example.com":
- * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.
- * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.
- *
- * @return {Array}
- * @public
- */
-
-defineGetter(req, 'subdomains', function subdomains() {
-  var hostname = this.hostname;
-
-  if (!hostname) return [];
-
-  var offset = this.app.get('subdomain offset');
-  var subdomains = !isIP(hostname)
-    ? hostname.split('.').reverse()
-    : [hostname];
-
-  return subdomains.slice(offset);
-});
-
-/**
- * Short-hand for `url.parse(req.url).pathname`.
- *
- * @return {String}
- * @public
- */
-
-defineGetter(req, 'path', function path() {
-  return parse(this).pathname;
-});
-
-/**
- * Parse the "Host" header field to a hostname.
- *
- * When the "trust proxy" setting trusts the socket
- * address, the "X-Forwarded-Host" header field will
- * be trusted.
- *
- * @return {String}
- * @public
- */
-
-defineGetter(req, 'hostname', function hostname(){
-  var trust = this.app.get('trust proxy fn');
-  var host = this.get('X-Forwarded-Host');
-
-  if (!host || !trust(this.connection.remoteAddress, 0)) {
-    host = this.get('Host');
-  } else if (host.indexOf(',') !== -1) {
-    // Note: X-Forwarded-Host is normally only ever a
-    //       single value, but this is to be safe.
-    host = host.substring(0, host.indexOf(',')).trimRight()
-  }
-
-  if (!host) return;
-
-  // IPv6 literal support
-  var offset = host[0] === '['
-    ? host.indexOf(']') + 1
-    : 0;
-  var index = host.indexOf(':', offset);
-
-  return index !== -1
-    ? host.substring(0, index)
-    : host;
-});
-
-// TODO: change req.host to return host in next major
-
-defineGetter(req, 'host', deprecate.function(function host(){
-  return this.hostname;
-}, 'req.host: Use req.hostname instead'));
-
-/**
- * Check if the request is fresh, aka
- * Last-Modified and/or the ETag
- * still match.
- *
- * @return {Boolean}
- * @public
- */
-
-defineGetter(req, 'fresh', function(){
-  var method = this.method;
-  var res = this.res
-  var status = res.statusCode
-
-  // GET or HEAD for weak freshness validation only
-  if ('GET' !== method && 'HEAD' !== method) return false;
-
-  // 2xx or 304 as per rfc2616 14.26
-  if ((status >= 200 && status < 300) || 304 === status) {
-    return fresh(this.headers, {
-      'etag': res.get('ETag'),
-      'last-modified': res.get('Last-Modified')
-    })
-  }
-
-  return false;
-});
-
-/**
- * Check if the request is stale, aka
- * "Last-Modified" and / or the "ETag" for the
- * resource has changed.
- *
- * @return {Boolean}
- * @public
- */
-
-defineGetter(req, 'stale', function stale(){
-  return !this.fresh;
-});
-
-/**
- * Check if the request was an _XMLHttpRequest_.
- *
- * @return {Boolean}
- * @public
- */
-
-defineGetter(req, 'xhr', function xhr(){
-  var val = this.get('X-Requested-With') || '';
-  return val.toLowerCase() === 'xmlhttprequest';
-});
-
-/**
- * Helper function for creating a getter on an object.
- *
- * @param {Object} obj
- * @param {String} name
- * @param {Function} getter
- * @private
- */
-function defineGetter(obj, name, getter) {
-  Object.defineProperty(obj, name, {
-    configurable: true,
-    enumerable: true,
-    get: getter
-  });
-}
+"use strict";var accepts=require("accepts"),deprecate=require("depd")("express"),isIP=require("net").isIP,typeis=require("type-is"),http=require("http"),fresh=require("fresh"),parseRange=require("range-parser"),parse=require("parseurl"),proxyaddr=require("proxy-addr"),req=Object.create(http.IncomingMessage.prototype);function defineGetter(e,r,t){Object.defineProperty(e,r,{configurable:!0,enumerable:!0,get:t})}module.exports=req,req.get=req.header=function(e){if(!e)throw new TypeError("name argument is required to req.get");if("string"!=typeof e)throw new TypeError("name must be a string to req.get");var r=e.toLowerCase();switch(r){case"referer":case"referrer":return this.headers.referrer||this.headers.referer;default:return this.headers[r]}},req.accepts=function(){var e=accepts(this);return e.types.apply(e,arguments)},req.acceptsEncodings=function(){var e=accepts(this);return e.encodings.apply(e,arguments)},req.acceptsEncoding=deprecate.function(req.acceptsEncodings,"req.acceptsEncoding: Use acceptsEncodings instead"),req.acceptsCharsets=function(){var e=accepts(this);return e.charsets.apply(e,arguments)},req.acceptsCharset=deprecate.function(req.acceptsCharsets,"req.acceptsCharset: Use acceptsCharsets instead"),req.acceptsLanguages=function(){var e=accepts(this);return e.languages.apply(e,arguments)},req.acceptsLanguage=deprecate.function(req.acceptsLanguages,"req.acceptsLanguage: Use acceptsLanguages instead"),req.range=function(e,r){var t=this.get("Range");if(t)return parseRange(e,t,r)},req.param=function(e,r){var t=this.params||{},s=this.body||{},n=this.query||{},a=1===arguments.length?"name":"name, default";return deprecate("req.param("+a+"): Use req.params, req.body, or req.query instead"),null!=t[e]&&t.hasOwnProperty(e)?t[e]:null!=s[e]?s[e]:null!=n[e]?n[e]:r},req.is=function(e){var r=e;if(!Array.isArray(e)){r=new Array(arguments.length);for(var t=0;t<r.length;t++)r[t]=arguments[t]}return typeis(this,r)},defineGetter(req,"protocol",(function(){var e=this.connection.encrypted?"https":"http";if(!this.app.get("trust proxy fn")(this.connection.remoteAddress,0))return e;var r=this.get("X-Forwarded-Proto")||e,t=r.indexOf(",");return-1!==t?r.substring(0,t).trim():r.trim()})),defineGetter(req,"secure",(function(){return"https"===this.protocol})),defineGetter(req,"ip",(function(){var e=this.app.get("trust proxy fn");return proxyaddr(this,e)})),defineGetter(req,"ips",(function(){var e=this.app.get("trust proxy fn"),r=proxyaddr.all(this,e);return r.reverse().pop(),r})),defineGetter(req,"subdomains",(function(){var e=this.hostname;if(!e)return[];var r=this.app.get("subdomain offset"),t=isIP(e)?[e]:e.split(".").reverse();return t.slice(r)})),defineGetter(req,"path",(function(){return parse(this).pathname})),defineGetter(req,"hostname",(function(){var e=this.app.get("trust proxy fn"),r=this.get("X-Forwarded-Host");if(r&&e(this.connection.remoteAddress,0)?-1!==r.indexOf(",")&&(r=r.substring(0,r.indexOf(",")).trimRight()):r=this.get("Host"),r){var t="["===r[0]?r.indexOf("]")+1:0,s=r.indexOf(":",t);return-1!==s?r.substring(0,s):r}})),defineGetter(req,"host",deprecate.function((function(){return this.hostname}),"req.host: Use req.hostname instead")),defineGetter(req,"fresh",(function(){var e=this.method,r=this.res,t=r.statusCode;return("GET"===e||"HEAD"===e)&&((t>=200&&t<300||304===t)&&fresh(this.headers,{etag:r.get("ETag"),"last-modified":r.get("Last-Modified")}))})),defineGetter(req,"stale",(function(){return!this.fresh})),defineGetter(req,"xhr",(function(){return"xmlhttprequest"===(this.get("X-Requested-With")||"").toLowerCase()}));
\ No newline at end of file
index c9f08cd..418aae5 100644 (file)
  * Copyright(c) 2014-2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict';
-
-/**
- * Module dependencies.
- * @private
- */
-
-var Buffer = require('safe-buffer').Buffer
-var contentDisposition = require('content-disposition');
-var deprecate = require('depd')('express');
-var encodeUrl = require('encodeurl');
-var escapeHtml = require('escape-html');
-var http = require('http');
-var isAbsolute = require('./utils').isAbsolute;
-var onFinished = require('on-finished');
-var path = require('path');
-var statuses = require('statuses')
-var merge = require('utils-merge');
-var sign = require('cookie-signature').sign;
-var normalizeType = require('./utils').normalizeType;
-var normalizeTypes = require('./utils').normalizeTypes;
-var setCharset = require('./utils').setCharset;
-var cookie = require('cookie');
-var send = require('send');
-var extname = path.extname;
-var mime = send.mime;
-var resolve = path.resolve;
-var vary = require('vary');
-
-/**
- * Response prototype.
- * @public
- */
-
-var res = Object.create(http.ServerResponse.prototype)
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = res
-
-/**
- * Module variables.
- * @private
- */
-
-var charsetRegExp = /;\s*charset\s*=/;
-
-/**
- * Set status `code`.
- *
- * @param {Number} code
- * @return {ServerResponse}
- * @public
- */
-
-res.status = function status(code) {
-  this.statusCode = code;
-  return this;
-};
-
-/**
- * Set Link header field with the given `links`.
- *
- * Examples:
- *
- *    res.links({
- *      next: 'http://api.example.com/users?page=2',
- *      last: 'http://api.example.com/users?page=5'
- *    });
- *
- * @param {Object} links
- * @return {ServerResponse}
- * @public
- */
-
-res.links = function(links){
-  var link = this.get('Link') || '';
-  if (link) link += ', ';
-  return this.set('Link', link + Object.keys(links).map(function(rel){
-    return '<' + links[rel] + '>; rel="' + rel + '"';
-  }).join(', '));
-};
-
-/**
- * Send a response.
- *
- * Examples:
- *
- *     res.send(Buffer.from('wahoo'));
- *     res.send({ some: 'json' });
- *     res.send('<p>some html</p>');
- *
- * @param {string|number|boolean|object|Buffer} body
- * @public
- */
-
-res.send = function send(body) {
-  var chunk = body;
-  var encoding;
-  var req = this.req;
-  var type;
-
-  // settings
-  var app = this.app;
-
-  // allow status / body
-  if (arguments.length === 2) {
-    // res.send(body, status) backwards compat
-    if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') {
-      deprecate('res.send(body, status): Use res.status(status).send(body) instead');
-      this.statusCode = arguments[1];
-    } else {
-      deprecate('res.send(status, body): Use res.status(status).send(body) instead');
-      this.statusCode = arguments[0];
-      chunk = arguments[1];
-    }
-  }
-
-  // disambiguate res.send(status) and res.send(status, num)
-  if (typeof chunk === 'number' && arguments.length === 1) {
-    // res.send(status) will set status message as text string
-    if (!this.get('Content-Type')) {
-      this.type('txt');
-    }
-
-    deprecate('res.send(status): Use res.sendStatus(status) instead');
-    this.statusCode = chunk;
-    chunk = statuses[chunk]
-  }
-
-  switch (typeof chunk) {
-    // string defaulting to html
-    case 'string':
-      if (!this.get('Content-Type')) {
-        this.type('html');
-      }
-      break;
-    case 'boolean':
-    case 'number':
-    case 'object':
-      if (chunk === null) {
-        chunk = '';
-      } else if (Buffer.isBuffer(chunk)) {
-        if (!this.get('Content-Type')) {
-          this.type('bin');
-        }
-      } else {
-        return this.json(chunk);
-      }
-      break;
-  }
-
-  // write strings in utf-8
-  if (typeof chunk === 'string') {
-    encoding = 'utf8';
-    type = this.get('Content-Type');
-
-    // reflect this in content-type
-    if (typeof type === 'string') {
-      this.set('Content-Type', setCharset(type, 'utf-8'));
-    }
-  }
-
-  // determine if ETag should be generated
-  var etagFn = app.get('etag fn')
-  var generateETag = !this.get('ETag') && typeof etagFn === 'function'
-
-  // populate Content-Length
-  var len
-  if (chunk !== undefined) {
-    if (Buffer.isBuffer(chunk)) {
-      // get length of Buffer
-      len = chunk.length
-    } else if (!generateETag && chunk.length < 1000) {
-      // just calculate length when no ETag + small chunk
-      len = Buffer.byteLength(chunk, encoding)
-    } else {
-      // convert chunk to Buffer and calculate
-      chunk = Buffer.from(chunk, encoding)
-      encoding = undefined;
-      len = chunk.length
-    }
-
-    this.set('Content-Length', len);
-  }
-
-  // populate ETag
-  var etag;
-  if (generateETag && len !== undefined) {
-    if ((etag = etagFn(chunk, encoding))) {
-      this.set('ETag', etag);
-    }
-  }
-
-  // freshness
-  if (req.fresh) this.statusCode = 304;
-
-  // strip irrelevant headers
-  if (204 === this.statusCode || 304 === this.statusCode) {
-    this.removeHeader('Content-Type');
-    this.removeHeader('Content-Length');
-    this.removeHeader('Transfer-Encoding');
-    chunk = '';
-  }
-
-  if (req.method === 'HEAD') {
-    // skip body for HEAD
-    this.end();
-  } else {
-    // respond
-    this.end(chunk, encoding);
-  }
-
-  return this;
-};
-
-/**
- * Send JSON response.
- *
- * Examples:
- *
- *     res.json(null);
- *     res.json({ user: 'tj' });
- *
- * @param {string|number|boolean|object} obj
- * @public
- */
-
-res.json = function json(obj) {
-  var val = obj;
-
-  // allow status / body
-  if (arguments.length === 2) {
-    // res.json(body, status) backwards compat
-    if (typeof arguments[1] === 'number') {
-      deprecate('res.json(obj, status): Use res.status(status).json(obj) instead');
-      this.statusCode = arguments[1];
-    } else {
-      deprecate('res.json(status, obj): Use res.status(status).json(obj) instead');
-      this.statusCode = arguments[0];
-      val = arguments[1];
-    }
-  }
-
-  // settings
-  var app = this.app;
-  var escape = app.get('json escape')
-  var replacer = app.get('json replacer');
-  var spaces = app.get('json spaces');
-  var body = stringify(val, replacer, spaces, escape)
-
-  // content-type
-  if (!this.get('Content-Type')) {
-    this.set('Content-Type', 'application/json');
-  }
-
-  return this.send(body);
-};
-
-/**
- * Send JSON response with JSONP callback support.
- *
- * Examples:
- *
- *     res.jsonp(null);
- *     res.jsonp({ user: 'tj' });
- *
- * @param {string|number|boolean|object} obj
- * @public
- */
-
-res.jsonp = function jsonp(obj) {
-  var val = obj;
-
-  // allow status / body
-  if (arguments.length === 2) {
-    // res.json(body, status) backwards compat
-    if (typeof arguments[1] === 'number') {
-      deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead');
-      this.statusCode = arguments[1];
-    } else {
-      deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead');
-      this.statusCode = arguments[0];
-      val = arguments[1];
-    }
-  }
-
-  // settings
-  var app = this.app;
-  var escape = app.get('json escape')
-  var replacer = app.get('json replacer');
-  var spaces = app.get('json spaces');
-  var body = stringify(val, replacer, spaces, escape)
-  var callback = this.req.query[app.get('jsonp callback name')];
-
-  // content-type
-  if (!this.get('Content-Type')) {
-    this.set('X-Content-Type-Options', 'nosniff');
-    this.set('Content-Type', 'application/json');
-  }
-
-  // fixup callback
-  if (Array.isArray(callback)) {
-    callback = callback[0];
-  }
-
-  // jsonp
-  if (typeof callback === 'string' && callback.length !== 0) {
-    this.set('X-Content-Type-Options', 'nosniff');
-    this.set('Content-Type', 'text/javascript');
-
-    // restrict callback charset
-    callback = callback.replace(/[^\[\]\w$.]/g, '');
-
-    // replace chars not allowed in JavaScript that are in JSON
-    body = body
-      .replace(/\u2028/g, '\\u2028')
-      .replace(/\u2029/g, '\\u2029');
-
-    // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"
-    // the typeof check is just to reduce client error noise
-    body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';
-  }
-
-  return this.send(body);
-};
-
-/**
- * Send given HTTP status code.
- *
- * Sets the response status to `statusCode` and the body of the
- * response to the standard description from node's http.STATUS_CODES
- * or the statusCode number if no description.
- *
- * Examples:
- *
- *     res.sendStatus(200);
- *
- * @param {number} statusCode
- * @public
- */
-
-res.sendStatus = function sendStatus(statusCode) {
-  var body = statuses[statusCode] || String(statusCode)
-
-  this.statusCode = statusCode;
-  this.type('txt');
-
-  return this.send(body);
-};
-
-/**
- * Transfer the file at the given `path`.
- *
- * Automatically sets the _Content-Type_ response header field.
- * The callback `callback(err)` is invoked when the transfer is complete
- * or when an error occurs. Be sure to check `res.sentHeader`
- * if you wish to attempt responding, as the header and some data
- * may have already been transferred.
- *
- * Options:
- *
- *   - `maxAge`   defaulting to 0 (can be string converted by `ms`)
- *   - `root`     root directory for relative filenames
- *   - `headers`  object of headers to serve with file
- *   - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them
- *
- * Other options are passed along to `send`.
- *
- * Examples:
- *
- *  The following example illustrates how `res.sendFile()` may
- *  be used as an alternative for the `static()` middleware for
- *  dynamic situations. The code backing `res.sendFile()` is actually
- *  the same code, so HTTP cache support etc is identical.
- *
- *     app.get('/user/:uid/photos/:file', function(req, res){
- *       var uid = req.params.uid
- *         , file = req.params.file;
- *
- *       req.user.mayViewFilesFrom(uid, function(yes){
- *         if (yes) {
- *           res.sendFile('/uploads/' + uid + '/' + file);
- *         } else {
- *           res.send(403, 'Sorry! you cant see that.');
- *         }
- *       });
- *     });
- *
- * @public
- */
-
-res.sendFile = function sendFile(path, options, callback) {
-  var done = callback;
-  var req = this.req;
-  var res = this;
-  var next = req.next;
-  var opts = options || {};
-
-  if (!path) {
-    throw new TypeError('path argument is required to res.sendFile');
-  }
-
-  if (typeof path !== 'string') {
-    throw new TypeError('path must be a string to res.sendFile')
-  }
-
-  // support function as second arg
-  if (typeof options === 'function') {
-    done = options;
-    opts = {};
-  }
-
-  if (!opts.root && !isAbsolute(path)) {
-    throw new TypeError('path must be absolute or specify root to res.sendFile');
-  }
-
-  // create file stream
-  var pathname = encodeURI(path);
-  var file = send(req, pathname, opts);
-
-  // transfer
-  sendfile(res, file, opts, function (err) {
-    if (done) return done(err);
-    if (err && err.code === 'EISDIR') return next();
-
-    // next() all but write errors
-    if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {
-      next(err);
-    }
-  });
-};
-
-/**
- * Transfer the file at the given `path`.
- *
- * Automatically sets the _Content-Type_ response header field.
- * The callback `callback(err)` is invoked when the transfer is complete
- * or when an error occurs. Be sure to check `res.sentHeader`
- * if you wish to attempt responding, as the header and some data
- * may have already been transferred.
- *
- * Options:
- *
- *   - `maxAge`   defaulting to 0 (can be string converted by `ms`)
- *   - `root`     root directory for relative filenames
- *   - `headers`  object of headers to serve with file
- *   - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them
- *
- * Other options are passed along to `send`.
- *
- * Examples:
- *
- *  The following example illustrates how `res.sendfile()` may
- *  be used as an alternative for the `static()` middleware for
- *  dynamic situations. The code backing `res.sendfile()` is actually
- *  the same code, so HTTP cache support etc is identical.
- *
- *     app.get('/user/:uid/photos/:file', function(req, res){
- *       var uid = req.params.uid
- *         , file = req.params.file;
- *
- *       req.user.mayViewFilesFrom(uid, function(yes){
- *         if (yes) {
- *           res.sendfile('/uploads/' + uid + '/' + file);
- *         } else {
- *           res.send(403, 'Sorry! you cant see that.');
- *         }
- *       });
- *     });
- *
- * @public
- */
-
-res.sendfile = function (path, options, callback) {
-  var done = callback;
-  var req = this.req;
-  var res = this;
-  var next = req.next;
-  var opts = options || {};
-
-  // support function as second arg
-  if (typeof options === 'function') {
-    done = options;
-    opts = {};
-  }
-
-  // create file stream
-  var file = send(req, path, opts);
-
-  // transfer
-  sendfile(res, file, opts, function (err) {
-    if (done) return done(err);
-    if (err && err.code === 'EISDIR') return next();
-
-    // next() all but write errors
-    if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {
-      next(err);
-    }
-  });
-};
-
-res.sendfile = deprecate.function(res.sendfile,
-  'res.sendfile: Use res.sendFile instead');
-
-/**
- * Transfer the file at the given `path` as an attachment.
- *
- * Optionally providing an alternate attachment `filename`,
- * and optional callback `callback(err)`. The callback is invoked
- * when the data transfer is complete, or when an error has
- * ocurred. Be sure to check `res.headersSent` if you plan to respond.
- *
- * Optionally providing an `options` object to use with `res.sendFile()`.
- * This function will set the `Content-Disposition` header, overriding
- * any `Content-Disposition` header passed as header options in order
- * to set the attachment and filename.
- *
- * This method uses `res.sendFile()`.
- *
- * @public
- */
-
-res.download = function download (path, filename, options, callback) {
-  var done = callback;
-  var name = filename;
-  var opts = options || null
-
-  // support function as second or third arg
-  if (typeof filename === 'function') {
-    done = filename;
-    name = null;
-    opts = null
-  } else if (typeof options === 'function') {
-    done = options
-    opts = null
-  }
-
-  // set Content-Disposition when file is sent
-  var headers = {
-    'Content-Disposition': contentDisposition(name || path)
-  };
-
-  // merge user-provided headers
-  if (opts && opts.headers) {
-    var keys = Object.keys(opts.headers)
-    for (var i = 0; i < keys.length; i++) {
-      var key = keys[i]
-      if (key.toLowerCase() !== 'content-disposition') {
-        headers[key] = opts.headers[key]
-      }
-    }
-  }
-
-  // merge user-provided options
-  opts = Object.create(opts)
-  opts.headers = headers
-
-  // Resolve the full path for sendFile
-  var fullPath = resolve(path);
-
-  // send file
-  return this.sendFile(fullPath, opts, done)
-};
-
-/**
- * Set _Content-Type_ response header with `type` through `mime.lookup()`
- * when it does not contain "/", or set the Content-Type to `type` otherwise.
- *
- * Examples:
- *
- *     res.type('.html');
- *     res.type('html');
- *     res.type('json');
- *     res.type('application/json');
- *     res.type('png');
- *
- * @param {String} type
- * @return {ServerResponse} for chaining
- * @public
- */
-
-res.contentType =
-res.type = function contentType(type) {
-  var ct = type.indexOf('/') === -1
-    ? mime.lookup(type)
-    : type;
-
-  return this.set('Content-Type', ct);
-};
-
-/**
- * Respond to the Acceptable formats using an `obj`
- * of mime-type callbacks.
- *
- * This method uses `req.accepted`, an array of
- * acceptable types ordered by their quality values.
- * When "Accept" is not present the _first_ callback
- * is invoked, otherwise the first match is used. When
- * no match is performed the server responds with
- * 406 "Not Acceptable".
- *
- * Content-Type is set for you, however if you choose
- * you may alter this within the callback using `res.type()`
- * or `res.set('Content-Type', ...)`.
- *
- *    res.format({
- *      'text/plain': function(){
- *        res.send('hey');
- *      },
- *
- *      'text/html': function(){
- *        res.send('<p>hey</p>');
- *      },
- *
- *      'appliation/json': function(){
- *        res.send({ message: 'hey' });
- *      }
- *    });
- *
- * In addition to canonicalized MIME types you may
- * also use extnames mapped to these types:
- *
- *    res.format({
- *      text: function(){
- *        res.send('hey');
- *      },
- *
- *      html: function(){
- *        res.send('<p>hey</p>');
- *      },
- *
- *      json: function(){
- *        res.send({ message: 'hey' });
- *      }
- *    });
- *
- * By default Express passes an `Error`
- * with a `.status` of 406 to `next(err)`
- * if a match is not made. If you provide
- * a `.default` callback it will be invoked
- * instead.
- *
- * @param {Object} obj
- * @return {ServerResponse} for chaining
- * @public
- */
-
-res.format = function(obj){
-  var req = this.req;
-  var next = req.next;
-
-  var fn = obj.default;
-  if (fn) delete obj.default;
-  var keys = Object.keys(obj);
-
-  var key = keys.length > 0
-    ? req.accepts(keys)
-    : false;
-
-  this.vary("Accept");
-
-  if (key) {
-    this.set('Content-Type', normalizeType(key).value);
-    obj[key](req, this, next);
-  } else if (fn) {
-    fn();
-  } else {
-    var err = new Error('Not Acceptable');
-    err.status = err.statusCode = 406;
-    err.types = normalizeTypes(keys).map(function(o){ return o.value });
-    next(err);
-  }
-
-  return this;
-};
-
-/**
- * Set _Content-Disposition_ header to _attachment_ with optional `filename`.
- *
- * @param {String} filename
- * @return {ServerResponse}
- * @public
- */
-
-res.attachment = function attachment(filename) {
-  if (filename) {
-    this.type(extname(filename));
-  }
-
-  this.set('Content-Disposition', contentDisposition(filename));
-
-  return this;
-};
-
-/**
- * Append additional header `field` with value `val`.
- *
- * Example:
- *
- *    res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);
- *    res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
- *    res.append('Warning', '199 Miscellaneous warning');
- *
- * @param {String} field
- * @param {String|Array} val
- * @return {ServerResponse} for chaining
- * @public
- */
-
-res.append = function append(field, val) {
-  var prev = this.get(field);
-  var value = val;
-
-  if (prev) {
-    // concat the new and prev vals
-    value = Array.isArray(prev) ? prev.concat(val)
-      : Array.isArray(val) ? [prev].concat(val)
-      : [prev, val];
-  }
-
-  return this.set(field, value);
-};
-
-/**
- * Set header `field` to `val`, or pass
- * an object of header fields.
- *
- * Examples:
- *
- *    res.set('Foo', ['bar', 'baz']);
- *    res.set('Accept', 'application/json');
- *    res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
- *
- * Aliased as `res.header()`.
- *
- * @param {String|Object} field
- * @param {String|Array} val
- * @return {ServerResponse} for chaining
- * @public
- */
-
-res.set =
-res.header = function header(field, val) {
-  if (arguments.length === 2) {
-    var value = Array.isArray(val)
-      ? val.map(String)
-      : String(val);
-
-    // add charset to content-type
-    if (field.toLowerCase() === 'content-type') {
-      if (Array.isArray(value)) {
-        throw new TypeError('Content-Type cannot be set to an Array');
-      }
-      if (!charsetRegExp.test(value)) {
-        var charset = mime.charsets.lookup(value.split(';')[0]);
-        if (charset) value += '; charset=' + charset.toLowerCase();
-      }
-    }
-
-    this.setHeader(field, value);
-  } else {
-    for (var key in field) {
-      this.set(key, field[key]);
-    }
-  }
-  return this;
-};
-
-/**
- * Get value for header `field`.
- *
- * @param {String} field
- * @return {String}
- * @public
- */
-
-res.get = function(field){
-  return this.getHeader(field);
-};
-
-/**
- * Clear cookie `name`.
- *
- * @param {String} name
- * @param {Object} [options]
- * @return {ServerResponse} for chaining
- * @public
- */
-
-res.clearCookie = function clearCookie(name, options) {
-  var opts = merge({ expires: new Date(1), path: '/' }, options);
-
-  return this.cookie(name, '', opts);
-};
-
-/**
- * Set cookie `name` to `value`, with the given `options`.
- *
- * Options:
- *
- *    - `maxAge`   max-age in milliseconds, converted to `expires`
- *    - `signed`   sign the cookie
- *    - `path`     defaults to "/"
- *
- * Examples:
- *
- *    // "Remember Me" for 15 minutes
- *    res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });
- *
- *    // same as above
- *    res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
- *
- * @param {String} name
- * @param {String|Object} value
- * @param {Object} [options]
- * @return {ServerResponse} for chaining
- * @public
- */
-
-res.cookie = function (name, value, options) {
-  var opts = merge({}, options);
-  var secret = this.req.secret;
-  var signed = opts.signed;
-
-  if (signed && !secret) {
-    throw new Error('cookieParser("secret") required for signed cookies');
-  }
-
-  var val = typeof value === 'object'
-    ? 'j:' + JSON.stringify(value)
-    : String(value);
-
-  if (signed) {
-    val = 's:' + sign(val, secret);
-  }
-
-  if ('maxAge' in opts) {
-    opts.expires = new Date(Date.now() + opts.maxAge);
-    opts.maxAge /= 1000;
-  }
-
-  if (opts.path == null) {
-    opts.path = '/';
-  }
-
-  this.append('Set-Cookie', cookie.serialize(name, String(val), opts));
-
-  return this;
-};
-
-/**
- * Set the location header to `url`.
- *
- * The given `url` can also be "back", which redirects
- * to the _Referrer_ or _Referer_ headers or "/".
- *
- * Examples:
- *
- *    res.location('/foo/bar').;
- *    res.location('http://example.com');
- *    res.location('../login');
- *
- * @param {String} url
- * @return {ServerResponse} for chaining
- * @public
- */
-
-res.location = function location(url) {
-  var loc = url;
-
-  // "back" is an alias for the referrer
-  if (url === 'back') {
-    loc = this.req.get('Referrer') || '/';
-  }
-
-  // set location
-  return this.set('Location', encodeUrl(loc));
-};
-
-/**
- * Redirect to the given `url` with optional response `status`
- * defaulting to 302.
- *
- * The resulting `url` is determined by `res.location()`, so
- * it will play nicely with mounted apps, relative paths,
- * `"back"` etc.
- *
- * Examples:
- *
- *    res.redirect('/foo/bar');
- *    res.redirect('http://example.com');
- *    res.redirect(301, 'http://example.com');
- *    res.redirect('../login'); // /blog/post/1 -> /blog/login
- *
- * @public
- */
-
-res.redirect = function redirect(url) {
-  var address = url;
-  var body;
-  var status = 302;
-
-  // allow status / url
-  if (arguments.length === 2) {
-    if (typeof arguments[0] === 'number') {
-      status = arguments[0];
-      address = arguments[1];
-    } else {
-      deprecate('res.redirect(url, status): Use res.redirect(status, url) instead');
-      status = arguments[1];
-    }
-  }
-
-  // Set location header
-  address = this.location(address).get('Location');
-
-  // Support text/{plain,html} by default
-  this.format({
-    text: function(){
-      body = statuses[status] + '. Redirecting to ' + address
-    },
-
-    html: function(){
-      var u = escapeHtml(address);
-      body = '<p>' + statuses[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>'
-    },
-
-    default: function(){
-      body = '';
-    }
-  });
-
-  // Respond
-  this.statusCode = status;
-  this.set('Content-Length', Buffer.byteLength(body));
-
-  if (this.req.method === 'HEAD') {
-    this.end();
-  } else {
-    this.end(body);
-  }
-};
-
-/**
- * Add `field` to Vary. If already present in the Vary set, then
- * this call is simply ignored.
- *
- * @param {Array|String} field
- * @return {ServerResponse} for chaining
- * @public
- */
-
-res.vary = function(field){
-  // checks for back-compat
-  if (!field || (Array.isArray(field) && !field.length)) {
-    deprecate('res.vary(): Provide a field name');
-    return this;
-  }
-
-  vary(this, field);
-
-  return this;
-};
-
-/**
- * Render `view` with the given `options` and optional callback `fn`.
- * When a callback function is given a response will _not_ be made
- * automatically, otherwise a response of _200_ and _text/html_ is given.
- *
- * Options:
- *
- *  - `cache`     boolean hinting to the engine it should cache
- *  - `filename`  filename of the view being rendered
- *
- * @public
- */
-
-res.render = function render(view, options, callback) {
-  var app = this.req.app;
-  var done = callback;
-  var opts = options || {};
-  var req = this.req;
-  var self = this;
-
-  // support callback function as second arg
-  if (typeof options === 'function') {
-    done = options;
-    opts = {};
-  }
-
-  // merge res.locals
-  opts._locals = self.locals;
-
-  // default callback to respond
-  done = done || function (err, str) {
-    if (err) return req.next(err);
-    self.send(str);
-  };
-
-  // render
-  app.render(view, opts, done);
-};
-
-// pipe the send file stream
-function sendfile(res, file, options, callback) {
-  var done = false;
-  var streaming;
-
-  // request aborted
-  function onaborted() {
-    if (done) return;
-    done = true;
-
-    var err = new Error('Request aborted');
-    err.code = 'ECONNABORTED';
-    callback(err);
-  }
-
-  // directory
-  function ondirectory() {
-    if (done) return;
-    done = true;
-
-    var err = new Error('EISDIR, read');
-    err.code = 'EISDIR';
-    callback(err);
-  }
-
-  // errors
-  function onerror(err) {
-    if (done) return;
-    done = true;
-    callback(err);
-  }
-
-  // ended
-  function onend() {
-    if (done) return;
-    done = true;
-    callback();
-  }
-
-  // file
-  function onfile() {
-    streaming = false;
-  }
-
-  // finished
-  function onfinish(err) {
-    if (err && err.code === 'ECONNRESET') return onaborted();
-    if (err) return onerror(err);
-    if (done) return;
-
-    setImmediate(function () {
-      if (streaming !== false && !done) {
-        onaborted();
-        return;
-      }
-
-      if (done) return;
-      done = true;
-      callback();
-    });
-  }
-
-  // streaming
-  function onstream() {
-    streaming = true;
-  }
-
-  file.on('directory', ondirectory);
-  file.on('end', onend);
-  file.on('error', onerror);
-  file.on('file', onfile);
-  file.on('stream', onstream);
-  onFinished(res, onfinish);
-
-  if (options.headers) {
-    // set headers on successful transfer
-    file.on('headers', function headers(res) {
-      var obj = options.headers;
-      var keys = Object.keys(obj);
-
-      for (var i = 0; i < keys.length; i++) {
-        var k = keys[i];
-        res.setHeader(k, obj[k]);
-      }
-    });
-  }
-
-  // pipe
-  file.pipe(res);
-}
-
-/**
- * Stringify JSON, like JSON.stringify, but v8 optimized, with the
- * ability to escape characters that can trigger HTML sniffing.
- *
- * @param {*} value
- * @param {function} replaces
- * @param {number} spaces
- * @param {boolean} escape
- * @returns {string}
- * @private
- */
-
-function stringify (value, replacer, spaces, escape) {
-  // v8 checks arguments.length for optimizing simple call
-  // https://bugs.chromium.org/p/v8/issues/detail?id=4730
-  var json = replacer || spaces
-    ? JSON.stringify(value, replacer, spaces)
-    : JSON.stringify(value);
-
-  if (escape) {
-    json = json.replace(/[<>&]/g, function (c) {
-      switch (c.charCodeAt(0)) {
-        case 0x3c:
-          return '\\u003c'
-        case 0x3e:
-          return '\\u003e'
-        case 0x26:
-          return '\\u0026'
-        /* istanbul ignore next: unreachable default */
-        default:
-          return c
-      }
-    })
-  }
-
-  return json
-}
+"use strict";var Buffer=require("safe-buffer").Buffer,contentDisposition=require("content-disposition"),deprecate=require("depd")("express"),encodeUrl=require("encodeurl"),escapeHtml=require("escape-html"),http=require("http"),isAbsolute=require("./utils").isAbsolute,onFinished=require("on-finished"),path=require("path"),statuses=require("statuses"),merge=require("utils-merge"),sign=require("cookie-signature").sign,normalizeType=require("./utils").normalizeType,normalizeTypes=require("./utils").normalizeTypes,setCharset=require("./utils").setCharset,cookie=require("cookie"),send=require("send"),extname=path.extname,mime=send.mime,resolve=path.resolve,vary=require("vary"),res=Object.create(http.ServerResponse.prototype);module.exports=res;var charsetRegExp=/;\s*charset\s*=/;function sendfile(e,t,s,r){var n,i=!1;function o(){if(!i){i=!0;var e=new Error("Request aborted");e.code="ECONNABORTED",r(e)}}function a(e){i||(i=!0,r(e))}t.on("directory",(function(){if(!i){i=!0;var e=new Error("EISDIR, read");e.code="EISDIR",r(e)}})),t.on("end",(function(){i||(i=!0,r())})),t.on("error",a),t.on("file",(function(){n=!1})),t.on("stream",(function(){n=!0})),onFinished(e,(function(e){return e&&"ECONNRESET"===e.code?o():e?a(e):void(i||setImmediate((function(){!1===n||i?i||(i=!0,r()):o()})))})),s.headers&&t.on("headers",(function(e){for(var t=s.headers,r=Object.keys(t),n=0;n<r.length;n++){var i=r[n];e.setHeader(i,t[i])}})),t.pipe(e)}function stringify(e,t,s,r){var n=t||s?JSON.stringify(e,t,s):JSON.stringify(e);return r&&(n=n.replace(/[<>&]/g,(function(e){switch(e.charCodeAt(0)){case 60:return"\\u003c";case 62:return"\\u003e";case 38:return"\\u0026";default:return e}}))),n}res.status=function(e){return this.statusCode=e,this},res.links=function(e){var t=this.get("Link")||"";return t&&(t+=", "),this.set("Link",t+Object.keys(e).map((function(t){return"<"+e[t]+'>; rel="'+t+'"'})).join(", "))},res.send=function(e){var t,s,r=e,n=this.req,i=this.app;switch(2===arguments.length&&("number"!=typeof arguments[0]&&"number"==typeof arguments[1]?(deprecate("res.send(body, status): Use res.status(status).send(body) instead"),this.statusCode=arguments[1]):(deprecate("res.send(status, body): Use res.status(status).send(body) instead"),this.statusCode=arguments[0],r=arguments[1])),"number"==typeof r&&1===arguments.length&&(this.get("Content-Type")||this.type("txt"),deprecate("res.send(status): Use res.sendStatus(status) instead"),this.statusCode=r,r=statuses[r]),typeof r){case"string":this.get("Content-Type")||this.type("html");break;case"boolean":case"number":case"object":if(null===r)r="";else{if(!Buffer.isBuffer(r))return this.json(r);this.get("Content-Type")||this.type("bin")}}"string"==typeof r&&(t="utf8","string"==typeof(s=this.get("Content-Type"))&&this.set("Content-Type",setCharset(s,"utf-8")));var o,a,u=i.get("etag fn"),c=!this.get("ETag")&&"function"==typeof u;return void 0!==r&&(Buffer.isBuffer(r)?o=r.length:!c&&r.length<1e3?o=Buffer.byteLength(r,t):(r=Buffer.from(r,t),t=void 0,o=r.length),this.set("Content-Length",o)),c&&void 0!==o&&(a=u(r,t))&&this.set("ETag",a),n.fresh&&(this.statusCode=304),204!==this.statusCode&&304!==this.statusCode||(this.removeHeader("Content-Type"),this.removeHeader("Content-Length"),this.removeHeader("Transfer-Encoding"),r=""),"HEAD"===n.method?this.end():this.end(r,t),this},res.json=function(e){var t=e;2===arguments.length&&("number"==typeof arguments[1]?(deprecate("res.json(obj, status): Use res.status(status).json(obj) instead"),this.statusCode=arguments[1]):(deprecate("res.json(status, obj): Use res.status(status).json(obj) instead"),this.statusCode=arguments[0],t=arguments[1]));var s=this.app,r=s.get("json escape"),n=s.get("json replacer"),i=s.get("json spaces"),o=stringify(t,n,i,r);return this.get("Content-Type")||this.set("Content-Type","application/json"),this.send(o)},res.jsonp=function(e){var t=e;2===arguments.length&&("number"==typeof arguments[1]?(deprecate("res.jsonp(obj, status): Use res.status(status).json(obj) instead"),this.statusCode=arguments[1]):(deprecate("res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead"),this.statusCode=arguments[0],t=arguments[1]));var s=this.app,r=s.get("json escape"),n=s.get("json replacer"),i=s.get("json spaces"),o=stringify(t,n,i,r),a=this.req.query[s.get("jsonp callback name")];return this.get("Content-Type")||(this.set("X-Content-Type-Options","nosniff"),this.set("Content-Type","application/json")),Array.isArray(a)&&(a=a[0]),"string"==typeof a&&0!==a.length&&(this.set("X-Content-Type-Options","nosniff"),this.set("Content-Type","text/javascript"),o="/**/ typeof "+(a=a.replace(/[^\[\]\w$.]/g,""))+" === 'function' && "+a+"("+(o=o.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"))+");"),this.send(o)},res.sendStatus=function(e){var t=statuses[e]||String(e);return this.statusCode=e,this.type("txt"),this.send(t)},res.sendFile=function(e,t,s){var r=s,n=this.req,i=n.next,o=t||{};if(!e)throw new TypeError("path argument is required to res.sendFile");if("string"!=typeof e)throw new TypeError("path must be a string to res.sendFile");if("function"==typeof t&&(r=t,o={}),!o.root&&!isAbsolute(e))throw new TypeError("path must be absolute or specify root to res.sendFile");var a=encodeURI(e);sendfile(this,send(n,a,o),o,(function(e){return r?r(e):e&&"EISDIR"===e.code?i():void(e&&"ECONNABORTED"!==e.code&&"write"!==e.syscall&&i(e))}))},res.sendfile=function(e,t,s){var r=s,n=this.req,i=n.next,o=t||{};"function"==typeof t&&(r=t,o={}),sendfile(this,send(n,e,o),o,(function(e){return r?r(e):e&&"EISDIR"===e.code?i():void(e&&"ECONNABORTED"!==e.code&&"write"!==e.syscall&&i(e))}))},res.sendfile=deprecate.function(res.sendfile,"res.sendfile: Use res.sendFile instead"),res.download=function(e,t,s,r){var n=r,i=t,o=s||null;"function"==typeof t?(n=t,i=null,o=null):"function"==typeof s&&(n=s,o=null);var a={"Content-Disposition":contentDisposition(i||e)};if(o&&o.headers)for(var u=Object.keys(o.headers),c=0;c<u.length;c++){var h=u[c];"content-disposition"!==h.toLowerCase()&&(a[h]=o.headers[h])}(o=Object.create(o)).headers=a;var p=resolve(e);return this.sendFile(p,o,n)},res.contentType=res.type=function(e){var t=-1===e.indexOf("/")?mime.lookup(e):e;return this.set("Content-Type",t)},res.format=function(e){var t=this.req,s=t.next,r=e.default;r&&delete e.default;var n=Object.keys(e),i=n.length>0&&t.accepts(n);if(this.vary("Accept"),i)this.set("Content-Type",normalizeType(i).value),e[i](t,this,s);else if(r)r();else{var o=new Error("Not Acceptable");o.status=o.statusCode=406,o.types=normalizeTypes(n).map((function(e){return e.value})),s(o)}return this},res.attachment=function(e){return e&&this.type(extname(e)),this.set("Content-Disposition",contentDisposition(e)),this},res.append=function(e,t){var s=this.get(e),r=t;return s&&(r=Array.isArray(s)?s.concat(t):Array.isArray(t)?[s].concat(t):[s,t]),this.set(e,r)},res.set=res.header=function(e,t){if(2===arguments.length){var s=Array.isArray(t)?t.map(String):String(t);if("content-type"===e.toLowerCase()){if(Array.isArray(s))throw new TypeError("Content-Type cannot be set to an Array");if(!charsetRegExp.test(s)){var r=mime.charsets.lookup(s.split(";")[0]);r&&(s+="; charset="+r.toLowerCase())}}this.setHeader(e,s)}else for(var n in e)this.set(n,e[n]);return this},res.get=function(e){return this.getHeader(e)},res.clearCookie=function(e,t){var s=merge({expires:new Date(1),path:"/"},t);return this.cookie(e,"",s)},res.cookie=function(e,t,s){var r=merge({},s),n=this.req.secret,i=r.signed;if(i&&!n)throw new Error('cookieParser("secret") required for signed cookies');var o="object"==typeof t?"j:"+JSON.stringify(t):String(t);return i&&(o="s:"+sign(o,n)),"maxAge"in r&&(r.expires=new Date(Date.now()+r.maxAge),r.maxAge/=1e3),null==r.path&&(r.path="/"),this.append("Set-Cookie",cookie.serialize(e,String(o),r)),this},res.location=function(e){var t=e;return"back"===e&&(t=this.req.get("Referrer")||"/"),this.set("Location",encodeUrl(t))},res.redirect=function(e){var t,s=e,r=302;2===arguments.length&&("number"==typeof arguments[0]?(r=arguments[0],s=arguments[1]):(deprecate("res.redirect(url, status): Use res.redirect(status, url) instead"),r=arguments[1])),s=this.location(s).get("Location"),this.format({text:function(){t=statuses[r]+". Redirecting to "+s},html:function(){var e=escapeHtml(s);t="<p>"+statuses[r]+'. Redirecting to <a href="'+e+'">'+e+"</a></p>"},default:function(){t=""}}),this.statusCode=r,this.set("Content-Length",Buffer.byteLength(t)),"HEAD"===this.req.method?this.end():this.end(t)},res.vary=function(e){return!e||Array.isArray(e)&&!e.length?(deprecate("res.vary(): Provide a field name"),this):(vary(this,e),this)},res.render=function(e,t,s){var r=this.req.app,n=s,i=t||{},o=this.req,a=this;"function"==typeof t&&(n=t,i={}),i._locals=a.locals,n=n||function(e,t){if(e)return o.next(e);a.send(t)},r.render(e,i,n)};
\ No newline at end of file
index 69e6d38..9ee6fbc 100644 (file)
@@ -5,658 +5,4 @@
  * Copyright(c) 2014-2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict';
-
-/**
- * Module dependencies.
- * @private
- */
-
-var Route = require('./route');
-var Layer = require('./layer');
-var methods = require('methods');
-var mixin = require('utils-merge');
-var debug = require('debug')('express:router');
-var deprecate = require('depd')('express');
-var flatten = require('array-flatten');
-var parseUrl = require('parseurl');
-var setPrototypeOf = require('setprototypeof')
-
-/**
- * Module variables.
- * @private
- */
-
-var objectRegExp = /^\[object (\S+)\]$/;
-var slice = Array.prototype.slice;
-var toString = Object.prototype.toString;
-
-/**
- * Initialize a new `Router` with the given `options`.
- *
- * @param {Object} [options]
- * @return {Router} which is an callable function
- * @public
- */
-
-var proto = module.exports = function(options) {
-  var opts = options || {};
-
-  function router(req, res, next) {
-    router.handle(req, res, next);
-  }
-
-  // mixin Router class functions
-  setPrototypeOf(router, proto)
-
-  router.params = {};
-  router._params = [];
-  router.caseSensitive = opts.caseSensitive;
-  router.mergeParams = opts.mergeParams;
-  router.strict = opts.strict;
-  router.stack = [];
-
-  return router;
-};
-
-/**
- * Map the given param placeholder `name`(s) to the given callback.
- *
- * Parameter mapping is used to provide pre-conditions to routes
- * which use normalized placeholders. For example a _:user_id_ parameter
- * could automatically load a user's information from the database without
- * any additional code,
- *
- * The callback uses the same signature as middleware, the only difference
- * being that the value of the placeholder is passed, in this case the _id_
- * of the user. Once the `next()` function is invoked, just like middleware
- * it will continue on to execute the route, or subsequent parameter functions.
- *
- * Just like in middleware, you must either respond to the request or call next
- * to avoid stalling the request.
- *
- *  app.param('user_id', function(req, res, next, id){
- *    User.find(id, function(err, user){
- *      if (err) {
- *        return next(err);
- *      } else if (!user) {
- *        return next(new Error('failed to load user'));
- *      }
- *      req.user = user;
- *      next();
- *    });
- *  });
- *
- * @param {String} name
- * @param {Function} fn
- * @return {app} for chaining
- * @public
- */
-
-proto.param = function param(name, fn) {
-  // param logic
-  if (typeof name === 'function') {
-    deprecate('router.param(fn): Refactor to use path params');
-    this._params.push(name);
-    return;
-  }
-
-  // apply param functions
-  var params = this._params;
-  var len = params.length;
-  var ret;
-
-  if (name[0] === ':') {
-    deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead');
-    name = name.substr(1);
-  }
-
-  for (var i = 0; i < len; ++i) {
-    if (ret = params[i](name, fn)) {
-      fn = ret;
-    }
-  }
-
-  // ensure we end up with a
-  // middleware function
-  if ('function' !== typeof fn) {
-    throw new Error('invalid param() call for ' + name + ', got ' + fn);
-  }
-
-  (this.params[name] = this.params[name] || []).push(fn);
-  return this;
-};
-
-/**
- * Dispatch a req, res into the router.
- * @private
- */
-
-proto.handle = function handle(req, res, out) {
-  var self = this;
-
-  debug('dispatching %s %s', req.method, req.url);
-
-  var idx = 0;
-  var protohost = getProtohost(req.url) || ''
-  var removed = '';
-  var slashAdded = false;
-  var paramcalled = {};
-
-  // store options for OPTIONS request
-  // only used if OPTIONS request
-  var options = [];
-
-  // middleware and routes
-  var stack = self.stack;
-
-  // manage inter-router variables
-  var parentParams = req.params;
-  var parentUrl = req.baseUrl || '';
-  var done = restore(out, req, 'baseUrl', 'next', 'params');
-
-  // setup next layer
-  req.next = next;
-
-  // for options requests, respond with a default if nothing else responds
-  if (req.method === 'OPTIONS') {
-    done = wrap(done, function(old, err) {
-      if (err || options.length === 0) return old(err);
-      sendOptionsResponse(res, options, old);
-    });
-  }
-
-  // setup basic req values
-  req.baseUrl = parentUrl;
-  req.originalUrl = req.originalUrl || req.url;
-
-  next();
-
-  function next(err) {
-    var layerError = err === 'route'
-      ? null
-      : err;
-
-    // remove added slash
-    if (slashAdded) {
-      req.url = req.url.substr(1);
-      slashAdded = false;
-    }
-
-    // restore altered req.url
-    if (removed.length !== 0) {
-      req.baseUrl = parentUrl;
-      req.url = protohost + removed + req.url.substr(protohost.length);
-      removed = '';
-    }
-
-    // signal to exit router
-    if (layerError === 'router') {
-      setImmediate(done, null)
-      return
-    }
-
-    // no more matching layers
-    if (idx >= stack.length) {
-      setImmediate(done, layerError);
-      return;
-    }
-
-    // get pathname of request
-    var path = getPathname(req);
-
-    if (path == null) {
-      return done(layerError);
-    }
-
-    // find next matching layer
-    var layer;
-    var match;
-    var route;
-
-    while (match !== true && idx < stack.length) {
-      layer = stack[idx++];
-      match = matchLayer(layer, path);
-      route = layer.route;
-
-      if (typeof match !== 'boolean') {
-        // hold on to layerError
-        layerError = layerError || match;
-      }
-
-      if (match !== true) {
-        continue;
-      }
-
-      if (!route) {
-        // process non-route handlers normally
-        continue;
-      }
-
-      if (layerError) {
-        // routes do not match with a pending error
-        match = false;
-        continue;
-      }
-
-      var method = req.method;
-      var has_method = route._handles_method(method);
-
-      // build up automatic options response
-      if (!has_method && method === 'OPTIONS') {
-        appendMethods(options, route._options());
-      }
-
-      // don't even bother matching route
-      if (!has_method && method !== 'HEAD') {
-        match = false;
-        continue;
-      }
-    }
-
-    // no match
-    if (match !== true) {
-      return done(layerError);
-    }
-
-    // store route for dispatch on change
-    if (route) {
-      req.route = route;
-    }
-
-    // Capture one-time layer values
-    req.params = self.mergeParams
-      ? mergeParams(layer.params, parentParams)
-      : layer.params;
-    var layerPath = layer.path;
-
-    // this should be done for the layer
-    self.process_params(layer, paramcalled, req, res, function (err) {
-      if (err) {
-        return next(layerError || err);
-      }
-
-      if (route) {
-        return layer.handle_request(req, res, next);
-      }
-
-      trim_prefix(layer, layerError, layerPath, path);
-    });
-  }
-
-  function trim_prefix(layer, layerError, layerPath, path) {
-    if (layerPath.length !== 0) {
-      // Validate path breaks on a path separator
-      var c = path[layerPath.length]
-      if (c && c !== '/' && c !== '.') return next(layerError)
-
-      // Trim off the part of the url that matches the route
-      // middleware (.use stuff) needs to have the path stripped
-      debug('trim prefix (%s) from url %s', layerPath, req.url);
-      removed = layerPath;
-      req.url = protohost + req.url.substr(protohost.length + removed.length);
-
-      // Ensure leading slash
-      if (!protohost && req.url[0] !== '/') {
-        req.url = '/' + req.url;
-        slashAdded = true;
-      }
-
-      // Setup base URL (no trailing slash)
-      req.baseUrl = parentUrl + (removed[removed.length - 1] === '/'
-        ? removed.substring(0, removed.length - 1)
-        : removed);
-    }
-
-    debug('%s %s : %s', layer.name, layerPath, req.originalUrl);
-
-    if (layerError) {
-      layer.handle_error(layerError, req, res, next);
-    } else {
-      layer.handle_request(req, res, next);
-    }
-  }
-};
-
-/**
- * Process any parameters for the layer.
- * @private
- */
-
-proto.process_params = function process_params(layer, called, req, res, done) {
-  var params = this.params;
-
-  // captured parameters from the layer, keys and values
-  var keys = layer.keys;
-
-  // fast track
-  if (!keys || keys.length === 0) {
-    return done();
-  }
-
-  var i = 0;
-  var name;
-  var paramIndex = 0;
-  var key;
-  var paramVal;
-  var paramCallbacks;
-  var paramCalled;
-
-  // process params in order
-  // param callbacks can be async
-  function param(err) {
-    if (err) {
-      return done(err);
-    }
-
-    if (i >= keys.length ) {
-      return done();
-    }
-
-    paramIndex = 0;
-    key = keys[i++];
-    name = key.name;
-    paramVal = req.params[name];
-    paramCallbacks = params[name];
-    paramCalled = called[name];
-
-    if (paramVal === undefined || !paramCallbacks) {
-      return param();
-    }
-
-    // param previously called with same value or error occurred
-    if (paramCalled && (paramCalled.match === paramVal
-      || (paramCalled.error && paramCalled.error !== 'route'))) {
-      // restore value
-      req.params[name] = paramCalled.value;
-
-      // next param
-      return param(paramCalled.error);
-    }
-
-    called[name] = paramCalled = {
-      error: null,
-      match: paramVal,
-      value: paramVal
-    };
-
-    paramCallback();
-  }
-
-  // single param callbacks
-  function paramCallback(err) {
-    var fn = paramCallbacks[paramIndex++];
-
-    // store updated value
-    paramCalled.value = req.params[key.name];
-
-    if (err) {
-      // store error
-      paramCalled.error = err;
-      param(err);
-      return;
-    }
-
-    if (!fn) return param();
-
-    try {
-      fn(req, res, paramCallback, paramVal, key.name);
-    } catch (e) {
-      paramCallback(e);
-    }
-  }
-
-  param();
-};
-
-/**
- * Use the given middleware function, with optional path, defaulting to "/".
- *
- * Use (like `.all`) will run for any http METHOD, but it will not add
- * handlers for those methods so OPTIONS requests will not consider `.use`
- * functions even if they could respond.
- *
- * The other difference is that _route_ path is stripped and not visible
- * to the handler function. The main effect of this feature is that mounted
- * handlers can operate without any code changes regardless of the "prefix"
- * pathname.
- *
- * @public
- */
-
-proto.use = function use(fn) {
-  var offset = 0;
-  var path = '/';
-
-  // default path to '/'
-  // disambiguate router.use([fn])
-  if (typeof fn !== 'function') {
-    var arg = fn;
-
-    while (Array.isArray(arg) && arg.length !== 0) {
-      arg = arg[0];
-    }
-
-    // first arg is the path
-    if (typeof arg !== 'function') {
-      offset = 1;
-      path = fn;
-    }
-  }
-
-  var callbacks = flatten(slice.call(arguments, offset));
-
-  if (callbacks.length === 0) {
-    throw new TypeError('Router.use() requires a middleware function')
-  }
-
-  for (var i = 0; i < callbacks.length; i++) {
-    var fn = callbacks[i];
-
-    if (typeof fn !== 'function') {
-      throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
-    }
-
-    // add the middleware
-    debug('use %o %s', path, fn.name || '<anonymous>')
-
-    var layer = new Layer(path, {
-      sensitive: this.caseSensitive,
-      strict: false,
-      end: false
-    }, fn);
-
-    layer.route = undefined;
-
-    this.stack.push(layer);
-  }
-
-  return this;
-};
-
-/**
- * Create a new Route for the given path.
- *
- * Each route contains a separate middleware stack and VERB handlers.
- *
- * See the Route api documentation for details on adding handlers
- * and middleware to routes.
- *
- * @param {String} path
- * @return {Route}
- * @public
- */
-
-proto.route = function route(path) {
-  var route = new Route(path);
-
-  var layer = new Layer(path, {
-    sensitive: this.caseSensitive,
-    strict: this.strict,
-    end: true
-  }, route.dispatch.bind(route));
-
-  layer.route = route;
-
-  this.stack.push(layer);
-  return route;
-};
-
-// create Router#VERB functions
-methods.concat('all').forEach(function(method){
-  proto[method] = function(path){
-    var route = this.route(path)
-    route[method].apply(route, slice.call(arguments, 1));
-    return this;
-  };
-});
-
-// append methods to a list of methods
-function appendMethods(list, addition) {
-  for (var i = 0; i < addition.length; i++) {
-    var method = addition[i];
-    if (list.indexOf(method) === -1) {
-      list.push(method);
-    }
-  }
-}
-
-// get pathname of request
-function getPathname(req) {
-  try {
-    return parseUrl(req).pathname;
-  } catch (err) {
-    return undefined;
-  }
-}
-
-// Get get protocol + host for a URL
-function getProtohost(url) {
-  if (typeof url !== 'string' || url.length === 0 || url[0] === '/') {
-    return undefined
-  }
-
-  var searchIndex = url.indexOf('?')
-  var pathLength = searchIndex !== -1
-    ? searchIndex
-    : url.length
-  var fqdnIndex = url.substr(0, pathLength).indexOf('://')
-
-  return fqdnIndex !== -1
-    ? url.substr(0, url.indexOf('/', 3 + fqdnIndex))
-    : undefined
-}
-
-// get type for error message
-function gettype(obj) {
-  var type = typeof obj;
-
-  if (type !== 'object') {
-    return type;
-  }
-
-  // inspect [[Class]] for objects
-  return toString.call(obj)
-    .replace(objectRegExp, '$1');
-}
-
-/**
- * Match path to a layer.
- *
- * @param {Layer} layer
- * @param {string} path
- * @private
- */
-
-function matchLayer(layer, path) {
-  try {
-    return layer.match(path);
-  } catch (err) {
-    return err;
-  }
-}
-
-// merge params with parent params
-function mergeParams(params, parent) {
-  if (typeof parent !== 'object' || !parent) {
-    return params;
-  }
-
-  // make copy of parent for base
-  var obj = mixin({}, parent);
-
-  // simple non-numeric merging
-  if (!(0 in params) || !(0 in parent)) {
-    return mixin(obj, params);
-  }
-
-  var i = 0;
-  var o = 0;
-
-  // determine numeric gaps
-  while (i in params) {
-    i++;
-  }
-
-  while (o in parent) {
-    o++;
-  }
-
-  // offset numeric indices in params before merge
-  for (i--; i >= 0; i--) {
-    params[i + o] = params[i];
-
-    // create holes for the merge when necessary
-    if (i < o) {
-      delete params[i];
-    }
-  }
-
-  return mixin(obj, params);
-}
-
-// restore obj props after function
-function restore(fn, obj) {
-  var props = new Array(arguments.length - 2);
-  var vals = new Array(arguments.length - 2);
-
-  for (var i = 0; i < props.length; i++) {
-    props[i] = arguments[i + 2];
-    vals[i] = obj[props[i]];
-  }
-
-  return function () {
-    // restore vals
-    for (var i = 0; i < props.length; i++) {
-      obj[props[i]] = vals[i];
-    }
-
-    return fn.apply(this, arguments);
-  };
-}
-
-// send an OPTIONS response
-function sendOptionsResponse(res, options, next) {
-  try {
-    var body = options.join(',');
-    res.set('Allow', body);
-    res.send(body);
-  } catch (err) {
-    next(err);
-  }
-}
-
-// wrap a function
-function wrap(old, fn) {
-  return function proxy() {
-    var args = new Array(arguments.length + 1);
-
-    args[0] = old;
-    for (var i = 0, len = arguments.length; i < len; i++) {
-      args[i + 1] = arguments[i];
-    }
-
-    fn.apply(this, args);
-  };
-}
+"use strict";var Route=require("./route"),Layer=require("./layer"),methods=require("methods"),mixin=require("utils-merge"),debug=require("debug")("express:router"),deprecate=require("depd")("express"),flatten=require("array-flatten"),parseUrl=require("parseurl"),setPrototypeOf=require("setprototypeof"),objectRegExp=/^\[object (\S+)\]$/,slice=Array.prototype.slice,toString=Object.prototype.toString,proto=module.exports=function(r){var e=r||{};function t(r,e,n){t.handle(r,e,n)}return setPrototypeOf(t,proto),t.params={},t._params=[],t.caseSensitive=e.caseSensitive,t.mergeParams=e.mergeParams,t.strict=e.strict,t.stack=[],t};function appendMethods(r,e){for(var t=0;t<e.length;t++){var n=e[t];-1===r.indexOf(n)&&r.push(n)}}function getPathname(r){try{return parseUrl(r).pathname}catch(r){return}}function getProtohost(r){if("string"==typeof r&&0!==r.length&&"/"!==r[0]){var e=r.indexOf("?"),t=-1!==e?e:r.length,n=r.substr(0,t).indexOf("://");return-1!==n?r.substr(0,r.indexOf("/",3+n)):void 0}}function gettype(r){var e=typeof r;return"object"!==e?e:toString.call(r).replace(objectRegExp,"$1")}function matchLayer(r,e){try{return r.match(e)}catch(r){return r}}function mergeParams(r,e){if("object"!=typeof e||!e)return r;var t=mixin({},e);if(!(0 in r)||!(0 in e))return mixin(t,r);for(var n=0,a=0;n in r;)n++;for(;a in e;)a++;for(n--;n>=0;n--)r[n+a]=r[n],n<a&&delete r[n];return mixin(t,r)}function restore(r,e){for(var t=new Array(arguments.length-2),n=new Array(arguments.length-2),a=0;a<t.length;a++)t[a]=arguments[a+2],n[a]=e[t[a]];return function(){for(var a=0;a<t.length;a++)e[t[a]]=n[a];return r.apply(this,arguments)}}function sendOptionsResponse(r,e,t){try{var n=e.join(",");r.set("Allow",n),r.send(n)}catch(r){t(r)}}function wrap(r,e){return function(){var t=new Array(arguments.length+1);t[0]=r;for(var n=0,a=arguments.length;n<a;n++)t[n+1]=arguments[n];e.apply(this,t)}}proto.param=function(r,e){if("function"==typeof r)return deprecate("router.param(fn): Refactor to use path params"),void this._params.push(r);var t,n=this._params,a=n.length;":"===r[0]&&(deprecate("router.param("+JSON.stringify(r)+", fn): Use router.param("+JSON.stringify(r.substr(1))+", fn) instead"),r=r.substr(1));for(var o=0;o<a;++o)(t=n[o](r,e))&&(e=t);if("function"!=typeof e)throw new Error("invalid param() call for "+r+", got "+e);return(this.params[r]=this.params[r]||[]).push(e),this},proto.handle=function(r,e,t){var n=this;debug("dispatching %s %s",r.method,r.url);var a=0,o=getProtohost(r.url)||"",s="",i=!1,u={},l=[],p=n.stack,f=r.params,c=r.baseUrl||"",h=restore(t,r,"baseUrl","next","params");function m(t){var g="route"===t?null:t;if(i&&(r.url=r.url.substr(1),i=!1),0!==s.length&&(r.baseUrl=c,r.url=o+s+r.url.substr(o.length),s=""),"router"!==g)if(a>=p.length)setImmediate(h,g);else{var d,v,y,b=getPathname(r);if(null==b)return h(g);for(;!0!==v&&a<p.length;)if(v=matchLayer(d=p[a++],b),y=d.route,"boolean"!=typeof v&&(g=g||v),!0===v&&y)if(g)v=!1;else{var w=r.method,x=y._handles_method(w);x||"OPTIONS"!==w||appendMethods(l,y._options()),x||"HEAD"===w||(v=!1)}if(!0!==v)return h(g);y&&(r.route=y),r.params=n.mergeParams?mergeParams(d.params,f):d.params;var O=d.path;n.process_params(d,u,r,e,(function(t){return t?m(g||t):y?d.handle_request(r,e,m):void function(t,n,a,u){if(0!==a.length){var l=u[a.length];if(l&&"/"!==l&&"."!==l)return m(n);debug("trim prefix (%s) from url %s",a,r.url),s=a,r.url=o+r.url.substr(o.length+s.length),o||"/"===r.url[0]||(r.url="/"+r.url,i=!0),r.baseUrl=c+("/"===s[s.length-1]?s.substring(0,s.length-1):s)}debug("%s %s : %s",t.name,a,r.originalUrl),n?t.handle_error(n,r,e,m):t.handle_request(r,e,m)}(d,g,O,b)}))}else setImmediate(h,null)}r.next=m,"OPTIONS"===r.method&&(h=wrap(h,(function(r,t){if(t||0===l.length)return r(t);sendOptionsResponse(e,l,r)}))),r.baseUrl=c,r.originalUrl=r.originalUrl||r.url,m()},proto.process_params=function(r,e,t,n,a){var o=this.params,s=r.keys;if(!s||0===s.length)return a();var i,u,l,p,f,c=0,h=0;function m(r){return r?a(r):c>=s.length?a():(h=0,u=s[c++],i=u.name,l=t.params[i],p=o[i],f=e[i],void 0!==l&&p?f&&(f.match===l||f.error&&"route"!==f.error)?(t.params[i]=f.value,m(f.error)):(e[i]=f={error:null,match:l,value:l},void g()):m())}function g(r){var e=p[h++];if(f.value=t.params[u.name],r)return f.error=r,void m(r);if(!e)return m();try{e(t,n,g,l,u.name)}catch(r){g(r)}}m()},proto.use=function(r){var e=0,t="/";if("function"!=typeof r){for(var n=r;Array.isArray(n)&&0!==n.length;)n=n[0];"function"!=typeof n&&(e=1,t=r)}var a=flatten(slice.call(arguments,e));if(0===a.length)throw new TypeError("Router.use() requires a middleware function");for(var o=0;o<a.length;o++){if("function"!=typeof(r=a[o]))throw new TypeError("Router.use() requires a middleware function but got a "+gettype(r));debug("use %o %s",t,r.name||"<anonymous>");var s=new Layer(t,{sensitive:this.caseSensitive,strict:!1,end:!1},r);s.route=void 0,this.stack.push(s)}return this},proto.route=function(r){var e=new Route(r),t=new Layer(r,{sensitive:this.caseSensitive,strict:this.strict,end:!0},e.dispatch.bind(e));return t.route=e,this.stack.push(t),e},methods.concat("all").forEach((function(r){proto[r]=function(e){var t=this.route(e);return t[r].apply(t,slice.call(arguments,1)),this}}));
\ No newline at end of file
index 4dc8e86..3c03d20 100644 (file)
@@ -5,177 +5,4 @@
  * Copyright(c) 2014-2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict';
-
-/**
- * Module dependencies.
- * @private
- */
-
-var pathRegexp = require('path-to-regexp');
-var debug = require('debug')('express:router:layer');
-
-/**
- * Module variables.
- * @private
- */
-
-var hasOwnProperty = Object.prototype.hasOwnProperty;
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = Layer;
-
-function Layer(path, options, fn) {
-  if (!(this instanceof Layer)) {
-    return new Layer(path, options, fn);
-  }
-
-  debug('new %o', path)
-  var opts = options || {};
-
-  this.handle = fn;
-  this.name = fn.name || '<anonymous>';
-  this.params = undefined;
-  this.path = undefined;
-  this.regexp = pathRegexp(path, this.keys = [], opts);
-
-  // set fast path flags
-  this.regexp.fast_star = path === '*'
-  this.regexp.fast_slash = path === '/' && opts.end === false
-}
-
-/**
- * Handle the error for the layer.
- *
- * @param {Error} error
- * @param {Request} req
- * @param {Response} res
- * @param {function} next
- * @api private
- */
-
-Layer.prototype.handle_error = function handle_error(error, req, res, next) {
-  var fn = this.handle;
-
-  if (fn.length !== 4) {
-    // not a standard error handler
-    return next(error);
-  }
-
-  try {
-    fn(error, req, res, next);
-  } catch (err) {
-    next(err);
-  }
-};
-
-/**
- * Handle the request for the layer.
- *
- * @param {Request} req
- * @param {Response} res
- * @param {function} next
- * @api private
- */
-
-Layer.prototype.handle_request = function handle(req, res, next) {
-  var fn = this.handle;
-
-  if (fn.length > 3) {
-    // not a standard request handler
-    return next();
-  }
-
-  try {
-    fn(req, res, next);
-  } catch (err) {
-    next(err);
-  }
-};
-
-/**
- * Check if this route matches `path`, if so
- * populate `.params`.
- *
- * @param {String} path
- * @return {Boolean}
- * @api private
- */
-
-Layer.prototype.match = function match(path) {
-  var match
-
-  if (path != null) {
-    // fast path non-ending match for / (any path matches)
-    if (this.regexp.fast_slash) {
-      this.params = {}
-      this.path = ''
-      return true
-    }
-
-    // fast path for * (everything matched in a param)
-    if (this.regexp.fast_star) {
-      this.params = {'0': decode_param(path)}
-      this.path = path
-      return true
-    }
-
-    // match the path
-    match = this.regexp.exec(path)
-  }
-
-  if (!match) {
-    this.params = undefined;
-    this.path = undefined;
-    return false;
-  }
-
-  // store values
-  this.params = {};
-  this.path = match[0]
-
-  var keys = this.keys;
-  var params = this.params;
-
-  for (var i = 1; i < match.length; i++) {
-    var key = keys[i - 1];
-    var prop = key.name;
-    var val = decode_param(match[i])
-
-    if (val !== undefined || !(hasOwnProperty.call(params, prop))) {
-      params[prop] = val;
-    }
-  }
-
-  return true;
-};
-
-/**
- * Decode param value.
- *
- * @param {string} val
- * @return {string}
- * @private
- */
-
-function decode_param(val) {
-  if (typeof val !== 'string' || val.length === 0) {
-    return val;
-  }
-
-  try {
-    return decodeURIComponent(val);
-  } catch (err) {
-    if (err instanceof URIError) {
-      err.message = 'Failed to decode param \'' + val + '\'';
-      err.status = err.statusCode = 400;
-    }
-
-    throw err;
-  }
-}
+"use strict";var pathRegexp=require("path-to-regexp"),debug=require("debug")("express:router:layer"),hasOwnProperty=Object.prototype.hasOwnProperty;function Layer(e,t,r){if(!(this instanceof Layer))return new Layer(e,t,r);debug("new %o",e);var a=t||{};this.handle=r,this.name=r.name||"<anonymous>",this.params=void 0,this.path=void 0,this.regexp=pathRegexp(e,this.keys=[],a),this.regexp.fast_star="*"===e,this.regexp.fast_slash="/"===e&&!1===a.end}function decode_param(e){if("string"!=typeof e||0===e.length)return e;try{return decodeURIComponent(e)}catch(t){throw t instanceof URIError&&(t.message="Failed to decode param '"+e+"'",t.status=t.statusCode=400),t}}module.exports=Layer,Layer.prototype.handle_error=function(e,t,r,a){var s=this.handle;if(4!==s.length)return a(e);try{s(e,t,r,a)}catch(e){a(e)}},Layer.prototype.handle_request=function(e,t,r){var a=this.handle;if(a.length>3)return r();try{a(e,t,r)}catch(e){r(e)}},Layer.prototype.match=function(e){var t;if(null!=e){if(this.regexp.fast_slash)return this.params={},this.path="",!0;if(this.regexp.fast_star)return this.params={0:decode_param(e)},this.path=e,!0;t=this.regexp.exec(e)}if(!t)return this.params=void 0,this.path=void 0,!1;this.params={},this.path=t[0];for(var r=this.keys,a=this.params,s=1;s<t.length;s++){var h=r[s-1].name,i=decode_param(t[s]);void 0===i&&hasOwnProperty.call(a,h)||(a[h]=i)}return!0};
\ No newline at end of file
index 178df0d..f08ebb2 100644 (file)
@@ -5,212 +5,4 @@
  * Copyright(c) 2014-2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict';
-
-/**
- * Module dependencies.
- * @private
- */
-
-var debug = require('debug')('express:router:route');
-var flatten = require('array-flatten');
-var Layer = require('./layer');
-var methods = require('methods');
-
-/**
- * Module variables.
- * @private
- */
-
-var slice = Array.prototype.slice;
-var toString = Object.prototype.toString;
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = Route;
-
-/**
- * Initialize `Route` with the given `path`,
- *
- * @param {String} path
- * @public
- */
-
-function Route(path) {
-  this.path = path;
-  this.stack = [];
-
-  debug('new %o', path)
-
-  // route handlers for various http methods
-  this.methods = {};
-}
-
-/**
- * Determine if the route handles a given method.
- * @private
- */
-
-Route.prototype._handles_method = function _handles_method(method) {
-  if (this.methods._all) {
-    return true;
-  }
-
-  var name = method.toLowerCase();
-
-  if (name === 'head' && !this.methods['head']) {
-    name = 'get';
-  }
-
-  return Boolean(this.methods[name]);
-};
-
-/**
- * @return {Array} supported HTTP methods
- * @private
- */
-
-Route.prototype._options = function _options() {
-  var methods = Object.keys(this.methods);
-
-  // append automatic head
-  if (this.methods.get && !this.methods.head) {
-    methods.push('head');
-  }
-
-  for (var i = 0; i < methods.length; i++) {
-    // make upper case
-    methods[i] = methods[i].toUpperCase();
-  }
-
-  return methods;
-};
-
-/**
- * dispatch req, res into this route
- * @private
- */
-
-Route.prototype.dispatch = function dispatch(req, res, done) {
-  var idx = 0;
-  var stack = this.stack;
-  if (stack.length === 0) {
-    return done();
-  }
-
-  var method = req.method.toLowerCase();
-  if (method === 'head' && !this.methods['head']) {
-    method = 'get';
-  }
-
-  req.route = this;
-
-  next();
-
-  function next(err) {
-    // signal to exit route
-    if (err && err === 'route') {
-      return done();
-    }
-
-    // signal to exit router
-    if (err && err === 'router') {
-      return done(err)
-    }
-
-    var layer = stack[idx++];
-    if (!layer) {
-      return done(err);
-    }
-
-    if (layer.method && layer.method !== method) {
-      return next(err);
-    }
-
-    if (err) {
-      layer.handle_error(err, req, res, next);
-    } else {
-      layer.handle_request(req, res, next);
-    }
-  }
-};
-
-/**
- * Add a handler for all HTTP verbs to this route.
- *
- * Behaves just like middleware and can respond or call `next`
- * to continue processing.
- *
- * You can use multiple `.all` call to add multiple handlers.
- *
- *   function check_something(req, res, next){
- *     next();
- *   };
- *
- *   function validate_user(req, res, next){
- *     next();
- *   };
- *
- *   route
- *   .all(validate_user)
- *   .all(check_something)
- *   .get(function(req, res, next){
- *     res.send('hello world');
- *   });
- *
- * @param {function} handler
- * @return {Route} for chaining
- * @api public
- */
-
-Route.prototype.all = function all() {
-  var handles = flatten(slice.call(arguments));
-
-  for (var i = 0; i < handles.length; i++) {
-    var handle = handles[i];
-
-    if (typeof handle !== 'function') {
-      var type = toString.call(handle);
-      var msg = 'Route.all() requires a callback function but got a ' + type
-      throw new TypeError(msg);
-    }
-
-    var layer = Layer('/', {}, handle);
-    layer.method = undefined;
-
-    this.methods._all = true;
-    this.stack.push(layer);
-  }
-
-  return this;
-};
-
-methods.forEach(function(method){
-  Route.prototype[method] = function(){
-    var handles = flatten(slice.call(arguments));
-
-    for (var i = 0; i < handles.length; i++) {
-      var handle = handles[i];
-
-      if (typeof handle !== 'function') {
-        var type = toString.call(handle);
-        var msg = 'Route.' + method + '() requires a callback function but got a ' + type
-        throw new Error(msg);
-      }
-
-      debug('%s %o', method, this.path)
-
-      var layer = Layer('/', {}, handle);
-      layer.method = method;
-
-      this.methods[method] = true;
-      this.stack.push(layer);
-    }
-
-    return this;
-  };
-});
+"use strict";var debug=require("debug")("express:router:route"),flatten=require("array-flatten"),Layer=require("./layer"),methods=require("methods"),slice=Array.prototype.slice,toString=Object.prototype.toString;function Route(t){this.path=t,this.stack=[],debug("new %o",t),this.methods={}}module.exports=Route,Route.prototype._handles_method=function(t){if(this.methods._all)return!0;var e=t.toLowerCase();return"head"!==e||this.methods.head||(e="get"),Boolean(this.methods[e])},Route.prototype._options=function(){var t=Object.keys(this.methods);this.methods.get&&!this.methods.head&&t.push("head");for(var e=0;e<t.length;e++)t[e]=t[e].toUpperCase();return t},Route.prototype.dispatch=function(t,e,r){var o=0,a=this.stack;if(0===a.length)return r();var h=t.method.toLowerCase();"head"!==h||this.methods.head||(h="get"),t.route=this,function s(i){if(i&&"route"===i)return r();if(i&&"router"===i)return r(i);var n=a[o++];if(!n)return r(i);if(n.method&&n.method!==h)return s(i);i?n.handle_error(i,t,e,s):n.handle_request(t,e,s)}()},Route.prototype.all=function(){for(var t=flatten(slice.call(arguments)),e=0;e<t.length;e++){var r=t[e];if("function"!=typeof r){var o=toString.call(r),a="Route.all() requires a callback function but got a "+o;throw new TypeError(a)}var h=Layer("/",{},r);h.method=void 0,this.methods._all=!0,this.stack.push(h)}return this},methods.forEach((function(t){Route.prototype[t]=function(){for(var e=flatten(slice.call(arguments)),r=0;r<e.length;r++){var o=e[r];if("function"!=typeof o){var a=toString.call(o),h="Route."+t+"() requires a callback function but got a "+a;throw new Error(h)}debug("%s %o",t,this.path);var s=Layer("/",{},o);s.method=t,this.methods[t]=!0,this.stack.push(s)}return this}}));
\ No newline at end of file
index bd81ac7..d886165 100644 (file)
@@ -4,303 +4,4 @@
  * Copyright(c) 2014-2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict';
-
-/**
- * Module dependencies.
- * @api private
- */
-
-var Buffer = require('safe-buffer').Buffer
-var contentDisposition = require('content-disposition');
-var contentType = require('content-type');
-var deprecate = require('depd')('express');
-var flatten = require('array-flatten');
-var mime = require('send').mime;
-var etag = require('etag');
-var proxyaddr = require('proxy-addr');
-var qs = require('qs');
-var querystring = require('querystring');
-
-/**
- * Return strong ETag for `body`.
- *
- * @param {String|Buffer} body
- * @param {String} [encoding]
- * @return {String}
- * @api private
- */
-
-exports.etag = createETagGenerator({ weak: false })
-
-/**
- * Return weak ETag for `body`.
- *
- * @param {String|Buffer} body
- * @param {String} [encoding]
- * @return {String}
- * @api private
- */
-
-exports.wetag = createETagGenerator({ weak: true })
-
-/**
- * Check if `path` looks absolute.
- *
- * @param {String} path
- * @return {Boolean}
- * @api private
- */
-
-exports.isAbsolute = function(path){
-  if ('/' === path[0]) return true;
-  if (':' === path[1] && ('\\' === path[2] || '/' === path[2])) return true; // Windows device path
-  if ('\\\\' === path.substring(0, 2)) return true; // Microsoft Azure absolute path
-};
-
-/**
- * Flatten the given `arr`.
- *
- * @param {Array} arr
- * @return {Array}
- * @api private
- */
-
-exports.flatten = deprecate.function(flatten,
-  'utils.flatten: use array-flatten npm module instead');
-
-/**
- * Normalize the given `type`, for example "html" becomes "text/html".
- *
- * @param {String} type
- * @return {Object}
- * @api private
- */
-
-exports.normalizeType = function(type){
-  return ~type.indexOf('/')
-    ? acceptParams(type)
-    : { value: mime.lookup(type), params: {} };
-};
-
-/**
- * Normalize `types`, for example "html" becomes "text/html".
- *
- * @param {Array} types
- * @return {Array}
- * @api private
- */
-
-exports.normalizeTypes = function(types){
-  var ret = [];
-
-  for (var i = 0; i < types.length; ++i) {
-    ret.push(exports.normalizeType(types[i]));
-  }
-
-  return ret;
-};
-
-/**
- * Generate Content-Disposition header appropriate for the filename.
- * non-ascii filenames are urlencoded and a filename* parameter is added
- *
- * @param {String} filename
- * @return {String}
- * @api private
- */
-
-exports.contentDisposition = deprecate.function(contentDisposition,
-  'utils.contentDisposition: use content-disposition npm module instead');
-
-/**
- * Parse accept params `str` returning an
- * object with `.value`, `.quality` and `.params`.
- * also includes `.originalIndex` for stable sorting
- *
- * @param {String} str
- * @return {Object}
- * @api private
- */
-
-function acceptParams(str, index) {
-  var parts = str.split(/ *; */);
-  var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index };
-
-  for (var i = 1; i < parts.length; ++i) {
-    var pms = parts[i].split(/ *= */);
-    if ('q' === pms[0]) {
-      ret.quality = parseFloat(pms[1]);
-    } else {
-      ret.params[pms[0]] = pms[1];
-    }
-  }
-
-  return ret;
-}
-
-/**
- * Compile "etag" value to function.
- *
- * @param  {Boolean|String|Function} val
- * @return {Function}
- * @api private
- */
-
-exports.compileETag = function(val) {
-  var fn;
-
-  if (typeof val === 'function') {
-    return val;
-  }
-
-  switch (val) {
-    case true:
-      fn = exports.wetag;
-      break;
-    case false:
-      break;
-    case 'strong':
-      fn = exports.etag;
-      break;
-    case 'weak':
-      fn = exports.wetag;
-      break;
-    default:
-      throw new TypeError('unknown value for etag function: ' + val);
-  }
-
-  return fn;
-}
-
-/**
- * Compile "query parser" value to function.
- *
- * @param  {String|Function} val
- * @return {Function}
- * @api private
- */
-
-exports.compileQueryParser = function compileQueryParser(val) {
-  var fn;
-
-  if (typeof val === 'function') {
-    return val;
-  }
-
-  switch (val) {
-    case true:
-      fn = querystring.parse;
-      break;
-    case false:
-      fn = newObject;
-      break;
-    case 'extended':
-      fn = parseExtendedQueryString;
-      break;
-    case 'simple':
-      fn = querystring.parse;
-      break;
-    default:
-      throw new TypeError('unknown value for query parser function: ' + val);
-  }
-
-  return fn;
-}
-
-/**
- * Compile "proxy trust" value to function.
- *
- * @param  {Boolean|String|Number|Array|Function} val
- * @return {Function}
- * @api private
- */
-
-exports.compileTrust = function(val) {
-  if (typeof val === 'function') return val;
-
-  if (val === true) {
-    // Support plain true/false
-    return function(){ return true };
-  }
-
-  if (typeof val === 'number') {
-    // Support trusting hop count
-    return function(a, i){ return i < val };
-  }
-
-  if (typeof val === 'string') {
-    // Support comma-separated values
-    val = val.split(/ *, */);
-  }
-
-  return proxyaddr.compile(val || []);
-}
-
-/**
- * Set the charset in a given Content-Type string.
- *
- * @param {String} type
- * @param {String} charset
- * @return {String}
- * @api private
- */
-
-exports.setCharset = function setCharset(type, charset) {
-  if (!type || !charset) {
-    return type;
-  }
-
-  // parse type
-  var parsed = contentType.parse(type);
-
-  // set charset
-  parsed.parameters.charset = charset;
-
-  // format type
-  return contentType.format(parsed);
-};
-
-/**
- * Create an ETag generator function, generating ETags with
- * the given options.
- *
- * @param {object} options
- * @return {function}
- * @private
- */
-
-function createETagGenerator (options) {
-  return function generateETag (body, encoding) {
-    var buf = !Buffer.isBuffer(body)
-      ? Buffer.from(body, encoding)
-      : body
-
-    return etag(buf, options)
-  }
-}
-
-/**
- * Parse an extended query string with qs.
- *
- * @return {Object}
- * @private
- */
-
-function parseExtendedQueryString(str) {
-  return qs.parse(str, {
-    allowPrototypes: true
-  });
-}
-
-/**
- * Return new empty object.
- *
- * @return {Object}
- * @api private
- */
-
-function newObject() {
-  return {};
-}
+"use strict";var Buffer=require("safe-buffer").Buffer,contentDisposition=require("content-disposition"),contentType=require("content-type"),deprecate=require("depd")("express"),flatten=require("array-flatten"),mime=require("send").mime,etag=require("etag"),proxyaddr=require("proxy-addr"),qs=require("qs"),querystring=require("querystring");function acceptParams(e,r){for(var t=e.split(/ *; */),n={value:t[0],quality:1,params:{},originalIndex:r},a=1;a<t.length;++a){var o=t[a].split(/ *= */);"q"===o[0]?n.quality=parseFloat(o[1]):n.params[o[0]]=o[1]}return n}function createETagGenerator(e){return function(r,t){var n=Buffer.isBuffer(r)?r:Buffer.from(r,t);return etag(n,e)}}function parseExtendedQueryString(e){return qs.parse(e,{allowPrototypes:!0})}function newObject(){return{}}exports.etag=createETagGenerator({weak:!1}),exports.wetag=createETagGenerator({weak:!0}),exports.isAbsolute=function(e){return"/"===e[0]||(":"===e[1]&&("\\"===e[2]||"/"===e[2])||("\\\\"===e.substring(0,2)||void 0))},exports.flatten=deprecate.function(flatten,"utils.flatten: use array-flatten npm module instead"),exports.normalizeType=function(e){return~e.indexOf("/")?acceptParams(e):{value:mime.lookup(e),params:{}}},exports.normalizeTypes=function(e){for(var r=[],t=0;t<e.length;++t)r.push(exports.normalizeType(e[t]));return r},exports.contentDisposition=deprecate.function(contentDisposition,"utils.contentDisposition: use content-disposition npm module instead"),exports.compileETag=function(e){var r;if("function"==typeof e)return e;switch(e){case!0:r=exports.wetag;break;case!1:break;case"strong":r=exports.etag;break;case"weak":r=exports.wetag;break;default:throw new TypeError("unknown value for etag function: "+e)}return r},exports.compileQueryParser=function(e){var r;if("function"==typeof e)return e;switch(e){case!0:r=querystring.parse;break;case!1:r=newObject;break;case"extended":r=parseExtendedQueryString;break;case"simple":r=querystring.parse;break;default:throw new TypeError("unknown value for query parser function: "+e)}return r},exports.compileTrust=function(e){return"function"==typeof e?e:!0===e?function(){return!0}:"number"==typeof e?function(r,t){return t<e}:("string"==typeof e&&(e=e.split(/ *, */)),proxyaddr.compile(e||[]))},exports.setCharset=function(e,r){if(!e||!r)return e;var t=contentType.parse(e);return t.parameters.charset=r,contentType.format(t)};
\ No newline at end of file
index cf101ca..d8742e8 100644 (file)
@@ -5,178 +5,4 @@
  * Copyright(c) 2014-2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict';
-
-/**
- * Module dependencies.
- * @private
- */
-
-var debug = require('debug')('express:view');
-var path = require('path');
-var fs = require('fs');
-
-/**
- * Module variables.
- * @private
- */
-
-var dirname = path.dirname;
-var basename = path.basename;
-var extname = path.extname;
-var join = path.join;
-var resolve = path.resolve;
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = View;
-
-/**
- * Initialize a new `View` with the given `name`.
- *
- * Options:
- *
- *   - `defaultEngine` the default template engine name
- *   - `engines` template engine require() cache
- *   - `root` root path for view lookup
- *
- * @param {string} name
- * @param {object} options
- * @public
- */
-
-function View(name, options) {
-  var opts = options || {};
-
-  this.defaultEngine = opts.defaultEngine;
-  this.ext = extname(name);
-  this.name = name;
-  this.root = opts.root;
-
-  if (!this.ext && !this.defaultEngine) {
-    throw new Error('No default engine was specified and no extension was provided.');
-  }
-
-  var fileName = name;
-
-  if (!this.ext) {
-    // get extension from default engine name
-    this.ext = this.defaultEngine[0] !== '.'
-      ? '.' + this.defaultEngine
-      : this.defaultEngine;
-
-    fileName += this.ext;
-  }
-
-  if (!opts.engines[this.ext]) {
-    // load engine
-    var mod = this.ext.substr(1)
-    debug('require "%s"', mod)
-
-    // default engine export
-    var fn = require(mod).__express
-
-    if (typeof fn !== 'function') {
-      throw new Error('Module "' + mod + '" does not provide a view engine.')
-    }
-
-    opts.engines[this.ext] = fn
-  }
-
-  // store loaded engine
-  this.engine = opts.engines[this.ext];
-
-  // lookup path
-  this.path = this.lookup(fileName);
-}
-
-/**
- * Lookup view by the given `name`
- *
- * @param {string} name
- * @private
- */
-
-View.prototype.lookup = function lookup(name) {
-  var path;
-  var roots = [].concat(this.root);
-
-  debug('lookup "%s"', name);
-
-  for (var i = 0; i < roots.length && !path; i++) {
-    var root = roots[i];
-
-    // resolve the path
-    var loc = resolve(root, name);
-    var dir = dirname(loc);
-    var file = basename(loc);
-
-    // resolve the file
-    path = this.resolve(dir, file);
-  }
-
-  return path;
-};
-
-/**
- * Render with the given options.
- *
- * @param {object} options
- * @param {function} callback
- * @private
- */
-
-View.prototype.render = function render(options, callback) {
-  debug('render "%s"', this.path);
-  this.engine(this.path, options, callback);
-};
-
-/**
- * Resolve the file within the given directory.
- *
- * @param {string} dir
- * @param {string} file
- * @private
- */
-
-View.prototype.resolve = function resolve(dir, file) {
-  var ext = this.ext;
-
-  // <path>.<ext>
-  var path = join(dir, file);
-  var stat = tryStat(path);
-
-  if (stat && stat.isFile()) {
-    return path;
-  }
-
-  // <path>/index.<ext>
-  path = join(dir, basename(file, ext), 'index' + ext);
-  stat = tryStat(path);
-
-  if (stat && stat.isFile()) {
-    return path;
-  }
-};
-
-/**
- * Return a stat, maybe.
- *
- * @param {string} path
- * @return {fs.Stats}
- * @private
- */
-
-function tryStat(path) {
-  debug('stat "%s"', path);
-
-  try {
-    return fs.statSync(path);
-  } catch (e) {
-    return undefined;
-  }
-}
+"use strict";var debug=require("debug")("express:view"),path=require("path"),fs=require("fs"),dirname=path.dirname,basename=path.basename,extname=path.extname,join=path.join,resolve=path.resolve;function View(e,t){var i=t||{};if(this.defaultEngine=i.defaultEngine,this.ext=extname(e),this.name=e,this.root=i.root,!this.ext&&!this.defaultEngine)throw new Error("No default engine was specified and no extension was provided.");var n=e;if(this.ext||(this.ext="."!==this.defaultEngine[0]?"."+this.defaultEngine:this.defaultEngine,n+=this.ext),!i.engines[this.ext]){var r=this.ext.substr(1);debug('require "%s"',r);var s=require(r).__express;if("function"!=typeof s)throw new Error('Module "'+r+'" does not provide a view engine.');i.engines[this.ext]=s}this.engine=i.engines[this.ext],this.path=this.lookup(n)}function tryStat(e){debug('stat "%s"',e);try{return fs.statSync(e)}catch(e){return}}module.exports=View,View.prototype.lookup=function(e){var t,i=[].concat(this.root);debug('lookup "%s"',e);for(var n=0;n<i.length&&!t;n++){var r=i[n],s=resolve(r,e),a=dirname(s),o=basename(s);t=this.resolve(a,o)}return t},View.prototype.render=function(e,t){debug('render "%s"',this.path),this.engine(this.path,e,t)},View.prototype.resolve=function(e,t){var i=this.ext,n=join(e,t),r=tryStat(n);return r&&r.isFile()||(r=tryStat(n=join(e,basename(t,i),"index"+i)))&&r.isFile()?n:void 0};
\ No newline at end of file
index 5673507..e69d629 100644 (file)
@@ -3,329 +3,4 @@
  * Copyright(c) 2014-2017 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module dependencies.
- * @private
- */
-
-var debug = require('debug')('finalhandler')
-var encodeUrl = require('encodeurl')
-var escapeHtml = require('escape-html')
-var onFinished = require('on-finished')
-var parseUrl = require('parseurl')
-var statuses = require('statuses')
-var unpipe = require('unpipe')
-
-/**
- * Module variables.
- * @private
- */
-
-var DOUBLE_SPACE_REGEXP = /\x20{2}/g
-var NEWLINE_REGEXP = /\n/g
-
-/* istanbul ignore next */
-var defer = typeof setImmediate === 'function'
-  ? setImmediate
-  : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) }
-var isFinished = onFinished.isFinished
-
-/**
- * Create a minimal HTML document.
- *
- * @param {string} message
- * @private
- */
-
-function createHtmlDocument (message) {
-  var body = escapeHtml(message)
-    .replace(NEWLINE_REGEXP, '<br>')
-    .replace(DOUBLE_SPACE_REGEXP, ' &nbsp;')
-
-  return '<!DOCTYPE html>\n' +
-    '<html lang="en">\n' +
-    '<head>\n' +
-    '<meta charset="utf-8">\n' +
-    '<title>Error</title>\n' +
-    '</head>\n' +
-    '<body>\n' +
-    '<pre>' + body + '</pre>\n' +
-    '</body>\n' +
-    '</html>\n'
-}
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = finalhandler
-
-/**
- * Create a function to handle the final response.
- *
- * @param {Request} req
- * @param {Response} res
- * @param {Object} [options]
- * @return {Function}
- * @public
- */
-
-function finalhandler (req, res, options) {
-  var opts = options || {}
-
-  // get environment
-  var env = opts.env || process.env.NODE_ENV || 'development'
-
-  // get error callback
-  var onerror = opts.onerror
-
-  return function (err) {
-    var headers
-    var msg
-    var status
-
-    // ignore 404 on in-flight response
-    if (!err && headersSent(res)) {
-      debug('cannot 404 after headers sent')
-      return
-    }
-
-    // unhandled error
-    if (err) {
-      // respect status code from error
-      status = getErrorStatusCode(err)
-
-      if (status === undefined) {
-        // fallback to status code on response
-        status = getResponseStatusCode(res)
-      } else {
-        // respect headers from error
-        headers = getErrorHeaders(err)
-      }
-
-      // get error message
-      msg = getErrorMessage(err, status, env)
-    } else {
-      // not found
-      status = 404
-      msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req))
-    }
-
-    debug('default %s', status)
-
-    // schedule onerror callback
-    if (err && onerror) {
-      defer(onerror, err, req, res)
-    }
-
-    // cannot actually respond
-    if (headersSent(res)) {
-      debug('cannot %d after headers sent', status)
-      req.socket.destroy()
-      return
-    }
-
-    // send response
-    send(req, res, status, headers, msg)
-  }
-}
-
-/**
- * Get headers from Error object.
- *
- * @param {Error} err
- * @return {object}
- * @private
- */
-
-function getErrorHeaders (err) {
-  if (!err.headers || typeof err.headers !== 'object') {
-    return undefined
-  }
-
-  var headers = Object.create(null)
-  var keys = Object.keys(err.headers)
-
-  for (var i = 0; i < keys.length; i++) {
-    var key = keys[i]
-    headers[key] = err.headers[key]
-  }
-
-  return headers
-}
-
-/**
- * Get message from Error object, fallback to status message.
- *
- * @param {Error} err
- * @param {number} status
- * @param {string} env
- * @return {string}
- * @private
- */
-
-function getErrorMessage (err, status, env) {
-  var msg
-
-  if (env !== 'production') {
-    // use err.stack, which typically includes err.message
-    msg = err.stack
-
-    // fallback to err.toString() when possible
-    if (!msg && typeof err.toString === 'function') {
-      msg = err.toString()
-    }
-  }
-
-  return msg || statuses[status]
-}
-
-/**
- * Get status code from Error object.
- *
- * @param {Error} err
- * @return {number}
- * @private
- */
-
-function getErrorStatusCode (err) {
-  // check err.status
-  if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) {
-    return err.status
-  }
-
-  // check err.statusCode
-  if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) {
-    return err.statusCode
-  }
-
-  return undefined
-}
-
-/**
- * Get resource name for the request.
- *
- * This is typically just the original pathname of the request
- * but will fallback to "resource" is that cannot be determined.
- *
- * @param {IncomingMessage} req
- * @return {string}
- * @private
- */
-
-function getResourceName (req) {
-  try {
-    return parseUrl.original(req).pathname
-  } catch (e) {
-    return 'resource'
-  }
-}
-
-/**
- * Get status code from response.
- *
- * @param {OutgoingMessage} res
- * @return {number}
- * @private
- */
-
-function getResponseStatusCode (res) {
-  var status = res.statusCode
-
-  // default status code to 500 if outside valid range
-  if (typeof status !== 'number' || status < 400 || status > 599) {
-    status = 500
-  }
-
-  return status
-}
-
-/**
- * Determine if the response headers have been sent.
- *
- * @param {object} res
- * @returns {boolean}
- * @private
- */
-
-function headersSent (res) {
-  return typeof res.headersSent !== 'boolean'
-    ? Boolean(res._header)
-    : res.headersSent
-}
-
-/**
- * Send response.
- *
- * @param {IncomingMessage} req
- * @param {OutgoingMessage} res
- * @param {number} status
- * @param {object} headers
- * @param {string} message
- * @private
- */
-
-function send (req, res, status, headers, message) {
-  function write () {
-    // response body
-    var body = createHtmlDocument(message)
-
-    // response status
-    res.statusCode = status
-    res.statusMessage = statuses[status]
-
-    // response headers
-    setHeaders(res, headers)
-
-    // security headers
-    res.setHeader('Content-Security-Policy', "default-src 'none'")
-    res.setHeader('X-Content-Type-Options', 'nosniff')
-
-    // standard headers
-    res.setHeader('Content-Type', 'text/html; charset=utf-8')
-    res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8'))
-
-    if (req.method === 'HEAD') {
-      res.end()
-      return
-    }
-
-    res.end(body, 'utf8')
-  }
-
-  if (isFinished(req)) {
-    write()
-    return
-  }
-
-  // unpipe everything from the request
-  unpipe(req)
-
-  // flush the request
-  onFinished(req, write)
-  req.resume()
-}
-
-/**
- * Set response headers from an object.
- *
- * @param {OutgoingMessage} res
- * @param {object} headers
- * @private
- */
-
-function setHeaders (res, headers) {
-  if (!headers) {
-    return
-  }
-
-  var keys = Object.keys(headers)
-  for (var i = 0; i < keys.length; i++) {
-    var key = keys[i]
-    res.setHeader(key, headers[key])
-  }
-}
+"use strict";var debug=require("debug")("finalhandler"),encodeUrl=require("encodeurl"),escapeHtml=require("escape-html"),onFinished=require("on-finished"),parseUrl=require("parseurl"),statuses=require("statuses"),unpipe=require("unpipe"),DOUBLE_SPACE_REGEXP=/\x20{2}/g,NEWLINE_REGEXP=/\n/g,defer="function"==typeof setImmediate?setImmediate:function(e){process.nextTick(e.bind.apply(e,arguments))},isFinished=onFinished.isFinished;function createHtmlDocument(e){return'<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<title>Error</title>\n</head>\n<body>\n<pre>'+escapeHtml(e).replace(NEWLINE_REGEXP,"<br>").replace(DOUBLE_SPACE_REGEXP," &nbsp;")+"</pre>\n</body>\n</html>\n"}function finalhandler(e,t,r){var n=r||{},s=n.env||process.env.NODE_ENV||"development",a=n.onerror;return function(r){var n,o,u;if(r||!headersSent(t)){if(r?(void 0===(u=getErrorStatusCode(r))?u=getResponseStatusCode(t):n=getErrorHeaders(r),o=getErrorMessage(r,u,s)):(u=404,o="Cannot "+e.method+" "+encodeUrl(getResourceName(e))),debug("default %s",u),r&&a&&defer(a,r,e,t),headersSent(t))return debug("cannot %d after headers sent",u),void e.socket.destroy();send(e,t,u,n,o)}else debug("cannot 404 after headers sent")}}function getErrorHeaders(e){if(e.headers&&"object"==typeof e.headers){for(var t=Object.create(null),r=Object.keys(e.headers),n=0;n<r.length;n++){var s=r[n];t[s]=e.headers[s]}return t}}function getErrorMessage(e,t,r){var n;return"production"!==r&&((n=e.stack)||"function"!=typeof e.toString||(n=e.toString())),n||statuses[t]}function getErrorStatusCode(e){return"number"==typeof e.status&&e.status>=400&&e.status<600?e.status:"number"==typeof e.statusCode&&e.statusCode>=400&&e.statusCode<600?e.statusCode:void 0}function getResourceName(e){try{return parseUrl.original(e).pathname}catch(e){return"resource"}}function getResponseStatusCode(e){var t=e.statusCode;return("number"!=typeof t||t<400||t>599)&&(t=500),t}function headersSent(e){return"boolean"!=typeof e.headersSent?Boolean(e._header):e.headersSent}function send(e,t,r,n,s){function a(){var a=createHtmlDocument(s);t.statusCode=r,t.statusMessage=statuses[r],setHeaders(t,n),t.setHeader("Content-Security-Policy","default-src 'none'"),t.setHeader("X-Content-Type-Options","nosniff"),t.setHeader("Content-Type","text/html; charset=utf-8"),t.setHeader("Content-Length",Buffer.byteLength(a,"utf8")),"HEAD"!==e.method?t.end(a,"utf8"):t.end()}isFinished(e)?a():(unpipe(e),onFinished(e,a),e.resume())}function setHeaders(e,t){if(t)for(var r=Object.keys(t),n=0;n<r.length;n++){var s=r[n];e.setHeader(s,t[s])}}module.exports=finalhandler;
\ No newline at end of file
index 8e83819..bc47053 100644 (file)
@@ -1,46 +1 @@
-'use strict';
-const path = require('path');
-const locatePath = require('locate-path');
-
-module.exports = (filename, opts = {}) => {
-       const startDir = path.resolve(opts.cwd || '');
-       const {root} = path.parse(startDir);
-
-       const filenames = [].concat(filename);
-
-       return new Promise(resolve => {
-               (function find(dir) {
-                       locatePath(filenames, {cwd: dir}).then(file => {
-                               if (file) {
-                                       resolve(path.join(dir, file));
-                               } else if (dir === root) {
-                                       resolve(null);
-                               } else {
-                                       find(path.dirname(dir));
-                               }
-                       });
-               })(startDir);
-       });
-};
-
-module.exports.sync = (filename, opts = {}) => {
-       let dir = path.resolve(opts.cwd || '');
-       const {root} = path.parse(dir);
-
-       const filenames = [].concat(filename);
-
-       // eslint-disable-next-line no-constant-condition
-       while (true) {
-               const file = locatePath.sync(filenames, {cwd: dir});
-
-               if (file) {
-                       return path.join(dir, file);
-               }
-
-               if (dir === root) {
-                       return null;
-               }
-
-               dir = path.dirname(dir);
-       }
-};
+"use strict";const path=require("path"),locatePath=require("locate-path");module.exports=(t,e={})=>{const o=path.resolve(e.cwd||""),{root:a}=path.parse(o),r=[].concat(t);return new Promise((t=>{!function e(o){locatePath(r,{cwd:o}).then((r=>{r?t(path.join(o,r)):o===a?t(null):e(path.dirname(o))}))}(o)}))},module.exports.sync=(t,e={})=>{let o=path.resolve(e.cwd||"");const{root:a}=path.parse(o),r=[].concat(t);for(;;){const t=locatePath.sync(r,{cwd:o});if(t)return path.join(o,t);if(o===a)return null;o=path.dirname(o)}};
\ No newline at end of file
index 7833b3d..2ead8e7 100644 (file)
@@ -3,74 +3,4 @@
  * Copyright(c) 2014-2017 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = forwarded
-
-/**
- * Get all addresses in the request, using the `X-Forwarded-For` header.
- *
- * @param {object} req
- * @return {array}
- * @public
- */
-
-function forwarded (req) {
-  if (!req) {
-    throw new TypeError('argument req is required')
-  }
-
-  // simple header parsing
-  var proxyAddrs = parse(req.headers['x-forwarded-for'] || '')
-  var socketAddr = req.connection.remoteAddress
-  var addrs = [socketAddr].concat(proxyAddrs)
-
-  // return all addresses
-  return addrs
-}
-
-/**
- * Parse the X-Forwarded-For header.
- *
- * @param {string} header
- * @private
- */
-
-function parse (header) {
-  var end = header.length
-  var list = []
-  var start = header.length
-
-  // gather addresses, backwards
-  for (var i = header.length - 1; i >= 0; i--) {
-    switch (header.charCodeAt(i)) {
-      case 0x20: /*   */
-        if (start === end) {
-          start = end = i
-        }
-        break
-      case 0x2c: /* , */
-        if (start !== end) {
-          list.push(header.substring(start, end))
-        }
-        start = end = i
-        break
-      default:
-        start = i
-        break
-    }
-  }
-
-  // final address
-  if (start !== end) {
-    list.push(header.substring(start, end))
-  }
-
-  return list
-}
+"use strict";function forwarded(r){if(!r)throw new TypeError("argument req is required");var e=parse(r.headers["x-forwarded-for"]||"");return[r.connection.remoteAddress].concat(e)}function parse(r){for(var e=r.length,t=[],s=r.length,n=r.length-1;n>=0;n--)switch(r.charCodeAt(n)){case 32:s===e&&(s=e=n);break;case 44:s!==e&&t.push(r.substring(s,e)),s=e=n;break;default:s=n}return s!==e&&t.push(r.substring(s,e)),t}module.exports=forwarded;
\ No newline at end of file
index d154f5a..8d59833 100644 (file)
@@ -4,134 +4,4 @@
  * Copyright(c) 2016-2017 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * RegExp to check for no-cache token in Cache-Control.
- * @private
- */
-
-var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = fresh
-
-/**
- * Check freshness of the response using request and response headers.
- *
- * @param {Object} reqHeaders
- * @param {Object} resHeaders
- * @return {Boolean}
- * @public
- */
-
-function fresh (reqHeaders, resHeaders) {
-  // fields
-  var modifiedSince = reqHeaders['if-modified-since']
-  var noneMatch = reqHeaders['if-none-match']
-
-  // unconditional request
-  if (!modifiedSince && !noneMatch) {
-    return false
-  }
-
-  // Always return stale when Cache-Control: no-cache
-  // to support end-to-end reload requests
-  // https://tools.ietf.org/html/rfc2616#section-14.9.4
-  var cacheControl = reqHeaders['cache-control']
-  if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) {
-    return false
-  }
-
-  // if-none-match
-  if (noneMatch && noneMatch !== '*') {
-    var etag = resHeaders['etag']
-
-    if (!etag) {
-      return false
-    }
-
-    var etagStale = true
-    var matches = parseTokenList(noneMatch)
-    for (var i = 0; i < matches.length; i++) {
-      var match = matches[i]
-      if (match === etag || match === 'W/' + etag || 'W/' + match === etag) {
-        etagStale = false
-        break
-      }
-    }
-
-    if (etagStale) {
-      return false
-    }
-  }
-
-  // if-modified-since
-  if (modifiedSince) {
-    var lastModified = resHeaders['last-modified']
-    var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince))
-
-    if (modifiedStale) {
-      return false
-    }
-  }
-
-  return true
-}
-
-/**
- * Parse an HTTP Date into a number.
- *
- * @param {string} date
- * @private
- */
-
-function parseHttpDate (date) {
-  var timestamp = date && Date.parse(date)
-
-  // istanbul ignore next: guard against date.js Date.parse patching
-  return typeof timestamp === 'number'
-    ? timestamp
-    : NaN
-}
-
-/**
- * Parse a HTTP token list.
- *
- * @param {string} str
- * @private
- */
-
-function parseTokenList (str) {
-  var end = 0
-  var list = []
-  var start = 0
-
-  // gather tokens
-  for (var i = 0, len = str.length; i < len; i++) {
-    switch (str.charCodeAt(i)) {
-      case 0x20: /*   */
-        if (start === end) {
-          start = end = i + 1
-        }
-        break
-      case 0x2c: /* , */
-        list.push(str.substring(start, end))
-        start = end = i + 1
-        break
-      default:
-        end = i + 1
-        break
-    }
-  }
-
-  // final token
-  list.push(str.substring(start, end))
-
-  return list
-}
+"use strict";var CACHE_CONTROL_NO_CACHE_REGEXP=/(?:^|,)\s*?no-cache\s*?(?:,|$)/;function fresh(r,e){var t=r["if-modified-since"],a=r["if-none-match"];if(!t&&!a)return!1;var s=r["cache-control"];if(s&&CACHE_CONTROL_NO_CACHE_REGEXP.test(s))return!1;if(a&&"*"!==a){var n=e.etag;if(!n)return!1;for(var i=!0,f=parseTokenList(a),u=0;u<f.length;u++){var o=f[u];if(o===n||o==="W/"+n||"W/"+o===n){i=!1;break}}if(i)return!1}if(t){var c=e["last-modified"];if(!(c&&parseHttpDate(c)<=parseHttpDate(t)))return!1}return!0}function parseHttpDate(r){var e=r&&Date.parse(r);return"number"==typeof e?e:NaN}function parseTokenList(r){for(var e=0,t=[],a=0,s=0,n=r.length;s<n;s++)switch(r.charCodeAt(s)){case 32:a===e&&(a=e=s+1);break;case 44:t.push(r.substring(a,e)),a=e=s+1;break;default:e=s+1}return t.push(r.substring(a,e)),t}module.exports=fresh;
\ No newline at end of file
index 57304f8..40b3103 100644 (file)
@@ -1,22 +1 @@
-"use strict";
-// Call this function in a another function to find out the file from
-// which that function was called from. (Inspects the v8 stack trace)
-//
-// Inspired by http://stackoverflow.com/questions/13227489
-module.exports = function getCallerFile(position) {
-    if (position === void 0) { position = 2; }
-    if (position >= Error.stackTraceLimit) {
-        throw new TypeError('getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `' + position + '` and Error.stackTraceLimit was: `' + Error.stackTraceLimit + '`');
-    }
-    var oldPrepareStackTrace = Error.prepareStackTrace;
-    Error.prepareStackTrace = function (_, stack) { return stack; };
-    var stack = new Error().stack;
-    Error.prepareStackTrace = oldPrepareStackTrace;
-    if (stack !== null && typeof stack === 'object') {
-        // stack[0] holds this file
-        // stack[1] holds where this function was called
-        // stack[2] holds the file we're interested in
-        return stack[position] ? stack[position].getFileName() : undefined;
-    }
-};
-//# sourceMappingURL=index.js.map
\ No newline at end of file
+"use strict";module.exports=function(r){if(void 0===r&&(r=2),r>=Error.stackTraceLimit)throw new TypeError("getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `"+r+"` and Error.stackTraceLimit was: `"+Error.stackTraceLimit+"`");var e=Error.prepareStackTrace;Error.prepareStackTrace=function(r,e){return e};var t=(new Error).stack;if(Error.prepareStackTrace=e,null!==t&&"object"==typeof t)return t[r]?t[r].getFileName():void 0};
\ No newline at end of file
index f3e2210..73302ff 100755 (executable)
@@ -1,109 +1 @@
-'use strict';
-const net = require('net');
-
-class Locked extends Error {
-       constructor(port) {
-               super(`${port} is locked`);
-       }
-}
-
-const lockedPorts = {
-       old: new Set(),
-       young: new Set()
-};
-
-// On this interval, the old locked ports are discarded,
-// the young locked ports are moved to old locked ports,
-// and a new young set for locked ports are created.
-const releaseOldLockedPortsIntervalMs = 1000 * 15;
-
-// Lazily create interval on first use
-let interval;
-
-const getAvailablePort = options => new Promise((resolve, reject) => {
-       const server = net.createServer();
-       server.unref();
-       server.on('error', reject);
-       server.listen(options, () => {
-               const {port} = server.address();
-               server.close(() => {
-                       resolve(port);
-               });
-       });
-});
-
-const portCheckSequence = function * (ports) {
-       if (ports) {
-               yield * ports;
-       }
-
-       yield 0; // Fall back to 0 if anything else failed
-};
-
-module.exports = async options => {
-       let ports;
-
-       if (options) {
-               ports = typeof options.port === 'number' ? [options.port] : options.port;
-       }
-
-       if (interval === undefined) {
-               interval = setInterval(() => {
-                       lockedPorts.old = lockedPorts.young;
-                       lockedPorts.young = new Set();
-               }, releaseOldLockedPortsIntervalMs);
-
-               // Does not exist in some environments (Electron, Jest jsdom env, browser, etc).
-               if (interval.unref) {
-                       interval.unref();
-               }
-       }
-
-       for (const port of portCheckSequence(ports)) {
-               try {
-                       let availablePort = await getAvailablePort({...options, port}); // eslint-disable-line no-await-in-loop
-                       while (lockedPorts.old.has(availablePort) || lockedPorts.young.has(availablePort)) {
-                               if (port !== 0) {
-                                       throw new Locked(port);
-                               }
-
-                               availablePort = await getAvailablePort({...options, port}); // eslint-disable-line no-await-in-loop
-                       }
-
-                       lockedPorts.young.add(availablePort);
-                       return availablePort;
-               } catch (error) {
-                       if (!['EADDRINUSE', 'EACCES'].includes(error.code) && !(error instanceof Locked)) {
-                               throw error;
-                       }
-               }
-       }
-
-       throw new Error('No available ports found');
-};
-
-module.exports.makeRange = (from, to) => {
-       if (!Number.isInteger(from) || !Number.isInteger(to)) {
-               throw new TypeError('`from` and `to` must be integer numbers');
-       }
-
-       if (from < 1024 || from > 65535) {
-               throw new RangeError('`from` must be between 1024 and 65535');
-       }
-
-       if (to < 1024 || to > 65536) {
-               throw new RangeError('`to` must be between 1024 and 65536');
-       }
-
-       if (to < from) {
-               throw new RangeError('`to` must be greater than or equal to `from`');
-       }
-
-       const generator = function * (from, to) {
-               for (let port = from; port <= to; port++) {
-                       yield port;
-               }
-       };
-
-       return generator(from, to);
-};
+"use strict";const net=require("net");class Locked extends Error{constructor(e){super(`${e} is locked`)}}const lockedPorts={old:new Set,young:new Set},releaseOldLockedPortsIntervalMs=15e3;let interval;const getAvailablePort=e=>new Promise(((r,o)=>{const t=net.createServer();t.unref(),t.on("error",o),t.listen(e,(()=>{const{port:e}=t.address();t.close((()=>{r(e)}))}))})),portCheckSequence=function*(e){e&&(yield*e),yield 0};module.exports=async e=>{let r;e&&(r="number"==typeof e.port?[e.port]:e.port),void 0===interval&&(interval=setInterval((()=>{lockedPorts.old=lockedPorts.young,lockedPorts.young=new Set}),15e3),interval.unref&&interval.unref());for(const o of portCheckSequence(r))try{let r=await getAvailablePort({...e,port:o});for(;lockedPorts.old.has(r)||lockedPorts.young.has(r);){if(0!==o)throw new Locked(o);r=await getAvailablePort({...e,port:o})}return lockedPorts.young.add(r),r}catch(e){if(!(["EADDRINUSE","EACCES"].includes(e.code)||e instanceof Locked))throw e}throw new Error("No available ports found")},module.exports.makeRange=(e,r)=>{if(!Number.isInteger(e)||!Number.isInteger(r))throw new TypeError("`from` and `to` must be integer numbers");if(e<1024||e>65535)throw new RangeError("`from` must be between 1024 and 65535");if(r<1024||r>65536)throw new RangeError("`to` must be between 1024 and 65536");if(r<e)throw new RangeError("`to` must be greater than or equal to `from`");return function*(e,r){for(let o=e;o<=r;o++)yield o}(e,r)};
\ No newline at end of file
index cf756a3..c2f29ac 100644 (file)
@@ -1,64 +1 @@
-/* global Blob File */
-
-/*
- * Module requirements.
- */
-
-var isArray = require('isarray');
-
-var toString = Object.prototype.toString;
-var withNativeBlob = typeof Blob === 'function' ||
-                        typeof Blob !== 'undefined' && toString.call(Blob) === '[object BlobConstructor]';
-var withNativeFile = typeof File === 'function' ||
-                        typeof File !== 'undefined' && toString.call(File) === '[object FileConstructor]';
-
-/**
- * Module exports.
- */
-
-module.exports = hasBinary;
-
-/**
- * Checks for binary data.
- *
- * Supports Buffer, ArrayBuffer, Blob and File.
- *
- * @param {Object} anything
- * @api public
- */
-
-function hasBinary (obj) {
-  if (!obj || typeof obj !== 'object') {
-    return false;
-  }
-
-  if (isArray(obj)) {
-    for (var i = 0, l = obj.length; i < l; i++) {
-      if (hasBinary(obj[i])) {
-        return true;
-      }
-    }
-    return false;
-  }
-
-  if ((typeof Buffer === 'function' && Buffer.isBuffer && Buffer.isBuffer(obj)) ||
-    (typeof ArrayBuffer === 'function' && obj instanceof ArrayBuffer) ||
-    (withNativeBlob && obj instanceof Blob) ||
-    (withNativeFile && obj instanceof File)
-  ) {
-    return true;
-  }
-
-  // see: https://github.com/Automattic/has-binary/pull/4
-  if (obj.toJSON && typeof obj.toJSON === 'function' && arguments.length === 1) {
-    return hasBinary(obj.toJSON(), true);
-  }
-
-  for (var key in obj) {
-    if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
-      return true;
-    }
-  }
-
-  return false;
-}
+var isArray=require("isarray"),toString=Object.prototype.toString,withNativeBlob="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===toString.call(Blob),withNativeFile="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===toString.call(File);function hasBinary(t){if(!t||"object"!=typeof t)return!1;if(isArray(t)){for(var r=0,e=t.length;r<e;r++)if(hasBinary(t[r]))return!0;return!1}if("function"==typeof Buffer&&Buffer.isBuffer&&Buffer.isBuffer(t)||"function"==typeof ArrayBuffer&&t instanceof ArrayBuffer||withNativeBlob&&t instanceof Blob||withNativeFile&&t instanceof File)return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return hasBinary(t.toJSON(),!0);for(var i in t)if(Object.prototype.hasOwnProperty.call(t,i)&&hasBinary(t[i]))return!0;return!1}module.exports=hasBinary;
\ No newline at end of file
index 952a7c8..bba9a22 100644 (file)
@@ -1,17 +1 @@
-
-/**
- * Module exports.
- *
- * Logic borrowed from Modernizr:
- *
- *   - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
- */
-
-try {
-  module.exports = typeof XMLHttpRequest !== 'undefined' &&
-    'withCredentials' in new XMLHttpRequest();
-} catch (err) {
-  // if XMLHttp support is disabled in IE then it will throw
-  // when trying to create
-  module.exports = false;
-}
+try{module.exports="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){module.exports=!1}
\ No newline at end of file
index d2dfb84..1c96bdb 100644 (file)
@@ -1,24 +1 @@
-var expect = require('chai').expect;
-
-describe('has-cors', function() {
-  beforeEach(function() {
-    // make sure result is not cached
-    delete require.cache[require.resolve('./')];
-  });
-  
-  it('should not have cors', function() {
-    var hasCors = require('./');
-
-    expect(hasCors).to.be.false;
-  });
-  
-  it('should have cors', function() {
-    global.XMLHttpRequest = function() {
-      this.withCredentials = true;
-    };
-
-    var hasCors = require('./');
-
-    expect(hasCors).to.be.true;
-  });
-});
+var expect=require("chai").expect;describe("has-cors",(function(){beforeEach((function(){delete require.cache[require.resolve("./")]})),it("should not have cors",(function(){var e=require("./");expect(e).to.be.false})),it("should have cors",(function(){global.XMLHttpRequest=function(){this.withCredentials=!0};var e=require("./");expect(e).to.be.true}))}));
\ No newline at end of file
index 5139728..ec5d2b3 100755 (executable)
@@ -1,8 +1 @@
-'use strict';
-module.exports = (flag, argv) => {
-       argv = argv || process.argv;
-       const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
-       const pos = argv.indexOf(prefix + flag);
-       const terminatorPos = argv.indexOf('--');
-       return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos);
-};
+"use strict";module.exports=(t,e)=>{e=e||process.argv;const s=t.startsWith("-")?"":1===t.length?"-":"--",r=e.indexOf(s+t),n=e.indexOf("--");return-1!==r&&(-1===n||r<n)};
\ No newline at end of file
index 10ca4ad..057baaa 100644 (file)
@@ -4,263 +4,4 @@
  * Copyright(c) 2016 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module dependencies.
- * @private
- */
-
-var deprecate = require('depd')('http-errors')
-var setPrototypeOf = require('setprototypeof')
-var statuses = require('statuses')
-var inherits = require('inherits')
-var toIdentifier = require('toidentifier')
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = createError
-module.exports.HttpError = createHttpErrorConstructor()
-
-// Populate exports for all constructors
-populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError)
-
-/**
- * Get the code class of a status code.
- * @private
- */
-
-function codeClass (status) {
-  return Number(String(status).charAt(0) + '00')
-}
-
-/**
- * Create a new HTTP Error.
- *
- * @returns {Error}
- * @public
- */
-
-function createError () {
-  // so much arity going on ~_~
-  var err
-  var msg
-  var status = 500
-  var props = {}
-  for (var i = 0; i < arguments.length; i++) {
-    var arg = arguments[i]
-    if (arg instanceof Error) {
-      err = arg
-      status = err.status || err.statusCode || status
-      continue
-    }
-    switch (typeof arg) {
-      case 'string':
-        msg = arg
-        break
-      case 'number':
-        status = arg
-        if (i !== 0) {
-          deprecate('non-first-argument status code; replace with createError(' + arg + ', ...)')
-        }
-        break
-      case 'object':
-        props = arg
-        break
-    }
-  }
-
-  if (typeof status === 'number' && (status < 400 || status >= 600)) {
-    deprecate('non-error status code; use only 4xx or 5xx status codes')
-  }
-
-  if (typeof status !== 'number' ||
-    (!statuses[status] && (status < 400 || status >= 600))) {
-    status = 500
-  }
-
-  // constructor
-  var HttpError = createError[status] || createError[codeClass(status)]
-
-  if (!err) {
-    // create error
-    err = HttpError
-      ? new HttpError(msg)
-      : new Error(msg || statuses[status])
-    Error.captureStackTrace(err, createError)
-  }
-
-  if (!HttpError || !(err instanceof HttpError) || err.status !== status) {
-    // add properties to generic error
-    err.expose = status < 500
-    err.status = err.statusCode = status
-  }
-
-  for (var key in props) {
-    if (key !== 'status' && key !== 'statusCode') {
-      err[key] = props[key]
-    }
-  }
-
-  return err
-}
-
-/**
- * Create HTTP error abstract base class.
- * @private
- */
-
-function createHttpErrorConstructor () {
-  function HttpError () {
-    throw new TypeError('cannot construct abstract class')
-  }
-
-  inherits(HttpError, Error)
-
-  return HttpError
-}
-
-/**
- * Create a constructor for a client error.
- * @private
- */
-
-function createClientErrorConstructor (HttpError, name, code) {
-  var className = name.match(/Error$/) ? name : name + 'Error'
-
-  function ClientError (message) {
-    // create the error object
-    var msg = message != null ? message : statuses[code]
-    var err = new Error(msg)
-
-    // capture a stack trace to the construction point
-    Error.captureStackTrace(err, ClientError)
-
-    // adjust the [[Prototype]]
-    setPrototypeOf(err, ClientError.prototype)
-
-    // redefine the error message
-    Object.defineProperty(err, 'message', {
-      enumerable: true,
-      configurable: true,
-      value: msg,
-      writable: true
-    })
-
-    // redefine the error name
-    Object.defineProperty(err, 'name', {
-      enumerable: false,
-      configurable: true,
-      value: className,
-      writable: true
-    })
-
-    return err
-  }
-
-  inherits(ClientError, HttpError)
-  nameFunc(ClientError, className)
-
-  ClientError.prototype.status = code
-  ClientError.prototype.statusCode = code
-  ClientError.prototype.expose = true
-
-  return ClientError
-}
-
-/**
- * Create a constructor for a server error.
- * @private
- */
-
-function createServerErrorConstructor (HttpError, name, code) {
-  var className = name.match(/Error$/) ? name : name + 'Error'
-
-  function ServerError (message) {
-    // create the error object
-    var msg = message != null ? message : statuses[code]
-    var err = new Error(msg)
-
-    // capture a stack trace to the construction point
-    Error.captureStackTrace(err, ServerError)
-
-    // adjust the [[Prototype]]
-    setPrototypeOf(err, ServerError.prototype)
-
-    // redefine the error message
-    Object.defineProperty(err, 'message', {
-      enumerable: true,
-      configurable: true,
-      value: msg,
-      writable: true
-    })
-
-    // redefine the error name
-    Object.defineProperty(err, 'name', {
-      enumerable: false,
-      configurable: true,
-      value: className,
-      writable: true
-    })
-
-    return err
-  }
-
-  inherits(ServerError, HttpError)
-  nameFunc(ServerError, className)
-
-  ServerError.prototype.status = code
-  ServerError.prototype.statusCode = code
-  ServerError.prototype.expose = false
-
-  return ServerError
-}
-
-/**
- * Set the name of a function, if possible.
- * @private
- */
-
-function nameFunc (func, name) {
-  var desc = Object.getOwnPropertyDescriptor(func, 'name')
-
-  if (desc && desc.configurable) {
-    desc.value = name
-    Object.defineProperty(func, 'name', desc)
-  }
-}
-
-/**
- * Populate the exports object with constructors for every error class.
- * @private
- */
-
-function populateConstructorExports (exports, codes, HttpError) {
-  codes.forEach(function forEachCode (code) {
-    var CodeError
-    var name = toIdentifier(statuses[code])
-
-    switch (codeClass(code)) {
-      case 400:
-        CodeError = createClientErrorConstructor(HttpError, name, code)
-        break
-      case 500:
-        CodeError = createServerErrorConstructor(HttpError, name, code)
-        break
-    }
-
-    if (CodeError) {
-      // export the constructor
-      exports[code] = CodeError
-      exports[name] = CodeError
-    }
-  })
-
-  // backwards-compatibility
-  exports["I'mateapot"] = deprecate.function(exports.ImATeapot,
-    '"I\'mateapot"; use "ImATeapot" instead')
-}
+"use strict";var deprecate=require("depd")("http-errors"),setPrototypeOf=require("setprototypeof"),statuses=require("statuses"),inherits=require("inherits"),toIdentifier=require("toidentifier");function codeClass(r){return Number(String(r).charAt(0)+"00")}function createError(){for(var r,e,t=500,o={},a=0;a<arguments.length;a++){var s=arguments[a];if(s instanceof Error)t=(r=s).status||r.statusCode||t;else switch(typeof s){case"string":e=s;break;case"number":t=s,0!==a&&deprecate("non-first-argument status code; replace with createError("+s+", ...)");break;case"object":o=s}}"number"==typeof t&&(t<400||t>=600)&&deprecate("non-error status code; use only 4xx or 5xx status codes"),("number"!=typeof t||!statuses[t]&&(t<400||t>=600))&&(t=500);var n=createError[t]||createError[codeClass(t)];for(var u in r||(r=n?new n(e):new Error(e||statuses[t]),Error.captureStackTrace(r,createError)),n&&r instanceof n&&r.status===t||(r.expose=t<500,r.status=r.statusCode=t),o)"status"!==u&&"statusCode"!==u&&(r[u]=o[u]);return r}function createHttpErrorConstructor(){function r(){throw new TypeError("cannot construct abstract class")}return inherits(r,Error),r}function createClientErrorConstructor(r,e,t){var o=e.match(/Error$/)?e:e+"Error";function a(r){var e=null!=r?r:statuses[t],s=new Error(e);return Error.captureStackTrace(s,a),setPrototypeOf(s,a.prototype),Object.defineProperty(s,"message",{enumerable:!0,configurable:!0,value:e,writable:!0}),Object.defineProperty(s,"name",{enumerable:!1,configurable:!0,value:o,writable:!0}),s}return inherits(a,r),nameFunc(a,o),a.prototype.status=t,a.prototype.statusCode=t,a.prototype.expose=!0,a}function createServerErrorConstructor(r,e,t){var o=e.match(/Error$/)?e:e+"Error";function a(r){var e=null!=r?r:statuses[t],s=new Error(e);return Error.captureStackTrace(s,a),setPrototypeOf(s,a.prototype),Object.defineProperty(s,"message",{enumerable:!0,configurable:!0,value:e,writable:!0}),Object.defineProperty(s,"name",{enumerable:!1,configurable:!0,value:o,writable:!0}),s}return inherits(a,r),nameFunc(a,o),a.prototype.status=t,a.prototype.statusCode=t,a.prototype.expose=!1,a}function nameFunc(r,e){var t=Object.getOwnPropertyDescriptor(r,"name");t&&t.configurable&&(t.value=e,Object.defineProperty(r,"name",t))}function populateConstructorExports(r,e,t){e.forEach((function(e){var o,a=toIdentifier(statuses[e]);switch(codeClass(e)){case 400:o=createClientErrorConstructor(t,a,e);break;case 500:o=createServerErrorConstructor(t,a,e)}o&&(r[e]=o,r[a]=o)})),r["I'mateapot"]=deprecate.function(r.ImATeapot,'"I\'mateapot"; use "ImATeapot" instead')}module.exports=createError,module.exports.HttpError=createHttpErrorConstructor(),populateConstructorExports(module.exports,statuses.codes,module.exports.HttpError);
\ No newline at end of file
index 1fe3e16..7922a8c 100644 (file)
@@ -1,555 +1 @@
-"use strict";
-var Buffer = require("safer-buffer").Buffer;
-
-// Multibyte codec. In this scheme, a character is represented by 1 or more bytes.
-// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences.
-// To save memory and loading time, we read table files only when requested.
-
-exports._dbcs = DBCSCodec;
-
-var UNASSIGNED = -1,
-    GB18030_CODE = -2,
-    SEQ_START  = -10,
-    NODE_START = -1000,
-    UNASSIGNED_NODE = new Array(0x100),
-    DEF_CHAR = -1;
-
-for (var i = 0; i < 0x100; i++)
-    UNASSIGNED_NODE[i] = UNASSIGNED;
-
-
-// Class DBCSCodec reads and initializes mapping tables.
-function DBCSCodec(codecOptions, iconv) {
-    this.encodingName = codecOptions.encodingName;
-    if (!codecOptions)
-        throw new Error("DBCS codec is called without the data.")
-    if (!codecOptions.table)
-        throw new Error("Encoding '" + this.encodingName + "' has no data.");
-
-    // Load tables.
-    var mappingTable = codecOptions.table();
-
-
-    // Decode tables: MBCS -> Unicode.
-
-    // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256.
-    // Trie root is decodeTables[0].
-    // Values: >=  0 -> unicode character code. can be > 0xFFFF
-    //         == UNASSIGNED -> unknown/unassigned sequence.
-    //         == GB18030_CODE -> this is the end of a GB18030 4-byte sequence.
-    //         <= NODE_START -> index of the next node in our trie to process next byte.
-    //         <= SEQ_START  -> index of the start of a character code sequence, in decodeTableSeq.
-    this.decodeTables = [];
-    this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node.
-
-    // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. 
-    this.decodeTableSeq = [];
-
-    // Actual mapping tables consist of chunks. Use them to fill up decode tables.
-    for (var i = 0; i < mappingTable.length; i++)
-        this._addDecodeChunk(mappingTable[i]);
-
-    this.defaultCharUnicode = iconv.defaultCharUnicode;
-
-    
-    // Encode tables: Unicode -> DBCS.
-
-    // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance.
-    // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null.
-    // Values: >=  0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.).
-    //         == UNASSIGNED -> no conversion found. Output a default char.
-    //         <= SEQ_START  -> it's an index in encodeTableSeq, see below. The character starts a sequence.
-    this.encodeTable = [];
-    
-    // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of
-    // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key
-    // means end of sequence (needed when one sequence is a strict subsequence of another).
-    // Objects are kept separately from encodeTable to increase performance.
-    this.encodeTableSeq = [];
-
-    // Some chars can be decoded, but need not be encoded.
-    var skipEncodeChars = {};
-    if (codecOptions.encodeSkipVals)
-        for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) {
-            var val = codecOptions.encodeSkipVals[i];
-            if (typeof val === 'number')
-                skipEncodeChars[val] = true;
-            else
-                for (var j = val.from; j <= val.to; j++)
-                    skipEncodeChars[j] = true;
-        }
-        
-    // Use decode trie to recursively fill out encode tables.
-    this._fillEncodeTable(0, 0, skipEncodeChars);
-
-    // Add more encoding pairs when needed.
-    if (codecOptions.encodeAdd) {
-        for (var uChar in codecOptions.encodeAdd)
-            if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar))
-                this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]);
-    }
-
-    this.defCharSB  = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)];
-    if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?'];
-    if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0);
-
-
-    // Load & create GB18030 tables when needed.
-    if (typeof codecOptions.gb18030 === 'function') {
-        this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges.
-
-        // Add GB18030 decode tables.
-        var thirdByteNodeIdx = this.decodeTables.length;
-        var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0);
-
-        var fourthByteNodeIdx = this.decodeTables.length;
-        var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0);
-
-        for (var i = 0x81; i <= 0xFE; i++) {
-            var secondByteNodeIdx = NODE_START - this.decodeTables[0][i];
-            var secondByteNode = this.decodeTables[secondByteNodeIdx];
-            for (var j = 0x30; j <= 0x39; j++)
-                secondByteNode[j] = NODE_START - thirdByteNodeIdx;
-        }
-        for (var i = 0x81; i <= 0xFE; i++)
-            thirdByteNode[i] = NODE_START - fourthByteNodeIdx;
-        for (var i = 0x30; i <= 0x39; i++)
-            fourthByteNode[i] = GB18030_CODE
-    }        
-}
-
-DBCSCodec.prototype.encoder = DBCSEncoder;
-DBCSCodec.prototype.decoder = DBCSDecoder;
-
-// Decoder helpers
-DBCSCodec.prototype._getDecodeTrieNode = function(addr) {
-    var bytes = [];
-    for (; addr > 0; addr >>= 8)
-        bytes.push(addr & 0xFF);
-    if (bytes.length == 0)
-        bytes.push(0);
-
-    var node = this.decodeTables[0];
-    for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie.
-        var val = node[bytes[i]];
-
-        if (val == UNASSIGNED) { // Create new node.
-            node[bytes[i]] = NODE_START - this.decodeTables.length;
-            this.decodeTables.push(node = UNASSIGNED_NODE.slice(0));
-        }
-        else if (val <= NODE_START) { // Existing node.
-            node = this.decodeTables[NODE_START - val];
-        }
-        else
-            throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16));
-    }
-    return node;
-}
-
-
-DBCSCodec.prototype._addDecodeChunk = function(chunk) {
-    // First element of chunk is the hex mbcs code where we start.
-    var curAddr = parseInt(chunk[0], 16);
-
-    // Choose the decoding node where we'll write our chars.
-    var writeTable = this._getDecodeTrieNode(curAddr);
-    curAddr = curAddr & 0xFF;
-
-    // Write all other elements of the chunk to the table.
-    for (var k = 1; k < chunk.length; k++) {
-        var part = chunk[k];
-        if (typeof part === "string") { // String, write as-is.
-            for (var l = 0; l < part.length;) {
-                var code = part.charCodeAt(l++);
-                if (0xD800 <= code && code < 0xDC00) { // Decode surrogate
-                    var codeTrail = part.charCodeAt(l++);
-                    if (0xDC00 <= codeTrail && codeTrail < 0xE000)
-                        writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00);
-                    else
-                        throw new Error("Incorrect surrogate pair in "  + this.encodingName + " at chunk " + chunk[0]);
-                }
-                else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used)
-                    var len = 0xFFF - code + 2;
-                    var seq = [];
-                    for (var m = 0; m < len; m++)
-                        seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq.
-
-                    writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length;
-                    this.decodeTableSeq.push(seq);
-                }
-                else
-                    writeTable[curAddr++] = code; // Basic char
-            }
-        } 
-        else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character.
-            var charCode = writeTable[curAddr - 1] + 1;
-            for (var l = 0; l < part; l++)
-                writeTable[curAddr++] = charCode++;
-        }
-        else
-            throw new Error("Incorrect type '" + typeof part + "' given in "  + this.encodingName + " at chunk " + chunk[0]);
-    }
-    if (curAddr > 0xFF)
-        throw new Error("Incorrect chunk in "  + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr);
-}
-
-// Encoder helpers
-DBCSCodec.prototype._getEncodeBucket = function(uCode) {
-    var high = uCode >> 8; // This could be > 0xFF because of astral characters.
-    if (this.encodeTable[high] === undefined)
-        this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand.
-    return this.encodeTable[high];
-}
-
-DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) {
-    var bucket = this._getEncodeBucket(uCode);
-    var low = uCode & 0xFF;
-    if (bucket[low] <= SEQ_START)
-        this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it.
-    else if (bucket[low] == UNASSIGNED)
-        bucket[low] = dbcsCode;
-}
-
-DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) {
-    
-    // Get the root of character tree according to first character of the sequence.
-    var uCode = seq[0];
-    var bucket = this._getEncodeBucket(uCode);
-    var low = uCode & 0xFF;
-
-    var node;
-    if (bucket[low] <= SEQ_START) {
-        // There's already a sequence with  - use it.
-        node = this.encodeTableSeq[SEQ_START-bucket[low]];
-    }
-    else {
-        // There was no sequence object - allocate a new one.
-        node = {};
-        if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence.
-        bucket[low] = SEQ_START - this.encodeTableSeq.length;
-        this.encodeTableSeq.push(node);
-    }
-
-    // Traverse the character tree, allocating new nodes as needed.
-    for (var j = 1; j < seq.length-1; j++) {
-        var oldVal = node[uCode];
-        if (typeof oldVal === 'object')
-            node = oldVal;
-        else {
-            node = node[uCode] = {}
-            if (oldVal !== undefined)
-                node[DEF_CHAR] = oldVal
-        }
-    }
-
-    // Set the leaf to given dbcsCode.
-    uCode = seq[seq.length-1];
-    node[uCode] = dbcsCode;
-}
-
-DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) {
-    var node = this.decodeTables[nodeIdx];
-    for (var i = 0; i < 0x100; i++) {
-        var uCode = node[i];
-        var mbCode = prefix + i;
-        if (skipEncodeChars[mbCode])
-            continue;
-
-        if (uCode >= 0)
-            this._setEncodeChar(uCode, mbCode);
-        else if (uCode <= NODE_START)
-            this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars);
-        else if (uCode <= SEQ_START)
-            this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode);
-    }
-}
-
-
-
-// == Encoder ==================================================================
-
-function DBCSEncoder(options, codec) {
-    // Encoder state
-    this.leadSurrogate = -1;
-    this.seqObj = undefined;
-    
-    // Static data
-    this.encodeTable = codec.encodeTable;
-    this.encodeTableSeq = codec.encodeTableSeq;
-    this.defaultCharSingleByte = codec.defCharSB;
-    this.gb18030 = codec.gb18030;
-}
-
-DBCSEncoder.prototype.write = function(str) {
-    var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)),
-        leadSurrogate = this.leadSurrogate,
-        seqObj = this.seqObj, nextChar = -1,
-        i = 0, j = 0;
-
-    while (true) {
-        // 0. Get next character.
-        if (nextChar === -1) {
-            if (i == str.length) break;
-            var uCode = str.charCodeAt(i++);
-        }
-        else {
-            var uCode = nextChar;
-            nextChar = -1;    
-        }
-
-        // 1. Handle surrogates.
-        if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates.
-            if (uCode < 0xDC00) { // We've got lead surrogate.
-                if (leadSurrogate === -1) {
-                    leadSurrogate = uCode;
-                    continue;
-                } else {
-                    leadSurrogate = uCode;
-                    // Double lead surrogate found.
-                    uCode = UNASSIGNED;
-                }
-            } else { // We've got trail surrogate.
-                if (leadSurrogate !== -1) {
-                    uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00);
-                    leadSurrogate = -1;
-                } else {
-                    // Incomplete surrogate pair - only trail surrogate found.
-                    uCode = UNASSIGNED;
-                }
-                
-            }
-        }
-        else if (leadSurrogate !== -1) {
-            // Incomplete surrogate pair - only lead surrogate found.
-            nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char.
-            leadSurrogate = -1;
-        }
-
-        // 2. Convert uCode character.
-        var dbcsCode = UNASSIGNED;
-        if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence
-            var resCode = seqObj[uCode];
-            if (typeof resCode === 'object') { // Sequence continues.
-                seqObj = resCode;
-                continue;
-
-            } else if (typeof resCode == 'number') { // Sequence finished. Write it.
-                dbcsCode = resCode;
-
-            } else if (resCode == undefined) { // Current character is not part of the sequence.
-
-                // Try default character for this sequence
-                resCode = seqObj[DEF_CHAR];
-                if (resCode !== undefined) {
-                    dbcsCode = resCode; // Found. Write it.
-                    nextChar = uCode; // Current character will be written too in the next iteration.
-
-                } else {
-                    // TODO: What if we have no default? (resCode == undefined)
-                    // Then, we should write first char of the sequence as-is and try the rest recursively.
-                    // Didn't do it for now because no encoding has this situation yet.
-                    // Currently, just skip the sequence and write current char.
-                }
-            }
-            seqObj = undefined;
-        }
-        else if (uCode >= 0) {  // Regular character
-            var subtable = this.encodeTable[uCode >> 8];
-            if (subtable !== undefined)
-                dbcsCode = subtable[uCode & 0xFF];
-            
-            if (dbcsCode <= SEQ_START) { // Sequence start
-                seqObj = this.encodeTableSeq[SEQ_START-dbcsCode];
-                continue;
-            }
-
-            if (dbcsCode == UNASSIGNED && this.gb18030) {
-                // Use GB18030 algorithm to find character(s) to write.
-                var idx = findIdx(this.gb18030.uChars, uCode);
-                if (idx != -1) {
-                    var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]);
-                    newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600;
-                    newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260;
-                    newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10;
-                    newBuf[j++] = 0x30 + dbcsCode;
-                    continue;
-                }
-            }
-        }
-
-        // 3. Write dbcsCode character.
-        if (dbcsCode === UNASSIGNED)
-            dbcsCode = this.defaultCharSingleByte;
-        
-        if (dbcsCode < 0x100) {
-            newBuf[j++] = dbcsCode;
-        }
-        else if (dbcsCode < 0x10000) {
-            newBuf[j++] = dbcsCode >> 8;   // high byte
-            newBuf[j++] = dbcsCode & 0xFF; // low byte
-        }
-        else {
-            newBuf[j++] = dbcsCode >> 16;
-            newBuf[j++] = (dbcsCode >> 8) & 0xFF;
-            newBuf[j++] = dbcsCode & 0xFF;
-        }
-    }
-
-    this.seqObj = seqObj;
-    this.leadSurrogate = leadSurrogate;
-    return newBuf.slice(0, j);
-}
-
-DBCSEncoder.prototype.end = function() {
-    if (this.leadSurrogate === -1 && this.seqObj === undefined)
-        return; // All clean. Most often case.
-
-    var newBuf = Buffer.alloc(10), j = 0;
-
-    if (this.seqObj) { // We're in the sequence.
-        var dbcsCode = this.seqObj[DEF_CHAR];
-        if (dbcsCode !== undefined) { // Write beginning of the sequence.
-            if (dbcsCode < 0x100) {
-                newBuf[j++] = dbcsCode;
-            }
-            else {
-                newBuf[j++] = dbcsCode >> 8;   // high byte
-                newBuf[j++] = dbcsCode & 0xFF; // low byte
-            }
-        } else {
-            // See todo above.
-        }
-        this.seqObj = undefined;
-    }
-
-    if (this.leadSurrogate !== -1) {
-        // Incomplete surrogate pair - only lead surrogate found.
-        newBuf[j++] = this.defaultCharSingleByte;
-        this.leadSurrogate = -1;
-    }
-    
-    return newBuf.slice(0, j);
-}
-
-// Export for testing
-DBCSEncoder.prototype.findIdx = findIdx;
-
-
-// == Decoder ==================================================================
-
-function DBCSDecoder(options, codec) {
-    // Decoder state
-    this.nodeIdx = 0;
-    this.prevBuf = Buffer.alloc(0);
-
-    // Static data
-    this.decodeTables = codec.decodeTables;
-    this.decodeTableSeq = codec.decodeTableSeq;
-    this.defaultCharUnicode = codec.defaultCharUnicode;
-    this.gb18030 = codec.gb18030;
-}
-
-DBCSDecoder.prototype.write = function(buf) {
-    var newBuf = Buffer.alloc(buf.length*2),
-        nodeIdx = this.nodeIdx, 
-        prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length,
-        seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence.
-        uCode;
-
-    if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later.
-        prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]);
-    
-    for (var i = 0, j = 0; i < buf.length; i++) {
-        var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset];
-
-        // Lookup in current trie node.
-        var uCode = this.decodeTables[nodeIdx][curByte];
-
-        if (uCode >= 0) { 
-            // Normal character, just use it.
-        }
-        else if (uCode === UNASSIGNED) { // Unknown char.
-            // TODO: Callback with seq.
-            //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset);
-            i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle).
-            uCode = this.defaultCharUnicode.charCodeAt(0);
-        }
-        else if (uCode === GB18030_CODE) {
-            var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset);
-            var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30);
-            var idx = findIdx(this.gb18030.gbChars, ptr);
-            uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx];
-        }
-        else if (uCode <= NODE_START) { // Go to next trie node.
-            nodeIdx = NODE_START - uCode;
-            continue;
-        }
-        else if (uCode <= SEQ_START) { // Output a sequence of chars.
-            var seq = this.decodeTableSeq[SEQ_START - uCode];
-            for (var k = 0; k < seq.length - 1; k++) {
-                uCode = seq[k];
-                newBuf[j++] = uCode & 0xFF;
-                newBuf[j++] = uCode >> 8;
-            }
-            uCode = seq[seq.length-1];
-        }
-        else
-            throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte);
-
-        // Write the character to buffer, handling higher planes using surrogate pair.
-        if (uCode > 0xFFFF) { 
-            uCode -= 0x10000;
-            var uCodeLead = 0xD800 + Math.floor(uCode / 0x400);
-            newBuf[j++] = uCodeLead & 0xFF;
-            newBuf[j++] = uCodeLead >> 8;
-
-            uCode = 0xDC00 + uCode % 0x400;
-        }
-        newBuf[j++] = uCode & 0xFF;
-        newBuf[j++] = uCode >> 8;
-
-        // Reset trie node.
-        nodeIdx = 0; seqStart = i+1;
-    }
-
-    this.nodeIdx = nodeIdx;
-    this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset);
-    return newBuf.slice(0, j).toString('ucs2');
-}
-
-DBCSDecoder.prototype.end = function() {
-    var ret = '';
-
-    // Try to parse all remaining chars.
-    while (this.prevBuf.length > 0) {
-        // Skip 1 character in the buffer.
-        ret += this.defaultCharUnicode;
-        var buf = this.prevBuf.slice(1);
-
-        // Parse remaining as usual.
-        this.prevBuf = Buffer.alloc(0);
-        this.nodeIdx = 0;
-        if (buf.length > 0)
-            ret += this.write(buf);
-    }
-
-    this.nodeIdx = 0;
-    return ret;
-}
-
-// Binary search for GB18030. Returns largest i such that table[i] <= val.
-function findIdx(table, val) {
-    if (table[0] > val)
-        return -1;
-
-    var l = 0, r = table.length;
-    while (l < r-1) { // always table[l] <= val < table[r]
-        var mid = l + Math.floor((r-l+1)/2);
-        if (table[mid] <= val)
-            l = mid;
-        else
-            r = mid;
-    }
-    return l;
-}
-
+"use strict";var Buffer=require("safer-buffer").Buffer;exports._dbcs=DBCSCodec;for(var UNASSIGNED=-1,GB18030_CODE=-2,SEQ_START=-10,NODE_START=-1e3,UNASSIGNED_NODE=new Array(256),DEF_CHAR=-1,i=0;i<256;i++)UNASSIGNED_NODE[i]=UNASSIGNED;function DBCSCodec(e,t){if(this.encodingName=e.encodingName,!e)throw new Error("DBCS codec is called without the data.");if(!e.table)throw new Error("Encoding '"+this.encodingName+"' has no data.");var o=e.table();this.decodeTables=[],this.decodeTables[0]=UNASSIGNED_NODE.slice(0),this.decodeTableSeq=[];for(var r=0;r<o.length;r++)this._addDecodeChunk(o[r]);this.defaultCharUnicode=t.defaultCharUnicode,this.encodeTable=[],this.encodeTableSeq=[];var i={};if(e.encodeSkipVals)for(r=0;r<e.encodeSkipVals.length;r++){var d=e.encodeSkipVals[r];if("number"==typeof d)i[d]=!0;else for(var a=d.from;a<=d.to;a++)i[a]=!0}if(this._fillEncodeTable(0,0,i),e.encodeAdd)for(var n in e.encodeAdd)Object.prototype.hasOwnProperty.call(e.encodeAdd,n)&&this._setEncodeChar(n.charCodeAt(0),e.encodeAdd[n]);if(this.defCharSB=this.encodeTable[0][t.defaultCharSingleByte.charCodeAt(0)],this.defCharSB===UNASSIGNED&&(this.defCharSB=this.encodeTable[0]["?"]),this.defCharSB===UNASSIGNED&&(this.defCharSB="?".charCodeAt(0)),"function"==typeof e.gb18030){this.gb18030=e.gb18030();var h=this.decodeTables.length,s=this.decodeTables[h]=UNASSIGNED_NODE.slice(0),c=this.decodeTables.length,l=this.decodeTables[c]=UNASSIGNED_NODE.slice(0);for(r=129;r<=254;r++){var S=NODE_START-this.decodeTables[0][r],f=this.decodeTables[S];for(a=48;a<=57;a++)f[a]=NODE_START-h}for(r=129;r<=254;r++)s[r]=NODE_START-c;for(r=48;r<=57;r++)l[r]=GB18030_CODE}}function DBCSEncoder(e,t){this.leadSurrogate=-1,this.seqObj=void 0,this.encodeTable=t.encodeTable,this.encodeTableSeq=t.encodeTableSeq,this.defaultCharSingleByte=t.defCharSB,this.gb18030=t.gb18030}function DBCSDecoder(e,t){this.nodeIdx=0,this.prevBuf=Buffer.alloc(0),this.decodeTables=t.decodeTables,this.decodeTableSeq=t.decodeTableSeq,this.defaultCharUnicode=t.defaultCharUnicode,this.gb18030=t.gb18030}function findIdx(e,t){if(e[0]>t)return-1;for(var o=0,r=e.length;o<r-1;){var i=o+Math.floor((r-o+1)/2);e[i]<=t?o=i:r=i}return o}DBCSCodec.prototype.encoder=DBCSEncoder,DBCSCodec.prototype.decoder=DBCSDecoder,DBCSCodec.prototype._getDecodeTrieNode=function(e){for(var t=[];e>0;e>>=8)t.push(255&e);0==t.length&&t.push(0);for(var o=this.decodeTables[0],r=t.length-1;r>0;r--){var i=o[t[r]];if(i==UNASSIGNED)o[t[r]]=NODE_START-this.decodeTables.length,this.decodeTables.push(o=UNASSIGNED_NODE.slice(0));else{if(!(i<=NODE_START))throw new Error("Overwrite byte in "+this.encodingName+", addr: "+e.toString(16));o=this.decodeTables[NODE_START-i]}}return o},DBCSCodec.prototype._addDecodeChunk=function(e){var t=parseInt(e[0],16),o=this._getDecodeTrieNode(t);t&=255;for(var r=1;r<e.length;r++){var i=e[r];if("string"==typeof i)for(var d=0;d<i.length;){var a=i.charCodeAt(d++);if(55296<=a&&a<56320){var n=i.charCodeAt(d++);if(!(56320<=n&&n<57344))throw new Error("Incorrect surrogate pair in "+this.encodingName+" at chunk "+e[0]);o[t++]=65536+1024*(a-55296)+(n-56320)}else if(4080<a&&a<=4095){for(var h=4095-a+2,s=[],c=0;c<h;c++)s.push(i.charCodeAt(d++));o[t++]=SEQ_START-this.decodeTableSeq.length,this.decodeTableSeq.push(s)}else o[t++]=a}else{if("number"!=typeof i)throw new Error("Incorrect type '"+typeof i+"' given in "+this.encodingName+" at chunk "+e[0]);var l=o[t-1]+1;for(d=0;d<i;d++)o[t++]=l++}}if(t>255)throw new Error("Incorrect chunk in "+this.encodingName+" at addr "+e[0]+": too long"+t)},DBCSCodec.prototype._getEncodeBucket=function(e){var t=e>>8;return void 0===this.encodeTable[t]&&(this.encodeTable[t]=UNASSIGNED_NODE.slice(0)),this.encodeTable[t]},DBCSCodec.prototype._setEncodeChar=function(e,t){var o=this._getEncodeBucket(e),r=255&e;o[r]<=SEQ_START?this.encodeTableSeq[SEQ_START-o[r]][DEF_CHAR]=t:o[r]==UNASSIGNED&&(o[r]=t)},DBCSCodec.prototype._setEncodeSequence=function(e,t){var o,r=e[0],i=this._getEncodeBucket(r),d=255&r;i[d]<=SEQ_START?o=this.encodeTableSeq[SEQ_START-i[d]]:(o={},i[d]!==UNASSIGNED&&(o[DEF_CHAR]=i[d]),i[d]=SEQ_START-this.encodeTableSeq.length,this.encodeTableSeq.push(o));for(var a=1;a<e.length-1;a++){var n=o[r];"object"==typeof n?o=n:(o=o[r]={},void 0!==n&&(o[DEF_CHAR]=n))}o[r=e[e.length-1]]=t},DBCSCodec.prototype._fillEncodeTable=function(e,t,o){for(var r=this.decodeTables[e],i=0;i<256;i++){var d=r[i],a=t+i;o[a]||(d>=0?this._setEncodeChar(d,a):d<=NODE_START?this._fillEncodeTable(NODE_START-d,a<<8,o):d<=SEQ_START&&this._setEncodeSequence(this.decodeTableSeq[SEQ_START-d],a))}},DBCSEncoder.prototype.write=function(e){for(var t=Buffer.alloc(e.length*(this.gb18030?4:3)),o=this.leadSurrogate,r=this.seqObj,i=-1,d=0,a=0;;){if(-1===i){if(d==e.length)break;var n=e.charCodeAt(d++)}else{n=i;i=-1}if(55296<=n&&n<57344)if(n<56320){if(-1===o){o=n;continue}o=n,n=UNASSIGNED}else-1!==o?(n=65536+1024*(o-55296)+(n-56320),o=-1):n=UNASSIGNED;else-1!==o&&(i=n,n=UNASSIGNED,o=-1);var h=UNASSIGNED;if(void 0!==r&&n!=UNASSIGNED){var s=r[n];if("object"==typeof s){r=s;continue}"number"==typeof s?h=s:null==s&&void 0!==(s=r[DEF_CHAR])&&(h=s,i=n),r=void 0}else if(n>=0){var c=this.encodeTable[n>>8];if(void 0!==c&&(h=c[255&n]),h<=SEQ_START){r=this.encodeTableSeq[SEQ_START-h];continue}if(h==UNASSIGNED&&this.gb18030){var l=findIdx(this.gb18030.uChars,n);if(-1!=l){h=this.gb18030.gbChars[l]+(n-this.gb18030.uChars[l]);t[a++]=129+Math.floor(h/12600),h%=12600,t[a++]=48+Math.floor(h/1260),h%=1260,t[a++]=129+Math.floor(h/10),h%=10,t[a++]=48+h;continue}}}h===UNASSIGNED&&(h=this.defaultCharSingleByte),h<256?t[a++]=h:h<65536?(t[a++]=h>>8,t[a++]=255&h):(t[a++]=h>>16,t[a++]=h>>8&255,t[a++]=255&h)}return this.seqObj=r,this.leadSurrogate=o,t.slice(0,a)},DBCSEncoder.prototype.end=function(){if(-1!==this.leadSurrogate||void 0!==this.seqObj){var e=Buffer.alloc(10),t=0;if(this.seqObj){var o=this.seqObj[DEF_CHAR];void 0!==o&&(o<256?e[t++]=o:(e[t++]=o>>8,e[t++]=255&o)),this.seqObj=void 0}return-1!==this.leadSurrogate&&(e[t++]=this.defaultCharSingleByte,this.leadSurrogate=-1),e.slice(0,t)}},DBCSEncoder.prototype.findIdx=findIdx,DBCSDecoder.prototype.write=function(e){var t=Buffer.alloc(2*e.length),o=this.nodeIdx,r=this.prevBuf,i=this.prevBuf.length,d=-this.prevBuf.length;i>0&&(r=Buffer.concat([r,e.slice(0,10)]));for(var a=0,n=0;a<e.length;a++){var h,s=a>=0?e[a]:r[a+i];if((h=this.decodeTables[o][s])>=0);else if(h===UNASSIGNED)a=d,h=this.defaultCharUnicode.charCodeAt(0);else if(h===GB18030_CODE){var c=d>=0?e.slice(d,a+1):r.slice(d+i,a+1+i),l=12600*(c[0]-129)+1260*(c[1]-48)+10*(c[2]-129)+(c[3]-48),S=findIdx(this.gb18030.gbChars,l);h=this.gb18030.uChars[S]+l-this.gb18030.gbChars[S]}else{if(h<=NODE_START){o=NODE_START-h;continue}if(!(h<=SEQ_START))throw new Error("iconv-lite internal error: invalid decoding table value "+h+" at "+o+"/"+s);for(var f=this.decodeTableSeq[SEQ_START-h],T=0;T<f.length-1;T++)h=f[T],t[n++]=255&h,t[n++]=h>>8;h=f[f.length-1]}if(h>65535){h-=65536;var u=55296+Math.floor(h/1024);t[n++]=255&u,t[n++]=u>>8,h=56320+h%1024}t[n++]=255&h,t[n++]=h>>8,o=0,d=a+1}return this.nodeIdx=o,this.prevBuf=d>=0?e.slice(d):r.slice(d+i),t.slice(0,n).toString("ucs2")},DBCSDecoder.prototype.end=function(){for(var e="";this.prevBuf.length>0;){e+=this.defaultCharUnicode;var t=this.prevBuf.slice(1);this.prevBuf=Buffer.alloc(0),this.nodeIdx=0,t.length>0&&(e+=this.write(t))}return this.nodeIdx=0,e};
\ No newline at end of file
index 4b61914..4aaa2b6 100644 (file)
@@ -1,176 +1 @@
-"use strict";
-
-// Description of supported double byte encodings and aliases.
-// Tables are not require()-d until they are needed to speed up library load.
-// require()-s are direct to support Browserify.
-
-module.exports = {
-    
-    // == Japanese/ShiftJIS ====================================================
-    // All japanese encodings are based on JIS X set of standards:
-    // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF.
-    // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. 
-    //              Has several variations in 1978, 1983, 1990 and 1997.
-    // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead.
-    // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233.
-    //              2 planes, first is superset of 0208, second - revised 0212.
-    //              Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx)
-
-    // Byte encodings are:
-    //  * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte
-    //               encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC.
-    //               Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI.
-    //  * EUC-JP:    Up to 3 bytes per character. Used mostly on *nixes.
-    //               0x00-0x7F       - lower part of 0201
-    //               0x8E, 0xA1-0xDF - upper part of 0201
-    //               (0xA1-0xFE)x2   - 0208 plane (94x94).
-    //               0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94).
-    //  * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon.
-    //               Used as-is in ISO2022 family.
-    //  * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, 
-    //                0201-1976 Roman, 0208-1978, 0208-1983.
-    //  * ISO2022-JP-1: Adds esc seq for 0212-1990.
-    //  * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7.
-    //  * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2.
-    //  * ISO2022-JP-2004: Adds 0213-2004 Plane 1.
-    //
-    // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes.
-    //
-    // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html
-
-    'shiftjis': {
-        type: '_dbcs',
-        table: function() { return require('./tables/shiftjis.json') },
-        encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E},
-        encodeSkipVals: [{from: 0xED40, to: 0xF940}],
-    },
-    'csshiftjis': 'shiftjis',
-    'mskanji': 'shiftjis',
-    'sjis': 'shiftjis',
-    'windows31j': 'shiftjis',
-    'ms31j': 'shiftjis',
-    'xsjis': 'shiftjis',
-    'windows932': 'shiftjis',
-    'ms932': 'shiftjis',
-    '932': 'shiftjis',
-    'cp932': 'shiftjis',
-
-    'eucjp': {
-        type: '_dbcs',
-        table: function() { return require('./tables/eucjp.json') },
-        encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E},
-    },
-
-    // TODO: KDDI extension to Shift_JIS
-    // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes.
-    // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars.
-
-
-    // == Chinese/GBK ==========================================================
-    // http://en.wikipedia.org/wiki/GBK
-    // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder
-
-    // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936
-    'gb2312': 'cp936',
-    'gb231280': 'cp936',
-    'gb23121980': 'cp936',
-    'csgb2312': 'cp936',
-    'csiso58gb231280': 'cp936',
-    'euccn': 'cp936',
-
-    // Microsoft's CP936 is a subset and approximation of GBK.
-    'windows936': 'cp936',
-    'ms936': 'cp936',
-    '936': 'cp936',
-    'cp936': {
-        type: '_dbcs',
-        table: function() { return require('./tables/cp936.json') },
-    },
-
-    // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other.
-    'gbk': {
-        type: '_dbcs',
-        table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) },
-    },
-    'xgbk': 'gbk',
-    'isoir58': 'gbk',
-
-    // GB18030 is an algorithmic extension of GBK.
-    // Main source: https://www.w3.org/TR/encoding/#gbk-encoder
-    // http://icu-project.org/docs/papers/gb18030.html
-    // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml
-    // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0
-    'gb18030': {
-        type: '_dbcs',
-        table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) },
-        gb18030: function() { return require('./tables/gb18030-ranges.json') },
-        encodeSkipVals: [0x80],
-        encodeAdd: {'€': 0xA2E3},
-    },
-
-    'chinese': 'gb18030',
-
-
-    // == Korean ===============================================================
-    // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same.
-    'windows949': 'cp949',
-    'ms949': 'cp949',
-    '949': 'cp949',
-    'cp949': {
-        type: '_dbcs',
-        table: function() { return require('./tables/cp949.json') },
-    },
-
-    'cseuckr': 'cp949',
-    'csksc56011987': 'cp949',
-    'euckr': 'cp949',
-    'isoir149': 'cp949',
-    'korean': 'cp949',
-    'ksc56011987': 'cp949',
-    'ksc56011989': 'cp949',
-    'ksc5601': 'cp949',
-
-
-    // == Big5/Taiwan/Hong Kong ================================================
-    // There are lots of tables for Big5 and cp950. Please see the following links for history:
-    // http://moztw.org/docs/big5/  http://www.haible.de/bruno/charsets/conversion-tables/Big5.html
-    // Variations, in roughly number of defined chars:
-    //  * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT
-    //  * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/
-    //  * Big5-2003 (Taiwan standard) almost superset of cp950.
-    //  * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers.
-    //  * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. 
-    //    many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years.
-    //    Plus, it has 4 combining sequences.
-    //    Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299
-    //    because big5-hkscs is the only encoding to include astral characters in non-algorithmic way.
-    //    Implementations are not consistent within browsers; sometimes labeled as just big5.
-    //    MS Internet Explorer switches from big5 to big5-hkscs when a patch applied.
-    //    Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31
-    //    In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s.
-    //    Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt
-    //                   http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt
-    // 
-    // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder
-    // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong.
-
-    'windows950': 'cp950',
-    'ms950': 'cp950',
-    '950': 'cp950',
-    'cp950': {
-        type: '_dbcs',
-        table: function() { return require('./tables/cp950.json') },
-    },
-
-    // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus.
-    'big5': 'big5hkscs',
-    'big5hkscs': {
-        type: '_dbcs',
-        table: function() { return require('./tables/cp950.json').concat(require('./tables/big5-added.json')) },
-        encodeSkipVals: [0xa2cc],
-    },
-
-    'cnbig5': 'big5hkscs',
-    'csbig5': 'big5hkscs',
-    'xxbig5': 'big5hkscs',
-};
+"use strict";module.exports={shiftjis:{type:"_dbcs",table:function(){return require("./tables/shiftjis.json")},encodeAdd:{"¥":92,"‾":126},encodeSkipVals:[{from:60736,to:63808}]},csshiftjis:"shiftjis",mskanji:"shiftjis",sjis:"shiftjis",windows31j:"shiftjis",ms31j:"shiftjis",xsjis:"shiftjis",windows932:"shiftjis",ms932:"shiftjis",932:"shiftjis",cp932:"shiftjis",eucjp:{type:"_dbcs",table:function(){return require("./tables/eucjp.json")},encodeAdd:{"¥":92,"‾":126}},gb2312:"cp936",gb231280:"cp936",gb23121980:"cp936",csgb2312:"cp936",csiso58gb231280:"cp936",euccn:"cp936",windows936:"cp936",ms936:"cp936",936:"cp936",cp936:{type:"_dbcs",table:function(){return require("./tables/cp936.json")}},gbk:{type:"_dbcs",table:function(){return require("./tables/cp936.json").concat(require("./tables/gbk-added.json"))}},xgbk:"gbk",isoir58:"gbk",gb18030:{type:"_dbcs",table:function(){return require("./tables/cp936.json").concat(require("./tables/gbk-added.json"))},gb18030:function(){return require("./tables/gb18030-ranges.json")},encodeSkipVals:[128],encodeAdd:{"€":41699}},chinese:"gb18030",windows949:"cp949",ms949:"cp949",949:"cp949",cp949:{type:"_dbcs",table:function(){return require("./tables/cp949.json")}},cseuckr:"cp949",csksc56011987:"cp949",euckr:"cp949",isoir149:"cp949",korean:"cp949",ksc56011987:"cp949",ksc56011989:"cp949",ksc5601:"cp949",windows950:"cp950",ms950:"cp950",950:"cp950",cp950:{type:"_dbcs",table:function(){return require("./tables/cp950.json")}},big5:"big5hkscs",big5hkscs:{type:"_dbcs",table:function(){return require("./tables/cp950.json").concat(require("./tables/big5-added.json"))},encodeSkipVals:[41676]},cnbig5:"big5hkscs",csbig5:"big5hkscs",xxbig5:"big5hkscs"};
\ No newline at end of file
index e304003..6709a4c 100644 (file)
@@ -1,22 +1 @@
-"use strict";
-
-// Update this array if you add/rename/remove files in this directory.
-// We support Browserify by skipping automatic module discovery and requiring modules directly.
-var modules = [
-    require("./internal"),
-    require("./utf16"),
-    require("./utf7"),
-    require("./sbcs-codec"),
-    require("./sbcs-data"),
-    require("./sbcs-data-generated"),
-    require("./dbcs-codec"),
-    require("./dbcs-data"),
-];
-
-// Put all encoding/alias/codec definitions to single object and export it. 
-for (var i = 0; i < modules.length; i++) {
-    var module = modules[i];
-    for (var enc in module)
-        if (Object.prototype.hasOwnProperty.call(module, enc))
-            exports[enc] = module[enc];
-}
+"use strict";for(var modules=[require("./internal"),require("./utf16"),require("./utf7"),require("./sbcs-codec"),require("./sbcs-data"),require("./sbcs-data-generated"),require("./dbcs-codec"),require("./dbcs-data")],i=0;i<modules.length;i++){var module=modules[i];for(var enc in module)Object.prototype.hasOwnProperty.call(module,enc)&&(exports[enc]=module[enc])}
\ No newline at end of file
index 05ce38b..c7e4694 100644 (file)
@@ -1,188 +1 @@
-"use strict";
-var Buffer = require("safer-buffer").Buffer;
-
-// Export Node.js internal encodings.
-
-module.exports = {
-    // Encodings
-    utf8:   { type: "_internal", bomAware: true},
-    cesu8:  { type: "_internal", bomAware: true},
-    unicode11utf8: "utf8",
-
-    ucs2:   { type: "_internal", bomAware: true},
-    utf16le: "ucs2",
-
-    binary: { type: "_internal" },
-    base64: { type: "_internal" },
-    hex:    { type: "_internal" },
-
-    // Codec.
-    _internal: InternalCodec,
-};
-
-//------------------------------------------------------------------------------
-
-function InternalCodec(codecOptions, iconv) {
-    this.enc = codecOptions.encodingName;
-    this.bomAware = codecOptions.bomAware;
-
-    if (this.enc === "base64")
-        this.encoder = InternalEncoderBase64;
-    else if (this.enc === "cesu8") {
-        this.enc = "utf8"; // Use utf8 for decoding.
-        this.encoder = InternalEncoderCesu8;
-
-        // Add decoder for versions of Node not supporting CESU-8
-        if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') {
-            this.decoder = InternalDecoderCesu8;
-            this.defaultCharUnicode = iconv.defaultCharUnicode;
-        }
-    }
-}
-
-InternalCodec.prototype.encoder = InternalEncoder;
-InternalCodec.prototype.decoder = InternalDecoder;
-
-//------------------------------------------------------------------------------
-
-// We use node.js internal decoder. Its signature is the same as ours.
-var StringDecoder = require('string_decoder').StringDecoder;
-
-if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method.
-    StringDecoder.prototype.end = function() {};
-
-
-function InternalDecoder(options, codec) {
-    StringDecoder.call(this, codec.enc);
-}
-
-InternalDecoder.prototype = StringDecoder.prototype;
-
-
-//------------------------------------------------------------------------------
-// Encoder is mostly trivial
-
-function InternalEncoder(options, codec) {
-    this.enc = codec.enc;
-}
-
-InternalEncoder.prototype.write = function(str) {
-    return Buffer.from(str, this.enc);
-}
-
-InternalEncoder.prototype.end = function() {
-}
-
-
-//------------------------------------------------------------------------------
-// Except base64 encoder, which must keep its state.
-
-function InternalEncoderBase64(options, codec) {
-    this.prevStr = '';
-}
-
-InternalEncoderBase64.prototype.write = function(str) {
-    str = this.prevStr + str;
-    var completeQuads = str.length - (str.length % 4);
-    this.prevStr = str.slice(completeQuads);
-    str = str.slice(0, completeQuads);
-
-    return Buffer.from(str, "base64");
-}
-
-InternalEncoderBase64.prototype.end = function() {
-    return Buffer.from(this.prevStr, "base64");
-}
-
-
-//------------------------------------------------------------------------------
-// CESU-8 encoder is also special.
-
-function InternalEncoderCesu8(options, codec) {
-}
-
-InternalEncoderCesu8.prototype.write = function(str) {
-    var buf = Buffer.alloc(str.length * 3), bufIdx = 0;
-    for (var i = 0; i < str.length; i++) {
-        var charCode = str.charCodeAt(i);
-        // Naive implementation, but it works because CESU-8 is especially easy
-        // to convert from UTF-16 (which all JS strings are encoded in).
-        if (charCode < 0x80)
-            buf[bufIdx++] = charCode;
-        else if (charCode < 0x800) {
-            buf[bufIdx++] = 0xC0 + (charCode >>> 6);
-            buf[bufIdx++] = 0x80 + (charCode & 0x3f);
-        }
-        else { // charCode will always be < 0x10000 in javascript.
-            buf[bufIdx++] = 0xE0 + (charCode >>> 12);
-            buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f);
-            buf[bufIdx++] = 0x80 + (charCode & 0x3f);
-        }
-    }
-    return buf.slice(0, bufIdx);
-}
-
-InternalEncoderCesu8.prototype.end = function() {
-}
-
-//------------------------------------------------------------------------------
-// CESU-8 decoder is not implemented in Node v4.0+
-
-function InternalDecoderCesu8(options, codec) {
-    this.acc = 0;
-    this.contBytes = 0;
-    this.accBytes = 0;
-    this.defaultCharUnicode = codec.defaultCharUnicode;
-}
-
-InternalDecoderCesu8.prototype.write = function(buf) {
-    var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, 
-        res = '';
-    for (var i = 0; i < buf.length; i++) {
-        var curByte = buf[i];
-        if ((curByte & 0xC0) !== 0x80) { // Leading byte
-            if (contBytes > 0) { // Previous code is invalid
-                res += this.defaultCharUnicode;
-                contBytes = 0;
-            }
-
-            if (curByte < 0x80) { // Single-byte code
-                res += String.fromCharCode(curByte);
-            } else if (curByte < 0xE0) { // Two-byte code
-                acc = curByte & 0x1F;
-                contBytes = 1; accBytes = 1;
-            } else if (curByte < 0xF0) { // Three-byte code
-                acc = curByte & 0x0F;
-                contBytes = 2; accBytes = 1;
-            } else { // Four or more are not supported for CESU-8.
-                res += this.defaultCharUnicode;
-            }
-        } else { // Continuation byte
-            if (contBytes > 0) { // We're waiting for it.
-                acc = (acc << 6) | (curByte & 0x3f);
-                contBytes--; accBytes++;
-                if (contBytes === 0) {
-                    // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80)
-                    if (accBytes === 2 && acc < 0x80 && acc > 0)
-                        res += this.defaultCharUnicode;
-                    else if (accBytes === 3 && acc < 0x800)
-                        res += this.defaultCharUnicode;
-                    else
-                        // Actually add character.
-                        res += String.fromCharCode(acc);
-                }
-            } else { // Unexpected continuation byte
-                res += this.defaultCharUnicode;
-            }
-        }
-    }
-    this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes;
-    return res;
-}
-
-InternalDecoderCesu8.prototype.end = function() {
-    var res = 0;
-    if (this.contBytes > 0)
-        res += this.defaultCharUnicode;
-    return res;
-}
+"use strict";var Buffer=require("safer-buffer").Buffer;function InternalCodec(e,t){this.enc=e.encodingName,this.bomAware=e.bomAware,"base64"===this.enc?this.encoder=InternalEncoderBase64:"cesu8"===this.enc&&(this.enc="utf8",this.encoder=InternalEncoderCesu8,"💩"!==Buffer.from("eda0bdedb2a9","hex").toString()&&(this.decoder=InternalDecoderCesu8,this.defaultCharUnicode=t.defaultCharUnicode))}module.exports={utf8:{type:"_internal",bomAware:!0},cesu8:{type:"_internal",bomAware:!0},unicode11utf8:"utf8",ucs2:{type:"_internal",bomAware:!0},utf16le:"ucs2",binary:{type:"_internal"},base64:{type:"_internal"},hex:{type:"_internal"},_internal:InternalCodec},InternalCodec.prototype.encoder=InternalEncoder,InternalCodec.prototype.decoder=InternalDecoder;var StringDecoder=require("string_decoder").StringDecoder;function InternalDecoder(e,t){StringDecoder.call(this,t.enc)}function InternalEncoder(e,t){this.enc=t.enc}function InternalEncoderBase64(e,t){this.prevStr=""}function InternalEncoderCesu8(e,t){}function InternalDecoderCesu8(e,t){this.acc=0,this.contBytes=0,this.accBytes=0,this.defaultCharUnicode=t.defaultCharUnicode}StringDecoder.prototype.end||(StringDecoder.prototype.end=function(){}),InternalDecoder.prototype=StringDecoder.prototype,InternalEncoder.prototype.write=function(e){return Buffer.from(e,this.enc)},InternalEncoder.prototype.end=function(){},InternalEncoderBase64.prototype.write=function(e){var t=(e=this.prevStr+e).length-e.length%4;return this.prevStr=e.slice(t),e=e.slice(0,t),Buffer.from(e,"base64")},InternalEncoderBase64.prototype.end=function(){return Buffer.from(this.prevStr,"base64")},InternalEncoderCesu8.prototype.write=function(e){for(var t=Buffer.alloc(3*e.length),r=0,n=0;n<e.length;n++){var o=e.charCodeAt(n);o<128?t[r++]=o:o<2048?(t[r++]=192+(o>>>6),t[r++]=128+(63&o)):(t[r++]=224+(o>>>12),t[r++]=128+(o>>>6&63),t[r++]=128+(63&o))}return t.slice(0,r)},InternalEncoderCesu8.prototype.end=function(){},InternalDecoderCesu8.prototype.write=function(e){for(var t=this.acc,r=this.contBytes,n=this.accBytes,o="",c=0;c<e.length;c++){var i=e[c];128!=(192&i)?(r>0&&(o+=this.defaultCharUnicode,r=0),i<128?o+=String.fromCharCode(i):i<224?(t=31&i,r=1,n=1):i<240?(t=15&i,r=2,n=1):o+=this.defaultCharUnicode):r>0?(t=t<<6|63&i,n++,0===--r&&(o+=2===n&&t<128&&t>0||3===n&&t<2048?this.defaultCharUnicode:String.fromCharCode(t))):o+=this.defaultCharUnicode}return this.acc=t,this.contBytes=r,this.accBytes=n,o},InternalDecoderCesu8.prototype.end=function(){var e=0;return this.contBytes>0&&(e+=this.defaultCharUnicode),e};
\ No newline at end of file
index abac5ff..c23c013 100644 (file)
@@ -1,72 +1 @@
-"use strict";
-var Buffer = require("safer-buffer").Buffer;
-
-// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that
-// correspond to encoded bytes (if 128 - then lower half is ASCII). 
-
-exports._sbcs = SBCSCodec;
-function SBCSCodec(codecOptions, iconv) {
-    if (!codecOptions)
-        throw new Error("SBCS codec is called without the data.")
-    
-    // Prepare char buffer for decoding.
-    if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256))
-        throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)");
-    
-    if (codecOptions.chars.length === 128) {
-        var asciiString = "";
-        for (var i = 0; i < 128; i++)
-            asciiString += String.fromCharCode(i);
-        codecOptions.chars = asciiString + codecOptions.chars;
-    }
-
-    this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2');
-    
-    // Encoding buffer.
-    var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0));
-
-    for (var i = 0; i < codecOptions.chars.length; i++)
-        encodeBuf[codecOptions.chars.charCodeAt(i)] = i;
-
-    this.encodeBuf = encodeBuf;
-}
-
-SBCSCodec.prototype.encoder = SBCSEncoder;
-SBCSCodec.prototype.decoder = SBCSDecoder;
-
-
-function SBCSEncoder(options, codec) {
-    this.encodeBuf = codec.encodeBuf;
-}
-
-SBCSEncoder.prototype.write = function(str) {
-    var buf = Buffer.alloc(str.length);
-    for (var i = 0; i < str.length; i++)
-        buf[i] = this.encodeBuf[str.charCodeAt(i)];
-    
-    return buf;
-}
-
-SBCSEncoder.prototype.end = function() {
-}
-
-
-function SBCSDecoder(options, codec) {
-    this.decodeBuf = codec.decodeBuf;
-}
-
-SBCSDecoder.prototype.write = function(buf) {
-    // Strings are immutable in JS -> we use ucs2 buffer to speed up computations.
-    var decodeBuf = this.decodeBuf;
-    var newBuf = Buffer.alloc(buf.length*2);
-    var idx1 = 0, idx2 = 0;
-    for (var i = 0; i < buf.length; i++) {
-        idx1 = buf[i]*2; idx2 = i*2;
-        newBuf[idx2] = decodeBuf[idx1];
-        newBuf[idx2+1] = decodeBuf[idx1+1];
-    }
-    return newBuf.toString('ucs2');
-}
-
-SBCSDecoder.prototype.end = function() {
-}
+"use strict";var Buffer=require("safer-buffer").Buffer;function SBCSCodec(e,r){if(!e)throw new Error("SBCS codec is called without the data.");if(!e.chars||128!==e.chars.length&&256!==e.chars.length)throw new Error("Encoding '"+e.type+"' has incorrect 'chars' (must be of len 128 or 256)");if(128===e.chars.length){for(var o="",t=0;t<128;t++)o+=String.fromCharCode(t);e.chars=o+e.chars}this.decodeBuf=Buffer.from(e.chars,"ucs2");var c=Buffer.alloc(65536,r.defaultCharSingleByte.charCodeAt(0));for(t=0;t<e.chars.length;t++)c[e.chars.charCodeAt(t)]=t;this.encodeBuf=c}function SBCSEncoder(e,r){this.encodeBuf=r.encodeBuf}function SBCSDecoder(e,r){this.decodeBuf=r.decodeBuf}exports._sbcs=SBCSCodec,SBCSCodec.prototype.encoder=SBCSEncoder,SBCSCodec.prototype.decoder=SBCSDecoder,SBCSEncoder.prototype.write=function(e){for(var r=Buffer.alloc(e.length),o=0;o<e.length;o++)r[o]=this.encodeBuf[e.charCodeAt(o)];return r},SBCSEncoder.prototype.end=function(){},SBCSDecoder.prototype.write=function(e){for(var r=this.decodeBuf,o=Buffer.alloc(2*e.length),t=0,c=0,n=0;n<e.length;n++)t=2*e[n],o[c=2*n]=r[t],o[c+1]=r[t+1];return o.toString("ucs2")},SBCSDecoder.prototype.end=function(){};
\ No newline at end of file
index 9b48236..abc7f1a 100644 (file)
@@ -1,451 +1 @@
-"use strict";
-
-// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script.
-module.exports = {
-  "437": "cp437",
-  "737": "cp737",
-  "775": "cp775",
-  "850": "cp850",
-  "852": "cp852",
-  "855": "cp855",
-  "856": "cp856",
-  "857": "cp857",
-  "858": "cp858",
-  "860": "cp860",
-  "861": "cp861",
-  "862": "cp862",
-  "863": "cp863",
-  "864": "cp864",
-  "865": "cp865",
-  "866": "cp866",
-  "869": "cp869",
-  "874": "windows874",
-  "922": "cp922",
-  "1046": "cp1046",
-  "1124": "cp1124",
-  "1125": "cp1125",
-  "1129": "cp1129",
-  "1133": "cp1133",
-  "1161": "cp1161",
-  "1162": "cp1162",
-  "1163": "cp1163",
-  "1250": "windows1250",
-  "1251": "windows1251",
-  "1252": "windows1252",
-  "1253": "windows1253",
-  "1254": "windows1254",
-  "1255": "windows1255",
-  "1256": "windows1256",
-  "1257": "windows1257",
-  "1258": "windows1258",
-  "28591": "iso88591",
-  "28592": "iso88592",
-  "28593": "iso88593",
-  "28594": "iso88594",
-  "28595": "iso88595",
-  "28596": "iso88596",
-  "28597": "iso88597",
-  "28598": "iso88598",
-  "28599": "iso88599",
-  "28600": "iso885910",
-  "28601": "iso885911",
-  "28603": "iso885913",
-  "28604": "iso885914",
-  "28605": "iso885915",
-  "28606": "iso885916",
-  "windows874": {
-    "type": "_sbcs",
-    "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
-  },
-  "win874": "windows874",
-  "cp874": "windows874",
-  "windows1250": {
-    "type": "_sbcs",
-    "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙"
-  },
-  "win1250": "windows1250",
-  "cp1250": "windows1250",
-  "windows1251": {
-    "type": "_sbcs",
-    "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
-  },
-  "win1251": "windows1251",
-  "cp1251": "windows1251",
-  "windows1252": {
-    "type": "_sbcs",
-    "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
-  },
-  "win1252": "windows1252",
-  "cp1252": "windows1252",
-  "windows1253": {
-    "type": "_sbcs",
-    "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�"
-  },
-  "win1253": "windows1253",
-  "cp1253": "windows1253",
-  "windows1254": {
-    "type": "_sbcs",
-    "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ"
-  },
-  "win1254": "windows1254",
-  "cp1254": "windows1254",
-  "windows1255": {
-    "type": "_sbcs",
-    "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�"
-  },
-  "win1255": "windows1255",
-  "cp1255": "windows1255",
-  "windows1256": {
-    "type": "_sbcs",
-    "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے"
-  },
-  "win1256": "windows1256",
-  "cp1256": "windows1256",
-  "windows1257": {
-    "type": "_sbcs",
-    "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙"
-  },
-  "win1257": "windows1257",
-  "cp1257": "windows1257",
-  "windows1258": {
-    "type": "_sbcs",
-    "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
-  },
-  "win1258": "windows1258",
-  "cp1258": "windows1258",
-  "iso88591": {
-    "type": "_sbcs",
-    "chars": "\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
-  },
-  "cp28591": "iso88591",
-  "iso88592": {
-    "type": "_sbcs",
-    "chars": "\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙"
-  },
-  "cp28592": "iso88592",
-  "iso88593": {
-    "type": "_sbcs",
-    "chars": "\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f Ħ˘£¤�Ĥ§¨İŞĞĴ­�Ż°ħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙"
-  },
-  "cp28593": "iso88593",
-  "iso88594": {
-    "type": "_sbcs",
-    "chars": "\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ĄĸŖ¤ĨĻ§¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩļˇ¸šēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖ×ØŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙"
-  },
-  "cp28594": "iso88594",
-  "iso88595": {
-    "type": "_sbcs",
-    "chars": "\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ"
-  },
-  "cp28595": "iso88595",
-  "iso88596": {
-    "type": "_sbcs",
-    "chars": "\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������"
-  },
-  "cp28596": "iso88596",
-  "iso88597": {
-    "type": "_sbcs",
-    "chars": "\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�"
-  },
-  "cp28597": "iso88597",
-  "iso88598": {
-    "type": "_sbcs",
-    "chars": "\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�"
-  },
-  "cp28598": "iso88598",
-  "iso88599": {
-    "type": "_sbcs",
-    "chars": "\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ"
-  },
-  "cp28599": "iso88599",
-  "iso885910": {
-    "type": "_sbcs",
-    "chars": "\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ĄĒĢĪĨĶ§ĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ"
-  },
-  "cp28600": "iso885910",
-  "iso885911": {
-    "type": "_sbcs",
-    "chars": "\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
-  },
-  "cp28601": "iso885911",
-  "iso885913": {
-    "type": "_sbcs",
-    "chars": "\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’"
-  },
-  "cp28603": "iso885913",
-  "iso885914": {
-    "type": "_sbcs",
-    "chars": "\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ"
-  },
-  "cp28604": "iso885914",
-  "iso885915": {
-    "type": "_sbcs",
-    "chars": "\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
-  },
-  "cp28605": "iso885915",
-  "iso885916": {
-    "type": "_sbcs",
-    "chars": "\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ĄąŁ€„Š§š©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ"
-  },
-  "cp28606": "iso885916",
-  "cp437": {
-    "type": "_sbcs",
-    "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
-  },
-  "ibm437": "cp437",
-  "csibm437": "cp437",
-  "cp737": {
-    "type": "_sbcs",
-    "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ "
-  },
-  "ibm737": "cp737",
-  "csibm737": "cp737",
-  "cp775": {
-    "type": "_sbcs",
-    "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£ØפĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ "
-  },
-  "ibm775": "cp775",
-  "csibm775": "cp775",
-  "cp850": {
-    "type": "_sbcs",
-    "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ "
-  },
-  "ibm850": "cp850",
-  "csibm850": "cp850",
-  "cp852": {
-    "type": "_sbcs",
-    "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ "
-  },
-  "ibm852": "cp852",
-  "csibm852": "cp852",
-  "cp855": {
-    "type": "_sbcs",
-    "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ "
-  },
-  "ibm855": "cp855",
-  "csibm855": "cp855",
-  "cp856": {
-    "type": "_sbcs",
-    "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ "
-  },
-  "ibm856": "cp856",
-  "csibm856": "cp856",
-  "cp857": {
-    "type": "_sbcs",
-    "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ "
-  },
-  "ibm857": "cp857",
-  "csibm857": "cp857",
-  "cp858": {
-    "type": "_sbcs",
-    "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ "
-  },
-  "ibm858": "cp858",
-  "csibm858": "cp858",
-  "cp860": {
-    "type": "_sbcs",
-    "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
-  },
-  "ibm860": "cp860",
-  "csibm860": "cp860",
-  "cp861": {
-    "type": "_sbcs",
-    "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
-  },
-  "ibm861": "cp861",
-  "csibm861": "cp861",
-  "cp862": {
-    "type": "_sbcs",
-    "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
-  },
-  "ibm862": "cp862",
-  "csibm862": "cp862",
-  "cp863": {
-    "type": "_sbcs",
-    "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
-  },
-  "ibm863": "cp863",
-  "csibm863": "cp863",
-  "cp864": {
-    "type": "_sbcs",
-    "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\7f°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�"
-  },
-  "ibm864": "cp864",
-  "csibm864": "cp864",
-  "cp865": {
-    "type": "_sbcs",
-    "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
-  },
-  "ibm865": "cp865",
-  "csibm865": "cp865",
-  "cp866": {
-    "type": "_sbcs",
-    "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ "
-  },
-  "ibm866": "cp866",
-  "csibm866": "cp866",
-  "cp869": {
-    "type": "_sbcs",
-    "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ "
-  },
-  "ibm869": "cp869",
-  "csibm869": "cp869",
-  "cp922": {
-    "type": "_sbcs",
-    "chars": "\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖ×ØÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ"
-  },
-  "ibm922": "cp922",
-  "csibm922": "cp922",
-  "cp1046": {
-    "type": "_sbcs",
-    "chars": "ﺈ×÷ﹱ\88■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�"
-  },
-  "ibm1046": "cp1046",
-  "csibm1046": "cp1046",
-  "cp1124": {
-    "type": "_sbcs",
-    "chars": "\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ"
-  },
-  "ibm1124": "cp1124",
-  "csibm1124": "cp1124",
-  "cp1125": {
-    "type": "_sbcs",
-    "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ "
-  },
-  "ibm1125": "cp1125",
-  "csibm1125": "cp1125",
-  "cp1129": {
-    "type": "_sbcs",
-    "chars": "\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
-  },
-  "ibm1129": "cp1129",
-  "csibm1129": "cp1129",
-  "cp1133": {
-    "type": "_sbcs",
-    "chars": "\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�"
-  },
-  "ibm1133": "cp1133",
-  "csibm1133": "cp1133",
-  "cp1161": {
-    "type": "_sbcs",
-    "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ "
-  },
-  "ibm1161": "cp1161",
-  "csibm1161": "cp1161",
-  "cp1162": {
-    "type": "_sbcs",
-    "chars": "€\81\82\83\84\86\87\88\89\8a\8b\8c\8d\8e\8f\90‘’“”•–—\98\99\9a\9b\9c\9d\9e\9f กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
-  },
-  "ibm1162": "cp1162",
-  "csibm1162": "cp1162",
-  "cp1163": {
-    "type": "_sbcs",
-    "chars": "\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"
-  },
-  "ibm1163": "cp1163",
-  "csibm1163": "cp1163",
-  "maccroatian": {
-    "type": "_sbcs",
-    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ"
-  },
-  "maccyrillic": {
-    "type": "_sbcs",
-    "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤"
-  },
-  "macgreek": {
-    "type": "_sbcs",
-    "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�"
-  },
-  "maciceland": {
-    "type": "_sbcs",
-    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
-  },
-  "macroman": {
-    "type": "_sbcs",
-    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
-  },
-  "macromania": {
-    "type": "_sbcs",
-    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
-  },
-  "macthai": {
-    "type": "_sbcs",
-    "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����"
-  },
-  "macturkish": {
-    "type": "_sbcs",
-    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ"
-  },
-  "macukraine": {
-    "type": "_sbcs",
-    "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤"
-  },
-  "koi8r": {
-    "type": "_sbcs",
-    "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
-  },
-  "koi8u": {
-    "type": "_sbcs",
-    "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
-  },
-  "koi8ru": {
-    "type": "_sbcs",
-    "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
-  },
-  "koi8t": {
-    "type": "_sbcs",
-    "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"
-  },
-  "armscii8": {
-    "type": "_sbcs",
-    "chars": "\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�"
-  },
-  "rk1048": {
-    "type": "_sbcs",
-    "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
-  },
-  "tcvn": {
-    "type": "_sbcs",
-    "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\7fÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ"
-  },
-  "georgianacademy": {
-    "type": "_sbcs",
-    "chars": "\80\81‚ƒ„…†‡ˆ‰Š‹Œ\8d\8e\8f\90‘’“”•–—˜™š›œ\9d\9eŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
-  },
-  "georgianps": {
-    "type": "_sbcs",
-    "chars": "\80\81‚ƒ„…†‡ˆ‰Š‹Œ\8d\8e\8f\90‘’“”•–—˜™š›œ\9d\9eŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"
-  },
-  "pt154": {
-    "type": "_sbcs",
-    "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"
-  },
-  "viscii": {
-    "type": "_sbcs",
-    "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\7fẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ"
-  },
-  "iso646cn": {
-    "type": "_sbcs",
-    "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾\7f��������������������������������������������������������������������������������������������������������������������������������"
-  },
-  "iso646jp": {
-    "type": "_sbcs",
-    "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾\7f��������������������������������������������������������������������������������������������������������������������������������"
-  },
-  "hproman8": {
-    "type": "_sbcs",
-    "chars": "\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�"
-  },
-  "macintosh": {
-    "type": "_sbcs",
-    "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"
-  },
-  "ascii": {
-    "type": "_sbcs",
-    "chars": "��������������������������������������������������������������������������������������������������������������������������������"
-  },
-  "tis620": {
-    "type": "_sbcs",
-    "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"
-  }
-}
\ No newline at end of file
+"use strict";module.exports={437:"cp437",737:"cp737",775:"cp775",850:"cp850",852:"cp852",855:"cp855",856:"cp856",857:"cp857",858:"cp858",860:"cp860",861:"cp861",862:"cp862",863:"cp863",864:"cp864",865:"cp865",866:"cp866",869:"cp869",874:"windows874",922:"cp922",1046:"cp1046",1124:"cp1124",1125:"cp1125",1129:"cp1129",1133:"cp1133",1161:"cp1161",1162:"cp1162",1163:"cp1163",1250:"windows1250",1251:"windows1251",1252:"windows1252",1253:"windows1253",1254:"windows1254",1255:"windows1255",1256:"windows1256",1257:"windows1257",1258:"windows1258",28591:"iso88591",28592:"iso88592",28593:"iso88593",28594:"iso88594",28595:"iso88595",28596:"iso88596",28597:"iso88597",28598:"iso88598",28599:"iso88599",28600:"iso885910",28601:"iso885911",28603:"iso885913",28604:"iso885914",28605:"iso885915",28606:"iso885916",windows874:{type:"_sbcs",chars:"€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"},win874:"windows874",cp874:"windows874",windows1250:{type:"_sbcs",chars:"€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙"},win1250:"windows1250",cp1250:"windows1250",windows1251:{type:"_sbcs",chars:"ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"},win1251:"windows1251",cp1251:"windows1251",windows1252:{type:"_sbcs",chars:"€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"},win1252:"windows1252",cp1252:"windows1252",windows1253:{type:"_sbcs",chars:"€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�"},win1253:"windows1253",cp1253:"windows1253",windows1254:{type:"_sbcs",chars:"€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ"},win1254:"windows1254",cp1254:"windows1254",windows1255:{type:"_sbcs",chars:"€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�"},win1255:"windows1255",cp1255:"windows1255",windows1256:{type:"_sbcs",chars:"€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے"},win1256:"windows1256",cp1256:"windows1256",windows1257:{type:"_sbcs",chars:"€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙"},win1257:"windows1257",cp1257:"windows1257",windows1258:{type:"_sbcs",chars:"€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"},win1258:"windows1258",cp1258:"windows1258",iso88591:{type:"_sbcs",chars:"\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"},cp28591:"iso88591",iso88592:{type:"_sbcs",chars:"\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙"},cp28592:"iso88592",iso88593:{type:"_sbcs",chars:"\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f Ħ˘£¤�Ĥ§¨İŞĞĴ­�Ż°ħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙"},cp28593:"iso88593",iso88594:{type:"_sbcs",chars:"\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ĄĸŖ¤ĨĻ§¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩļˇ¸šēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖ×ØŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙"},cp28594:"iso88594",iso88595:{type:"_sbcs",chars:"\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ"},cp28595:"iso88595",iso88596:{type:"_sbcs",chars:"\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������"},cp28596:"iso88596",iso88597:{type:"_sbcs",chars:"\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�"},cp28597:"iso88597",iso88598:{type:"_sbcs",chars:"\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�"},cp28598:"iso88598",iso88599:{type:"_sbcs",chars:"\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ"},cp28599:"iso88599",iso885910:{type:"_sbcs",chars:"\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ĄĒĢĪĨĶ§ĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ"},cp28600:"iso885910",iso885911:{type:"_sbcs",chars:"\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"},cp28601:"iso885911",iso885913:{type:"_sbcs",chars:"\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’"},cp28603:"iso885913",iso885914:{type:"_sbcs",chars:"\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ"},cp28604:"iso885914",iso885915:{type:"_sbcs",chars:"\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"},cp28605:"iso885915",iso885916:{type:"_sbcs",chars:"\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ĄąŁ€„Š§š©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ"},cp28606:"iso885916",cp437:{type:"_sbcs",chars:"ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "},ibm437:"cp437",csibm437:"cp437",cp737:{type:"_sbcs",chars:"ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ "},ibm737:"cp737",csibm737:"cp737",cp775:{type:"_sbcs",chars:"ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£ØפĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ "},ibm775:"cp775",csibm775:"cp775",cp850:{type:"_sbcs",chars:"ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ "},ibm850:"cp850",csibm850:"cp850",cp852:{type:"_sbcs",chars:"ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ "},ibm852:"cp852",csibm852:"cp852",cp855:{type:"_sbcs",chars:"ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ "},ibm855:"cp855",csibm855:"cp855",cp856:{type:"_sbcs",chars:"אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ "},ibm856:"cp856",csibm856:"cp856",cp857:{type:"_sbcs",chars:"ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ "},ibm857:"cp857",csibm857:"cp857",cp858:{type:"_sbcs",chars:"ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ "},ibm858:"cp858",csibm858:"cp858",cp860:{type:"_sbcs",chars:"ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "},ibm860:"cp860",csibm860:"cp860",cp861:{type:"_sbcs",chars:"ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "},ibm861:"cp861",csibm861:"cp861",cp862:{type:"_sbcs",chars:"אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "},ibm862:"cp862",csibm862:"cp862",cp863:{type:"_sbcs",chars:"ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "},ibm863:"cp863",csibm863:"cp863",cp864:{type:"_sbcs",chars:"\0\ 1\ 2\ 3\ 4\ 5\ 6\a\b\t\n\v\f\r\ e\ f\10\11\12\13\14\15\16\17\18\19\1a\e\1c\1d\1e\1f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\7f°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�"},ibm864:"cp864",csibm864:"cp864",cp865:{type:"_sbcs",chars:"ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "},ibm865:"cp865",csibm865:"cp865",cp866:{type:"_sbcs",chars:"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ "},ibm866:"cp866",csibm866:"cp866",cp869:{type:"_sbcs",chars:"������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ "},ibm869:"cp869",csibm869:"cp869",cp922:{type:"_sbcs",chars:"\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖ×ØÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ"},ibm922:"cp922",csibm922:"cp922",cp1046:{type:"_sbcs",chars:"ﺈ×÷ﹱ\88■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�"},ibm1046:"cp1046",csibm1046:"cp1046",cp1124:{type:"_sbcs",chars:"\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ"},ibm1124:"cp1124",csibm1124:"cp1124",cp1125:{type:"_sbcs",chars:"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ "},ibm1125:"cp1125",csibm1125:"cp1125",cp1129:{type:"_sbcs",chars:"\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"},ibm1129:"cp1129",csibm1129:"cp1129",cp1133:{type:"_sbcs",chars:"\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�"},ibm1133:"cp1133",csibm1133:"cp1133",cp1161:{type:"_sbcs",chars:"��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ "},ibm1161:"cp1161",csibm1161:"cp1161",cp1162:{type:"_sbcs",chars:"€\81\82\83\84\86\87\88\89\8a\8b\8c\8d\8e\8f\90‘’“”•–—\98\99\9a\9b\9c\9d\9e\9f กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"},ibm1162:"cp1162",csibm1162:"cp1162",cp1163:{type:"_sbcs",chars:"\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"},ibm1163:"cp1163",csibm1163:"cp1163",maccroatian:{type:"_sbcs",chars:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ"},maccyrillic:{type:"_sbcs",chars:"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤"},macgreek:{type:"_sbcs",chars:"Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�"},maciceland:{type:"_sbcs",chars:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"},macroman:{type:"_sbcs",chars:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"},macromania:{type:"_sbcs",chars:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"},macthai:{type:"_sbcs",chars:"«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู\ufeff​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����"},macturkish:{type:"_sbcs",chars:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ"},macukraine:{type:"_sbcs",chars:"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤"},koi8r:{type:"_sbcs",chars:"─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"},koi8u:{type:"_sbcs",chars:"─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"},koi8ru:{type:"_sbcs",chars:"─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"},koi8t:{type:"_sbcs",chars:"қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ"},armscii8:{type:"_sbcs",chars:"\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�"},rk1048:{type:"_sbcs",chars:"ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"},tcvn:{type:"_sbcs",chars:"\0ÚỤ\ 3ỪỬỮ\a\b\t\n\v\f\r\ e\ f\10ỨỰỲỶỸÝỴ\18\19\1a\e\1c\1d\1e\1f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\7fÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ"},georgianacademy:{type:"_sbcs",chars:"\80\81‚ƒ„…†‡ˆ‰Š‹Œ\8d\8e\8f\90‘’“”•–—˜™š›œ\9d\9eŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ"},georgianps:{type:"_sbcs",chars:"\80\81‚ƒ„…†‡ˆ‰Š‹Œ\8d\8e\8f\90‘’“”•–—˜™š›œ\9d\9eŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"},pt154:{type:"_sbcs",chars:"ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"},viscii:{type:"_sbcs",chars:"\0\ 1\ 3\ 4ẴẪ\a\b\t\n\v\f\r\ e\ f\10\11\12\13\15\16\17\18\1a\e\1c\1d\1f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\7fẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ"},iso646cn:{type:"_sbcs",chars:"\0\ 1\ 2\ 3\ 4\ 5\ 6\a\b\t\n\v\f\r\ e\ f\10\11\12\13\14\15\16\17\18\19\1a\e\1c\1d\1e\1f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾\7f��������������������������������������������������������������������������������������������������������������������������������"},iso646jp:{type:"_sbcs",chars:"\0\ 1\ 2\ 3\ 4\ 5\ 6\a\b\t\n\v\f\r\ e\ f\10\11\12\13\14\15\16\17\18\19\1a\e\1c\1d\1e\1f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾\7f��������������������������������������������������������������������������������������������������������������������������������"},hproman8:{type:"_sbcs",chars:"\80\81\82\83\84\85\86\87\88\89\8a\8b\8c\8d\8e\8f\90\91\92\93\94\95\96\97\98\99\9a\9b\9c\9d\9e\9f ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�"},macintosh:{type:"_sbcs",chars:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"},ascii:{type:"_sbcs",chars:"��������������������������������������������������������������������������������������������������������������������������������"},tis620:{type:"_sbcs",chars:"���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"}};
\ No newline at end of file
index fdb81a3..1b60c14 100644 (file)
@@ -1,174 +1 @@
-"use strict";
-
-// Manually added data to be used by sbcs codec in addition to generated one.
-
-module.exports = {
-    // Not supported by iconv, not sure why.
-    "10029": "maccenteuro",
-    "maccenteuro": {
-        "type": "_sbcs",
-        "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ"
-    },
-
-    "808": "cp808",
-    "ibm808": "cp808",
-    "cp808": {
-        "type": "_sbcs",
-        "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ "
-    },
-
-    "mik": {
-        "type": "_sbcs",
-        "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
-    },
-
-    // Aliases of generated encodings.
-    "ascii8bit": "ascii",
-    "usascii": "ascii",
-    "ansix34": "ascii",
-    "ansix341968": "ascii",
-    "ansix341986": "ascii",
-    "csascii": "ascii",
-    "cp367": "ascii",
-    "ibm367": "ascii",
-    "isoir6": "ascii",
-    "iso646us": "ascii",
-    "iso646irv": "ascii",
-    "us": "ascii",
-
-    "latin1": "iso88591",
-    "latin2": "iso88592",
-    "latin3": "iso88593",
-    "latin4": "iso88594",
-    "latin5": "iso88599",
-    "latin6": "iso885910",
-    "latin7": "iso885913",
-    "latin8": "iso885914",
-    "latin9": "iso885915",
-    "latin10": "iso885916",
-
-    "csisolatin1": "iso88591",
-    "csisolatin2": "iso88592",
-    "csisolatin3": "iso88593",
-    "csisolatin4": "iso88594",
-    "csisolatincyrillic": "iso88595",
-    "csisolatinarabic": "iso88596",
-    "csisolatingreek" : "iso88597",
-    "csisolatinhebrew": "iso88598",
-    "csisolatin5": "iso88599",
-    "csisolatin6": "iso885910",
-
-    "l1": "iso88591",
-    "l2": "iso88592",
-    "l3": "iso88593",
-    "l4": "iso88594",
-    "l5": "iso88599",
-    "l6": "iso885910",
-    "l7": "iso885913",
-    "l8": "iso885914",
-    "l9": "iso885915",
-    "l10": "iso885916",
-
-    "isoir14": "iso646jp",
-    "isoir57": "iso646cn",
-    "isoir100": "iso88591",
-    "isoir101": "iso88592",
-    "isoir109": "iso88593",
-    "isoir110": "iso88594",
-    "isoir144": "iso88595",
-    "isoir127": "iso88596",
-    "isoir126": "iso88597",
-    "isoir138": "iso88598",
-    "isoir148": "iso88599",
-    "isoir157": "iso885910",
-    "isoir166": "tis620",
-    "isoir179": "iso885913",
-    "isoir199": "iso885914",
-    "isoir203": "iso885915",
-    "isoir226": "iso885916",
-
-    "cp819": "iso88591",
-    "ibm819": "iso88591",
-
-    "cyrillic": "iso88595",
-
-    "arabic": "iso88596",
-    "arabic8": "iso88596",
-    "ecma114": "iso88596",
-    "asmo708": "iso88596",
-
-    "greek" : "iso88597",
-    "greek8" : "iso88597",
-    "ecma118" : "iso88597",
-    "elot928" : "iso88597",
-
-    "hebrew": "iso88598",
-    "hebrew8": "iso88598",
-
-    "turkish": "iso88599",
-    "turkish8": "iso88599",
-
-    "thai": "iso885911",
-    "thai8": "iso885911",
-
-    "celtic": "iso885914",
-    "celtic8": "iso885914",
-    "isoceltic": "iso885914",
-
-    "tis6200": "tis620",
-    "tis62025291": "tis620",
-    "tis62025330": "tis620",
-
-    "10000": "macroman",
-    "10006": "macgreek",
-    "10007": "maccyrillic",
-    "10079": "maciceland",
-    "10081": "macturkish",
-
-    "cspc8codepage437": "cp437",
-    "cspc775baltic": "cp775",
-    "cspc850multilingual": "cp850",
-    "cspcp852": "cp852",
-    "cspc862latinhebrew": "cp862",
-    "cpgr": "cp869",
-
-    "msee": "cp1250",
-    "mscyrl": "cp1251",
-    "msansi": "cp1252",
-    "msgreek": "cp1253",
-    "msturk": "cp1254",
-    "mshebr": "cp1255",
-    "msarab": "cp1256",
-    "winbaltrim": "cp1257",
-
-    "cp20866": "koi8r",
-    "20866": "koi8r",
-    "ibm878": "koi8r",
-    "cskoi8r": "koi8r",
-
-    "cp21866": "koi8u",
-    "21866": "koi8u",
-    "ibm1168": "koi8u",
-
-    "strk10482002": "rk1048",
-
-    "tcvn5712": "tcvn",
-    "tcvn57121": "tcvn",
-
-    "gb198880": "iso646cn",
-    "cn": "iso646cn",
-
-    "csiso14jisc6220ro": "iso646jp",
-    "jisc62201969ro": "iso646jp",
-    "jp": "iso646jp",
-
-    "cshproman8": "hproman8",
-    "r8": "hproman8",
-    "roman8": "hproman8",
-    "xroman8": "hproman8",
-    "ibm1051": "hproman8",
-
-    "mac": "macintosh",
-    "csmacintosh": "macintosh",
-};
-
+"use strict";module.exports={10029:"maccenteuro",maccenteuro:{type:"_sbcs",chars:"ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ"},808:"cp808",ibm808:"cp808",cp808:{type:"_sbcs",chars:"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ "},mik:{type:"_sbcs",chars:"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "},ascii8bit:"ascii",usascii:"ascii",ansix34:"ascii",ansix341968:"ascii",ansix341986:"ascii",csascii:"ascii",cp367:"ascii",ibm367:"ascii",isoir6:"ascii",iso646us:"ascii",iso646irv:"ascii",us:"ascii",latin1:"iso88591",latin2:"iso88592",latin3:"iso88593",latin4:"iso88594",latin5:"iso88599",latin6:"iso885910",latin7:"iso885913",latin8:"iso885914",latin9:"iso885915",latin10:"iso885916",csisolatin1:"iso88591",csisolatin2:"iso88592",csisolatin3:"iso88593",csisolatin4:"iso88594",csisolatincyrillic:"iso88595",csisolatinarabic:"iso88596",csisolatingreek:"iso88597",csisolatinhebrew:"iso88598",csisolatin5:"iso88599",csisolatin6:"iso885910",l1:"iso88591",l2:"iso88592",l3:"iso88593",l4:"iso88594",l5:"iso88599",l6:"iso885910",l7:"iso885913",l8:"iso885914",l9:"iso885915",l10:"iso885916",isoir14:"iso646jp",isoir57:"iso646cn",isoir100:"iso88591",isoir101:"iso88592",isoir109:"iso88593",isoir110:"iso88594",isoir144:"iso88595",isoir127:"iso88596",isoir126:"iso88597",isoir138:"iso88598",isoir148:"iso88599",isoir157:"iso885910",isoir166:"tis620",isoir179:"iso885913",isoir199:"iso885914",isoir203:"iso885915",isoir226:"iso885916",cp819:"iso88591",ibm819:"iso88591",cyrillic:"iso88595",arabic:"iso88596",arabic8:"iso88596",ecma114:"iso88596",asmo708:"iso88596",greek:"iso88597",greek8:"iso88597",ecma118:"iso88597",elot928:"iso88597",hebrew:"iso88598",hebrew8:"iso88598",turkish:"iso88599",turkish8:"iso88599",thai:"iso885911",thai8:"iso885911",celtic:"iso885914",celtic8:"iso885914",isoceltic:"iso885914",tis6200:"tis620",tis62025291:"tis620",tis62025330:"tis620",1e4:"macroman",10006:"macgreek",10007:"maccyrillic",10079:"maciceland",10081:"macturkish",cspc8codepage437:"cp437",cspc775baltic:"cp775",cspc850multilingual:"cp850",cspcp852:"cp852",cspc862latinhebrew:"cp862",cpgr:"cp869",msee:"cp1250",mscyrl:"cp1251",msansi:"cp1252",msgreek:"cp1253",msturk:"cp1254",mshebr:"cp1255",msarab:"cp1256",winbaltrim:"cp1257",cp20866:"koi8r",20866:"koi8r",ibm878:"koi8r",cskoi8r:"koi8r",cp21866:"koi8u",21866:"koi8u",ibm1168:"koi8u",strk10482002:"rk1048",tcvn5712:"tcvn",tcvn57121:"tcvn",gb198880:"iso646cn",cn:"iso646cn",csiso14jisc6220ro:"iso646jp",jisc62201969ro:"iso646jp",jp:"iso646jp",cshproman8:"hproman8",r8:"hproman8",roman8:"hproman8",xroman8:"hproman8",ibm1051:"hproman8",mac:"macintosh",csmacintosh:"macintosh"};
\ No newline at end of file
index 54765ae..3f90905 100644 (file)
@@ -1,177 +1 @@
-"use strict";
-var Buffer = require("safer-buffer").Buffer;
-
-// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js
-
-// == UTF16-BE codec. ==========================================================
-
-exports.utf16be = Utf16BECodec;
-function Utf16BECodec() {
-}
-
-Utf16BECodec.prototype.encoder = Utf16BEEncoder;
-Utf16BECodec.prototype.decoder = Utf16BEDecoder;
-Utf16BECodec.prototype.bomAware = true;
-
-
-// -- Encoding
-
-function Utf16BEEncoder() {
-}
-
-Utf16BEEncoder.prototype.write = function(str) {
-    var buf = Buffer.from(str, 'ucs2');
-    for (var i = 0; i < buf.length; i += 2) {
-        var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp;
-    }
-    return buf;
-}
-
-Utf16BEEncoder.prototype.end = function() {
-}
-
-
-// -- Decoding
-
-function Utf16BEDecoder() {
-    this.overflowByte = -1;
-}
-
-Utf16BEDecoder.prototype.write = function(buf) {
-    if (buf.length == 0)
-        return '';
-
-    var buf2 = Buffer.alloc(buf.length + 1),
-        i = 0, j = 0;
-
-    if (this.overflowByte !== -1) {
-        buf2[0] = buf[0];
-        buf2[1] = this.overflowByte;
-        i = 1; j = 2;
-    }
-
-    for (; i < buf.length-1; i += 2, j+= 2) {
-        buf2[j] = buf[i+1];
-        buf2[j+1] = buf[i];
-    }
-
-    this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1;
-
-    return buf2.slice(0, j).toString('ucs2');
-}
-
-Utf16BEDecoder.prototype.end = function() {
-}
-
-
-// == UTF-16 codec =============================================================
-// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic.
-// Defaults to UTF-16LE, as it's prevalent and default in Node.
-// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le
-// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'});
-
-// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false).
-
-exports.utf16 = Utf16Codec;
-function Utf16Codec(codecOptions, iconv) {
-    this.iconv = iconv;
-}
-
-Utf16Codec.prototype.encoder = Utf16Encoder;
-Utf16Codec.prototype.decoder = Utf16Decoder;
-
-
-// -- Encoding (pass-through)
-
-function Utf16Encoder(options, codec) {
-    options = options || {};
-    if (options.addBOM === undefined)
-        options.addBOM = true;
-    this.encoder = codec.iconv.getEncoder('utf-16le', options);
-}
-
-Utf16Encoder.prototype.write = function(str) {
-    return this.encoder.write(str);
-}
-
-Utf16Encoder.prototype.end = function() {
-    return this.encoder.end();
-}
-
-
-// -- Decoding
-
-function Utf16Decoder(options, codec) {
-    this.decoder = null;
-    this.initialBytes = [];
-    this.initialBytesLen = 0;
-
-    this.options = options || {};
-    this.iconv = codec.iconv;
-}
-
-Utf16Decoder.prototype.write = function(buf) {
-    if (!this.decoder) {
-        // Codec is not chosen yet. Accumulate initial bytes.
-        this.initialBytes.push(buf);
-        this.initialBytesLen += buf.length;
-        
-        if (this.initialBytesLen < 16) // We need more bytes to use space heuristic (see below)
-            return '';
-
-        // We have enough bytes -> detect endianness.
-        var buf = Buffer.concat(this.initialBytes),
-            encoding = detectEncoding(buf, this.options.defaultEncoding);
-        this.decoder = this.iconv.getDecoder(encoding, this.options);
-        this.initialBytes.length = this.initialBytesLen = 0;
-    }
-
-    return this.decoder.write(buf);
-}
-
-Utf16Decoder.prototype.end = function() {
-    if (!this.decoder) {
-        var buf = Buffer.concat(this.initialBytes),
-            encoding = detectEncoding(buf, this.options.defaultEncoding);
-        this.decoder = this.iconv.getDecoder(encoding, this.options);
-
-        var res = this.decoder.write(buf),
-            trail = this.decoder.end();
-
-        return trail ? (res + trail) : res;
-    }
-    return this.decoder.end();
-}
-
-function detectEncoding(buf, defaultEncoding) {
-    var enc = defaultEncoding || 'utf-16le';
-
-    if (buf.length >= 2) {
-        // Check BOM.
-        if (buf[0] == 0xFE && buf[1] == 0xFF) // UTF-16BE BOM
-            enc = 'utf-16be';
-        else if (buf[0] == 0xFF && buf[1] == 0xFE) // UTF-16LE BOM
-            enc = 'utf-16le';
-        else {
-            // No BOM found. Try to deduce encoding from initial content.
-            // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon.
-            // So, we count ASCII as if it was LE or BE, and decide from that.
-            var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions
-                _len = Math.min(buf.length - (buf.length % 2), 64); // Len is always even.
-
-            for (var i = 0; i < _len; i += 2) {
-                if (buf[i] === 0 && buf[i+1] !== 0) asciiCharsBE++;
-                if (buf[i] !== 0 && buf[i+1] === 0) asciiCharsLE++;
-            }
-
-            if (asciiCharsBE > asciiCharsLE)
-                enc = 'utf-16be';
-            else if (asciiCharsBE < asciiCharsLE)
-                enc = 'utf-16le';
-        }
-    }
-
-    return enc;
-}
-
-
+"use strict";var Buffer=require("safer-buffer").Buffer;function Utf16BECodec(){}function Utf16BEEncoder(){}function Utf16BEDecoder(){this.overflowByte=-1}function Utf16Codec(t,e){this.iconv=e}function Utf16Encoder(t,e){void 0===(t=t||{}).addBOM&&(t.addBOM=!0),this.encoder=e.iconv.getEncoder("utf-16le",t)}function Utf16Decoder(t,e){this.decoder=null,this.initialBytes=[],this.initialBytesLen=0,this.options=t||{},this.iconv=e.iconv}function detectEncoding(t,e){var o=e||"utf-16le";if(t.length>=2)if(254==t[0]&&255==t[1])o="utf-16be";else if(255==t[0]&&254==t[1])o="utf-16le";else{for(var i=0,n=0,r=Math.min(t.length-t.length%2,64),c=0;c<r;c+=2)0===t[c]&&0!==t[c+1]&&n++,0!==t[c]&&0===t[c+1]&&i++;n>i?o="utf-16be":n<i&&(o="utf-16le")}return o}exports.utf16be=Utf16BECodec,Utf16BECodec.prototype.encoder=Utf16BEEncoder,Utf16BECodec.prototype.decoder=Utf16BEDecoder,Utf16BECodec.prototype.bomAware=!0,Utf16BEEncoder.prototype.write=function(t){for(var e=Buffer.from(t,"ucs2"),o=0;o<e.length;o+=2){var i=e[o];e[o]=e[o+1],e[o+1]=i}return e},Utf16BEEncoder.prototype.end=function(){},Utf16BEDecoder.prototype.write=function(t){if(0==t.length)return"";var e=Buffer.alloc(t.length+1),o=0,i=0;for(-1!==this.overflowByte&&(e[0]=t[0],e[1]=this.overflowByte,o=1,i=2);o<t.length-1;o+=2,i+=2)e[i]=t[o+1],e[i+1]=t[o];return this.overflowByte=o==t.length-1?t[t.length-1]:-1,e.slice(0,i).toString("ucs2")},Utf16BEDecoder.prototype.end=function(){},exports.utf16=Utf16Codec,Utf16Codec.prototype.encoder=Utf16Encoder,Utf16Codec.prototype.decoder=Utf16Decoder,Utf16Encoder.prototype.write=function(t){return this.encoder.write(t)},Utf16Encoder.prototype.end=function(){return this.encoder.end()},Utf16Decoder.prototype.write=function(t){if(!this.decoder){if(this.initialBytes.push(t),this.initialBytesLen+=t.length,this.initialBytesLen<16)return"";var e=detectEncoding(t=Buffer.concat(this.initialBytes),this.options.defaultEncoding);this.decoder=this.iconv.getDecoder(e,this.options),this.initialBytes.length=this.initialBytesLen=0}return this.decoder.write(t)},Utf16Decoder.prototype.end=function(){if(!this.decoder){var t=Buffer.concat(this.initialBytes),e=detectEncoding(t,this.options.defaultEncoding);this.decoder=this.iconv.getDecoder(e,this.options);var o=this.decoder.write(t),i=this.decoder.end();return i?o+i:o}return this.decoder.end()};
\ No newline at end of file
index b7631c2..80afcda 100644 (file)
@@ -1,290 +1 @@
-"use strict";
-var Buffer = require("safer-buffer").Buffer;
-
-// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152
-// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3
-
-exports.utf7 = Utf7Codec;
-exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7
-function Utf7Codec(codecOptions, iconv) {
-    this.iconv = iconv;
-};
-
-Utf7Codec.prototype.encoder = Utf7Encoder;
-Utf7Codec.prototype.decoder = Utf7Decoder;
-Utf7Codec.prototype.bomAware = true;
-
-
-// -- Encoding
-
-var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g;
-
-function Utf7Encoder(options, codec) {
-    this.iconv = codec.iconv;
-}
-
-Utf7Encoder.prototype.write = function(str) {
-    // Naive implementation.
-    // Non-direct chars are encoded as "+<base64>-"; single "+" char is encoded as "+-".
-    return Buffer.from(str.replace(nonDirectChars, function(chunk) {
-        return "+" + (chunk === '+' ? '' : 
-            this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) 
-            + "-";
-    }.bind(this)));
-}
-
-Utf7Encoder.prototype.end = function() {
-}
-
-
-// -- Decoding
-
-function Utf7Decoder(options, codec) {
-    this.iconv = codec.iconv;
-    this.inBase64 = false;
-    this.base64Accum = '';
-}
-
-var base64Regex = /[A-Za-z0-9\/+]/;
-var base64Chars = [];
-for (var i = 0; i < 256; i++)
-    base64Chars[i] = base64Regex.test(String.fromCharCode(i));
-
-var plusChar = '+'.charCodeAt(0), 
-    minusChar = '-'.charCodeAt(0),
-    andChar = '&'.charCodeAt(0);
-
-Utf7Decoder.prototype.write = function(buf) {
-    var res = "", lastI = 0,
-        inBase64 = this.inBase64,
-        base64Accum = this.base64Accum;
-
-    // The decoder is more involved as we must handle chunks in stream.
-
-    for (var i = 0; i < buf.length; i++) {
-        if (!inBase64) { // We're in direct mode.
-            // Write direct chars until '+'
-            if (buf[i] == plusChar) {
-                res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars.
-                lastI = i+1;
-                inBase64 = true;
-            }
-        } else { // We decode base64.
-            if (!base64Chars[buf[i]]) { // Base64 ended.
-                if (i == lastI && buf[i] == minusChar) {// "+-" -> "+"
-                    res += "+";
-                } else {
-                    var b64str = base64Accum + buf.slice(lastI, i).toString();
-                    res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
-                }
-
-                if (buf[i] != minusChar) // Minus is absorbed after base64.
-                    i--;
-
-                lastI = i+1;
-                inBase64 = false;
-                base64Accum = '';
-            }
-        }
-    }
-
-    if (!inBase64) {
-        res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars.
-    } else {
-        var b64str = base64Accum + buf.slice(lastI).toString();
-
-        var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars.
-        base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future.
-        b64str = b64str.slice(0, canBeDecoded);
-
-        res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
-    }
-
-    this.inBase64 = inBase64;
-    this.base64Accum = base64Accum;
-
-    return res;
-}
-
-Utf7Decoder.prototype.end = function() {
-    var res = "";
-    if (this.inBase64 && this.base64Accum.length > 0)
-        res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be");
-
-    this.inBase64 = false;
-    this.base64Accum = '';
-    return res;
-}
-
-
-// UTF-7-IMAP codec.
-// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3)
-// Differences:
-//  * Base64 part is started by "&" instead of "+"
-//  * Direct characters are 0x20-0x7E, except "&" (0x26)
-//  * In Base64, "," is used instead of "/"
-//  * Base64 must not be used to represent direct characters.
-//  * No implicit shift back from Base64 (should always end with '-')
-//  * String must end in non-shifted position.
-//  * "-&" while in base64 is not allowed.
-
-
-exports.utf7imap = Utf7IMAPCodec;
-function Utf7IMAPCodec(codecOptions, iconv) {
-    this.iconv = iconv;
-};
-
-Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder;
-Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder;
-Utf7IMAPCodec.prototype.bomAware = true;
-
-
-// -- Encoding
-
-function Utf7IMAPEncoder(options, codec) {
-    this.iconv = codec.iconv;
-    this.inBase64 = false;
-    this.base64Accum = Buffer.alloc(6);
-    this.base64AccumIdx = 0;
-}
-
-Utf7IMAPEncoder.prototype.write = function(str) {
-    var inBase64 = this.inBase64,
-        base64Accum = this.base64Accum,
-        base64AccumIdx = this.base64AccumIdx,
-        buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0;
-
-    for (var i = 0; i < str.length; i++) {
-        var uChar = str.charCodeAt(i);
-        if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'.
-            if (inBase64) {
-                if (base64AccumIdx > 0) {
-                    bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx);
-                    base64AccumIdx = 0;
-                }
-
-                buf[bufIdx++] = minusChar; // Write '-', then go to direct mode.
-                inBase64 = false;
-            }
-
-            if (!inBase64) {
-                buf[bufIdx++] = uChar; // Write direct character
-
-                if (uChar === andChar)  // Ampersand -> '&-'
-                    buf[bufIdx++] = minusChar;
-            }
-
-        } else { // Non-direct character
-            if (!inBase64) {
-                buf[bufIdx++] = andChar; // Write '&', then go to base64 mode.
-                inBase64 = true;
-            }
-            if (inBase64) {
-                base64Accum[base64AccumIdx++] = uChar >> 8;
-                base64Accum[base64AccumIdx++] = uChar & 0xFF;
-
-                if (base64AccumIdx == base64Accum.length) {
-                    bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx);
-                    base64AccumIdx = 0;
-                }
-            }
-        }
-    }
-
-    this.inBase64 = inBase64;
-    this.base64AccumIdx = base64AccumIdx;
-
-    return buf.slice(0, bufIdx);
-}
-
-Utf7IMAPEncoder.prototype.end = function() {
-    var buf = Buffer.alloc(10), bufIdx = 0;
-    if (this.inBase64) {
-        if (this.base64AccumIdx > 0) {
-            bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx);
-            this.base64AccumIdx = 0;
-        }
-
-        buf[bufIdx++] = minusChar; // Write '-', then go to direct mode.
-        this.inBase64 = false;
-    }
-
-    return buf.slice(0, bufIdx);
-}
-
-
-// -- Decoding
-
-function Utf7IMAPDecoder(options, codec) {
-    this.iconv = codec.iconv;
-    this.inBase64 = false;
-    this.base64Accum = '';
-}
-
-var base64IMAPChars = base64Chars.slice();
-base64IMAPChars[','.charCodeAt(0)] = true;
-
-Utf7IMAPDecoder.prototype.write = function(buf) {
-    var res = "", lastI = 0,
-        inBase64 = this.inBase64,
-        base64Accum = this.base64Accum;
-
-    // The decoder is more involved as we must handle chunks in stream.
-    // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end).
-
-    for (var i = 0; i < buf.length; i++) {
-        if (!inBase64) { // We're in direct mode.
-            // Write direct chars until '&'
-            if (buf[i] == andChar) {
-                res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars.
-                lastI = i+1;
-                inBase64 = true;
-            }
-        } else { // We decode base64.
-            if (!base64IMAPChars[buf[i]]) { // Base64 ended.
-                if (i == lastI && buf[i] == minusChar) { // "&-" -> "&"
-                    res += "&";
-                } else {
-                    var b64str = base64Accum + buf.slice(lastI, i).toString().replace(/,/g, '/');
-                    res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
-                }
-
-                if (buf[i] != minusChar) // Minus may be absorbed after base64.
-                    i--;
-
-                lastI = i+1;
-                inBase64 = false;
-                base64Accum = '';
-            }
-        }
-    }
-
-    if (!inBase64) {
-        res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars.
-    } else {
-        var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/');
-
-        var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars.
-        base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future.
-        b64str = b64str.slice(0, canBeDecoded);
-
-        res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be");
-    }
-
-    this.inBase64 = inBase64;
-    this.base64Accum = base64Accum;
-
-    return res;
-}
-
-Utf7IMAPDecoder.prototype.end = function() {
-    var res = "";
-    if (this.inBase64 && this.base64Accum.length > 0)
-        res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be");
-
-    this.inBase64 = false;
-    this.base64Accum = '';
-    return res;
-}
-
-
+"use strict";var Buffer=require("safer-buffer").Buffer;function Utf7Codec(e,t){this.iconv=t}exports.utf7=Utf7Codec,exports.unicode11utf7="utf7",Utf7Codec.prototype.encoder=Utf7Encoder,Utf7Codec.prototype.decoder=Utf7Decoder,Utf7Codec.prototype.bomAware=!0;var nonDirectChars=/[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g;function Utf7Encoder(e,t){this.iconv=t.iconv}function Utf7Decoder(e,t){this.iconv=t.iconv,this.inBase64=!1,this.base64Accum=""}Utf7Encoder.prototype.write=function(e){return Buffer.from(e.replace(nonDirectChars,function(e){return"+"+("+"===e?"":this.iconv.encode(e,"utf16-be").toString("base64").replace(/=+$/,""))+"-"}.bind(this)))},Utf7Encoder.prototype.end=function(){};for(var base64Regex=/[A-Za-z0-9\/+]/,base64Chars=[],i=0;i<256;i++)base64Chars[i]=base64Regex.test(String.fromCharCode(i));var plusChar="+".charCodeAt(0),minusChar="-".charCodeAt(0),andChar="&".charCodeAt(0);function Utf7IMAPCodec(e,t){this.iconv=t}function Utf7IMAPEncoder(e,t){this.iconv=t.iconv,this.inBase64=!1,this.base64Accum=Buffer.alloc(6),this.base64AccumIdx=0}function Utf7IMAPDecoder(e,t){this.iconv=t.iconv,this.inBase64=!1,this.base64Accum=""}Utf7Decoder.prototype.write=function(e){for(var t="",i=0,s=this.inBase64,c=this.base64Accum,r=0;r<e.length;r++)if(s){if(!base64Chars[e[r]]){if(r==i&&e[r]==minusChar)t+="+";else{var o=c+e.slice(i,r).toString();t+=this.iconv.decode(Buffer.from(o,"base64"),"utf16-be")}e[r]!=minusChar&&r--,i=r+1,s=!1,c=""}}else e[r]==plusChar&&(t+=this.iconv.decode(e.slice(i,r),"ascii"),i=r+1,s=!0);if(s){var n=(o=c+e.slice(i).toString()).length-o.length%8;c=o.slice(n),o=o.slice(0,n),t+=this.iconv.decode(Buffer.from(o,"base64"),"utf16-be")}else t+=this.iconv.decode(e.slice(i),"ascii");return this.inBase64=s,this.base64Accum=c,t},Utf7Decoder.prototype.end=function(){var e="";return this.inBase64&&this.base64Accum.length>0&&(e=this.iconv.decode(Buffer.from(this.base64Accum,"base64"),"utf16-be")),this.inBase64=!1,this.base64Accum="",e},exports.utf7imap=Utf7IMAPCodec,Utf7IMAPCodec.prototype.encoder=Utf7IMAPEncoder,Utf7IMAPCodec.prototype.decoder=Utf7IMAPDecoder,Utf7IMAPCodec.prototype.bomAware=!0,Utf7IMAPEncoder.prototype.write=function(e){for(var t=this.inBase64,i=this.base64Accum,s=this.base64AccumIdx,c=Buffer.alloc(5*e.length+10),r=0,o=0;o<e.length;o++){var n=e.charCodeAt(o);32<=n&&n<=126?(t&&(s>0&&(r+=c.write(i.slice(0,s).toString("base64").replace(/\//g,",").replace(/=+$/,""),r),s=0),c[r++]=minusChar,t=!1),t||(c[r++]=n,n===andChar&&(c[r++]=minusChar))):(t||(c[r++]=andChar,t=!0),t&&(i[s++]=n>>8,i[s++]=255&n,s==i.length&&(r+=c.write(i.toString("base64").replace(/\//g,","),r),s=0)))}return this.inBase64=t,this.base64AccumIdx=s,c.slice(0,r)},Utf7IMAPEncoder.prototype.end=function(){var e=Buffer.alloc(10),t=0;return this.inBase64&&(this.base64AccumIdx>0&&(t+=e.write(this.base64Accum.slice(0,this.base64AccumIdx).toString("base64").replace(/\//g,",").replace(/=+$/,""),t),this.base64AccumIdx=0),e[t++]=minusChar,this.inBase64=!1),e.slice(0,t)};var base64IMAPChars=base64Chars.slice();base64IMAPChars[",".charCodeAt(0)]=!0,Utf7IMAPDecoder.prototype.write=function(e){for(var t="",i=0,s=this.inBase64,c=this.base64Accum,r=0;r<e.length;r++)if(s){if(!base64IMAPChars[e[r]]){if(r==i&&e[r]==minusChar)t+="&";else{var o=c+e.slice(i,r).toString().replace(/,/g,"/");t+=this.iconv.decode(Buffer.from(o,"base64"),"utf16-be")}e[r]!=minusChar&&r--,i=r+1,s=!1,c=""}}else e[r]==andChar&&(t+=this.iconv.decode(e.slice(i,r),"ascii"),i=r+1,s=!0);if(s){var n=(o=c+e.slice(i).toString().replace(/,/g,"/")).length-o.length%8;c=o.slice(n),o=o.slice(0,n),t+=this.iconv.decode(Buffer.from(o,"base64"),"utf16-be")}else t+=this.iconv.decode(e.slice(i),"ascii");return this.inBase64=s,this.base64Accum=c,t},Utf7IMAPDecoder.prototype.end=function(){var e="";return this.inBase64&&this.base64Accum.length>0&&(e=this.iconv.decode(Buffer.from(this.base64Accum,"base64"),"utf16-be")),this.inBase64=!1,this.base64Accum="",e};
\ No newline at end of file
index 1050872..d099f59 100644 (file)
@@ -1,52 +1 @@
-"use strict";
-
-var BOMChar = '\uFEFF';
-
-exports.PrependBOM = PrependBOMWrapper
-function PrependBOMWrapper(encoder, options) {
-    this.encoder = encoder;
-    this.addBOM = true;
-}
-
-PrependBOMWrapper.prototype.write = function(str) {
-    if (this.addBOM) {
-        str = BOMChar + str;
-        this.addBOM = false;
-    }
-
-    return this.encoder.write(str);
-}
-
-PrependBOMWrapper.prototype.end = function() {
-    return this.encoder.end();
-}
-
-
-//------------------------------------------------------------------------------
-
-exports.StripBOM = StripBOMWrapper;
-function StripBOMWrapper(decoder, options) {
-    this.decoder = decoder;
-    this.pass = false;
-    this.options = options || {};
-}
-
-StripBOMWrapper.prototype.write = function(buf) {
-    var res = this.decoder.write(buf);
-    if (this.pass || !res)
-        return res;
-
-    if (res[0] === BOMChar) {
-        res = res.slice(1);
-        if (typeof this.options.stripBOM === 'function')
-            this.options.stripBOM();
-    }
-
-    this.pass = true;
-    return res;
-}
-
-StripBOMWrapper.prototype.end = function() {
-    return this.decoder.end();
-}
-
+"use strict";var BOMChar="\ufeff";function PrependBOMWrapper(r,t){this.encoder=r,this.addBOM=!0}function StripBOMWrapper(r,t){this.decoder=r,this.pass=!1,this.options=t||{}}exports.PrependBOM=PrependBOMWrapper,PrependBOMWrapper.prototype.write=function(r){return this.addBOM&&(r=BOMChar+r,this.addBOM=!1),this.encoder.write(r)},PrependBOMWrapper.prototype.end=function(){return this.encoder.end()},exports.StripBOM=StripBOMWrapper,StripBOMWrapper.prototype.write=function(r){var t=this.decoder.write(r);return this.pass||!t||(t[0]===BOMChar&&(t=t.slice(1),"function"==typeof this.options.stripBOM&&this.options.stripBOM()),this.pass=!0),t},StripBOMWrapper.prototype.end=function(){return this.decoder.end()};
\ No newline at end of file
index 87f5394..45f073e 100644 (file)
@@ -1,217 +1 @@
-"use strict";
-var Buffer = require("buffer").Buffer;
-// Note: not polyfilled with safer-buffer on a purpose, as overrides Buffer
-
-// == Extend Node primitives to use iconv-lite =================================
-
-module.exports = function (iconv) {
-    var original = undefined; // Place to keep original methods.
-
-    // Node authors rewrote Buffer internals to make it compatible with
-    // Uint8Array and we cannot patch key functions since then.
-    // Note: this does use older Buffer API on a purpose
-    iconv.supportsNodeEncodingsExtension = !(Buffer.from || new Buffer(0) instanceof Uint8Array);
-
-    iconv.extendNodeEncodings = function extendNodeEncodings() {
-        if (original) return;
-        original = {};
-
-        if (!iconv.supportsNodeEncodingsExtension) {
-            console.error("ACTION NEEDED: require('iconv-lite').extendNodeEncodings() is not supported in your version of Node");
-            console.error("See more info at https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility");
-            return;
-        }
-
-        var nodeNativeEncodings = {
-            'hex': true, 'utf8': true, 'utf-8': true, 'ascii': true, 'binary': true, 
-            'base64': true, 'ucs2': true, 'ucs-2': true, 'utf16le': true, 'utf-16le': true,
-        };
-
-        Buffer.isNativeEncoding = function(enc) {
-            return enc && nodeNativeEncodings[enc.toLowerCase()];
-        }
-
-        // -- SlowBuffer -----------------------------------------------------------
-        var SlowBuffer = require('buffer').SlowBuffer;
-
-        original.SlowBufferToString = SlowBuffer.prototype.toString;
-        SlowBuffer.prototype.toString = function(encoding, start, end) {
-            encoding = String(encoding || 'utf8').toLowerCase();
-
-            // Use native conversion when possible
-            if (Buffer.isNativeEncoding(encoding))
-                return original.SlowBufferToString.call(this, encoding, start, end);
-
-            // Otherwise, use our decoding method.
-            if (typeof start == 'undefined') start = 0;
-            if (typeof end == 'undefined') end = this.length;
-            return iconv.decode(this.slice(start, end), encoding);
-        }
-
-        original.SlowBufferWrite = SlowBuffer.prototype.write;
-        SlowBuffer.prototype.write = function(string, offset, length, encoding) {
-            // Support both (string, offset, length, encoding)
-            // and the legacy (string, encoding, offset, length)
-            if (isFinite(offset)) {
-                if (!isFinite(length)) {
-                    encoding = length;
-                    length = undefined;
-                }
-            } else {  // legacy
-                var swap = encoding;
-                encoding = offset;
-                offset = length;
-                length = swap;
-            }
-
-            offset = +offset || 0;
-            var remaining = this.length - offset;
-            if (!length) {
-                length = remaining;
-            } else {
-                length = +length;
-                if (length > remaining) {
-                    length = remaining;
-                }
-            }
-            encoding = String(encoding || 'utf8').toLowerCase();
-
-            // Use native conversion when possible
-            if (Buffer.isNativeEncoding(encoding))
-                return original.SlowBufferWrite.call(this, string, offset, length, encoding);
-
-            if (string.length > 0 && (length < 0 || offset < 0))
-                throw new RangeError('attempt to write beyond buffer bounds');
-
-            // Otherwise, use our encoding method.
-            var buf = iconv.encode(string, encoding);
-            if (buf.length < length) length = buf.length;
-            buf.copy(this, offset, 0, length);
-            return length;
-        }
-
-        // -- Buffer ---------------------------------------------------------------
-
-        original.BufferIsEncoding = Buffer.isEncoding;
-        Buffer.isEncoding = function(encoding) {
-            return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding);
-        }
-
-        original.BufferByteLength = Buffer.byteLength;
-        Buffer.byteLength = SlowBuffer.byteLength = function(str, encoding) {
-            encoding = String(encoding || 'utf8').toLowerCase();
-
-            // Use native conversion when possible
-            if (Buffer.isNativeEncoding(encoding))
-                return original.BufferByteLength.call(this, str, encoding);
-
-            // Slow, I know, but we don't have a better way yet.
-            return iconv.encode(str, encoding).length;
-        }
-
-        original.BufferToString = Buffer.prototype.toString;
-        Buffer.prototype.toString = function(encoding, start, end) {
-            encoding = String(encoding || 'utf8').toLowerCase();
-
-            // Use native conversion when possible
-            if (Buffer.isNativeEncoding(encoding))
-                return original.BufferToString.call(this, encoding, start, end);
-
-            // Otherwise, use our decoding method.
-            if (typeof start == 'undefined') start = 0;
-            if (typeof end == 'undefined') end = this.length;
-            return iconv.decode(this.slice(start, end), encoding);
-        }
-
-        original.BufferWrite = Buffer.prototype.write;
-        Buffer.prototype.write = function(string, offset, length, encoding) {
-            var _offset = offset, _length = length, _encoding = encoding;
-            // Support both (string, offset, length, encoding)
-            // and the legacy (string, encoding, offset, length)
-            if (isFinite(offset)) {
-                if (!isFinite(length)) {
-                    encoding = length;
-                    length = undefined;
-                }
-            } else {  // legacy
-                var swap = encoding;
-                encoding = offset;
-                offset = length;
-                length = swap;
-            }
-
-            encoding = String(encoding || 'utf8').toLowerCase();
-
-            // Use native conversion when possible
-            if (Buffer.isNativeEncoding(encoding))
-                return original.BufferWrite.call(this, string, _offset, _length, _encoding);
-
-            offset = +offset || 0;
-            var remaining = this.length - offset;
-            if (!length) {
-                length = remaining;
-            } else {
-                length = +length;
-                if (length > remaining) {
-                    length = remaining;
-                }
-            }
-
-            if (string.length > 0 && (length < 0 || offset < 0))
-                throw new RangeError('attempt to write beyond buffer bounds');
-
-            // Otherwise, use our encoding method.
-            var buf = iconv.encode(string, encoding);
-            if (buf.length < length) length = buf.length;
-            buf.copy(this, offset, 0, length);
-            return length;
-
-            // TODO: Set _charsWritten.
-        }
-
-
-        // -- Readable -------------------------------------------------------------
-        if (iconv.supportsStreams) {
-            var Readable = require('stream').Readable;
-
-            original.ReadableSetEncoding = Readable.prototype.setEncoding;
-            Readable.prototype.setEncoding = function setEncoding(enc, options) {
-                // Use our own decoder, it has the same interface.
-                // We cannot use original function as it doesn't handle BOM-s.
-                this._readableState.decoder = iconv.getDecoder(enc, options);
-                this._readableState.encoding = enc;
-            }
-
-            Readable.prototype.collect = iconv._collect;
-        }
-    }
-
-    // Remove iconv-lite Node primitive extensions.
-    iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() {
-        if (!iconv.supportsNodeEncodingsExtension)
-            return;
-        if (!original)
-            throw new Error("require('iconv-lite').undoExtendNodeEncodings(): Nothing to undo; extendNodeEncodings() is not called.")
-
-        delete Buffer.isNativeEncoding;
-
-        var SlowBuffer = require('buffer').SlowBuffer;
-
-        SlowBuffer.prototype.toString = original.SlowBufferToString;
-        SlowBuffer.prototype.write = original.SlowBufferWrite;
-
-        Buffer.isEncoding = original.BufferIsEncoding;
-        Buffer.byteLength = original.BufferByteLength;
-        Buffer.prototype.toString = original.BufferToString;
-        Buffer.prototype.write = original.BufferWrite;
-
-        if (iconv.supportsStreams) {
-            var Readable = require('stream').Readable;
-
-            Readable.prototype.setEncoding = original.ReadableSetEncoding;
-            delete Readable.prototype.collect;
-        }
-
-        original = undefined;
-    }
-}
+"use strict";var Buffer=require("buffer").Buffer;module.exports=function(e){var t=void 0;e.supportsNodeEncodingsExtension=!(Buffer.from||new Buffer(0)instanceof Uint8Array),e.extendNodeEncodings=function(){if(!t){if(t={},!e.supportsNodeEncodingsExtension)return console.error("ACTION NEEDED: require('iconv-lite').extendNodeEncodings() is not supported in your version of Node"),void console.error("See more info at https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility");var r={hex:!0,utf8:!0,"utf-8":!0,ascii:!0,binary:!0,base64:!0,ucs2:!0,"ucs-2":!0,utf16le:!0,"utf-16le":!0};Buffer.isNativeEncoding=function(e){return e&&r[e.toLowerCase()]};var o=require("buffer").SlowBuffer;if(t.SlowBufferToString=o.prototype.toString,o.prototype.toString=function(r,o,i){return r=String(r||"utf8").toLowerCase(),Buffer.isNativeEncoding(r)?t.SlowBufferToString.call(this,r,o,i):(void 0===o&&(o=0),void 0===i&&(i=this.length),e.decode(this.slice(o,i),r))},t.SlowBufferWrite=o.prototype.write,o.prototype.write=function(r,o,i,n){if(isFinite(o))isFinite(i)||(n=i,i=void 0);else{var f=n;n=o,o=i,i=f}o=+o||0;var u=this.length-o;if(i?(i=+i)>u&&(i=u):i=u,n=String(n||"utf8").toLowerCase(),Buffer.isNativeEncoding(n))return t.SlowBufferWrite.call(this,r,o,i,n);if(r.length>0&&(i<0||o<0))throw new RangeError("attempt to write beyond buffer bounds");var s=e.encode(r,n);return s.length<i&&(i=s.length),s.copy(this,o,0,i),i},t.BufferIsEncoding=Buffer.isEncoding,Buffer.isEncoding=function(t){return Buffer.isNativeEncoding(t)||e.encodingExists(t)},t.BufferByteLength=Buffer.byteLength,Buffer.byteLength=o.byteLength=function(r,o){return o=String(o||"utf8").toLowerCase(),Buffer.isNativeEncoding(o)?t.BufferByteLength.call(this,r,o):e.encode(r,o).length},t.BufferToString=Buffer.prototype.toString,Buffer.prototype.toString=function(r,o,i){return r=String(r||"utf8").toLowerCase(),Buffer.isNativeEncoding(r)?t.BufferToString.call(this,r,o,i):(void 0===o&&(o=0),void 0===i&&(i=this.length),e.decode(this.slice(o,i),r))},t.BufferWrite=Buffer.prototype.write,Buffer.prototype.write=function(r,o,i,n){var f=o,u=i,s=n;if(isFinite(o))isFinite(i)||(n=i,i=void 0);else{var d=n;n=o,o=i,i=d}if(n=String(n||"utf8").toLowerCase(),Buffer.isNativeEncoding(n))return t.BufferWrite.call(this,r,f,u,s);o=+o||0;var c=this.length-o;if(i?(i=+i)>c&&(i=c):i=c,r.length>0&&(i<0||o<0))throw new RangeError("attempt to write beyond buffer bounds");var g=e.encode(r,n);return g.length<i&&(i=g.length),g.copy(this,o,0,i),i},e.supportsStreams){var i=require("stream").Readable;t.ReadableSetEncoding=i.prototype.setEncoding,i.prototype.setEncoding=function(t,r){this._readableState.decoder=e.getDecoder(t,r),this._readableState.encoding=t},i.prototype.collect=e._collect}}},e.undoExtendNodeEncodings=function(){if(e.supportsNodeEncodingsExtension){if(!t)throw new Error("require('iconv-lite').undoExtendNodeEncodings(): Nothing to undo; extendNodeEncodings() is not called.");delete Buffer.isNativeEncoding;var r=require("buffer").SlowBuffer;if(r.prototype.toString=t.SlowBufferToString,r.prototype.write=t.SlowBufferWrite,Buffer.isEncoding=t.BufferIsEncoding,Buffer.byteLength=t.BufferByteLength,Buffer.prototype.toString=t.BufferToString,Buffer.prototype.write=t.BufferWrite,e.supportsStreams){var o=require("stream").Readable;o.prototype.setEncoding=t.ReadableSetEncoding,delete o.prototype.collect}t=void 0}}};
\ No newline at end of file
index 5391919..a94fcc1 100644 (file)
@@ -1,153 +1 @@
-"use strict";
-
-// Some environments don't have global Buffer (e.g. React Native).
-// Solution would be installing npm modules "buffer" and "stream" explicitly.
-var Buffer = require("safer-buffer").Buffer;
-
-var bomHandling = require("./bom-handling"),
-    iconv = module.exports;
-
-// All codecs and aliases are kept here, keyed by encoding name/alias.
-// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`.
-iconv.encodings = null;
-
-// Characters emitted in case of error.
-iconv.defaultCharUnicode = '�';
-iconv.defaultCharSingleByte = '?';
-
-// Public API.
-iconv.encode = function encode(str, encoding, options) {
-    str = "" + (str || ""); // Ensure string.
-
-    var encoder = iconv.getEncoder(encoding, options);
-
-    var res = encoder.write(str);
-    var trail = encoder.end();
-    
-    return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res;
-}
-
-iconv.decode = function decode(buf, encoding, options) {
-    if (typeof buf === 'string') {
-        if (!iconv.skipDecodeWarning) {
-            console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding');
-            iconv.skipDecodeWarning = true;
-        }
-
-        buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer.
-    }
-
-    var decoder = iconv.getDecoder(encoding, options);
-
-    var res = decoder.write(buf);
-    var trail = decoder.end();
-
-    return trail ? (res + trail) : res;
-}
-
-iconv.encodingExists = function encodingExists(enc) {
-    try {
-        iconv.getCodec(enc);
-        return true;
-    } catch (e) {
-        return false;
-    }
-}
-
-// Legacy aliases to convert functions
-iconv.toEncoding = iconv.encode;
-iconv.fromEncoding = iconv.decode;
-
-// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache.
-iconv._codecDataCache = {};
-iconv.getCodec = function getCodec(encoding) {
-    if (!iconv.encodings)
-        iconv.encodings = require("../encodings"); // Lazy load all encoding definitions.
-    
-    // Canonicalize encoding name: strip all non-alphanumeric chars and appended year.
-    var enc = iconv._canonicalizeEncoding(encoding);
-
-    // Traverse iconv.encodings to find actual codec.
-    var codecOptions = {};
-    while (true) {
-        var codec = iconv._codecDataCache[enc];
-        if (codec)
-            return codec;
-
-        var codecDef = iconv.encodings[enc];
-
-        switch (typeof codecDef) {
-            case "string": // Direct alias to other encoding.
-                enc = codecDef;
-                break;
-
-            case "object": // Alias with options. Can be layered.
-                for (var key in codecDef)
-                    codecOptions[key] = codecDef[key];
-
-                if (!codecOptions.encodingName)
-                    codecOptions.encodingName = enc;
-                
-                enc = codecDef.type;
-                break;
-
-            case "function": // Codec itself.
-                if (!codecOptions.encodingName)
-                    codecOptions.encodingName = enc;
-
-                // The codec function must load all tables and return object with .encoder and .decoder methods.
-                // It'll be called only once (for each different options object).
-                codec = new codecDef(codecOptions, iconv);
-
-                iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later.
-                return codec;
-
-            default:
-                throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')");
-        }
-    }
-}
-
-iconv._canonicalizeEncoding = function(encoding) {
-    // Canonicalize encoding name: strip all non-alphanumeric chars and appended year.
-    return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, "");
-}
-
-iconv.getEncoder = function getEncoder(encoding, options) {
-    var codec = iconv.getCodec(encoding),
-        encoder = new codec.encoder(options, codec);
-
-    if (codec.bomAware && options && options.addBOM)
-        encoder = new bomHandling.PrependBOM(encoder, options);
-
-    return encoder;
-}
-
-iconv.getDecoder = function getDecoder(encoding, options) {
-    var codec = iconv.getCodec(encoding),
-        decoder = new codec.decoder(options, codec);
-
-    if (codec.bomAware && !(options && options.stripBOM === false))
-        decoder = new bomHandling.StripBOM(decoder, options);
-
-    return decoder;
-}
-
-
-// Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json.
-var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node;
-if (nodeVer) {
-
-    // Load streaming support in Node v0.10+
-    var nodeVerArr = nodeVer.split(".").map(Number);
-    if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) {
-        require("./streams")(iconv);
-    }
-
-    // Load Node primitive extensions.
-    require("./extend-node")(iconv);
-}
-
-if ("Ā" != "\u0100") {
-    console.error("iconv-lite warning: javascript files use encoding different from utf-8. See https://github.com/ashtuchkin/iconv-lite/wiki/Javascript-source-file-encodings for more info.");
-}
+"use strict";var Buffer=require("safer-buffer").Buffer,bomHandling=require("./bom-handling"),iconv=module.exports;iconv.encodings=null,iconv.defaultCharUnicode="�",iconv.defaultCharSingleByte="?",iconv.encode=function(e,n,o){e=""+(e||"");var c=iconv.getEncoder(n,o),r=c.write(e),i=c.end();return i&&i.length>0?Buffer.concat([r,i]):r},iconv.decode=function(e,n,o){"string"==typeof e&&(iconv.skipDecodeWarning||(console.error("Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding"),iconv.skipDecodeWarning=!0),e=Buffer.from(""+(e||""),"binary"));var c=iconv.getDecoder(n,o),r=c.write(e),i=c.end();return i?r+i:r},iconv.encodingExists=function(e){try{return iconv.getCodec(e),!0}catch(e){return!1}},iconv.toEncoding=iconv.encode,iconv.fromEncoding=iconv.decode,iconv._codecDataCache={},iconv.getCodec=function(e){iconv.encodings||(iconv.encodings=require("../encodings"));for(var n=iconv._canonicalizeEncoding(e),o={};;){var c=iconv._codecDataCache[n];if(c)return c;var r=iconv.encodings[n];switch(typeof r){case"string":n=r;break;case"object":for(var i in r)o[i]=r[i];o.encodingName||(o.encodingName=n),n=r.type;break;case"function":return o.encodingName||(o.encodingName=n),c=new r(o,iconv),iconv._codecDataCache[o.encodingName]=c,c;default:throw new Error("Encoding not recognized: '"+e+"' (searched as: '"+n+"')")}}},iconv._canonicalizeEncoding=function(e){return(""+e).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g,"")},iconv.getEncoder=function(e,n){var o=iconv.getCodec(e),c=new o.encoder(n,o);return o.bomAware&&n&&n.addBOM&&(c=new bomHandling.PrependBOM(c,n)),c},iconv.getDecoder=function(e,n){var o=iconv.getCodec(e),c=new o.decoder(n,o);return!o.bomAware||n&&!1===n.stripBOM||(c=new bomHandling.StripBOM(c,n)),c};var nodeVer="undefined"!=typeof process&&process.versions&&process.versions.node;if(nodeVer){var nodeVerArr=nodeVer.split(".").map(Number);(nodeVerArr[0]>0||nodeVerArr[1]>=10)&&require("./streams")(iconv),require("./extend-node")(iconv)}
\ No newline at end of file
index 4409552..6b527d0 100644 (file)
@@ -1,121 +1 @@
-"use strict";
-
-var Buffer = require("buffer").Buffer,
-    Transform = require("stream").Transform;
-
-
-// == Exports ==================================================================
-module.exports = function(iconv) {
-    
-    // Additional Public API.
-    iconv.encodeStream = function encodeStream(encoding, options) {
-        return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options);
-    }
-
-    iconv.decodeStream = function decodeStream(encoding, options) {
-        return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options);
-    }
-
-    iconv.supportsStreams = true;
-
-
-    // Not published yet.
-    iconv.IconvLiteEncoderStream = IconvLiteEncoderStream;
-    iconv.IconvLiteDecoderStream = IconvLiteDecoderStream;
-    iconv._collect = IconvLiteDecoderStream.prototype.collect;
-};
-
-
-// == Encoder stream =======================================================
-function IconvLiteEncoderStream(conv, options) {
-    this.conv = conv;
-    options = options || {};
-    options.decodeStrings = false; // We accept only strings, so we don't need to decode them.
-    Transform.call(this, options);
-}
-
-IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, {
-    constructor: { value: IconvLiteEncoderStream }
-});
-
-IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) {
-    if (typeof chunk != 'string')
-        return done(new Error("Iconv encoding stream needs strings as its input."));
-    try {
-        var res = this.conv.write(chunk);
-        if (res && res.length) this.push(res);
-        done();
-    }
-    catch (e) {
-        done(e);
-    }
-}
-
-IconvLiteEncoderStream.prototype._flush = function(done) {
-    try {
-        var res = this.conv.end();
-        if (res && res.length) this.push(res);
-        done();
-    }
-    catch (e) {
-        done(e);
-    }
-}
-
-IconvLiteEncoderStream.prototype.collect = function(cb) {
-    var chunks = [];
-    this.on('error', cb);
-    this.on('data', function(chunk) { chunks.push(chunk); });
-    this.on('end', function() {
-        cb(null, Buffer.concat(chunks));
-    });
-    return this;
-}
-
-
-// == Decoder stream =======================================================
-function IconvLiteDecoderStream(conv, options) {
-    this.conv = conv;
-    options = options || {};
-    options.encoding = this.encoding = 'utf8'; // We output strings.
-    Transform.call(this, options);
-}
-
-IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, {
-    constructor: { value: IconvLiteDecoderStream }
-});
-
-IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) {
-    if (!Buffer.isBuffer(chunk))
-        return done(new Error("Iconv decoding stream needs buffers as its input."));
-    try {
-        var res = this.conv.write(chunk);
-        if (res && res.length) this.push(res, this.encoding);
-        done();
-    }
-    catch (e) {
-        done(e);
-    }
-}
-
-IconvLiteDecoderStream.prototype._flush = function(done) {
-    try {
-        var res = this.conv.end();
-        if (res && res.length) this.push(res, this.encoding);                
-        done();
-    }
-    catch (e) {
-        done(e);
-    }
-}
-
-IconvLiteDecoderStream.prototype.collect = function(cb) {
-    var res = '';
-    this.on('error', cb);
-    this.on('data', function(chunk) { res += chunk; });
-    this.on('end', function() {
-        cb(null, res);
-    });
-    return this;
-}
-
+"use strict";var Buffer=require("buffer").Buffer,Transform=require("stream").Transform;function IconvLiteEncoderStream(t,e){this.conv=t,(e=e||{}).decodeStrings=!1,Transform.call(this,e)}function IconvLiteDecoderStream(t,e){this.conv=t,(e=e||{}).encoding=this.encoding="utf8",Transform.call(this,e)}module.exports=function(t){t.encodeStream=function(e,r){return new IconvLiteEncoderStream(t.getEncoder(e,r),r)},t.decodeStream=function(e,r){return new IconvLiteDecoderStream(t.getDecoder(e,r),r)},t.supportsStreams=!0,t.IconvLiteEncoderStream=IconvLiteEncoderStream,t.IconvLiteDecoderStream=IconvLiteDecoderStream,t._collect=IconvLiteDecoderStream.prototype.collect},IconvLiteEncoderStream.prototype=Object.create(Transform.prototype,{constructor:{value:IconvLiteEncoderStream}}),IconvLiteEncoderStream.prototype._transform=function(t,e,r){if("string"!=typeof t)return r(new Error("Iconv encoding stream needs strings as its input."));try{var o=this.conv.write(t);o&&o.length&&this.push(o),r()}catch(t){r(t)}},IconvLiteEncoderStream.prototype._flush=function(t){try{var e=this.conv.end();e&&e.length&&this.push(e),t()}catch(e){t(e)}},IconvLiteEncoderStream.prototype.collect=function(t){var e=[];return this.on("error",t),this.on("data",(function(t){e.push(t)})),this.on("end",(function(){t(null,Buffer.concat(e))})),this},IconvLiteDecoderStream.prototype=Object.create(Transform.prototype,{constructor:{value:IconvLiteDecoderStream}}),IconvLiteDecoderStream.prototype._transform=function(t,e,r){if(!Buffer.isBuffer(t))return r(new Error("Iconv decoding stream needs buffers as its input."));try{var o=this.conv.write(t);o&&o.length&&this.push(o,this.encoding),r()}catch(t){r(t)}},IconvLiteDecoderStream.prototype._flush=function(t){try{var e=this.conv.end();e&&e.length&&this.push(e,this.encoding),t()}catch(e){t(e)}},IconvLiteDecoderStream.prototype.collect=function(t){var e="";return this.on("error",t),this.on("data",(function(t){e+=t})),this.on("end",(function(){t(null,e)})),this};
\ No newline at end of file
index 81d26c3..008385b 100644 (file)
@@ -1,85 +1,2 @@
 /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
-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
-}
+exports.read=function(a,o,t,r,h){var M,p,w=8*h-r-1,f=(1<<w)-1,e=f>>1,i=-7,N=t?h-1:0,n=t?-1:1,s=a[o+N];for(N+=n,M=s&(1<<-i)-1,s>>=-i,i+=w;i>0;M=256*M+a[o+N],N+=n,i-=8);for(p=M&(1<<-i)-1,M>>=-i,i+=r;i>0;p=256*p+a[o+N],N+=n,i-=8);if(0===M)M=1-e;else{if(M===f)return p?NaN:1/0*(s?-1:1);p+=Math.pow(2,r),M-=e}return(s?-1:1)*p*Math.pow(2,M-r)},exports.write=function(a,o,t,r,h,M){var p,w,f,e=8*M-h-1,i=(1<<e)-1,N=i>>1,n=23===h?Math.pow(2,-24)-Math.pow(2,-77):0,s=r?0:M-1,u=r?1:-1,l=o<0||0===o&&1/o<0?1:0;for(o=Math.abs(o),isNaN(o)||o===1/0?(w=isNaN(o)?1:0,p=i):(p=Math.floor(Math.log(o)/Math.LN2),o*(f=Math.pow(2,-p))<1&&(p--,f*=2),(o+=p+N>=1?n/f:n*Math.pow(2,1-N))*f>=2&&(p++,f/=2),p+N>=i?(w=0,p=i):p+N>=1?(w=(o*f-1)*Math.pow(2,h),p+=N):(w=o*Math.pow(2,N-1)*Math.pow(2,h),p=0));h>=8;a[t+s]=255&w,s+=u,w/=256,h-=8);for(p=p<<h|w,e+=h;e>0;a[t+s]=255&p,s+=u,p/=256,e-=8);a[t+s-u]|=128*l};
\ No newline at end of file
index 9d9667b..ea4efa9 100644 (file)
@@ -1,10 +1 @@
-
-var indexOf = [].indexOf;
-
-module.exports = function(arr, obj){
-  if (indexOf) return arr.indexOf(obj);
-  for (var i = 0; i < arr.length; ++i) {
-    if (arr[i] === obj) return i;
-  }
-  return -1;
-};
\ No newline at end of file
+var indexOf=[].indexOf;module.exports=function(e,n){if(indexOf)return e.indexOf(n);for(var r=0;r<e.length;++r)if(e[r]===n)return r;return-1};
\ No newline at end of file
index 3b94763..4698010 100644 (file)
@@ -1,7 +1 @@
-try {
-  var util = require('util');
-  if (typeof util.inherits !== 'function') throw '';
-  module.exports = util.inherits;
-} catch (e) {
-  module.exports = require('./inherits_browser.js');
-}
+try{var util=require("util");if("function"!=typeof util.inherits)throw"";module.exports=util.inherits}catch(i){module.exports=require("./inherits_browser.js")}
\ No newline at end of file
index c1e78a7..7d37808 100644 (file)
@@ -1,23 +1 @@
-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"==typeof Object.create?module.exports=function(t,e){t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:module.exports=function(t,e){t.super_=e;var o=function(){};o.prototype=e.prototype,t.prototype=new o,t.prototype.constructor=t};
\ No newline at end of file
index b54a7cc..6b8c616 100644 (file)
@@ -1 +1 @@
-(function(){var r,t,n,e,i,o,a,s;t={},s=this,"undefined"!=typeof module&&null!==module&&module.exports?module.exports=t:s.ipaddr=t,a=function(r,t,n,e){var i,o;if(r.length!==t.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");for(i=0;e>0;){if((o=n-e)<0&&(o=0),r[i]>>o!=t[i]>>o)return!1;e-=n,i+=1}return!0},t.subnetMatch=function(r,t,n){var e,i,o,a,s;null==n&&(n="unicast");for(o in t)for(!(a=t[o])[0]||a[0]instanceof Array||(a=[a]),e=0,i=a.length;e<i;e++)if(s=a[e],r.kind()===s[0].kind()&&r.match.apply(r,s))return o;return n},t.IPv4=function(){function r(r){var t,n,e;if(4!==r.length)throw new Error("ipaddr: ipv4 octet count should be 4");for(t=0,n=r.length;t<n;t++)if(!(0<=(e=r[t])&&e<=255))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=r}return r.prototype.kind=function(){return"ipv4"},r.prototype.toString=function(){return this.octets.join(".")},r.prototype.toNormalizedString=function(){return this.toString()},r.prototype.toByteArray=function(){return this.octets.slice(0)},r.prototype.match=function(r,t){var n;if(void 0===t&&(r=(n=r)[0],t=n[1]),"ipv4"!==r.kind())throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return a(this.octets,r.octets,8,t)},r.prototype.SpecialRanges={unspecified:[[new r([0,0,0,0]),8]],broadcast:[[new r([255,255,255,255]),32]],multicast:[[new r([224,0,0,0]),4]],linkLocal:[[new r([169,254,0,0]),16]],loopback:[[new r([127,0,0,0]),8]],carrierGradeNat:[[new r([100,64,0,0]),10]],private:[[new r([10,0,0,0]),8],[new r([172,16,0,0]),12],[new r([192,168,0,0]),16]],reserved:[[new r([192,0,0,0]),24],[new r([192,0,2,0]),24],[new r([192,88,99,0]),24],[new r([198,51,100,0]),24],[new r([203,0,113,0]),24],[new r([240,0,0,0]),4]]},r.prototype.range=function(){return t.subnetMatch(this,this.SpecialRanges)},r.prototype.toIPv4MappedAddress=function(){return t.IPv6.parse("::ffff:"+this.toString())},r.prototype.prefixLengthFromSubnetMask=function(){var r,t,n,e,i,o,a;for(a={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},r=0,i=!1,t=n=3;n>=0;t=n+=-1){if(!((e=this.octets[t])in a))return null;if(o=a[e],i&&0!==o)return null;8!==o&&(i=!0),r+=o}return 32-r},r}(),n="(0?\\d+|0x[a-f0-9]+)",e={fourOctet:new RegExp("^"+n+"\\."+n+"\\."+n+"\\."+n+"$","i"),longValue:new RegExp("^"+n+"$","i")},t.IPv4.parser=function(r){var t,n,i,o,a;if(n=function(r){return"0"===r[0]&&"x"!==r[1]?parseInt(r,8):parseInt(r)},t=r.match(e.fourOctet))return function(){var r,e,o,a;for(a=[],r=0,e=(o=t.slice(1,6)).length;r<e;r++)i=o[r],a.push(n(i));return a}();if(t=r.match(e.longValue)){if((a=n(t[1]))>4294967295||a<0)throw new Error("ipaddr: address outside defined range");return function(){var r,t;for(t=[],o=r=0;r<=24;o=r+=8)t.push(a>>o&255);return t}().reverse()}return null},t.IPv6=function(){function r(r,t){var n,e,i,o,a,s;if(16===r.length)for(this.parts=[],n=e=0;e<=14;n=e+=2)this.parts.push(r[n]<<8|r[n+1]);else{if(8!==r.length)throw new Error("ipaddr: ipv6 part count should be 8 or 16");this.parts=r}for(i=0,o=(s=this.parts).length;i<o;i++)if(!(0<=(a=s[i])&&a<=65535))throw new Error("ipaddr: ipv6 part should fit in 16 bits");t&&(this.zoneId=t)}return r.prototype.kind=function(){return"ipv6"},r.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},r.prototype.toRFC5952String=function(){var r,t,n,e,i;for(e=/((^|:)(0(:|$)){2,})/g,i=this.toNormalizedString(),r=0,t=-1;n=e.exec(i);)n[0].length>t&&(r=n.index,t=n[0].length);return t<0?i:i.substring(0,r)+"::"+i.substring(r+t)},r.prototype.toByteArray=function(){var r,t,n,e,i;for(r=[],t=0,n=(i=this.parts).length;t<n;t++)e=i[t],r.push(e>>8),r.push(255&e);return r},r.prototype.toNormalizedString=function(){var r,t,n;return r=function(){var r,n,e,i;for(i=[],r=0,n=(e=this.parts).length;r<n;r++)t=e[r],i.push(t.toString(16));return i}.call(this).join(":"),n="",this.zoneId&&(n="%"+this.zoneId),r+n},r.prototype.toFixedLengthString=function(){var r,t,n;return r=function(){var r,n,e,i;for(i=[],r=0,n=(e=this.parts).length;r<n;r++)t=e[r],i.push(t.toString(16).padStart(4,"0"));return i}.call(this).join(":"),n="",this.zoneId&&(n="%"+this.zoneId),r+n},r.prototype.match=function(r,t){var n;if(void 0===t&&(r=(n=r)[0],t=n[1]),"ipv6"!==r.kind())throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return a(this.parts,r.parts,16,t)},r.prototype.SpecialRanges={unspecified:[new r([0,0,0,0,0,0,0,0]),128],linkLocal:[new r([65152,0,0,0,0,0,0,0]),10],multicast:[new r([65280,0,0,0,0,0,0,0]),8],loopback:[new r([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new r([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new r([0,0,0,0,0,65535,0,0]),96],rfc6145:[new r([0,0,0,0,65535,0,0,0]),96],rfc6052:[new r([100,65435,0,0,0,0,0,0]),96],"6to4":[new r([8194,0,0,0,0,0,0,0]),16],teredo:[new r([8193,0,0,0,0,0,0,0]),32],reserved:[[new r([8193,3512,0,0,0,0,0,0]),32]]},r.prototype.range=function(){return t.subnetMatch(this,this.SpecialRanges)},r.prototype.isIPv4MappedAddress=function(){return"ipv4Mapped"===this.range()},r.prototype.toIPv4Address=function(){var r,n,e;if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");return e=this.parts.slice(-2),r=e[0],n=e[1],new t.IPv4([r>>8,255&r,n>>8,255&n])},r.prototype.prefixLengthFromSubnetMask=function(){var r,t,n,e,i,o,a;for(a={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},r=0,i=!1,t=n=7;n>=0;t=n+=-1){if(!((e=this.parts[t])in a))return null;if(o=a[e],i&&0!==o)return null;16!==o&&(i=!0),r+=o}return 128-r},r}(),i="(?:[0-9a-f]+::?)+",o={zoneIndex:new RegExp("%[0-9a-z]{1,}","i"),native:new RegExp("^(::)?("+i+")?([0-9a-f]+)?(::)?(%[0-9a-z]{1,})?$","i"),transitional:new RegExp("^((?:"+i+")|(?:::)(?:"+i+")?)"+n+"\\."+n+"\\."+n+"\\."+n+"(%[0-9a-z]{1,})?$","i")},r=function(r,t){var n,e,i,a,s,p;if(r.indexOf("::")!==r.lastIndexOf("::"))return null;for((p=(r.match(o.zoneIndex)||[])[0])&&(p=p.substring(1),r=r.replace(/%.+$/,"")),n=0,e=-1;(e=r.indexOf(":",e+1))>=0;)n++;if("::"===r.substr(0,2)&&n--,"::"===r.substr(-2,2)&&n--,n>t)return null;for(s=t-n,a=":";s--;)a+="0:";return":"===(r=r.replace("::",a))[0]&&(r=r.slice(1)),":"===r[r.length-1]&&(r=r.slice(0,-1)),t=function(){var t,n,e,o;for(o=[],t=0,n=(e=r.split(":")).length;t<n;t++)i=e[t],o.push(parseInt(i,16));return o}(),{parts:t,zoneId:p}},t.IPv6.parser=function(t){var n,e,i,a,s,p,u;if(o.native.test(t))return r(t,8);if((a=t.match(o.transitional))&&(u=a[6]||"",(n=r(a[1].slice(0,-1)+u,6)).parts)){for(e=0,i=(p=[parseInt(a[2]),parseInt(a[3]),parseInt(a[4]),parseInt(a[5])]).length;e<i;e++)if(!(0<=(s=p[e])&&s<=255))return null;return n.parts.push(p[0]<<8|p[1]),n.parts.push(p[2]<<8|p[3]),{parts:n.parts,zoneId:n.zoneId}}return null},t.IPv4.isIPv4=t.IPv6.isIPv6=function(r){return null!==this.parser(r)},t.IPv4.isValid=function(r){try{return new this(this.parser(r)),!0}catch(r){return r,!1}},t.IPv4.isValidFourPartDecimal=function(r){return!(!t.IPv4.isValid(r)||!r.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},t.IPv6.isValid=function(r){var t;if("string"==typeof r&&-1===r.indexOf(":"))return!1;try{return t=this.parser(r),new this(t.parts,t.zoneId),!0}catch(r){return r,!1}},t.IPv4.parse=function(r){var t;if(null===(t=this.parser(r)))throw new Error("ipaddr: string is not formatted like ip address");return new this(t)},t.IPv6.parse=function(r){var t;if(null===(t=this.parser(r)).parts)throw new Error("ipaddr: string is not formatted like ip address");return new this(t.parts,t.zoneId)},t.IPv4.parseCIDR=function(r){var t,n,e;if((n=r.match(/^(.+)\/(\d+)$/))&&(t=parseInt(n[2]))>=0&&t<=32)return e=[this.parse(n[1]),t],Object.defineProperty(e,"toString",{value:function(){return this.join("/")}}),e;throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},t.IPv4.subnetMaskFromPrefixLength=function(r){var t,n,e;if((r=parseInt(r))<0||r>32)throw new Error("ipaddr: invalid IPv4 prefix length");for(e=[0,0,0,0],n=0,t=Math.floor(r/8);n<t;)e[n]=255,n++;return t<4&&(e[t]=Math.pow(2,r%8)-1<<8-r%8),new this(e)},t.IPv4.broadcastAddressFromCIDR=function(r){var t,n,e,i,o;try{for(e=(t=this.parseCIDR(r))[0].toByteArray(),o=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],n=0;n<4;)i.push(parseInt(e[n],10)|255^parseInt(o[n],10)),n++;return new this(i)}catch(r){throw r,new Error("ipaddr: the address does not have IPv4 CIDR format")}},t.IPv4.networkAddressFromCIDR=function(r){var t,n,e,i,o;try{for(e=(t=this.parseCIDR(r))[0].toByteArray(),o=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],n=0;n<4;)i.push(parseInt(e[n],10)&parseInt(o[n],10)),n++;return new this(i)}catch(r){throw r,new Error("ipaddr: the address does not have IPv4 CIDR format")}},t.IPv6.parseCIDR=function(r){var t,n,e;if((n=r.match(/^(.+)\/(\d+)$/))&&(t=parseInt(n[2]))>=0&&t<=128)return e=[this.parse(n[1]),t],Object.defineProperty(e,"toString",{value:function(){return this.join("/")}}),e;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},t.isValid=function(r){return t.IPv6.isValid(r)||t.IPv4.isValid(r)},t.parse=function(r){if(t.IPv6.isValid(r))return t.IPv6.parse(r);if(t.IPv4.isValid(r))return t.IPv4.parse(r);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},t.parseCIDR=function(r){try{return t.IPv6.parseCIDR(r)}catch(n){n;try{return t.IPv4.parseCIDR(r)}catch(r){throw r,new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},t.fromByteArray=function(r){var n;if(4===(n=r.length))return new t.IPv4(r);if(16===n)return new t.IPv6(r);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},t.process=function(r){var t;return t=this.parse(r),"ipv6"===t.kind()&&t.isIPv4MappedAddress()?t.toIPv4Address():t}}).call(this);
\ No newline at end of file
+(function(){var r,t,n,e,i,o,a;t={},"undefined"!=typeof module&&null!==module&&module.exports?module.exports=t:this.ipaddr=t,a=function(r,t,n,e){var i,o;if(r.length!==t.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");for(i=0;e>0;){if((o=n-e)<0&&(o=0),r[i]>>o!=t[i]>>o)return!1;e-=n,i+=1}return!0},t.subnetMatch=function(r,t,n){var e,i,o,a,s;for(o in null==n&&(n="unicast"),t)for(!(a=t[o])[0]||a[0]instanceof Array||(a=[a]),e=0,i=a.length;e<i;e++)if(s=a[e],r.kind()===s[0].kind()&&r.match.apply(r,s))return o;return n},t.IPv4=function(){function r(r){var t,n,e;if(4!==r.length)throw new Error("ipaddr: ipv4 octet count should be 4");for(t=0,n=r.length;t<n;t++)if(!(0<=(e=r[t])&&e<=255))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=r}return r.prototype.kind=function(){return"ipv4"},r.prototype.toString=function(){return this.octets.join(".")},r.prototype.toNormalizedString=function(){return this.toString()},r.prototype.toByteArray=function(){return this.octets.slice(0)},r.prototype.match=function(r,t){var n;if(void 0===t&&(r=(n=r)[0],t=n[1]),"ipv4"!==r.kind())throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return a(this.octets,r.octets,8,t)},r.prototype.SpecialRanges={unspecified:[[new r([0,0,0,0]),8]],broadcast:[[new r([255,255,255,255]),32]],multicast:[[new r([224,0,0,0]),4]],linkLocal:[[new r([169,254,0,0]),16]],loopback:[[new r([127,0,0,0]),8]],carrierGradeNat:[[new r([100,64,0,0]),10]],private:[[new r([10,0,0,0]),8],[new r([172,16,0,0]),12],[new r([192,168,0,0]),16]],reserved:[[new r([192,0,0,0]),24],[new r([192,0,2,0]),24],[new r([192,88,99,0]),24],[new r([198,51,100,0]),24],[new r([203,0,113,0]),24],[new r([240,0,0,0]),4]]},r.prototype.range=function(){return t.subnetMatch(this,this.SpecialRanges)},r.prototype.toIPv4MappedAddress=function(){return t.IPv6.parse("::ffff:"+this.toString())},r.prototype.prefixLengthFromSubnetMask=function(){var r,t,n,e,i,o,a;for(a={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},r=0,i=!1,t=n=3;n>=0;t=n+=-1){if(!((e=this.octets[t])in a))return null;if(o=a[e],i&&0!==o)return null;8!==o&&(i=!0),r+=o}return 32-r},r}(),n="(0?\\d+|0x[a-f0-9]+)",e={fourOctet:new RegExp("^"+n+"\\."+n+"\\."+n+"\\."+n+"$","i"),longValue:new RegExp("^"+n+"$","i")},t.IPv4.parser=function(r){var t,n,i,o,a;if(n=function(r){return"0"===r[0]&&"x"!==r[1]?parseInt(r,8):parseInt(r)},t=r.match(e.fourOctet))return function(){var r,e,o,a;for(a=[],r=0,e=(o=t.slice(1,6)).length;r<e;r++)i=o[r],a.push(n(i));return a}();if(t=r.match(e.longValue)){if((a=n(t[1]))>4294967295||a<0)throw new Error("ipaddr: address outside defined range");return function(){var r,t;for(t=[],o=r=0;r<=24;o=r+=8)t.push(a>>o&255);return t}().reverse()}return null},t.IPv6=function(){function r(r,t){var n,e,i,o,a,s;if(16===r.length)for(this.parts=[],n=e=0;e<=14;n=e+=2)this.parts.push(r[n]<<8|r[n+1]);else{if(8!==r.length)throw new Error("ipaddr: ipv6 part count should be 8 or 16");this.parts=r}for(i=0,o=(s=this.parts).length;i<o;i++)if(!(0<=(a=s[i])&&a<=65535))throw new Error("ipaddr: ipv6 part should fit in 16 bits");t&&(this.zoneId=t)}return r.prototype.kind=function(){return"ipv6"},r.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},r.prototype.toRFC5952String=function(){var r,t,n,e,i;for(e=/((^|:)(0(:|$)){2,})/g,i=this.toNormalizedString(),r=0,t=-1;n=e.exec(i);)n[0].length>t&&(r=n.index,t=n[0].length);return t<0?i:i.substring(0,r)+"::"+i.substring(r+t)},r.prototype.toByteArray=function(){var r,t,n,e,i;for(r=[],t=0,n=(i=this.parts).length;t<n;t++)e=i[t],r.push(e>>8),r.push(255&e);return r},r.prototype.toNormalizedString=function(){var r,t,n;return r=function(){var r,n,e,i;for(i=[],r=0,n=(e=this.parts).length;r<n;r++)t=e[r],i.push(t.toString(16));return i}.call(this).join(":"),n="",this.zoneId&&(n="%"+this.zoneId),r+n},r.prototype.toFixedLengthString=function(){var r,t,n;return r=function(){var r,n,e,i;for(i=[],r=0,n=(e=this.parts).length;r<n;r++)t=e[r],i.push(t.toString(16).padStart(4,"0"));return i}.call(this).join(":"),n="",this.zoneId&&(n="%"+this.zoneId),r+n},r.prototype.match=function(r,t){var n;if(void 0===t&&(r=(n=r)[0],t=n[1]),"ipv6"!==r.kind())throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return a(this.parts,r.parts,16,t)},r.prototype.SpecialRanges={unspecified:[new r([0,0,0,0,0,0,0,0]),128],linkLocal:[new r([65152,0,0,0,0,0,0,0]),10],multicast:[new r([65280,0,0,0,0,0,0,0]),8],loopback:[new r([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new r([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new r([0,0,0,0,0,65535,0,0]),96],rfc6145:[new r([0,0,0,0,65535,0,0,0]),96],rfc6052:[new r([100,65435,0,0,0,0,0,0]),96],"6to4":[new r([8194,0,0,0,0,0,0,0]),16],teredo:[new r([8193,0,0,0,0,0,0,0]),32],reserved:[[new r([8193,3512,0,0,0,0,0,0]),32]]},r.prototype.range=function(){return t.subnetMatch(this,this.SpecialRanges)},r.prototype.isIPv4MappedAddress=function(){return"ipv4Mapped"===this.range()},r.prototype.toIPv4Address=function(){var r,n,e;if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");return r=(e=this.parts.slice(-2))[0],n=e[1],new t.IPv4([r>>8,255&r,n>>8,255&n])},r.prototype.prefixLengthFromSubnetMask=function(){var r,t,n,e,i,o,a;for(a={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},r=0,i=!1,t=n=7;n>=0;t=n+=-1){if(!((e=this.parts[t])in a))return null;if(o=a[e],i&&0!==o)return null;16!==o&&(i=!0),r+=o}return 128-r},r}(),i="(?:[0-9a-f]+::?)+",o={zoneIndex:new RegExp("%[0-9a-z]{1,}","i"),native:new RegExp("^(::)?("+i+")?([0-9a-f]+)?(::)?(%[0-9a-z]{1,})?$","i"),transitional:new RegExp("^((?:"+i+")|(?:::)(?:"+i+")?)"+n+"\\."+n+"\\."+n+"\\."+n+"(%[0-9a-z]{1,})?$","i")},r=function(r,t){var n,e,i,a,s,p;if(r.indexOf("::")!==r.lastIndexOf("::"))return null;for((p=(r.match(o.zoneIndex)||[])[0])&&(p=p.substring(1),r=r.replace(/%.+$/,"")),n=0,e=-1;(e=r.indexOf(":",e+1))>=0;)n++;if("::"===r.substr(0,2)&&n--,"::"===r.substr(-2,2)&&n--,n>t)return null;for(s=t-n,a=":";s--;)a+="0:";return":"===(r=r.replace("::",a))[0]&&(r=r.slice(1)),":"===r[r.length-1]&&(r=r.slice(0,-1)),{parts:t=function(){var t,n,e,o;for(o=[],t=0,n=(e=r.split(":")).length;t<n;t++)i=e[t],o.push(parseInt(i,16));return o}(),zoneId:p}},t.IPv6.parser=function(t){var n,e,i,a,s,p,u;if(o.native.test(t))return r(t,8);if((a=t.match(o.transitional))&&(u=a[6]||"",(n=r(a[1].slice(0,-1)+u,6)).parts)){for(e=0,i=(p=[parseInt(a[2]),parseInt(a[3]),parseInt(a[4]),parseInt(a[5])]).length;e<i;e++)if(!(0<=(s=p[e])&&s<=255))return null;return n.parts.push(p[0]<<8|p[1]),n.parts.push(p[2]<<8|p[3]),{parts:n.parts,zoneId:n.zoneId}}return null},t.IPv4.isIPv4=t.IPv6.isIPv6=function(r){return null!==this.parser(r)},t.IPv4.isValid=function(r){try{return new this(this.parser(r)),!0}catch(r){return!1}},t.IPv4.isValidFourPartDecimal=function(r){return!(!t.IPv4.isValid(r)||!r.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},t.IPv6.isValid=function(r){var t;if("string"==typeof r&&-1===r.indexOf(":"))return!1;try{return new this((t=this.parser(r)).parts,t.zoneId),!0}catch(r){return!1}},t.IPv4.parse=function(r){var t;if(null===(t=this.parser(r)))throw new Error("ipaddr: string is not formatted like ip address");return new this(t)},t.IPv6.parse=function(r){var t;if(null===(t=this.parser(r)).parts)throw new Error("ipaddr: string is not formatted like ip address");return new this(t.parts,t.zoneId)},t.IPv4.parseCIDR=function(r){var t,n,e;if((n=r.match(/^(.+)\/(\d+)$/))&&(t=parseInt(n[2]))>=0&&t<=32)return e=[this.parse(n[1]),t],Object.defineProperty(e,"toString",{value:function(){return this.join("/")}}),e;throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},t.IPv4.subnetMaskFromPrefixLength=function(r){var t,n,e;if((r=parseInt(r))<0||r>32)throw new Error("ipaddr: invalid IPv4 prefix length");for(e=[0,0,0,0],n=0,t=Math.floor(r/8);n<t;)e[n]=255,n++;return t<4&&(e[t]=Math.pow(2,r%8)-1<<8-r%8),new this(e)},t.IPv4.broadcastAddressFromCIDR=function(r){var t,n,e,i,o;try{for(e=(t=this.parseCIDR(r))[0].toByteArray(),o=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],n=0;n<4;)i.push(parseInt(e[n],10)|255^parseInt(o[n],10)),n++;return new this(i)}catch(r){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},t.IPv4.networkAddressFromCIDR=function(r){var t,n,e,i,o;try{for(e=(t=this.parseCIDR(r))[0].toByteArray(),o=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],n=0;n<4;)i.push(parseInt(e[n],10)&parseInt(o[n],10)),n++;return new this(i)}catch(r){throw new Error("ipaddr: the address does not have IPv4 CIDR format")}},t.IPv6.parseCIDR=function(r){var t,n,e;if((n=r.match(/^(.+)\/(\d+)$/))&&(t=parseInt(n[2]))>=0&&t<=128)return e=[this.parse(n[1]),t],Object.defineProperty(e,"toString",{value:function(){return this.join("/")}}),e;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},t.isValid=function(r){return t.IPv6.isValid(r)||t.IPv4.isValid(r)},t.parse=function(r){if(t.IPv6.isValid(r))return t.IPv6.parse(r);if(t.IPv4.isValid(r))return t.IPv4.parse(r);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},t.parseCIDR=function(r){try{return t.IPv6.parseCIDR(r)}catch(n){try{return t.IPv4.parseCIDR(r)}catch(r){throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},t.fromByteArray=function(r){var n;if(4===(n=r.length))return new t.IPv4(r);if(16===n)return new t.IPv6(r);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},t.process=function(r){var t;return"ipv6"===(t=this.parse(r)).kind()&&t.isIPv4MappedAddress()?t.toIPv4Address():t}}).call(this);
\ No newline at end of file
index 18bd93b..9c93081 100644 (file)
@@ -1,673 +1 @@
-(function() {
-  var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex;
-
-  ipaddr = {};
-
-  root = this;
-
-  if ((typeof module !== "undefined" && module !== null) && module.exports) {
-    module.exports = ipaddr;
-  } else {
-    root['ipaddr'] = ipaddr;
-  }
-
-  matchCIDR = function(first, second, partSize, cidrBits) {
-    var part, shift;
-    if (first.length !== second.length) {
-      throw new Error("ipaddr: cannot match CIDR for objects with different lengths");
-    }
-    part = 0;
-    while (cidrBits > 0) {
-      shift = partSize - cidrBits;
-      if (shift < 0) {
-        shift = 0;
-      }
-      if (first[part] >> shift !== second[part] >> shift) {
-        return false;
-      }
-      cidrBits -= partSize;
-      part += 1;
-    }
-    return true;
-  };
-
-  ipaddr.subnetMatch = function(address, rangeList, defaultName) {
-    var k, len, rangeName, rangeSubnets, subnet;
-    if (defaultName == null) {
-      defaultName = 'unicast';
-    }
-    for (rangeName in rangeList) {
-      rangeSubnets = rangeList[rangeName];
-      if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) {
-        rangeSubnets = [rangeSubnets];
-      }
-      for (k = 0, len = rangeSubnets.length; k < len; k++) {
-        subnet = rangeSubnets[k];
-        if (address.kind() === subnet[0].kind()) {
-          if (address.match.apply(address, subnet)) {
-            return rangeName;
-          }
-        }
-      }
-    }
-    return defaultName;
-  };
-
-  ipaddr.IPv4 = (function() {
-    function IPv4(octets) {
-      var k, len, octet;
-      if (octets.length !== 4) {
-        throw new Error("ipaddr: ipv4 octet count should be 4");
-      }
-      for (k = 0, len = octets.length; k < len; k++) {
-        octet = octets[k];
-        if (!((0 <= octet && octet <= 255))) {
-          throw new Error("ipaddr: ipv4 octet should fit in 8 bits");
-        }
-      }
-      this.octets = octets;
-    }
-
-    IPv4.prototype.kind = function() {
-      return 'ipv4';
-    };
-
-    IPv4.prototype.toString = function() {
-      return this.octets.join(".");
-    };
-
-    IPv4.prototype.toNormalizedString = function() {
-      return this.toString();
-    };
-
-    IPv4.prototype.toByteArray = function() {
-      return this.octets.slice(0);
-    };
-
-    IPv4.prototype.match = function(other, cidrRange) {
-      var ref;
-      if (cidrRange === void 0) {
-        ref = other, other = ref[0], cidrRange = ref[1];
-      }
-      if (other.kind() !== 'ipv4') {
-        throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");
-      }
-      return matchCIDR(this.octets, other.octets, 8, cidrRange);
-    };
-
-    IPv4.prototype.SpecialRanges = {
-      unspecified: [[new IPv4([0, 0, 0, 0]), 8]],
-      broadcast: [[new IPv4([255, 255, 255, 255]), 32]],
-      multicast: [[new IPv4([224, 0, 0, 0]), 4]],
-      linkLocal: [[new IPv4([169, 254, 0, 0]), 16]],
-      loopback: [[new IPv4([127, 0, 0, 0]), 8]],
-      carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]],
-      "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]],
-      reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]]
-    };
-
-    IPv4.prototype.range = function() {
-      return ipaddr.subnetMatch(this, this.SpecialRanges);
-    };
-
-    IPv4.prototype.toIPv4MappedAddress = function() {
-      return ipaddr.IPv6.parse("::ffff:" + (this.toString()));
-    };
-
-    IPv4.prototype.prefixLengthFromSubnetMask = function() {
-      var cidr, i, k, octet, stop, zeros, zerotable;
-      zerotable = {
-        0: 8,
-        128: 7,
-        192: 6,
-        224: 5,
-        240: 4,
-        248: 3,
-        252: 2,
-        254: 1,
-        255: 0
-      };
-      cidr = 0;
-      stop = false;
-      for (i = k = 3; k >= 0; i = k += -1) {
-        octet = this.octets[i];
-        if (octet in zerotable) {
-          zeros = zerotable[octet];
-          if (stop && zeros !== 0) {
-            return null;
-          }
-          if (zeros !== 8) {
-            stop = true;
-          }
-          cidr += zeros;
-        } else {
-          return null;
-        }
-      }
-      return 32 - cidr;
-    };
-
-    return IPv4;
-
-  })();
-
-  ipv4Part = "(0?\\d+|0x[a-f0-9]+)";
-
-  ipv4Regexes = {
-    fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'),
-    longValue: new RegExp("^" + ipv4Part + "$", 'i')
-  };
-
-  ipaddr.IPv4.parser = function(string) {
-    var match, parseIntAuto, part, shift, value;
-    parseIntAuto = function(string) {
-      if (string[0] === "0" && string[1] !== "x") {
-        return parseInt(string, 8);
-      } else {
-        return parseInt(string);
-      }
-    };
-    if (match = string.match(ipv4Regexes.fourOctet)) {
-      return (function() {
-        var k, len, ref, results;
-        ref = match.slice(1, 6);
-        results = [];
-        for (k = 0, len = ref.length; k < len; k++) {
-          part = ref[k];
-          results.push(parseIntAuto(part));
-        }
-        return results;
-      })();
-    } else if (match = string.match(ipv4Regexes.longValue)) {
-      value = parseIntAuto(match[1]);
-      if (value > 0xffffffff || value < 0) {
-        throw new Error("ipaddr: address outside defined range");
-      }
-      return ((function() {
-        var k, results;
-        results = [];
-        for (shift = k = 0; k <= 24; shift = k += 8) {
-          results.push((value >> shift) & 0xff);
-        }
-        return results;
-      })()).reverse();
-    } else {
-      return null;
-    }
-  };
-
-  ipaddr.IPv6 = (function() {
-    function IPv6(parts, zoneId) {
-      var i, k, l, len, part, ref;
-      if (parts.length === 16) {
-        this.parts = [];
-        for (i = k = 0; k <= 14; i = k += 2) {
-          this.parts.push((parts[i] << 8) | parts[i + 1]);
-        }
-      } else if (parts.length === 8) {
-        this.parts = parts;
-      } else {
-        throw new Error("ipaddr: ipv6 part count should be 8 or 16");
-      }
-      ref = this.parts;
-      for (l = 0, len = ref.length; l < len; l++) {
-        part = ref[l];
-        if (!((0 <= part && part <= 0xffff))) {
-          throw new Error("ipaddr: ipv6 part should fit in 16 bits");
-        }
-      }
-      if (zoneId) {
-        this.zoneId = zoneId;
-      }
-    }
-
-    IPv6.prototype.kind = function() {
-      return 'ipv6';
-    };
-
-    IPv6.prototype.toString = function() {
-      return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, '::');
-    };
-
-    IPv6.prototype.toRFC5952String = function() {
-      var bestMatchIndex, bestMatchLength, match, regex, string;
-      regex = /((^|:)(0(:|$)){2,})/g;
-      string = this.toNormalizedString();
-      bestMatchIndex = 0;
-      bestMatchLength = -1;
-      while ((match = regex.exec(string))) {
-        if (match[0].length > bestMatchLength) {
-          bestMatchIndex = match.index;
-          bestMatchLength = match[0].length;
-        }
-      }
-      if (bestMatchLength < 0) {
-        return string;
-      }
-      return string.substring(0, bestMatchIndex) + '::' + string.substring(bestMatchIndex + bestMatchLength);
-    };
-
-    IPv6.prototype.toByteArray = function() {
-      var bytes, k, len, part, ref;
-      bytes = [];
-      ref = this.parts;
-      for (k = 0, len = ref.length; k < len; k++) {
-        part = ref[k];
-        bytes.push(part >> 8);
-        bytes.push(part & 0xff);
-      }
-      return bytes;
-    };
-
-    IPv6.prototype.toNormalizedString = function() {
-      var addr, part, suffix;
-      addr = ((function() {
-        var k, len, ref, results;
-        ref = this.parts;
-        results = [];
-        for (k = 0, len = ref.length; k < len; k++) {
-          part = ref[k];
-          results.push(part.toString(16));
-        }
-        return results;
-      }).call(this)).join(":");
-      suffix = '';
-      if (this.zoneId) {
-        suffix = '%' + this.zoneId;
-      }
-      return addr + suffix;
-    };
-
-    IPv6.prototype.toFixedLengthString = function() {
-      var addr, part, suffix;
-      addr = ((function() {
-        var k, len, ref, results;
-        ref = this.parts;
-        results = [];
-        for (k = 0, len = ref.length; k < len; k++) {
-          part = ref[k];
-          results.push(part.toString(16).padStart(4, '0'));
-        }
-        return results;
-      }).call(this)).join(":");
-      suffix = '';
-      if (this.zoneId) {
-        suffix = '%' + this.zoneId;
-      }
-      return addr + suffix;
-    };
-
-    IPv6.prototype.match = function(other, cidrRange) {
-      var ref;
-      if (cidrRange === void 0) {
-        ref = other, other = ref[0], cidrRange = ref[1];
-      }
-      if (other.kind() !== 'ipv6') {
-        throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");
-      }
-      return matchCIDR(this.parts, other.parts, 16, cidrRange);
-    };
-
-    IPv6.prototype.SpecialRanges = {
-      unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128],
-      linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10],
-      multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8],
-      loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128],
-      uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7],
-      ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96],
-      rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96],
-      rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96],
-      '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16],
-      teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32],
-      reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]]
-    };
-
-    IPv6.prototype.range = function() {
-      return ipaddr.subnetMatch(this, this.SpecialRanges);
-    };
-
-    IPv6.prototype.isIPv4MappedAddress = function() {
-      return this.range() === 'ipv4Mapped';
-    };
-
-    IPv6.prototype.toIPv4Address = function() {
-      var high, low, ref;
-      if (!this.isIPv4MappedAddress()) {
-        throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");
-      }
-      ref = this.parts.slice(-2), high = ref[0], low = ref[1];
-      return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]);
-    };
-
-    IPv6.prototype.prefixLengthFromSubnetMask = function() {
-      var cidr, i, k, part, stop, zeros, zerotable;
-      zerotable = {
-        0: 16,
-        32768: 15,
-        49152: 14,
-        57344: 13,
-        61440: 12,
-        63488: 11,
-        64512: 10,
-        65024: 9,
-        65280: 8,
-        65408: 7,
-        65472: 6,
-        65504: 5,
-        65520: 4,
-        65528: 3,
-        65532: 2,
-        65534: 1,
-        65535: 0
-      };
-      cidr = 0;
-      stop = false;
-      for (i = k = 7; k >= 0; i = k += -1) {
-        part = this.parts[i];
-        if (part in zerotable) {
-          zeros = zerotable[part];
-          if (stop && zeros !== 0) {
-            return null;
-          }
-          if (zeros !== 16) {
-            stop = true;
-          }
-          cidr += zeros;
-        } else {
-          return null;
-        }
-      }
-      return 128 - cidr;
-    };
-
-    return IPv6;
-
-  })();
-
-  ipv6Part = "(?:[0-9a-f]+::?)+";
-
-  zoneIndex = "%[0-9a-z]{1,}";
-
-  ipv6Regexes = {
-    zoneIndex: new RegExp(zoneIndex, 'i'),
-    "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?(" + zoneIndex + ")?$", 'i'),
-    transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + (ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part) + ("(" + zoneIndex + ")?$"), 'i')
-  };
-
-  expandIPv6 = function(string, parts) {
-    var colonCount, lastColon, part, replacement, replacementCount, zoneId;
-    if (string.indexOf('::') !== string.lastIndexOf('::')) {
-      return null;
-    }
-    zoneId = (string.match(ipv6Regexes['zoneIndex']) || [])[0];
-    if (zoneId) {
-      zoneId = zoneId.substring(1);
-      string = string.replace(/%.+$/, '');
-    }
-    colonCount = 0;
-    lastColon = -1;
-    while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) {
-      colonCount++;
-    }
-    if (string.substr(0, 2) === '::') {
-      colonCount--;
-    }
-    if (string.substr(-2, 2) === '::') {
-      colonCount--;
-    }
-    if (colonCount > parts) {
-      return null;
-    }
-    replacementCount = parts - colonCount;
-    replacement = ':';
-    while (replacementCount--) {
-      replacement += '0:';
-    }
-    string = string.replace('::', replacement);
-    if (string[0] === ':') {
-      string = string.slice(1);
-    }
-    if (string[string.length - 1] === ':') {
-      string = string.slice(0, -1);
-    }
-    parts = (function() {
-      var k, len, ref, results;
-      ref = string.split(":");
-      results = [];
-      for (k = 0, len = ref.length; k < len; k++) {
-        part = ref[k];
-        results.push(parseInt(part, 16));
-      }
-      return results;
-    })();
-    return {
-      parts: parts,
-      zoneId: zoneId
-    };
-  };
-
-  ipaddr.IPv6.parser = function(string) {
-    var addr, k, len, match, octet, octets, zoneId;
-    if (ipv6Regexes['native'].test(string)) {
-      return expandIPv6(string, 8);
-    } else if (match = string.match(ipv6Regexes['transitional'])) {
-      zoneId = match[6] || '';
-      addr = expandIPv6(match[1].slice(0, -1) + zoneId, 6);
-      if (addr.parts) {
-        octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])];
-        for (k = 0, len = octets.length; k < len; k++) {
-          octet = octets[k];
-          if (!((0 <= octet && octet <= 255))) {
-            return null;
-          }
-        }
-        addr.parts.push(octets[0] << 8 | octets[1]);
-        addr.parts.push(octets[2] << 8 | octets[3]);
-        return {
-          parts: addr.parts,
-          zoneId: addr.zoneId
-        };
-      }
-    }
-    return null;
-  };
-
-  ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) {
-    return this.parser(string) !== null;
-  };
-
-  ipaddr.IPv4.isValid = function(string) {
-    var e;
-    try {
-      new this(this.parser(string));
-      return true;
-    } catch (error1) {
-      e = error1;
-      return false;
-    }
-  };
-
-  ipaddr.IPv4.isValidFourPartDecimal = function(string) {
-    if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) {
-      return true;
-    } else {
-      return false;
-    }
-  };
-
-  ipaddr.IPv6.isValid = function(string) {
-    var addr, e;
-    if (typeof string === "string" && string.indexOf(":") === -1) {
-      return false;
-    }
-    try {
-      addr = this.parser(string);
-      new this(addr.parts, addr.zoneId);
-      return true;
-    } catch (error1) {
-      e = error1;
-      return false;
-    }
-  };
-
-  ipaddr.IPv4.parse = function(string) {
-    var parts;
-    parts = this.parser(string);
-    if (parts === null) {
-      throw new Error("ipaddr: string is not formatted like ip address");
-    }
-    return new this(parts);
-  };
-
-  ipaddr.IPv6.parse = function(string) {
-    var addr;
-    addr = this.parser(string);
-    if (addr.parts === null) {
-      throw new Error("ipaddr: string is not formatted like ip address");
-    }
-    return new this(addr.parts, addr.zoneId);
-  };
-
-  ipaddr.IPv4.parseCIDR = function(string) {
-    var maskLength, match, parsed;
-    if (match = string.match(/^(.+)\/(\d+)$/)) {
-      maskLength = parseInt(match[2]);
-      if (maskLength >= 0 && maskLength <= 32) {
-        parsed = [this.parse(match[1]), maskLength];
-        Object.defineProperty(parsed, 'toString', {
-          value: function() {
-            return this.join('/');
-          }
-        });
-        return parsed;
-      }
-    }
-    throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range");
-  };
-
-  ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) {
-    var filledOctetCount, j, octets;
-    prefix = parseInt(prefix);
-    if (prefix < 0 || prefix > 32) {
-      throw new Error('ipaddr: invalid IPv4 prefix length');
-    }
-    octets = [0, 0, 0, 0];
-    j = 0;
-    filledOctetCount = Math.floor(prefix / 8);
-    while (j < filledOctetCount) {
-      octets[j] = 255;
-      j++;
-    }
-    if (filledOctetCount < 4) {
-      octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8);
-    }
-    return new this(octets);
-  };
-
-  ipaddr.IPv4.broadcastAddressFromCIDR = function(string) {
-    var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets;
-    try {
-      cidr = this.parseCIDR(string);
-      ipInterfaceOctets = cidr[0].toByteArray();
-      subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();
-      octets = [];
-      i = 0;
-      while (i < 4) {
-        octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255);
-        i++;
-      }
-      return new this(octets);
-    } catch (error1) {
-      error = error1;
-      throw new Error('ipaddr: the address does not have IPv4 CIDR format');
-    }
-  };
-
-  ipaddr.IPv4.networkAddressFromCIDR = function(string) {
-    var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets;
-    try {
-      cidr = this.parseCIDR(string);
-      ipInterfaceOctets = cidr[0].toByteArray();
-      subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();
-      octets = [];
-      i = 0;
-      while (i < 4) {
-        octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));
-        i++;
-      }
-      return new this(octets);
-    } catch (error1) {
-      error = error1;
-      throw new Error('ipaddr: the address does not have IPv4 CIDR format');
-    }
-  };
-
-  ipaddr.IPv6.parseCIDR = function(string) {
-    var maskLength, match, parsed;
-    if (match = string.match(/^(.+)\/(\d+)$/)) {
-      maskLength = parseInt(match[2]);
-      if (maskLength >= 0 && maskLength <= 128) {
-        parsed = [this.parse(match[1]), maskLength];
-        Object.defineProperty(parsed, 'toString', {
-          value: function() {
-            return this.join('/');
-          }
-        });
-        return parsed;
-      }
-    }
-    throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range");
-  };
-
-  ipaddr.isValid = function(string) {
-    return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string);
-  };
-
-  ipaddr.parse = function(string) {
-    if (ipaddr.IPv6.isValid(string)) {
-      return ipaddr.IPv6.parse(string);
-    } else if (ipaddr.IPv4.isValid(string)) {
-      return ipaddr.IPv4.parse(string);
-    } else {
-      throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format");
-    }
-  };
-
-  ipaddr.parseCIDR = function(string) {
-    var e;
-    try {
-      return ipaddr.IPv6.parseCIDR(string);
-    } catch (error1) {
-      e = error1;
-      try {
-        return ipaddr.IPv4.parseCIDR(string);
-      } catch (error1) {
-        e = error1;
-        throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format");
-      }
-    }
-  };
-
-  ipaddr.fromByteArray = function(bytes) {
-    var length;
-    length = bytes.length;
-    if (length === 4) {
-      return new ipaddr.IPv4(bytes);
-    } else if (length === 16) {
-      return new ipaddr.IPv6(bytes);
-    } else {
-      throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address");
-    }
-  };
-
-  ipaddr.process = function(string) {
-    var addr;
-    addr = this.parse(string);
-    if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) {
-      return addr.toIPv4Address();
-    } else {
-      return addr;
-    }
-  };
-
-}).call(this);
+(function(){var r,t,n,e,i,o,a,s;t={},"undefined"!=typeof module&&null!==module&&module.exports?module.exports=t:this.ipaddr=t,a=function(r,t,n,e){var i,o;if(r.length!==t.length)throw new Error("ipaddr: cannot match CIDR for objects with different lengths");for(i=0;e>0;){if((o=n-e)<0&&(o=0),r[i]>>o!=t[i]>>o)return!1;e-=n,i+=1}return!0},t.subnetMatch=function(r,t,n){var e,i,o,a,s;for(o in null==n&&(n="unicast"),t)for(!(a=t[o])[0]||a[0]instanceof Array||(a=[a]),e=0,i=a.length;e<i;e++)if(s=a[e],r.kind()===s[0].kind()&&r.match.apply(r,s))return o;return n},t.IPv4=function(){function r(r){var t,n,e;if(4!==r.length)throw new Error("ipaddr: ipv4 octet count should be 4");for(t=0,n=r.length;t<n;t++)if(!(0<=(e=r[t])&&e<=255))throw new Error("ipaddr: ipv4 octet should fit in 8 bits");this.octets=r}return r.prototype.kind=function(){return"ipv4"},r.prototype.toString=function(){return this.octets.join(".")},r.prototype.toNormalizedString=function(){return this.toString()},r.prototype.toByteArray=function(){return this.octets.slice(0)},r.prototype.match=function(r,t){var n;if(void 0===t&&(r=(n=r)[0],t=n[1]),"ipv4"!==r.kind())throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");return a(this.octets,r.octets,8,t)},r.prototype.SpecialRanges={unspecified:[[new r([0,0,0,0]),8]],broadcast:[[new r([255,255,255,255]),32]],multicast:[[new r([224,0,0,0]),4]],linkLocal:[[new r([169,254,0,0]),16]],loopback:[[new r([127,0,0,0]),8]],carrierGradeNat:[[new r([100,64,0,0]),10]],private:[[new r([10,0,0,0]),8],[new r([172,16,0,0]),12],[new r([192,168,0,0]),16]],reserved:[[new r([192,0,0,0]),24],[new r([192,0,2,0]),24],[new r([192,88,99,0]),24],[new r([198,51,100,0]),24],[new r([203,0,113,0]),24],[new r([240,0,0,0]),4]]},r.prototype.range=function(){return t.subnetMatch(this,this.SpecialRanges)},r.prototype.toIPv4MappedAddress=function(){return t.IPv6.parse("::ffff:"+this.toString())},r.prototype.prefixLengthFromSubnetMask=function(){var r,t,n,e,i,o,a;for(a={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},r=0,i=!1,t=n=3;n>=0;t=n+=-1){if(!((e=this.octets[t])in a))return null;if(o=a[e],i&&0!==o)return null;8!==o&&(i=!0),r+=o}return 32-r},r}(),n="(0?\\d+|0x[a-f0-9]+)",e={fourOctet:new RegExp("^"+n+"\\."+n+"\\."+n+"\\."+n+"$","i"),longValue:new RegExp("^"+n+"$","i")},t.IPv4.parser=function(r){var t,n,i,o,a;if(n=function(r){return"0"===r[0]&&"x"!==r[1]?parseInt(r,8):parseInt(r)},t=r.match(e.fourOctet))return function(){var r,e,o,a;for(a=[],r=0,e=(o=t.slice(1,6)).length;r<e;r++)i=o[r],a.push(n(i));return a}();if(t=r.match(e.longValue)){if((a=n(t[1]))>4294967295||a<0)throw new Error("ipaddr: address outside defined range");return function(){var r,t;for(t=[],o=r=0;r<=24;o=r+=8)t.push(a>>o&255);return t}().reverse()}return null},t.IPv6=function(){function r(r,t){var n,e,i,o,a,s;if(16===r.length)for(this.parts=[],n=e=0;e<=14;n=e+=2)this.parts.push(r[n]<<8|r[n+1]);else{if(8!==r.length)throw new Error("ipaddr: ipv6 part count should be 8 or 16");this.parts=r}for(i=0,o=(s=this.parts).length;i<o;i++)if(!(0<=(a=s[i])&&a<=65535))throw new Error("ipaddr: ipv6 part should fit in 16 bits");t&&(this.zoneId=t)}return r.prototype.kind=function(){return"ipv6"},r.prototype.toString=function(){return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/,"::")},r.prototype.toRFC5952String=function(){var r,t,n,e,i;for(e=/((^|:)(0(:|$)){2,})/g,i=this.toNormalizedString(),r=0,t=-1;n=e.exec(i);)n[0].length>t&&(r=n.index,t=n[0].length);return t<0?i:i.substring(0,r)+"::"+i.substring(r+t)},r.prototype.toByteArray=function(){var r,t,n,e,i;for(r=[],t=0,n=(i=this.parts).length;t<n;t++)e=i[t],r.push(e>>8),r.push(255&e);return r},r.prototype.toNormalizedString=function(){var r,t,n;return r=function(){var r,n,e,i;for(i=[],r=0,n=(e=this.parts).length;r<n;r++)t=e[r],i.push(t.toString(16));return i}.call(this).join(":"),n="",this.zoneId&&(n="%"+this.zoneId),r+n},r.prototype.toFixedLengthString=function(){var r,t,n;return r=function(){var r,n,e,i;for(i=[],r=0,n=(e=this.parts).length;r<n;r++)t=e[r],i.push(t.toString(16).padStart(4,"0"));return i}.call(this).join(":"),n="",this.zoneId&&(n="%"+this.zoneId),r+n},r.prototype.match=function(r,t){var n;if(void 0===t&&(r=(n=r)[0],t=n[1]),"ipv6"!==r.kind())throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");return a(this.parts,r.parts,16,t)},r.prototype.SpecialRanges={unspecified:[new r([0,0,0,0,0,0,0,0]),128],linkLocal:[new r([65152,0,0,0,0,0,0,0]),10],multicast:[new r([65280,0,0,0,0,0,0,0]),8],loopback:[new r([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new r([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new r([0,0,0,0,0,65535,0,0]),96],rfc6145:[new r([0,0,0,0,65535,0,0,0]),96],rfc6052:[new r([100,65435,0,0,0,0,0,0]),96],"6to4":[new r([8194,0,0,0,0,0,0,0]),16],teredo:[new r([8193,0,0,0,0,0,0,0]),32],reserved:[[new r([8193,3512,0,0,0,0,0,0]),32]]},r.prototype.range=function(){return t.subnetMatch(this,this.SpecialRanges)},r.prototype.isIPv4MappedAddress=function(){return"ipv4Mapped"===this.range()},r.prototype.toIPv4Address=function(){var r,n,e;if(!this.isIPv4MappedAddress())throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");return r=(e=this.parts.slice(-2))[0],n=e[1],new t.IPv4([r>>8,255&r,n>>8,255&n])},r.prototype.prefixLengthFromSubnetMask=function(){var r,t,n,e,i,o,a;for(a={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},r=0,i=!1,t=n=7;n>=0;t=n+=-1){if(!((e=this.parts[t])in a))return null;if(o=a[e],i&&0!==o)return null;16!==o&&(i=!0),r+=o}return 128-r},r}(),i="(?:[0-9a-f]+::?)+",s="%[0-9a-z]{1,}",o={zoneIndex:new RegExp(s,"i"),native:new RegExp("^(::)?("+i+")?([0-9a-f]+)?(::)?("+s+")?$","i"),transitional:new RegExp("^((?:"+i+")|(?:::)(?:"+i+")?)"+n+"\\."+n+"\\."+n+"\\."+n+"(%[0-9a-z]{1,})?$","i")},r=function(r,t){var n,e,i,a,s,p;if(r.indexOf("::")!==r.lastIndexOf("::"))return null;for((p=(r.match(o.zoneIndex)||[])[0])&&(p=p.substring(1),r=r.replace(/%.+$/,"")),n=0,e=-1;(e=r.indexOf(":",e+1))>=0;)n++;if("::"===r.substr(0,2)&&n--,"::"===r.substr(-2,2)&&n--,n>t)return null;for(s=t-n,a=":";s--;)a+="0:";return":"===(r=r.replace("::",a))[0]&&(r=r.slice(1)),":"===r[r.length-1]&&(r=r.slice(0,-1)),{parts:t=function(){var t,n,e,o;for(o=[],t=0,n=(e=r.split(":")).length;t<n;t++)i=e[t],o.push(parseInt(i,16));return o}(),zoneId:p}},t.IPv6.parser=function(t){var n,e,i,a,s,p,u;if(o.native.test(t))return r(t,8);if((a=t.match(o.transitional))&&(u=a[6]||"",(n=r(a[1].slice(0,-1)+u,6)).parts)){for(e=0,i=(p=[parseInt(a[2]),parseInt(a[3]),parseInt(a[4]),parseInt(a[5])]).length;e<i;e++)if(!(0<=(s=p[e])&&s<=255))return null;return n.parts.push(p[0]<<8|p[1]),n.parts.push(p[2]<<8|p[3]),{parts:n.parts,zoneId:n.zoneId}}return null},t.IPv4.isIPv4=t.IPv6.isIPv6=function(r){return null!==this.parser(r)},t.IPv4.isValid=function(r){try{return new this(this.parser(r)),!0}catch(r){return r,!1}},t.IPv4.isValidFourPartDecimal=function(r){return!(!t.IPv4.isValid(r)||!r.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},t.IPv6.isValid=function(r){var t;if("string"==typeof r&&-1===r.indexOf(":"))return!1;try{return new this((t=this.parser(r)).parts,t.zoneId),!0}catch(r){return r,!1}},t.IPv4.parse=function(r){var t;if(null===(t=this.parser(r)))throw new Error("ipaddr: string is not formatted like ip address");return new this(t)},t.IPv6.parse=function(r){var t;if(null===(t=this.parser(r)).parts)throw new Error("ipaddr: string is not formatted like ip address");return new this(t.parts,t.zoneId)},t.IPv4.parseCIDR=function(r){var t,n,e;if((n=r.match(/^(.+)\/(\d+)$/))&&(t=parseInt(n[2]))>=0&&t<=32)return e=[this.parse(n[1]),t],Object.defineProperty(e,"toString",{value:function(){return this.join("/")}}),e;throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range")},t.IPv4.subnetMaskFromPrefixLength=function(r){var t,n,e;if((r=parseInt(r))<0||r>32)throw new Error("ipaddr: invalid IPv4 prefix length");for(e=[0,0,0,0],n=0,t=Math.floor(r/8);n<t;)e[n]=255,n++;return t<4&&(e[t]=Math.pow(2,r%8)-1<<8-r%8),new this(e)},t.IPv4.broadcastAddressFromCIDR=function(r){var t,n,e,i,o;try{for(e=(t=this.parseCIDR(r))[0].toByteArray(),o=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],n=0;n<4;)i.push(parseInt(e[n],10)|255^parseInt(o[n],10)),n++;return new this(i)}catch(r){throw r,new Error("ipaddr: the address does not have IPv4 CIDR format")}},t.IPv4.networkAddressFromCIDR=function(r){var t,n,e,i,o;try{for(e=(t=this.parseCIDR(r))[0].toByteArray(),o=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],n=0;n<4;)i.push(parseInt(e[n],10)&parseInt(o[n],10)),n++;return new this(i)}catch(r){throw r,new Error("ipaddr: the address does not have IPv4 CIDR format")}},t.IPv6.parseCIDR=function(r){var t,n,e;if((n=r.match(/^(.+)\/(\d+)$/))&&(t=parseInt(n[2]))>=0&&t<=128)return e=[this.parse(n[1]),t],Object.defineProperty(e,"toString",{value:function(){return this.join("/")}}),e;throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range")},t.isValid=function(r){return t.IPv6.isValid(r)||t.IPv4.isValid(r)},t.parse=function(r){if(t.IPv6.isValid(r))return t.IPv6.parse(r);if(t.IPv4.isValid(r))return t.IPv4.parse(r);throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format")},t.parseCIDR=function(r){try{return t.IPv6.parseCIDR(r)}catch(n){n;try{return t.IPv4.parseCIDR(r)}catch(r){throw r,new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format")}}},t.fromByteArray=function(r){var n;if(4===(n=r.length))return new t.IPv4(r);if(16===n)return new t.IPv6(r);throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address")},t.process=function(r){var t;return"ipv6"===(t=this.parse(r)).kind()&&t.isIPv4MappedAddress()?t.toIPv4Address():t}}).call(this);
\ No newline at end of file
index d506327..4373268 100644 (file)
@@ -1,46 +1 @@
-'use strict';
-/* eslint-disable yoda */
-module.exports = x => {
-       if (Number.isNaN(x)) {
-               return false;
-       }
-
-       // code points are derived from:
-       // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt
-       if (
-               x >= 0x1100 && (
-                       x <= 0x115f ||  // Hangul Jamo
-                       x === 0x2329 || // LEFT-POINTING ANGLE BRACKET
-                       x === 0x232a || // RIGHT-POINTING ANGLE BRACKET
-                       // CJK Radicals Supplement .. Enclosed CJK Letters and Months
-                       (0x2e80 <= x && x <= 0x3247 && x !== 0x303f) ||
-                       // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
-                       (0x3250 <= x && x <= 0x4dbf) ||
-                       // CJK Unified Ideographs .. Yi Radicals
-                       (0x4e00 <= x && x <= 0xa4c6) ||
-                       // Hangul Jamo Extended-A
-                       (0xa960 <= x && x <= 0xa97c) ||
-                       // Hangul Syllables
-                       (0xac00 <= x && x <= 0xd7a3) ||
-                       // CJK Compatibility Ideographs
-                       (0xf900 <= x && x <= 0xfaff) ||
-                       // Vertical Forms
-                       (0xfe10 <= x && x <= 0xfe19) ||
-                       // CJK Compatibility Forms .. Small Form Variants
-                       (0xfe30 <= x && x <= 0xfe6b) ||
-                       // Halfwidth and Fullwidth Forms
-                       (0xff01 <= x && x <= 0xff60) ||
-                       (0xffe0 <= x && x <= 0xffe6) ||
-                       // Kana Supplement
-                       (0x1b000 <= x && x <= 0x1b001) ||
-                       // Enclosed Ideographic Supplement
-                       (0x1f200 <= x && x <= 0x1f251) ||
-                       // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
-                       (0x20000 <= x && x <= 0x3fffd)
-               )
-       ) {
-               return true;
-       }
-
-       return false;
-};
+"use strict";module.exports=e=>!Number.isNaN(e)&&(e>=4352&&(e<=4447||9001===e||9002===e||11904<=e&&e<=12871&&12351!==e||12880<=e&&e<=19903||19968<=e&&e<=42182||43360<=e&&e<=43388||44032<=e&&e<=55203||63744<=e&&e<=64255||65040<=e&&e<=65049||65072<=e&&e<=65131||65281<=e&&e<=65376||65504<=e&&e<=65510||110592<=e&&e<=110593||127488<=e&&e<=127569||131072<=e&&e<=262141));
\ No newline at end of file
index a57f634..7c21612 100644 (file)
@@ -1,5 +1 @@
-var toString = {}.toString;
-
-module.exports = Array.isArray || function (arr) {
-  return toString.call(arr) == '[object Array]';
-};
+var toString={}.toString;module.exports=Array.isArray||function(r){return"[object Array]"==toString.call(r)};
\ No newline at end of file
index 9f68abb..01b220a 100755 (executable)
@@ -1,31 +1,2 @@
 #!/usr/bin/env node
-/*
- * Jake JavaScript build tool
- * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-*/
-
-// Try to load a local jake
-try {
-  require(`${ process.cwd() }/node_modules/jake`);
-}
-// If that fails, likely running globally
-catch(e) {
-  require('../lib/jake');
-}
-
-var args = process.argv.slice(2);
-
-jake.run.apply(jake, args);
+try{require(`${process.cwd()}/node_modules/jake`)}catch(e){require("../lib/jake")}var args=process.argv.slice(2);jake.run.apply(jake,args);
\ No newline at end of file
index b0ae79b..c273fff 100755 (executable)
@@ -1,105 +1 @@
-let fs = require('fs')
-let path = require('path');
-let proc = require('child_process');
-
-const PROJECT_DIR = process.cwd();
-process.env.PROJECT_DIR = PROJECT_DIR;
-
-namespace('doc', function () {
-  task('generate', ['doc:clobber'], function () {
-    var cmd = '../node-jsdoc-toolkit/app/run.js -n -r=100 ' +
-        '-t=../node-jsdoc-toolkit/templates/codeview -d=./doc/ ./lib';
-    jake.logger.log('Generating docs ...');
-    jake.exec([cmd], function () {
-      jake.logger.log('Done.');
-      complete();
-    });
-  }, {async: true});
-
-  task('clobber', function () {
-    var cmd = 'rm -fr ./doc/*';
-    jake.exec([cmd], function () {
-      jake.logger.log('Clobbered old docs.');
-      complete();
-    });
-  }, {async: true});
-
-});
-
-desc('Generate docs for Jake');
-task('doc', ['doc:generate']);
-
-npmPublishTask('jake', function () {
-  this.packageFiles.include([
-    'Makefile',
-    'jakefile.js',
-    'README.md',
-    'package.json',
-    'usage.txt',
-    'lib/**',
-    'bin/**',
-    'test/**'
-    ]);
-  this.packageFiles.exclude([
-    'test/tmp'
-  ]);
-});
-
-jake.Task['publish:package'].directory = PROJECT_DIR;
-
-namespace('test', function () {
-
-  let integrationTest = task('integration', ['publish:package'], async function () {
-    let pkg = JSON.parse(fs.readFileSync(`${PROJECT_DIR}/package.json`).toString());
-    let version = pkg.version;
-
-    proc.execSync('rm -rf ./node_modules');
-    // Install from the actual package, run tests from the packaged binary
-    proc.execSync(`mkdir -p node_modules/.bin && mv ${PROJECT_DIR}/pkg/jake-v` +
-        `${version} node_modules/jake && ln -s ${process.cwd()}` +
-      '/node_modules/jake/bin/cli.js ./node_modules/.bin/jake');
-
-    let testArgs = [];
-    if (process.env.filter) {
-      testArgs.push(process.env.filter);
-    }
-    else {
-      testArgs.push('*.js');
-    }
-    let spawned = proc.spawn(`${PROJECT_DIR}/node_modules/.bin/mocha`, testArgs, {
-      stdio: 'inherit'
-    });
-    return new Promise((resolve, reject) => {
-      spawned.on('exit', () => {
-        if (!(process.env.noclobber || process.env.noClobber)) {
-          proc.execSync('rm -rf tmp_publish && rm -rf package.json' +
-              ' && rm -rf package-lock.json && rm -rf node_modules');
-          // Rather than invoking 'clobber' task
-          jake.rmRf(`${PROJECT_DIR}/pkg`);
-        }
-        resolve();
-      });
-    });
-
-  });
-
-  integrationTest.directory = `${PROJECT_DIR}/test/integration`;
-
-  let unitTest = task('unit', async function () {
-    let testArgs = [];
-    if (process.env.filter) {
-      testArgs.push(process.env.filter);
-    }
-    else {
-      testArgs.push('*.js');
-    }
-    let spawned = proc.spawn(`${PROJECT_DIR}/node_modules/.bin/mocha`, testArgs, {
-      stdio: 'inherit'
-    });
-  });
-
-  unitTest.directory = `${PROJECT_DIR}/test/unit`;
-});
-
-desc('Runs all tests');
-task('test', ['test:unit', 'test:integration']);
+let fs=require("fs"),path=require("path"),proc=require("child_process");const PROJECT_DIR=process.cwd();process.env.PROJECT_DIR=PROJECT_DIR,namespace("doc",(function(){task("generate",["doc:clobber"],(function(){jake.logger.log("Generating docs ..."),jake.exec(["../node-jsdoc-toolkit/app/run.js -n -r=100 -t=../node-jsdoc-toolkit/templates/codeview -d=./doc/ ./lib"],(function(){jake.logger.log("Done."),complete()}))}),{async:!0}),task("clobber",(function(){jake.exec(["rm -fr ./doc/*"],(function(){jake.logger.log("Clobbered old docs."),complete()}))}),{async:!0})})),desc("Generate docs for Jake"),task("doc",["doc:generate"]),npmPublishTask("jake",(function(){this.packageFiles.include(["Makefile","jakefile.js","README.md","package.json","usage.txt","lib/**","bin/**","test/**"]),this.packageFiles.exclude(["test/tmp"])})),jake.Task["publish:package"].directory=PROJECT_DIR,namespace("test",(function(){task("integration",["publish:package"],(async function(){let e=JSON.parse(fs.readFileSync(`${PROJECT_DIR}/package.json`).toString()).version;proc.execSync("rm -rf ./node_modules"),proc.execSync(`mkdir -p node_modules/.bin && mv ${PROJECT_DIR}/pkg/jake-v${e} node_modules/jake && ln -s ${process.cwd()}/node_modules/jake/bin/cli.js ./node_modules/.bin/jake`);let o=[];process.env.filter?o.push(process.env.filter):o.push("*.js");let s=proc.spawn(`${PROJECT_DIR}/node_modules/.bin/mocha`,o,{stdio:"inherit"});return new Promise(((e,o)=>{s.on("exit",(()=>{process.env.noclobber||process.env.noClobber||(proc.execSync("rm -rf tmp_publish && rm -rf package.json && rm -rf package-lock.json && rm -rf node_modules"),jake.rmRf(`${PROJECT_DIR}/pkg`)),e()}))}))})).directory=`${PROJECT_DIR}/test/integration`,task("unit",(async function(){let e=[];process.env.filter?e.push(process.env.filter):e.push("*.js");proc.spawn(`${PROJECT_DIR}/node_modules/.bin/mocha`,e,{stdio:"inherit"})})).directory=`${PROJECT_DIR}/test/unit`})),desc("Runs all tests"),task("test",["test:unit","test:integration"]);
\ No newline at end of file
index 9f09140..669f0a9 100755 (executable)
@@ -1,409 +1 @@
-/*
- * Jake JavaScript build tool
- * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-*/
-let { uuid } = require('./utils');
-
-let api = new (function () {
-  /**
-    @name task
-    @static
-    @function
-    @description Creates a Jake Task
-    `
-    @param {String} name The name of the Task
-    @param {Array} [prereqs] Prerequisites to be run before this task
-    @param {Function} [action] The action to perform for this task
-    @param {Object} [opts]
-      @param {Boolean} [opts.asyc=false] Perform this task asynchronously.
-      If you flag a task with this option, you must call the global
-      `complete` method inside the task's action, for execution to proceed
-      to the next task.
-
-    @example
-    desc('This is the default task.');
-    task('default', function (params) {
-      console.log('This is the default task.');
-    });
-
-    desc('This task has prerequisites.');
-    task('hasPrereqs', ['foo', 'bar', 'baz'], function (params) {
-      console.log('Ran some prereqs first.');
-    });
-
-    desc('This is an asynchronous task.');
-    task('asyncTask', function () {
-      setTimeout(complete, 1000);
-    }, {async: true});
-   */
-  this.task = function (name, prereqs, action, opts) {
-    let args = Array.prototype.slice.call(arguments);
-    let createdTask;
-    args.unshift('task');
-    createdTask = jake.createTask.apply(global, args);
-    jake.currentTaskDescription = null;
-    return createdTask;
-  };
-
-  /**
-    @name rule
-    @static
-    @function
-    @description Creates a Jake Suffix Rule
-    `
-    @param {String} pattern The suffix name of the objective
-    @param {String} source The suffix name of the objective
-    @param {Array} [prereqs] Prerequisites to be run before this task
-    @param {Function} [action] The action to perform for this task
-    @param {Object} [opts]
-      @param {Boolean} [opts.asyc=false] Perform this task asynchronously.
-      If you flag a task with this option, you must call the global
-      `complete` method inside the task's action, for execution to proceed
-      to the next task.
-    @example
-    desc('This is a rule, which does not support namespace or pattern.');
-    rule('.o', '.c', {async: true}, function () {
-      let cmd = util.format('gcc -o %s %s', this.name, this.source);
-      jake.exec([cmd], function () {
-        complete();
-      }, {printStdout: true});
-    });
-
-    desc('This rule has prerequisites.');
-    rule('.o', '.c', ['util.h'], {async: true}, function () {
-      let cmd = util.format('gcc -o %s %s', this.name, this.source);
-      jake.exec([cmd], function () {
-        complete();
-      }, {printStdout: true});
-    });
-
-    desc('This is a rule with patterns.');
-    rule('%.o', '%.c', {async: true}, function () {
-      let cmd = util.format('gcc -o %s %s', this.name, this.source);
-      jake.exec([cmd], function () {
-        complete();
-      }, {printStdout: true});
-    });
-
-    desc('This is another rule with patterns.');
-    rule('obj/%.o', 'src/%.c', {async: true}, function () {
-      let cmd = util.format('gcc -o %s %s', this.name, this.source);
-      jake.exec([cmd], function () {
-        complete();
-      }, {printStdout: true});
-    });
-
-    desc('This is an example with chain rules.');
-    rule('%.pdf', '%.dvi', {async: true}, function () {
-      let cmd = util.format('dvipdfm %s',this.source);
-      jake.exec([cmd], function () {
-        complete();
-      }, {printStdout: true});
-    });
-
-    rule('%.dvi', '%.tex', {async: true}, function () {
-      let cmd = util.format('latex %s',this.source);
-      jake.exec([cmd], function () {
-        complete();
-      }, {printStdout: true});
-    });
-
-    desc('This rule has a namespace.');
-    task('default', ['debug:obj/main.o]);
-
-    namespace('debug', {async: true}, function() {
-      rule('obj/%.o', 'src/%.c', function () {
-        // ...
-      });
-    }
-   */
-  this.rule = function () {
-    let args = Array.prototype.slice.call(arguments);
-    let arg;
-    let pattern = args.shift();
-    let source = args.shift();
-    let prereqs = [];
-    let action = function () {};
-    let opts = {};
-    let key = pattern.toString(); // May be a RegExp
-
-    while ((arg = args.shift())) {
-      if (typeof arg == 'function') {
-        action = arg;
-      }
-      else if (Array.isArray(arg)) {
-        prereqs = arg;
-      }
-      else {
-        opts = arg;
-      }
-    }
-
-    jake.currentNamespace.rules[key] = new jake.Rule({
-      pattern: pattern,
-      source: source,
-      prereqs: prereqs,
-      action: action,
-      opts: opts,
-      desc: jake.currentTaskDescription,
-      ns: jake.currentNamespace
-    });
-    jake.currentTaskDescription = null;
-  };
-
-  /**
-    @name directory
-    @static
-    @function
-    @description Creates a Jake DirectoryTask. Can be used as a prerequisite
-    for FileTasks, or for simply ensuring a directory exists for use with a
-    Task's action.
-    `
-    @param {String} name The name of the DiretoryTask
-
-    @example
-
-    // Creates the package directory for distribution
-    directory('pkg');
-   */
-  this.directory = function (name) {
-    let args = Array.prototype.slice.call(arguments);
-    let createdTask;
-    args.unshift('directory');
-    createdTask = jake.createTask.apply(global, args);
-    jake.currentTaskDescription = null;
-    return createdTask;
-  };
-
-  /**
-    @name file
-    @static
-    @function
-    @description Creates a Jake FileTask.
-    `
-    @param {String} name The name of the FileTask
-    @param {Array} [prereqs] Prerequisites to be run before this task
-    @param {Function} [action] The action to create this file, if it doesn't
-    exist already.
-    @param {Object} [opts]
-      @param {Array} [opts.asyc=false] Perform this task asynchronously.
-      If you flag a task with this option, you must call the global
-      `complete` method inside the task's action, for execution to proceed
-      to the next task.
-
-   */
-  this.file = function (name, prereqs, action, opts) {
-    let args = Array.prototype.slice.call(arguments);
-    let createdTask;
-    args.unshift('file');
-    createdTask = jake.createTask.apply(global, args);
-    jake.currentTaskDescription = null;
-    return createdTask;
-  };
-
-  /**
-    @name desc
-    @static
-    @function
-    @description Creates a description for a Jake Task (or FileTask,
-    DirectoryTask). When invoked, the description that iscreated will
-    be associated with whatever Task is created next.
-    `
-    @param {String} description The description for the Task
-   */
-  this.desc = function (description) {
-    jake.currentTaskDescription = description;
-  };
-
-  /**
-    @name namespace
-    @static
-    @function
-    @description Creates a namespace which allows logical grouping
-    of tasks, and prevents name-collisions with task-names. Namespaces
-    can be nested inside of other namespaces.
-    `
-    @param {String} name The name of the namespace
-    @param {Function} scope The enclosing scope for the namespaced tasks
-
-    @example
-    namespace('doc', function () {
-      task('generate', ['doc:clobber'], function () {
-        // Generate some docs
-      });
-
-      task('clobber', function () {
-        // Clobber the doc directory first
-      });
-    });
-   */
-  this.namespace = function (name, closure) {
-    let curr = jake.currentNamespace;
-    let ns = curr.childNamespaces[name] || new jake.Namespace(name, curr);
-    let fn = closure || function () {};
-    curr.childNamespaces[name] = ns;
-    jake.currentNamespace = ns;
-    fn();
-    jake.currentNamespace = curr;
-    jake.currentTaskDescription = null;
-    return ns;
-  };
-
-  /**
-    @name complete
-    @static
-    @function
-    @description Completes an asynchronous task, allowing Jake's
-    execution to proceed to the next task. Calling complete globally or without
-    arguments completes the last task on the invocationChain. If you use parallel
-    execution of prereqs this will probably complete a wrong task. You should call this
-    function with this task as the first argument, before the optional return value.
-    Alternatively you can call task.complete()
-    `
-    @example
-    task('generate', ['doc:clobber'], function () {
-      exec('./generate_docs.sh', function (err, stdout, stderr) {
-        if (err || stderr) {
-          fail(err || stderr);
-        }
-        else {
-          console.log(stdout);
-          complete();
-        }
-      });
-    }, {async: true});
-   */
-  this.complete = function (task, val) {
-    //this should detect if the first arg is a task, but I guess it should be more thorough
-    if(task && task. _currentPrereqIndex >=0 ) {
-      task.complete(val);
-    }
-    else {
-      val = task;
-      if(jake._invocationChain.length > 0) {
-        jake._invocationChain[jake._invocationChain.length-1].complete(val);
-      }
-    }
-  };
-
-  /**
-    @name fail
-    @static
-    @function
-    @description Causes Jake execution to abort with an error.
-    Allows passing an optional error code, which will be used to
-    set the exit-code of exiting process.
-    `
-    @param {Error|String} err The error to thow when aborting execution.
-    If this argument is an Error object, it will simply be thrown. If
-    a String, it will be used as the error-message. (If it is a multi-line
-    String, the first line will be used as the Error message, and the
-    remaining lines will be used as the error-stack.)
-
-    @example
-    task('createTests, function () {
-      if (!fs.existsSync('./tests')) {
-        fail('Test directory does not exist.');
-      }
-      else {
-        // Do some testing stuff ...
-      }
-    });
-   */
-  this.fail = function (err, code) {
-    let msg;
-    let errObj;
-    if (code) {
-      jake.errorCode = code;
-    }
-    if (err) {
-      if (typeof err == 'string') {
-        // Use the initial or only line of the error as the error-message
-        // If there was a multi-line error, use the rest as the stack
-        msg = err.split('\n');
-        errObj = new Error(msg.shift());
-        if (msg.length) {
-          errObj.stack = msg.join('\n');
-        }
-        throw errObj;
-      }
-      else if (err instanceof Error) {
-        throw err;
-      }
-      else {
-        throw new Error(err.toString());
-      }
-    }
-    else {
-      throw new Error();
-    }
-  };
-
-  this.packageTask = function (name, version, prereqs, definition) {
-    return new jake.PackageTask(name, version, prereqs, definition);
-  };
-
-  this.publishTask = function (name, prereqs, opts, definition) {
-    return new jake.PublishTask(name, prereqs, opts, definition);
-  };
-
-  // Backward-compat
-  this.npmPublishTask = function (name, prereqs, opts, definition) {
-    return new jake.PublishTask(name, prereqs, opts, definition);
-  };
-
-  this.testTask = function () {
-    let ctor = function () {};
-    let t;
-    ctor.prototype = jake.TestTask.prototype;
-    t = new ctor();
-    jake.TestTask.apply(t, arguments);
-    return t;
-  };
-
-  this.setTaskTimeout = function (t) {
-    this._taskTimeout = t;
-  };
-
-  this.setSeriesAutoPrefix = function (prefix) {
-    this._seriesAutoPrefix = prefix;
-  };
-
-  this.series = function (...args) {
-    let prereqs = args.map((arg) => {
-      let name = (this._seriesAutoPrefix || '') + arg.name;
-      jake.task(name, arg);
-      return name;
-    });
-    let seriesName = uuid();
-    let seriesTask = jake.task(seriesName, prereqs);
-    seriesTask._internal = true;
-    let res = function () {
-      return new Promise((resolve) => {
-        seriesTask.invoke();
-        seriesTask.on('complete', (val) => {
-          resolve(val);
-        });
-      });
-    };
-    Object.defineProperty(res, 'name', {value: uuid(),
-      writable: false});
-    return res;
-  };
-
-})();
-
-module.exports = api;
+let{uuid:uuid}=require("./utils"),api=new function(){this.task=function(e,t,n,r){let a,i=Array.prototype.slice.call(arguments);return i.unshift("task"),a=jake.createTask.apply(global,i),jake.currentTaskDescription=null,a},this.rule=function(){let e,t=Array.prototype.slice.call(arguments),n=t.shift(),r=t.shift(),a=[],i=function(){},s={},o=n.toString();for(;e=t.shift();)"function"==typeof e?i=e:Array.isArray(e)?a=e:s=e;jake.currentNamespace.rules[o]=new jake.Rule({pattern:n,source:r,prereqs:a,action:i,opts:s,desc:jake.currentTaskDescription,ns:jake.currentNamespace}),jake.currentTaskDescription=null},this.directory=function(e){let t,n=Array.prototype.slice.call(arguments);return n.unshift("directory"),t=jake.createTask.apply(global,n),jake.currentTaskDescription=null,t},this.file=function(e,t,n,r){let a,i=Array.prototype.slice.call(arguments);return i.unshift("file"),a=jake.createTask.apply(global,i),jake.currentTaskDescription=null,a},this.desc=function(e){jake.currentTaskDescription=e},this.namespace=function(e,t){let n=jake.currentNamespace,r=n.childNamespaces[e]||new jake.Namespace(e,n),a=t||function(){};return n.childNamespaces[e]=r,jake.currentNamespace=r,a(),jake.currentNamespace=n,jake.currentTaskDescription=null,r},this.complete=function(e,t){e&&e._currentPrereqIndex>=0?e.complete(t):(t=e,jake._invocationChain.length>0&&jake._invocationChain[jake._invocationChain.length-1].complete(t))},this.fail=function(e,t){let n,r;throw t&&(jake.errorCode=t),e?"string"==typeof e?(n=e.split("\n"),r=new Error(n.shift()),n.length&&(r.stack=n.join("\n")),r):e instanceof Error?e:new Error(e.toString()):new Error},this.packageTask=function(e,t,n,r){return new jake.PackageTask(e,t,n,r)},this.publishTask=function(e,t,n,r){return new jake.PublishTask(e,t,n,r)},this.npmPublishTask=function(e,t,n,r){return new jake.PublishTask(e,t,n,r)},this.testTask=function(){let e,t=function(){};return t.prototype=jake.TestTask.prototype,e=new t,jake.TestTask.apply(e,arguments),e},this.setTaskTimeout=function(e){this._taskTimeout=e},this.setSeriesAutoPrefix=function(e){this._seriesAutoPrefix=e},this.series=function(...e){let t=e.map((e=>{let t=(this._seriesAutoPrefix||"")+e.name;return jake.task(t,e),t})),n=uuid(),r=jake.task(n,t);r._internal=!0;let a=function(){return new Promise((e=>{r.invoke(),r.on("complete",(t=>{e(t)}))}))};return Object.defineProperty(a,"name",{value:uuid(),writable:!1}),a}};module.exports=api;
\ No newline at end of file
index a463163..f729381 100755 (executable)
@@ -1,319 +1 @@
-/*
- * Jake JavaScript build tool
- * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-*/
-
-if (!global.jake) {
-
-  let EventEmitter = require('events').EventEmitter;
-  // And so it begins
-  global.jake = new EventEmitter();
-
-  let fs = require('fs');
-  let chalk = require('chalk');
-  let taskNs = require('./task');
-  let Task = taskNs.Task;
-  let FileTask = taskNs.FileTask;
-  let DirectoryTask = taskNs.DirectoryTask;
-  let Rule = require('./rule').Rule;
-  let Namespace = require('./namespace').Namespace;
-  let RootNamespace = require('./namespace').RootNamespace;
-  let api = require('./api');
-  let utils = require('./utils');
-  let Program = require('./program').Program;
-  let loader = require('./loader')();
-  let pkg = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString());
-
-  const MAX_RULE_RECURSION_LEVEL = 16;
-
-  // Globalize jake and top-level API methods (e.g., `task`, `desc`)
-  Object.assign(global, api);
-
-  // Copy utils onto base jake
-  jake.logger = utils.logger;
-  jake.exec = utils.exec;
-
-  // File utils should be aliased directly on base jake as well
-  Object.assign(jake, utils.file);
-
-  // Also add top-level API methods to exported object for those who don't want to
-  // use the globals (`file` here will overwrite the 'file' utils namespace)
-  Object.assign(jake, api);
-
-  Object.assign(jake, new (function () {
-
-    this._invocationChain = [];
-    this._taskTimeout = 30000;
-
-    // Public properties
-    // =================
-    this.version = pkg.version;
-    // Used when Jake exits with a specific error-code
-    this.errorCode = null;
-    // Loads Jakefiles/jakelibdirs
-    this.loader = loader;
-    // The root of all ... namespaces
-    this.rootNamespace = new RootNamespace();
-    // Non-namespaced tasks are placed into the default
-    this.defaultNamespace = this.rootNamespace;
-    // Start in the default
-    this.currentNamespace = this.defaultNamespace;
-    // Saves the description created by a 'desc' call that prefaces a
-    // 'task' call that defines a task.
-    this.currentTaskDescription = null;
-    this.program = new Program();
-    this.FileList = require('filelist').FileList;
-    this.PackageTask = require('./package_task').PackageTask;
-    this.PublishTask = require('./publish_task').PublishTask;
-    this.TestTask = require('./test_task').TestTask;
-    this.Task = Task;
-    this.FileTask = FileTask;
-    this.DirectoryTask = DirectoryTask;
-    this.Namespace = Namespace;
-    this.Rule = Rule;
-
-    this.parseAllTasks = function () {
-      let _parseNs = function (ns) {
-        let nsTasks = ns.tasks;
-        let nsNamespaces = ns.childNamespaces;
-        for (let q in nsTasks) {
-          let nsTask = nsTasks[q];
-          jake.Task[nsTask.fullName] = nsTask;
-        }
-        for (let p in nsNamespaces) {
-          let nsNamespace = nsNamespaces[p];
-          _parseNs(nsNamespace);
-        }
-      };
-      _parseNs(jake.defaultNamespace);
-    };
-
-    /**
-     * Displays the list of descriptions avaliable for tasks defined in
-     * a Jakefile
-     */
-    this.showAllTaskDescriptions = function (f) {
-      let p;
-      let maxTaskNameLength = 0;
-      let task;
-      let padding;
-      let name;
-      let descr;
-      let filter = typeof f == 'string' ? f : null;
-
-      for (p in jake.Task) {
-        if (!Object.prototype.hasOwnProperty.call(jake.Task, p)) {
-          continue;
-        }
-        if (filter && p.indexOf(filter) == -1) {
-          continue;
-        }
-        task = jake.Task[p];
-        // Record the length of the longest task name -- used for
-        // pretty alignment of the task descriptions
-        if (task.description) {
-          maxTaskNameLength = p.length > maxTaskNameLength ?
-            p.length : maxTaskNameLength;
-        }
-      }
-      // Print out each entry with descriptions neatly aligned
-      for (p in jake.Task) {
-        if (!Object.prototype.hasOwnProperty.call(jake.Task, p)) {
-          continue;
-        }
-        if (filter && p.indexOf(filter) == -1) {
-          continue;
-        }
-        task = jake.Task[p];
-
-        //name = '\033[32m' + p + '\033[39m ';
-        name = chalk.green(p);
-
-        descr = task.description;
-        if (descr) {
-          descr = chalk.gray('# ' + descr);
-
-          // Create padding-string with calculated length
-          padding = (new Array(maxTaskNameLength - p.length + 2)).join(' ');
-
-          console.log('jake ' + name + padding + descr);
-        }
-      }
-    };
-
-    this.createTask = function () {
-      let args = Array.prototype.slice.call(arguments);
-      let arg;
-      let obj;
-      let task;
-      let type;
-      let name;
-      let action;
-      let opts = {};
-      let prereqs = [];
-
-      type = args.shift();
-
-      // name, [deps], [action]
-      // Name (string) + deps (array) format
-      if (typeof args[0] == 'string') {
-        name = args.shift();
-        if (Array.isArray(args[0])) {
-          prereqs = args.shift();
-        }
-      }
-      // name:deps, [action]
-      // Legacy object-literal syntax, e.g.: {'name': ['depA', 'depB']}
-      else {
-        obj = args.shift();
-        for (let p in obj) {
-          prereqs = prereqs.concat(obj[p]);
-          name = p;
-        }
-      }
-
-      // Optional opts/callback or callback/opts
-      while ((arg = args.shift())) {
-        if (typeof arg == 'function') {
-          action = arg;
-        }
-        else {
-          opts = Object.assign(Object.create(null), arg);
-        }
-      }
-
-      task = jake.currentNamespace.resolveTask(name);
-      if (task && !action) {
-        // Task already exists and no action, just update prereqs, and return it.
-        task.prereqs = task.prereqs.concat(prereqs);
-        return task;
-      }
-
-      switch (type) {
-      case 'directory':
-        action = function () {
-          jake.mkdirP(name);
-        };
-        task = new DirectoryTask(name, prereqs, action, opts);
-        break;
-      case 'file':
-        task = new FileTask(name, prereqs, action, opts);
-        break;
-      default:
-        task = new Task(name, prereqs, action, opts);
-      }
-
-      jake.currentNamespace.addTask(task);
-
-      if (jake.currentTaskDescription) {
-        task.description = jake.currentTaskDescription;
-        jake.currentTaskDescription = null;
-      }
-
-      // FIXME: Should only need to add a new entry for the current
-      // task-definition, not reparse the entire structure
-      jake.parseAllTasks();
-
-      return task;
-    };
-
-    this.attemptRule = function (name, ns, level) {
-      let prereqRule;
-      let prereq;
-      if (level > MAX_RULE_RECURSION_LEVEL) {
-        return null;
-      }
-      // Check Rule
-      prereqRule = ns.matchRule(name);
-      if (prereqRule) {
-        prereq = prereqRule.createTask(name, level);
-      }
-      return prereq || null;
-    };
-
-    this.createPlaceholderFileTask = function (name, namespace) {
-      let parsed = name.split(':');
-      let filePath = parsed.pop(); // Strip any namespace
-      let task;
-
-      task = namespace.resolveTask(name);
-
-      // If there's not already an existing dummy FileTask for it,
-      // create one
-      if (!task) {
-        // Create a dummy FileTask only if file actually exists
-        if (fs.existsSync(filePath)) {
-          task = new jake.FileTask(filePath);
-          task.dummy = true;
-          let ns;
-          if (parsed.length) {
-            ns = namespace.resolveNamespace(parsed.join(':'));
-          }
-          else {
-            ns = namespace;
-          }
-          if (!namespace) {
-            throw new Error('Invalid namespace, cannot add FileTask');
-          }
-          ns.addTask(task);
-          // Put this dummy Task in the global Tasks list so
-          // modTime will be eval'd correctly
-          jake.Task[`${ns.path}:${filePath}`] = task;
-        }
-      }
-
-      return task || null;
-    };
-
-
-    this.run = function () {
-      let args = Array.prototype.slice.call(arguments);
-      let program = this.program;
-      let loader = this.loader;
-      let preempt;
-      let opts;
-
-      program.parseArgs(args);
-      program.init();
-
-      preempt = program.firstPreemptiveOption();
-      if (preempt) {
-        preempt();
-      }
-      else {
-        opts = program.opts;
-        // jakefile flag set but no jakefile yet
-        if (opts.autocomplete && opts.jakefile === true) {
-          process.stdout.write('no-complete');
-          return;
-        }
-        // Load Jakefile and jakelibdir files
-        let jakefileLoaded = loader.loadFile(opts.jakefile);
-        let jakelibdirLoaded = loader.loadDirectory(opts.jakelibdir);
-
-        if(!jakefileLoaded && !jakelibdirLoaded && !opts.autocomplete) {
-          fail('No Jakefile. Specify a valid path with -f/--jakefile, ' +
-              'or place one in the current directory.');
-        }
-
-        program.run();
-      }
-    };
-
-  })());
-}
-
-module.exports = jake;
+if(!global.jake){let e=require("events").EventEmitter;global.jake=new e;let a=require("fs"),t=require("chalk"),s=require("./task"),r=s.Task,i=s.FileTask,l=s.DirectoryTask,n=require("./rule").Rule,o=require("./namespace").Namespace,c=require("./namespace").RootNamespace,k=require("./api"),u=require("./utils"),p=require("./program").Program,h=require("./loader")(),f=JSON.parse(a.readFileSync(__dirname+"/../package.json").toString());const j=16;Object.assign(global,k),jake.logger=u.logger,jake.exec=u.exec,Object.assign(jake,u.file),Object.assign(jake,k),Object.assign(jake,new function(){this._invocationChain=[],this._taskTimeout=3e4,this.version=f.version,this.errorCode=null,this.loader=h,this.rootNamespace=new c,this.defaultNamespace=this.rootNamespace,this.currentNamespace=this.defaultNamespace,this.currentTaskDescription=null,this.program=new p,this.FileList=require("filelist").FileList,this.PackageTask=require("./package_task").PackageTask,this.PublishTask=require("./publish_task").PublishTask,this.TestTask=require("./test_task").TestTask,this.Task=r,this.FileTask=i,this.DirectoryTask=l,this.Namespace=o,this.Rule=n,this.parseAllTasks=function(){let e=function(a){let t=a.tasks,s=a.childNamespaces;for(let e in t){let a=t[e];jake.Task[a.fullName]=a}for(let a in s){let t=s[a];e(t)}};e(jake.defaultNamespace)},this.showAllTaskDescriptions=function(e){let a,s,r,i,l,n=0,o="string"==typeof e?e:null;for(a in jake.Task)Object.prototype.hasOwnProperty.call(jake.Task,a)&&(o&&-1==a.indexOf(o)||(s=jake.Task[a],s.description&&(n=a.length>n?a.length:n)));for(a in jake.Task)Object.prototype.hasOwnProperty.call(jake.Task,a)&&(o&&-1==a.indexOf(o)||(s=jake.Task[a],i=t.green(a),l=s.description,l&&(l=t.gray("# "+l),r=new Array(n-a.length+2).join(" "),console.log("jake "+i+r+l))))},this.createTask=function(){let e,a,t,s,n,o,c=Array.prototype.slice.call(arguments),k={},u=[];if(s=c.shift(),"string"==typeof c[0])n=c.shift(),Array.isArray(c[0])&&(u=c.shift());else{a=c.shift();for(let e in a)u=u.concat(a[e]),n=e}for(;e=c.shift();)"function"==typeof e?o=e:k=Object.assign(Object.create(null),e);if(t=jake.currentNamespace.resolveTask(n),t&&!o)return t.prereqs=t.prereqs.concat(u),t;switch(s){case"directory":o=function(){jake.mkdirP(n)},t=new l(n,u,o,k);break;case"file":t=new i(n,u,o,k);break;default:t=new r(n,u,o,k)}return jake.currentNamespace.addTask(t),jake.currentTaskDescription&&(t.description=jake.currentTaskDescription,jake.currentTaskDescription=null),jake.parseAllTasks(),t},this.attemptRule=function(e,a,t){let s,r;return t>j?null:(s=a.matchRule(e),s&&(r=s.createTask(e,t)),r||null)},this.createPlaceholderFileTask=function(e,t){let s,r=e.split(":"),i=r.pop();if(s=t.resolveTask(e),!s&&a.existsSync(i)){let e;if(s=new jake.FileTask(i),s.dummy=!0,e=r.length?t.resolveNamespace(r.join(":")):t,!t)throw new Error("Invalid namespace, cannot add FileTask");e.addTask(s),jake.Task[`${e.path}:${i}`]=s}return s||null},this.run=function(){let e,a,t=Array.prototype.slice.call(arguments),s=this.program,r=this.loader;if(s.parseArgs(t),s.init(),e=s.firstPreemptiveOption(),e)e();else{if(a=s.opts,a.autocomplete&&!0===a.jakefile)return void process.stdout.write("no-complete");let e=r.loadFile(a.jakefile),t=r.loadDirectory(a.jakelibdir);e||t||a.autocomplete||fail("No Jakefile. Specify a valid path with -f/--jakefile, or place one in the current directory."),s.run()}}})}module.exports=jake;
\ No newline at end of file
index 02ad262..d4f18fe 100755 (executable)
@@ -1,165 +1 @@
-/*
- * Jake JavaScript build tool
- * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-*/
-
-let path = require('path');
-let fs = require('fs');
-let existsSync = fs.existsSync;
-let utils = require('./utils');
-
-// Files like jakelib/foobar.jake.js
-const JAKELIB_FILE_PAT = /\.jake$|\.js$/;
-const SUPPORTED_EXTENSIONS = {
-  'js': null,
-  'coffee': function () {
-    try {
-      let cs = require('coffeescript');
-      if (typeof cs.register == 'function') {
-        cs.register();
-      }
-    }
-    catch(e) {
-      throw new Error('You have a CoffeeScript Jakefile, but have not installed CoffeeScript');
-    }
-  },
-  'ls': function () {
-    try {
-      require('livescript');
-    }
-    catch (e) {
-      throw new Error('You have a LiveScript Jakefile, but have not installed LiveScript');
-    }
-  }
-};
-const IMPLICIT_JAKEFILE_NAMES = [
-  'Jakefile',
-  'Gulpfile'
-];
-
-let Loader = function () {
-  // Load a Jakefile, running the code inside -- this may result in
-  // tasks getting defined using the original Jake API, e.g.,
-  // `task('foo' ['bar', 'baz']);`, or can also auto-create tasks
-  // from any functions exported from the file
-  function loadFile(filePath) {
-    let exported = require(filePath);
-    for (let [key, value] of Object.entries(exported)) {
-      let t;
-      if (typeof value == 'function') {
-        t = jake.task(key, value);
-        t.description = '(Exported function)';
-      }
-    }
-  }
-
-  function fileExists(name) {
-    let nameWithExt = null;
-    // Support no file extension as well
-    let exts = Object.keys(SUPPORTED_EXTENSIONS).concat(['']);
-    exts.some((ext) => {
-      let fname = ext ? `${name}.${ext}` : name;
-      if (existsSync(fname)) {
-        nameWithExt = fname;
-        return true;
-      }
-    });
-    return nameWithExt;
-  }
-
-  // Recursive
-  function findImplicitJakefile() {
-    let cwd = process.cwd();
-    let names = IMPLICIT_JAKEFILE_NAMES;
-    let found = null;
-    names.some((name) => {
-      let n;
-      // Prefer all-lowercase
-      n = name.toLowerCase();
-      if ((found = fileExists(n))) {
-        return found;
-      }
-      // Check mixed-case as well
-      n = name;
-      if ((found = fileExists(n))) {
-        return found;
-      }
-    });
-    if (found) {
-      return found;
-    }
-    else {
-      process.chdir("..");
-      // If we've walked all the way up the directory tree,
-      // bail out with no result
-      if (cwd === process.cwd()) {
-        return null;
-      }
-      return findImplicitJakefile();
-    }
-  }
-
-  this.loadFile = function (fileSpecified) {
-    let jakefile;
-    let origCwd = process.cwd();
-
-    if (fileSpecified) {
-      if (existsSync(fileSpecified)) {
-        jakefile = fileSpecified;
-      }
-    }
-    else {
-      jakefile = findImplicitJakefile();
-    }
-
-    if (jakefile) {
-      let ext = jakefile.split('.')[1];
-      let loaderFunc = SUPPORTED_EXTENSIONS[ext];
-      loaderFunc && loaderFunc();
-
-      loadFile(utils.file.absolutize(jakefile));
-      return true;
-    }
-    else {
-      if (!fileSpecified) {
-        // Restore the working directory on failure
-        process.chdir(origCwd);
-      }
-      return false;
-    }
-  };
-
-  this.loadDirectory = function (d) {
-    let dirname = d || 'jakelib';
-    let dirlist;
-    dirname = utils.file.absolutize(dirname);
-    if (existsSync(dirname)) {
-      dirlist = fs.readdirSync(dirname);
-      dirlist.forEach(function (filePath) {
-        if (JAKELIB_FILE_PAT.test(filePath)) {
-          loadFile(path.join(dirname, filePath));
-        }
-      });
-      return true;
-    }
-    return false;
-  };
-
-};
-
-module.exports = function () {
-  return new Loader();
-};
+let path=require("path"),fs=require("fs"),existsSync=fs.existsSync,utils=require("./utils");const JAKELIB_FILE_PAT=/\.jake$|\.js$/,SUPPORTED_EXTENSIONS={js:null,coffee:function(){try{let e=require("coffeescript");"function"==typeof e.register&&e.register()}catch(e){throw new Error("You have a CoffeeScript Jakefile, but have not installed CoffeeScript")}},ls:function(){try{require("livescript")}catch(e){throw new Error("You have a LiveScript Jakefile, but have not installed LiveScript")}}},IMPLICIT_JAKEFILE_NAMES=["Jakefile","Gulpfile"];let Loader=function(){function e(e){let t=require(e);for(let[e,r]of Object.entries(t)){let t;"function"==typeof r&&(t=jake.task(e,r),t.description="(Exported function)")}}function t(e){let t=null;return Object.keys(SUPPORTED_EXTENSIONS).concat([""]).some((r=>{let i=r?`${e}.${r}`:e;if(existsSync(i))return t=i,!0})),t}function r(){let e=process.cwd(),i=null;return IMPLICIT_JAKEFILE_NAMES.some((e=>{let r;return r=e.toLowerCase(),(i=t(r))?i:(r=e,(i=t(r))?i:void 0)})),i||(process.chdir(".."),e===process.cwd()?null:r())}this.loadFile=function(t){let i,n=process.cwd();if(t?existsSync(t)&&(i=t):i=r(),i){let t=i.split(".")[1],r=SUPPORTED_EXTENSIONS[t];return r&&r(),e(utils.file.absolutize(i)),!0}return t||process.chdir(n),!1},this.loadDirectory=function(t){let r,i=t||"jakelib";return i=utils.file.absolutize(i),!!existsSync(i)&&(r=fs.readdirSync(i),r.forEach((function(t){JAKELIB_FILE_PAT.test(t)&&e(path.join(i,t))})),!0)}};module.exports=function(){return new Loader};
\ No newline at end of file
index a3c2787..934ef65 100755 (executable)
@@ -1,115 +1 @@
-const ROOT_NAMESPACE_NAME = '__rootNamespace__';
-
-class Namespace {
-  constructor(name, parentNamespace) {
-    this.name = name;
-    this.parentNamespace = parentNamespace;
-    this.childNamespaces = {};
-    this.tasks = {};
-    this.rules = {};
-    this.path = this.getPath();
-  }
-
-  get fullName() {
-    return this._getFullName();
-  }
-
-  addTask(task) {
-    this.tasks[task.name] = task;
-    task.namespace = this;
-  }
-
-  resolveTask(name) {
-    if (!name) {
-      return;
-    }
-
-    let taskPath = name.split(':');
-    let taskName = taskPath.pop();
-    let task;
-    let ns;
-
-    // Namespaced, return either relative to current, or from root
-    if (taskPath.length) {
-      taskPath = taskPath.join(':');
-      ns = this.resolveNamespace(taskPath) ||
-        Namespace.ROOT_NAMESPACE.resolveNamespace(taskPath);
-      task = (ns && ns.resolveTask(taskName));
-    }
-    // Bare task, return either local, or top-level
-    else {
-      task = this.tasks[name] || Namespace.ROOT_NAMESPACE.tasks[name];
-    }
-
-    return task || null;
-  }
-
-
-  resolveNamespace(relativeName) {
-    if (!relativeName) {
-      return this;
-    }
-
-    let parts = relativeName.split(':');
-    let ns = this;
-
-    for (let i = 0, ii = parts.length; (ns && i < ii); i++) {
-      ns = ns.childNamespaces[parts[i]];
-    }
-
-    return ns || null;
-  }
-
-  matchRule(relativeName) {
-    let parts = relativeName.split(':');
-    parts.pop();
-    let ns = this.resolveNamespace(parts.join(':'));
-    let rules = ns ? ns.rules : [];
-    let r;
-    let match;
-
-    for (let p in rules) {
-      r = rules[p];
-      if (r.match(relativeName)) {
-        match = r;
-      }
-    }
-
-    return (ns && match) ||
-        (this.parentNamespace &&
-        this.parentNamespace.matchRule(relativeName));
-  }
-
-  getPath() {
-    let parts = [];
-    let next = this.parentNamespace;
-    while (next) {
-      parts.push(next.name);
-      next = next.parentNamespace;
-    }
-    parts.pop(); // Remove '__rootNamespace__'
-    return parts.reverse().join(':');
-  }
-
-  _getFullName() {
-    let path = this.path;
-    path = (path && path.split(':')) || [];
-    path.push(this.name);
-    return path.join(':');
-  }
-
-  isRootNamespace() {
-    return !this.parentNamespace;
-  }
-}
-
-class RootNamespace extends Namespace {
-  constructor() {
-    super(ROOT_NAMESPACE_NAME, null);
-    Namespace.ROOT_NAMESPACE = this;
-  }
-}
-
-module.exports.Namespace = Namespace;
-module.exports.RootNamespace = RootNamespace;
-
+const ROOT_NAMESPACE_NAME="__rootNamespace__";class Namespace{constructor(e,s){this.name=e,this.parentNamespace=s,this.childNamespaces={},this.tasks={},this.rules={},this.path=this.getPath()}get fullName(){return this._getFullName()}addTask(e){this.tasks[e.name]=e,e.namespace=this}resolveTask(e){if(!e)return;let s,a,t=e.split(":"),p=t.pop();return t.length?(t=t.join(":"),a=this.resolveNamespace(t)||Namespace.ROOT_NAMESPACE.resolveNamespace(t),s=a&&a.resolveTask(p)):s=this.tasks[e]||Namespace.ROOT_NAMESPACE.tasks[e],s||null}resolveNamespace(e){if(!e)return this;let s=e.split(":"),a=this;for(let e=0,t=s.length;a&&e<t;e++)a=a.childNamespaces[s[e]];return a||null}matchRule(e){let s=e.split(":");s.pop();let a,t,p=this.resolveNamespace(s.join(":")),r=p?p.rules:[];for(let s in r)a=r[s],a.match(e)&&(t=a);return p&&t||this.parentNamespace&&this.parentNamespace.matchRule(e)}getPath(){let e=[],s=this.parentNamespace;for(;s;)e.push(s.name),s=s.parentNamespace;return e.pop(),e.reverse().join(":")}_getFullName(){let e=this.path;return e=e&&e.split(":")||[],e.push(this.name),e.join(":")}isRootNamespace(){return!this.parentNamespace}}class RootNamespace extends Namespace{constructor(){super("__rootNamespace__",null),Namespace.ROOT_NAMESPACE=this}}module.exports.Namespace=Namespace,module.exports.RootNamespace=RootNamespace;
\ No newline at end of file
index 527aca7..484c49e 100755 (executable)
@@ -1,406 +1 @@
-/*
- * Jake JavaScript build tool
- * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-*/
-
-let path = require('path');
-let fs = require('fs');
-let exec = require('child_process').exec;
-let FileList = require('filelist').FileList;
-
-/**
-  @name jake
-  @namespace jake
-*/
-/**
-  @name jake.PackageTask
-  @constructor
-  @description Instantiating a PackageTask creates a number of Jake
-  Tasks that make packaging and distributing your software easy.
-
-  @param {String} name The name of the project
-  @param {String} version The current project version (will be
-  appended to the project-name in the package-archive
-  @param {Function} definition Defines the contents of the package,
-  and format of the package-archive. Will be executed on the instantiated
-  PackageTask (i.e., 'this', will be the PackageTask instance),
-  to set the various instance-propertiess.
-
-  @example
-  let t = new jake.PackageTask('rous', 'v' + version, function () {
-    let files = [
-      'Capfile'
-    , 'Jakefile'
-    , 'README.md'
-    , 'package.json'
-    , 'app/*'
-    , 'bin/*'
-    , 'config/*'
-    , 'lib/*'
-    , 'node_modules/*'
-    ];
-    this.packageFiles.include(files);
-    this.packageFiles.exclude('node_modules/foobar');
-    this.needTarGz = true;
-  });
-
- */
-let PackageTask = function () {
-  let args = Array.prototype.slice.call(arguments);
-  let name = args.shift();
-  let version = args.shift();
-  let definition = args.pop();
-  let prereqs = args.pop() || []; // Optional
-
-  prereqs = [].concat(prereqs); // Accept string or list
-
-  /**
-    @name jake.PackageTask#name
-    @public
-    @type {String}
-    @description The name of the project
-   */
-  this.name = name;
-  /**
-    @name jake.PackageTask#version
-    @public
-    @type {String}
-    @description The project version-string
-   */
-  this.version = version;
-  /**
-    @name jake.PackageTask#prereqs
-    @public
-    @type {Array}
-    @description Tasks to run before packaging
-   */
-  this.prereqs = prereqs;
-  /**
-    @name jake.PackageTask#packageDir
-    @public
-    @type {String='pkg'}
-    @description The directory-name to use for packaging the software
-   */
-  this.packageDir = 'pkg';
-  /**
-    @name jake.PackageTask#packageFiles
-    @public
-    @type {jake.FileList}
-    @description The list of files and directories to include in the
-    package-archive
-   */
-  this.packageFiles = new FileList();
-  /**
-    @name jake.PackageTask#needTar
-    @public
-    @type {Boolean=false}
-    @description If set to true, uses the `tar` utility to create
-    a gzip .tgz archive of the package
-   */
-  this.needTar = false;
-  /**
-    @name jake.PackageTask#needTarGz
-    @public
-    @type {Boolean=false}
-    @description If set to true, uses the `tar` utility to create
-    a gzip .tar.gz archive of the package
-   */
-  this.needTarGz = false;
-  /**
-    @name jake.PackageTask#needTarBz2
-    @public
-    @type {Boolean=false}
-    @description If set to true, uses the `tar` utility to create
-    a bzip2 .bz2 archive of the package
-   */
-  this.needTarBz2 = false;
-  /**
-    @name jake.PackageTask#needJar
-    @public
-    @type {Boolean=false}
-    @description If set to true, uses the `jar` utility to create
-    a .jar archive of the package
-   */
-  this.needJar = false;
-  /**
-    @name jake.PackageTask#needZip
-    @public
-    @type {Boolean=false}
-    @description If set to true, uses the `zip` utility to create
-    a .zip archive of the package
-   */
-  this.needZip = false;
-  /**
-    @name jake.PackageTask#manifestFile
-    @public
-    @type {String=null}
-    @description Can be set to point the `jar` utility at a manifest
-    file to use in a .jar archive. If unset, one will be automatically
-    created by the `jar` utility. This path should be relative to the
-    root of the package directory (this.packageDir above, likely 'pkg')
-   */
-  this.manifestFile = null;
-  /**
-    @name jake.PackageTask#tarCommand
-    @public
-    @type {String='tar'}
-    @description The shell-command to use for creating tar archives.
-   */
-  this.tarCommand = 'tar';
-  /**
-    @name jake.PackageTask#jarCommand
-    @public
-    @type {String='jar'}
-    @description The shell-command to use for creating jar archives.
-   */
-  this.jarCommand = 'jar';
-  /**
-    @name jake.PackageTask#zipCommand
-    @public
-    @type {String='zip'}
-    @description The shell-command to use for creating zip archives.
-   */
-  this.zipCommand = 'zip';
-  /**
-    @name jake.PackageTask#archiveNoBaseDir
-    @public
-    @type {Boolean=false}
-    @description Simple option for performing the archive on the
-    contents of the directory instead of the directory itself
-   */
-  this.archiveNoBaseDir = false;
-  /**
-    @name jake.PackageTask#archiveChangeDir
-    @public
-    @type {String=null}
-    @description Equivalent to the '-C' command for the `tar` and `jar`
-    commands. ("Change to this directory before adding files.")
-   */
-  this.archiveChangeDir = null;
-  /**
-    @name jake.PackageTask#archiveContentDir
-    @public
-    @type {String=null}
-    @description Specifies the files and directories to include in the
-    package-archive. If unset, this will default to the main package
-    directory -- i.e., name + version.
-   */
-  this.archiveContentDir = null;
-
-  if (typeof definition == 'function') {
-    definition.call(this);
-  }
-  this.define();
-};
-
-PackageTask.prototype = new (function () {
-
-  let _compressOpts = {
-    Tar: {
-      ext: '.tgz',
-      flags: 'czf',
-      cmd: 'tar'
-    },
-    TarGz: {
-      ext: '.tar.gz',
-      flags: 'czf',
-      cmd: 'tar'
-    },
-    TarBz2: {
-      ext: '.tar.bz2',
-      flags: 'cjf',
-      cmd: 'tar'
-    },
-    Jar: {
-      ext: '.jar',
-      flags: 'cf',
-      cmd: 'jar'
-    },
-    Zip: {
-      ext: '.zip',
-      flags: 'qr',
-      cmd: 'zip'
-    }
-  };
-
-  this.define = function () {
-    let self = this;
-    let packageDirPath = this.packageDirPath();
-    let compressTaskArr = [];
-
-    desc('Build the package for distribution');
-    task('package', self.prereqs.concat(['clobberPackage', 'buildPackage']));
-    // Backward-compat alias
-    task('repackage', ['package']);
-
-    task('clobberPackage', function () {
-      jake.rmRf(self.packageDir, {silent: true});
-    });
-
-    desc('Remove the package');
-    task('clobber', ['clobberPackage']);
-
-    let doCommand = function (p) {
-      let filename = path.resolve(self.packageDir + '/' + self.packageName() +
-                                  _compressOpts[p].ext);
-      if (process.platform == 'win32') {
-        // Windows full path may have drive letter, which is going to cause
-        // namespace problems, so strip it.
-        if (filename.length > 2 && filename[1] == ':') {
-          filename = filename.substr(2);
-        }
-      }
-      compressTaskArr.push(filename);
-
-      file(filename, [packageDirPath], function () {
-        let cmd;
-        let opts = _compressOpts[p];
-        // Directory to move to when doing the compression-task
-        // Changes in the case of zip for emulating -C option
-        let chdir = self.packageDir;
-        // Save the current dir so it's possible to pop back up
-        // after compressing
-        let currDir = process.cwd();
-        let archiveChangeDir;
-        let archiveContentDir;
-
-        if (self.archiveNoBaseDir) {
-          archiveChangeDir = self.packageName();
-          archiveContentDir = '.';
-        }
-        else {
-          archiveChangeDir = self.archiveChangeDir;
-          archiveContentDir = self.archiveContentDir;
-        }
-
-        cmd = self[opts.cmd + 'Command'];
-        cmd += ' -' + opts.flags;
-        if (opts.cmd == 'jar' && self.manifestFile) {
-          cmd += 'm';
-        }
-
-        // The name of the archive to create -- use full path
-        // so compression can be performed from a different dir
-        // if needed
-        cmd += ' ' + filename;
-
-        if (opts.cmd == 'jar' && self.manifestFile) {
-          cmd += ' ' + self.manifestFile;
-        }
-
-        // Where to perform the compression -- -C option isn't
-        // supported in zip, so actually do process.chdir for this
-        if (archiveChangeDir) {
-          if (opts.cmd == 'zip') {
-            chdir = path.join(chdir, archiveChangeDir);
-          }
-          else {
-            cmd += ' -C ' + archiveChangeDir;
-          }
-        }
-
-        // Where to get the archive content
-        if (archiveContentDir) {
-          cmd += ' ' + archiveContentDir;
-        }
-        else {
-          cmd += ' ' + self.packageName();
-        }
-
-        // Move into the desired dir (usually packageDir) to compress
-        // Return back up to the current dir after the exec
-        process.chdir(chdir);
-
-        exec(cmd, function (err, stdout, stderr) {
-          if (err) { throw err; }
-
-          // Return back up to the starting directory (see above,
-          // before exec)
-          process.chdir(currDir);
-
-          complete();
-        });
-      }, {async: true});
-    };
-
-    for (let p in _compressOpts) {
-      if (this['need' + p]) {
-        doCommand(p);
-      }
-    }
-
-    task('buildPackage', compressTaskArr, function () {});
-
-    directory(this.packageDir);
-
-    file(packageDirPath, this.packageFiles, function () {
-      jake.mkdirP(packageDirPath);
-      let fileList = [];
-      self.packageFiles.forEach(function (name) {
-        let f = path.join(self.packageDirPath(), name);
-        let fDir = path.dirname(f);
-        jake.mkdirP(fDir, {silent: true});
-
-        // Add both files and directories
-        fileList.push({
-          from: name,
-          to: f
-        });
-      });
-      let _copyFile = function () {
-        let file = fileList.pop();
-        let stat;
-        if (file) {
-          stat = fs.statSync(file.from);
-          // Target is a directory, just create it
-          if (stat.isDirectory()) {
-            jake.mkdirP(file.to, {silent: true});
-            _copyFile();
-          }
-          // Otherwise copy the file
-          else {
-            jake.cpR(file.from, file.to, {silent: true});
-            _copyFile();
-          }
-        }
-        else {
-          complete();
-        }
-      };
-      _copyFile();
-    }, {async: true});
-
-
-  };
-
-  this.packageName = function () {
-    if (this.version) {
-      return this.name + '-' + this.version;
-    }
-    else {
-      return this.name;
-    }
-  };
-
-  this.packageDirPath = function () {
-    return this.packageDir + '/' + this.packageName();
-  };
-
-})();
-
-jake.PackageTask = PackageTask;
-exports.PackageTask = PackageTask;
-
+let path=require("path"),fs=require("fs"),exec=require("child_process").exec,FileList=require("filelist").FileList,PackageTask=function(){let e=Array.prototype.slice.call(arguments),a=e.shift(),i=e.shift(),t=e.pop(),s=e.pop()||[];s=[].concat(s),this.name=a,this.version=i,this.prereqs=s,this.packageDir="pkg",this.packageFiles=new FileList,this.needTar=!1,this.needTarGz=!1,this.needTarBz2=!1,this.needJar=!1,this.needZip=!1,this.manifestFile=null,this.tarCommand="tar",this.jarCommand="jar",this.zipCommand="zip",this.archiveNoBaseDir=!1,this.archiveChangeDir=null,this.archiveContentDir=null,"function"==typeof t&&t.call(this),this.define()};PackageTask.prototype=new function(){let e={Tar:{ext:".tgz",flags:"czf",cmd:"tar"},TarGz:{ext:".tar.gz",flags:"czf",cmd:"tar"},TarBz2:{ext:".tar.bz2",flags:"cjf",cmd:"tar"},Jar:{ext:".jar",flags:"cf",cmd:"jar"},Zip:{ext:".zip",flags:"qr",cmd:"zip"}};this.define=function(){let a=this,i=this.packageDirPath(),t=[];desc("Build the package for distribution"),task("package",a.prereqs.concat(["clobberPackage","buildPackage"])),task("repackage",["package"]),task("clobberPackage",(function(){jake.rmRf(a.packageDir,{silent:!0})})),desc("Remove the package"),task("clobber",["clobberPackage"]);let s=function(s){let c=path.resolve(a.packageDir+"/"+a.packageName()+e[s].ext);"win32"==process.platform&&c.length>2&&":"==c[1]&&(c=c.substr(2)),t.push(c),file(c,[i],(function(){let i,t,r,n=e[s],o=a.packageDir,h=process.cwd();a.archiveNoBaseDir?(t=a.packageName(),r="."):(t=a.archiveChangeDir,r=a.archiveContentDir),i=a[n.cmd+"Command"],i+=" -"+n.flags,"jar"==n.cmd&&a.manifestFile&&(i+="m"),i+=" "+c,"jar"==n.cmd&&a.manifestFile&&(i+=" "+a.manifestFile),t&&("zip"==n.cmd?o=path.join(o,t):i+=" -C "+t),i+=r?" "+r:" "+a.packageName(),process.chdir(o),exec(i,(function(e,a,i){if(e)throw e;process.chdir(h),complete()}))}),{async:!0})};for(let a in e)this["need"+a]&&s(a);task("buildPackage",t,(function(){})),directory(this.packageDir),file(i,this.packageFiles,(function(){jake.mkdirP(i);let e=[];a.packageFiles.forEach((function(i){let t=path.join(a.packageDirPath(),i),s=path.dirname(t);jake.mkdirP(s,{silent:!0}),e.push({from:i,to:t})}));let t=function(){let a,i=e.pop();i?(a=fs.statSync(i.from),a.isDirectory()?(jake.mkdirP(i.to,{silent:!0}),t()):(jake.cpR(i.from,i.to,{silent:!0}),t())):complete()};t()}),{async:!0})},this.packageName=function(){return this.version?this.name+"-"+this.version:this.name},this.packageDirPath=function(){return this.packageDir+"/"+this.packageName()}},jake.PackageTask=PackageTask,exports.PackageTask=PackageTask;
\ No newline at end of file
index 1bd24c9..3526841 100755 (executable)
@@ -1,134 +1 @@
-/*
- * Jake JavaScript build tool
- * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-*/
-
-let parseargs = {};
-let isOpt = function (arg) { return arg.indexOf('-') === 0 };
-let removeOptPrefix = function (opt) { return opt.replace(/^--/, '').replace(/^-/, '') };
-
-/**
- * @constructor
- * Parses a list of command-line args into a key/value object of
- * options and an array of positional commands.
- * @ param {Array} opts A list of options in the following format:
- * [{full: 'foo', abbr: 'f'}, {full: 'bar', abbr: 'b'}]]
- */
-parseargs.Parser = function (opts) {
-  // A key/value object of matching options parsed out of the args
-  this.opts = {};
-  this.taskNames = null;
-  this.envVars = null;
-
-  // Data structures used for parsing
-  this.reg = opts;
-  this.shortOpts = {};
-  this.longOpts = {};
-
-  let self = this;
-  [].forEach.call(opts, function (item) {
-    self.shortOpts[item.abbr] = item;
-    self.longOpts[item.full] = item;
-  });
-};
-
-parseargs.Parser.prototype = new function () {
-
-  let _trueOrNextVal = function (argParts, args) {
-    if (argParts[1]) {
-      return argParts[1];
-    }
-    else {
-      return (!args[0] || isOpt(args[0])) ?
-        true : args.shift();
-    }
-  };
-
-  /**
-   * Parses an array of arguments into options and positional commands
-   * @param {Array} args The command-line args to parse
-   */
-  this.parse = function (args) {
-    let cmds = [];
-    let cmd;
-    let envVars = {};
-    let opts = {};
-    let arg;
-    let argItem;
-    let argParts;
-    let cmdItems;
-    let taskNames = [];
-    let preempt;
-
-    while (args.length) {
-      arg = args.shift();
-
-      if (isOpt(arg)) {
-        arg = removeOptPrefix(arg);
-        argParts = arg.split('=');
-        argItem = this.longOpts[argParts[0]] || this.shortOpts[argParts[0]];
-        if (argItem) {
-          // First-encountered preemptive opt takes precedence -- no further opts
-          // or possibility of ambiguity, so just look for a value, or set to
-          // true and then bail
-          if (argItem.preempts) {
-            opts[argItem.full] = _trueOrNextVal(argParts, args);
-            preempt = true;
-            break;
-          }
-          // If the opt requires a value, see if we can get a value from the
-          // next arg, or infer true from no-arg -- if it's followed by another
-          // opt, throw an error
-          if (argItem.expectValue || argItem.allowValue) {
-            opts[argItem.full] = _trueOrNextVal(argParts, args);
-            if (argItem.expectValue && !opts[argItem.full]) {
-              throw new Error(argItem.full + ' option expects a value.');
-            }
-          }
-          else {
-            opts[argItem.full] = true;
-          }
-        }
-      }
-      else {
-        cmds.unshift(arg);
-      }
-    }
-
-    if (!preempt) {
-      // Parse out any env-vars and task-name
-      while ((cmd = cmds.pop())) {
-        cmdItems = cmd.split('=');
-        if (cmdItems.length > 1) {
-          envVars[cmdItems[0]] = cmdItems[1];
-        }
-        else {
-          taskNames.push(cmd);
-        }
-      }
-
-    }
-
-    return {
-      opts: opts,
-      envVars: envVars,
-      taskNames: taskNames
-    };
-  };
-
-};
-
-module.exports = parseargs;
+let parseargs={},isOpt=function(t){return 0===t.indexOf("-")},removeOptPrefix=function(t){return t.replace(/^--/,"").replace(/^-/,"")};parseargs.Parser=function(t){this.opts={},this.taskNames=null,this.envVars=null,this.reg=t,this.shortOpts={},this.longOpts={};let e=this;[].forEach.call(t,(function(t){e.shortOpts[t.abbr]=t,e.longOpts[t.full]=t}))},parseargs.Parser.prototype=new function(){let t=function(t,e){return t[1]?t[1]:!(e[0]&&!isOpt(e[0]))||e.shift()};this.parse=function(e){let s,r,l,i,p,n,o=[],a={},f={},u=[];for(;e.length;)if(r=e.shift(),isOpt(r)){if(r=removeOptPrefix(r),i=r.split("="),l=this.longOpts[i[0]]||this.shortOpts[i[0]],l){if(l.preempts){f[l.full]=t(i,e),n=!0;break}if(l.expectValue||l.allowValue){if(f[l.full]=t(i,e),l.expectValue&&!f[l.full])throw new Error(l.full+" option expects a value.")}else f[l.full]=!0}}else o.unshift(r);if(!n)for(;s=o.pop();)p=s.split("="),p.length>1?a[p[0]]=p[1]:u.push(s);return{opts:f,envVars:a,taskNames:u}}},module.exports=parseargs;
\ No newline at end of file
index 121632f..466d878 100755 (executable)
@@ -1,282 +1 @@
-/*
- * Jake JavaScript build tool
- * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-*/
-
-let fs = require('fs');
-let parseargs = require('./parseargs');
-let utils = require('./utils');
-let Program;
-let usage = require('fs').readFileSync(`${__dirname}/../usage.txt`).toString();
-let { Task } = require('./task/task');
-
-function die(msg) {
-  console.log(msg);
-  process.stdout.write('', function () {
-    process.stderr.write('', function () {
-      process.exit();
-    });
-  });
-}
-
-let preempts = {
-  version: function () {
-    die(jake.version);
-  },
-  help: function () {
-    die(usage);
-  }
-};
-
-let AVAILABLE_OPTS = [
-  { full: 'jakefile',
-    abbr: 'f',
-    expectValue: true
-  },
-  { full: 'quiet',
-    abbr: 'q',
-    expectValue: false
-  },
-  { full: 'directory',
-    abbr: 'C',
-    expectValue: true
-  },
-  { full: 'always-make',
-    abbr: 'B',
-    expectValue: false
-  },
-  { full: 'tasks',
-    abbr: 'T',
-    expectValue: false,
-    allowValue: true
-  },
-  // Alias t
-  { full: 'tasks',
-    abbr: 't',
-    expectValue: false,
-    allowValue: true
-  },
-  // Alias ls
-  { full: 'tasks',
-    abbr: 'ls',
-    expectValue: false,
-    allowValue: true
-  },
-  { full: 'help',
-    abbr: 'h',
-  },
-  { full: 'version',
-    abbr: 'V',
-  },
-  // Alias lowercase v
-  { full: 'version',
-    abbr: 'v',
-  },
-  { full: 'jakelibdir',
-    abbr: 'J',
-    expectValue: true
-  },
-  { full: 'allow-rejection',
-    abbr: 'ar',
-    expectValue: false
-  }
-];
-
-Program = function () {
-  this.availableOpts = AVAILABLE_OPTS;
-  this.opts = {};
-  this.taskNames = null;
-  this.taskArgs = null;
-  this.envVars = null;
-  this.die = die;
-};
-
-Program.prototype = new (function () {
-
-  this.handleErr = function (err) {
-    if (jake.listeners('error').length !== 0) {
-      jake.emit('error', err);
-      return;
-    }
-
-    if (jake.listeners('error').length) {
-      jake.emit('error', err);
-      return;
-    }
-
-    utils.logger.error('jake aborted.');
-    if (err.stack) {
-      utils.logger.error(err.stack);
-    }
-    else {
-      utils.logger.error(err.message);
-    }
-
-    process.stdout.write('', function () {
-      process.stderr.write('', function () {
-        jake.errorCode = jake.errorCode || 1;
-        process.exit(jake.errorCode);
-      });
-    });
-  };
-
-  this.parseArgs = function (args) {
-    let result = (new parseargs.Parser(this.availableOpts)).parse(args);
-    this.setOpts(result.opts);
-    this.setTaskNames(result.taskNames);
-    this.setEnvVars(result.envVars);
-  };
-
-  this.setOpts = function (options) {
-    let opts = options || {};
-    Object.assign(this.opts, opts);
-  };
-
-  this.internalOpts = function (options) {
-    this.availableOpts = this.availableOpts.concat(options);
-  };
-
-  this.autocompletions = function (cur) {
-    let p; let i; let task;
-    let commonPrefix = '';
-    let matches = [];
-
-    for (p in jake.Task) {
-      task = jake.Task[p];
-      if (
-        'fullName' in task
-          && (
-            // if empty string, program converts to true
-            cur === true ||
-            task.fullName.indexOf(cur) === 0
-          )
-      ) {
-        if (matches.length === 0) {
-          commonPrefix = task.fullName;
-        }
-        else {
-          for (i = commonPrefix.length; i > -1; --i) {
-            commonPrefix = commonPrefix.substr(0, i);
-            if (task.fullName.indexOf(commonPrefix) === 0) {
-              break;
-            }
-          }
-        }
-        matches.push(task.fullName);
-      }
-    }
-
-    if (matches.length > 1 && commonPrefix === cur) {
-      matches.unshift('yes-space');
-    }
-    else {
-      matches.unshift('no-space');
-    }
-
-    process.stdout.write(matches.join(' '));
-  };
-
-  this.setTaskNames = function (names) {
-    if (names && !Array.isArray(names)) {
-      throw new Error('Task names must be an array');
-    }
-    this.taskNames = (names && names.length) ? names : ['default'];
-  };
-
-  this.setEnvVars = function (vars) {
-    this.envVars = vars || null;
-  };
-
-  this.firstPreemptiveOption = function () {
-    let opts = this.opts;
-    for (let p in opts) {
-      if (preempts[p]) {
-        return preempts[p];
-      }
-    }
-    return false;
-  };
-
-  this.init = function (configuration) {
-    let self = this;
-    let config = configuration || {};
-    if (config.options) {
-      this.setOpts(config.options);
-    }
-    if (config.taskNames) {
-      this.setTaskNames(config.taskNames);
-    }
-    if (config.envVars) {
-      this.setEnvVars(config.envVars);
-    }
-    process.addListener('uncaughtException', function (err) {
-      self.handleErr(err);
-    });
-    if (!this.opts['allow-rejection']) {
-      process.addListener('unhandledRejection', (reason, promise) => {
-        utils.logger.error('Unhandled rejection at:', promise, 'reason:', reason);
-        self.handleErr(reason);
-      });
-    }
-    if (this.envVars) {
-      Object.assign(process.env, this.envVars);
-    }
-  };
-
-  this.run = function () {
-    let rootTask;
-    let taskNames;
-    let dirname;
-    let opts = this.opts;
-
-    if (opts.autocomplete) {
-      return this.autocompletions(opts['autocomplete-cur'], opts['autocomplete-prev']);
-    }
-    // Run with `jake -T`, just show descriptions
-    if (opts.tasks) {
-      return jake.showAllTaskDescriptions(opts.tasks);
-    }
-
-    taskNames = this.taskNames;
-    if (!(Array.isArray(taskNames) && taskNames.length)) {
-      throw new Error('Please pass jake.runTasks an array of task-names');
-    }
-
-    // Set working dir
-    dirname = opts.directory;
-    if (dirname) {
-      if (fs.existsSync(dirname) &&
-        fs.statSync(dirname).isDirectory()) {
-        process.chdir(dirname);
-      }
-      else {
-        throw new Error(dirname + ' is not a valid directory path');
-      }
-    }
-
-    rootTask = task(Task.ROOT_TASK_NAME, taskNames, function () {});
-    rootTask._internal = true;
-
-    rootTask.once('complete', function () {
-      jake.emit('complete');
-    });
-    jake.emit('start');
-    rootTask.invoke();
-  };
-
-})();
-
-module.exports.Program = Program;
+let Program,fs=require("fs"),parseargs=require("./parseargs"),utils=require("./utils"),usage=require("fs").readFileSync(`${__dirname}/../usage.txt`).toString(),{Task:Task}=require("./task/task");function die(e){console.log(e),process.stdout.write("",(function(){process.stderr.write("",(function(){process.exit()}))}))}let preempts={version:function(){die(jake.version)},help:function(){die(usage)}},AVAILABLE_OPTS=[{full:"jakefile",abbr:"f",expectValue:!0},{full:"quiet",abbr:"q",expectValue:!1},{full:"directory",abbr:"C",expectValue:!0},{full:"always-make",abbr:"B",expectValue:!1},{full:"tasks",abbr:"T",expectValue:!1,allowValue:!0},{full:"tasks",abbr:"t",expectValue:!1,allowValue:!0},{full:"tasks",abbr:"ls",expectValue:!1,allowValue:!0},{full:"help",abbr:"h"},{full:"version",abbr:"V"},{full:"version",abbr:"v"},{full:"jakelibdir",abbr:"J",expectValue:!0},{full:"allow-rejection",abbr:"ar",expectValue:!1}];Program=function(){this.availableOpts=AVAILABLE_OPTS,this.opts={},this.taskNames=null,this.taskArgs=null,this.envVars=null,this.die=die},Program.prototype=new function(){this.handleErr=function(e){0===jake.listeners("error").length?jake.listeners("error").length?jake.emit("error",e):(utils.logger.error("jake aborted."),e.stack?utils.logger.error(e.stack):utils.logger.error(e.message),process.stdout.write("",(function(){process.stderr.write("",(function(){jake.errorCode=jake.errorCode||1,process.exit(jake.errorCode)}))}))):jake.emit("error",e)},this.parseArgs=function(e){let s=new parseargs.Parser(this.availableOpts).parse(e);this.setOpts(s.opts),this.setTaskNames(s.taskNames),this.setEnvVars(s.envVars)},this.setOpts=function(e){let s=e||{};Object.assign(this.opts,s)},this.internalOpts=function(e){this.availableOpts=this.availableOpts.concat(e)},this.autocompletions=function(e){let s,t,r,a="",i=[];for(s in jake.Task)if(r=jake.Task[s],"fullName"in r&&(!0===e||0===r.fullName.indexOf(e))){if(0===i.length)a=r.fullName;else for(t=a.length;t>-1&&(a=a.substr(0,t),0!==r.fullName.indexOf(a));--t);i.push(r.fullName)}i.length>1&&a===e?i.unshift("yes-space"):i.unshift("no-space"),process.stdout.write(i.join(" "))},this.setTaskNames=function(e){if(e&&!Array.isArray(e))throw new Error("Task names must be an array");this.taskNames=e&&e.length?e:["default"]},this.setEnvVars=function(e){this.envVars=e||null},this.firstPreemptiveOption=function(){let e=this.opts;for(let s in e)if(preempts[s])return preempts[s];return!1},this.init=function(e){let s=this,t=e||{};t.options&&this.setOpts(t.options),t.taskNames&&this.setTaskNames(t.taskNames),t.envVars&&this.setEnvVars(t.envVars),process.addListener("uncaughtException",(function(e){s.handleErr(e)})),this.opts["allow-rejection"]||process.addListener("unhandledRejection",((e,t)=>{utils.logger.error("Unhandled rejection at:",t,"reason:",e),s.handleErr(e)})),this.envVars&&Object.assign(process.env,this.envVars)},this.run=function(){let e,s,t,r=this.opts;if(r.autocomplete)return this.autocompletions(r["autocomplete-cur"],r["autocomplete-prev"]);if(r.tasks)return jake.showAllTaskDescriptions(r.tasks);if(s=this.taskNames,!Array.isArray(s)||!s.length)throw new Error("Please pass jake.runTasks an array of task-names");if(t=r.directory,t){if(!fs.existsSync(t)||!fs.statSync(t).isDirectory())throw new Error(t+" is not a valid directory path");process.chdir(t)}e=task(Task.ROOT_TASK_NAME,s,(function(){})),e._internal=!0,e.once("complete",(function(){jake.emit("complete")})),jake.emit("start"),e.invoke()}},module.exports.Program=Program;
\ No newline at end of file
index f0cacfd..42440ea 100755 (executable)
@@ -1,290 +1 @@
-/*
- * Jake JavaScript build tool
- * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-*/
-
-let fs = require('fs');
-let path = require('path');
-let exec = require('child_process').execSync;
-let FileList = require('filelist').FileList;
-
-let PublishTask = function () {
-  let args = Array.prototype.slice.call(arguments).filter(function (item) {
-    return typeof item != 'undefined';
-  });
-  let arg;
-  let opts = {};
-  let definition;
-  let prereqs = [];
-  let createDef = function (arg) {
-    return function () {
-      this.packageFiles.include(arg);
-    };
-  };
-
-  this.name = args.shift();
-
-  // Old API, just name + list of files
-  if (args.length == 1 && (Array.isArray(args[0]) || typeof args[0] == 'string')) {
-    definition = createDef(args.pop());
-  }
-  // Current API, name + [prereqs] + [opts] + definition
-  else {
-    while ((arg = args.pop())) {
-      // Definition func
-      if (typeof arg == 'function') {
-        definition = arg;
-      }
-      // Prereqs
-      else if (Array.isArray(arg) || typeof arg == 'string') {
-        prereqs = arg;
-      }
-      // Opts
-      else {
-        opts = arg;
-      }
-    }
-  }
-
-  this.prereqs = prereqs;
-  this.packageFiles = new FileList();
-  this.publishCmd = opts.publishCmd || 'npm publish %filename';
-  this.publishMessage = opts.publishMessage || 'BOOM! Published.';
-  this.gitCmd = opts.gitCmd || 'git';
-  this.versionFiles = opts.versionFiles || ['package.json'];
-  this.scheduleDelay = 5000;
-
-  // Override utility funcs for testing
-  this._ensureRepoClean = function (stdout) {
-    if (stdout.length) {
-      fail(new Error('Git repository is not clean.'));
-    }
-  };
-  this._getCurrentBranch = function (stdout) {
-    return String(stdout).trim();
-  };
-
-  if (typeof definition == 'function') {
-    definition.call(this);
-  }
-  this.define();
-};
-
-
-PublishTask.prototype = new (function () {
-
-  let _currentBranch = null;
-
-  let getPackage = function () {
-    let pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(),
-      '/package.json')).toString());
-    return pkg;
-  };
-  let getPackageVersionNumber = function () {
-    return getPackage().version;
-  };
-
-  this.define = function () {
-    let self = this;
-
-    namespace('publish', function () {
-      task('fetchTags', function () {
-        // Make sure local tags are up to date
-        exec(self.gitCmd + ' fetch --tags');
-        console.log('Fetched remote tags.');
-      });
-
-      task('getCurrentBranch', function () {
-        // Figure out what branch to push to
-        let stdout = exec(self.gitCmd + ' symbolic-ref --short HEAD').toString();
-        if (!stdout) {
-          throw new Error('No current Git branch found');
-        }
-        _currentBranch = self._getCurrentBranch(stdout);
-        console.log('On branch ' + _currentBranch);
-      });
-
-      task('ensureClean', function () {
-        // Only bump, push, and tag if the Git repo is clean
-        let stdout = exec(self.gitCmd + ' status --porcelain --untracked-files=no').toString();
-        // Throw if there's output
-        self._ensureRepoClean(stdout);
-      });
-
-      task('updateVersionFiles', function () {
-        let pkg;
-        let version;
-        let arr;
-        let patch;
-
-        // Grab the current version-string
-        pkg = getPackage();
-        version = pkg.version;
-        // Increment the patch-number for the version
-        arr = version.split('.');
-        patch = parseInt(arr.pop(), 10) + 1;
-        arr.push(patch);
-        version = arr.join('.');
-
-        // Update package.json or other files with the new version-info
-        self.versionFiles.forEach(function (file) {
-          let p = path.join(process.cwd(), file);
-          let data = JSON.parse(fs.readFileSync(p).toString());
-          data.version = version;
-          fs.writeFileSync(p, JSON.stringify(data, true, 2) + '\n');
-        });
-        // Return the version string so that listeners for the 'complete' event
-        // for this task can use it (e.g., to update other files before pushing
-        // to Git)
-        return version;
-      });
-
-      task('pushVersion', ['ensureClean', 'updateVersionFiles'], function () {
-        let version = getPackageVersionNumber();
-        let message = 'Version ' + version;
-        let cmds = [
-          self.gitCmd + ' commit -a -m "' + message + '"',
-          self.gitCmd + ' push origin ' + _currentBranch,
-          self.gitCmd + ' tag -a v' + version + ' -m "' + message + '"',
-          self.gitCmd + ' push --tags'
-        ];
-        cmds.forEach((cmd) => {
-          exec(cmd);
-        });
-        version = getPackageVersionNumber();
-        console.log('Bumped version number to v' + version + '.');
-      });
-
-      let defineTask = task('definePackage', function () {
-        let version = getPackageVersionNumber();
-        new jake.PackageTask(self.name, 'v' + version, self.prereqs, function () {
-          // Replace the PackageTask's FileList with the PublishTask's FileList
-          this.packageFiles = self.packageFiles;
-          this.needTarGz = true; // Default to tar.gz
-          // If any of the need<CompressionFormat> or archive opts are set
-          // proxy them to the PackageTask
-          for (let p in this) {
-            if (p.indexOf('need') === 0 || p.indexOf('archive') === 0) {
-              if (typeof self[p] != 'undefined') {
-                this[p] = self[p];
-              }
-            }
-          }
-        });
-      });
-      defineTask._internal = true;
-
-      task('package', function () {
-        let definePack = jake.Task['publish:definePackage'];
-        let pack = jake.Task['package'];
-        let version = getPackageVersionNumber();
-
-        // May have already been run
-        if (definePack.taskStatus == jake.Task.runStatuses.DONE) {
-          definePack.reenable(true);
-        }
-        definePack.invoke();
-        // Set manually, completion happens in next tick, creating deadlock
-        definePack.taskStatus = jake.Task.runStatuses.DONE;
-        pack.invoke();
-        console.log('Created package for ' + self.name + ' v' + version);
-      });
-
-      task('publish', function () {
-        return new Promise((resolve) => {
-          let version = getPackageVersionNumber();
-          let filename;
-          let cmd;
-
-          console.log('Publishing ' + self.name + ' v' + version);
-
-          if (typeof self.createPublishCommand == 'function') {
-            cmd = self.createPublishCommand(version);
-          }
-          else {
-            filename = './pkg/' + self.name + '-v' + version + '.tar.gz';
-            cmd = self.publishCmd.replace(/%filename/gi, filename);
-          }
-
-          if (typeof cmd == 'function') {
-            cmd(function (err) {
-              if (err) {
-                throw err;
-              }
-              console.log(self.publishMessage);
-              resolve();
-            });
-          }
-          else {
-            // Hackity hack -- NPM publish sometimes returns errror like:
-            // Error sending version data\nnpm ERR!
-            // Error: forbidden 0.2.4 is modified, should match modified time
-            setTimeout(function () {
-              let stdout = exec(cmd).toString() || '';
-              stdout = stdout.trim();
-              if (stdout) {
-                console.log(stdout);
-              }
-              console.log(self.publishMessage);
-              resolve();
-            }, self.scheduleDelay);
-          }
-        });
-      });
-
-      task('cleanup', function () {
-        return new Promise((resolve) => {
-          let clobber = jake.Task.clobber;
-          clobber.reenable(true);
-          clobber.on('complete', function () {
-            console.log('Cleaned up package');
-            resolve();
-          });
-          clobber.invoke();
-        });
-      });
-
-    });
-
-    let prefixNs = function (item) {
-      return 'publish:' + item;
-    };
-
-    // Create aliases in the default namespace
-    desc('Create a new version and release.');
-    task('publish', self.prereqs.concat(['version', 'release']
-      .map(prefixNs)));
-
-    desc('Release the existing version.');
-    task('publishExisting', self.prereqs.concat(['release']
-      .map(prefixNs)));
-
-    task('version', ['fetchTags', 'getCurrentBranch', 'pushVersion']
-      .map(prefixNs));
-
-    task('release', ['package', 'publish', 'cleanup']
-      .map(prefixNs));
-
-    // Invoke proactively so there will be a callable 'package' task
-    // which can be used apart from 'publish'
-    jake.Task['publish:definePackage'].invoke();
-  };
-
-})();
-
-jake.PublishTask = PublishTask;
-exports.PublishTask = PublishTask;
-
+let fs=require("fs"),path=require("path"),exec=require("child_process").execSync,FileList=require("filelist").FileList,PublishTask=function(){let e,n,t=Array.prototype.slice.call(arguments).filter((function(e){return void 0!==e})),s={},i=[],a=function(e){return function(){this.packageFiles.include(e)}};if(this.name=t.shift(),1!=t.length||!Array.isArray(t[0])&&"string"!=typeof t[0])for(;e=t.pop();)"function"==typeof e?n=e:Array.isArray(e)||"string"==typeof e?i=e:s=e;else n=a(t.pop());this.prereqs=i,this.packageFiles=new FileList,this.publishCmd=s.publishCmd||"npm publish %filename",this.publishMessage=s.publishMessage||"BOOM! Published.",this.gitCmd=s.gitCmd||"git",this.versionFiles=s.versionFiles||["package.json"],this.scheduleDelay=5e3,this._ensureRepoClean=function(e){e.length&&fail(new Error("Git repository is not clean."))},this._getCurrentBranch=function(e){return String(e).trim()},"function"==typeof n&&n.call(this),this.define()};PublishTask.prototype=new function(){let e=null,n=function(){return JSON.parse(fs.readFileSync(path.join(process.cwd(),"/package.json")).toString())},t=function(){return n().version};this.define=function(){let s=this;namespace("publish",(function(){task("fetchTags",(function(){exec(s.gitCmd+" fetch --tags"),console.log("Fetched remote tags.")})),task("getCurrentBranch",(function(){let n=exec(s.gitCmd+" symbolic-ref --short HEAD").toString();if(!n)throw new Error("No current Git branch found");e=s._getCurrentBranch(n),console.log("On branch "+e)})),task("ensureClean",(function(){let e=exec(s.gitCmd+" status --porcelain --untracked-files=no").toString();s._ensureRepoClean(e)})),task("updateVersionFiles",(function(){let e,t,i,a;return e=n(),t=e.version,i=t.split("."),a=parseInt(i.pop(),10)+1,i.push(a),t=i.join("."),s.versionFiles.forEach((function(e){let n=path.join(process.cwd(),e),s=JSON.parse(fs.readFileSync(n).toString());s.version=t,fs.writeFileSync(n,JSON.stringify(s,!0,2)+"\n")})),t})),task("pushVersion",["ensureClean","updateVersionFiles"],(function(){let n=t(),i="Version "+n;[s.gitCmd+' commit -a -m "'+i+'"',s.gitCmd+" push origin "+e,s.gitCmd+" tag -a v"+n+' -m "'+i+'"',s.gitCmd+" push --tags"].forEach((e=>{exec(e)})),n=t(),console.log("Bumped version number to v"+n+".")})),task("definePackage",(function(){let e=t();new jake.PackageTask(s.name,"v"+e,s.prereqs,(function(){this.packageFiles=s.packageFiles,this.needTarGz=!0;for(let e in this)0!==e.indexOf("need")&&0!==e.indexOf("archive")||void 0!==s[e]&&(this[e]=s[e])}))}))._internal=!0,task("package",(function(){let e=jake.Task["publish:definePackage"],n=jake.Task.package,i=t();e.taskStatus==jake.Task.runStatuses.DONE&&e.reenable(!0),e.invoke(),e.taskStatus=jake.Task.runStatuses.DONE,n.invoke(),console.log("Created package for "+s.name+" v"+i)})),task("publish",(function(){return new Promise((e=>{let n,i,a=t();console.log("Publishing "+s.name+" v"+a),"function"==typeof s.createPublishCommand?i=s.createPublishCommand(a):(n="./pkg/"+s.name+"-v"+a+".tar.gz",i=s.publishCmd.replace(/%filename/gi,n)),"function"==typeof i?i((function(n){if(n)throw n;console.log(s.publishMessage),e()})):setTimeout((function(){let n=exec(i).toString()||"";n=n.trim(),n&&console.log(n),console.log(s.publishMessage),e()}),s.scheduleDelay)}))})),task("cleanup",(function(){return new Promise((e=>{let n=jake.Task.clobber;n.reenable(!0),n.on("complete",(function(){console.log("Cleaned up package"),e()})),n.invoke()}))}))}));let i=function(e){return"publish:"+e};desc("Create a new version and release."),task("publish",s.prereqs.concat(["version","release"].map(i))),desc("Release the existing version."),task("publishExisting",s.prereqs.concat(["release"].map(i))),task("version",["fetchTags","getCurrentBranch","pushVersion"].map(i)),task("release",["package","publish","cleanup"].map(i)),jake.Task["publish:definePackage"].invoke()}},jake.PublishTask=PublishTask,exports.PublishTask=PublishTask;
\ No newline at end of file
index 25f51ae..d18b9ad 100755 (executable)
@@ -1,311 +1 @@
-let path = require('path');
-let fs = require('fs');
-let Task = require('./task/task').Task;
-
-// Split a task to two parts, name space and task name.
-// For example, given 'foo:bin/a%.c', return an object with
-// - 'ns'     : foo
-// - 'name'   : bin/a%.c
-function splitNs(task) {
-  let parts = task.split(':');
-  let name = parts.pop();
-  let ns = resolveNs(parts);
-  return {
-    'name' : name,
-    'ns'   : ns
-  };
-}
-
-// Return the namespace based on an array of names.
-// For example, given ['foo', 'baz' ], return the namespace
-//
-//   default -> foo -> baz
-//
-// where default is the global root namespace
-// and -> means child namespace.
-function resolveNs(parts) {
-  let  ns = jake.defaultNamespace;
-  for(let i = 0, l = parts.length; ns && i < l; i++) {
-    ns = ns.childNamespaces[parts[i]];
-  }
-  return ns;
-}
-
-// Given a pattern p, say 'foo:bin/a%.c'
-// Return an object with
-// - 'ns'     : foo
-// - 'dir'    : bin
-// - 'prefix' : a
-// - 'suffix' : .c
-function resolve(p) {
-  let task = splitNs(p);
-  let name  = task.name;
-  let ns    = task.ns;
-  let split = path.basename(name).split('%');
-  return {
-    ns: ns,
-    dir: path.dirname(name),
-    prefix: split[0],
-    suffix: split[1]
-  };
-}
-
-// Test whether string a is a suffix of string b
-function stringEndWith(a, b) {
-  let l;
-  return (l = b.lastIndexOf(a)) == -1 ? false : l + a.length == b.length;
-}
-
-// Replace the suffix a of the string s with b.
-// Note that, it is assumed a is a suffix of s.
-function stringReplaceSuffix(s, a, b) {
-  return s.slice(0, s.lastIndexOf(a)) + b;
-}
-
-class Rule {
-  constructor(opts) {
-    this.pattern = opts.pattern;
-    this.source = opts.source;
-    this.prereqs = opts.prereqs;
-    this.action = opts.action;
-    this.opts = opts.opts;
-    this.desc =  opts.desc;
-    this.ns = opts.ns;
-  }
-
-  // Create a file task based on this rule for the specified
-  // task-name
-  // ======
-  // FIXME: Right now this just throws away any passed-in args
-  // for the synthsized task (taskArgs param)
-  // ======
-  createTask(fullName, level) {
-    let self = this;
-    let pattern;
-    let source;
-    let action;
-    let opts;
-    let prereqs;
-    let valid;
-    let src;
-    let tNs;
-    let createdTask;
-    let name = Task.getBaseTaskName(fullName);
-    let nsPath = Task.getBaseNamespacePath(fullName);
-    let ns = this.ns.resolveNamespace(nsPath);
-
-    pattern = this.pattern;
-    source = this.source;
-
-    if (typeof source == 'string') {
-      src = Rule.getSource(name, pattern, source);
-    }
-    else {
-      src = source(name);
-    }
-
-    // TODO: Write a utility function that appends a
-    // taskname to a namespace path
-    src = nsPath.split(':').filter(function (item) {
-      return !!item;
-    }).concat(src).join(':');
-
-    // Generate the prerequisite for the matching task.
-    //    It is the original prerequisites plus the prerequisite
-    //    representing source file, i.e.,
-    //
-    //      rule( '%.o', '%.c', ['some.h'] ...
-    //
-    //    If the objective is main.o, then new task should be
-    //
-    //      file( 'main.o', ['main.c', 'some.h' ] ...
-    prereqs = this.prereqs.slice(); // Get a copy to work with
-    prereqs.unshift(src);
-
-    // Prereq should be:
-    // 1. an existing task
-    // 2. an existing file on disk
-    // 3. a valid rule (i.e., not at too deep a level)
-    valid = prereqs.some(function (p) {
-      let ns = self.ns;
-      return ns.resolveTask(p) ||
-        fs.existsSync(Task.getBaseTaskName(p)) ||
-        jake.attemptRule(p, ns, level + 1);
-    });
-
-    // If any of the prereqs aren't valid, the rule isn't valid
-    if (!valid) {
-      return null;
-    }
-    // Otherwise, hunky-dory, finish creating the task for the rule
-    else {
-      // Create the action for the task
-      action = function () {
-        let task = this;
-        self.action.apply(task);
-      };
-
-      opts = this.opts;
-
-      // Insert the file task into Jake
-      //
-      // Since createTask function stores the task as a child task
-      // of currentNamespace. Here we temporariliy switch the namespace.
-      // FIXME: Should allow optional ns passed in instead of this hack
-      tNs = jake.currentNamespace;
-      jake.currentNamespace = ns;
-      createdTask = jake.createTask('file', name, prereqs, action, opts);
-      createdTask.source = src.split(':').pop();
-      jake.currentNamespace = tNs;
-
-      return createdTask;
-    }
-  }
-
-  match(name) {
-    return Rule.match(this.pattern, name);
-  }
-
-  // Test wether the a prerequisite matchs the pattern.
-  // The arg 'pattern' does not have namespace as prefix.
-  // For example, the following tests are true
-  //
-  //   pattern      |    name
-  //   bin/%.o      |    bin/main.o
-  //   bin/%.o      |    foo:bin/main.o
-  //
-  // The following tests are false (trivally)
-  //
-  //   pattern      |    name
-  //   bin/%.o      |    foobin/main.o
-  //   bin/%.o      |    bin/main.oo
-  static match(pattern, name) {
-    let p;
-    let task;
-    let obj;
-    let filename;
-
-    if (pattern instanceof RegExp) {
-      return pattern.test(name);
-    }
-    else if (pattern.indexOf('%') == -1) {
-      // No Pattern. No Folder. No Namespace.
-      // A Simple Suffix Rule. Just test suffix
-      return stringEndWith(pattern, name);
-    }
-    else {
-      // Resolve the dir, prefix and suffix of pattern
-      p = resolve(pattern);
-
-      // Resolve the namespace and task-name
-      task = splitNs(name);
-      name = task.name;
-
-      // Set the objective as the task-name
-      obj = name;
-
-      // Namespace is already matched.
-
-      // Check dir
-      if (path.dirname(obj) != p.dir) {
-        return false;
-      }
-
-      filename = path.basename(obj);
-
-      // Check file name length
-      if ((p.prefix.length + p.suffix.length + 1) > filename.length) {
-        // Length does not match.
-        return false;
-      }
-
-      // Check prefix
-      if (filename.indexOf(p.prefix) !== 0) {
-        return false;
-      }
-
-      // Check suffix
-      if (!stringEndWith(p.suffix, filename)) {
-        return false;
-      }
-
-      // OK. Find a match.
-      return true;
-    }
-  }
-
-  // Generate the source based on
-  //  - name    name for the synthesized task
-  //  - pattern    pattern for the objective
-  //  - source    pattern for the source
-  //
-  // Return the source with properties
-  //  - dep      the prerequisite of source
-  //             (with the namespace)
-  //
-  //  - file     the file name of source
-  //             (without the namespace)
-  //
-  // For example, given
-  //
-  //  - name   foo:bin/main.o
-  //  - pattern    bin/%.o
-  //  - source    src/%.c
-  //
-  //    return 'foo:src/main.c',
-  //
-  static getSource(name, pattern, source) {
-    let dep;
-    let pat;
-    let match;
-    let file;
-    let src;
-
-    // Regex pattern -- use to look up the extension
-    if (pattern instanceof RegExp) {
-      match = pattern.exec(name);
-      if (match) {
-        if (typeof source == 'function') {
-          src = source(name);
-        }
-        else {
-          src = stringReplaceSuffix(name, match[0], source);
-        }
-      }
-    }
-    // Assume string
-    else {
-      // Simple string suffix replacement
-      if (pattern.indexOf('%') == -1) {
-        if (typeof source == 'function') {
-          src = source(name);
-        }
-        else {
-          src = stringReplaceSuffix(name, pattern, source);
-        }
-      }
-      // Percent-based substitution
-      else {
-        pat = pattern.replace('%', '(.*?)');
-        pat = new RegExp(pat);
-        match = pat.exec(name);
-        if (match) {
-          if (typeof source == 'function') {
-            src = source(name);
-          }
-          else {
-            file = match[1];
-            file = source.replace('%', file);
-            dep = match[0];
-            src = name.replace(dep, file);
-          }
-        }
-      }
-    }
-
-    return src;
-  }
-}
-
-
-exports.Rule = Rule;
+let path=require("path"),fs=require("fs"),Task=require("./task/task").Task;function splitNs(e){let t=e.split(":");return{name:t.pop(),ns:resolveNs(t)}}function resolveNs(e){let t=jake.defaultNamespace;for(let s=0,n=e.length;t&&s<n;s++)t=t.childNamespaces[e[s]];return t}function resolve(e){let t=splitNs(e),s=t.name,n=t.ns,a=path.basename(s).split("%");return{ns:n,dir:path.dirname(s),prefix:a[0],suffix:a[1]}}function stringEndWith(e,t){let s;return-1!=(s=t.lastIndexOf(e))&&s+e.length==t.length}function stringReplaceSuffix(e,t,s){return e.slice(0,e.lastIndexOf(t))+s}class Rule{constructor(e){this.pattern=e.pattern,this.source=e.source,this.prereqs=e.prereqs,this.action=e.action,this.opts=e.opts,this.desc=e.desc,this.ns=e.ns}createTask(e,t){let s,n,a,r,i,c,p,l,u,f=this,o=Task.getBaseTaskName(e),h=Task.getBaseNamespacePath(e),g=this.ns.resolveNamespace(h);return s=this.pattern,n=this.source,p="string"==typeof n?Rule.getSource(o,s,n):n(o),p=h.split(":").filter((function(e){return!!e})).concat(p).join(":"),i=this.prereqs.slice(),i.unshift(p),c=i.some((function(e){let s=f.ns;return s.resolveTask(e)||fs.existsSync(Task.getBaseTaskName(e))||jake.attemptRule(e,s,t+1)})),c?(a=function(){f.action.apply(this)},r=this.opts,l=jake.currentNamespace,jake.currentNamespace=g,u=jake.createTask("file",o,i,a,r),u.source=p.split(":").pop(),jake.currentNamespace=l,u):null}match(e){return Rule.match(this.pattern,e)}static match(e,t){let s,n,a,r;return e instanceof RegExp?e.test(t):-1==e.indexOf("%")?stringEndWith(e,t):(s=resolve(e),n=splitNs(t),a=t=n.name,path.dirname(a)==s.dir&&(r=path.basename(a),!(s.prefix.length+s.suffix.length+1>r.length)&&(0===r.indexOf(s.prefix)&&!!stringEndWith(s.suffix,r))))}static getSource(e,t,s){let n,a,r,i,c;return t instanceof RegExp?(r=t.exec(e),r&&(c="function"==typeof s?s(e):stringReplaceSuffix(e,r[0],s))):-1==t.indexOf("%")?c="function"==typeof s?s(e):stringReplaceSuffix(e,t,s):(a=t.replace("%","(.*?)"),a=new RegExp(a),r=a.exec(e),r&&("function"==typeof s?c=s(e):(i=r[1],i=s.replace("%",i),n=r[0],c=e.replace(n,i)))),c}}exports.Rule=Rule;
\ No newline at end of file
index b17b624..db15ef6 100755 (executable)
@@ -1,30 +1 @@
-let fs = require('fs');
-let FileTask = require('./file_task').FileTask;
-
-/**
-  @name jake
-  @namespace jake
-*/
-/**
-  @name jake.DirectoryTask
-  @constructor
-  @augments EventEmitter
-  @augments jake.Task
-  @augments jake.FileTask
-  @description A Jake DirectoryTask
-
-  @param {String} name The name of the directory to create.
- */
-class DirectoryTask extends FileTask {
-  constructor(...args) {
-    super(...args);
-    if (fs.existsSync(this.name)) {
-      this.updateModTime();
-    }
-    else {
-      this.modTime = null;
-    }
-  }
-}
-
-exports.DirectoryTask = DirectoryTask;
+let fs=require("fs"),FileTask=require("./file_task").FileTask;class DirectoryTask extends FileTask{constructor(...e){super(...e),fs.existsSync(this.name)?this.updateModTime():this.modTime=null}}exports.DirectoryTask=DirectoryTask;
\ No newline at end of file
index 6fad84b..f4ddae9 100755 (executable)
@@ -1,124 +1 @@
-let fs = require('fs');
-let Task = require('./task').Task;
-
-function isFileOrDirectory(t) {
-  return (t instanceof FileTask ||
-          t instanceof DirectoryTask);
-}
-
-function isFile(t) {
-  return (t instanceof FileTask && !(t instanceof DirectoryTask));
-}
-
-/**
-  @name jake
-  @namespace jake
-*/
-/**
-  @name jake.FileTask
-  @class`
-  @extentds Task
-  @description A Jake FileTask
-
-  @param {String} name The name of the Task
-  @param {Array} [prereqs] Prerequisites to be run before this task
-  @param {Function} [action] The action to perform to create this file
-  @param {Object} [opts]
-    @param {Array} [opts.asyc=false] Perform this task asynchronously.
-    If you flag a task with this option, you must call the global
-    `complete` method inside the task's action, for execution to proceed
-    to the next task.
- */
-class FileTask extends Task {
-  constructor(...args) {
-    super(...args);
-    this.dummy = false;
-    if (fs.existsSync(this.name)) {
-      this.updateModTime();
-    }
-    else {
-      this.modTime = null;
-    }
-  }
-
-  isNeeded() {
-    let prereqs = this.prereqs;
-    let prereqName;
-    let prereqTask;
-
-    // No repeatsies
-    if (this.taskStatus == Task.runStatuses.DONE) {
-      return false;
-    }
-    // The always-make override
-    else if (jake.program.opts['always-make']) {
-      return true;
-    }
-    // Default case
-    else {
-
-      // We need either an existing file, or an action to create one.
-      // First try grabbing the actual mod-time of the file
-      try {
-        this.updateModTime();
-      }
-      // Then fall back to looking for an action
-      catch(e) {
-        if (typeof this.action == 'function') {
-          return true;
-        }
-        else {
-          throw new Error('File-task ' + this.fullName + ' has no ' +
-            'existing file, and no action to create one.');
-        }
-      }
-
-      // Compare mod-time of all the prereqs with its mod-time
-      // If any prereqs are newer, need to run the action to update
-      if (prereqs && prereqs.length) {
-        for (let i = 0, ii = prereqs.length; i < ii; i++) {
-          prereqName = prereqs[i];
-          prereqTask = this.namespace.resolveTask(prereqName) ||
-            jake.createPlaceholderFileTask(prereqName, this.namespace);
-          // Run the action if:
-          // 1. The prereq is a normal task (not file/dir)
-          // 2. The prereq is a file-task with a mod-date more recent than
-          // the one for this file/dir
-          if (prereqTask) {
-            if (!isFileOrDirectory(prereqTask) ||
-                (isFile(prereqTask) && prereqTask.modTime > this.modTime)) {
-              return true;
-            }
-          }
-        }
-      }
-      // File/dir has no prereqs, and exists -- no need to run
-      else {
-        // Effectively done
-        this.taskStatus = Task.runStatuses.DONE;
-        return false;
-      }
-    }
-  }
-
-  updateModTime() {
-    let stats = fs.statSync(this.name);
-    this.modTime = stats.mtime;
-  }
-
-  complete() {
-    if (!this.dummy) {
-      this.updateModTime();
-    }
-    // Hackity hack
-    Task.prototype.complete.apply(this, arguments);
-  }
-
-}
-
-exports.FileTask = FileTask;
-
-// DirectoryTask is a subclass of FileTask, depends on it
-// being defined
-let DirectoryTask = require('./directory_task').DirectoryTask;
-
+let fs=require("fs"),Task=require("./task").Task;function isFileOrDirectory(e){return e instanceof FileTask||e instanceof DirectoryTask}function isFile(e){return e instanceof FileTask&&!(e instanceof DirectoryTask)}class FileTask extends Task{constructor(...e){super(...e),this.dummy=!1,fs.existsSync(this.name)?this.updateModTime():this.modTime=null}isNeeded(){let e,t,s=this.prereqs;if(this.taskStatus==Task.runStatuses.DONE)return!1;if(jake.program.opts["always-make"])return!0;try{this.updateModTime()}catch(e){if("function"==typeof this.action)return!0;throw new Error("File-task "+this.fullName+" has no existing file, and no action to create one.")}if(!s||!s.length)return this.taskStatus=Task.runStatuses.DONE,!1;for(let i=0,a=s.length;i<a;i++)if(e=s[i],t=this.namespace.resolveTask(e)||jake.createPlaceholderFileTask(e,this.namespace),t&&(!isFileOrDirectory(t)||isFile(t)&&t.modTime>this.modTime))return!0}updateModTime(){let e=fs.statSync(this.name);this.modTime=e.mtime}complete(){this.dummy||this.updateModTime(),Task.prototype.complete.apply(this,arguments)}}exports.FileTask=FileTask;let DirectoryTask=require("./directory_task").DirectoryTask;
\ No newline at end of file
index bc93f41..1d6a92d 100755 (executable)
@@ -1,9 +1 @@
-
-let Task = require('./task').Task;
-let FileTask = require('./file_task').FileTask;
-let DirectoryTask = require('./directory_task').DirectoryTask;
-
-exports.Task = Task;
-exports.FileTask = FileTask;
-exports.DirectoryTask = DirectoryTask;
-
+let Task=require("./task").Task,FileTask=require("./file_task").FileTask,DirectoryTask=require("./directory_task").DirectoryTask;exports.Task=Task,exports.FileTask=FileTask,exports.DirectoryTask=DirectoryTask;
\ No newline at end of file
index 9e8886f..8b7d7fb 100755 (executable)
@@ -1,439 +1 @@
-let EventEmitter = require('events').EventEmitter;
-let async = require('async');
-let chalk = require('chalk');
-// 'rule' module is required at the bottom because circular deps
-
-// Used for task value, so better not to use
-// null, since value should be unset/uninitialized
-let UNDEFINED_VALUE;
-
-const ROOT_TASK_NAME = '__rootTask__';
-const POLLING_INTERVAL = 100;
-
-// Parse any positional args attached to the task-name
-function parsePrereqName(name) {
-  let taskArr = name.split('[');
-  let taskName = taskArr[0];
-  let taskArgs = [];
-  if (taskArr[1]) {
-    taskArgs = taskArr[1].replace(/\]$/, '');
-    taskArgs = taskArgs.split(',');
-  }
-  return {
-    name: taskName,
-    args: taskArgs
-  };
-}
-
-/**
-  @name jake.Task
-  @class
-  @extends EventEmitter
-  @description A Jake Task
-
-  @param {String} name The name of the Task
-  @param {Array} [prereqs] Prerequisites to be run before this task
-  @param {Function} [action] The action to perform for this task
-  @param {Object} [opts]
-    @param {Array} [opts.asyc=false] Perform this task asynchronously.
-    If you flag a task with this option, you must call the global
-    `complete` method inside the task's action, for execution to proceed
-    to the next task.
- */
-class Task extends EventEmitter {
-
-  constructor(name, prereqs, action, options) {
-    // EventEmitter ctor takes no args
-    super();
-
-    if (name.indexOf(':') > -1) {
-      throw new Error('Task name cannot include a colon. It is used internally as namespace delimiter.');
-    }
-    let opts = options || {};
-
-    this._currentPrereqIndex = 0;
-    this._internal = false;
-    this._skipped = false;
-
-    this.name = name;
-    this.prereqs = prereqs;
-    this.action = action;
-    this.async = false;
-    this.taskStatus = Task.runStatuses.UNSTARTED;
-    this.description = null;
-    this.args = [];
-    this.value = UNDEFINED_VALUE;
-    this.concurrency = 1;
-    this.startTime = null;
-    this.endTime = null;
-    this.directory = null;
-    this.namespace = null;
-
-    // Support legacy async-flag -- if not explicitly passed or falsy, will
-    // be set to empty-object
-    if (typeof opts == 'boolean' && opts === true) {
-      this.async = true;
-    }
-    else {
-      if (opts.async) {
-        this.async = true;
-      }
-      if (opts.concurrency) {
-        this.concurrency = opts.concurrency;
-      }
-    }
-
-    //Do a test on self dependencies for this task
-    if(Array.isArray(this.prereqs) && this.prereqs.indexOf(this.name) !== -1) {
-      throw new Error("Cannot use prereq " + this.name + " as a dependency of itself");
-    }
-  }
-
-  get fullName() {
-    return this._getFullName();
-  }
-
-  _initInvocationChain() {
-    // Legacy global invocation chain
-    jake._invocationChain.push(this);
-
-    // New root chain
-    if (!this._invocationChain) {
-      this._invocationChainRoot = true;
-      this._invocationChain = [];
-      if (jake.currentRunningTask) {
-        jake.currentRunningTask._waitForChains = jake.currentRunningTask._waitForChains || [];
-        jake.currentRunningTask._waitForChains.push(this._invocationChain);
-      }
-    }
-  }
-
-  /**
-    @name jake.Task#invoke
-    @function
-    @description Runs prerequisites, then this task. If the task has already
-    been run, will not run the task again.
-   */
-  invoke() {
-    this._initInvocationChain();
-
-    this.args = Array.prototype.slice.call(arguments);
-    this.reenabled = false
-    this.runPrereqs();
-  }
-
-  /**
-    @name jake.Task#execute
-    @function
-    @description Run only this task, without prereqs. If the task has already
-    been run, *will* run the task again.
-   */
-  execute() {
-    this._initInvocationChain();
-
-    this.args = Array.prototype.slice.call(arguments);
-    this.reenable();
-    this.reenabled = true
-    this.run();
-  }
-
-  runPrereqs() {
-    if (this.prereqs && this.prereqs.length) {
-
-      if (this.concurrency > 1) {
-        async.eachLimit(this.prereqs, this.concurrency,
-
-          (name, cb) => {
-            let parsed = parsePrereqName(name);
-
-            let prereq = this.namespace.resolveTask(parsed.name) ||
-          jake.attemptRule(name, this.namespace, 0) ||
-          jake.createPlaceholderFileTask(name, this.namespace);
-
-            if (!prereq) {
-              throw new Error('Unknown task "' + name + '"');
-            }
-
-            //Test for circular invocation
-            if(prereq === this) {
-              setImmediate(function () {
-                cb(new Error("Cannot use prereq " + prereq.name + " as a dependency of itself"));
-              });
-            }
-
-            if (prereq.taskStatus == Task.runStatuses.DONE) {
-            //prereq already done, return
-              setImmediate(cb);
-            }
-            else {
-            //wait for complete before calling cb
-              prereq.once('_done', () => {
-                prereq.removeAllListeners('_done');
-                setImmediate(cb);
-              });
-              // Start the prereq if we are the first to encounter it
-              if (prereq.taskStatus === Task.runStatuses.UNSTARTED) {
-                prereq.taskStatus = Task.runStatuses.STARTED;
-                prereq.invoke.apply(prereq, parsed.args);
-              }
-            }
-          },
-
-          (err) => {
-          //async callback is called after all prereqs have run.
-            if (err) {
-              throw err;
-            }
-            else {
-              setImmediate(this.run.bind(this));
-            }
-          }
-        );
-      }
-      else {
-        setImmediate(this.nextPrereq.bind(this));
-      }
-    }
-    else {
-      setImmediate(this.run.bind(this));
-    }
-  }
-
-  nextPrereq() {
-    let self = this;
-    let index = this._currentPrereqIndex;
-    let name = this.prereqs[index];
-    let prereq;
-    let parsed;
-
-    if (name) {
-
-      parsed = parsePrereqName(name);
-
-      prereq = this.namespace.resolveTask(parsed.name) ||
-          jake.attemptRule(name, this.namespace, 0) ||
-          jake.createPlaceholderFileTask(name, this.namespace);
-
-      if (!prereq) {
-        throw new Error('Unknown task "' + name + '"');
-      }
-
-      // Do when done
-      if (prereq.taskStatus == Task.runStatuses.DONE) {
-        self.handlePrereqDone(prereq);
-      }
-      else {
-        prereq.once('_done', () => {
-          this.handlePrereqDone(prereq);
-          prereq.removeAllListeners('_done');
-        });
-        if (prereq.taskStatus == Task.runStatuses.UNSTARTED) {
-          prereq.taskStatus = Task.runStatuses.STARTED;
-          prereq._invocationChain = this._invocationChain;
-          prereq.invoke.apply(prereq, parsed.args);
-        }
-      }
-    }
-  }
-
-  /**
-    @name jake.Task#reenable
-    @function
-    @description Reenables a task so that it can be run again.
-   */
-  reenable(deep) {
-    let prereqs;
-    let prereq;
-    this._skipped = false;
-    this.taskStatus = Task.runStatuses.UNSTARTED;
-    this.value = UNDEFINED_VALUE;
-    if (deep && this.prereqs) {
-      prereqs = this.prereqs;
-      for (let i = 0, ii = prereqs.length; i < ii; i++) {
-        prereq = jake.Task[prereqs[i]];
-        if (prereq) {
-          prereq.reenable(deep);
-        }
-      }
-    }
-  }
-
-  handlePrereqDone(prereq) {
-    this._currentPrereqIndex++;
-    if (this._currentPrereqIndex < this.prereqs.length) {
-      setImmediate(this.nextPrereq.bind(this));
-    }
-    else {
-      setImmediate(this.run.bind(this));
-    }
-  }
-
-  isNeeded() {
-    let needed = true;
-    if (this.taskStatus == Task.runStatuses.DONE) {
-      needed = false;
-    }
-    return needed;
-  }
-
-  run() {
-    let val, previous;
-    let hasAction = typeof this.action == 'function';
-
-    if (!this.isNeeded()) {
-      this.emit('skip');
-      this.emit('_done');
-    }
-    else {
-      if (this._invocationChain.length) {
-        previous = this._invocationChain[this._invocationChain.length - 1];
-        // If this task is repeating and its previous is equal to this, don't check its status because it was set to UNSTARTED by the reenable() method
-        if (!(this.reenabled && previous == this)) {
-          if (previous.taskStatus != Task.runStatuses.DONE) {
-            let now = (new Date()).getTime();
-            if (now - this.startTime > jake._taskTimeout) {
-              return jake.fail(`Timed out waiting for task: ${previous.name} with status of ${previous.taskStatus}`);
-            }
-            setTimeout(this.run.bind(this), POLLING_INTERVAL);
-            return;
-          }
-        }
-      }
-      if (!(this.reenabled && previous == this)) {
-        this._invocationChain.push(this);
-      }
-
-      if (!(this._internal || jake.program.opts.quiet)) {
-        console.log("Starting '" + chalk.green(this.fullName) + "'...");
-      }
-
-      this.startTime = (new Date()).getTime();
-      this.emit('start');
-
-      jake.currentRunningTask = this;
-
-      if (hasAction) {
-        try {
-          if (this.directory) {
-            process.chdir(this.directory);
-          }
-
-          val = this.action.apply(this, this.args);
-
-          if (typeof val == 'object' && typeof val.then == 'function') {
-            this.async = true;
-
-            val.then(
-              (result) => {
-                setImmediate(() => {
-                  this.complete(result);
-                });
-              },
-              (err) => {
-                setImmediate(() => {
-                  this.errorOut(err);
-                });
-              });
-          }
-        }
-        catch (err) {
-          this.errorOut(err);
-          return; // Bail out, not complete
-        }
-      }
-
-      if (!(hasAction && this.async)) {
-        setImmediate(() => {
-          this.complete(val);
-        });
-      }
-    }
-  }
-
-  errorOut(err) {
-    this.taskStatus = Task.runStatuses.ERROR;
-    this._invocationChain.chainStatus = Task.runStatuses.ERROR;
-    this.emit('error', err);
-  }
-
-  complete(val) {
-
-    if (Array.isArray(this._waitForChains)) {
-      let stillWaiting = this._waitForChains.some((chain) => {
-        return !(chain.chainStatus == Task.runStatuses.DONE ||
-              chain.chainStatus == Task.runStatuses.ERROR);
-      });
-      if (stillWaiting) {
-        let now = (new Date()).getTime();
-        let elapsed = now - this.startTime;
-        if (elapsed > jake._taskTimeout) {
-          return jake.fail(`Timed out waiting for task: ${this.name} with status of ${this.taskStatus}. Elapsed: ${elapsed}`);
-        }
-        setTimeout(() => {
-          this.complete(val);
-        }, POLLING_INTERVAL);
-        return;
-      }
-    }
-
-    jake._invocationChain.splice(jake._invocationChain.indexOf(this), 1);
-
-    if (this._invocationChainRoot) {
-      this._invocationChain.chainStatus = Task.runStatuses.DONE;
-    }
-
-    this._currentPrereqIndex = 0;
-
-    // If 'complete' getting called because task has been
-    // run already, value will not be passed -- leave in place
-    if (!this._skipped) {
-      this.taskStatus = Task.runStatuses.DONE;
-      this.value = val;
-
-      this.emit('complete', this.value);
-      this.emit('_done');
-
-      this.endTime = (new Date()).getTime();
-      let taskTime = this.endTime - this.startTime;
-
-      if (!(this._internal || jake.program.opts.quiet)) {
-        console.log("Finished '" + chalk.green(this.fullName) + "' after " + chalk.magenta(taskTime + ' ms'));
-      }
-
-    }
-  }
-
-  _getFullName() {
-    let ns = this.namespace;
-    let path = (ns && ns.path) || '';
-    path = (path && path.split(':')) || [];
-    if (this.namespace !== jake.defaultNamespace) {
-      path.push(this.namespace.name);
-    }
-    path.push(this.name);
-    return path.join(':');
-  }
-
-  static getBaseNamespacePath(fullName) {
-    return fullName.split(':').slice(0, -1).join(':');
-  }
-
-  static getBaseTaskName(fullName) {
-    return fullName.split(':').pop();
-  }
-}
-
-Task.runStatuses = {
-  UNSTARTED: 'unstarted',
-  DONE: 'done',
-  STARTED: 'started',
-  ERROR: 'error'
-};
-
-Task.ROOT_TASK_NAME = ROOT_TASK_NAME;
-
-exports.Task = Task;
-
-// Required here because circular deps
-require('../rule');
-
+let UNDEFINED_VALUE,EventEmitter=require("events").EventEmitter,async=require("async"),chalk=require("chalk");const ROOT_TASK_NAME="__rootTask__",POLLING_INTERVAL=100;function parsePrereqName(t){let e=t.split("["),s=e[0],i=[];return e[1]&&(i=e[1].replace(/\]$/,""),i=i.split(",")),{name:s,args:i}}class Task extends EventEmitter{constructor(t,e,s,i){if(super(),t.indexOf(":")>-1)throw new Error("Task name cannot include a colon. It is used internally as namespace delimiter.");let a=i||{};if(this._currentPrereqIndex=0,this._internal=!1,this._skipped=!1,this.name=t,this.prereqs=e,this.action=s,this.async=!1,this.taskStatus=Task.runStatuses.UNSTARTED,this.description=null,this.args=[],this.value=UNDEFINED_VALUE,this.concurrency=1,this.startTime=null,this.endTime=null,this.directory=null,this.namespace=null,"boolean"==typeof a&&!0===a?this.async=!0:(a.async&&(this.async=!0),a.concurrency&&(this.concurrency=a.concurrency)),Array.isArray(this.prereqs)&&-1!==this.prereqs.indexOf(this.name))throw new Error("Cannot use prereq "+this.name+" as a dependency of itself")}get fullName(){return this._getFullName()}_initInvocationChain(){jake._invocationChain.push(this),this._invocationChain||(this._invocationChainRoot=!0,this._invocationChain=[],jake.currentRunningTask&&(jake.currentRunningTask._waitForChains=jake.currentRunningTask._waitForChains||[],jake.currentRunningTask._waitForChains.push(this._invocationChain)))}invoke(){this._initInvocationChain(),this.args=Array.prototype.slice.call(arguments),this.reenabled=!1,this.runPrereqs()}execute(){this._initInvocationChain(),this.args=Array.prototype.slice.call(arguments),this.reenable(),this.reenabled=!0,this.run()}runPrereqs(){this.prereqs&&this.prereqs.length?this.concurrency>1?async.eachLimit(this.prereqs,this.concurrency,((t,e)=>{let s=parsePrereqName(t),i=this.namespace.resolveTask(s.name)||jake.attemptRule(t,this.namespace,0)||jake.createPlaceholderFileTask(t,this.namespace);if(!i)throw new Error('Unknown task "'+t+'"');i===this&&setImmediate((function(){e(new Error("Cannot use prereq "+i.name+" as a dependency of itself"))})),i.taskStatus==Task.runStatuses.DONE?setImmediate(e):(i.once("_done",(()=>{i.removeAllListeners("_done"),setImmediate(e)})),i.taskStatus===Task.runStatuses.UNSTARTED&&(i.taskStatus=Task.runStatuses.STARTED,i.invoke.apply(i,s.args)))}),(t=>{if(t)throw t;setImmediate(this.run.bind(this))})):setImmediate(this.nextPrereq.bind(this)):setImmediate(this.run.bind(this))}nextPrereq(){let t,e,s=this,i=this._currentPrereqIndex,a=this.prereqs[i];if(a){if(e=parsePrereqName(a),t=this.namespace.resolveTask(e.name)||jake.attemptRule(a,this.namespace,0)||jake.createPlaceholderFileTask(a,this.namespace),!t)throw new Error('Unknown task "'+a+'"');t.taskStatus==Task.runStatuses.DONE?s.handlePrereqDone(t):(t.once("_done",(()=>{this.handlePrereqDone(t),t.removeAllListeners("_done")})),t.taskStatus==Task.runStatuses.UNSTARTED&&(t.taskStatus=Task.runStatuses.STARTED,t._invocationChain=this._invocationChain,t.invoke.apply(t,e.args)))}}reenable(t){let e,s;if(this._skipped=!1,this.taskStatus=Task.runStatuses.UNSTARTED,this.value=UNDEFINED_VALUE,t&&this.prereqs){e=this.prereqs;for(let i=0,a=e.length;i<a;i++)s=jake.Task[e[i]],s&&s.reenable(t)}}handlePrereqDone(t){this._currentPrereqIndex++,this._currentPrereqIndex<this.prereqs.length?setImmediate(this.nextPrereq.bind(this)):setImmediate(this.run.bind(this))}isNeeded(){let t=!0;return this.taskStatus==Task.runStatuses.DONE&&(t=!1),t}run(){let t,e,s="function"==typeof this.action;if(this.isNeeded()){if(this._invocationChain.length&&(e=this._invocationChain[this._invocationChain.length-1],(!this.reenabled||e!=this)&&e.taskStatus!=Task.runStatuses.DONE)){return(new Date).getTime()-this.startTime>jake._taskTimeout?jake.fail(`Timed out waiting for task: ${e.name} with status of ${e.taskStatus}`):void setTimeout(this.run.bind(this),100)}if(this.reenabled&&e==this||this._invocationChain.push(this),this._internal||jake.program.opts.quiet||console.log("Starting '"+chalk.green(this.fullName)+"'..."),this.startTime=(new Date).getTime(),this.emit("start"),jake.currentRunningTask=this,s)try{this.directory&&process.chdir(this.directory),t=this.action.apply(this,this.args),"object"==typeof t&&"function"==typeof t.then&&(this.async=!0,t.then((t=>{setImmediate((()=>{this.complete(t)}))}),(t=>{setImmediate((()=>{this.errorOut(t)}))})))}catch(t){return void this.errorOut(t)}s&&this.async||setImmediate((()=>{this.complete(t)}))}else this.emit("skip"),this.emit("_done")}errorOut(t){this.taskStatus=Task.runStatuses.ERROR,this._invocationChain.chainStatus=Task.runStatuses.ERROR,this.emit("error",t)}complete(t){if(Array.isArray(this._waitForChains)){if(this._waitForChains.some((t=>!(t.chainStatus==Task.runStatuses.DONE||t.chainStatus==Task.runStatuses.ERROR)))){let e=(new Date).getTime()-this.startTime;return e>jake._taskTimeout?jake.fail(`Timed out waiting for task: ${this.name} with status of ${this.taskStatus}. Elapsed: ${e}`):void setTimeout((()=>{this.complete(t)}),100)}}if(jake._invocationChain.splice(jake._invocationChain.indexOf(this),1),this._invocationChainRoot&&(this._invocationChain.chainStatus=Task.runStatuses.DONE),this._currentPrereqIndex=0,!this._skipped){this.taskStatus=Task.runStatuses.DONE,this.value=t,this.emit("complete",this.value),this.emit("_done"),this.endTime=(new Date).getTime();let e=this.endTime-this.startTime;this._internal||jake.program.opts.quiet||console.log("Finished '"+chalk.green(this.fullName)+"' after "+chalk.magenta(e+" ms"))}}_getFullName(){let t=this.namespace,e=t&&t.path||"";return e=e&&e.split(":")||[],this.namespace!==jake.defaultNamespace&&e.push(this.namespace.name),e.push(this.name),e.join(":")}static getBaseNamespacePath(t){return t.split(":").slice(0,-1).join(":")}static getBaseTaskName(t){return t.split(":").pop()}}Task.runStatuses={UNSTARTED:"unstarted",DONE:"done",STARTED:"started",ERROR:"error"},Task.ROOT_TASK_NAME="__rootTask__",exports.Task=Task,require("../rule");
\ No newline at end of file
index 6482bf1..0da321f 100755 (executable)
@@ -1,270 +1 @@
-/*
- * Jake JavaScript build tool
- * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-*/
-
-let path = require('path');
-let currDir = process.cwd();
-
-/**
-  @name jake
-  @namespace jake
-*/
-/**
-  @name jake.TestTask
-  @constructor
-  @description Instantiating a TestTask creates a number of Jake
-  Tasks that make running tests for your software easy.
-
-  @param {String} name The name of the project
-  @param {Function} definition Defines the list of files containing the tests,
-  and the name of the namespace/task for running them. Will be executed on the
-  instantiated TestTask (i.e., 'this', will be the TestTask instance), to set
-  the various instance-propertiess.
-
-  @example
-  let t = new jake.TestTask('bij-js', function () {
-    this.testName = 'testSpecial';
-    this.testFiles.include('test/**');
-  });
-
- */
-let TestTask = function () {
-  let self = this;
-  let args = Array.prototype.slice.call(arguments);
-  let name = args.shift();
-  let definition = args.pop();
-  let prereqs = args.pop() || [];
-
-  /**
-    @name jake.TestTask#testNam
-    @public
-    @type {String}
-    @description The name of the namespace to place the tests in, and
-    the top-level task for running tests. Defaults to "test"
-   */
-  this.testName = 'test';
-
-  /**
-    @name jake.TestTask#testFiles
-    @public
-    @type {jake.FileList}
-    @description The list of files containing tests to load
-   */
-  this.testFiles = new jake.FileList();
-
-  /**
-    @name jake.TestTask#showDescription
-    @public
-    @type {Boolean}
-    @description Show the created task when doing Jake -T
-   */
-  this.showDescription = true;
-
-  /*
-    @name jake.TestTask#totalTests
-    @public
-    @type {Number}
-    @description The total number of tests to run
-  */
-  this.totalTests = 0;
-
-  /*
-    @name jake.TestTask#executedTests
-    @public
-    @type {Number}
-    @description The number of tests successfully run
-  */
-  this.executedTests = 0;
-
-  if (typeof definition == 'function') {
-    definition.call(this);
-  }
-
-  if (this.showDescription) {
-    desc('Run the tests for ' + name);
-  }
-
-  task(this.testName, prereqs, {async: true}, function () {
-    let t = jake.Task[this.fullName + ':run'];
-    t.on('complete', function () {
-      complete();
-    });
-    // Pass args to the namespaced test
-    t.invoke.apply(t, arguments);
-  });
-
-  namespace(self.testName, function () {
-
-    let runTask = task('run', {async: true}, function (pat) {
-      let re;
-      let testFiles;
-
-      // Don't nest; make a top-level namespace. Don't want
-      // re-calling from inside to nest infinitely
-      jake.currentNamespace = jake.defaultNamespace;
-
-      re = new RegExp(pat);
-      // Get test files that match the passed-in pattern
-      testFiles = self.testFiles.toArray()
-        .filter(function (f) {
-          return (re).test(f);
-        }) // Don't load the same file multiple times -- should this be in FileList?
-        .reduce(function (p, c) {
-          if (p.indexOf(c) < 0) {
-            p.push(c);
-          }
-          return p;
-        }, []);
-
-      // Create a namespace for all the testing tasks to live in
-      namespace(self.testName + 'Exec', function () {
-        // Each test will be a prereq for the dummy top-level task
-        let prereqs = [];
-        // Continuation to pass to the async tests, wrapping `continune`
-        let next = function () {
-          complete();
-        };
-        // Create the task for this test-function
-        let createTask = function (name, action) {
-          // If the test-function is defined with a continuation
-          // param, flag the task as async
-          let t;
-          let isAsync = !!action.length;
-
-          // Define the actual namespaced task with the name, the
-          // wrapped action, and the correc async-flag
-          t = task(name, createAction(name, action), {
-            async: isAsync
-          });
-          t.once('complete', function () {
-            self.executedTests++;
-          });
-          t._internal = true;
-          return t;
-        };
-        // Used as the action for the defined task for each test.
-        let createAction = function (n, a) {
-          // A wrapped function that passes in the `next` function
-          // for any tasks that run asynchronously
-          return function () {
-            let cb;
-            if (a.length) {
-              cb = next;
-            }
-            if (!(n == 'before' || n == 'after' ||
-                    /_beforeEach$/.test(n) || /_afterEach$/.test(n))) {
-              jake.logger.log(n);
-            }
-            // 'this' will be the task when action is run
-            return a.call(this, cb);
-          };
-        };
-          // Dummy top-level task for everything to be prereqs for
-        let topLevel;
-
-        // Pull in each test-file, and iterate over any exported
-        // test-functions. Register each test-function as a prereq task
-        testFiles.forEach(function (file) {
-          let exp = require(path.join(currDir, file));
-
-          // Create a namespace for each filename, so test-name collisions
-          // won't be a problem
-          namespace(file, function () {
-            let testPrefix = self.testName + 'Exec:' + file + ':';
-            let testName;
-            // Dummy task for displaying file banner
-            testName = '*** Running ' + file + ' ***';
-            prereqs.push(testPrefix + testName);
-            createTask(testName, function () {});
-
-            // 'before' setup
-            if (typeof exp.before == 'function') {
-              prereqs.push(testPrefix + 'before');
-              // Create the task
-              createTask('before', exp.before);
-            }
-
-            // Walk each exported function, and create a task for each
-            for (let p in exp) {
-              if (p == 'before' || p == 'after' ||
-                  p == 'beforeEach' || p == 'afterEach') {
-                continue;
-              }
-
-              if (typeof exp.beforeEach == 'function') {
-                prereqs.push(testPrefix + p + '_beforeEach');
-                // Create the task
-                createTask(p + '_beforeEach', exp.beforeEach);
-              }
-
-              // Add the namespace:name of this test to the list of prereqs
-              // for the dummy top-level task
-              prereqs.push(testPrefix + p);
-              // Create the task
-              createTask(p, exp[p]);
-
-              if (typeof exp.afterEach == 'function') {
-                prereqs.push(testPrefix + p + '_afterEach');
-                // Create the task
-                createTask(p + '_afterEach', exp.afterEach);
-              }
-            }
-
-            // 'after' teardown
-            if (typeof exp.after == 'function') {
-              prereqs.push(testPrefix + 'after');
-              // Create the task
-              let afterTask = createTask('after', exp.after);
-              afterTask._internal = true;
-            }
-
-          });
-        });
-
-        self.totalTests = prereqs.length;
-        process.on('exit', function () {
-          // Throw in the case where the process exits without
-          // finishing tests, but no error was thrown
-          if (!jake.errorCode && (self.totalTests > self.executedTests)) {
-            throw new Error('Process exited without all tests completing.');
-          }
-        });
-
-        // Create the dummy top-level task. When calling a task internally
-        // with `invoke` that is async (or has async prereqs), have to listen
-        // for the 'complete' event to know when it's done
-        topLevel = task('__top__', prereqs);
-        topLevel._internal = true;
-        topLevel.addListener('complete', function () {
-          jake.logger.log('All tests ran successfully');
-          complete();
-        });
-
-        topLevel.invoke(); // Do the thing!
-      });
-
-    });
-    runTask._internal = true;
-
-  });
-
-
-};
-
-jake.TestTask = TestTask;
-exports.TestTask = TestTask;
-
+let path=require("path"),currDir=process.cwd(),TestTask=function(){let e=this,t=Array.prototype.slice.call(arguments),n=t.shift(),s=t.pop(),a=t.pop()||[];this.testName="test",this.testFiles=new jake.FileList,this.showDescription=!0,this.totalTests=0,this.executedTests=0,"function"==typeof s&&s.call(this),this.showDescription&&desc("Run the tests for "+n),task(this.testName,a,{async:!0},(function(){let e=jake.Task[this.fullName+":run"];e.on("complete",(function(){complete()})),e.invoke.apply(e,arguments)})),namespace(e.testName,(function(){task("run",{async:!0},(function(t){let n,s;jake.currentNamespace=jake.defaultNamespace,n=new RegExp(t),s=e.testFiles.toArray().filter((function(e){return n.test(e)})).reduce((function(e,t){return e.indexOf(t)<0&&e.push(t),e}),[]),namespace(e.testName+"Exec",(function(){let t,n=[],a=function(){complete()},o=function(t,n){let s,a=!!n.length;return s=task(t,r(t,n),{async:a}),s.once("complete",(function(){e.executedTests++})),s._internal=!0,s},r=function(e,t){return function(){let n;return t.length&&(n=a),"before"==e||"after"==e||/_beforeEach$/.test(e)||/_afterEach$/.test(e)||jake.logger.log(e),t.call(this,n)}};s.forEach((function(t){let s=require(path.join(currDir,t));namespace(t,(function(){let a,r=e.testName+"Exec:"+t+":";a="*** Running "+t+" ***",n.push(r+a),o(a,(function(){})),"function"==typeof s.before&&(n.push(r+"before"),o("before",s.before));for(let e in s)"before"!=e&&"after"!=e&&"beforeEach"!=e&&"afterEach"!=e&&("function"==typeof s.beforeEach&&(n.push(r+e+"_beforeEach"),o(e+"_beforeEach",s.beforeEach)),n.push(r+e),o(e,s[e]),"function"==typeof s.afterEach&&(n.push(r+e+"_afterEach"),o(e+"_afterEach",s.afterEach)));if("function"==typeof s.after){n.push(r+"after"),o("after",s.after)._internal=!0}}))})),e.totalTests=n.length,process.on("exit",(function(){if(!jake.errorCode&&e.totalTests>e.executedTests)throw new Error("Process exited without all tests completing.")})),t=task("__top__",n),t._internal=!0,t.addListener("complete",(function(){jake.logger.log("All tests ran successfully"),complete()})),t.invoke()}))}))._internal=!0}))};jake.TestTask=TestTask,exports.TestTask=TestTask;
\ No newline at end of file
index a436def..a7eeafe 100755 (executable)
@@ -1,286 +1 @@
-/*
- * Utilities: A classic collection of JavaScript utilities
- * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-*/
-
-let fs = require('fs');
-let path = require('path');
-
-/**
-  @name file
-  @namespace file
-*/
-
-let fileUtils = new (function () {
-
-  // Recursively copy files and directories
-  let _copyFile = function (fromPath, toPath, opts) {
-    let from = path.normalize(fromPath)
-    let to = path.normalize(toPath)
-    let options = opts || {}
-    let fromStat;
-    let toStat;
-    let destExists;
-    let destDoesNotExistErr;
-    let content;
-    let filename;
-    let dirContents;
-    let targetDir;
-
-    fromStat = fs.statSync(from);
-
-    try {
-      //console.dir(to + ' destExists');
-      toStat = fs.statSync(to);
-      destExists = true;
-    }
-    catch(e) {
-      //console.dir(to + ' does not exist');
-      destDoesNotExistErr = e;
-      destExists = false;
-    }
-    // Destination dir or file exists, copy into (directory)
-    // or overwrite (file)
-    if (destExists) {
-
-      // If there's a rename-via-copy file/dir name passed, use it.
-      // Otherwise use the actual file/dir name
-      filename = options.rename || path.basename(from);
-
-      // Copying a directory
-      if (fromStat.isDirectory()) {
-        dirContents = fs.readdirSync(from);
-        targetDir = path.join(to, filename);
-        // We don't care if the target dir already exists
-        try {
-          fs.mkdirSync(targetDir, {mode: fromStat.mode & 0o777});
-        }
-        catch(e) {
-          if (e.code !== 'EEXIST') {
-            throw e;
-          }
-        }
-        for (let i = 0, ii = dirContents.length; i < ii; i++) {
-          _copyFile(path.join(from, dirContents[i]), targetDir, {preserveMode: options.preserveMode});
-        }
-      }
-      // Copying a file
-      else {
-        content = fs.readFileSync(from);
-        let mode = fromStat.mode & 0o777;
-        let targetFile = to;
-
-        if (toStat.isDirectory()) {
-          targetFile = path.join(to, filename);
-        }
-
-        let fileExists = fs.existsSync(targetFile);
-        fs.writeFileSync(targetFile, content);
-
-        // If the file didn't already exist, use the original file mode.
-        // Otherwise, only update the mode if preserverMode is true.
-        if(!fileExists || options.preserveMode) {
-          fs.chmodSync(targetFile, mode);
-        }
-      }
-    }
-    // Dest doesn't exist, can't create it
-    else {
-      throw destDoesNotExistErr;
-    }
-  };
-
-  // Remove the given directory
-  let _rmDir = function (dirPath) {
-    let dir = path.normalize(dirPath);
-    let paths = [];
-    paths = fs.readdirSync(dir);
-    paths.forEach(function (p) {
-      let curr = path.join(dir, p);
-      let stat = fs.lstatSync(curr);
-      if (stat.isDirectory()) {
-        _rmDir(curr);
-      }
-      else {
-        try {
-          fs.unlinkSync(curr);
-        } catch(e) {
-          if (e.code === 'EPERM') {
-            fs.chmodSync(curr, parseInt(666, 8));
-            fs.unlinkSync(curr);
-          } else {
-            throw e;
-          }
-        }
-      }
-    });
-    fs.rmdirSync(dir);
-  };
-
-  /**
-    @name file#cpR
-    @public
-    @function
-    @description Copies a directory/file to a destination
-    @param {String} fromPath The source path to copy from
-    @param {String} toPath The destination path to copy to
-    @param {Object} opts Options to use
-      @param {Boolean} [opts.preserveMode] If target file already exists, this
-        determines whether the original file's mode is copied over. The default of
-        false mimics the behavior of the `cp` command line tool. (Default: false)
-  */
-  this.cpR = function (fromPath, toPath, options) {
-    let from = path.normalize(fromPath);
-    let to = path.normalize(toPath);
-    let toStat;
-    let doesNotExistErr;
-    let filename;
-    let opts = options || {};
-
-    if (from == to) {
-      throw new Error('Cannot copy ' + from + ' to itself.');
-    }
-
-    // Handle rename-via-copy
-    try {
-      toStat = fs.statSync(to);
-    }
-    catch(e) {
-      doesNotExistErr = e;
-
-      // Get abs path so it's possible to check parent dir
-      if (!this.isAbsolute(to)) {
-        to = path.join(process.cwd(), to);
-      }
-
-      // Save the file/dir name
-      filename = path.basename(to);
-      // See if a parent dir exists, so there's a place to put the
-      /// renamed file/dir (resets the destination for the copy)
-      to = path.dirname(to);
-      try {
-        toStat = fs.statSync(to);
-      }
-      catch(e) {}
-      if (toStat && toStat.isDirectory()) {
-        // Set the rename opt to pass to the copy func, will be used
-        // as the new file/dir name
-        opts.rename = filename;
-        //console.log('filename ' + filename);
-      }
-      else {
-        throw doesNotExistErr;
-      }
-    }
-
-    _copyFile(from, to, opts);
-  };
-
-  /**
-    @name file#mkdirP
-    @public
-    @function
-    @description Create the given directory(ies) using the given mode permissions
-    @param {String} dir The directory to create
-    @param {Number} mode The mode to give the created directory(ies)(Default: 0755)
-  */
-  this.mkdirP = function (dir, mode) {
-    let dirPath = path.normalize(dir);
-    let paths = dirPath.split(/\/|\\/);
-    let currPath = '';
-    let next;
-
-    if (paths[0] == '' || /^[A-Za-z]+:/.test(paths[0])) {
-      currPath = paths.shift() || '/';
-      currPath = path.join(currPath, paths.shift());
-      //console.log('basedir');
-    }
-    while ((next = paths.shift())) {
-      if (next == '..') {
-        currPath = path.join(currPath, next);
-        continue;
-      }
-      currPath = path.join(currPath, next);
-      try {
-        //console.log('making ' + currPath);
-        fs.mkdirSync(currPath, mode || parseInt(755, 8));
-      }
-      catch(e) {
-        if (e.code != 'EEXIST') {
-          throw e;
-        }
-      }
-    }
-  };
-
-  /**
-    @name file#rmRf
-    @public
-    @function
-    @description Deletes the given directory/file
-    @param {String} p The path to delete, can be a directory or file
-  */
-  this.rmRf = function (p, options) {
-    let stat;
-    try {
-      stat = fs.lstatSync(p);
-      if (stat.isDirectory()) {
-        _rmDir(p);
-      }
-      else {
-        fs.unlinkSync(p);
-      }
-    }
-    catch (e) {}
-  };
-
-  /**
-    @name file#isAbsolute
-    @public
-    @function
-    @return {Boolean/String} If it's absolute the first character is returned otherwise false
-    @description Checks if a given path is absolute or relative
-    @param {String} p Path to check
-  */
-  this.isAbsolute = function (p) {
-    let match = /^[A-Za-z]+:\\|^\//.exec(p);
-    if (match && match.length) {
-      return match[0];
-    }
-    return false;
-  };
-
-  /**
-    @name file#absolutize
-    @public
-    @function
-    @return {String} Returns the absolute path for the given path
-    @description Returns the absolute path for the given path
-    @param {String} p The path to get the absolute path for
-  */
-  this.absolutize = function (p) {
-    if (this.isAbsolute(p)) {
-      return p;
-    }
-    else {
-      return path.join(process.cwd(), p);
-    }
-  };
-
-})();
-
-module.exports = fileUtils;
-
+let fs=require("fs"),path=require("path"),fileUtils=new function(){let t=function(e,i,n){let s,r,o,c,a,f,h,l,y=path.normalize(e),p=path.normalize(i),d=n||{};s=fs.statSync(y);try{r=fs.statSync(p),o=!0}catch(t){c=t,o=!1}if(!o)throw c;if(f=d.rename||path.basename(y),s.isDirectory()){h=fs.readdirSync(y),l=path.join(p,f);try{fs.mkdirSync(l,{mode:511&s.mode})}catch(t){if("EEXIST"!==t.code)throw t}for(let e=0,i=h.length;e<i;e++)t(path.join(y,h[e]),l,{preserveMode:d.preserveMode})}else{a=fs.readFileSync(y);let t=511&s.mode,e=p;r.isDirectory()&&(e=path.join(p,f));let i=fs.existsSync(e);fs.writeFileSync(e,a),i&&!d.preserveMode||fs.chmodSync(e,t)}},e=function(t){let i=path.normalize(t),n=[];n=fs.readdirSync(i),n.forEach((function(t){let n=path.join(i,t);if(fs.lstatSync(n).isDirectory())e(n);else try{fs.unlinkSync(n)}catch(t){if("EPERM"!==t.code)throw t;fs.chmodSync(n,parseInt(666,8)),fs.unlinkSync(n)}})),fs.rmdirSync(i)};this.cpR=function(e,i,n){let s,r,o,c=path.normalize(e),a=path.normalize(i),f=n||{};if(c==a)throw new Error("Cannot copy "+c+" to itself.");try{s=fs.statSync(a)}catch(t){r=t,this.isAbsolute(a)||(a=path.join(process.cwd(),a)),o=path.basename(a),a=path.dirname(a);try{s=fs.statSync(a)}catch(t){}if(!s||!s.isDirectory())throw r;f.rename=o}t(c,a,f)},this.mkdirP=function(t,e){let i,n=path.normalize(t).split(/\/|\\/),s="";for((""==n[0]||/^[A-Za-z]+:/.test(n[0]))&&(s=n.shift()||"/",s=path.join(s,n.shift()));i=n.shift();)if(".."!=i){s=path.join(s,i);try{fs.mkdirSync(s,e||parseInt(755,8))}catch(t){if("EEXIST"!=t.code)throw t}}else s=path.join(s,i)},this.rmRf=function(t,i){let n;try{n=fs.lstatSync(t),n.isDirectory()?e(t):fs.unlinkSync(t)}catch(t){}},this.isAbsolute=function(t){let e=/^[A-Za-z]+:\\|^\//.exec(t);return!(!e||!e.length)&&e[0]},this.absolutize=function(t){return this.isAbsolute(t)?t:path.join(process.cwd(),t)}};module.exports=fileUtils;
\ No newline at end of file
index 17d686b..eaa4d5a 100755 (executable)
@@ -1,297 +1 @@
-/*
- * Jake JavaScript build tool
- * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-*/
-
-
-let util = require('util'); // Native Node util module
-let spawn = require('child_process').spawn;
-let EventEmitter = require('events').EventEmitter;
-let logger = require('./logger');
-let file = require('./file');
-let Exec;
-
-const _UUID_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
-
-let parseArgs = function (argumentsObj) {
-  let args;
-  let arg;
-  let cmds;
-  let callback;
-  let opts = {
-    interactive: false,
-    printStdout: false,
-    printStderr: false,
-    breakOnError: true
-  };
-
-  args = Array.prototype.slice.call(argumentsObj);
-
-  cmds = args.shift();
-  // Arrayize if passed a single string command
-  if (typeof cmds == 'string') {
-    cmds = [cmds];
-  }
-  // Make a copy if it's an actual list
-  else {
-    cmds = cmds.slice();
-  }
-
-  // Get optional callback or opts
-  while((arg = args.shift())) {
-    if (typeof arg == 'function') {
-      callback = arg;
-    }
-    else if (typeof arg == 'object') {
-      opts = Object.assign(opts, arg);
-    }
-  }
-
-  // Backward-compat shim
-  if (typeof opts.stdout != 'undefined') {
-    opts.printStdout = opts.stdout;
-    delete opts.stdout;
-  }
-  if (typeof opts.stderr != 'undefined') {
-    opts.printStderr = opts.stderr;
-    delete opts.stderr;
-  }
-
-  return {
-    cmds: cmds,
-    opts: opts,
-    callback: callback
-  };
-};
-
-/**
-  @name jake
-  @namespace jake
-*/
-let utils = new (function () {
-  /**
-    @name jake.exec
-    @static
-    @function
-    @description Executes shell-commands asynchronously with an optional
-    final callback.
-    `
-    @param {String[]} cmds The list of shell-commands to execute
-    @param {Object} [opts]
-      @param {Boolean} [opts.printStdout=false] Print stdout from each command
-      @param {Boolean} [opts.printStderr=false] Print stderr from each command
-      @param {Boolean} [opts.breakOnError=true] Stop further execution on
-      the first error.
-      @param {Boolean} [opts.windowsVerbatimArguments=false] Don't translate
-      arguments on Windows.
-    @param {Function} [callback] Callback to run after executing  the
-    commands
-
-    @example
-    let cmds = [
-          'echo "showing directories"'
-        , 'ls -al | grep ^d'
-        , 'echo "moving up a directory"'
-        , 'cd ../'
-        ]
-      , callback = function () {
-          console.log('Finished running commands.');
-        }
-    jake.exec(cmds, {stdout: true}, callback);
-   */
-  this.exec = function (a, b, c) {
-    let parsed = parseArgs(arguments);
-    let cmds = parsed.cmds;
-    let opts = parsed.opts;
-    let callback = parsed.callback;
-
-    let ex = new Exec(cmds, opts, callback);
-
-    ex.addListener('error', function (msg, code) {
-      if (opts.breakOnError) {
-        fail(msg, code);
-      }
-    });
-    ex.run();
-
-    return ex;
-  };
-
-  this.createExec = function (a, b, c) {
-    return new Exec(a, b, c);
-  };
-
-  // From Math.uuid.js, https://github.com/broofa/node-uuid
-  // Robert Kieffer (robert@broofa.com), MIT license
-  this.uuid = function (length, radix) {
-    var chars = _UUID_CHARS
-      , uuid = []
-      , r
-      , i;
-
-    radix = radix || chars.length;
-
-    if (length) {
-      // Compact form
-      i = -1;
-      while (++i < length) {
-        uuid[i] = chars[0 | Math.random()*radix];
-      }
-    } else {
-      // rfc4122, version 4 form
-
-      // rfc4122 requires these characters
-      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
-      uuid[14] = '4';
-
-      // Fill in random data.  At i==19 set the high bits of clock sequence as
-      // per rfc4122, sec. 4.1.5
-      i = -1;
-      while (++i < 36) {
-        if (!uuid[i]) {
-          r = 0 | Math.random()*16;
-          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
-        }
-      }
-    }
-
-    return uuid.join('');
-  };
-
-})();
-
-Exec = function () {
-  let parsed = parseArgs(arguments);
-  let cmds = parsed.cmds;
-  let opts = parsed.opts;
-  let callback = parsed.callback;
-
-  this._cmds = cmds;
-  this._callback = callback;
-  this._config = opts;
-};
-
-util.inherits(Exec, EventEmitter);
-
-Object.assign(Exec.prototype, new (function () {
-
-  let _run = function () {
-    let self = this;
-    let sh;
-    let cmd;
-    let args;
-    let next = this._cmds.shift();
-    let config = this._config;
-    let errData = '';
-    let shStdio;
-    let handleStdoutData = function (data) {
-      self.emit('stdout', data);
-    };
-    let handleStderrData = function (data) {
-      let d = data.toString();
-      self.emit('stderr', data);
-      // Accumulate the error-data so we can use it as the
-      // stack if the process exits with an error
-      errData += d;
-    };
-
-    // Keep running as long as there are commands in the array
-    if (next) {
-      let spawnOpts = {};
-      this.emit('cmdStart', next);
-
-      // Ganking part of Node's child_process.exec to get cmdline args parsed
-      if (process.platform == 'win32') {
-        cmd = 'cmd';
-        args = ['/c', next];
-        if (config.windowsVerbatimArguments) {
-          spawnOpts.windowsVerbatimArguments = true;
-        }
-      }
-      else {
-        cmd = '/bin/sh';
-        args = ['-c', next];
-      }
-
-      if (config.interactive) {
-        spawnOpts.stdio = 'inherit';
-        sh = spawn(cmd, args, spawnOpts);
-      }
-      else {
-        shStdio = [
-          process.stdin
-        ];
-        if (config.printStdout) {
-          shStdio.push(process.stdout);
-        }
-        else {
-          shStdio.push('pipe');
-        }
-        if (config.printStderr) {
-          shStdio.push(process.stderr);
-        }
-        else {
-          shStdio.push('pipe');
-        }
-        spawnOpts.stdio = shStdio;
-        sh = spawn(cmd, args, spawnOpts);
-        if (!config.printStdout) {
-          sh.stdout.addListener('data', handleStdoutData);
-        }
-        if (!config.printStderr) {
-          sh.stderr.addListener('data', handleStderrData);
-        }
-      }
-
-      // Exit, handle err or run next
-      sh.on('exit', function (code) {
-        let msg;
-        if (code !== 0) {
-          msg = errData || 'Process exited with error.';
-          msg = msg.trim();
-          self.emit('error', msg, code);
-        }
-        if (code === 0 || !config.breakOnError) {
-          self.emit('cmdEnd', next);
-          setTimeout(function () { _run.call(self); }, 0);
-        }
-      });
-
-    }
-    else {
-      self.emit('end');
-      if (typeof self._callback == 'function') {
-        self._callback();
-      }
-    }
-  };
-
-  this.append = function (cmd) {
-    this._cmds.push(cmd);
-  };
-
-  this.run = function () {
-    _run.call(this);
-  };
-
-})());
-
-utils.Exec = Exec;
-utils.file = file;
-utils.logger = logger;
-
-module.exports = utils;
-
+let Exec,util=require("util"),spawn=require("child_process").spawn,EventEmitter=require("events").EventEmitter,logger=require("./logger"),file=require("./file");const _UUID_CHARS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");let parseArgs=function(t){let e,r,i,s,n={interactive:!1,printStdout:!1,printStderr:!1,breakOnError:!0};for(e=Array.prototype.slice.call(t),i=e.shift(),i="string"==typeof i?[i]:i.slice();r=e.shift();)"function"==typeof r?s=r:"object"==typeof r&&(n=Object.assign(n,r));return void 0!==n.stdout&&(n.printStdout=n.stdout,delete n.stdout),void 0!==n.stderr&&(n.printStderr=n.stderr,delete n.stderr),{cmds:i,opts:n,callback:s}},utils=new function(){this.exec=function(t,e,r){let i=parseArgs(arguments),s=i.cmds,n=i.opts,o=i.callback,c=new Exec(s,n,o);return c.addListener("error",(function(t,e){n.breakOnError&&fail(t,e)})),c.run(),c},this.createExec=function(t,e,r){return new Exec(t,e,r)},this.uuid=function(t,e){var r,i,s=_UUID_CHARS,n=[];if(e=e||s.length,t)for(i=-1;++i<t;)n[i]=s[0|Math.random()*e];else for(n[8]=n[13]=n[18]=n[23]="-",n[14]="4",i=-1;++i<36;)n[i]||(r=0|16*Math.random(),n[i]=s[19==i?3&r|8:r]);return n.join("")}};Exec=function(){let t=parseArgs(arguments),e=t.cmds,r=t.opts,i=t.callback;this._cmds=e,this._callback=i,this._config=r},util.inherits(Exec,EventEmitter),Object.assign(Exec.prototype,new function(){let t=function(){let e,r,i,s,n=this,o=this._cmds.shift(),c=this._config,u="",l=function(t){n.emit("stdout",t)},d=function(t){let e=t.toString();n.emit("stderr",t),u+=e};if(o){let a={};this.emit("cmdStart",o),"win32"==process.platform?(r="cmd",i=["/c",o],c.windowsVerbatimArguments&&(a.windowsVerbatimArguments=!0)):(r="/bin/sh",i=["-c",o]),c.interactive?(a.stdio="inherit",e=spawn(r,i,a)):(s=[process.stdin],c.printStdout?s.push(process.stdout):s.push("pipe"),c.printStderr?s.push(process.stderr):s.push("pipe"),a.stdio=s,e=spawn(r,i,a),c.printStdout||e.stdout.addListener("data",l),c.printStderr||e.stderr.addListener("data",d)),e.on("exit",(function(e){let r;0!==e&&(r=u||"Process exited with error.",r=r.trim(),n.emit("error",r,e)),0!==e&&c.breakOnError||(n.emit("cmdEnd",o),setTimeout((function(){t.call(n)}),0))}))}else n.emit("end"),"function"==typeof n._callback&&n._callback()};this.append=function(t){this._cmds.push(t)},this.run=function(){t.call(this)}}),utils.Exec=Exec,utils.file=file,utils.logger=logger,module.exports=utils;
\ No newline at end of file
index 8f72686..b6dc11b 100755 (executable)
@@ -1,24 +1 @@
-let util = require('util');
-
-let logger = new (function () {
-  let _output = function (type, out) {
-    let quiet = typeof jake != 'undefined' && jake.program &&
-        jake.program.opts && jake.program.opts.quiet;
-    let msg;
-    if (!quiet) {
-      msg = typeof out == 'string' ? out : util.inspect(out);
-      console[type](msg);
-    }
-  };
-
-  this.log = function (out) {
-    _output('log', out);
-  };
-
-  this.error = function (out) {
-    _output('error', out);
-  };
-
-})();
-
-module.exports = logger;
+let util=require("util"),logger=new function(){let e=function(e,o){let t;"undefined"!=typeof jake&&jake.program&&jake.program.opts&&jake.program.opts.quiet||(t="string"==typeof o?o:util.inspect(o),console[e](t))};this.log=function(o){e("log",o)},this.error=function(o){e("error",o)}};module.exports=logger;
\ No newline at end of file
index 4ae41e8..b80b897 100755 (executable)
@@ -1,42 +1 @@
-let assert = require('assert');
-let exec = require('child_process').execSync;
-
-suite('concurrent', function () {
-
-  this.timeout(7000);
-
-  test(' simple concurrent prerequisites 1', function () {
-    let out = exec('./node_modules/.bin/jake -q concurrent:simple1').toString().trim()
-    assert.equal('Started A\nStarted B\nFinished B\nFinished A', out);
-  });
-
-  test(' simple concurrent prerequisites 2', function () {
-    let out = exec('./node_modules/.bin/jake -q concurrent:simple2').toString().trim()
-    assert.equal('Started C\nStarted D\nFinished C\nFinished D', out);
-  });
-
-  test(' sequential concurrent prerequisites', function () {
-    let out = exec('./node_modules/.bin/jake -q concurrent:seqconcurrent').toString().trim()
-    assert.equal('Started A\nStarted B\nFinished B\nFinished A\nStarted C\nStarted D\nFinished C\nFinished D', out);
-  });
-
-  test(' concurrent concurrent prerequisites', function () {
-    let out = exec('./node_modules/.bin/jake -q concurrent:concurrentconcurrent').toString().trim()
-    assert.equal('Started A\nStarted B\nStarted C\nStarted D\nFinished B\nFinished C\nFinished A\nFinished D', out);
-  });
-
-  test(' concurrent prerequisites with subdependency', function () {
-    let out = exec('./node_modules/.bin/jake -q concurrent:subdep').toString().trim()
-    assert.equal('Started A\nFinished A\nStarted Ba\nFinished Ba', out);
-  });
-
-  test(' failing in concurrent prerequisites', function () {
-    try {
-      exec('./node_modules/.bin/jake -q concurrent:Cfail');
-    }
-    catch(err) {
-      assert(err.message.indexOf('Command failed') > -1);
-    }
-  });
-
-});
+let assert=require("assert"),exec=require("child_process").execSync;suite("concurrent",(function(){this.timeout(7e3),test(" simple concurrent prerequisites 1",(function(){let e=exec("./node_modules/.bin/jake -q concurrent:simple1").toString().trim();assert.equal("Started A\nStarted B\nFinished B\nFinished A",e)})),test(" simple concurrent prerequisites 2",(function(){let e=exec("./node_modules/.bin/jake -q concurrent:simple2").toString().trim();assert.equal("Started C\nStarted D\nFinished C\nFinished D",e)})),test(" sequential concurrent prerequisites",(function(){let e=exec("./node_modules/.bin/jake -q concurrent:seqconcurrent").toString().trim();assert.equal("Started A\nStarted B\nFinished B\nFinished A\nStarted C\nStarted D\nFinished C\nFinished D",e)})),test(" concurrent concurrent prerequisites",(function(){let e=exec("./node_modules/.bin/jake -q concurrent:concurrentconcurrent").toString().trim();assert.equal("Started A\nStarted B\nStarted C\nStarted D\nFinished B\nFinished C\nFinished A\nFinished D",e)})),test(" concurrent prerequisites with subdependency",(function(){let e=exec("./node_modules/.bin/jake -q concurrent:subdep").toString().trim();assert.equal("Started A\nFinished A\nStarted Ba\nFinished Ba",e)})),test(" failing in concurrent prerequisites",(function(){try{exec("./node_modules/.bin/jake -q concurrent:Cfail")}catch(e){assert(e.message.indexOf("Command failed")>-1)}}))}));
\ No newline at end of file
index 97ed0d6..ea2a4e2 100755 (executable)
@@ -1,228 +1 @@
-/*
- * Jake JavaScript build tool
- * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-*/
-
-const PROJECT_DIR = process.env.PROJECT_DIR;
-
-let assert = require('assert');
-let fs = require('fs');
-let path = require('path');
-let file = require(`${PROJECT_DIR}/lib/utils/file`);
-let existsSync = fs.existsSync || path.existsSync;
-let exec = require('child_process').execSync;
-
-suite('fileUtils', function () {
-
-  test('mkdirP', function () {
-    let expected = [
-      ['foo'],
-      ['foo', 'bar'],
-      ['foo', 'bar', 'baz'],
-      ['foo', 'bar', 'baz', 'qux']
-    ];
-    file.mkdirP('foo/bar/baz/qux');
-    let res = exec('find foo').toString().trim().split('\n');
-    for (let i = 0, ii = res.length; i < ii; i++) {
-      assert.equal(path.join.apply(path, expected[i]), res[i]);
-    }
-    file.rmRf('foo');
-  });
-
-  test('rmRf', function () {
-    file.mkdirP('foo/bar/baz/qux');
-    file.rmRf('foo/bar');
-    let res = exec('find foo').toString().trim().split('\n');
-    assert.equal(1, res.length);
-    assert.equal('foo', res[0]);
-    fs.rmdirSync('foo');
-  });
-
-  test('rmRf with symlink subdir', function () {
-    file.mkdirP('foo');
-    file.mkdirP('bar');
-    fs.writeFileSync('foo/hello.txt', 'hello, it\'s me');
-    fs.symlinkSync('../foo', 'bar/foo'); file.rmRf('bar');
-
-    // Make sure the bar directory was successfully deleted
-    let barDeleted = false;
-    try {
-      fs.statSync('bar');
-    } catch(err) {
-      if(err.code == 'ENOENT') {
-        barDeleted = true;
-      }
-    }
-    assert.equal(true, barDeleted);
-
-    // Make sure that the file inside the linked folder wasn't deleted
-    let res = fs.readdirSync('foo');
-    assert.equal(1, res.length);
-    assert.equal('hello.txt', res[0]);
-
-    // Cleanup
-    fs.unlinkSync('foo/hello.txt');
-    fs.rmdirSync('foo');
-  });
-
-  test('rmRf with symlinked dir', function () {
-    file.mkdirP('foo');
-    fs.writeFileSync('foo/hello.txt', 'hello!');
-    fs.symlinkSync('foo', 'bar');
-    file.rmRf('bar');
-
-    // Make sure the bar directory was successfully deleted
-    let barDeleted = false;
-    try {
-      fs.statSync('bar');
-    } catch(err) {
-      if(err.code == 'ENOENT') {
-        barDeleted = true;
-      }
-    }
-    assert.equal(true, barDeleted);
-
-    // Make sure that the file inside the linked folder wasn't deleted
-    let res = fs.readdirSync('foo');
-    assert.equal(1, res.length);
-    assert.equal('hello.txt', res[0]);
-
-    // Cleanup
-    fs.unlinkSync('foo/hello.txt');
-    fs.rmdirSync('foo');
-  });
-
-  test('cpR with same name and different directory', function () {
-    file.mkdirP('foo');
-    fs.writeFileSync('foo/bar.txt', 'w00t');
-    file.cpR('foo', 'bar');
-    assert.ok(existsSync('bar/bar.txt'));
-    file.rmRf('foo');
-    file.rmRf('bar');
-  });
-
-  test('cpR with same to and from will throw', function () {
-    assert.throws(function () {
-      file.cpR('foo.txt', 'foo.txt');
-    });
-  });
-
-  test('cpR rename via copy in directory', function () {
-    file.mkdirP('foo');
-    fs.writeFileSync('foo/bar.txt', 'w00t');
-    file.cpR('foo/bar.txt', 'foo/baz.txt');
-    assert.ok(existsSync('foo/baz.txt'));
-    file.rmRf('foo');
-  });
-
-  test('cpR rename via copy in base', function () {
-    fs.writeFileSync('bar.txt', 'w00t');
-    file.cpR('bar.txt', 'baz.txt');
-    assert.ok(existsSync('baz.txt'));
-    file.rmRf('bar.txt');
-    file.rmRf('baz.txt');
-  });
-
-  test('cpR keeps file mode', function () {
-    fs.writeFileSync('bar.txt', 'w00t', {mode: 0o750});
-    fs.writeFileSync('bar1.txt', 'w00t!', {mode: 0o744});
-    file.cpR('bar.txt', 'baz.txt');
-    file.cpR('bar1.txt', 'baz1.txt');
-
-    assert.ok(existsSync('baz.txt'));
-    assert.ok(existsSync('baz1.txt'));
-    let bazStat = fs.statSync('baz.txt');
-    let bazStat1 = fs.statSync('baz1.txt');
-    assert.equal(0o750, bazStat.mode & 0o7777);
-    assert.equal(0o744, bazStat1.mode & 0o7777);
-
-    file.rmRf('bar.txt');
-    file.rmRf('baz.txt');
-    file.rmRf('bar1.txt');
-    file.rmRf('baz1.txt');
-  });
-
-  test('cpR keeps file mode when overwriting with preserveMode', function () {
-    fs.writeFileSync('bar.txt', 'w00t', {mode: 0o755});
-    fs.writeFileSync('baz.txt', 'w00t!', {mode: 0o744});
-    file.cpR('bar.txt', 'baz.txt', {silent: true, preserveMode: true});
-
-    assert.ok(existsSync('baz.txt'));
-    let bazStat = fs.statSync('baz.txt');
-    assert.equal(0o755, bazStat.mode & 0o777);
-
-    file.rmRf('bar.txt');
-    file.rmRf('baz.txt');
-  });
-
-  test('cpR does not keep file mode when overwriting', function () {
-    fs.writeFileSync('bar.txt', 'w00t', {mode: 0o766});
-    fs.writeFileSync('baz.txt', 'w00t!', {mode: 0o744});
-    file.cpR('bar.txt', 'baz.txt');
-
-    assert.ok(existsSync('baz.txt'));
-    let bazStat = fs.statSync('baz.txt');
-    assert.equal(0o744, bazStat.mode & 0o777);
-
-    file.rmRf('bar.txt');
-    file.rmRf('baz.txt');
-  });
-
-  test('cpR copies file mode recursively', function () {
-    fs.mkdirSync('foo');
-    fs.writeFileSync('foo/bar.txt', 'w00t', {mode: 0o740});
-    file.cpR('foo', 'baz');
-
-    assert.ok(existsSync('baz'));
-    let barStat = fs.statSync('baz/bar.txt');
-    assert.equal(0o740, barStat.mode & 0o777);
-
-    file.rmRf('foo');
-    file.rmRf('baz');
-  });
-
-  test('cpR keeps file mode recursively', function () {
-    fs.mkdirSync('foo');
-    fs.writeFileSync('foo/bar.txt', 'w00t', {mode: 0o740});
-    fs.mkdirSync('baz');
-    fs.mkdirSync('baz/foo');
-    fs.writeFileSync('baz/foo/bar.txt', 'w00t!', {mode: 0o755});
-    file.cpR('foo', 'baz', {silent: true, preserveMode: true});
-
-    assert.ok(existsSync('baz'));
-    let barStat = fs.statSync('baz/foo/bar.txt');
-    assert.equal(0o740, barStat.mode & 0o777);
-
-    file.rmRf('foo');
-    file.rmRf('baz');
-  });
-
-  test('cpR copies directory mode recursively', function () {
-    fs.mkdirSync('foo', 0o755);
-    fs.mkdirSync('foo/bar', 0o700);
-    file.cpR('foo', 'bar');
-
-    assert.ok(existsSync('foo'));
-    let fooBarStat = fs.statSync('bar/bar');
-    assert.equal(0o700, fooBarStat.mode & 0o777);
-
-    file.rmRf('foo');
-    file.rmRf('bar');
-  });
-
-});
-
-
+const PROJECT_DIR=process.env.PROJECT_DIR;let assert=require("assert"),fs=require("fs"),path=require("path"),file=require(`${PROJECT_DIR}/lib/utils/file`),existsSync=fs.existsSync||path.existsSync,exec=require("child_process").execSync;suite("fileUtils",(function(){test("mkdirP",(function(){let t=[["foo"],["foo","bar"],["foo","bar","baz"],["foo","bar","baz","qux"]];file.mkdirP("foo/bar/baz/qux");let e=exec("find foo").toString().trim().split("\n");for(let f=0,o=e.length;f<o;f++)assert.equal(path.join.apply(path,t[f]),e[f]);file.rmRf("foo")})),test("rmRf",(function(){file.mkdirP("foo/bar/baz/qux"),file.rmRf("foo/bar");let t=exec("find foo").toString().trim().split("\n");assert.equal(1,t.length),assert.equal("foo",t[0]),fs.rmdirSync("foo")})),test("rmRf with symlink subdir",(function(){file.mkdirP("foo"),file.mkdirP("bar"),fs.writeFileSync("foo/hello.txt","hello, it's me"),fs.symlinkSync("../foo","bar/foo"),file.rmRf("bar");let t=!1;try{fs.statSync("bar")}catch(e){"ENOENT"==e.code&&(t=!0)}assert.equal(!0,t);let e=fs.readdirSync("foo");assert.equal(1,e.length),assert.equal("hello.txt",e[0]),fs.unlinkSync("foo/hello.txt"),fs.rmdirSync("foo")})),test("rmRf with symlinked dir",(function(){file.mkdirP("foo"),fs.writeFileSync("foo/hello.txt","hello!"),fs.symlinkSync("foo","bar"),file.rmRf("bar");let t=!1;try{fs.statSync("bar")}catch(e){"ENOENT"==e.code&&(t=!0)}assert.equal(!0,t);let e=fs.readdirSync("foo");assert.equal(1,e.length),assert.equal("hello.txt",e[0]),fs.unlinkSync("foo/hello.txt"),fs.rmdirSync("foo")})),test("cpR with same name and different directory",(function(){file.mkdirP("foo"),fs.writeFileSync("foo/bar.txt","w00t"),file.cpR("foo","bar"),assert.ok(existsSync("bar/bar.txt")),file.rmRf("foo"),file.rmRf("bar")})),test("cpR with same to and from will throw",(function(){assert.throws((function(){file.cpR("foo.txt","foo.txt")}))})),test("cpR rename via copy in directory",(function(){file.mkdirP("foo"),fs.writeFileSync("foo/bar.txt","w00t"),file.cpR("foo/bar.txt","foo/baz.txt"),assert.ok(existsSync("foo/baz.txt")),file.rmRf("foo")})),test("cpR rename via copy in base",(function(){fs.writeFileSync("bar.txt","w00t"),file.cpR("bar.txt","baz.txt"),assert.ok(existsSync("baz.txt")),file.rmRf("bar.txt"),file.rmRf("baz.txt")})),test("cpR keeps file mode",(function(){fs.writeFileSync("bar.txt","w00t",{mode:488}),fs.writeFileSync("bar1.txt","w00t!",{mode:484}),file.cpR("bar.txt","baz.txt"),file.cpR("bar1.txt","baz1.txt"),assert.ok(existsSync("baz.txt")),assert.ok(existsSync("baz1.txt"));let t=fs.statSync("baz.txt"),e=fs.statSync("baz1.txt");assert.equal(488,4095&t.mode),assert.equal(484,4095&e.mode),file.rmRf("bar.txt"),file.rmRf("baz.txt"),file.rmRf("bar1.txt"),file.rmRf("baz1.txt")})),test("cpR keeps file mode when overwriting with preserveMode",(function(){fs.writeFileSync("bar.txt","w00t",{mode:493}),fs.writeFileSync("baz.txt","w00t!",{mode:484}),file.cpR("bar.txt","baz.txt",{silent:!0,preserveMode:!0}),assert.ok(existsSync("baz.txt"));let t=fs.statSync("baz.txt");assert.equal(493,511&t.mode),file.rmRf("bar.txt"),file.rmRf("baz.txt")})),test("cpR does not keep file mode when overwriting",(function(){fs.writeFileSync("bar.txt","w00t",{mode:502}),fs.writeFileSync("baz.txt","w00t!",{mode:484}),file.cpR("bar.txt","baz.txt"),assert.ok(existsSync("baz.txt"));let t=fs.statSync("baz.txt");assert.equal(484,511&t.mode),file.rmRf("bar.txt"),file.rmRf("baz.txt")})),test("cpR copies file mode recursively",(function(){fs.mkdirSync("foo"),fs.writeFileSync("foo/bar.txt","w00t",{mode:480}),file.cpR("foo","baz"),assert.ok(existsSync("baz"));let t=fs.statSync("baz/bar.txt");assert.equal(480,511&t.mode),file.rmRf("foo"),file.rmRf("baz")})),test("cpR keeps file mode recursively",(function(){fs.mkdirSync("foo"),fs.writeFileSync("foo/bar.txt","w00t",{mode:480}),fs.mkdirSync("baz"),fs.mkdirSync("baz/foo"),fs.writeFileSync("baz/foo/bar.txt","w00t!",{mode:493}),file.cpR("foo","baz",{silent:!0,preserveMode:!0}),assert.ok(existsSync("baz"));let t=fs.statSync("baz/foo/bar.txt");assert.equal(480,511&t.mode),file.rmRf("foo"),file.rmRf("baz")})),test("cpR copies directory mode recursively",(function(){fs.mkdirSync("foo",493),fs.mkdirSync("foo/bar",448),file.cpR("foo","bar"),assert.ok(existsSync("foo"));let t=fs.statSync("bar/bar");assert.equal(448,511&t.mode),file.rmRf("foo"),file.rmRf("bar")}))}));
\ No newline at end of file
index b48f07e..1ba8a6a 100755 (executable)
@@ -1,125 +1 @@
-/*
- * Jake JavaScript build tool
- * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-*/
-
-const PROJECT_DIR = process.env.PROJECT_DIR;
-
-let assert = require('assert');
-let fs = require('fs');
-let exec = require('child_process').execSync;
-let { rmRf } = require(`${PROJECT_DIR}/lib/jake`);
-
-let cleanUpAndNext = function (callback) {
-  rmRf('./foo', {
-    silent: true
-  });
-  callback && callback();
-};
-
-suite('fileTask', function () {
-  this.timeout(7000);
-
-  setup(function () {
-    cleanUpAndNext();
-  });
-
-  test('where a file-task prereq does not change with --always-make', function () {
-    let out;
-    out = exec('./node_modules/.bin/jake -q fileTest:foo/from-src1.txt').toString().trim();
-    assert.equal('fileTest:foo/src1.txt task\nfileTest:foo/from-src1.txt task',
-      out);
-    out = exec('./node_modules/.bin/jake -q -B fileTest:foo/from-src1.txt').toString().trim();
-    assert.equal('fileTest:foo/src1.txt task\nfileTest:foo/from-src1.txt task',
-      out);
-    cleanUpAndNext();
-  });
-
-  test('concating two files', function () {
-    let out;
-    out = exec('./node_modules/.bin/jake -q fileTest:foo/concat.txt').toString().trim();
-    assert.equal('fileTest:foo/src1.txt task\ndefault task\nfileTest:foo/src2.txt task\n' +
-          'fileTest:foo/concat.txt task', out);
-    // Check to see the two files got concat'd
-    let data = fs.readFileSync(process.cwd() + '/foo/concat.txt');
-    assert.equal('src1src2', data.toString());
-    cleanUpAndNext();
-  });
-
-  test('where a file-task prereq does not change', function () {
-    let out;
-    out = exec('./node_modules/.bin/jake -q fileTest:foo/from-src1.txt').toString().trim();
-    assert.equal('fileTest:foo/src1.txt task\nfileTest:foo/from-src1.txt task', out);
-    out = exec('./node_modules/.bin/jake -q fileTest:foo/from-src1.txt').toString().trim();
-    // Second time should be a no-op
-    assert.equal('', out);
-    cleanUpAndNext();
-  });
-
-  test('where a file-task prereq does change, then does not', function (next) {
-    exec('mkdir -p ./foo');
-    exec('touch ./foo/from-src1.txt');
-    setTimeout(() => {
-      fs.writeFileSync('./foo/src1.txt', '-SRC');
-      // Task should run the first time
-      let out;
-      out = exec('./node_modules/.bin/jake -q fileTest:foo/from-src1.txt').toString().trim();
-      assert.equal('fileTest:foo/from-src1.txt task', out);
-      // Task should not run on subsequent invocation
-      out = exec('./node_modules/.bin/jake -q fileTest:foo/from-src1.txt').toString().trim();
-      assert.equal('', out);
-      cleanUpAndNext(next);
-    }, 1000);
-  });
-
-  test('a preexisting file', function () {
-    let prereqData = 'howdy';
-    exec('mkdir -p ./foo');
-    fs.writeFileSync('foo/prereq.txt', prereqData);
-    let out;
-    out = exec('./node_modules/.bin/jake -q fileTest:foo/from-prereq.txt').toString().trim();
-    assert.equal('fileTest:foo/from-prereq.txt task', out);
-    let data = fs.readFileSync(process.cwd() + '/foo/from-prereq.txt');
-    assert.equal(prereqData, data.toString());
-    out = exec('./node_modules/.bin/jake -q fileTest:foo/from-prereq.txt').toString().trim();
-    // Second time should be a no-op
-    assert.equal('', out);
-    cleanUpAndNext();
-  });
-
-  test('a preexisting file with --always-make flag', function () {
-    let prereqData = 'howdy';
-    exec('mkdir -p ./foo');
-    fs.writeFileSync('foo/prereq.txt', prereqData);
-    let out;
-    out = exec('./node_modules/.bin/jake -q fileTest:foo/from-prereq.txt').toString().trim();
-    assert.equal('fileTest:foo/from-prereq.txt task', out);
-    let data = fs.readFileSync(process.cwd() + '/foo/from-prereq.txt');
-    assert.equal(prereqData, data.toString());
-    out = exec('./node_modules/.bin/jake -q -B fileTest:foo/from-prereq.txt').toString().trim();
-    assert.equal('fileTest:foo/from-prereq.txt task', out);
-    cleanUpAndNext();
-  });
-
-  test('nested directory-task', function () {
-    exec('./node_modules/.bin/jake -q fileTest:foo/bar/baz/bamf.txt');
-    let data = fs.readFileSync(process.cwd() + '/foo/bar/baz/bamf.txt');
-    assert.equal('w00t', data);
-    cleanUpAndNext();
-  });
-
-});
-
+const PROJECT_DIR=process.env.PROJECT_DIR;let assert=require("assert"),fs=require("fs"),exec=require("child_process").execSync,{rmRf:rmRf}=require(`${PROJECT_DIR}/lib/jake`),cleanUpAndNext=function(e){rmRf("./foo",{silent:!0}),e&&e()};suite("fileTask",(function(){this.timeout(7e3),setup((function(){cleanUpAndNext()})),test("where a file-task prereq does not change with --always-make",(function(){let e;e=exec("./node_modules/.bin/jake -q fileTest:foo/from-src1.txt").toString().trim(),assert.equal("fileTest:foo/src1.txt task\nfileTest:foo/from-src1.txt task",e),e=exec("./node_modules/.bin/jake -q -B fileTest:foo/from-src1.txt").toString().trim(),assert.equal("fileTest:foo/src1.txt task\nfileTest:foo/from-src1.txt task",e),cleanUpAndNext()})),test("concating two files",(function(){let e;e=exec("./node_modules/.bin/jake -q fileTest:foo/concat.txt").toString().trim(),assert.equal("fileTest:foo/src1.txt task\ndefault task\nfileTest:foo/src2.txt task\nfileTest:foo/concat.txt task",e);let t=fs.readFileSync(process.cwd()+"/foo/concat.txt");assert.equal("src1src2",t.toString()),cleanUpAndNext()})),test("where a file-task prereq does not change",(function(){let e;e=exec("./node_modules/.bin/jake -q fileTest:foo/from-src1.txt").toString().trim(),assert.equal("fileTest:foo/src1.txt task\nfileTest:foo/from-src1.txt task",e),e=exec("./node_modules/.bin/jake -q fileTest:foo/from-src1.txt").toString().trim(),assert.equal("",e),cleanUpAndNext()})),test("where a file-task prereq does change, then does not",(function(e){exec("mkdir -p ./foo"),exec("touch ./foo/from-src1.txt"),setTimeout((()=>{let t;fs.writeFileSync("./foo/src1.txt","-SRC"),t=exec("./node_modules/.bin/jake -q fileTest:foo/from-src1.txt").toString().trim(),assert.equal("fileTest:foo/from-src1.txt task",t),t=exec("./node_modules/.bin/jake -q fileTest:foo/from-src1.txt").toString().trim(),assert.equal("",t),cleanUpAndNext(e)}),1e3)})),test("a preexisting file",(function(){let e,t="howdy";exec("mkdir -p ./foo"),fs.writeFileSync("foo/prereq.txt",t),e=exec("./node_modules/.bin/jake -q fileTest:foo/from-prereq.txt").toString().trim(),assert.equal("fileTest:foo/from-prereq.txt task",e);let o=fs.readFileSync(process.cwd()+"/foo/from-prereq.txt");assert.equal(t,o.toString()),e=exec("./node_modules/.bin/jake -q fileTest:foo/from-prereq.txt").toString().trim(),assert.equal("",e),cleanUpAndNext()})),test("a preexisting file with --always-make flag",(function(){let e,t="howdy";exec("mkdir -p ./foo"),fs.writeFileSync("foo/prereq.txt",t),e=exec("./node_modules/.bin/jake -q fileTest:foo/from-prereq.txt").toString().trim(),assert.equal("fileTest:foo/from-prereq.txt task",e);let o=fs.readFileSync(process.cwd()+"/foo/from-prereq.txt");assert.equal(t,o.toString()),e=exec("./node_modules/.bin/jake -q -B fileTest:foo/from-prereq.txt").toString().trim(),assert.equal("fileTest:foo/from-prereq.txt task",e),cleanUpAndNext()})),test("nested directory-task",(function(){exec("./node_modules/.bin/jake -q fileTest:foo/bar/baz/bamf.txt");let e=fs.readFileSync(process.cwd()+"/foo/bar/baz/bamf.txt");assert.equal("w00t",e),cleanUpAndNext()}))}));
\ No newline at end of file
index 9caaa4e..a1070c5 100755 (executable)
@@ -1,80 +1 @@
-var exec = require('child_process').exec;
-
-var helpers = new (function () {
-  var _tests;
-  var _names = [];
-  var _name;
-  var _callback;
-  var _runner = function () {
-    if ((_name = _names.shift())) {
-      console.log('Running ' + _name);
-      _tests[_name]();
-    }
-    else {
-      _callback();
-    }
-  };
-
-  this.exec = function () {
-    var args = Array.prototype.slice.call(arguments);
-    var arg;
-    var cmd = args.shift();
-    var opts = {};
-    var callback;
-    // Optional opts/callback or callback/opts
-    while ((arg = args.shift())) {
-      if (typeof arg == 'function') {
-        callback = arg;
-      }
-      else {
-        opts = arg;
-      }
-    }
-
-    cmd += ' --trace';
-    var execOpts = opts.execOpts ? opts.execOpts : {};
-    exec(cmd, execOpts, function (err, stdout, stderr) {
-      var out = helpers.trim(stdout);
-      if (err) {
-        if (opts.breakOnError === false) {
-          return callback(err);
-        }
-        else {
-          throw err;
-        }
-      }
-      if (stderr) {
-        callback(stderr);
-      }
-      else {
-        callback(out);
-      }
-    });
-  };
-
-  this.trim = function (s) {
-    var str = s || '';
-    return str.replace(/^\s*|\s*$/g, '');
-  };
-
-  this.parse = function (s) {
-    var str = s || '';
-    str = helpers.trim(str);
-    str = str.replace(/'/g, '"');
-    return JSON.parse(str);
-  };
-
-  this.run = function (tests, callback) {
-    _tests = tests;
-    _names = Object.keys(tests);
-    _callback = callback;
-    _runner();
-  };
-
-  this.next = function () {
-    _runner();
-  };
-
-})();
-
-module.exports = helpers;
+var exec=require("child_process").exec,helpers=new function(){var e,r,t,n=[],i=function(){(r=n.shift())?(console.log("Running "+r),e[r]()):t()};this.exec=function(){for(var e,r,t=Array.prototype.slice.call(arguments),n=t.shift(),i={};e=t.shift();)"function"==typeof e?r=e:i=e;n+=" --trace";var c=i.execOpts?i.execOpts:{};exec(n,c,(function(e,t,n){var c=helpers.trim(t);if(e){if(!1===i.breakOnError)return r(e);throw e}r(n||c)}))},this.trim=function(e){return(e||"").replace(/^\s*|\s*$/g,"")},this.parse=function(e){var r=e||"";return r=(r=helpers.trim(r)).replace(/'/g,'"'),JSON.parse(r)},this.run=function(r,c){e=r,n=Object.keys(r),t=c,i()},this.next=function(){i()}};module.exports=helpers;
\ No newline at end of file
index f3b7d1a..8b1d780 100755 (executable)
@@ -1,337 +1 @@
-let fs = require('fs');
-let Q = require('q');
-
-desc('The default t.');
-task('default', function () {
-  console.log('default task');
-});
-
-desc('No action.');
-task({'noAction': ['default']});
-
-desc('No action, no prereqs.');
-task('noActionNoPrereqs');
-
-desc('Top-level zerbofrangazoomy task');
-task('zerbofrangazoomy', function () {
-  console.log('Whaaaaaaaa? Ran the zerbofrangazoomy task!')
-});
-
-desc('Task that throws');
-task('throwy', function () {
-  let errorListener = function (err) {
-    console.log('Emitted');
-    console.log(err.toString());
-
-    jake.removeListener('error', errorListener);
-  };
-
-  jake.on('error', errorListener);
-
-  throw new Error('I am bad');
-});
-
-desc('Task that rejects a Promise');
-task('promiseRejecter', function () {
-  const originalOption = jake.program.opts['allow-rejection'];
-
-  const errorListener = function (err) {
-    console.log(err.toString());
-    jake.removeListener('error', errorListener);
-    jake.program.opts['allow-rejection'] = originalOption; // Restore original 'allow-rejection' option
-  };
-  jake.on('error', errorListener);
-
-  jake.program.opts['allow-rejection'] = false; // Do not allow rejection so the rejection is passed to error handlers
-
-  Promise.reject('<promise rejected on purpose>');
-});
-
-desc('Accepts args and env vars.');
-task('argsEnvVars', function () {
-  let res = {
-    args: arguments
-    , env: {
-      foo: process.env.foo
-      , baz: process.env.baz
-    }
-  };
-  console.log(JSON.stringify(res));
-});
-
-namespace('foo', function () {
-  desc('The foo:bar t.');
-  task('bar', function () {
-    if (arguments.length) {
-      console.log('foo:bar[' +
-          Array.prototype.join.call(arguments, ',') +
-          '] task');
-    }
-    else {
-      console.log('foo:bar task');
-    }
-  });
-
-  desc('The foo:baz task, calls foo:bar as a prerequisite.');
-  task('baz', ['foo:bar'], function () {
-    console.log('foo:baz task');
-  });
-
-  desc('The foo:qux task, calls foo:bar with cmdline args as a prerequisite.');
-  task('qux', ['foo:bar[asdf,qwer]'], function () {
-    console.log('foo:qux task');
-  });
-
-  desc('The foo:frang task,`invokes` foo:bar with passed args as a prerequisite.');
-  task('frang', function () {
-    let t = jake.Task['foo:bar'];
-    // Do args pass-through
-    t.invoke.apply(t, arguments);
-    t.on('complete', () => {
-      console.log('foo:frang task');
-    });
-  });
-
-  desc('The foo:zerb task, `executes` foo:bar with passed args as a prerequisite.');
-  task('zerb', function () {
-    let t = jake.Task['foo:bar'];
-    // Do args pass-through
-    t.execute.apply(t, arguments);
-    t.on('complete', () => {
-      console.log('foo:zerb task');
-    });
-  });
-
-  desc('The foo:zoobie task, has no prerequisites.');
-  task('zoobie', function () {
-    console.log('foo:zoobie task');
-  });
-
-  desc('The foo:voom task, run the foo:zoobie task repeatedly.');
-  task('voom', function () {
-    let t = jake.Task['foo:bar'];
-    t.on('complete', function () {
-      console.log('complete');
-    });
-    t.execute.apply(t);
-    t.execute.apply(t);
-  });
-
-  desc('The foo:asdf task, has the same prereq twice.');
-  task('asdf', ['foo:bar', 'foo:baz'], function () {
-    console.log('foo:asdf task');
-  });
-
-});
-
-namespace('bar', function () {
-  desc('The bar:foo task, has no prerequisites, is async, returns Promise which resolves.');
-  task('foo', async function () {
-    return new Promise((resolve, reject) => {
-      console.log('bar:foo task');
-      resolve();
-    });
-  });
-
-  desc('The bar:promise task has no prerequisites, is async, returns Q-based promise.');
-  task('promise', function () {
-    return Q()
-      .then(function () {
-        console.log('bar:promise task');
-        return 123654;
-      });
-  });
-
-  desc('The bar:dependOnpromise task waits for a promise based async test');
-  task('dependOnpromise', ['promise'], function () {
-    console.log('bar:dependOnpromise task saw value', jake.Task["bar:promise"].value);
-  });
-
-  desc('The bar:brokenPromise task is a failing Q-promise based async task.');
-  task('brokenPromise', function () {
-    return Q()
-      .then(function () {
-        throw new Error("nom nom nom");
-      });
-  });
-
-  desc('The bar:bar task, has the async bar:foo task as a prerequisite.');
-  task('bar', ['bar:foo'], function () {
-    console.log('bar:bar task');
-  });
-
-});
-
-namespace('hoge', function () {
-  desc('The hoge:hoge task, has no prerequisites.');
-  task('hoge', function () {
-    console.log('hoge:hoge task');
-  });
-
-  desc('The hoge:piyo task, has no prerequisites.');
-  task('piyo', function () {
-    console.log('hoge:piyo task');
-  });
-
-  desc('The hoge:fuga task, has hoge:hoge and hoge:piyo as prerequisites.');
-  task('fuga', ['hoge:hoge', 'hoge:piyo'], function () {
-    console.log('hoge:fuga task');
-  });
-
-  desc('The hoge:charan task, has hoge:fuga as a prerequisite.');
-  task('charan', ['hoge:fuga'], function () {
-    console.log('hoge:charan task');
-  });
-
-  desc('The hoge:gero task, has hoge:fuga as a prerequisite.');
-  task('gero', ['hoge:fuga'], function () {
-    console.log('hoge:gero task');
-  });
-
-  desc('The hoge:kira task, has hoge:charan and hoge:gero as prerequisites.');
-  task('kira', ['hoge:charan', 'hoge:gero'], function () {
-    console.log('hoge:kira task');
-  });
-
-});
-
-namespace('fileTest', function () {
-  directory('foo');
-
-  desc('File task, concatenating two files together');
-  file('foo/concat.txt', ['fileTest:foo', 'fileTest:foo/src1.txt', 'fileTest:foo/src2.txt'], function () {
-    console.log('fileTest:foo/concat.txt task');
-    let data1 = fs.readFileSync('foo/src1.txt');
-    let data2 = fs.readFileSync('foo/src2.txt');
-    fs.writeFileSync('foo/concat.txt', data1 + data2);
-  });
-
-  desc('File task, async creation with writeFile');
-  file('foo/src1.txt', function () {
-    return new Promise(function (resolve, reject) {
-      fs.writeFile('foo/src1.txt', 'src1', function (err) {
-        if (err) {
-          reject(err);
-        }
-        else {
-          console.log('fileTest:foo/src1.txt task');
-          resolve();
-        }
-      });
-    });
-  });
-
-  desc('File task, sync creation with writeFileSync');
-  file('foo/src2.txt', ['default'], function () {
-    fs.writeFileSync('foo/src2.txt', 'src2');
-    console.log('fileTest:foo/src2.txt task');
-  });
-
-  desc('File task, do not run unless the prereq file changes');
-  file('foo/from-src1.txt', ['fileTest:foo', 'fileTest:foo/src1.txt'], function () {
-    let data = fs.readFileSync('foo/src1.txt').toString();
-    fs.writeFileSync('foo/from-src1.txt', data);
-    console.log('fileTest:foo/from-src1.txt task');
-  });
-
-  desc('File task, run if the prereq file changes');
-  task('touch-prereq', function () {
-    fs.writeFileSync('foo/prereq.txt', 'UPDATED');
-  })
-
-  desc('File task, has a preexisting file (with no associated task) as a prereq');
-  file('foo/from-prereq.txt', ['fileTest:foo', 'foo/prereq.txt'], function () {
-    let data = fs.readFileSync('foo/prereq.txt');
-    fs.writeFileSync('foo/from-prereq.txt', data);
-    console.log('fileTest:foo/from-prereq.txt task');
-  });
-
-  directory('foo/bar/baz');
-
-  desc('Write a file in a nested subdirectory');
-  file('foo/bar/baz/bamf.txt', ['foo/bar/baz'], function () {
-    fs.writeFileSync('foo/bar/baz/bamf.txt', 'w00t');
-  });
-
-});
-
-task('blammo');
-// Define task
-task('voom', ['blammo'], function () {
-  console.log(this.prereqs.length);
-});
-
-// Modify, add a prereq
-task('voom', ['noActionNoPrereqs']);
-
-namespace('vronk', function () {
-  task('groo', function () {
-    let t = jake.Task['vronk:zong'];
-    t.addListener('error', function (e) {
-      console.log(e.message);
-    });
-    t.invoke();
-  });
-  task('zong', function () {
-    throw new Error('OMFGZONG');
-  });
-});
-
-// define namespace
-namespace('one', function () {
-  task('one', function () {
-    console.log('one:one');
-  });
-});
-
-// modify namespace (add task)
-namespace('one', function () {
-  task('two', ['one:one'], function () {
-    console.log('one:two');
-  });
-});
-
-task('selfdepconst', [], function () {
-  task('selfdep', ['selfdep'], function () {
-    console.log("I made a task that depends on itself");
-  });
-});
-task('selfdepdyn', function () {
-  task('selfdeppar', [], {concurrency: 2}, function () {
-    console.log("I will depend on myself and will fail at runtime");
-  });
-  task('selfdeppar', ['selfdeppar']);
-  jake.Task['selfdeppar'].invoke();
-});
-
-namespace("large", function () {
-  task("leaf", function () {
-    console.log("large:leaf");
-  });
-
-  const same = [];
-  for (let i = 0; i < 2000; i++) {
-    same.push("leaf");
-  }
-
-  desc("Task with a large number of same prereqs");
-  task("same", same, { concurrency: 2 }, function () {
-    console.log("large:same");
-  });
-
-  const different = [];
-  for (let i = 0; i < 2000; i++) {
-    const name = "leaf-" + i;
-    task(name, function () {
-      if (name === "leaf-12" || name === "leaf-123") {
-        console.log(name);
-      }
-    });
-    different.push(name);
-  }
-
-  desc("Task with a large number of different prereqs");
-  task("different", different, { concurrency: 2 } , function () {
-    console.log("large:different")
-  })
-});
+let fs=require("fs"),Q=require("q");desc("The default t."),task("default",(function(){console.log("default task")})),desc("No action."),task({noAction:["default"]}),desc("No action, no prereqs."),task("noActionNoPrereqs"),desc("Top-level zerbofrangazoomy task"),task("zerbofrangazoomy",(function(){console.log("Whaaaaaaaa? Ran the zerbofrangazoomy task!")})),desc("Task that throws"),task("throwy",(function(){let e=function(o){console.log("Emitted"),console.log(o.toString()),jake.removeListener("error",e)};throw jake.on("error",e),new Error("I am bad")})),desc("Task that rejects a Promise"),task("promiseRejecter",(function(){const e=jake.program.opts["allow-rejection"],o=function(s){console.log(s.toString()),jake.removeListener("error",o),jake.program.opts["allow-rejection"]=e};jake.on("error",o),jake.program.opts["allow-rejection"]=!1,Promise.reject("<promise rejected on purpose>")})),desc("Accepts args and env vars."),task("argsEnvVars",(function(){let e={args:arguments,env:{foo:process.env.foo,baz:process.env.baz}};console.log(JSON.stringify(e))})),namespace("foo",(function(){desc("The foo:bar t."),task("bar",(function(){arguments.length?console.log("foo:bar["+Array.prototype.join.call(arguments,",")+"] task"):console.log("foo:bar task")})),desc("The foo:baz task, calls foo:bar as a prerequisite."),task("baz",["foo:bar"],(function(){console.log("foo:baz task")})),desc("The foo:qux task, calls foo:bar with cmdline args as a prerequisite."),task("qux",["foo:bar[asdf,qwer]"],(function(){console.log("foo:qux task")})),desc("The foo:frang task,`invokes` foo:bar with passed args as a prerequisite."),task("frang",(function(){let e=jake.Task["foo:bar"];e.invoke.apply(e,arguments),e.on("complete",(()=>{console.log("foo:frang task")}))})),desc("The foo:zerb task, `executes` foo:bar with passed args as a prerequisite."),task("zerb",(function(){let e=jake.Task["foo:bar"];e.execute.apply(e,arguments),e.on("complete",(()=>{console.log("foo:zerb task")}))})),desc("The foo:zoobie task, has no prerequisites."),task("zoobie",(function(){console.log("foo:zoobie task")})),desc("The foo:voom task, run the foo:zoobie task repeatedly."),task("voom",(function(){let e=jake.Task["foo:bar"];e.on("complete",(function(){console.log("complete")})),e.execute.apply(e),e.execute.apply(e)})),desc("The foo:asdf task, has the same prereq twice."),task("asdf",["foo:bar","foo:baz"],(function(){console.log("foo:asdf task")}))})),namespace("bar",(function(){desc("The bar:foo task, has no prerequisites, is async, returns Promise which resolves."),task("foo",(async function(){return new Promise(((e,o)=>{console.log("bar:foo task"),e()}))})),desc("The bar:promise task has no prerequisites, is async, returns Q-based promise."),task("promise",(function(){return Q().then((function(){return console.log("bar:promise task"),123654}))})),desc("The bar:dependOnpromise task waits for a promise based async test"),task("dependOnpromise",["promise"],(function(){console.log("bar:dependOnpromise task saw value",jake.Task["bar:promise"].value)})),desc("The bar:brokenPromise task is a failing Q-promise based async task."),task("brokenPromise",(function(){return Q().then((function(){throw new Error("nom nom nom")}))})),desc("The bar:bar task, has the async bar:foo task as a prerequisite."),task("bar",["bar:foo"],(function(){console.log("bar:bar task")}))})),namespace("hoge",(function(){desc("The hoge:hoge task, has no prerequisites."),task("hoge",(function(){console.log("hoge:hoge task")})),desc("The hoge:piyo task, has no prerequisites."),task("piyo",(function(){console.log("hoge:piyo task")})),desc("The hoge:fuga task, has hoge:hoge and hoge:piyo as prerequisites."),task("fuga",["hoge:hoge","hoge:piyo"],(function(){console.log("hoge:fuga task")})),desc("The hoge:charan task, has hoge:fuga as a prerequisite."),task("charan",["hoge:fuga"],(function(){console.log("hoge:charan task")})),desc("The hoge:gero task, has hoge:fuga as a prerequisite."),task("gero",["hoge:fuga"],(function(){console.log("hoge:gero task")})),desc("The hoge:kira task, has hoge:charan and hoge:gero as prerequisites."),task("kira",["hoge:charan","hoge:gero"],(function(){console.log("hoge:kira task")}))})),namespace("fileTest",(function(){directory("foo"),desc("File task, concatenating two files together"),file("foo/concat.txt",["fileTest:foo","fileTest:foo/src1.txt","fileTest:foo/src2.txt"],(function(){console.log("fileTest:foo/concat.txt task");let e=fs.readFileSync("foo/src1.txt"),o=fs.readFileSync("foo/src2.txt");fs.writeFileSync("foo/concat.txt",e+o)})),desc("File task, async creation with writeFile"),file("foo/src1.txt",(function(){return new Promise((function(e,o){fs.writeFile("foo/src1.txt","src1",(function(s){s?o(s):(console.log("fileTest:foo/src1.txt task"),e())}))}))})),desc("File task, sync creation with writeFileSync"),file("foo/src2.txt",["default"],(function(){fs.writeFileSync("foo/src2.txt","src2"),console.log("fileTest:foo/src2.txt task")})),desc("File task, do not run unless the prereq file changes"),file("foo/from-src1.txt",["fileTest:foo","fileTest:foo/src1.txt"],(function(){let e=fs.readFileSync("foo/src1.txt").toString();fs.writeFileSync("foo/from-src1.txt",e),console.log("fileTest:foo/from-src1.txt task")})),desc("File task, run if the prereq file changes"),task("touch-prereq",(function(){fs.writeFileSync("foo/prereq.txt","UPDATED")})),desc("File task, has a preexisting file (with no associated task) as a prereq"),file("foo/from-prereq.txt",["fileTest:foo","foo/prereq.txt"],(function(){let e=fs.readFileSync("foo/prereq.txt");fs.writeFileSync("foo/from-prereq.txt",e),console.log("fileTest:foo/from-prereq.txt task")})),directory("foo/bar/baz"),desc("Write a file in a nested subdirectory"),file("foo/bar/baz/bamf.txt",["foo/bar/baz"],(function(){fs.writeFileSync("foo/bar/baz/bamf.txt","w00t")}))})),task("blammo"),task("voom",["blammo"],(function(){console.log(this.prereqs.length)})),task("voom",["noActionNoPrereqs"]),namespace("vronk",(function(){task("groo",(function(){let e=jake.Task["vronk:zong"];e.addListener("error",(function(e){console.log(e.message)})),e.invoke()})),task("zong",(function(){throw new Error("OMFGZONG")}))})),namespace("one",(function(){task("one",(function(){console.log("one:one")}))})),namespace("one",(function(){task("two",["one:one"],(function(){console.log("one:two")}))})),task("selfdepconst",[],(function(){task("selfdep",["selfdep"],(function(){console.log("I made a task that depends on itself")}))})),task("selfdepdyn",(function(){task("selfdeppar",[],{concurrency:2},(function(){console.log("I will depend on myself and will fail at runtime")})),task("selfdeppar",["selfdeppar"]),jake.Task.selfdeppar.invoke()})),namespace("large",(function(){task("leaf",(function(){console.log("large:leaf")}));const e=[];for(let o=0;o<2e3;o++)e.push("leaf");desc("Task with a large number of same prereqs"),task("same",e,{concurrency:2},(function(){console.log("large:same")}));const o=[];for(let e=0;e<2e3;e++){const s="leaf-"+e;task(s,(function(){"leaf-12"!==s&&"leaf-123"!==s||console.log(s)})),o.push(s)}desc("Task with a large number of different prereqs"),task("different",o,{concurrency:2},(function(){console.log("large:different")}))}));
\ No newline at end of file
index 684c86f..8930293 100755 (executable)
@@ -1,113 +1 @@
-
-namespace('concurrent', function () {
-  task('A', function () {
-    console.log('Started A');
-    return new Promise((resolve, reject) => {
-      setTimeout(() => {
-        console.log('Finished A');
-        resolve();
-      }, 200);
-    });
-  });
-
-  task('B', function () {
-    console.log('Started B');
-    return new Promise((resolve, reject) => {
-      setTimeout(() => {
-        console.log('Finished B');
-        resolve();
-      }, 50);
-    });
-  });
-
-  task('C', function () {
-    console.log('Started C');
-    return new Promise((resolve, reject) => {
-      setTimeout(() => {
-        console.log('Finished C');
-        resolve();
-      }, 100);
-    });
-  });
-
-  task('D', function () {
-    console.log('Started D');
-    return new Promise((resolve, reject) => {
-      setTimeout(() => {
-        console.log('Finished D');
-        resolve();
-      }, 300);
-    });
-  });
-
-  task('Ba', ['A'], function () {
-    console.log('Started Ba');
-    return new Promise((resolve, reject) => {
-      setTimeout(() => {
-        console.log('Finished Ba');
-        resolve();
-      }, 50);
-    });
-  });
-
-  task('Afail', function () {
-    console.log('Started failing task');
-    return new Promise((resolve, reject) => {
-      setTimeout(() => {
-        console.log('Failing B with error');
-        throw new Error('I failed');
-      }, 50);
-    });
-  });
-
-  task('simple1', ['A','B'], {concurrency: 2}, function () {
-    return new Promise((resolve, reject) => {
-      setTimeout(() => {
-        resolve();
-      }, 50);
-    });
-  });
-
-  task('simple2', ['C','D'], {concurrency: 2}, function () {
-    return new Promise((resolve, reject) => {
-      setTimeout(() => {
-        resolve();
-      }, 50);
-    });
-  });
-
-  task('seqconcurrent', ['simple1','simple2'], function () {
-    return new Promise((resolve, reject) => {
-      setTimeout(() => {
-        resolve();
-      }, 50);
-    });
-  });
-
-  task('concurrentconcurrent', ['simple1','simple2'], {concurrency: 2}, function () {
-    return new Promise((resolve, reject) => {
-      setTimeout(() => {
-        resolve();
-      }, 50);
-    });
-  });
-
-  task('subdep', ['A','Ba'], {concurrency: 2}, function () {
-    return new Promise((resolve, reject) => {
-      setTimeout(() => {
-        resolve();
-      }, 50);
-    });
-  });
-
-  task('fail', ['A', 'B', 'Afail'], {concurrency: 3}, function () {
-    return new Promise((resolve, reject) => {
-      setTimeout(() => {
-        resolve();
-      }, 50);
-    });
-  });
-
-});
-
-
+namespace("concurrent",(function(){task("A",(function(){return console.log("Started A"),new Promise(((e,n)=>{setTimeout((()=>{console.log("Finished A"),e()}),200)}))})),task("B",(function(){return console.log("Started B"),new Promise(((e,n)=>{setTimeout((()=>{console.log("Finished B"),e()}),50)}))})),task("C",(function(){return console.log("Started C"),new Promise(((e,n)=>{setTimeout((()=>{console.log("Finished C"),e()}),100)}))})),task("D",(function(){return console.log("Started D"),new Promise(((e,n)=>{setTimeout((()=>{console.log("Finished D"),e()}),300)}))})),task("Ba",["A"],(function(){return console.log("Started Ba"),new Promise(((e,n)=>{setTimeout((()=>{console.log("Finished Ba"),e()}),50)}))})),task("Afail",(function(){return console.log("Started failing task"),new Promise(((e,n)=>{setTimeout((()=>{throw console.log("Failing B with error"),new Error("I failed")}),50)}))})),task("simple1",["A","B"],{concurrency:2},(function(){return new Promise(((e,n)=>{setTimeout((()=>{e()}),50)}))})),task("simple2",["C","D"],{concurrency:2},(function(){return new Promise(((e,n)=>{setTimeout((()=>{e()}),50)}))})),task("seqconcurrent",["simple1","simple2"],(function(){return new Promise(((e,n)=>{setTimeout((()=>{e()}),50)}))})),task("concurrentconcurrent",["simple1","simple2"],{concurrency:2},(function(){return new Promise(((e,n)=>{setTimeout((()=>{e()}),50)}))})),task("subdep",["A","Ba"],{concurrency:2},(function(){return new Promise(((e,n)=>{setTimeout((()=>{e()}),50)}))})),task("fail",["A","B","Afail"],{concurrency:3},(function(){return new Promise(((e,n)=>{setTimeout((()=>{e()}),50)}))}))}));
\ No newline at end of file
index 52dd04a..47da0bc 100755 (executable)
@@ -1,49 +1 @@
-/*
- * Jake JavaScript build tool
- * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-*/
-
-const PROJECT_DIR = process.env.PROJECT_DIR;
-
-let fs = require('fs');
-let { publishTask, rmRf, mkdirP } = require(`${PROJECT_DIR}/lib/jake`);
-
-fs.writeFileSync('package.json', '{"version": "0.0.1"}');
-mkdirP('tmp_publish');
-fs.writeFileSync('tmp_publish/foo.txt', 'FOO');
-
-publishTask('zerb', function () {
-  this.packageFiles.include([
-    'package.json'
-    , 'tmp_publish/**'
-  ]);
-  this.publishCmd = 'node -p -e "\'%filename\'"';
-  this.gitCmd = 'echo'
-  this.scheduleDelay = 0;
-
-  this._ensureRepoClean = function () {};
-  this._getCurrentBranch = function () {
-    return 'v0.0'
-  };
-});
-
-jake.setTaskTimeout(5000);
-
-jake.Task['publish'].on('complete', function () {
-  rmRf('tmp_publish', {silent: true});
-  rmRf('package.json', {silent: true});
-});
-
+const PROJECT_DIR=process.env.PROJECT_DIR;let fs=require("fs"),{publishTask:publishTask,rmRf:rmRf,mkdirP:mkdirP}=require(`${PROJECT_DIR}/lib/jake`);fs.writeFileSync("package.json",'{"version": "0.0.1"}'),mkdirP("tmp_publish"),fs.writeFileSync("tmp_publish/foo.txt","FOO"),publishTask("zerb",(function(){this.packageFiles.include(["package.json","tmp_publish/**"]),this.publishCmd="node -p -e \"'%filename'\"",this.gitCmd="echo",this.scheduleDelay=0,this._ensureRepoClean=function(){},this._getCurrentBranch=function(){return"v0.0"}})),jake.setTaskTimeout(5e3),jake.Task.publish.on("complete",(function(){rmRf("tmp_publish",{silent:!0}),rmRf("package.json",{silent:!0})}));
\ No newline at end of file
index c63751d..517cb73 100755 (executable)
@@ -1,10 +1 @@
-let { task, namespace } = require("jake");
-
-namespace('usingRequire', function () {
-  task('test', () => {
-    console.log('howdy test');
-  });
-});
-
-
-
+let{task:task,namespace:namespace}=require("jake");namespace("usingRequire",(function(){task("test",(()=>{console.log("howdy test")}))}));
\ No newline at end of file
index 8e977dd..a5269f5 100755 (executable)
@@ -1,222 +1 @@
-/*
- * Jake JavaScript build tool
- * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-*/
-
-const PROJECT_DIR = process.env.PROJECT_DIR;
-
-let exec = require('child_process').execSync;
-let fs = require('fs');
-let util = require('util');
-let { rule, rmRf } = require(`${PROJECT_DIR}/lib/jake`);
-
-directory('tmpsrc');
-directory('tmpbin');
-
-////////////////////////////////////////////////////////////
-// Simple Suffix Rule
-file('tmp', ['tmp_init', 'tmp_dep1.o', 'tmp_dep2.o'], function (params) {
-  console.log('tmp task');
-  let data1 = fs.readFileSync('tmp_dep1.o');
-  let data2 = fs.readFileSync('tmp_dep2.o');
-  fs.writeFileSync('tmp', data1 + data2);
-});
-
-rule('.o', '.c', function () {
-  let cmd = util.format('cp %s %s', this.source, this.name);
-  console.log(cmd + ' task');
-  exec(cmd);
-});
-
-file('tmp_dep1.c', function () {
-  fs.writeFileSync('tmp_dep1.c', 'src_1');
-  console.log('tmp_dep1.c task');
-});
-
-// note that tmp_dep2.o depends on tmp_dep2.c, which is a
-// static file.
-task('tmp_init', function () {
-  fs.writeFileSync('tmp_dep2.c', 'src_2');
-  console.log('tmp_dep2.c task');
-});
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Pattern Rule
-file('tmp_p', ['tmp_init', 'tmp_dep1.oo', 'tmp_dep2.oo'], function (params) {
-  console.log('tmp pattern task');
-  let data1 = fs.readFileSync('tmp_dep1.oo');
-  let data2 = fs.readFileSync('tmp_dep2.oo');
-  fs.writeFileSync('tmp_p', data1 + data2 + ' pattern');
-});
-
-rule('%.oo', '%.c', function () {
-  let cmd = util.format('cp %s %s', this.source, this.name);
-  console.log(cmd + ' task');
-  exec(cmd);
-});
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Pattern Rule with Folder
-// i.e.  rule('tmpbin/%.oo', 'tmpsrc/%.c', ...
-file('tmp_pf', [
-  'tmp_src_init'
-  , 'tmpbin'
-  , 'tmpbin/tmp_dep1.oo'
-  , 'tmpbin/tmp_dep2.oo' ], function (params) {
-  console.log('tmp pattern folder task');
-  let data1 = fs.readFileSync('tmpbin/tmp_dep1.oo');
-  let data2 = fs.readFileSync('tmpbin/tmp_dep2.oo');
-  fs.writeFileSync('tmp_pf', data1 + data2 + ' pattern folder');
-});
-
-rule('tmpbin/%.oo', 'tmpsrc/%.c', function () {
-  let cmd = util.format('cp %s %s', this.source, this.name);
-  console.log(cmd + ' task');
-  exec(cmd);
-});
-
-file('tmpsrc/tmp_dep2.c',['tmpsrc'], function () {
-  fs.writeFileSync('tmpsrc/tmp_dep2.c', 'src/src_2');
-  console.log('tmpsrc/tmp_dep2.c task');
-});
-
-// Create static files in folder tmpsrc.
-task('tmp_src_init', ['tmpsrc'], function () {
-  fs.writeFileSync('tmpsrc/tmp_dep1.c', 'src/src_1');
-  console.log('tmpsrc/tmp_dep1.c task');
-});
-////////////////////////////////////////////////////////////
-
-
-////////////////////////////////////////////////////////////
-// Namespace Test. This is a Mixed Test.
-// Test for
-// -  rules belonging to different namespace.
-// -  rules with folder and pattern
-task('tmp_ns', [
-  'tmpbin'
-  , 'rule:init'
-  , 'tmpbin/tmp_dep2.oo'    // *** This relies on a rule defined before.
-  , 'rule:tmpbin/dep1.oo'
-  , 'rule:tmpbin/file2.oo' ], function () {
-  console.log('tmp pattern folder namespace task');
-  let data1 = fs.readFileSync('tmpbin/dep1.oo');
-  let data2 = fs.readFileSync('tmpbin/tmp_dep2.oo');
-  let data3 = fs.readFileSync('tmpbin/file2.oo');
-  fs.writeFileSync('tmp_ns', data1 + data2 + data3 + ' pattern folder namespace');
-});
-
-namespace('rule', function () {
-  task('init', ['tmpsrc'], function () {
-    fs.writeFileSync('tmpsrc/file2.c', 'src/src_3');
-    console.log('tmpsrc/file2.c init task');
-  });
-
-  file('tmpsrc/dep1.c',['tmpsrc'], function () {
-    fs.writeFileSync('tmpsrc/dep1.c', 'src/src_1');
-    console.log('tmpsrc/dep1.c task');
-  }, {async: true});
-
-  rule('tmpbin/%.oo', 'tmpsrc/%.c', function () {
-    let cmd = util.format('cp %s %s', this.source, this.name);
-    console.log(cmd + ' ns task');
-    exec(cmd);
-  });
-});
-////////////////////////////////////////////////////////////
-
-////////////////////////////////////////////////////////////
-// Chain rule
-// rule('tmpbin/%.pdf', 'tmpbin/%.dvi', function() { ...
-// rule('tmpbin/%.dvi', 'tmpsrc/%.tex', ['tmpbin'], function() { ...
-task('tmp_cr', [
-  'chainrule:init'
-  , 'chainrule:tmpbin/file1.pdf'
-  , 'chainrule:tmpbin/file2.pdf' ], function () {
-  console.log('tmp chainrule namespace task');
-  let data1 = fs.readFileSync('tmpbin/file1.pdf');
-  let data2 = fs.readFileSync('tmpbin/file2.pdf');
-  fs.writeFileSync('tmp_cr', data1 + data2 + ' chainrule namespace');
-});
-
-namespace('chainrule', function () {
-  task('init', ['tmpsrc', 'tmpbin'], function () {
-    fs.writeFileSync('tmpsrc/file1.tex', 'tex1 ');
-    fs.writeFileSync('tmpsrc/file2.tex', 'tex2 ');
-    console.log('chainrule init task');
-  });
-
-  rule('tmpbin/%.pdf', 'tmpbin/%.dvi', function () {
-    let cmd = util.format('cp %s %s', this.source, this.name);
-    console.log(cmd + ' dvi->pdf task');
-    exec(cmd);
-  });
-
-  rule('tmpbin/%.dvi', 'tmpsrc/%.tex', ['tmpbin'], function () {
-    let cmd = util.format('cp %s %s', this.source, this.name);
-    console.log(cmd + ' tex->dvi task');
-    exec(cmd);
-  });
-});
-////////////////////////////////////////////////////////////
-namespace('precedence', function () {
-  task('test', ['foo.html'], function () {
-    console.log('ran test');
-  });
-
-  rule('.html', '.txt', function () {
-    console.log('created html');
-    let data = fs.readFileSync(this.source);
-    fs.writeFileSync(this.name, data.toString());
-  });
-});
-
-namespace('regexPattern', function () {
-  task('test', ['foo.html'], function () {
-    console.log('ran test');
-  });
-
-  rule(/\.html$/, '.txt', function () {
-    console.log('created html');
-    let data = fs.readFileSync(this.source);
-    fs.writeFileSync(this.name, data.toString());
-  });
-});
-
-namespace('sourceFunction', function () {
-
-  let srcFunc = function (taskName) {
-    return taskName.replace(/\.[^.]+$/, '.txt');
-  };
-
-  task('test', ['foo.html'], function () {
-    console.log('ran test');
-  });
-
-  rule('.html', srcFunc, function () {
-    console.log('created html');
-    let data = fs.readFileSync(this.source);
-    fs.writeFileSync(this.name, data.toString());
-  });
-});
-
-////////////////////////////////////////////////////////////
-task('clean', function () {
-  rmRf('./foo');
-  rmRf('./tmp');
-});
+const PROJECT_DIR=process.env.PROJECT_DIR;let exec=require("child_process").execSync,fs=require("fs"),util=require("util"),{rule:rule,rmRf:rmRf}=require(`${PROJECT_DIR}/lib/jake`);directory("tmpsrc"),directory("tmpbin"),file("tmp",["tmp_init","tmp_dep1.o","tmp_dep2.o"],(function(t){console.log("tmp task");let e=fs.readFileSync("tmp_dep1.o"),n=fs.readFileSync("tmp_dep2.o");fs.writeFileSync("tmp",e+n)})),rule(".o",".c",(function(){let t=util.format("cp %s %s",this.source,this.name);console.log(t+" task"),exec(t)})),file("tmp_dep1.c",(function(){fs.writeFileSync("tmp_dep1.c","src_1"),console.log("tmp_dep1.c task")})),task("tmp_init",(function(){fs.writeFileSync("tmp_dep2.c","src_2"),console.log("tmp_dep2.c task")})),file("tmp_p",["tmp_init","tmp_dep1.oo","tmp_dep2.oo"],(function(t){console.log("tmp pattern task");let e=fs.readFileSync("tmp_dep1.oo"),n=fs.readFileSync("tmp_dep2.oo");fs.writeFileSync("tmp_p",e+n+" pattern")})),rule("%.oo","%.c",(function(){let t=util.format("cp %s %s",this.source,this.name);console.log(t+" task"),exec(t)})),file("tmp_pf",["tmp_src_init","tmpbin","tmpbin/tmp_dep1.oo","tmpbin/tmp_dep2.oo"],(function(t){console.log("tmp pattern folder task");let e=fs.readFileSync("tmpbin/tmp_dep1.oo"),n=fs.readFileSync("tmpbin/tmp_dep2.oo");fs.writeFileSync("tmp_pf",e+n+" pattern folder")})),rule("tmpbin/%.oo","tmpsrc/%.c",(function(){let t=util.format("cp %s %s",this.source,this.name);console.log(t+" task"),exec(t)})),file("tmpsrc/tmp_dep2.c",["tmpsrc"],(function(){fs.writeFileSync("tmpsrc/tmp_dep2.c","src/src_2"),console.log("tmpsrc/tmp_dep2.c task")})),task("tmp_src_init",["tmpsrc"],(function(){fs.writeFileSync("tmpsrc/tmp_dep1.c","src/src_1"),console.log("tmpsrc/tmp_dep1.c task")})),task("tmp_ns",["tmpbin","rule:init","tmpbin/tmp_dep2.oo","rule:tmpbin/dep1.oo","rule:tmpbin/file2.oo"],(function(){console.log("tmp pattern folder namespace task");let t=fs.readFileSync("tmpbin/dep1.oo"),e=fs.readFileSync("tmpbin/tmp_dep2.oo"),n=fs.readFileSync("tmpbin/file2.oo");fs.writeFileSync("tmp_ns",t+e+n+" pattern folder namespace")})),namespace("rule",(function(){task("init",["tmpsrc"],(function(){fs.writeFileSync("tmpsrc/file2.c","src/src_3"),console.log("tmpsrc/file2.c init task")})),file("tmpsrc/dep1.c",["tmpsrc"],(function(){fs.writeFileSync("tmpsrc/dep1.c","src/src_1"),console.log("tmpsrc/dep1.c task")}),{async:!0}),rule("tmpbin/%.oo","tmpsrc/%.c",(function(){let t=util.format("cp %s %s",this.source,this.name);console.log(t+" ns task"),exec(t)}))})),task("tmp_cr",["chainrule:init","chainrule:tmpbin/file1.pdf","chainrule:tmpbin/file2.pdf"],(function(){console.log("tmp chainrule namespace task");let t=fs.readFileSync("tmpbin/file1.pdf"),e=fs.readFileSync("tmpbin/file2.pdf");fs.writeFileSync("tmp_cr",t+e+" chainrule namespace")})),namespace("chainrule",(function(){task("init",["tmpsrc","tmpbin"],(function(){fs.writeFileSync("tmpsrc/file1.tex","tex1 "),fs.writeFileSync("tmpsrc/file2.tex","tex2 "),console.log("chainrule init task")})),rule("tmpbin/%.pdf","tmpbin/%.dvi",(function(){let t=util.format("cp %s %s",this.source,this.name);console.log(t+" dvi->pdf task"),exec(t)})),rule("tmpbin/%.dvi","tmpsrc/%.tex",["tmpbin"],(function(){let t=util.format("cp %s %s",this.source,this.name);console.log(t+" tex->dvi task"),exec(t)}))})),namespace("precedence",(function(){task("test",["foo.html"],(function(){console.log("ran test")})),rule(".html",".txt",(function(){console.log("created html");let t=fs.readFileSync(this.source);fs.writeFileSync(this.name,t.toString())}))})),namespace("regexPattern",(function(){task("test",["foo.html"],(function(){console.log("ran test")})),rule(/\.html$/,".txt",(function(){console.log("created html");let t=fs.readFileSync(this.source);fs.writeFileSync(this.name,t.toString())}))})),namespace("sourceFunction",(function(){task("test",["foo.html"],(function(){console.log("ran test")})),rule(".html",(function(t){return t.replace(/\.[^.]+$/,".txt")}),(function(){console.log("created html");let t=fs.readFileSync(this.source);fs.writeFileSync(this.name,t.toString())}))})),task("clean",(function(){rmRf("./foo"),rmRf("./tmp")}));
\ No newline at end of file
index 034fd94..cbaa13d 100755 (executable)
@@ -1,24 +1 @@
-let assert = require('assert');
-let exec = require('child_process').execSync;
-
-suite('publishTask', function () {
-
-  this.timeout(7000);
-
-  test('default task', function () {
-    let out = exec('./node_modules/.bin/jake  -q publish').toString().trim();
-    let expected = [
-      'Fetched remote tags.'
-      , 'On branch v0.0'
-      , 'Bumped version number to v0.0.2.'
-      , 'Created package for zerb v0.0.2'
-      , 'Publishing zerb v0.0.2'
-      , './pkg/zerb-v0.0.2.tar.gz'
-      , 'BOOM! Published.'
-      , 'Cleaned up package'
-    ].join('\n');
-    assert.equal(expected, out);
-  });
-
-});
-
+let assert=require("assert"),exec=require("child_process").execSync;suite("publishTask",(function(){this.timeout(7e3),test("default task",(function(){let e=exec("./node_modules/.bin/jake  -q publish").toString().trim(),t=["Fetched remote tags.","On branch v0.0","Bumped version number to v0.0.2.","Created package for zerb v0.0.2","Publishing zerb v0.0.2","./pkg/zerb-v0.0.2.tar.gz","BOOM! Published.","Cleaned up package"].join("\n");assert.equal(t,e)}))}));
\ No newline at end of file
index b837b1d..6c018c2 100755 (executable)
@@ -1,216 +1 @@
-/*
- * Jake JavaScript build tool
- * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-*/
-
-const PROJECT_DIR = process.env.PROJECT_DIR;
-
-let assert = require('assert');
-let exec = require('child_process').execSync;
-let fs = require('fs');
-let { Rule } = require(`${PROJECT_DIR}/lib/rule`);
-let { rmRf } = require(`${PROJECT_DIR}/lib/jake`);
-
-let cleanUpAndNext = function (callback) {
-  // Gotta add globbing to file utils rmRf
-  let tmpFiles = [
-    'tmp'
-    , 'tmp_ns'
-    , 'tmp_cr'
-    , 'tmp_p'
-    , 'tmp_pf'
-    , 'tmpbin'
-    , 'tmpsrc'
-    , 'tmp_dep1.c'
-    , 'tmp_dep1.o'
-    , 'tmp_dep1.oo'
-    , 'tmp_dep2.c'
-    , 'tmp_dep2.o'
-    , 'tmp_dep2.oo'
-    , 'foo'
-    , 'foo.html'
-  ];
-  tmpFiles.forEach(function (f) {
-    rmRf(f, {
-      silent: true
-    });
-  });
-  callback && callback();
-};
-
-suite('rule', function () {
-
-  this.timeout(7000);
-
-  setup(function (next) {
-    cleanUpAndNext(next);
-  });
-
-
-  //  - name   foo:bin/main.o
-  //  - pattern    bin/%.o
-  //  - source    src/%.c
-  //
-  // return {
-  //    'dep' : 'foo:src/main.c',
-  //    'file': 'src/main.c'
-  //  };
-  test('Rule.getSource', function () {
-    let src = Rule.getSource('foo:bin/main.o', 'bin/%.o', 'src/%.c');
-    assert.equal('foo:src/main.c', src);
-  });
-
-  test('rule w/o pattern', function () {
-    let out = exec( './node_modules/.bin/jake -q  tmp').toString().trim();
-    let output = [
-      "tmp_dep2.c task"
-      , "tmp_dep1.c task"
-      , "cp tmp_dep1.c tmp_dep1.o task"
-      , "cp tmp_dep2.c tmp_dep2.o task"
-      , "tmp task"];
-    assert.equal( output.join('\n'), out);
-    let data = fs.readFileSync(process.cwd() + '/tmp');
-    assert.equal('src_1src_2', data.toString());
-    cleanUpAndNext();
-  });
-
-  test('rule w pattern w/o folder w/o namespace', function () {
-    let out = exec( './node_modules/.bin/jake  -q  tmp_p').toString().trim();
-    let output = [
-      "tmp_dep2.c task"
-      , "tmp_dep1.c task"
-      , "cp tmp_dep1.c tmp_dep1.oo task"
-      , "cp tmp_dep2.c tmp_dep2.oo task"
-      , "tmp pattern task"];
-    let data;
-    assert.equal( output.join('\n'), out);
-    data = fs.readFileSync(process.cwd() + '/tmp_p');
-    assert.equal('src_1src_2 pattern', data.toString());
-    cleanUpAndNext();
-  });
-
-  test('rule w pattern w folder w/o namespace', function () {
-    let out = exec( './node_modules/.bin/jake  -q  tmp_pf').toString().trim();
-    let output = [
-      "tmpsrc/tmp_dep1.c task"
-      , "cp tmpsrc/tmp_dep1.c tmpbin/tmp_dep1.oo task"
-      , "tmpsrc/tmp_dep2.c task"
-      , "cp tmpsrc/tmp_dep2.c tmpbin/tmp_dep2.oo task"
-      , "tmp pattern folder task"];
-    let data;
-    assert.equal( output.join('\n'), out);
-    data = fs.readFileSync(process.cwd() + '/tmp_pf');
-    assert.equal('src/src_1src/src_2 pattern folder', data.toString());
-    cleanUpAndNext();
-  });
-
-  test.skip('rule w pattern w folder w namespace', function () {
-    let out = exec( './node_modules/.bin/jake -q   tmp_ns').toString().trim();
-    let output = [
-      "tmpsrc/file2.c init task" // yes
-      , "tmpsrc/tmp_dep2.c task" // no
-      , "cp tmpsrc/tmp_dep2.c tmpbin/tmp_dep2.oo task" // no
-      , "tmpsrc/dep1.c task" // no
-      , "cp tmpsrc/dep1.c tmpbin/dep1.oo ns task" // no
-      , "cp tmpsrc/file2.c tmpbin/file2.oo ns task" // yes
-      , "tmp pattern folder namespace task"]; // yes
-    let data;
-    assert.equal( output.join('\n'), out);
-    data = fs.readFileSync(process.cwd() + '/tmp_ns');
-    assert.equal('src/src_1src/src_2src/src_3 pattern folder namespace', data.toString());
-    cleanUpAndNext();
-  });
-
-  test.skip('rule w chain w pattern w folder w namespace', function () {
-    let out = exec( './node_modules/.bin/jake -q tmp_cr').toString().trim();
-    let output = [
-      "chainrule init task"
-      , "cp tmpsrc/file1.tex tmpbin/file1.dvi tex->dvi task"
-      , "cp tmpbin/file1.dvi tmpbin/file1.pdf dvi->pdf task"
-      , "cp tmpsrc/file2.tex tmpbin/file2.dvi tex->dvi task"
-      , "cp tmpbin/file2.dvi tmpbin/file2.pdf dvi->pdf task"
-      , "tmp chainrule namespace task"];
-    let data;
-    assert.equal( output.join('\n'), out);
-    data = fs.readFileSync(process.cwd() + '/tmp_cr');
-    assert.equal('tex1 tex2  chainrule namespace', data.toString());
-    cleanUpAndNext();
-  });
-
-
-  ['precedence', 'regexPattern', 'sourceFunction'].forEach(function (key) {
-
-    test('rule with source file not created yet (' + key  + ')', function () {
-      let write = process.stderr.write;
-      process.stderr.write = () => {};
-      rmRf('foo.txt', {silent: true});
-      rmRf('foo.html', {silent: true});
-      try {
-        exec('./node_modules/.bin/jake  ' + key + ':test');
-      }
-      catch(err) {
-        // foo.txt prereq doesn't exist yet
-        assert.ok(err.message.indexOf('Unknown task "foo.html"') > -1);
-      }
-      process.stderr.write = write;
-    });
-
-    test('rule with source file now created (' + key  + ')', function () {
-      fs.writeFileSync('foo.txt', '');
-      let out = exec('./node_modules/.bin/jake -q  ' + key + ':test').toString().trim();
-      // Should run prereq and test task
-      let output = [
-        'created html'
-        , 'ran test'
-      ];
-      assert.equal(output.join('\n'), out);
-    });
-
-    test('rule with source file modified (' + key  + ')', function (next) {
-      setTimeout(function () {
-        fs.writeFileSync('foo.txt', '');
-        let out = exec('./node_modules/.bin/jake -q  ' + key + ':test').toString().trim();
-        // Should again run both prereq and test task
-        let output = [
-          'created html'
-          , 'ran test'
-        ];
-        assert.equal(output.join('\n'), out);
-        //next();
-        cleanUpAndNext(next);
-      }, 1000); // Wait to do the touch to ensure mod-time is different
-    });
-
-    test('rule with existing objective file and no source ' +
-        ' (should be normal file-task) (' + key  + ')', function () {
-      // Remove just the source file
-      fs.writeFileSync('foo.html', '');
-      rmRf('foo.txt', {silent: true});
-      let out = exec('./node_modules/.bin/jake -q  ' + key + ':test').toString().trim();
-      // Should treat existing objective file as plain file-task,
-      // and just run test-task
-      let output = [
-        'ran test'
-      ];
-      assert.equal(output.join('\n'), out);
-      cleanUpAndNext();
-    });
-
-  });
-
-});
-
-
+const PROJECT_DIR=process.env.PROJECT_DIR;let assert=require("assert"),exec=require("child_process").execSync,fs=require("fs"),{Rule:Rule}=require(`${PROJECT_DIR}/lib/rule`),{rmRf:rmRf}=require(`${PROJECT_DIR}/lib/jake`),cleanUpAndNext=function(e){["tmp","tmp_ns","tmp_cr","tmp_p","tmp_pf","tmpbin","tmpsrc","tmp_dep1.c","tmp_dep1.o","tmp_dep1.oo","tmp_dep2.c","tmp_dep2.o","tmp_dep2.oo","foo","foo.html"].forEach((function(e){rmRf(e,{silent:!0})})),e&&e()};suite("rule",(function(){this.timeout(7e3),setup((function(e){cleanUpAndNext(e)})),test("Rule.getSource",(function(){let e=Rule.getSource("foo:bin/main.o","bin/%.o","src/%.c");assert.equal("foo:src/main.c",e)})),test("rule w/o pattern",(function(){let e=exec("./node_modules/.bin/jake -q  tmp").toString().trim();assert.equal(["tmp_dep2.c task","tmp_dep1.c task","cp tmp_dep1.c tmp_dep1.o task","cp tmp_dep2.c tmp_dep2.o task","tmp task"].join("\n"),e);let t=fs.readFileSync(process.cwd()+"/tmp");assert.equal("src_1src_2",t.toString()),cleanUpAndNext()})),test("rule w pattern w/o folder w/o namespace",(function(){let e,t=exec("./node_modules/.bin/jake  -q  tmp_p").toString().trim();assert.equal(["tmp_dep2.c task","tmp_dep1.c task","cp tmp_dep1.c tmp_dep1.oo task","cp tmp_dep2.c tmp_dep2.oo task","tmp pattern task"].join("\n"),t),e=fs.readFileSync(process.cwd()+"/tmp_p"),assert.equal("src_1src_2 pattern",e.toString()),cleanUpAndNext()})),test("rule w pattern w folder w/o namespace",(function(){let e,t=exec("./node_modules/.bin/jake  -q  tmp_pf").toString().trim();assert.equal(["tmpsrc/tmp_dep1.c task","cp tmpsrc/tmp_dep1.c tmpbin/tmp_dep1.oo task","tmpsrc/tmp_dep2.c task","cp tmpsrc/tmp_dep2.c tmpbin/tmp_dep2.oo task","tmp pattern folder task"].join("\n"),t),e=fs.readFileSync(process.cwd()+"/tmp_pf"),assert.equal("src/src_1src/src_2 pattern folder",e.toString()),cleanUpAndNext()})),test.skip("rule w pattern w folder w namespace",(function(){let e,t=exec("./node_modules/.bin/jake -q   tmp_ns").toString().trim();assert.equal(["tmpsrc/file2.c init task","tmpsrc/tmp_dep2.c task","cp tmpsrc/tmp_dep2.c tmpbin/tmp_dep2.oo task","tmpsrc/dep1.c task","cp tmpsrc/dep1.c tmpbin/dep1.oo ns task","cp tmpsrc/file2.c tmpbin/file2.oo ns task","tmp pattern folder namespace task"].join("\n"),t),e=fs.readFileSync(process.cwd()+"/tmp_ns"),assert.equal("src/src_1src/src_2src/src_3 pattern folder namespace",e.toString()),cleanUpAndNext()})),test.skip("rule w chain w pattern w folder w namespace",(function(){let e,t=exec("./node_modules/.bin/jake -q tmp_cr").toString().trim();assert.equal(["chainrule init task","cp tmpsrc/file1.tex tmpbin/file1.dvi tex->dvi task","cp tmpbin/file1.dvi tmpbin/file1.pdf dvi->pdf task","cp tmpsrc/file2.tex tmpbin/file2.dvi tex->dvi task","cp tmpbin/file2.dvi tmpbin/file2.pdf dvi->pdf task","tmp chainrule namespace task"].join("\n"),t),e=fs.readFileSync(process.cwd()+"/tmp_cr"),assert.equal("tex1 tex2  chainrule namespace",e.toString()),cleanUpAndNext()})),["precedence","regexPattern","sourceFunction"].forEach((function(e){test("rule with source file not created yet ("+e+")",(function(){let t=process.stderr.write;process.stderr.write=()=>{},rmRf("foo.txt",{silent:!0}),rmRf("foo.html",{silent:!0});try{exec("./node_modules/.bin/jake  "+e+":test")}catch(e){assert.ok(e.message.indexOf('Unknown task "foo.html"')>-1)}process.stderr.write=t})),test("rule with source file now created ("+e+")",(function(){fs.writeFileSync("foo.txt","");let t=exec("./node_modules/.bin/jake -q  "+e+":test").toString().trim();assert.equal(["created html","ran test"].join("\n"),t)})),test("rule with source file modified ("+e+")",(function(t){setTimeout((function(){fs.writeFileSync("foo.txt","");let s=exec("./node_modules/.bin/jake -q  "+e+":test").toString().trim();assert.equal(["created html","ran test"].join("\n"),s),cleanUpAndNext(t)}),1e3)})),test("rule with existing objective file and no source  (should be normal file-task) ("+e+")",(function(){fs.writeFileSync("foo.html",""),rmRf("foo.txt",{silent:!0});let t=exec("./node_modules/.bin/jake -q  "+e+":test").toString().trim();assert.equal(["ran test"].join("\n"),t),cleanUpAndNext()}))}))}));
\ No newline at end of file
index 22d58d1..b8c469e 100755 (executable)
@@ -1,39 +1 @@
-let assert = require('assert');
-let exec = require('child_process').execSync;
-
-suite('selfDep', function () {
-
-  this.timeout(7000);
-
-  let origStderrWrite;
-
-  setup(function () {
-    origStderrWrite = process.stderr.write;
-    process.stderr.write = function () {};
-  });
-
-  teardown(function () {
-    process.stderr.write = origStderrWrite;
-  });
-
-  test('self dep const', function () {
-    try {
-      exec('./node_modules/.bin/jake selfdepconst');
-    }
-    catch(e) {
-      assert(e.message.indexOf('dependency of itself') > -1)
-    }
-  });
-
-  test('self dep dyn', function () {
-    try {
-      exec('./node_modules/.bin/jake selfdepdyn');
-    }
-    catch(e) {
-      assert(e.message.indexOf('dependency of itself') > -1)
-    }
-  });
-
-});
-
-
+let assert=require("assert"),exec=require("child_process").execSync;suite("selfDep",(function(){let e;this.timeout(7e3),setup((function(){e=process.stderr.write,process.stderr.write=function(){}})),teardown((function(){process.stderr.write=e})),test("self dep const",(function(){try{exec("./node_modules/.bin/jake selfdepconst")}catch(e){assert(e.message.indexOf("dependency of itself")>-1)}})),test("self dep dyn",(function(){try{exec("./node_modules/.bin/jake selfdepdyn")}catch(e){assert(e.message.indexOf("dependency of itself")>-1)}}))}));
\ No newline at end of file
index 36e20e8..24d00f3 100755 (executable)
@@ -1,164 +1 @@
-let assert = require('assert');
-let h = require('./helpers');
-let exec = require('child_process').execSync;
-
-suite('taskBase', function () {
-
-  this.timeout(7000);
-
-  test('default task', function () {
-    let out;
-    out = exec('./node_modules/.bin/jake -q').toString().trim();
-    assert.equal(out, 'default task');
-    out = exec('./node_modules/.bin/jake -q default').toString().trim();
-    assert.equal(out, 'default task');
-  });
-
-  test('task with no action', function () {
-    let out = exec('./node_modules/.bin/jake -q noAction').toString().trim();
-    assert.equal(out, 'default task');
-  });
-
-  test('a task with no action and no prereqs', function () {
-    exec('./node_modules/.bin/jake noActionNoPrereqs');
-  });
-
-  test('a task that exists at the top-level, and not in the specified namespace, should error', function () {
-    let res = require('child_process').spawnSync('./node_modules/.bin/jake',
-    ['asdfasdfasdf:zerbofrangazoomy']);
-    let err = res.stderr.toString();
-    assert.ok(err.indexOf('Unknown task' > -1));
-  });
-
-  test('passing args to a task', function () {
-    let out = exec('./node_modules/.bin/jake -q argsEnvVars[foo,bar]').toString().trim();
-    let parsed = h.parse(out);
-    let args = parsed.args;
-    assert.equal(args[0], 'foo');
-    assert.equal(args[1], 'bar');
-  });
-
-  test('a task with environment vars', function () {
-    let out = exec('./node_modules/.bin/jake -q argsEnvVars foo=bar baz=qux').toString().trim();
-    let parsed = h.parse(out);
-    let env = parsed.env;
-    assert.equal(env.foo, 'bar');
-    assert.equal(env.baz, 'qux');
-  });
-
-  test('passing args and using environment vars', function () {
-    let out = exec('./node_modules/.bin/jake -q argsEnvVars[foo,bar] foo=bar baz=qux').toString().trim();
-    let parsed = h.parse(out);
-    let args = parsed.args;
-    let env = parsed.env;
-    assert.equal(args[0], 'foo');
-    assert.equal(args[1], 'bar');
-    assert.equal(env.foo, 'bar');
-    assert.equal(env.baz, 'qux');
-  });
-
-  test('a simple prereq', function () {
-    let out = exec('./node_modules/.bin/jake -q foo:baz').toString().trim();
-    assert.equal(out, 'foo:bar task\nfoo:baz task');
-  });
-
-  test('a duplicate prereq only runs once', function () {
-    let out = exec('./node_modules/.bin/jake -q foo:asdf').toString().trim();
-    assert.equal(out, 'foo:bar task\nfoo:baz task\nfoo:asdf task');
-  });
-
-  test('a prereq with command-line args', function () {
-    let out = exec('./node_modules/.bin/jake -q foo:qux').toString().trim();
-    assert.equal(out, 'foo:bar[asdf,qwer] task\nfoo:qux task');
-  });
-
-  test('a prereq with args via invoke', function () {
-    let out = exec('./node_modules/.bin/jake -q foo:frang[zxcv,uiop]').toString().trim();
-    assert.equal(out, 'foo:bar[zxcv,uiop] task\nfoo:frang task');
-  });
-
-  test('a prereq with args via execute', function () {
-    let out = exec('./node_modules/.bin/jake -q foo:zerb[zxcv,uiop]').toString().trim();
-    assert.equal(out, 'foo:bar[zxcv,uiop] task\nfoo:zerb task');
-  });
-
-  test('repeating the task via execute', function () {
-    let out = exec('./node_modules/.bin/jake -q foo:voom').toString().trim();
-    assert.equal(out, 'foo:bar task\nfoo:bar task\ncomplete\ncomplete');
-  });
-
-  test('prereq execution-order', function () {
-    let out = exec('./node_modules/.bin/jake -q hoge:fuga').toString().trim();
-    assert.equal(out, 'hoge:hoge task\nhoge:piyo task\nhoge:fuga task');
-  });
-
-  test('basic async task', function () {
-    let out = exec('./node_modules/.bin/jake -q bar:bar').toString().trim();
-    assert.equal(out, 'bar:foo task\nbar:bar task');
-  });
-
-  test('promise async task', function () {
-    let out = exec('./node_modules/.bin/jake -q bar:dependOnpromise').toString().trim();
-    assert.equal(out, 'bar:promise task\nbar:dependOnpromise task saw value 123654');
-  });
-
-  test('failing promise async task', function () {
-    try {
-      exec('./node_modules/.bin/jake -q bar:brokenPromise');
-    }
-    catch(e) {
-      assert(e.message.indexOf('Command failed') > -1);
-    }
-  });
-
-  test('that current-prereq index gets reset', function () {
-    let out = exec('./node_modules/.bin/jake -q hoge:kira').toString().trim();
-    assert.equal(out, 'hoge:hoge task\nhoge:piyo task\nhoge:fuga task\n' +
-        'hoge:charan task\nhoge:gero task\nhoge:kira task');
-  });
-
-  test('modifying a task by adding prereq during execution', function () {
-    let out = exec('./node_modules/.bin/jake -q voom').toString().trim();
-    assert.equal(out, 2);
-  });
-
-  test('listening for task error-event', function () {
-    try {
-      exec('./node_modules/.bin/jake -q vronk:groo').toString().trim();
-    }
-    catch(e) {
-      assert(e.message.indexOf('OMFGZONG') > -1);
-    }
-  });
-
-  test('listening for jake error-event', function () {
-    let out = exec('./node_modules/.bin/jake -q throwy').toString().trim();
-    assert(out.indexOf('Emitted\nError: I am bad') > -1);
-  });
-
-  test('listening for jake unhandledRejection-event', function () {
-    let out = exec('./node_modules/.bin/jake -q promiseRejecter').toString().trim();
-    assert.equal(out, '<promise rejected on purpose>');
-  });
-
-  test('large number of same prereqs', function () {
-    let out = exec('./node_modules/.bin/jake -q large:same').toString().trim();
-    assert.equal(out, 'large:leaf\nlarge:same');
-  });
-
-  test('large number of different prereqs', function () {
-    let out = exec('./node_modules/.bin/jake -q large:different').toString().trim();
-    assert.equal(out, 'leaf-12\nleaf-123\nlarge:different');
-  });
-
-  test('large number of different prereqs', function () {
-    let out = exec('./node_modules/.bin/jake -q usingRequire:test').toString().trim();
-    assert.equal(out, 'howdy test');
-  });
-
-  test('modifying a namespace by adding a new task', function () {
-    let out = exec('./node_modules/.bin/jake -q one:two').toString().trim();
-    assert.equal('one:one\none:two', out);
-  });
-
-});
+let assert=require("assert"),h=require("./helpers"),exec=require("child_process").execSync;suite("taskBase",(function(){this.timeout(7e3),test("default task",(function(){let e;e=exec("./node_modules/.bin/jake -q").toString().trim(),assert.equal(e,"default task"),e=exec("./node_modules/.bin/jake -q default").toString().trim(),assert.equal(e,"default task")})),test("task with no action",(function(){let e=exec("./node_modules/.bin/jake -q noAction").toString().trim();assert.equal(e,"default task")})),test("a task with no action and no prereqs",(function(){exec("./node_modules/.bin/jake noActionNoPrereqs")})),test("a task that exists at the top-level, and not in the specified namespace, should error",(function(){let e=require("child_process").spawnSync("./node_modules/.bin/jake",["asdfasdfasdf:zerbofrangazoomy"]).stderr.toString();assert.ok(e.indexOf(!1))})),test("passing args to a task",(function(){let e=exec("./node_modules/.bin/jake -q argsEnvVars[foo,bar]").toString().trim(),t=h.parse(e).args;assert.equal(t[0],"foo"),assert.equal(t[1],"bar")})),test("a task with environment vars",(function(){let e=exec("./node_modules/.bin/jake -q argsEnvVars foo=bar baz=qux").toString().trim(),t=h.parse(e).env;assert.equal(t.foo,"bar"),assert.equal(t.baz,"qux")})),test("passing args and using environment vars",(function(){let e=exec("./node_modules/.bin/jake -q argsEnvVars[foo,bar] foo=bar baz=qux").toString().trim(),t=h.parse(e),a=t.args,o=t.env;assert.equal(a[0],"foo"),assert.equal(a[1],"bar"),assert.equal(o.foo,"bar"),assert.equal(o.baz,"qux")})),test("a simple prereq",(function(){let e=exec("./node_modules/.bin/jake -q foo:baz").toString().trim();assert.equal(e,"foo:bar task\nfoo:baz task")})),test("a duplicate prereq only runs once",(function(){let e=exec("./node_modules/.bin/jake -q foo:asdf").toString().trim();assert.equal(e,"foo:bar task\nfoo:baz task\nfoo:asdf task")})),test("a prereq with command-line args",(function(){let e=exec("./node_modules/.bin/jake -q foo:qux").toString().trim();assert.equal(e,"foo:bar[asdf,qwer] task\nfoo:qux task")})),test("a prereq with args via invoke",(function(){let e=exec("./node_modules/.bin/jake -q foo:frang[zxcv,uiop]").toString().trim();assert.equal(e,"foo:bar[zxcv,uiop] task\nfoo:frang task")})),test("a prereq with args via execute",(function(){let e=exec("./node_modules/.bin/jake -q foo:zerb[zxcv,uiop]").toString().trim();assert.equal(e,"foo:bar[zxcv,uiop] task\nfoo:zerb task")})),test("repeating the task via execute",(function(){let e=exec("./node_modules/.bin/jake -q foo:voom").toString().trim();assert.equal(e,"foo:bar task\nfoo:bar task\ncomplete\ncomplete")})),test("prereq execution-order",(function(){let e=exec("./node_modules/.bin/jake -q hoge:fuga").toString().trim();assert.equal(e,"hoge:hoge task\nhoge:piyo task\nhoge:fuga task")})),test("basic async task",(function(){let e=exec("./node_modules/.bin/jake -q bar:bar").toString().trim();assert.equal(e,"bar:foo task\nbar:bar task")})),test("promise async task",(function(){let e=exec("./node_modules/.bin/jake -q bar:dependOnpromise").toString().trim();assert.equal(e,"bar:promise task\nbar:dependOnpromise task saw value 123654")})),test("failing promise async task",(function(){try{exec("./node_modules/.bin/jake -q bar:brokenPromise")}catch(e){assert(e.message.indexOf("Command failed")>-1)}})),test("that current-prereq index gets reset",(function(){let e=exec("./node_modules/.bin/jake -q hoge:kira").toString().trim();assert.equal(e,"hoge:hoge task\nhoge:piyo task\nhoge:fuga task\nhoge:charan task\nhoge:gero task\nhoge:kira task")})),test("modifying a task by adding prereq during execution",(function(){let e=exec("./node_modules/.bin/jake -q voom").toString().trim();assert.equal(e,2)})),test("listening for task error-event",(function(){try{exec("./node_modules/.bin/jake -q vronk:groo").toString().trim()}catch(e){assert(e.message.indexOf("OMFGZONG")>-1)}})),test("listening for jake error-event",(function(){let e=exec("./node_modules/.bin/jake -q throwy").toString().trim();assert(e.indexOf("Emitted\nError: I am bad")>-1)})),test("listening for jake unhandledRejection-event",(function(){let e=exec("./node_modules/.bin/jake -q promiseRejecter").toString().trim();assert.equal(e,"<promise rejected on purpose>")})),test("large number of same prereqs",(function(){let e=exec("./node_modules/.bin/jake -q large:same").toString().trim();assert.equal(e,"large:leaf\nlarge:same")})),test("large number of different prereqs",(function(){let e=exec("./node_modules/.bin/jake -q large:different").toString().trim();assert.equal(e,"leaf-12\nleaf-123\nlarge:different")})),test("large number of different prereqs",(function(){let e=exec("./node_modules/.bin/jake -q usingRequire:test").toString().trim();assert.equal(e,"howdy test")})),test("modifying a namespace by adding a new task",(function(){let e=exec("./node_modules/.bin/jake -q one:two").toString().trim();assert.equal("one:one\none:two",e)}))}));
\ No newline at end of file
index 89ff523..b38377d 100755 (executable)
@@ -1,36 +1 @@
-
-task('foo', function () {
-  console.log('ran top-level foo');
-});
-
-task('bar', function () {
-  console.log('ran top-level bar');
-});
-
-task('zerb', function () {
-  console.log('ran zerb');
-});
-
-namespace('zooby', function () {
-  task('zerp', function () {});
-
-  task('derp', ['zerp'], function () {});
-
-  namespace('frang', function () {
-
-    namespace('w00t', function () {
-      task('bar', function () {
-        console.log('ran zooby:frang:w00t:bar');
-      });
-    });
-
-    task('asdf', function () {});
-  });
-
-});
-
-namespace('hurr', function () {
-  namespace('durr');
-});
-
-
+task("foo",(function(){console.log("ran top-level foo")})),task("bar",(function(){console.log("ran top-level bar")})),task("zerb",(function(){console.log("ran zerb")})),namespace("zooby",(function(){task("zerp",(function(){})),task("derp",["zerp"],(function(){})),namespace("frang",(function(){namespace("w00t",(function(){task("bar",(function(){console.log("ran zooby:frang:w00t:bar")}))})),task("asdf",(function(){}))}))})),namespace("hurr",(function(){namespace("durr")}));
\ No newline at end of file
index c6b3ff5..4e7d1b6 100755 (executable)
@@ -1,77 +1 @@
-/*
- * Jake JavaScript build tool
- * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-*/
-
-const PROJECT_DIR = process.env.PROJECT_DIR;
-
-// Load the jake global
-require(`${PROJECT_DIR}/lib/jake`);
-let { Namespace } = require(`${PROJECT_DIR}/lib/namespace`);
-
-require('./jakefile');
-
-let assert = require('assert');
-
-suite('namespace', function () {
-
-  this.timeout(7000);
-
-  test('resolve namespace by relative name', function () {
-    let aaa, bbb, ccc;
-    aaa = namespace('aaa', function () {
-      bbb = namespace('bbb', function () {
-        ccc = namespace('ccc', function () {
-        });
-      });
-    });
-
-    assert.ok(aaa, Namespace.ROOT_NAMESPACE.resolveNamespace('aaa'));
-    assert.ok(bbb === aaa.resolveNamespace('bbb'));
-    assert.ok(ccc === aaa.resolveNamespace('bbb:ccc'));
-  });
-
-  test('resolve task in sub-namespace by relative path', function () {
-    let curr = Namespace.ROOT_NAMESPACE.resolveNamespace('zooby');
-    let task = curr.resolveTask('frang:w00t:bar');
-    assert.ok(task.action.toString().indexOf('zooby:frang:w00t:bar') > -1);
-  });
-
-  test('prefer local to top-level', function () {
-    let curr = Namespace.ROOT_NAMESPACE.resolveNamespace('zooby:frang:w00t');
-    let task = curr.resolveTask('bar');
-    assert.ok(task.action.toString().indexOf('zooby:frang:w00t:bar') > -1);
-  });
-
-  test('does resolve top-level', function () {
-    let curr = Namespace.ROOT_NAMESPACE.resolveNamespace('zooby:frang:w00t');
-    let task = curr.resolveTask('foo');
-    assert.ok(task.action.toString().indexOf('top-level foo') > -1);
-  });
-
-  test('absolute lookup works from sub-namespaces', function () {
-    let curr = Namespace.ROOT_NAMESPACE.resolveNamespace('hurr:durr');
-    let task = curr.resolveTask('zooby:frang:w00t:bar');
-    assert.ok(task.action.toString().indexOf('zooby:frang:w00t:bar') > -1);
-  });
-
-  test('resolution miss with throw error', function () {
-    let curr = Namespace.ROOT_NAMESPACE;
-    let task = curr.resolveTask('asdf:qwer');
-    assert.ok(!task);
-  });
-
-});
+const PROJECT_DIR=process.env.PROJECT_DIR;require(`${PROJECT_DIR}/lib/jake`);let{Namespace:Namespace}=require(`${PROJECT_DIR}/lib/namespace`);require("./jakefile");let assert=require("assert");suite("namespace",(function(){this.timeout(7e3),test("resolve namespace by relative name",(function(){let e,a,s;e=namespace("aaa",(function(){a=namespace("bbb",(function(){s=namespace("ccc",(function(){}))}))})),assert.ok(e,Namespace.ROOT_NAMESPACE.resolveNamespace("aaa")),assert.ok(a===e.resolveNamespace("bbb")),assert.ok(s===e.resolveNamespace("bbb:ccc"))})),test("resolve task in sub-namespace by relative path",(function(){let e=Namespace.ROOT_NAMESPACE.resolveNamespace("zooby").resolveTask("frang:w00t:bar");assert.ok(e.action.toString().indexOf("zooby:frang:w00t:bar")>-1)})),test("prefer local to top-level",(function(){let e=Namespace.ROOT_NAMESPACE.resolveNamespace("zooby:frang:w00t").resolveTask("bar");assert.ok(e.action.toString().indexOf("zooby:frang:w00t:bar")>-1)})),test("does resolve top-level",(function(){let e=Namespace.ROOT_NAMESPACE.resolveNamespace("zooby:frang:w00t").resolveTask("foo");assert.ok(e.action.toString().indexOf("top-level foo")>-1)})),test("absolute lookup works from sub-namespaces",(function(){let e=Namespace.ROOT_NAMESPACE.resolveNamespace("hurr:durr").resolveTask("zooby:frang:w00t:bar");assert.ok(e.action.toString().indexOf("zooby:frang:w00t:bar")>-1)})),test("resolution miss with throw error",(function(){let e=Namespace.ROOT_NAMESPACE.resolveTask("asdf:qwer");assert.ok(!e)}))}));
\ No newline at end of file
index 7a3ddd5..44adb2c 100755 (executable)
@@ -1,169 +1 @@
-/*
- * Jake JavaScript build tool
- * Copyright 2112 Matthew Eernisse (mde@fleegix.org)
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *         http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
-*/
-
-const PROJECT_DIR = process.env.PROJECT_DIR;
-
-let parseargs = require(`${PROJECT_DIR}/lib/parseargs`);
-let assert = require('assert');
-let optsReg = [
-  { full: 'directory',
-    abbr: 'C',
-    preempts: false,
-    expectValue: true
-  },
-  { full: 'jakefile',
-    abbr: 'f',
-    preempts: false,
-    expectValue: true
-  },
-  { full: 'tasks',
-    abbr: 'T',
-    preempts: true
-  },
-  { full: 'tasks',
-    abbr: 'ls',
-    preempts: true
-  },
-  { full: 'trace',
-    abbr: 't',
-    preempts: false,
-    expectValue: false
-  },
-  { full: 'help',
-    abbr: 'h',
-    preempts: true
-  },
-  { full: 'version',
-    abbr: 'V',
-    preempts: true
-  }
-];
-let p = new parseargs.Parser(optsReg);
-let z = function (s) { return s.split(' '); };
-let res;
-
-suite('parseargs', function () {
-
-  test('long preemptive opt and val with equal-sign, ignore further opts', function () {
-    res = p.parse(z('--tasks=foo --jakefile=asdf'));
-    assert.equal('foo', res.opts.tasks);
-    assert.equal(undefined, res.opts.jakefile);
-  });
-
-  test('long preemptive opt and val without equal-sign, ignore further opts', function () {
-    res = p.parse(z('--tasks foo --jakefile=asdf'));
-    assert.equal('foo', res.opts.tasks);
-    assert.equal(undefined, res.opts.jakefile);
-  });
-
-  test('long preemptive opt and no val, ignore further opts', function () {
-    res = p.parse(z('--tasks --jakefile=asdf'));
-    assert.equal(true, res.opts.tasks);
-    assert.equal(undefined, res.opts.jakefile);
-  });
-
-  test('preemptive opt with no val, should be true', function () {
-    res = p.parse(z('-T'));
-    assert.equal(true, res.opts.tasks);
-  });
-
-  test('preemptive opt with no val, should be true and ignore further opts', function () {
-    res = p.parse(z('-T -f'));
-    assert.equal(true, res.opts.tasks);
-    assert.equal(undefined, res.opts.jakefile);
-  });
-
-  test('preemptive opt with val, should be val', function () {
-    res = p.parse(z('-T zoobie -f foo/bar/baz'));
-    assert.equal('zoobie', res.opts.tasks);
-    assert.equal(undefined, res.opts.jakefile);
-  });
-
-  test('-f expects a value, -t does not (howdy is task-name)', function () {
-    res = p.parse(z('-f zoobie -t howdy'));
-    assert.equal('zoobie', res.opts.jakefile);
-    assert.equal(true, res.opts.trace);
-    assert.equal('howdy', res.taskNames[0]);
-  });
-
-  test('different order, -f expects a value, -t does not (howdy is task-name)', function () {
-    res = p.parse(z('-f zoobie howdy -t'));
-    assert.equal('zoobie', res.opts.jakefile);
-    assert.equal(true, res.opts.trace);
-    assert.equal('howdy', res.taskNames[0]);
-  });
-
-  test('-f expects a value, -t does not (foo=bar is env var)', function () {
-    res = p.parse(z('-f zoobie -t foo=bar'));
-    assert.equal('zoobie', res.opts.jakefile);
-    assert.equal(true, res.opts.trace);
-    assert.equal('bar', res.envVars.foo);
-    assert.equal(undefined, res.taskNames[0]);
-  });
-
-  test('-f expects a value, -t does not (foo=bar is env-var, task-name follows)', function () {
-    res = p.parse(z('-f zoobie -t howdy foo=bar'));
-    assert.equal('zoobie', res.opts.jakefile);
-    assert.equal(true, res.opts.trace);
-    assert.equal('bar', res.envVars.foo);
-    assert.equal('howdy', res.taskNames[0]);
-  });
-
-  test('-t does not expect a value, -f does (howdy is task-name)', function () {
-    res = p.parse(z('-t howdy -f zoobie'));
-    assert.equal(true, res.opts.trace);
-    assert.equal('zoobie', res.opts.jakefile);
-    assert.equal('howdy', res.taskNames[0]);
-  });
-
-  test('--trace does not expect a value, -f does (howdy is task-name)', function () {
-    res = p.parse(z('--trace howdy --jakefile zoobie'));
-    assert.equal(true, res.opts.trace);
-    assert.equal('zoobie', res.opts.jakefile);
-    assert.equal('howdy', res.taskNames[0]);
-  });
-
-  test('--trace does not expect a value (equal), -f does (throw howdy away)', function () {
-    res = p.parse(z('--trace=howdy --jakefile=zoobie'));
-    assert.equal(true, res.opts.trace);
-    assert.equal('zoobie', res.opts.jakefile);
-    assert.equal(undefined, res.taskNames[0]);
-  });
-
-  /*
-, test('task-name with positional args', function () {
-    res = p.parse(z('foo:bar[asdf,qwer]'));
-    assert.equal('asdf', p.taskArgs[0]);
-    assert.equal('qwer', p.taskArgs[1]);
-  }
-
-, test('opts, env vars, task-name with positional args', function () {
-    res = p.parse(z('-f ./tests/Jakefile -t default[asdf,qwer] foo=bar'));
-    assert.equal('./tests/Jakefile', res.opts.jakefile);
-    assert.equal(true, res.opts.trace);
-    assert.equal('bar', res.envVars.foo);
-    assert.equal('default', res.taskName);
-    assert.equal('asdf', p.taskArgs[0]);
-    assert.equal('qwer', p.taskArgs[1]);
-  }
-*/
-
-
-});
-
-
+const PROJECT_DIR=process.env.PROJECT_DIR;let res,parseargs=require(`${PROJECT_DIR}/lib/parseargs`),assert=require("assert"),optsReg=[{full:"directory",abbr:"C",preempts:!1,expectValue:!0},{full:"jakefile",abbr:"f",preempts:!1,expectValue:!0},{full:"tasks",abbr:"T",preempts:!0},{full:"tasks",abbr:"ls",preempts:!0},{full:"trace",abbr:"t",preempts:!1,expectValue:!1},{full:"help",abbr:"h",preempts:!0},{full:"version",abbr:"V",preempts:!0}],p=new parseargs.Parser(optsReg),z=function(e){return e.split(" ")};suite("parseargs",(function(){test("long preemptive opt and val with equal-sign, ignore further opts",(function(){res=p.parse(z("--tasks=foo --jakefile=asdf")),assert.equal("foo",res.opts.tasks),assert.equal(void 0,res.opts.jakefile)})),test("long preemptive opt and val without equal-sign, ignore further opts",(function(){res=p.parse(z("--tasks foo --jakefile=asdf")),assert.equal("foo",res.opts.tasks),assert.equal(void 0,res.opts.jakefile)})),test("long preemptive opt and no val, ignore further opts",(function(){res=p.parse(z("--tasks --jakefile=asdf")),assert.equal(!0,res.opts.tasks),assert.equal(void 0,res.opts.jakefile)})),test("preemptive opt with no val, should be true",(function(){res=p.parse(z("-T")),assert.equal(!0,res.opts.tasks)})),test("preemptive opt with no val, should be true and ignore further opts",(function(){res=p.parse(z("-T -f")),assert.equal(!0,res.opts.tasks),assert.equal(void 0,res.opts.jakefile)})),test("preemptive opt with val, should be val",(function(){res=p.parse(z("-T zoobie -f foo/bar/baz")),assert.equal("zoobie",res.opts.tasks),assert.equal(void 0,res.opts.jakefile)})),test("-f expects a value, -t does not (howdy is task-name)",(function(){res=p.parse(z("-f zoobie -t howdy")),assert.equal("zoobie",res.opts.jakefile),assert.equal(!0,res.opts.trace),assert.equal("howdy",res.taskNames[0])})),test("different order, -f expects a value, -t does not (howdy is task-name)",(function(){res=p.parse(z("-f zoobie howdy -t")),assert.equal("zoobie",res.opts.jakefile),assert.equal(!0,res.opts.trace),assert.equal("howdy",res.taskNames[0])})),test("-f expects a value, -t does not (foo=bar is env var)",(function(){res=p.parse(z("-f zoobie -t foo=bar")),assert.equal("zoobie",res.opts.jakefile),assert.equal(!0,res.opts.trace),assert.equal("bar",res.envVars.foo),assert.equal(void 0,res.taskNames[0])})),test("-f expects a value, -t does not (foo=bar is env-var, task-name follows)",(function(){res=p.parse(z("-f zoobie -t howdy foo=bar")),assert.equal("zoobie",res.opts.jakefile),assert.equal(!0,res.opts.trace),assert.equal("bar",res.envVars.foo),assert.equal("howdy",res.taskNames[0])})),test("-t does not expect a value, -f does (howdy is task-name)",(function(){res=p.parse(z("-t howdy -f zoobie")),assert.equal(!0,res.opts.trace),assert.equal("zoobie",res.opts.jakefile),assert.equal("howdy",res.taskNames[0])})),test("--trace does not expect a value, -f does (howdy is task-name)",(function(){res=p.parse(z("--trace howdy --jakefile zoobie")),assert.equal(!0,res.opts.trace),assert.equal("zoobie",res.opts.jakefile),assert.equal("howdy",res.taskNames[0])})),test("--trace does not expect a value (equal), -f does (throw howdy away)",(function(){res=p.parse(z("--trace=howdy --jakefile=zoobie")),assert.equal(!0,res.opts.trace),assert.equal("zoobie",res.opts.jakefile),assert.equal(void 0,res.taskNames[0])}))}));
\ No newline at end of file
index 5aae6ee..5139335 100644 (file)
@@ -1,24 +1 @@
-'use strict';
-const path = require('path');
-const pathExists = require('path-exists');
-const pLocate = require('p-locate');
-
-module.exports = (iterable, options) => {
-       options = Object.assign({
-               cwd: process.cwd()
-       }, options);
-
-       return pLocate(iterable, el => pathExists(path.resolve(options.cwd, el)), options);
-};
-
-module.exports.sync = (iterable, options) => {
-       options = Object.assign({
-               cwd: process.cwd()
-       }, options);
-
-       for (const el of iterable) {
-               if (pathExists.sync(path.resolve(options.cwd, el))) {
-                       return el;
-               }
-       }
-};
+"use strict";const path=require("path"),pathExists=require("path-exists"),pLocate=require("p-locate");module.exports=(s,e)=>(e=Object.assign({cwd:process.cwd()},e),pLocate(s,(s=>pathExists(path.resolve(e.cwd,s))),e)),module.exports.sync=(s,e)=>{e=Object.assign({cwd:process.cwd()},e);for(const t of s)if(pathExists.sync(path.resolve(e.cwd,t)))return t};
\ No newline at end of file
index 07f7295..ce3b29f 100644 (file)
@@ -3,268 +3,4 @@
  * Copyright(c) 2014 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-/**
- * RegExp to match *( ";" parameter ) in RFC 2616 sec 3.7
- *
- * parameter     = token "=" ( token | quoted-string )
- * token         = 1*<any CHAR except CTLs or separators>
- * separators    = "(" | ")" | "<" | ">" | "@"
- *               | "," | ";" | ":" | "\" | <">
- *               | "/" | "[" | "]" | "?" | "="
- *               | "{" | "}" | SP | HT
- * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> )
- * qdtext        = <any TEXT except <">>
- * quoted-pair   = "\" CHAR
- * CHAR          = <any US-ASCII character (octets 0 - 127)>
- * TEXT          = <any OCTET except CTLs, but including LWS>
- * LWS           = [CRLF] 1*( SP | HT )
- * CRLF          = CR LF
- * CR            = <US-ASCII CR, carriage return (13)>
- * LF            = <US-ASCII LF, linefeed (10)>
- * SP            = <US-ASCII SP, space (32)>
- * SHT           = <US-ASCII HT, horizontal-tab (9)>
- * CTL           = <any US-ASCII control character (octets 0 - 31) and DEL (127)>
- * OCTET         = <any 8-bit sequence of data>
- */
-var paramRegExp = /; *([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *= *("(?:[ !\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u0020-\u007e])*"|[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) */g;
-var textRegExp = /^[\u0020-\u007e\u0080-\u00ff]+$/
-var tokenRegExp = /^[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+$/
-
-/**
- * RegExp to match quoted-pair in RFC 2616
- *
- * quoted-pair = "\" CHAR
- * CHAR        = <any US-ASCII character (octets 0 - 127)>
- */
-var qescRegExp = /\\([\u0000-\u007f])/g;
-
-/**
- * RegExp to match chars that must be quoted-pair in RFC 2616
- */
-var quoteRegExp = /([\\"])/g;
-
-/**
- * RegExp to match type in RFC 6838
- *
- * type-name = restricted-name
- * subtype-name = restricted-name
- * restricted-name = restricted-name-first *126restricted-name-chars
- * restricted-name-first  = ALPHA / DIGIT
- * restricted-name-chars  = ALPHA / DIGIT / "!" / "#" /
- *                          "$" / "&" / "-" / "^" / "_"
- * restricted-name-chars =/ "." ; Characters before first dot always
- *                              ; specify a facet name
- * restricted-name-chars =/ "+" ; Characters after last plus always
- *                              ; specify a structured syntax suffix
- * ALPHA =  %x41-5A / %x61-7A   ; A-Z / a-z
- * DIGIT =  %x30-39             ; 0-9
- */
-var subtypeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_.-]{0,126}$/
-var typeNameRegExp = /^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}$/
-var typeRegExp = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/;
-
-/**
- * Module exports.
- */
-
-exports.format = format
-exports.parse = parse
-
-/**
- * Format object to media type.
- *
- * @param {object} obj
- * @return {string}
- * @api public
- */
-
-function format(obj) {
-  if (!obj || typeof obj !== 'object') {
-    throw new TypeError('argument obj is required')
-  }
-
-  var parameters = obj.parameters
-  var subtype = obj.subtype
-  var suffix = obj.suffix
-  var type = obj.type
-
-  if (!type || !typeNameRegExp.test(type)) {
-    throw new TypeError('invalid type')
-  }
-
-  if (!subtype || !subtypeNameRegExp.test(subtype)) {
-    throw new TypeError('invalid subtype')
-  }
-
-  // format as type/subtype
-  var string = type + '/' + subtype
-
-  // append +suffix
-  if (suffix) {
-    if (!typeNameRegExp.test(suffix)) {
-      throw new TypeError('invalid suffix')
-    }
-
-    string += '+' + suffix
-  }
-
-  // append parameters
-  if (parameters && typeof parameters === 'object') {
-    var param
-    var params = Object.keys(parameters).sort()
-
-    for (var i = 0; i < params.length; i++) {
-      param = params[i]
-
-      if (!tokenRegExp.test(param)) {
-        throw new TypeError('invalid parameter name')
-      }
-
-      string += '; ' + param + '=' + qstring(parameters[param])
-    }
-  }
-
-  return string
-}
-
-/**
- * Parse media type to object.
- *
- * @param {string|object} string
- * @return {Object}
- * @api public
- */
-
-function parse(string) {
-  if (!string) {
-    throw new TypeError('argument string is required')
-  }
-
-  // support req/res-like objects as argument
-  if (typeof string === 'object') {
-    string = getcontenttype(string)
-  }
-
-  if (typeof string !== 'string') {
-    throw new TypeError('argument string is required to be a string')
-  }
-
-  var index = string.indexOf(';')
-  var type = index !== -1
-    ? string.substr(0, index)
-    : string
-
-  var key
-  var match
-  var obj = splitType(type)
-  var params = {}
-  var value
-
-  paramRegExp.lastIndex = index
-
-  while (match = paramRegExp.exec(string)) {
-    if (match.index !== index) {
-      throw new TypeError('invalid parameter format')
-    }
-
-    index += match[0].length
-    key = match[1].toLowerCase()
-    value = match[2]
-
-    if (value[0] === '"') {
-      // remove quotes and escapes
-      value = value
-        .substr(1, value.length - 2)
-        .replace(qescRegExp, '$1')
-    }
-
-    params[key] = value
-  }
-
-  if (index !== -1 && index !== string.length) {
-    throw new TypeError('invalid parameter format')
-  }
-
-  obj.parameters = params
-
-  return obj
-}
-
-/**
- * Get content-type from req/res objects.
- *
- * @param {object}
- * @return {Object}
- * @api private
- */
-
-function getcontenttype(obj) {
-  if (typeof obj.getHeader === 'function') {
-    // res-like
-    return obj.getHeader('content-type')
-  }
-
-  if (typeof obj.headers === 'object') {
-    // req-like
-    return obj.headers && obj.headers['content-type']
-  }
-}
-
-/**
- * Quote a string if necessary.
- *
- * @param {string} val
- * @return {string}
- * @api private
- */
-
-function qstring(val) {
-  var str = String(val)
-
-  // no need to quote tokens
-  if (tokenRegExp.test(str)) {
-    return str
-  }
-
-  if (str.length > 0 && !textRegExp.test(str)) {
-    throw new TypeError('invalid parameter value')
-  }
-
-  return '"' + str.replace(quoteRegExp, '\\$1') + '"'
-}
-
-/**
- * Simply "type/subtype+siffx" into parts.
- *
- * @param {string} string
- * @return {Object}
- * @api private
- */
-
-function splitType(string) {
-  var match = typeRegExp.exec(string.toLowerCase())
-
-  if (!match) {
-    throw new TypeError('invalid media type')
-  }
-
-  var type = match[1]
-  var subtype = match[2]
-  var suffix
-
-  // suffix after last +
-  var index = subtype.lastIndexOf('+')
-  if (index !== -1) {
-    suffix = subtype.substr(index + 1)
-    subtype = subtype.substr(0, index)
-  }
-
-  var obj = {
-    type: type,
-    subtype: subtype,
-    suffix: suffix
-  }
-
-  return obj
-}
+var paramRegExp=/; *([!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) *= *("(?:[ !\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u0020-\u007e])*"|[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+) */g,textRegExp=/^[\u0020-\u007e\u0080-\u00ff]+$/,tokenRegExp=/^[!#$%&'\*\+\-\.0-9A-Z\^_`a-z\|~]+$/,qescRegExp=/\\([\u0000-\u007f])/g,quoteRegExp=/([\\"])/g,subtypeNameRegExp=/^[A-Za-z0-9][A-Za-z0-9!#$&^_.-]{0,126}$/,typeNameRegExp=/^[A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126}$/,typeRegExp=/^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/;function format(e){if(!e||"object"!=typeof e)throw new TypeError("argument obj is required");var t=e.parameters,r=e.subtype,a=e.suffix,p=e.type;if(!p||!typeNameRegExp.test(p))throw new TypeError("invalid type");if(!r||!subtypeNameRegExp.test(r))throw new TypeError("invalid subtype");var n=p+"/"+r;if(a){if(!typeNameRegExp.test(a))throw new TypeError("invalid suffix");n+="+"+a}if(t&&"object"==typeof t)for(var o,i=Object.keys(t).sort(),s=0;s<i.length;s++){if(o=i[s],!tokenRegExp.test(o))throw new TypeError("invalid parameter name");n+="; "+o+"="+qstring(t[o])}return n}function parse(e){if(!e)throw new TypeError("argument string is required");if("object"==typeof e&&(e=getcontenttype(e)),"string"!=typeof e)throw new TypeError("argument string is required to be a string");var t,r,a,p=e.indexOf(";"),n=splitType(-1!==p?e.substr(0,p):e),o={};for(paramRegExp.lastIndex=p;r=paramRegExp.exec(e);){if(r.index!==p)throw new TypeError("invalid parameter format");p+=r[0].length,t=r[1].toLowerCase(),'"'===(a=r[2])[0]&&(a=a.substr(1,a.length-2).replace(qescRegExp,"$1")),o[t]=a}if(-1!==p&&p!==e.length)throw new TypeError("invalid parameter format");return n.parameters=o,n}function getcontenttype(e){return"function"==typeof e.getHeader?e.getHeader("content-type"):"object"==typeof e.headers?e.headers&&e.headers["content-type"]:void 0}function qstring(e){var t=String(e);if(tokenRegExp.test(t))return t;if(t.length>0&&!textRegExp.test(t))throw new TypeError("invalid parameter value");return'"'+t.replace(quoteRegExp,"\\$1")+'"'}function splitType(e){var t=typeRegExp.exec(e.toLowerCase());if(!t)throw new TypeError("invalid media type");var r,a=t[1],p=t[2],n=p.lastIndexOf("+");return-1!==n&&(r=p.substr(n+1),p=p.substr(0,n)),{type:a,subtype:p,suffix:r}}exports.format=format,exports.parse=parse;
\ No newline at end of file
index 573b132..885cd58 100644 (file)
@@ -4,57 +4,4 @@
  * Copyright(c) 2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = merge
-
-/**
- * Module variables.
- * @private
- */
-
-var hasOwnProperty = Object.prototype.hasOwnProperty
-
-/**
- * Merge the property descriptors of `src` into `dest`
- *
- * @param {object} dest Object to add descriptors to
- * @param {object} src Object to clone descriptors from
- * @param {boolean} [redefine=true] Redefine `dest` properties with `src` properties
- * @returns {object} Reference to dest
- * @public
- */
-
-function merge(dest, src, redefine) {
-  if (!dest) {
-    throw new TypeError('argument dest is required')
-  }
-
-  if (!src) {
-    throw new TypeError('argument src is required')
-  }
-
-  if (redefine === undefined) {
-    // Default to true
-    redefine = true
-  }
-
-  Object.getOwnPropertyNames(src).forEach(function forEachOwnPropertyName(name) {
-    if (!redefine && hasOwnProperty.call(dest, name)) {
-      // Skip desriptor
-      return
-    }
-
-    // Copy descriptor
-    var descriptor = Object.getOwnPropertyDescriptor(src, name)
-    Object.defineProperty(dest, name, descriptor)
-  })
-
-  return dest
-}
+"use strict";module.exports=merge;var hasOwnProperty=Object.prototype.hasOwnProperty;function merge(r,e,t){if(!r)throw new TypeError("argument dest is required");if(!e)throw new TypeError("argument src is required");return void 0===t&&(t=!0),Object.getOwnPropertyNames(e).forEach((function(o){if(t||!hasOwnProperty.call(r,o)){var n=Object.getOwnPropertyDescriptor(e,o);Object.defineProperty(r,o,n)}})),r}
\ No newline at end of file
index 667a50b..dca6c3b 100644 (file)
@@ -4,66 +4,4 @@
  * Copyright(c) 2015-2016 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict';
-
-/**
- * Module dependencies.
- * @private
- */
-
-var http = require('http');
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = getCurrentNodeMethods() || getBasicNodeMethods();
-
-/**
- * Get the current Node.js methods.
- * @private
- */
-
-function getCurrentNodeMethods() {
-  return http.METHODS && http.METHODS.map(function lowerCaseMethod(method) {
-    return method.toLowerCase();
-  });
-}
-
-/**
- * Get the "basic" Node.js methods, a snapshot from Node.js 0.10.
- * @private
- */
-
-function getBasicNodeMethods() {
-  return [
-    'get',
-    'post',
-    'put',
-    'head',
-    'delete',
-    'options',
-    'trace',
-    'copy',
-    'lock',
-    'mkcol',
-    'move',
-    'purge',
-    'propfind',
-    'proppatch',
-    'unlock',
-    'report',
-    'mkactivity',
-    'checkout',
-    'merge',
-    'm-search',
-    'notify',
-    'subscribe',
-    'unsubscribe',
-    'patch',
-    'search',
-    'connect'
-  ];
-}
+"use strict";var http=require("http");function getCurrentNodeMethods(){return http.METHODS&&http.METHODS.map((function(t){return t.toLowerCase()}))}function getBasicNodeMethods(){return["get","post","put","head","delete","options","trace","copy","lock","mkcol","move","purge","propfind","proppatch","unlock","report","mkactivity","checkout","merge","m-search","notify","subscribe","unsubscribe","patch","search","connect"]}module.exports=getCurrentNodeMethods()||getBasicNodeMethods();
\ No newline at end of file
index 551031f..1590592 100644 (file)
@@ -3,9 +3,4 @@
  * Copyright(c) 2014 Jonathan Ong
  * MIT Licensed
  */
-
-/**
- * Module exports.
- */
-
-module.exports = require('./db.json')
+module.exports=require("./db.json");
\ No newline at end of file
index b9f34d5..6622683 100644 (file)
@@ -4,185 +4,4 @@
  * Copyright(c) 2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module dependencies.
- * @private
- */
-
-var db = require('mime-db')
-var extname = require('path').extname
-
-/**
- * Module variables.
- * @private
- */
-
-var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/
-var TEXT_TYPE_REGEXP = /^text\//i
-
-/**
- * Module exports.
- * @public
- */
-
-exports.charset = charset
-exports.charsets = { lookup: charset }
-exports.contentType = contentType
-exports.extension = extension
-exports.extensions = Object.create(null)
-exports.lookup = lookup
-exports.types = Object.create(null)
-
-// Populate the extensions/types maps
-populateMaps(exports.extensions, exports.types)
-
-/**
- * Get the default charset for a MIME type.
- *
- * @param {string} type
- * @return {boolean|string}
- */
-
-function charset (type) {
-  if (!type || typeof type !== 'string') {
-    return false
-  }
-
-  // TODO: use media-typer
-  var match = EXTRACT_TYPE_REGEXP.exec(type)
-  var mime = match && db[match[1].toLowerCase()]
-
-  if (mime && mime.charset) {
-    return mime.charset
-  }
-
-  // default text/* to utf-8
-  if (match && TEXT_TYPE_REGEXP.test(match[1])) {
-    return 'UTF-8'
-  }
-
-  return false
-}
-
-/**
- * Create a full Content-Type header given a MIME type or extension.
- *
- * @param {string} str
- * @return {boolean|string}
- */
-
-function contentType (str) {
-  // TODO: should this even be in this module?
-  if (!str || typeof str !== 'string') {
-    return false
-  }
-
-  var mime = str.indexOf('/') === -1
-    ? exports.lookup(str)
-    : str
-
-  if (!mime) {
-    return false
-  }
-
-  // TODO: use content-type or other module
-  if (mime.indexOf('charset') === -1) {
-    var charset = exports.charset(mime)
-    if (charset) mime += '; charset=' + charset.toLowerCase()
-  }
-
-  return mime
-}
-
-/**
- * Get the default extension for a MIME type.
- *
- * @param {string} type
- * @return {boolean|string}
- */
-
-function extension (type) {
-  if (!type || typeof type !== 'string') {
-    return false
-  }
-
-  // TODO: use media-typer
-  var match = EXTRACT_TYPE_REGEXP.exec(type)
-
-  // get extensions
-  var exts = match && exports.extensions[match[1].toLowerCase()]
-
-  if (!exts || !exts.length) {
-    return false
-  }
-
-  return exts[0]
-}
-
-/**
- * Lookup the MIME type for a file path/extension.
- *
- * @param {string} path
- * @return {boolean|string}
- */
-
-function lookup (path) {
-  if (!path || typeof path !== 'string') {
-    return false
-  }
-
-  // get the extension ("ext" or ".ext" or full path)
-  var extension = extname('x.' + path)
-    .toLowerCase()
-    .substr(1)
-
-  if (!extension) {
-    return false
-  }
-
-  return exports.types[extension] || false
-}
-
-/**
- * Populate the extensions and types maps.
- * @private
- */
-
-function populateMaps (extensions, types) {
-  // source preference (least -> most)
-  var preference = ['nginx', 'apache', undefined, 'iana']
-
-  Object.keys(db).forEach(function forEachMimeType (type) {
-    var mime = db[type]
-    var exts = mime.extensions
-
-    if (!exts || !exts.length) {
-      return
-    }
-
-    // mime -> extensions
-    extensions[type] = exts
-
-    // extension -> mime
-    for (var i = 0; i < exts.length; i++) {
-      var extension = exts[i]
-
-      if (types[extension]) {
-        var from = preference.indexOf(db[types[extension]].source)
-        var to = preference.indexOf(mime.source)
-
-        if (types[extension] !== 'application/octet-stream' &&
-          (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) {
-          // skip the remapping
-          continue
-        }
-      }
-
-      // set the extension -> mime
-      types[extension] = type
-    }
-  })
-}
+"use strict";var db=require("mime-db"),extname=require("path").extname,EXTRACT_TYPE_REGEXP=/^\s*([^;\s]*)(?:;|\s|$)/,TEXT_TYPE_REGEXP=/^text\//i;function charset(e){if(!e||"string"!=typeof e)return!1;var t=EXTRACT_TYPE_REGEXP.exec(e),r=t&&db[t[1].toLowerCase()];return r&&r.charset?r.charset:!(!t||!TEXT_TYPE_REGEXP.test(t[1]))&&"UTF-8"}function contentType(e){if(!e||"string"!=typeof e)return!1;var t=-1===e.indexOf("/")?exports.lookup(e):e;if(!t)return!1;if(-1===t.indexOf("charset")){var r=exports.charset(t);r&&(t+="; charset="+r.toLowerCase())}return t}function extension(e){if(!e||"string"!=typeof e)return!1;var t=EXTRACT_TYPE_REGEXP.exec(e),r=t&&exports.extensions[t[1].toLowerCase()];return!(!r||!r.length)&&r[0]}function lookup(e){if(!e||"string"!=typeof e)return!1;var t=extname("x."+e).toLowerCase().substr(1);return t&&exports.types[t]||!1}function populateMaps(e,t){var r=["nginx","apache",void 0,"iana"];Object.keys(db).forEach((function(n){var o=db[n],s=o.extensions;if(s&&s.length){e[n]=s;for(var a=0;a<s.length;a++){var i=s[a];if(t[i]){var p=r.indexOf(db[t[i]].source),c=r.indexOf(o.source);if("application/octet-stream"!==t[i]&&(p>c||p===c&&"application/"===t[i].substr(0,12)))continue}t[i]=n}}}))}exports.charset=charset,exports.charsets={lookup:charset},exports.contentType=contentType,exports.extension=extension,exports.extensions=Object.create(null),exports.lookup=lookup,exports.types=Object.create(null),populateMaps(exports.extensions,exports.types);
\ No newline at end of file
index 20b1ffe..14e44bc 100755 (executable)
@@ -1,8 +1,2 @@
 #!/usr/bin/env node
-
-var mime = require('./mime.js');
-var file = process.argv[2];
-var type = mime.lookup(file);
-
-process.stdout.write(type + '\n');
-
+var mime=require("./mime.js"),file=process.argv[2],type=mime.lookup(file);process.stdout.write(type+"\n");
\ No newline at end of file
index d7efbde..f297b6c 100644 (file)
@@ -1,108 +1 @@
-var path = require('path');
-var fs = require('fs');
-
-function Mime() {
-  // Map of extension -> mime type
-  this.types = Object.create(null);
-
-  // Map of mime type -> extension
-  this.extensions = Object.create(null);
-}
-
-/**
- * Define mimetype -> extension mappings.  Each key is a mime-type that maps
- * to an array of extensions associated with the type.  The first extension is
- * used as the default extension for the type.
- *
- * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});
- *
- * @param map (Object) type definitions
- */
-Mime.prototype.define = function (map) {
-  for (var type in map) {
-    var exts = map[type];
-    for (var i = 0; i < exts.length; i++) {
-      if (process.env.DEBUG_MIME && this.types[exts[i]]) {
-        console.warn((this._loading || "define()").replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' +
-          this.types[exts[i]] + ' to ' + type);
-      }
-
-      this.types[exts[i]] = type;
-    }
-
-    // Default extension is the first one we encounter
-    if (!this.extensions[type]) {
-      this.extensions[type] = exts[0];
-    }
-  }
-};
-
-/**
- * Load an Apache2-style ".types" file
- *
- * This may be called multiple times (it's expected).  Where files declare
- * overlapping types/extensions, the last file wins.
- *
- * @param file (String) path of file to load.
- */
-Mime.prototype.load = function(file) {
-  this._loading = file;
-  // Read file and split into lines
-  var map = {},
-      content = fs.readFileSync(file, 'ascii'),
-      lines = content.split(/[\r\n]+/);
-
-  lines.forEach(function(line) {
-    // Clean up whitespace/comments, and split into fields
-    var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/);
-    map[fields.shift()] = fields;
-  });
-
-  this.define(map);
-
-  this._loading = null;
-};
-
-/**
- * Lookup a mime type based on extension
- */
-Mime.prototype.lookup = function(path, fallback) {
-  var ext = path.replace(/^.*[\.\/\\]/, '').toLowerCase();
-
-  return this.types[ext] || fallback || this.default_type;
-};
-
-/**
- * Return file extension associated with a mime type
- */
-Mime.prototype.extension = function(mimeType) {
-  var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase();
-  return this.extensions[type];
-};
-
-// Default instance
-var mime = new Mime();
-
-// Define built-in types
-mime.define(require('./types.json'));
-
-// Default type
-mime.default_type = mime.lookup('bin');
-
-//
-// Additional API specific to the default instance
-//
-
-mime.Mime = Mime;
-
-/**
- * Lookup a charset based on mime type.
- */
-mime.charsets = {
-  lookup: function(mimeType, fallback) {
-    // Assume text types are utf8
-    return (/^text\/|^application\/(javascript|json)/).test(mimeType) ? 'UTF-8' : fallback;
-  }
-};
-
-module.exports = mime;
+var path=require("path"),fs=require("fs");function Mime(){this.types=Object.create(null),this.extensions=Object.create(null)}Mime.prototype.define=function(e){for(var t in e){for(var i=e[t],s=0;s<i.length;s++)process.env.DEBUG_MIME&&this.types[i[s]]&&console.warn((this._loading||"define()").replace(/.*\//,""),'changes "'+i[s]+'" extension type from '+this.types[i[s]]+" to "+t),this.types[i[s]]=t;this.extensions[t]||(this.extensions[t]=i[0])}},Mime.prototype.load=function(e){this._loading=e;var t={};fs.readFileSync(e,"ascii").split(/[\r\n]+/).forEach((function(e){var i=e.replace(/\s*#.*|^\s*|\s*$/g,"").split(/\s+/);t[i.shift()]=i})),this.define(t),this._loading=null},Mime.prototype.lookup=function(e,t){var i=e.replace(/^.*[\.\/\\]/,"").toLowerCase();return this.types[i]||t||this.default_type},Mime.prototype.extension=function(e){var t=e.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase();return this.extensions[t]};var mime=new Mime;mime.define(require("./types.json")),mime.default_type=mime.lookup("bin"),mime.Mime=Mime,mime.charsets={lookup:function(e,t){return/^text\/|^application\/(javascript|json)/.test(e)?"UTF-8":t}},module.exports=mime;
\ No newline at end of file
index 4928e48..3a843ac 100755 (executable)
@@ -1,53 +1,2 @@
 #!/usr/bin/env node
-
-'use strict';
-
-const fs = require('fs');
-const path = require('path');
-const mimeScore = require('mime-score');
-
-let db = require('mime-db');
-let chalk = require('chalk');
-
-const STANDARD_FACET_SCORE = 900;
-
-const byExtension = {};
-
-// Clear out any conflict extensions in mime-db
-for (let type in db) {
-  let entry = db[type];
-  entry.type = type;
-
-  if (!entry.extensions) continue;
-
-  entry.extensions.forEach(ext => {
-    if (ext in byExtension) {
-      const e0 = entry;
-      const e1 = byExtension[ext];
-      e0.pri = mimeScore(e0.type, e0.source);
-      e1.pri = mimeScore(e1.type, e1.source);
-
-      let drop = e0.pri < e1.pri ? e0 : e1;
-      let keep = e0.pri >= e1.pri ? e0 : e1;
-      drop.extensions = drop.extensions.filter(e => e !== ext);
-
-      console.log(`${ext}: Keeping ${chalk.green(keep.type)} (${keep.pri}), dropping ${chalk.red(drop.type)} (${drop.pri})`);
-    }
-    byExtension[ext] = entry;
-  });
-}
-
-function writeTypesFile(types, path) {
-  fs.writeFileSync(path, JSON.stringify(types));
-}
-
-// Segregate into standard and non-standard types based on facet per
-// https://tools.ietf.org/html/rfc6838#section-3.1
-const types = {};
-
-Object.keys(db).sort().forEach(k => {
-  const entry = db[k];
-  types[entry.type] = entry.extensions;
-});
-
-writeTypesFile(types, path.join(__dirname, '..', 'types.json'));
+"use strict";const fs=require("fs"),path=require("path"),mimeScore=require("mime-score");let db=require("mime-db"),chalk=require("chalk");const STANDARD_FACET_SCORE=900,byExtension={};for(let e in db){let i=db[e];i.type=e,i.extensions&&i.extensions.forEach((e=>{if(e in byExtension){const t=i,r=byExtension[e];t.pri=mimeScore(t.type,t.source),r.pri=mimeScore(r.type,r.source);let s=t.pri<r.pri?t:r,n=t.pri>=r.pri?t:r;s.extensions=s.extensions.filter((i=>i!==e)),console.log(`${e}: Keeping ${chalk.green(n.type)} (${n.pri}), dropping ${chalk.red(s.type)} (${s.pri})`)}byExtension[e]=i}))}function writeTypesFile(e,i){fs.writeFileSync(i,JSON.stringify(e))}const types={};Object.keys(db).sort().forEach((e=>{const i=db[e];types[i.type]=i.extensions})),writeTypesFile(types,path.join(__dirname,"..","types.json"));
\ No newline at end of file
index 42958a2..25603fc 100644 (file)
@@ -1,60 +1 @@
-/**
- * Usage: node test.js
- */
-
-var mime = require('../mime');
-var assert = require('assert');
-var path = require('path');
-
-//
-// Test mime lookups
-//
-
-assert.equal('text/plain', mime.lookup('text.txt'));     // normal file
-assert.equal('text/plain', mime.lookup('TEXT.TXT'));     // uppercase
-assert.equal('text/plain', mime.lookup('dir/text.txt')); // dir + file
-assert.equal('text/plain', mime.lookup('.text.txt'));    // hidden file
-assert.equal('text/plain', mime.lookup('.txt'));         // nameless
-assert.equal('text/plain', mime.lookup('txt'));          // extension-only
-assert.equal('text/plain', mime.lookup('/txt'));         // extension-less ()
-assert.equal('text/plain', mime.lookup('\\txt'));        // Windows, extension-less
-assert.equal('application/octet-stream', mime.lookup('text.nope')); // unrecognized
-assert.equal('fallback', mime.lookup('text.fallback', 'fallback')); // alternate default
-
-//
-// Test extensions
-//
-
-assert.equal('txt', mime.extension(mime.types.text));
-assert.equal('html', mime.extension(mime.types.htm));
-assert.equal('bin', mime.extension('application/octet-stream'));
-assert.equal('bin', mime.extension('application/octet-stream '));
-assert.equal('html', mime.extension(' text/html; charset=UTF-8'));
-assert.equal('html', mime.extension('text/html; charset=UTF-8 '));
-assert.equal('html', mime.extension('text/html; charset=UTF-8'));
-assert.equal('html', mime.extension('text/html ; charset=UTF-8'));
-assert.equal('html', mime.extension('text/html;charset=UTF-8'));
-assert.equal('html', mime.extension('text/Html;charset=UTF-8'));
-assert.equal(undefined, mime.extension('unrecognized'));
-
-//
-// Test node.types lookups
-//
-
-assert.equal('font/woff', mime.lookup('file.woff'));
-assert.equal('application/octet-stream', mime.lookup('file.buffer'));
-// TODO: Uncomment once #157 is resolved
-// assert.equal('audio/mp4', mime.lookup('file.m4a'));
-assert.equal('font/otf', mime.lookup('file.otf'));
-
-//
-// Test charsets
-//
-
-assert.equal('UTF-8', mime.charsets.lookup('text/plain'));
-assert.equal('UTF-8', mime.charsets.lookup(mime.types.js));
-assert.equal('UTF-8', mime.charsets.lookup(mime.types.json));
-assert.equal(undefined, mime.charsets.lookup(mime.types.bin));
-assert.equal('fallback', mime.charsets.lookup('application/octet-stream', 'fallback'));
-
-console.log('\nAll tests passed');
+var mime=require("../mime"),assert=require("assert"),path=require("path");assert.equal("text/plain",mime.lookup("text.txt")),assert.equal("text/plain",mime.lookup("TEXT.TXT")),assert.equal("text/plain",mime.lookup("dir/text.txt")),assert.equal("text/plain",mime.lookup(".text.txt")),assert.equal("text/plain",mime.lookup(".txt")),assert.equal("text/plain",mime.lookup("txt")),assert.equal("text/plain",mime.lookup("/txt")),assert.equal("text/plain",mime.lookup("\\txt")),assert.equal("application/octet-stream",mime.lookup("text.nope")),assert.equal("fallback",mime.lookup("text.fallback","fallback")),assert.equal("txt",mime.extension(mime.types.text)),assert.equal("html",mime.extension(mime.types.htm)),assert.equal("bin",mime.extension("application/octet-stream")),assert.equal("bin",mime.extension("application/octet-stream ")),assert.equal("html",mime.extension(" text/html; charset=UTF-8")),assert.equal("html",mime.extension("text/html; charset=UTF-8 ")),assert.equal("html",mime.extension("text/html; charset=UTF-8")),assert.equal("html",mime.extension("text/html ; charset=UTF-8")),assert.equal("html",mime.extension("text/html;charset=UTF-8")),assert.equal("html",mime.extension("text/Html;charset=UTF-8")),assert.equal(void 0,mime.extension("unrecognized")),assert.equal("font/woff",mime.lookup("file.woff")),assert.equal("application/octet-stream",mime.lookup("file.buffer")),assert.equal("font/otf",mime.lookup("file.otf")),assert.equal("UTF-8",mime.charsets.lookup("text/plain")),assert.equal("UTF-8",mime.charsets.lookup(mime.types.js)),assert.equal("UTF-8",mime.charsets.lookup(mime.types.json)),assert.equal(void 0,mime.charsets.lookup(mime.types.bin)),assert.equal("fallback",mime.charsets.lookup("application/octet-stream","fallback")),console.log("\nAll tests passed");
\ No newline at end of file
index 5b5f8cf..203f86d 100755 (executable)
@@ -1,923 +1 @@
-module.exports = minimatch
-minimatch.Minimatch = Minimatch
-
-var path = { sep: '/' }
-try {
-  path = require('path')
-} catch (er) {}
-
-var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}
-var expand = require('brace-expansion')
-
-var plTypes = {
-  '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
-  '?': { open: '(?:', close: ')?' },
-  '+': { open: '(?:', close: ')+' },
-  '*': { open: '(?:', close: ')*' },
-  '@': { open: '(?:', close: ')' }
-}
-
-// any single thing other than /
-// don't need to escape / when using new RegExp()
-var qmark = '[^/]'
-
-// * => any number of characters
-var star = qmark + '*?'
-
-// ** when dots are allowed.  Anything goes, except .. and .
-// not (^ or / followed by one or two dots followed by $ or /),
-// followed by anything, any number of times.
-var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
-
-// not a ^ or / followed by a dot,
-// followed by anything, any number of times.
-var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
-
-// characters that need to be escaped in RegExp.
-var reSpecials = charSet('().*{}+?[]^$\\!')
-
-// "abc" -> { a:true, b:true, c:true }
-function charSet (s) {
-  return s.split('').reduce(function (set, c) {
-    set[c] = true
-    return set
-  }, {})
-}
-
-// normalizes slashes.
-var slashSplit = /\/+/
-
-minimatch.filter = filter
-function filter (pattern, options) {
-  options = options || {}
-  return function (p, i, list) {
-    return minimatch(p, pattern, options)
-  }
-}
-
-function ext (a, b) {
-  a = a || {}
-  b = b || {}
-  var t = {}
-  Object.keys(b).forEach(function (k) {
-    t[k] = b[k]
-  })
-  Object.keys(a).forEach(function (k) {
-    t[k] = a[k]
-  })
-  return t
-}
-
-minimatch.defaults = function (def) {
-  if (!def || !Object.keys(def).length) return minimatch
-
-  var orig = minimatch
-
-  var m = function minimatch (p, pattern, options) {
-    return orig.minimatch(p, pattern, ext(def, options))
-  }
-
-  m.Minimatch = function Minimatch (pattern, options) {
-    return new orig.Minimatch(pattern, ext(def, options))
-  }
-
-  return m
-}
-
-Minimatch.defaults = function (def) {
-  if (!def || !Object.keys(def).length) return Minimatch
-  return minimatch.defaults(def).Minimatch
-}
-
-function minimatch (p, pattern, options) {
-  if (typeof pattern !== 'string') {
-    throw new TypeError('glob pattern string required')
-  }
-
-  if (!options) options = {}
-
-  // shortcut: comments match nothing.
-  if (!options.nocomment && pattern.charAt(0) === '#') {
-    return false
-  }
-
-  // "" only matches ""
-  if (pattern.trim() === '') return p === ''
-
-  return new Minimatch(pattern, options).match(p)
-}
-
-function Minimatch (pattern, options) {
-  if (!(this instanceof Minimatch)) {
-    return new Minimatch(pattern, options)
-  }
-
-  if (typeof pattern !== 'string') {
-    throw new TypeError('glob pattern string required')
-  }
-
-  if (!options) options = {}
-  pattern = pattern.trim()
-
-  // windows support: need to use /, not \
-  if (path.sep !== '/') {
-    pattern = pattern.split(path.sep).join('/')
-  }
-
-  this.options = options
-  this.set = []
-  this.pattern = pattern
-  this.regexp = null
-  this.negate = false
-  this.comment = false
-  this.empty = false
-
-  // make the set of regexps etc.
-  this.make()
-}
-
-Minimatch.prototype.debug = function () {}
-
-Minimatch.prototype.make = make
-function make () {
-  // don't do it more than once.
-  if (this._made) return
-
-  var pattern = this.pattern
-  var options = this.options
-
-  // empty patterns and comments match nothing.
-  if (!options.nocomment && pattern.charAt(0) === '#') {
-    this.comment = true
-    return
-  }
-  if (!pattern) {
-    this.empty = true
-    return
-  }
-
-  // step 1: figure out negation, etc.
-  this.parseNegate()
-
-  // step 2: expand braces
-  var set = this.globSet = this.braceExpand()
-
-  if (options.debug) this.debug = console.error
-
-  this.debug(this.pattern, set)
-
-  // step 3: now we have a set, so turn each one into a series of path-portion
-  // matching patterns.
-  // These will be regexps, except in the case of "**", which is
-  // set to the GLOBSTAR object for globstar behavior,
-  // and will not contain any / characters
-  set = this.globParts = set.map(function (s) {
-    return s.split(slashSplit)
-  })
-
-  this.debug(this.pattern, set)
-
-  // glob --> regexps
-  set = set.map(function (s, si, set) {
-    return s.map(this.parse, this)
-  }, this)
-
-  this.debug(this.pattern, set)
-
-  // filter out everything that didn't compile properly.
-  set = set.filter(function (s) {
-    return s.indexOf(false) === -1
-  })
-
-  this.debug(this.pattern, set)
-
-  this.set = set
-}
-
-Minimatch.prototype.parseNegate = parseNegate
-function parseNegate () {
-  var pattern = this.pattern
-  var negate = false
-  var options = this.options
-  var negateOffset = 0
-
-  if (options.nonegate) return
-
-  for (var i = 0, l = pattern.length
-    ; i < l && pattern.charAt(i) === '!'
-    ; i++) {
-    negate = !negate
-    negateOffset++
-  }
-
-  if (negateOffset) this.pattern = pattern.substr(negateOffset)
-  this.negate = negate
-}
-
-// Brace expansion:
-// a{b,c}d -> abd acd
-// a{b,}c -> abc ac
-// a{0..3}d -> a0d a1d a2d a3d
-// a{b,c{d,e}f}g -> abg acdfg acefg
-// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
-//
-// Invalid sets are not expanded.
-// a{2..}b -> a{2..}b
-// a{b}c -> a{b}c
-minimatch.braceExpand = function (pattern, options) {
-  return braceExpand(pattern, options)
-}
-
-Minimatch.prototype.braceExpand = braceExpand
-
-function braceExpand (pattern, options) {
-  if (!options) {
-    if (this instanceof Minimatch) {
-      options = this.options
-    } else {
-      options = {}
-    }
-  }
-
-  pattern = typeof pattern === 'undefined'
-    ? this.pattern : pattern
-
-  if (typeof pattern === 'undefined') {
-    throw new TypeError('undefined pattern')
-  }
-
-  if (options.nobrace ||
-    !pattern.match(/\{.*\}/)) {
-    // shortcut. no need to expand.
-    return [pattern]
-  }
-
-  return expand(pattern)
-}
-
-// parse a component of the expanded set.
-// At this point, no pattern may contain "/" in it
-// so we're going to return a 2d array, where each entry is the full
-// pattern, split on '/', and then turned into a regular expression.
-// A regexp is made at the end which joins each array with an
-// escaped /, and another full one which joins each regexp with |.
-//
-// Following the lead of Bash 4.1, note that "**" only has special meaning
-// when it is the *only* thing in a path portion.  Otherwise, any series
-// of * is equivalent to a single *.  Globstar behavior is enabled by
-// default, and can be disabled by setting options.noglobstar.
-Minimatch.prototype.parse = parse
-var SUBPARSE = {}
-function parse (pattern, isSub) {
-  if (pattern.length > 1024 * 64) {
-    throw new TypeError('pattern is too long')
-  }
-
-  var options = this.options
-
-  // shortcuts
-  if (!options.noglobstar && pattern === '**') return GLOBSTAR
-  if (pattern === '') return ''
-
-  var re = ''
-  var hasMagic = !!options.nocase
-  var escaping = false
-  // ? => one single character
-  var patternListStack = []
-  var negativeLists = []
-  var stateChar
-  var inClass = false
-  var reClassStart = -1
-  var classStart = -1
-  // . and .. never match anything that doesn't start with .,
-  // even when options.dot is set.
-  var patternStart = pattern.charAt(0) === '.' ? '' // anything
-  // not (start or / followed by . or .. followed by / or end)
-  : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
-  : '(?!\\.)'
-  var self = this
-
-  function clearStateChar () {
-    if (stateChar) {
-      // we had some state-tracking character
-      // that wasn't consumed by this pass.
-      switch (stateChar) {
-        case '*':
-          re += star
-          hasMagic = true
-        break
-        case '?':
-          re += qmark
-          hasMagic = true
-        break
-        default:
-          re += '\\' + stateChar
-        break
-      }
-      self.debug('clearStateChar %j %j', stateChar, re)
-      stateChar = false
-    }
-  }
-
-  for (var i = 0, len = pattern.length, c
-    ; (i < len) && (c = pattern.charAt(i))
-    ; i++) {
-    this.debug('%s\t%s %s %j', pattern, i, re, c)
-
-    // skip over any that are escaped.
-    if (escaping && reSpecials[c]) {
-      re += '\\' + c
-      escaping = false
-      continue
-    }
-
-    switch (c) {
-      case '/':
-        // completely not allowed, even escaped.
-        // Should already be path-split by now.
-        return false
-
-      case '\\':
-        clearStateChar()
-        escaping = true
-      continue
-
-      // the various stateChar values
-      // for the "extglob" stuff.
-      case '?':
-      case '*':
-      case '+':
-      case '@':
-      case '!':
-        this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
-
-        // all of those are literals inside a class, except that
-        // the glob [!a] means [^a] in regexp
-        if (inClass) {
-          this.debug('  in class')
-          if (c === '!' && i === classStart + 1) c = '^'
-          re += c
-          continue
-        }
-
-        // if we already have a stateChar, then it means
-        // that there was something like ** or +? in there.
-        // Handle the stateChar, then proceed with this one.
-        self.debug('call clearStateChar %j', stateChar)
-        clearStateChar()
-        stateChar = c
-        // if extglob is disabled, then +(asdf|foo) isn't a thing.
-        // just clear the statechar *now*, rather than even diving into
-        // the patternList stuff.
-        if (options.noext) clearStateChar()
-      continue
-
-      case '(':
-        if (inClass) {
-          re += '('
-          continue
-        }
-
-        if (!stateChar) {
-          re += '\\('
-          continue
-        }
-
-        patternListStack.push({
-          type: stateChar,
-          start: i - 1,
-          reStart: re.length,
-          open: plTypes[stateChar].open,
-          close: plTypes[stateChar].close
-        })
-        // negation is (?:(?!js)[^/]*)
-        re += stateChar === '!' ? '(?:(?!(?:' : '(?:'
-        this.debug('plType %j %j', stateChar, re)
-        stateChar = false
-      continue
-
-      case ')':
-        if (inClass || !patternListStack.length) {
-          re += '\\)'
-          continue
-        }
-
-        clearStateChar()
-        hasMagic = true
-        var pl = patternListStack.pop()
-        // negation is (?:(?!js)[^/]*)
-        // The others are (?:<pattern>)<type>
-        re += pl.close
-        if (pl.type === '!') {
-          negativeLists.push(pl)
-        }
-        pl.reEnd = re.length
-      continue
-
-      case '|':
-        if (inClass || !patternListStack.length || escaping) {
-          re += '\\|'
-          escaping = false
-          continue
-        }
-
-        clearStateChar()
-        re += '|'
-      continue
-
-      // these are mostly the same in regexp and glob
-      case '[':
-        // swallow any state-tracking char before the [
-        clearStateChar()
-
-        if (inClass) {
-          re += '\\' + c
-          continue
-        }
-
-        inClass = true
-        classStart = i
-        reClassStart = re.length
-        re += c
-      continue
-
-      case ']':
-        //  a right bracket shall lose its special
-        //  meaning and represent itself in
-        //  a bracket expression if it occurs
-        //  first in the list.  -- POSIX.2 2.8.3.2
-        if (i === classStart + 1 || !inClass) {
-          re += '\\' + c
-          escaping = false
-          continue
-        }
-
-        // handle the case where we left a class open.
-        // "[z-a]" is valid, equivalent to "\[z-a\]"
-        if (inClass) {
-          // split where the last [ was, make sure we don't have
-          // an invalid re. if so, re-walk the contents of the
-          // would-be class to re-translate any characters that
-          // were passed through as-is
-          // TODO: It would probably be faster to determine this
-          // without a try/catch and a new RegExp, but it's tricky
-          // to do safely.  For now, this is safe and works.
-          var cs = pattern.substring(classStart + 1, i)
-          try {
-            RegExp('[' + cs + ']')
-          } catch (er) {
-            // not a valid class!
-            var sp = this.parse(cs, SUBPARSE)
-            re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
-            hasMagic = hasMagic || sp[1]
-            inClass = false
-            continue
-          }
-        }
-
-        // finish up the class.
-        hasMagic = true
-        inClass = false
-        re += c
-      continue
-
-      default:
-        // swallow any state char that wasn't consumed
-        clearStateChar()
-
-        if (escaping) {
-          // no need
-          escaping = false
-        } else if (reSpecials[c]
-          && !(c === '^' && inClass)) {
-          re += '\\'
-        }
-
-        re += c
-
-    } // switch
-  } // for
-
-  // handle the case where we left a class open.
-  // "[abc" is valid, equivalent to "\[abc"
-  if (inClass) {
-    // split where the last [ was, and escape it
-    // this is a huge pita.  We now have to re-walk
-    // the contents of the would-be class to re-translate
-    // any characters that were passed through as-is
-    cs = pattern.substr(classStart + 1)
-    sp = this.parse(cs, SUBPARSE)
-    re = re.substr(0, reClassStart) + '\\[' + sp[0]
-    hasMagic = hasMagic || sp[1]
-  }
-
-  // handle the case where we had a +( thing at the *end*
-  // of the pattern.
-  // each pattern list stack adds 3 chars, and we need to go through
-  // and escape any | chars that were passed through as-is for the regexp.
-  // Go through and escape them, taking care not to double-escape any
-  // | chars that were already escaped.
-  for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
-    var tail = re.slice(pl.reStart + pl.open.length)
-    this.debug('setting tail', re, pl)
-    // maybe some even number of \, then maybe 1 \, followed by a |
-    tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
-      if (!$2) {
-        // the | isn't already escaped, so escape it.
-        $2 = '\\'
-      }
-
-      // need to escape all those slashes *again*, without escaping the
-      // one that we need for escaping the | character.  As it works out,
-      // escaping an even number of slashes can be done by simply repeating
-      // it exactly after itself.  That's why this trick works.
-      //
-      // I am sorry that you have to see this.
-      return $1 + $1 + $2 + '|'
-    })
-
-    this.debug('tail=%j\n   %s', tail, tail, pl, re)
-    var t = pl.type === '*' ? star
-      : pl.type === '?' ? qmark
-      : '\\' + pl.type
-
-    hasMagic = true
-    re = re.slice(0, pl.reStart) + t + '\\(' + tail
-  }
-
-  // handle trailing things that only matter at the very end.
-  clearStateChar()
-  if (escaping) {
-    // trailing \\
-    re += '\\\\'
-  }
-
-  // only need to apply the nodot start if the re starts with
-  // something that could conceivably capture a dot
-  var addPatternStart = false
-  switch (re.charAt(0)) {
-    case '.':
-    case '[':
-    case '(': addPatternStart = true
-  }
-
-  // Hack to work around lack of negative lookbehind in JS
-  // A pattern like: *.!(x).!(y|z) needs to ensure that a name
-  // like 'a.xyz.yz' doesn't match.  So, the first negative
-  // lookahead, has to look ALL the way ahead, to the end of
-  // the pattern.
-  for (var n = negativeLists.length - 1; n > -1; n--) {
-    var nl = negativeLists[n]
-
-    var nlBefore = re.slice(0, nl.reStart)
-    var nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
-    var nlLast = re.slice(nl.reEnd - 8, nl.reEnd)
-    var nlAfter = re.slice(nl.reEnd)
-
-    nlLast += nlAfter
-
-    // Handle nested stuff like *(*.js|!(*.json)), where open parens
-    // mean that we should *not* include the ) in the bit that is considered
-    // "after" the negated section.
-    var openParensBefore = nlBefore.split('(').length - 1
-    var cleanAfter = nlAfter
-    for (i = 0; i < openParensBefore; i++) {
-      cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
-    }
-    nlAfter = cleanAfter
-
-    var dollar = ''
-    if (nlAfter === '' && isSub !== SUBPARSE) {
-      dollar = '$'
-    }
-    var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast
-    re = newRe
-  }
-
-  // if the re is not "" at this point, then we need to make sure
-  // it doesn't match against an empty path part.
-  // Otherwise a/* will match a/, which it should not.
-  if (re !== '' && hasMagic) {
-    re = '(?=.)' + re
-  }
-
-  if (addPatternStart) {
-    re = patternStart + re
-  }
-
-  // parsing just a piece of a larger pattern.
-  if (isSub === SUBPARSE) {
-    return [re, hasMagic]
-  }
-
-  // skip the regexp for non-magical patterns
-  // unescape anything in it, though, so that it'll be
-  // an exact match against a file etc.
-  if (!hasMagic) {
-    return globUnescape(pattern)
-  }
-
-  var flags = options.nocase ? 'i' : ''
-  try {
-    var regExp = new RegExp('^' + re + '$', flags)
-  } catch (er) {
-    // If it was an invalid regular expression, then it can't match
-    // anything.  This trick looks for a character after the end of
-    // the string, which is of course impossible, except in multi-line
-    // mode, but it's not a /m regex.
-    return new RegExp('$.')
-  }
-
-  regExp._glob = pattern
-  regExp._src = re
-
-  return regExp
-}
-
-minimatch.makeRe = function (pattern, options) {
-  return new Minimatch(pattern, options || {}).makeRe()
-}
-
-Minimatch.prototype.makeRe = makeRe
-function makeRe () {
-  if (this.regexp || this.regexp === false) return this.regexp
-
-  // at this point, this.set is a 2d array of partial
-  // pattern strings, or "**".
-  //
-  // It's better to use .match().  This function shouldn't
-  // be used, really, but it's pretty convenient sometimes,
-  // when you just want to work with a regex.
-  var set = this.set
-
-  if (!set.length) {
-    this.regexp = false
-    return this.regexp
-  }
-  var options = this.options
-
-  var twoStar = options.noglobstar ? star
-    : options.dot ? twoStarDot
-    : twoStarNoDot
-  var flags = options.nocase ? 'i' : ''
-
-  var re = set.map(function (pattern) {
-    return pattern.map(function (p) {
-      return (p === GLOBSTAR) ? twoStar
-      : (typeof p === 'string') ? regExpEscape(p)
-      : p._src
-    }).join('\\\/')
-  }).join('|')
-
-  // must match entire pattern
-  // ending in a * or ** will make it less strict.
-  re = '^(?:' + re + ')$'
-
-  // can match anything, as long as it's not this.
-  if (this.negate) re = '^(?!' + re + ').*$'
-
-  try {
-    this.regexp = new RegExp(re, flags)
-  } catch (ex) {
-    this.regexp = false
-  }
-  return this.regexp
-}
-
-minimatch.match = function (list, pattern, options) {
-  options = options || {}
-  var mm = new Minimatch(pattern, options)
-  list = list.filter(function (f) {
-    return mm.match(f)
-  })
-  if (mm.options.nonull && !list.length) {
-    list.push(pattern)
-  }
-  return list
-}
-
-Minimatch.prototype.match = match
-function match (f, partial) {
-  this.debug('match', f, this.pattern)
-  // short-circuit in the case of busted things.
-  // comments, etc.
-  if (this.comment) return false
-  if (this.empty) return f === ''
-
-  if (f === '/' && partial) return true
-
-  var options = this.options
-
-  // windows: need to use /, not \
-  if (path.sep !== '/') {
-    f = f.split(path.sep).join('/')
-  }
-
-  // treat the test path as a set of pathparts.
-  f = f.split(slashSplit)
-  this.debug(this.pattern, 'split', f)
-
-  // just ONE of the pattern sets in this.set needs to match
-  // in order for it to be valid.  If negating, then just one
-  // match means that we have failed.
-  // Either way, return on the first hit.
-
-  var set = this.set
-  this.debug(this.pattern, 'set', set)
-
-  // Find the basename of the path by looking for the last non-empty segment
-  var filename
-  var i
-  for (i = f.length - 1; i >= 0; i--) {
-    filename = f[i]
-    if (filename) break
-  }
-
-  for (i = 0; i < set.length; i++) {
-    var pattern = set[i]
-    var file = f
-    if (options.matchBase && pattern.length === 1) {
-      file = [filename]
-    }
-    var hit = this.matchOne(file, pattern, partial)
-    if (hit) {
-      if (options.flipNegate) return true
-      return !this.negate
-    }
-  }
-
-  // didn't get any hits.  this is success if it's a negative
-  // pattern, failure otherwise.
-  if (options.flipNegate) return false
-  return this.negate
-}
-
-// set partial to true to test if, for example,
-// "/a/b" matches the start of "/*/b/*/d"
-// Partial means, if you run out of file before you run
-// out of pattern, then that's fine, as long as all
-// the parts match.
-Minimatch.prototype.matchOne = function (file, pattern, partial) {
-  var options = this.options
-
-  this.debug('matchOne',
-    { 'this': this, file: file, pattern: pattern })
-
-  this.debug('matchOne', file.length, pattern.length)
-
-  for (var fi = 0,
-      pi = 0,
-      fl = file.length,
-      pl = pattern.length
-      ; (fi < fl) && (pi < pl)
-      ; fi++, pi++) {
-    this.debug('matchOne loop')
-    var p = pattern[pi]
-    var f = file[fi]
-
-    this.debug(pattern, p, f)
-
-    // should be impossible.
-    // some invalid regexp stuff in the set.
-    if (p === false) return false
-
-    if (p === GLOBSTAR) {
-      this.debug('GLOBSTAR', [pattern, p, f])
-
-      // "**"
-      // a/**/b/**/c would match the following:
-      // a/b/x/y/z/c
-      // a/x/y/z/b/c
-      // a/b/x/b/x/c
-      // a/b/c
-      // To do this, take the rest of the pattern after
-      // the **, and see if it would match the file remainder.
-      // If so, return success.
-      // If not, the ** "swallows" a segment, and try again.
-      // This is recursively awful.
-      //
-      // a/**/b/**/c matching a/b/x/y/z/c
-      // - a matches a
-      // - doublestar
-      //   - matchOne(b/x/y/z/c, b/**/c)
-      //     - b matches b
-      //     - doublestar
-      //       - matchOne(x/y/z/c, c) -> no
-      //       - matchOne(y/z/c, c) -> no
-      //       - matchOne(z/c, c) -> no
-      //       - matchOne(c, c) yes, hit
-      var fr = fi
-      var pr = pi + 1
-      if (pr === pl) {
-        this.debug('** at the end')
-        // a ** at the end will just swallow the rest.
-        // We have found a match.
-        // however, it will not swallow /.x, unless
-        // options.dot is set.
-        // . and .. are *never* matched by **, for explosively
-        // exponential reasons.
-        for (; fi < fl; fi++) {
-          if (file[fi] === '.' || file[fi] === '..' ||
-            (!options.dot && file[fi].charAt(0) === '.')) return false
-        }
-        return true
-      }
-
-      // ok, let's see if we can swallow whatever we can.
-      while (fr < fl) {
-        var swallowee = file[fr]
-
-        this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
-
-        // XXX remove this slice.  Just pass the start index.
-        if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
-          this.debug('globstar found match!', fr, fl, swallowee)
-          // found a match.
-          return true
-        } else {
-          // can't swallow "." or ".." ever.
-          // can only swallow ".foo" when explicitly asked.
-          if (swallowee === '.' || swallowee === '..' ||
-            (!options.dot && swallowee.charAt(0) === '.')) {
-            this.debug('dot detected!', file, fr, pattern, pr)
-            break
-          }
-
-          // ** swallows a segment, and continue.
-          this.debug('globstar swallow a segment, and continue')
-          fr++
-        }
-      }
-
-      // no match was found.
-      // However, in partial mode, we can't say this is necessarily over.
-      // If there's more *pattern* left, then
-      if (partial) {
-        // ran out of file
-        this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
-        if (fr === fl) return true
-      }
-      return false
-    }
-
-    // something other than **
-    // non-magic patterns just have to match exactly
-    // patterns with magic have been turned into regexps.
-    var hit
-    if (typeof p === 'string') {
-      if (options.nocase) {
-        hit = f.toLowerCase() === p.toLowerCase()
-      } else {
-        hit = f === p
-      }
-      this.debug('string match', p, f, hit)
-    } else {
-      hit = f.match(p)
-      this.debug('pattern match', p, f, hit)
-    }
-
-    if (!hit) return false
-  }
-
-  // Note: ending in / means that we'll get a final ""
-  // at the end of the pattern.  This can only match a
-  // corresponding "" at the end of the file.
-  // If the file ends in /, then it can only match a
-  // a pattern that ends in /, unless the pattern just
-  // doesn't have any more for it. But, a/b/ should *not*
-  // match "a/b/*", even though "" matches against the
-  // [^/]*? pattern, except in partial mode, where it might
-  // simply not be reached yet.
-  // However, a/b/ should still satisfy a/*
-
-  // now either we fell off the end of the pattern, or we're done.
-  if (fi === fl && pi === pl) {
-    // ran out of pattern and filename at the same time.
-    // an exact hit!
-    return true
-  } else if (fi === fl) {
-    // ran out of file, but still had pattern left.
-    // this is ok if we're doing the match as part of
-    // a glob fs traversal.
-    return partial
-  } else if (pi === pl) {
-    // ran out of pattern, still have file left.
-    // this is only acceptable if we're on the very last
-    // empty segment of a file with a trailing slash.
-    // a/* should match a/b/
-    var emptyFileEnd = (fi === fl - 1) && (file[fi] === '')
-    return emptyFileEnd
-  }
-
-  // should be unreachable.
-  throw new Error('wtf?')
-}
-
-// replace stuff like \* with *
-function globUnescape (s) {
-  return s.replace(/\\(.)/g, '$1')
-}
-
-function regExpEscape (s) {
-  return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
-}
+module.exports=minimatch,minimatch.Minimatch=Minimatch;var path={sep:"/"};try{path=require("path")}catch(t){}var GLOBSTAR=minimatch.GLOBSTAR=Minimatch.GLOBSTAR={},expand=require("brace-expansion"),plTypes={"!":{open:"(?:(?!(?:",close:"))[^/]*?)"},"?":{open:"(?:",close:")?"},"+":{open:"(?:",close:")+"},"*":{open:"(?:",close:")*"},"@":{open:"(?:",close:")"}},qmark="[^/]",star=qmark+"*?",twoStarDot="(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?",twoStarNoDot="(?:(?!(?:\\/|^)\\.).)*?",reSpecials=charSet("().*{}+?[]^$\\!");function charSet(t){return t.split("").reduce((function(t,e){return t[e]=!0,t}),{})}var slashSplit=/\/+/;function filter(t,e){return e=e||{},function(n,i,r){return minimatch(n,t,e)}}function ext(t,e){t=t||{},e=e||{};var n={};return Object.keys(e).forEach((function(t){n[t]=e[t]})),Object.keys(t).forEach((function(e){n[e]=t[e]})),n}function minimatch(t,e,n){if("string"!=typeof e)throw new TypeError("glob pattern string required");return n||(n={}),!(!n.nocomment&&"#"===e.charAt(0))&&(""===e.trim()?""===t:new Minimatch(e,n).match(t))}function Minimatch(t,e){if(!(this instanceof Minimatch))return new Minimatch(t,e);if("string"!=typeof t)throw new TypeError("glob pattern string required");e||(e={}),t=t.trim(),"/"!==path.sep&&(t=t.split(path.sep).join("/")),this.options=e,this.set=[],this.pattern=t,this.regexp=null,this.negate=!1,this.comment=!1,this.empty=!1,this.make()}function make(){if(!this._made){var t=this.pattern,e=this.options;if(e.nocomment||"#"!==t.charAt(0))if(t){this.parseNegate();var n=this.globSet=this.braceExpand();e.debug&&(this.debug=console.error),this.debug(this.pattern,n),n=this.globParts=n.map((function(t){return t.split(slashSplit)})),this.debug(this.pattern,n),n=n.map((function(t,e,n){return t.map(this.parse,this)}),this),this.debug(this.pattern,n),n=n.filter((function(t){return-1===t.indexOf(!1)})),this.debug(this.pattern,n),this.set=n}else this.empty=!0;else this.comment=!0}}function parseNegate(){var t=this.pattern,e=!1,n=0;if(!this.options.nonegate){for(var i=0,r=t.length;i<r&&"!"===t.charAt(i);i++)e=!e,n++;n&&(this.pattern=t.substr(n)),this.negate=e}}function braceExpand(t,e){if(e||(e=this instanceof Minimatch?this.options:{}),void 0===(t=void 0===t?this.pattern:t))throw new TypeError("undefined pattern");return e.nobrace||!t.match(/\{.*\}/)?[t]:expand(t)}minimatch.filter=filter,minimatch.defaults=function(t){if(!t||!Object.keys(t).length)return minimatch;var e=minimatch,n=function(n,i,r){return e.minimatch(n,i,ext(t,r))};return n.Minimatch=function(n,i){return new e.Minimatch(n,ext(t,i))},n},Minimatch.defaults=function(t){return t&&Object.keys(t).length?minimatch.defaults(t).Minimatch:Minimatch},Minimatch.prototype.debug=function(){},Minimatch.prototype.make=make,Minimatch.prototype.parseNegate=parseNegate,minimatch.braceExpand=function(t,e){return braceExpand(t,e)},Minimatch.prototype.braceExpand=braceExpand,Minimatch.prototype.parse=parse;var SUBPARSE={};function parse(t,e){if(t.length>65536)throw new TypeError("pattern is too long");var n=this.options;if(!n.noglobstar&&"**"===t)return GLOBSTAR;if(""===t)return"";var i,r="",a=!!n.nocase,s=!1,h=[],c=[],o=!1,p=-1,u=-1,f="."===t.charAt(0)?"":n.dot?"(?!(?:^|\\/)\\.{1,2}(?:$|\\/))":"(?!\\.)",l=this;function m(){if(i){switch(i){case"*":r+=star,a=!0;break;case"?":r+=qmark,a=!0;break;default:r+="\\"+i}l.debug("clearStateChar %j %j",i,r),i=!1}}for(var g,d=0,b=t.length;d<b&&(g=t.charAt(d));d++)if(this.debug("%s\t%s %s %j",t,d,r,g),s&&reSpecials[g])r+="\\"+g,s=!1;else switch(g){case"/":return!1;case"\\":m(),s=!0;continue;case"?":case"*":case"+":case"@":case"!":if(this.debug("%s\t%s %s %j <-- stateChar",t,d,r,g),o){this.debug("  in class"),"!"===g&&d===u+1&&(g="^"),r+=g;continue}l.debug("call clearStateChar %j",i),m(),i=g,n.noext&&m();continue;case"(":if(o){r+="(";continue}if(!i){r+="\\(";continue}h.push({type:i,start:d-1,reStart:r.length,open:plTypes[i].open,close:plTypes[i].close}),r+="!"===i?"(?:(?!(?:":"(?:",this.debug("plType %j %j",i,r),i=!1;continue;case")":if(o||!h.length){r+="\\)";continue}m(),a=!0;var v=h.pop();r+=v.close,"!"===v.type&&c.push(v),v.reEnd=r.length;continue;case"|":if(o||!h.length||s){r+="\\|",s=!1;continue}m(),r+="|";continue;case"[":if(m(),o){r+="\\"+g;continue}o=!0,u=d,p=r.length,r+=g;continue;case"]":if(d===u+1||!o){r+="\\"+g,s=!1;continue}if(o){var S=t.substring(u+1,d);try{RegExp("["+S+"]")}catch(t){var y=this.parse(S,SUBPARSE);r=r.substr(0,p)+"\\["+y[0]+"\\]",a=a||y[1],o=!1;continue}}a=!0,o=!1,r+=g;continue;default:m(),s?s=!1:!reSpecials[g]||"^"===g&&o||(r+="\\"),r+=g}for(o&&(S=t.substr(u+1),y=this.parse(S,SUBPARSE),r=r.substr(0,p)+"\\["+y[0],a=a||y[1]),v=h.pop();v;v=h.pop()){var w=r.slice(v.reStart+v.open.length);this.debug("setting tail",r,v),w=w.replace(/((?:\\{2}){0,64})(\\?)\|/g,(function(t,e,n){return n||(n="\\"),e+e+n+"|"})),this.debug("tail=%j\n   %s",w,w,v,r);var E="*"===v.type?star:"?"===v.type?qmark:"\\"+v.type;a=!0,r=r.slice(0,v.reStart)+E+"\\("+w}m(),s&&(r+="\\\\");var x=!1;switch(r.charAt(0)){case".":case"[":case"(":x=!0}for(var M=c.length-1;M>-1;M--){var R=c[M],k=r.slice(0,R.reStart),A=r.slice(R.reStart,R.reEnd-8),O=r.slice(R.reEnd-8,R.reEnd),j=r.slice(R.reEnd);O+=j;var T=k.split("(").length-1,B=j;for(d=0;d<T;d++)B=B.replace(/\)[+*?]?/,"");var $="";""===(j=B)&&e!==SUBPARSE&&($="$"),r=k+A+j+$+O}if(""!==r&&a&&(r="(?=.)"+r),x&&(r=f+r),e===SUBPARSE)return[r,a];if(!a)return globUnescape(t);var L=n.nocase?"i":"";try{var q=new RegExp("^"+r+"$",L)}catch(t){return new RegExp("$.")}return q._glob=t,q._src=r,q}function makeRe(){if(this.regexp||!1===this.regexp)return this.regexp;var t=this.set;if(!t.length)return this.regexp=!1,this.regexp;var e=this.options,n=e.noglobstar?star:e.dot?twoStarDot:twoStarNoDot,i=e.nocase?"i":"",r=t.map((function(t){return t.map((function(t){return t===GLOBSTAR?n:"string"==typeof t?regExpEscape(t):t._src})).join("\\/")})).join("|");r="^(?:"+r+")$",this.negate&&(r="^(?!"+r+").*$");try{this.regexp=new RegExp(r,i)}catch(t){this.regexp=!1}return this.regexp}function match(t,e){if(this.debug("match",t,this.pattern),this.comment)return!1;if(this.empty)return""===t;if("/"===t&&e)return!0;var n=this.options;"/"!==path.sep&&(t=t.split(path.sep).join("/")),t=t.split(slashSplit),this.debug(this.pattern,"split",t);var i,r,a=this.set;for(this.debug(this.pattern,"set",a),r=t.length-1;r>=0&&!(i=t[r]);r--);for(r=0;r<a.length;r++){var s=a[r],h=t;if(n.matchBase&&1===s.length&&(h=[i]),this.matchOne(h,s,e))return!!n.flipNegate||!this.negate}return!n.flipNegate&&this.negate}function globUnescape(t){return t.replace(/\\(.)/g,"$1")}function regExpEscape(t){return t.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}minimatch.makeRe=function(t,e){return new Minimatch(t,e||{}).makeRe()},Minimatch.prototype.makeRe=makeRe,minimatch.match=function(t,e,n){var i=new Minimatch(e,n=n||{});return t=t.filter((function(t){return i.match(t)})),i.options.nonull&&!t.length&&t.push(e),t},Minimatch.prototype.match=match,Minimatch.prototype.matchOne=function(t,e,n){var i=this.options;this.debug("matchOne",{this:this,file:t,pattern:e}),this.debug("matchOne",t.length,e.length);for(var r=0,a=0,s=t.length,h=e.length;r<s&&a<h;r++,a++){this.debug("matchOne loop");var c,o=e[a],p=t[r];if(this.debug(e,o,p),!1===o)return!1;if(o===GLOBSTAR){this.debug("GLOBSTAR",[e,o,p]);var u=r,f=a+1;if(f===h){for(this.debug("** at the end");r<s;r++)if("."===t[r]||".."===t[r]||!i.dot&&"."===t[r].charAt(0))return!1;return!0}for(;u<s;){var l=t[u];if(this.debug("\nglobstar while",t,u,e,f,l),this.matchOne(t.slice(u),e.slice(f),n))return this.debug("globstar found match!",u,s,l),!0;if("."===l||".."===l||!i.dot&&"."===l.charAt(0)){this.debug("dot detected!",t,u,e,f);break}this.debug("globstar swallow a segment, and continue"),u++}return!(!n||(this.debug("\n>>> no match, partial?",t,u,e,f),u!==s))}if("string"==typeof o?(c=i.nocase?p.toLowerCase()===o.toLowerCase():p===o,this.debug("string match",o,p,c)):(c=p.match(o),this.debug("pattern match",o,p,c)),!c)return!1}if(r===s&&a===h)return!0;if(r===s)return n;if(a===h)return r===s-1&&""===t[r];throw new Error("wtf?")};
\ No newline at end of file
index c4498bc..193a2cf 100644 (file)
@@ -1,162 +1 @@
-/**
- * Helpers.
- */
-
-var s = 1000;
-var m = s * 60;
-var h = m * 60;
-var d = h * 24;
-var w = d * 7;
-var y = d * 365.25;
-
-/**
- * Parse or format the given `val`.
- *
- * Options:
- *
- *  - `long` verbose formatting [false]
- *
- * @param {String|Number} val
- * @param {Object} [options]
- * @throws {Error} throw an error if val is not a non-empty string or a number
- * @return {String|Number}
- * @api public
- */
-
-module.exports = function(val, options) {
-  options = options || {};
-  var type = typeof val;
-  if (type === 'string' && val.length > 0) {
-    return parse(val);
-  } else if (type === 'number' && isFinite(val)) {
-    return options.long ? fmtLong(val) : fmtShort(val);
-  }
-  throw new Error(
-    'val is not a non-empty string or a valid number. val=' +
-      JSON.stringify(val)
-  );
-};
-
-/**
- * Parse the given `str` and return milliseconds.
- *
- * @param {String} str
- * @return {Number}
- * @api private
- */
-
-function parse(str) {
-  str = String(str);
-  if (str.length > 100) {
-    return;
-  }
-  var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
-    str
-  );
-  if (!match) {
-    return;
-  }
-  var n = parseFloat(match[1]);
-  var type = (match[2] || 'ms').toLowerCase();
-  switch (type) {
-    case 'years':
-    case 'year':
-    case 'yrs':
-    case 'yr':
-    case 'y':
-      return n * y;
-    case 'weeks':
-    case 'week':
-    case 'w':
-      return n * w;
-    case 'days':
-    case 'day':
-    case 'd':
-      return n * d;
-    case 'hours':
-    case 'hour':
-    case 'hrs':
-    case 'hr':
-    case 'h':
-      return n * h;
-    case 'minutes':
-    case 'minute':
-    case 'mins':
-    case 'min':
-    case 'm':
-      return n * m;
-    case 'seconds':
-    case 'second':
-    case 'secs':
-    case 'sec':
-    case 's':
-      return n * s;
-    case 'milliseconds':
-    case 'millisecond':
-    case 'msecs':
-    case 'msec':
-    case 'ms':
-      return n;
-    default:
-      return undefined;
-  }
-}
-
-/**
- * Short format for `ms`.
- *
- * @param {Number} ms
- * @return {String}
- * @api private
- */
-
-function fmtShort(ms) {
-  var msAbs = Math.abs(ms);
-  if (msAbs >= d) {
-    return Math.round(ms / d) + 'd';
-  }
-  if (msAbs >= h) {
-    return Math.round(ms / h) + 'h';
-  }
-  if (msAbs >= m) {
-    return Math.round(ms / m) + 'm';
-  }
-  if (msAbs >= s) {
-    return Math.round(ms / s) + 's';
-  }
-  return ms + 'ms';
-}
-
-/**
- * Long format for `ms`.
- *
- * @param {Number} ms
- * @return {String}
- * @api private
- */
-
-function fmtLong(ms) {
-  var msAbs = Math.abs(ms);
-  if (msAbs >= d) {
-    return plural(ms, msAbs, d, 'day');
-  }
-  if (msAbs >= h) {
-    return plural(ms, msAbs, h, 'hour');
-  }
-  if (msAbs >= m) {
-    return plural(ms, msAbs, m, 'minute');
-  }
-  if (msAbs >= s) {
-    return plural(ms, msAbs, s, 'second');
-  }
-  return ms + ' ms';
-}
-
-/**
- * Pluralization helper.
- */
-
-function plural(ms, msAbs, n, name) {
-  var isPlural = msAbs >= n * 1.5;
-  return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
-}
+var s=1e3,m=60*s,h=60*m,d=24*h,w=7*d,y=365.25*d;function parse(e){if(!((e=String(e)).length>100)){var r=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(r){var a=parseFloat(r[1]);switch((r[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return a*y;case"weeks":case"week":case"w":return a*w;case"days":case"day":case"d":return a*d;case"hours":case"hour":case"hrs":case"hr":case"h":return a*h;case"minutes":case"minute":case"mins":case"min":case"m":return a*m;case"seconds":case"second":case"secs":case"sec":case"s":return a*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}}}function fmtShort(e){var r=Math.abs(e);return r>=d?Math.round(e/d)+"d":r>=h?Math.round(e/h)+"h":r>=m?Math.round(e/m)+"m":r>=s?Math.round(e/s)+"s":e+"ms"}function fmtLong(e){var r=Math.abs(e);return r>=d?plural(e,r,d,"day"):r>=h?plural(e,r,h,"hour"):r>=m?plural(e,r,m,"minute"):r>=s?plural(e,r,s,"second"):e+" ms"}function plural(s,e,r,a){var n=e>=1.5*r;return Math.round(s/r)+" "+a+(n?"s":"")}module.exports=function(s,e){e=e||{};var r=typeof s;if("string"===r&&s.length>0)return parse(s);if("number"===r&&isFinite(s))return e.long?fmtLong(s):fmtShort(s);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(s))};
\ No newline at end of file
index 8d4f6a2..c988eb2 100644 (file)
@@ -5,120 +5,4 @@
  * Copyright(c) 2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict';
-
-/**
- * Cached loaded submodules.
- * @private
- */
-
-var modules = Object.create(null);
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = Negotiator;
-module.exports.Negotiator = Negotiator;
-
-/**
- * Create a Negotiator instance from a request.
- * @param {object} request
- * @public
- */
-
-function Negotiator(request) {
-  if (!(this instanceof Negotiator)) {
-    return new Negotiator(request);
-  }
-
-  this.request = request;
-}
-
-Negotiator.prototype.charset = function charset(available) {
-  var set = this.charsets(available);
-  return set && set[0];
-};
-
-Negotiator.prototype.charsets = function charsets(available) {
-  var preferredCharsets = loadModule('charset').preferredCharsets;
-  return preferredCharsets(this.request.headers['accept-charset'], available);
-};
-
-Negotiator.prototype.encoding = function encoding(available) {
-  var set = this.encodings(available);
-  return set && set[0];
-};
-
-Negotiator.prototype.encodings = function encodings(available) {
-  var preferredEncodings = loadModule('encoding').preferredEncodings;
-  return preferredEncodings(this.request.headers['accept-encoding'], available);
-};
-
-Negotiator.prototype.language = function language(available) {
-  var set = this.languages(available);
-  return set && set[0];
-};
-
-Negotiator.prototype.languages = function languages(available) {
-  var preferredLanguages = loadModule('language').preferredLanguages;
-  return preferredLanguages(this.request.headers['accept-language'], available);
-};
-
-Negotiator.prototype.mediaType = function mediaType(available) {
-  var set = this.mediaTypes(available);
-  return set && set[0];
-};
-
-Negotiator.prototype.mediaTypes = function mediaTypes(available) {
-  var preferredMediaTypes = loadModule('mediaType').preferredMediaTypes;
-  return preferredMediaTypes(this.request.headers.accept, available);
-};
-
-// Backwards compatibility
-Negotiator.prototype.preferredCharset = Negotiator.prototype.charset;
-Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets;
-Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding;
-Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings;
-Negotiator.prototype.preferredLanguage = Negotiator.prototype.language;
-Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages;
-Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType;
-Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes;
-
-/**
- * Load the given module.
- * @private
- */
-
-function loadModule(moduleName) {
-  var module = modules[moduleName];
-
-  if (module !== undefined) {
-    return module;
-  }
-
-  // This uses a switch for static require analysis
-  switch (moduleName) {
-    case 'charset':
-      module = require('./lib/charset');
-      break;
-    case 'encoding':
-      module = require('./lib/encoding');
-      break;
-    case 'language':
-      module = require('./lib/language');
-      break;
-    case 'mediaType':
-      module = require('./lib/mediaType');
-      break;
-    default:
-      throw new Error('Cannot find module \'' + moduleName + '\'');
-  }
-
-  // Store to prevent invoking require()
-  modules[moduleName] = module;
-
-  return module;
-}
+"use strict";var modules=Object.create(null);function Negotiator(e){if(!(this instanceof Negotiator))return new Negotiator(e);this.request=e}function loadModule(e){var t=modules[e];if(void 0!==t)return t;switch(e){case"charset":t=require("./lib/charset");break;case"encoding":t=require("./lib/encoding");break;case"language":t=require("./lib/language");break;case"mediaType":t=require("./lib/mediaType");break;default:throw new Error("Cannot find module '"+e+"'")}return modules[e]=t,t}module.exports=Negotiator,module.exports.Negotiator=Negotiator,Negotiator.prototype.charset=function(e){var t=this.charsets(e);return t&&t[0]},Negotiator.prototype.charsets=function(e){return(0,loadModule("charset").preferredCharsets)(this.request.headers["accept-charset"],e)},Negotiator.prototype.encoding=function(e){var t=this.encodings(e);return t&&t[0]},Negotiator.prototype.encodings=function(e){return(0,loadModule("encoding").preferredEncodings)(this.request.headers["accept-encoding"],e)},Negotiator.prototype.language=function(e){var t=this.languages(e);return t&&t[0]},Negotiator.prototype.languages=function(e){return(0,loadModule("language").preferredLanguages)(this.request.headers["accept-language"],e)},Negotiator.prototype.mediaType=function(e){var t=this.mediaTypes(e);return t&&t[0]},Negotiator.prototype.mediaTypes=function(e){return(0,loadModule("mediaType").preferredMediaTypes)(this.request.headers.accept,e)},Negotiator.prototype.preferredCharset=Negotiator.prototype.charset,Negotiator.prototype.preferredCharsets=Negotiator.prototype.charsets,Negotiator.prototype.preferredEncoding=Negotiator.prototype.encoding,Negotiator.prototype.preferredEncodings=Negotiator.prototype.encodings,Negotiator.prototype.preferredLanguage=Negotiator.prototype.language,Negotiator.prototype.preferredLanguages=Negotiator.prototype.languages,Negotiator.prototype.preferredMediaType=Negotiator.prototype.mediaType,Negotiator.prototype.preferredMediaTypes=Negotiator.prototype.mediaTypes;
\ No newline at end of file
index cdd0148..4d556a4 100644 (file)
@@ -1,169 +1 @@
-/**
- * negotiator
- * Copyright(c) 2012 Isaac Z. Schlueter
- * Copyright(c) 2014 Federico Romero
- * Copyright(c) 2014-2015 Douglas Christopher Wilson
- * MIT Licensed
- */
-
-'use strict';
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = preferredCharsets;
-module.exports.preferredCharsets = preferredCharsets;
-
-/**
- * Module variables.
- * @private
- */
-
-var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/;
-
-/**
- * Parse the Accept-Charset header.
- * @private
- */
-
-function parseAcceptCharset(accept) {
-  var accepts = accept.split(',');
-
-  for (var i = 0, j = 0; i < accepts.length; i++) {
-    var charset = parseCharset(accepts[i].trim(), i);
-
-    if (charset) {
-      accepts[j++] = charset;
-    }
-  }
-
-  // trim accepts
-  accepts.length = j;
-
-  return accepts;
-}
-
-/**
- * Parse a charset from the Accept-Charset header.
- * @private
- */
-
-function parseCharset(str, i) {
-  var match = simpleCharsetRegExp.exec(str);
-  if (!match) return null;
-
-  var charset = match[1];
-  var q = 1;
-  if (match[2]) {
-    var params = match[2].split(';')
-    for (var j = 0; j < params.length; j++) {
-      var p = params[j].trim().split('=');
-      if (p[0] === 'q') {
-        q = parseFloat(p[1]);
-        break;
-      }
-    }
-  }
-
-  return {
-    charset: charset,
-    q: q,
-    i: i
-  };
-}
-
-/**
- * Get the priority of a charset.
- * @private
- */
-
-function getCharsetPriority(charset, accepted, index) {
-  var priority = {o: -1, q: 0, s: 0};
-
-  for (var i = 0; i < accepted.length; i++) {
-    var spec = specify(charset, accepted[i], index);
-
-    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
-      priority = spec;
-    }
-  }
-
-  return priority;
-}
-
-/**
- * Get the specificity of the charset.
- * @private
- */
-
-function specify(charset, spec, index) {
-  var s = 0;
-  if(spec.charset.toLowerCase() === charset.toLowerCase()){
-    s |= 1;
-  } else if (spec.charset !== '*' ) {
-    return null
-  }
-
-  return {
-    i: index,
-    o: spec.i,
-    q: spec.q,
-    s: s
-  }
-}
-
-/**
- * Get the preferred charsets from an Accept-Charset header.
- * @public
- */
-
-function preferredCharsets(accept, provided) {
-  // RFC 2616 sec 14.2: no header = *
-  var accepts = parseAcceptCharset(accept === undefined ? '*' : accept || '');
-
-  if (!provided) {
-    // sorted list of all charsets
-    return accepts
-      .filter(isQuality)
-      .sort(compareSpecs)
-      .map(getFullCharset);
-  }
-
-  var priorities = provided.map(function getPriority(type, index) {
-    return getCharsetPriority(type, accepts, index);
-  });
-
-  // sorted list of accepted charsets
-  return priorities.filter(isQuality).sort(compareSpecs).map(function getCharset(priority) {
-    return provided[priorities.indexOf(priority)];
-  });
-}
-
-/**
- * Compare two specs.
- * @private
- */
-
-function compareSpecs(a, b) {
-  return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
-}
-
-/**
- * Get full charset string.
- * @private
- */
-
-function getFullCharset(spec) {
-  return spec.charset;
-}
-
-/**
- * Check if a spec has any quality.
- * @private
- */
-
-function isQuality(spec) {
-  return spec.q > 0;
-}
+"use strict";module.exports=preferredCharsets,module.exports.preferredCharsets=preferredCharsets;var simpleCharsetRegExp=/^\s*([^\s;]+)\s*(?:;(.*))?$/;function parseAcceptCharset(r){for(var e=r.split(","),t=0,s=0;t<e.length;t++){var a=parseCharset(e[t].trim(),t);a&&(e[s++]=a)}return e.length=s,e}function parseCharset(r,e){var t=simpleCharsetRegExp.exec(r);if(!t)return null;var s=t[1],a=1;if(t[2])for(var i=t[2].split(";"),n=0;n<i.length;n++){var o=i[n].trim().split("=");if("q"===o[0]){a=parseFloat(o[1]);break}}return{charset:s,q:a,i:e}}function getCharsetPriority(r,e,t){for(var s={o:-1,q:0,s:0},a=0;a<e.length;a++){var i=specify(r,e[a],t);i&&(s.s-i.s||s.q-i.q||s.o-i.o)<0&&(s=i)}return s}function specify(r,e,t){var s=0;if(e.charset.toLowerCase()===r.toLowerCase())s|=1;else if("*"!==e.charset)return null;return{i:t,o:e.i,q:e.q,s:s}}function preferredCharsets(r,e){var t=parseAcceptCharset(void 0===r?"*":r||"");if(!e)return t.filter(isQuality).sort(compareSpecs).map(getFullCharset);var s=e.map((function(r,e){return getCharsetPriority(r,t,e)}));return s.filter(isQuality).sort(compareSpecs).map((function(r){return e[s.indexOf(r)]}))}function compareSpecs(r,e){return e.q-r.q||e.s-r.s||r.o-e.o||r.i-e.i||0}function getFullCharset(r){return r.charset}function isQuality(r){return r.q>0}
\ No newline at end of file
index 8432cd7..5d5e63c 100644 (file)
@@ -1,184 +1 @@
-/**
- * negotiator
- * Copyright(c) 2012 Isaac Z. Schlueter
- * Copyright(c) 2014 Federico Romero
- * Copyright(c) 2014-2015 Douglas Christopher Wilson
- * MIT Licensed
- */
-
-'use strict';
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = preferredEncodings;
-module.exports.preferredEncodings = preferredEncodings;
-
-/**
- * Module variables.
- * @private
- */
-
-var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/;
-
-/**
- * Parse the Accept-Encoding header.
- * @private
- */
-
-function parseAcceptEncoding(accept) {
-  var accepts = accept.split(',');
-  var hasIdentity = false;
-  var minQuality = 1;
-
-  for (var i = 0, j = 0; i < accepts.length; i++) {
-    var encoding = parseEncoding(accepts[i].trim(), i);
-
-    if (encoding) {
-      accepts[j++] = encoding;
-      hasIdentity = hasIdentity || specify('identity', encoding);
-      minQuality = Math.min(minQuality, encoding.q || 1);
-    }
-  }
-
-  if (!hasIdentity) {
-    /*
-     * If identity doesn't explicitly appear in the accept-encoding header,
-     * it's added to the list of acceptable encoding with the lowest q
-     */
-    accepts[j++] = {
-      encoding: 'identity',
-      q: minQuality,
-      i: i
-    };
-  }
-
-  // trim accepts
-  accepts.length = j;
-
-  return accepts;
-}
-
-/**
- * Parse an encoding from the Accept-Encoding header.
- * @private
- */
-
-function parseEncoding(str, i) {
-  var match = simpleEncodingRegExp.exec(str);
-  if (!match) return null;
-
-  var encoding = match[1];
-  var q = 1;
-  if (match[2]) {
-    var params = match[2].split(';');
-    for (var j = 0; j < params.length; j++) {
-      var p = params[j].trim().split('=');
-      if (p[0] === 'q') {
-        q = parseFloat(p[1]);
-        break;
-      }
-    }
-  }
-
-  return {
-    encoding: encoding,
-    q: q,
-    i: i
-  };
-}
-
-/**
- * Get the priority of an encoding.
- * @private
- */
-
-function getEncodingPriority(encoding, accepted, index) {
-  var priority = {o: -1, q: 0, s: 0};
-
-  for (var i = 0; i < accepted.length; i++) {
-    var spec = specify(encoding, accepted[i], index);
-
-    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
-      priority = spec;
-    }
-  }
-
-  return priority;
-}
-
-/**
- * Get the specificity of the encoding.
- * @private
- */
-
-function specify(encoding, spec, index) {
-  var s = 0;
-  if(spec.encoding.toLowerCase() === encoding.toLowerCase()){
-    s |= 1;
-  } else if (spec.encoding !== '*' ) {
-    return null
-  }
-
-  return {
-    i: index,
-    o: spec.i,
-    q: spec.q,
-    s: s
-  }
-};
-
-/**
- * Get the preferred encodings from an Accept-Encoding header.
- * @public
- */
-
-function preferredEncodings(accept, provided) {
-  var accepts = parseAcceptEncoding(accept || '');
-
-  if (!provided) {
-    // sorted list of all encodings
-    return accepts
-      .filter(isQuality)
-      .sort(compareSpecs)
-      .map(getFullEncoding);
-  }
-
-  var priorities = provided.map(function getPriority(type, index) {
-    return getEncodingPriority(type, accepts, index);
-  });
-
-  // sorted list of accepted encodings
-  return priorities.filter(isQuality).sort(compareSpecs).map(function getEncoding(priority) {
-    return provided[priorities.indexOf(priority)];
-  });
-}
-
-/**
- * Compare two specs.
- * @private
- */
-
-function compareSpecs(a, b) {
-  return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
-}
-
-/**
- * Get full encoding string.
- * @private
- */
-
-function getFullEncoding(spec) {
-  return spec.encoding;
-}
-
-/**
- * Check if a spec has any quality.
- * @private
- */
-
-function isQuality(spec) {
-  return spec.q > 0;
-}
+"use strict";module.exports=preferredEncodings,module.exports.preferredEncodings=preferredEncodings;var simpleEncodingRegExp=/^\s*([^\s;]+)\s*(?:;(.*))?$/;function parseAcceptEncoding(n){for(var e=n.split(","),r=!1,i=1,t=0,o=0;t<e.length;t++){var c=parseEncoding(e[t].trim(),t);c&&(e[o++]=c,r=r||specify("identity",c),i=Math.min(i,c.q||1))}return r||(e[o++]={encoding:"identity",q:i,i:t}),e.length=o,e}function parseEncoding(n,e){var r=simpleEncodingRegExp.exec(n);if(!r)return null;var i=r[1],t=1;if(r[2])for(var o=r[2].split(";"),c=0;c<o.length;c++){var s=o[c].trim().split("=");if("q"===s[0]){t=parseFloat(s[1]);break}}return{encoding:i,q:t,i:e}}function getEncodingPriority(n,e,r){for(var i={o:-1,q:0,s:0},t=0;t<e.length;t++){var o=specify(n,e[t],r);o&&(i.s-o.s||i.q-o.q||i.o-o.o)<0&&(i=o)}return i}function specify(n,e,r){var i=0;if(e.encoding.toLowerCase()===n.toLowerCase())i|=1;else if("*"!==e.encoding)return null;return{i:r,o:e.i,q:e.q,s:i}}function preferredEncodings(n,e){var r=parseAcceptEncoding(n||"");if(!e)return r.filter(isQuality).sort(compareSpecs).map(getFullEncoding);var i=e.map((function(n,e){return getEncodingPriority(n,r,e)}));return i.filter(isQuality).sort(compareSpecs).map((function(n){return e[i.indexOf(n)]}))}function compareSpecs(n,e){return e.q-n.q||e.s-n.s||n.o-e.o||n.i-e.i||0}function getFullEncoding(n){return n.encoding}function isQuality(n){return n.q>0}
\ No newline at end of file
index 62f737f..e68c927 100644 (file)
@@ -1,179 +1 @@
-/**
- * negotiator
- * Copyright(c) 2012 Isaac Z. Schlueter
- * Copyright(c) 2014 Federico Romero
- * Copyright(c) 2014-2015 Douglas Christopher Wilson
- * MIT Licensed
- */
-
-'use strict';
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = preferredLanguages;
-module.exports.preferredLanguages = preferredLanguages;
-
-/**
- * Module variables.
- * @private
- */
-
-var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/;
-
-/**
- * Parse the Accept-Language header.
- * @private
- */
-
-function parseAcceptLanguage(accept) {
-  var accepts = accept.split(',');
-
-  for (var i = 0, j = 0; i < accepts.length; i++) {
-    var language = parseLanguage(accepts[i].trim(), i);
-
-    if (language) {
-      accepts[j++] = language;
-    }
-  }
-
-  // trim accepts
-  accepts.length = j;
-
-  return accepts;
-}
-
-/**
- * Parse a language from the Accept-Language header.
- * @private
- */
-
-function parseLanguage(str, i) {
-  var match = simpleLanguageRegExp.exec(str);
-  if (!match) return null;
-
-  var prefix = match[1],
-    suffix = match[2],
-    full = prefix;
-
-  if (suffix) full += "-" + suffix;
-
-  var q = 1;
-  if (match[3]) {
-    var params = match[3].split(';')
-    for (var j = 0; j < params.length; j++) {
-      var p = params[j].split('=');
-      if (p[0] === 'q') q = parseFloat(p[1]);
-    }
-  }
-
-  return {
-    prefix: prefix,
-    suffix: suffix,
-    q: q,
-    i: i,
-    full: full
-  };
-}
-
-/**
- * Get the priority of a language.
- * @private
- */
-
-function getLanguagePriority(language, accepted, index) {
-  var priority = {o: -1, q: 0, s: 0};
-
-  for (var i = 0; i < accepted.length; i++) {
-    var spec = specify(language, accepted[i], index);
-
-    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
-      priority = spec;
-    }
-  }
-
-  return priority;
-}
-
-/**
- * Get the specificity of the language.
- * @private
- */
-
-function specify(language, spec, index) {
-  var p = parseLanguage(language)
-  if (!p) return null;
-  var s = 0;
-  if(spec.full.toLowerCase() === p.full.toLowerCase()){
-    s |= 4;
-  } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) {
-    s |= 2;
-  } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) {
-    s |= 1;
-  } else if (spec.full !== '*' ) {
-    return null
-  }
-
-  return {
-    i: index,
-    o: spec.i,
-    q: spec.q,
-    s: s
-  }
-};
-
-/**
- * Get the preferred languages from an Accept-Language header.
- * @public
- */
-
-function preferredLanguages(accept, provided) {
-  // RFC 2616 sec 14.4: no header = *
-  var accepts = parseAcceptLanguage(accept === undefined ? '*' : accept || '');
-
-  if (!provided) {
-    // sorted list of all languages
-    return accepts
-      .filter(isQuality)
-      .sort(compareSpecs)
-      .map(getFullLanguage);
-  }
-
-  var priorities = provided.map(function getPriority(type, index) {
-    return getLanguagePriority(type, accepts, index);
-  });
-
-  // sorted list of accepted languages
-  return priorities.filter(isQuality).sort(compareSpecs).map(function getLanguage(priority) {
-    return provided[priorities.indexOf(priority)];
-  });
-}
-
-/**
- * Compare two specs.
- * @private
- */
-
-function compareSpecs(a, b) {
-  return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
-}
-
-/**
- * Get full language string.
- * @private
- */
-
-function getFullLanguage(spec) {
-  return spec.full;
-}
-
-/**
- * Check if a spec has any quality.
- * @private
- */
-
-function isQuality(spec) {
-  return spec.q > 0;
-}
+"use strict";module.exports=preferredLanguages,module.exports.preferredLanguages=preferredLanguages;var simpleLanguageRegExp=/^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/;function parseAcceptLanguage(e){for(var r=e.split(","),a=0,t=0;a<r.length;a++){var u=parseLanguage(r[a].trim(),a);u&&(r[t++]=u)}return r.length=t,r}function parseLanguage(e,r){var a=simpleLanguageRegExp.exec(e);if(!a)return null;var t=a[1],u=a[2],n=t;u&&(n+="-"+u);var i=1;if(a[3])for(var s=a[3].split(";"),l=0;l<s.length;l++){var o=s[l].split("=");"q"===o[0]&&(i=parseFloat(o[1]))}return{prefix:t,suffix:u,q:i,i:r,full:n}}function getLanguagePriority(e,r,a){for(var t={o:-1,q:0,s:0},u=0;u<r.length;u++){var n=specify(e,r[u],a);n&&(t.s-n.s||t.q-n.q||t.o-n.o)<0&&(t=n)}return t}function specify(e,r,a){var t=parseLanguage(e);if(!t)return null;var u=0;if(r.full.toLowerCase()===t.full.toLowerCase())u|=4;else if(r.prefix.toLowerCase()===t.full.toLowerCase())u|=2;else if(r.full.toLowerCase()===t.prefix.toLowerCase())u|=1;else if("*"!==r.full)return null;return{i:a,o:r.i,q:r.q,s:u}}function preferredLanguages(e,r){var a=parseAcceptLanguage(void 0===e?"*":e||"");if(!r)return a.filter(isQuality).sort(compareSpecs).map(getFullLanguage);var t=r.map((function(e,r){return getLanguagePriority(e,a,r)}));return t.filter(isQuality).sort(compareSpecs).map((function(e){return r[t.indexOf(e)]}))}function compareSpecs(e,r){return r.q-e.q||r.s-e.s||e.o-r.o||e.i-r.i||0}function getFullLanguage(e){return e.full}function isQuality(e){return e.q>0}
\ No newline at end of file
index 67309dd..1c03e6a 100644 (file)
@@ -1,294 +1 @@
-/**
- * negotiator
- * Copyright(c) 2012 Isaac Z. Schlueter
- * Copyright(c) 2014 Federico Romero
- * Copyright(c) 2014-2015 Douglas Christopher Wilson
- * MIT Licensed
- */
-
-'use strict';
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = preferredMediaTypes;
-module.exports.preferredMediaTypes = preferredMediaTypes;
-
-/**
- * Module variables.
- * @private
- */
-
-var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/;
-
-/**
- * Parse the Accept header.
- * @private
- */
-
-function parseAccept(accept) {
-  var accepts = splitMediaTypes(accept);
-
-  for (var i = 0, j = 0; i < accepts.length; i++) {
-    var mediaType = parseMediaType(accepts[i].trim(), i);
-
-    if (mediaType) {
-      accepts[j++] = mediaType;
-    }
-  }
-
-  // trim accepts
-  accepts.length = j;
-
-  return accepts;
-}
-
-/**
- * Parse a media type from the Accept header.
- * @private
- */
-
-function parseMediaType(str, i) {
-  var match = simpleMediaTypeRegExp.exec(str);
-  if (!match) return null;
-
-  var params = Object.create(null);
-  var q = 1;
-  var subtype = match[2];
-  var type = match[1];
-
-  if (match[3]) {
-    var kvps = splitParameters(match[3]).map(splitKeyValuePair);
-
-    for (var j = 0; j < kvps.length; j++) {
-      var pair = kvps[j];
-      var key = pair[0].toLowerCase();
-      var val = pair[1];
-
-      // get the value, unwrapping quotes
-      var value = val && val[0] === '"' && val[val.length - 1] === '"'
-        ? val.substr(1, val.length - 2)
-        : val;
-
-      if (key === 'q') {
-        q = parseFloat(value);
-        break;
-      }
-
-      // store parameter
-      params[key] = value;
-    }
-  }
-
-  return {
-    type: type,
-    subtype: subtype,
-    params: params,
-    q: q,
-    i: i
-  };
-}
-
-/**
- * Get the priority of a media type.
- * @private
- */
-
-function getMediaTypePriority(type, accepted, index) {
-  var priority = {o: -1, q: 0, s: 0};
-
-  for (var i = 0; i < accepted.length; i++) {
-    var spec = specify(type, accepted[i], index);
-
-    if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
-      priority = spec;
-    }
-  }
-
-  return priority;
-}
-
-/**
- * Get the specificity of the media type.
- * @private
- */
-
-function specify(type, spec, index) {
-  var p = parseMediaType(type);
-  var s = 0;
-
-  if (!p) {
-    return null;
-  }
-
-  if(spec.type.toLowerCase() == p.type.toLowerCase()) {
-    s |= 4
-  } else if(spec.type != '*') {
-    return null;
-  }
-
-  if(spec.subtype.toLowerCase() == p.subtype.toLowerCase()) {
-    s |= 2
-  } else if(spec.subtype != '*') {
-    return null;
-  }
-
-  var keys = Object.keys(spec.params);
-  if (keys.length > 0) {
-    if (keys.every(function (k) {
-      return spec.params[k] == '*' || (spec.params[k] || '').toLowerCase() == (p.params[k] || '').toLowerCase();
-    })) {
-      s |= 1
-    } else {
-      return null
-    }
-  }
-
-  return {
-    i: index,
-    o: spec.i,
-    q: spec.q,
-    s: s,
-  }
-}
-
-/**
- * Get the preferred media types from an Accept header.
- * @public
- */
-
-function preferredMediaTypes(accept, provided) {
-  // RFC 2616 sec 14.2: no header = */*
-  var accepts = parseAccept(accept === undefined ? '*/*' : accept || '');
-
-  if (!provided) {
-    // sorted list of all types
-    return accepts
-      .filter(isQuality)
-      .sort(compareSpecs)
-      .map(getFullType);
-  }
-
-  var priorities = provided.map(function getPriority(type, index) {
-    return getMediaTypePriority(type, accepts, index);
-  });
-
-  // sorted list of accepted types
-  return priorities.filter(isQuality).sort(compareSpecs).map(function getType(priority) {
-    return provided[priorities.indexOf(priority)];
-  });
-}
-
-/**
- * Compare two specs.
- * @private
- */
-
-function compareSpecs(a, b) {
-  return (b.q - a.q) || (b.s - a.s) || (a.o - b.o) || (a.i - b.i) || 0;
-}
-
-/**
- * Get full type string.
- * @private
- */
-
-function getFullType(spec) {
-  return spec.type + '/' + spec.subtype;
-}
-
-/**
- * Check if a spec has any quality.
- * @private
- */
-
-function isQuality(spec) {
-  return spec.q > 0;
-}
-
-/**
- * Count the number of quotes in a string.
- * @private
- */
-
-function quoteCount(string) {
-  var count = 0;
-  var index = 0;
-
-  while ((index = string.indexOf('"', index)) !== -1) {
-    count++;
-    index++;
-  }
-
-  return count;
-}
-
-/**
- * Split a key value pair.
- * @private
- */
-
-function splitKeyValuePair(str) {
-  var index = str.indexOf('=');
-  var key;
-  var val;
-
-  if (index === -1) {
-    key = str;
-  } else {
-    key = str.substr(0, index);
-    val = str.substr(index + 1);
-  }
-
-  return [key, val];
-}
-
-/**
- * Split an Accept header into media types.
- * @private
- */
-
-function splitMediaTypes(accept) {
-  var accepts = accept.split(',');
-
-  for (var i = 1, j = 0; i < accepts.length; i++) {
-    if (quoteCount(accepts[j]) % 2 == 0) {
-      accepts[++j] = accepts[i];
-    } else {
-      accepts[j] += ',' + accepts[i];
-    }
-  }
-
-  // trim accepts
-  accepts.length = j + 1;
-
-  return accepts;
-}
-
-/**
- * Split a string of parameters.
- * @private
- */
-
-function splitParameters(str) {
-  var parameters = str.split(';');
-
-  for (var i = 1, j = 0; i < parameters.length; i++) {
-    if (quoteCount(parameters[j]) % 2 == 0) {
-      parameters[++j] = parameters[i];
-    } else {
-      parameters[j] += ';' + parameters[i];
-    }
-  }
-
-  // trim parameters
-  parameters.length = j + 1;
-
-  for (var i = 0; i < parameters.length; i++) {
-    parameters[i] = parameters[i].trim();
-  }
-
-  return parameters;
-}
+"use strict";module.exports=preferredMediaTypes,module.exports.preferredMediaTypes=preferredMediaTypes;var simpleMediaTypeRegExp=/^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/;function parseAccept(e){for(var r=splitMediaTypes(e),t=0,i=0;t<r.length;t++){var n=parseMediaType(r[t].trim(),t);n&&(r[i++]=n)}return r.length=i,r}function parseMediaType(e,r){var t=simpleMediaTypeRegExp.exec(e);if(!t)return null;var i=Object.create(null),n=1,a=t[2],s=t[1];if(t[3])for(var p=splitParameters(t[3]).map(splitKeyValuePair),u=0;u<p.length;u++){var o=p[u],l=o[0].toLowerCase(),f=o[1],y=f&&'"'===f[0]&&'"'===f[f.length-1]?f.substr(1,f.length-2):f;if("q"===l){n=parseFloat(y);break}i[l]=y}return{type:s,subtype:a,params:i,q:n,i:r}}function getMediaTypePriority(e,r,t){for(var i={o:-1,q:0,s:0},n=0;n<r.length;n++){var a=specify(e,r[n],t);a&&(i.s-a.s||i.q-a.q||i.o-a.o)<0&&(i=a)}return i}function specify(e,r,t){var i=parseMediaType(e),n=0;if(!i)return null;if(r.type.toLowerCase()==i.type.toLowerCase())n|=4;else if("*"!=r.type)return null;if(r.subtype.toLowerCase()==i.subtype.toLowerCase())n|=2;else if("*"!=r.subtype)return null;var a=Object.keys(r.params);if(a.length>0){if(!a.every((function(e){return"*"==r.params[e]||(r.params[e]||"").toLowerCase()==(i.params[e]||"").toLowerCase()})))return null;n|=1}return{i:t,o:r.i,q:r.q,s:n}}function preferredMediaTypes(e,r){var t=parseAccept(void 0===e?"*/*":e||"");if(!r)return t.filter(isQuality).sort(compareSpecs).map(getFullType);var i=r.map((function(e,r){return getMediaTypePriority(e,t,r)}));return i.filter(isQuality).sort(compareSpecs).map((function(e){return r[i.indexOf(e)]}))}function compareSpecs(e,r){return r.q-e.q||r.s-e.s||e.o-r.o||e.i-r.i||0}function getFullType(e){return e.type+"/"+e.subtype}function isQuality(e){return e.q>0}function quoteCount(e){for(var r=0,t=0;-1!==(t=e.indexOf('"',t));)r++,t++;return r}function splitKeyValuePair(e){var r,t,i=e.indexOf("=");return-1===i?r=e:(r=e.substr(0,i),t=e.substr(i+1)),[r,t]}function splitMediaTypes(e){for(var r=e.split(","),t=1,i=0;t<r.length;t++)quoteCount(r[i])%2==0?r[++i]=r[t]:r[i]+=","+r[t];return r.length=i+1,r}function splitParameters(e){for(var r=e.split(";"),t=1,i=0;t<r.length;t++)quoteCount(r[i])%2==0?r[++i]=r[t]:r[i]+=";"+r[t];r.length=i+1;for(t=0;t<r.length;t++)r[t]=r[t].trim();return r}
\ No newline at end of file
index 9abd98f..37710c3 100644 (file)
@@ -4,193 +4,4 @@
  * Copyright(c) 2014 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = onFinished
-module.exports.isFinished = isFinished
-
-/**
- * Module dependencies.
- * @private
- */
-
-var first = require('ee-first')
-
-/**
- * Variables.
- * @private
- */
-
-/* istanbul ignore next */
-var defer = typeof setImmediate === 'function'
-  ? setImmediate
-  : function(fn){ process.nextTick(fn.bind.apply(fn, arguments)) }
-
-/**
- * Invoke callback when the response has finished, useful for
- * cleaning up resources afterwards.
- *
- * @param {object} msg
- * @param {function} listener
- * @return {object}
- * @public
- */
-
-function onFinished(msg, listener) {
-  if (isFinished(msg) !== false) {
-    defer(listener, null, msg)
-    return msg
-  }
-
-  // attach the listener to the message
-  attachListener(msg, listener)
-
-  return msg
-}
-
-/**
- * Determine if message is already finished.
- *
- * @param {object} msg
- * @return {boolean}
- * @public
- */
-
-function isFinished(msg) {
-  var socket = msg.socket
-
-  if (typeof msg.finished === 'boolean') {
-    // OutgoingMessage
-    return Boolean(msg.finished || (socket && !socket.writable))
-  }
-
-  if (typeof msg.complete === 'boolean') {
-    // IncomingMessage
-    return Boolean(msg.upgrade || !socket || !socket.readable || (msg.complete && !msg.readable))
-  }
-
-  // don't know
-  return undefined
-}
-
-/**
- * Attach a finished listener to the message.
- *
- * @param {object} msg
- * @param {function} callback
- * @private
- */
-
-function attachFinishedListener(msg, callback) {
-  var eeMsg
-  var eeSocket
-  var finished = false
-
-  function onFinish(error) {
-    eeMsg.cancel()
-    eeSocket.cancel()
-
-    finished = true
-    callback(error)
-  }
-
-  // finished on first message event
-  eeMsg = eeSocket = first([[msg, 'end', 'finish']], onFinish)
-
-  function onSocket(socket) {
-    // remove listener
-    msg.removeListener('socket', onSocket)
-
-    if (finished) return
-    if (eeMsg !== eeSocket) return
-
-    // finished on first socket event
-    eeSocket = first([[socket, 'error', 'close']], onFinish)
-  }
-
-  if (msg.socket) {
-    // socket already assigned
-    onSocket(msg.socket)
-    return
-  }
-
-  // wait for socket to be assigned
-  msg.on('socket', onSocket)
-
-  if (msg.socket === undefined) {
-    // node.js 0.8 patch
-    patchAssignSocket(msg, onSocket)
-  }
-}
-
-/**
- * Attach the listener to the message.
- *
- * @param {object} msg
- * @return {function}
- * @private
- */
-
-function attachListener(msg, listener) {
-  var attached = msg.__onFinished
-
-  // create a private single listener with queue
-  if (!attached || !attached.queue) {
-    attached = msg.__onFinished = createListener(msg)
-    attachFinishedListener(msg, attached)
-  }
-
-  attached.queue.push(listener)
-}
-
-/**
- * Create listener on message.
- *
- * @param {object} msg
- * @return {function}
- * @private
- */
-
-function createListener(msg) {
-  function listener(err) {
-    if (msg.__onFinished === listener) msg.__onFinished = null
-    if (!listener.queue) return
-
-    var queue = listener.queue
-    listener.queue = null
-
-    for (var i = 0; i < queue.length; i++) {
-      queue[i](err, msg)
-    }
-  }
-
-  listener.queue = []
-
-  return listener
-}
-
-/**
- * Patch ServerResponse.prototype.assignSocket for node.js 0.8.
- *
- * @param {ServerResponse} res
- * @param {function} callback
- * @private
- */
-
-function patchAssignSocket(res, callback) {
-  var assignSocket = res.assignSocket
-
-  if (typeof assignSocket !== 'function') return
-
-  // res.on('socket', callback) is broken in 0.8
-  res.assignSocket = function _assignSocket(socket) {
-    assignSocket.call(this, socket)
-    callback(socket)
-  }
-}
+"use strict";module.exports=onFinished,module.exports.isFinished=isFinished;var first=require("ee-first"),defer="function"==typeof setImmediate?setImmediate:function(e){process.nextTick(e.bind.apply(e,arguments))};function onFinished(e,n){return!1!==isFinished(e)?(defer(n,null,e),e):(attachListener(e,n),e)}function isFinished(e){var n=e.socket;return"boolean"==typeof e.finished?Boolean(e.finished||n&&!n.writable):"boolean"==typeof e.complete?Boolean(e.upgrade||!n||!n.readable||e.complete&&!e.readable):void 0}function attachFinishedListener(e,n){var i,t,o=!1;function s(e){i.cancel(),t.cancel(),o=!0,n(e)}function r(n){e.removeListener("socket",r),o||i===t&&(t=first([[n,"error","close"]],s))}i=t=first([[e,"end","finish"]],s),e.socket?r(e.socket):(e.on("socket",r),void 0===e.socket&&patchAssignSocket(e,r))}function attachListener(e,n){var i=e.__onFinished;i&&i.queue||(i=e.__onFinished=createListener(e),attachFinishedListener(e,i)),i.queue.push(n)}function createListener(e){function n(i){if(e.__onFinished===n&&(e.__onFinished=null),n.queue){var t=n.queue;n.queue=null;for(var o=0;o<t.length;o++)t[o](i,e)}}return n.queue=[],n}function patchAssignSocket(e,n){var i=e.assignSocket;"function"==typeof i&&(e.assignSocket=function(e){i.call(this,e),n(e)})}
\ No newline at end of file
index 7db6375..42f27b4 100755 (executable)
@@ -3,130 +3,4 @@
  * Copyright(c) 2014 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = onHeaders
-
-/**
- * Create a replacement writeHead method.
- *
- * @param {function} prevWriteHead
- * @param {function} listener
- * @private
- */
-
-function createWriteHead (prevWriteHead, listener) {
-  var fired = false
-
-  // return function with core name and argument list
-  return function writeHead (statusCode) {
-    // set headers from arguments
-    var args = setWriteHeadHeaders.apply(this, arguments)
-
-    // fire listener
-    if (!fired) {
-      fired = true
-      listener.call(this)
-
-      // pass-along an updated status code
-      if (typeof args[0] === 'number' && this.statusCode !== args[0]) {
-        args[0] = this.statusCode
-        args.length = 1
-      }
-    }
-
-    return prevWriteHead.apply(this, args)
-  }
-}
-
-/**
- * Execute a listener when a response is about to write headers.
- *
- * @param {object} res
- * @return {function} listener
- * @public
- */
-
-function onHeaders (res, listener) {
-  if (!res) {
-    throw new TypeError('argument res is required')
-  }
-
-  if (typeof listener !== 'function') {
-    throw new TypeError('argument listener must be a function')
-  }
-
-  res.writeHead = createWriteHead(res.writeHead, listener)
-}
-
-/**
- * Set headers contained in array on the response object.
- *
- * @param {object} res
- * @param {array} headers
- * @private
- */
-
-function setHeadersFromArray (res, headers) {
-  for (var i = 0; i < headers.length; i++) {
-    res.setHeader(headers[i][0], headers[i][1])
-  }
-}
-
-/**
- * Set headers contained in object on the response object.
- *
- * @param {object} res
- * @param {object} headers
- * @private
- */
-
-function setHeadersFromObject (res, headers) {
-  var keys = Object.keys(headers)
-  for (var i = 0; i < keys.length; i++) {
-    var k = keys[i]
-    if (k) res.setHeader(k, headers[k])
-  }
-}
-
-/**
- * Set headers and other properties on the response object.
- *
- * @param {number} statusCode
- * @private
- */
-
-function setWriteHeadHeaders (statusCode) {
-  var length = arguments.length
-  var headerIndex = length > 1 && typeof arguments[1] === 'string'
-    ? 2
-    : 1
-
-  var headers = length >= headerIndex + 1
-    ? arguments[headerIndex]
-    : undefined
-
-  this.statusCode = statusCode
-
-  if (Array.isArray(headers)) {
-    // handle array case
-    setHeadersFromArray(this, headers)
-  } else if (headers) {
-    // handle object case
-    setHeadersFromObject(this, headers)
-  }
-
-  // copy leading arguments
-  var args = new Array(Math.min(length, headerIndex))
-  for (var i = 0; i < args.length; i++) {
-    args[i] = arguments[i]
-  }
-
-  return args
-}
+"use strict";function createWriteHead(e,r){var t=!1;return function(a){var s=setWriteHeadHeaders.apply(this,arguments);return t||(t=!0,r.call(this),"number"==typeof s[0]&&this.statusCode!==s[0]&&(s[0]=this.statusCode,s.length=1)),e.apply(this,s)}}function onHeaders(e,r){if(!e)throw new TypeError("argument res is required");if("function"!=typeof r)throw new TypeError("argument listener must be a function");e.writeHead=createWriteHead(e.writeHead,r)}function setHeadersFromArray(e,r){for(var t=0;t<r.length;t++)e.setHeader(r[t][0],r[t][1])}function setHeadersFromObject(e,r){for(var t=Object.keys(r),a=0;a<t.length;a++){var s=t[a];s&&e.setHeader(s,r[s])}}function setWriteHeadHeaders(e){var r=arguments.length,t=r>1&&"string"==typeof arguments[1]?2:1,a=r>=t+1?arguments[t]:void 0;this.statusCode=e,Array.isArray(a)?setHeadersFromArray(this,a):a&&setHeadersFromObject(this,a);for(var s=new Array(Math.min(r,t)),n=0;n<s.length;n++)s[n]=arguments[n];return s}module.exports=onHeaders;
\ No newline at end of file
index 6a72a4c..e218f0d 100644 (file)
@@ -1,57 +1 @@
-'use strict';
-const pTry = require('p-try');
-
-const pLimit = concurrency => {
-       if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) {
-               return Promise.reject(new TypeError('Expected `concurrency` to be a number from 1 and up'));
-       }
-
-       const queue = [];
-       let activeCount = 0;
-
-       const next = () => {
-               activeCount--;
-
-               if (queue.length > 0) {
-                       queue.shift()();
-               }
-       };
-
-       const run = (fn, resolve, ...args) => {
-               activeCount++;
-
-               const result = pTry(fn, ...args);
-
-               resolve(result);
-
-               result.then(next, next);
-       };
-
-       const enqueue = (fn, resolve, ...args) => {
-               if (activeCount < concurrency) {
-                       run(fn, resolve, ...args);
-               } else {
-                       queue.push(run.bind(null, fn, resolve, ...args));
-               }
-       };
-
-       const generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args));
-       Object.defineProperties(generator, {
-               activeCount: {
-                       get: () => activeCount
-               },
-               pendingCount: {
-                       get: () => queue.length
-               },
-               clearQueue: {
-                       value: () => {
-                               queue.length = 0;
-                       }
-               }
-       });
-
-       return generator;
-};
-
-module.exports = pLimit;
-module.exports.default = pLimit;
+"use strict";const pTry=require("p-try"),pLimit=e=>{if(!Number.isInteger(e)&&e!==1/0||!(e>0))return Promise.reject(new TypeError("Expected `concurrency` to be a number from 1 and up"));const t=[];let r=0;const n=()=>{r--,t.length>0&&t.shift()()},i=(e,t,...i)=>{r++;const u=pTry(e,...i);t(u),u.then(n,n)},u=(n,...u)=>new Promise((o=>((n,u,...o)=>{r<e?i(n,u,...o):t.push(i.bind(null,n,u,...o))})(n,o,...u)));return Object.defineProperties(u,{activeCount:{get:()=>r},pendingCount:{get:()=>t.length},clearQueue:{value:()=>{t.length=0}}}),u};module.exports=pLimit,module.exports.default=pLimit;
\ No newline at end of file
index 4bd08aa..4e79c9d 100644 (file)
@@ -1,34 +1 @@
-'use strict';
-const pLimit = require('p-limit');
-
-class EndError extends Error {
-       constructor(value) {
-               super();
-               this.value = value;
-       }
-}
-
-// The input can also be a promise, so we `Promise.resolve()` it
-const testElement = (el, tester) => Promise.resolve(el).then(tester);
-
-// The input can also be a promise, so we `Promise.all()` them both
-const finder = el => Promise.all(el).then(val => val[1] === true && Promise.reject(new EndError(val[0])));
-
-module.exports = (iterable, tester, opts) => {
-       opts = Object.assign({
-               concurrency: Infinity,
-               preserveOrder: true
-       }, opts);
-
-       const limit = pLimit(opts.concurrency);
-
-       // Start all the promises concurrently with optional limit
-       const items = [...iterable].map(el => [el, limit(testElement, el, tester)]);
-
-       // Check the promises either serially or concurrently
-       const checkLimit = pLimit(opts.preserveOrder ? 1 : Infinity);
-
-       return Promise.all(items.map(el => checkLimit(finder, el)))
-               .then(() => {})
-               .catch(err => err instanceof EndError ? err.value : Promise.reject(err));
-};
+"use strict";const pLimit=require("p-limit");class EndError extends Error{constructor(e){super(),this.value=e}}const testElement=(e,r)=>Promise.resolve(e).then(r),finder=e=>Promise.all(e).then((e=>!0===e[1]&&Promise.reject(new EndError(e[0]))));module.exports=(e,r,t)=>{t=Object.assign({concurrency:1/0,preserveOrder:!0},t);const s=pLimit(t.concurrency),n=[...e].map((e=>[e,s(testElement,e,r)])),i=pLimit(t.preserveOrder?1:1/0);return Promise.all(n.map((e=>i(finder,e)))).then((()=>{})).catch((e=>e instanceof EndError?e.value:Promise.reject(e)))};
\ No newline at end of file
index db858da..0924755 100644 (file)
@@ -1,9 +1 @@
-'use strict';
-
-const pTry = (fn, ...arguments_) => new Promise(resolve => {
-       resolve(fn(...arguments_));
-});
-
-module.exports = pTry;
-// TODO: remove this in the next major version
-module.exports.default = pTry;
+"use strict";const pTry=(e,...r)=>new Promise((o=>{o(e(...r))}));module.exports=pTry,module.exports.default=pTry;
\ No newline at end of file
index e0b366e..bcc2a23 100644 (file)
@@ -1,37 +1 @@
-/**
- * Compiles a querystring
- * Returns string representation of the object
- *
- * @param {Object}
- * @api private
- */
-
-exports.encode = function (obj) {
-  var str = '';
-
-  for (var i in obj) {
-    if (obj.hasOwnProperty(i)) {
-      if (str.length) str += '&';
-      str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
-    }
-  }
-
-  return str;
-};
-
-/**
- * Parses a simple querystring into an object
- *
- * @param {String} qs
- * @api private
- */
-
-exports.decode = function(qs){
-  var qry = {};
-  var pairs = qs.split('&');
-  for (var i = 0, l = pairs.length; i < l; i++) {
-    var pair = pairs[i].split('=');
-    qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
-  }
-  return qry;
-};
+exports.encode=function(e){var n="";for(var o in e)e.hasOwnProperty(o)&&(n.length&&(n+="&"),n+=encodeURIComponent(o)+"="+encodeURIComponent(e[o]));return n},exports.decode=function(e){for(var n={},o=e.split("&"),t=0,r=o.length;t<r;t++){var d=o[t].split("=");n[decodeURIComponent(d[0])]=decodeURIComponent(d[1])}return n};
\ No newline at end of file
index 2ccb925..f06681e 100644 (file)
@@ -1,27 +1 @@
-var assert = require('better-assert');
-var expect = require('expect.js');
-var util = require('./index.js');
-
-describe('querystring test suite', function(){
-       it('should parse a querystring and return an object', function () {
-               
-               // Single assignment
-               var queryObj = util.decode("foo=bar");
-               expect(queryObj.foo).to.be("bar");
-               
-               // Multiple assignments
-               queryObj = util.decode("france=paris&germany=berlin");
-               expect(queryObj.france).to.be("paris");
-               expect(queryObj.germany).to.be("berlin");
-               
-               // Assignments containing non-alphanumeric characters
-               queryObj = util.decode("india=new%20delhi");
-               expect(queryObj.india).to.be("new delhi");
-       });
-       
-       it('should construct a query string from an object', function () {
-               expect(util.encode({ a: 'b' })).to.be('a=b');
-               expect(util.encode({ a: 'b', c: 'd' })).to.be('a=b&c=d');
-               expect(util.encode({ a: 'b', c: 'tobi rocks' })).to.be('a=b&c=tobi%20rocks');
-       });
-});
+var assert=require("better-assert"),expect=require("expect.js"),util=require("./index.js");describe("querystring test suite",(function(){it("should parse a querystring and return an object",(function(){var e=util.decode("foo=bar");expect(e.foo).to.be("bar"),e=util.decode("france=paris&germany=berlin"),expect(e.france).to.be("paris"),expect(e.germany).to.be("berlin"),e=util.decode("india=new%20delhi"),expect(e.india).to.be("new delhi")})),it("should construct a query string from an object",(function(){expect(util.encode({a:"b"})).to.be("a=b"),expect(util.encode({a:"b",c:"d"})).to.be("a=b&c=d"),expect(util.encode({a:"b",c:"tobi rocks"})).to.be("a=b&c=tobi%20rocks")}))}));
\ No newline at end of file
index d4704b4..a5282b0 100644 (file)
@@ -1,68 +1 @@
-/**
- * Parses an URI
- *
- * @author Steven Levithan <stevenlevithan.com> (MIT license)
- * @api private
- */
-
-var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
-
-var parts = [
-    'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
-];
-
-module.exports = function parseuri(str) {
-    var src = str,
-        b = str.indexOf('['),
-        e = str.indexOf(']');
-
-    if (b != -1 && e != -1) {
-        str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
-    }
-
-    var m = re.exec(str || ''),
-        uri = {},
-        i = 14;
-
-    while (i--) {
-        uri[parts[i]] = m[i] || '';
-    }
-
-    if (b != -1 && e != -1) {
-        uri.source = src;
-        uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
-        uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
-        uri.ipv6uri = true;
-    }
-
-    uri.pathNames = pathNames(uri, uri['path']);
-    uri.queryKey = queryKey(uri, uri['query']);
-
-    return uri;
-};
-
-function pathNames(obj, path) {
-    var regx = /\/{2,9}/g,
-        names = path.replace(regx, "/").split("/");
-
-    if (path.substr(0, 1) == '/' || path.length === 0) {
-        names.splice(0, 1);
-    }
-    if (path.substr(path.length - 1, 1) == '/') {
-        names.splice(names.length - 1, 1);
-    }
-
-    return names;
-}
-
-function queryKey(uri, query) {
-    var data = {};
-
-    query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
-        if ($1) {
-            data[$1] = $2;
-        }
-    });
-
-    return data;
-}
+var re=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,parts=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function pathNames(e,r){var t=r.replace(/\/{2,9}/g,"/").split("/");return"/"!=r.substr(0,1)&&0!==r.length||t.splice(0,1),"/"==r.substr(r.length-1,1)&&t.splice(t.length-1,1),t}function queryKey(e,r){var t={};return r.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(e,r,s){r&&(t[r]=s)})),t}module.exports=function(e){var r=e,t=e.indexOf("["),s=e.indexOf("]");-1!=t&&-1!=s&&(e=e.substring(0,t)+e.substring(t,s).replace(/:/g,";")+e.substring(s,e.length));for(var a=re.exec(e||""),u={},n=14;n--;)u[parts[n]]=a[n]||"";return-1!=t&&-1!=s&&(u.source=r,u.host=u.host.substring(1,u.host.length-1).replace(/;/g,":"),u.authority=u.authority.replace("[","").replace("]","").replace(/;/g,":"),u.ipv6uri=!0),u.pathNames=pathNames(u,u.path),u.queryKey=queryKey(u,u.query),u};
\ No newline at end of file
index be447df..e8cb52f 100644 (file)
@@ -1,54 +1 @@
-var assert = require('better-assert');
-var expect = require('expect.js');
-var parseuri = require('./index.js');
-
-describe('my suite', function(){
-       it('should parse an uri', function () {
-    var http = parseuri('http://google.com')
-      , https = parseuri('https://www.google.com:80')
-      , query = parseuri('google.com:8080/foo/bar?foo=bar')
-      , localhost = parseuri('localhost:8080')
-      , ipv6 = parseuri('2001:0db8:85a3:0042:1000:8a2e:0370:7334')
-      , ipv6short = parseuri('2001:db8:85a3:42:1000:8a2e:370:7334')
-      , ipv6port = parseuri('2001:db8:85a3:42:1000:8a2e:370:7334:80')
-      , ipv6abbrev = parseuri('2001::7334:a:80')
-      , ipv6http = parseuri('http://[2001::7334:a]:80')
-      , ipv6query = parseuri('http://[2001::7334:a]:80/foo/bar?foo=bar')
-
-    expect(http.protocol).to.be('http');
-    expect(http.port).to.be('');
-    expect(http.host).to.be('google.com');
-    expect(https.protocol).to.be('https');
-    expect(https.port).to.be('80');
-    expect(https.host).to.be('www.google.com');
-    expect(query.port).to.be('8080');
-    expect(query.query).to.be('foo=bar');
-    expect(query.path).to.be('/foo/bar');
-    expect(query.relative).to.be('/foo/bar?foo=bar');
-    expect(query.queryKey.foo).to.be('bar');
-    expect(query.pathNames[0]).to.be('foo');
-    expect(query.pathNames[1]).to.be('bar');
-    expect(localhost.protocol).to.be('');
-    expect(localhost.host).to.be('localhost');
-    expect(localhost.port).to.be('8080');
-    expect(ipv6.protocol).to.be('');
-    expect(ipv6.host).to.be('2001:0db8:85a3:0042:1000:8a2e:0370:7334');
-    expect(ipv6.port).to.be('');
-    expect(ipv6short.protocol).to.be('');
-    expect(ipv6short.host).to.be('2001:db8:85a3:42:1000:8a2e:370:7334');
-    expect(ipv6short.port).to.be('');
-    expect(ipv6port.protocol).to.be('');
-    expect(ipv6port.host).to.be('2001:db8:85a3:42:1000:8a2e:370:7334');
-    expect(ipv6port.port).to.be('80');
-    expect(ipv6abbrev.protocol).to.be('');
-    expect(ipv6abbrev.host).to.be('2001::7334:a:80');
-    expect(ipv6abbrev.port).to.be('');
-    expect(ipv6http.protocol).to.be('http');
-    expect(ipv6http.port).to.be('80');
-    expect(ipv6http.host).to.be('2001::7334:a');
-    expect(ipv6query.protocol).to.be('http');
-    expect(ipv6query.port).to.be('80');
-    expect(ipv6query.host).to.be('2001::7334:a');
-    expect(ipv6query.relative).to.be('/foo/bar?foo=bar');
-  });
-});
+var assert=require("better-assert"),expect=require("expect.js"),parseuri=require("./index.js");describe("my suite",(function(){it("should parse an uri",(function(){var e=parseuri("http://google.com"),t=parseuri("https://www.google.com:80"),o=parseuri("google.com:8080/foo/bar?foo=bar"),p=parseuri("localhost:8080"),r=parseuri("2001:0db8:85a3:0042:1000:8a2e:0370:7334"),a=parseuri("2001:db8:85a3:42:1000:8a2e:370:7334"),c=parseuri("2001:db8:85a3:42:1000:8a2e:370:7334:80"),b=parseuri("2001::7334:a:80"),x=parseuri("http://[2001::7334:a]:80"),s=parseuri("http://[2001::7334:a]:80/foo/bar?foo=bar");expect(e.protocol).to.be("http"),expect(e.port).to.be(""),expect(e.host).to.be("google.com"),expect(t.protocol).to.be("https"),expect(t.port).to.be("80"),expect(t.host).to.be("www.google.com"),expect(o.port).to.be("8080"),expect(o.query).to.be("foo=bar"),expect(o.path).to.be("/foo/bar"),expect(o.relative).to.be("/foo/bar?foo=bar"),expect(o.queryKey.foo).to.be("bar"),expect(o.pathNames[0]).to.be("foo"),expect(o.pathNames[1]).to.be("bar"),expect(p.protocol).to.be(""),expect(p.host).to.be("localhost"),expect(p.port).to.be("8080"),expect(r.protocol).to.be(""),expect(r.host).to.be("2001:0db8:85a3:0042:1000:8a2e:0370:7334"),expect(r.port).to.be(""),expect(a.protocol).to.be(""),expect(a.host).to.be("2001:db8:85a3:42:1000:8a2e:370:7334"),expect(a.port).to.be(""),expect(c.protocol).to.be(""),expect(c.host).to.be("2001:db8:85a3:42:1000:8a2e:370:7334"),expect(c.port).to.be("80"),expect(b.protocol).to.be(""),expect(b.host).to.be("2001::7334:a:80"),expect(b.port).to.be(""),expect(x.protocol).to.be("http"),expect(x.port).to.be("80"),expect(x.host).to.be("2001::7334:a"),expect(s.protocol).to.be("http"),expect(s.port).to.be("80"),expect(s.host).to.be("2001::7334:a"),expect(s.relative).to.be("/foo/bar?foo=bar")}))}));
\ No newline at end of file
index ece7223..49831c8 100644 (file)
@@ -4,155 +4,4 @@
  * Copyright(c) 2014-2017 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module dependencies.
- * @private
- */
-
-var url = require('url')
-var parse = url.parse
-var Url = url.Url
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = parseurl
-module.exports.original = originalurl
-
-/**
- * Parse the `req` url with memoization.
- *
- * @param {ServerRequest} req
- * @return {Object}
- * @public
- */
-
-function parseurl (req) {
-  var url = req.url
-
-  if (url === undefined) {
-    // URL is undefined
-    return undefined
-  }
-
-  var parsed = req._parsedUrl
-
-  if (fresh(url, parsed)) {
-    // Return cached URL parse
-    return parsed
-  }
-
-  // Parse the URL
-  parsed = fastparse(url)
-  parsed._raw = url
-
-  return (req._parsedUrl = parsed)
-};
-
-/**
- * Parse the `req` original url with fallback and memoization.
- *
- * @param {ServerRequest} req
- * @return {Object}
- * @public
- */
-
-function originalurl (req) {
-  var url = req.originalUrl
-
-  if (typeof url !== 'string') {
-    // Fallback
-    return parseurl(req)
-  }
-
-  var parsed = req._parsedOriginalUrl
-
-  if (fresh(url, parsed)) {
-    // Return cached URL parse
-    return parsed
-  }
-
-  // Parse the URL
-  parsed = fastparse(url)
-  parsed._raw = url
-
-  return (req._parsedOriginalUrl = parsed)
-};
-
-/**
- * Parse the `str` url with fast-path short-cut.
- *
- * @param {string} str
- * @return {Object}
- * @private
- */
-
-function fastparse (str) {
-  if (typeof str !== 'string' || str.charCodeAt(0) !== 0x2f /* / */) {
-    return parse(str)
-  }
-
-  var pathname = str
-  var query = null
-  var search = null
-
-  // This takes the regexp from https://github.com/joyent/node/pull/7878
-  // Which is /^(\/[^?#\s]*)(\?[^#\s]*)?$/
-  // And unrolls it into a for loop
-  for (var i = 1; i < str.length; i++) {
-    switch (str.charCodeAt(i)) {
-      case 0x3f: /* ?  */
-        if (search === null) {
-          pathname = str.substring(0, i)
-          query = str.substring(i + 1)
-          search = str.substring(i)
-        }
-        break
-      case 0x09: /* \t */
-      case 0x0a: /* \n */
-      case 0x0c: /* \f */
-      case 0x0d: /* \r */
-      case 0x20: /*    */
-      case 0x23: /* #  */
-      case 0xa0:
-      case 0xfeff:
-        return parse(str)
-    }
-  }
-
-  var url = Url !== undefined
-    ? new Url()
-    : {}
-
-  url.path = str
-  url.href = str
-  url.pathname = pathname
-
-  if (search !== null) {
-    url.query = query
-    url.search = search
-  }
-
-  return url
-}
-
-/**
- * Determine if parsed is still fresh for url.
- *
- * @param {string} url
- * @param {object} parsedUrl
- * @return {boolean}
- * @private
- */
-
-function fresh (url, parsedUrl) {
-  return typeof parsedUrl === 'object' &&
-    parsedUrl !== null &&
-    (Url === undefined || parsedUrl instanceof Url) &&
-    parsedUrl._raw === url
-}
+"use strict";var url=require("url"),parse=url.parse,Url=url.Url;function parseurl(r){var e=r.url;if(void 0!==e){var a=r._parsedUrl;return fresh(e,a)?a:((a=fastparse(e))._raw=e,r._parsedUrl=a)}}function originalurl(r){var e=r.originalUrl;if("string"!=typeof e)return parseurl(r);var a=r._parsedOriginalUrl;return fresh(e,a)?a:((a=fastparse(e))._raw=e,r._parsedOriginalUrl=a)}function fastparse(r){if("string"!=typeof r||47!==r.charCodeAt(0))return parse(r);for(var e=r,a=null,s=null,l=1;l<r.length;l++)switch(r.charCodeAt(l)){case 63:null===s&&(e=r.substring(0,l),a=r.substring(l+1),s=r.substring(l));break;case 9:case 10:case 12:case 13:case 32:case 35:case 160:case 65279:return parse(r)}var n=void 0!==Url?new Url:{};return n.path=r,n.href=r,n.pathname=e,null!==s&&(n.query=a,n.search=s),n}function fresh(r,e){return"object"==typeof e&&null!==e&&(void 0===Url||e instanceof Url)&&e._raw===r}module.exports=parseurl,module.exports.original=originalurl;
\ No newline at end of file
index 16ae60a..c461580 100644 (file)
@@ -1,17 +1 @@
-'use strict';
-const fs = require('fs');
-
-module.exports = fp => new Promise(resolve => {
-       fs.access(fp, err => {
-               resolve(!err);
-       });
-});
-
-module.exports.sync = fp => {
-       try {
-               fs.accessSync(fp);
-               return true;
-       } catch (err) {
-               return false;
-       }
-};
+"use strict";const fs=require("fs");module.exports=s=>new Promise((e=>{fs.access(s,(s=>{e(!s)}))})),module.exports.sync=s=>{try{return fs.accessSync(s),!0}catch(s){return!1}};
\ No newline at end of file
index 500d1da..9a74b1a 100644 (file)
@@ -1,129 +1 @@
-/**
- * Expose `pathtoRegexp`.
- */
-
-module.exports = pathtoRegexp;
-
-/**
- * Match matching groups in a regular expression.
- */
-var MATCHING_GROUP_REGEXP = /\((?!\?)/g;
-
-/**
- * Normalize the given path string,
- * returning a regular expression.
- *
- * An empty array should be passed,
- * which will contain the placeholder
- * key names. For example "/user/:id" will
- * then contain ["id"].
- *
- * @param  {String|RegExp|Array} path
- * @param  {Array} keys
- * @param  {Object} options
- * @return {RegExp}
- * @api private
- */
-
-function pathtoRegexp(path, keys, options) {
-  options = options || {};
-  keys = keys || [];
-  var strict = options.strict;
-  var end = options.end !== false;
-  var flags = options.sensitive ? '' : 'i';
-  var extraOffset = 0;
-  var keysOffset = keys.length;
-  var i = 0;
-  var name = 0;
-  var m;
-
-  if (path instanceof RegExp) {
-    while (m = MATCHING_GROUP_REGEXP.exec(path.source)) {
-      keys.push({
-        name: name++,
-        optional: false,
-        offset: m.index
-      });
-    }
-
-    return path;
-  }
-
-  if (Array.isArray(path)) {
-    // Map array parts into regexps and return their source. We also pass
-    // the same keys and options instance into every generation to get
-    // consistent matching groups before we join the sources together.
-    path = path.map(function (value) {
-      return pathtoRegexp(value, keys, options).source;
-    });
-
-    return new RegExp('(?:' + path.join('|') + ')', flags);
-  }
-
-  path = ('^' + path + (strict ? '' : path[path.length - 1] === '/' ? '?' : '/?'))
-    .replace(/\/\(/g, '/(?:')
-    .replace(/([\/\.])/g, '\\$1')
-    .replace(/(\\\/)?(\\\.)?:(\w+)(\(.*?\))?(\*)?(\?)?/g, function (match, slash, format, key, capture, star, optional, offset) {
-      slash = slash || '';
-      format = format || '';
-      capture = capture || '([^\\/' + format + ']+?)';
-      optional = optional || '';
-
-      keys.push({
-        name: key,
-        optional: !!optional,
-        offset: offset + extraOffset
-      });
-
-      var result = ''
-        + (optional ? '' : slash)
-        + '(?:'
-        + format + (optional ? slash : '') + capture
-        + (star ? '((?:[\\/' + format + '].+?)?)' : '')
-        + ')'
-        + optional;
-
-      extraOffset += result.length - match.length;
-
-      return result;
-    })
-    .replace(/\*/g, function (star, index) {
-      var len = keys.length
-
-      while (len-- > keysOffset && keys[len].offset > index) {
-        keys[len].offset += 3; // Replacement length minus asterisk length.
-      }
-
-      return '(.*)';
-    });
-
-  // This is a workaround for handling unnamed matching groups.
-  while (m = MATCHING_GROUP_REGEXP.exec(path)) {
-    var escapeCount = 0;
-    var index = m.index;
-
-    while (path.charAt(--index) === '\\') {
-      escapeCount++;
-    }
-
-    // It's possible to escape the bracket.
-    if (escapeCount % 2 === 1) {
-      continue;
-    }
-
-    if (keysOffset + i === keys.length || keys[keysOffset + i].offset > m.index) {
-      keys.splice(keysOffset + i, 0, {
-        name: name++, // Unnamed matching groups must be consistently linear.
-        optional: false,
-        offset: m.index
-      });
-    }
-
-    i++;
-  }
-
-  // If the path is non-ending, match until the end or a slash.
-  path += (end ? '$' : (path[path.length - 1] === '/' ? '' : '(?=\\/|$)'));
-
-  return new RegExp(path, flags);
-};
+module.exports=pathtoRegexp;var MATCHING_GROUP_REGEXP=/\((?!\?)/g;function pathtoRegexp(e,n,t){n=n||[];var r,o=(t=t||{}).strict,a=!1!==t.end,f=t.sensitive?"":"i",i=0,p=n.length,g=0,s=0;if(e instanceof RegExp){for(;r=MATCHING_GROUP_REGEXP.exec(e.source);)n.push({name:s++,optional:!1,offset:r.index});return e}if(Array.isArray(e))return e=e.map((function(e){return pathtoRegexp(e,n,t).source})),new RegExp("(?:"+e.join("|")+")",f);for(e=("^"+e+(o?"":"/"===e[e.length-1]?"?":"/?")).replace(/\/\(/g,"/(?:").replace(/([\/\.])/g,"\\$1").replace(/(\\\/)?(\\\.)?:(\w+)(\(.*?\))?(\*)?(\?)?/g,(function(e,t,r,o,a,f,p,g){t=t||"",r=r||"",a=a||"([^\\/"+r+"]+?)",p=p||"",n.push({name:o,optional:!!p,offset:g+i});var s=(p?"":t)+"(?:"+r+(p?t:"")+a+(f?"((?:[\\/"+r+"].+?)?)":"")+")"+p;return i+=s.length-e.length,s})).replace(/\*/g,(function(e,t){for(var r=n.length;r-- >p&&n[r].offset>t;)n[r].offset+=3;return"(.*)"}));r=MATCHING_GROUP_REGEXP.exec(e);){for(var c=0,l=r.index;"\\"===e.charAt(--l);)c++;c%2!=1&&((p+g===n.length||n[p+g].offset>r.index)&&n.splice(p+g,0,{name:s++,optional:!1,offset:r.index}),g++)}return e+=a?"$":"/"===e[e.length-1]?"":"(?=\\/|$)",new RegExp(e,f)}
\ No newline at end of file
index 379b329..5e85765 100644 (file)
-(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.png = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
-(function (Buffer){
-'use strict';
-
-var interlaceUtils = require('./interlace');
-
-var pixelBppMapper = [
-  // 0 - dummy entry
-  function() {},
-
-  // 1 - L
-  // 0: 0, 1: 0, 2: 0, 3: 0xff
-  function(pxData, data, pxPos, rawPos) {
-    if (rawPos === data.length) {
-      throw new Error('Ran out of data');
-    }
-
-    var pixel = data[rawPos];
-    pxData[pxPos] = pixel;
-    pxData[pxPos + 1] = pixel;
-    pxData[pxPos + 2] = pixel;
-    pxData[pxPos + 3] = 0xff;
-  },
-
-  // 2 - LA
-  // 0: 0, 1: 0, 2: 0, 3: 1
-  function(pxData, data, pxPos, rawPos) {
-    if (rawPos + 1 >= data.length) {
-      throw new Error('Ran out of data');
-    }
-
-    var pixel = data[rawPos];
-    pxData[pxPos] = pixel;
-    pxData[pxPos + 1] = pixel;
-    pxData[pxPos + 2] = pixel;
-    pxData[pxPos + 3] = data[rawPos + 1];
-  },
-
-  // 3 - RGB
-  // 0: 0, 1: 1, 2: 2, 3: 0xff
-  function(pxData, data, pxPos, rawPos) {
-    if (rawPos + 2 >= data.length) {
-      throw new Error('Ran out of data');
-    }
-
-    pxData[pxPos] = data[rawPos];
-    pxData[pxPos + 1] = data[rawPos + 1];
-    pxData[pxPos + 2] = data[rawPos + 2];
-    pxData[pxPos + 3] = 0xff;
-  },
-
-  // 4 - RGBA
-  // 0: 0, 1: 1, 2: 2, 3: 3
-  function(pxData, data, pxPos, rawPos) {
-    if (rawPos + 3 >= data.length) {
-      throw new Error('Ran out of data');
-    }
-
-    pxData[pxPos] = data[rawPos];
-    pxData[pxPos + 1] = data[rawPos + 1];
-    pxData[pxPos + 2] = data[rawPos + 2];
-    pxData[pxPos + 3] = data[rawPos + 3];
-  }
-];
-
-var pixelBppCustomMapper = [
-  // 0 - dummy entry
-  function() {},
-
-  // 1 - L
-  // 0: 0, 1: 0, 2: 0, 3: 0xff
-  function(pxData, pixelData, pxPos, maxBit) {
-    var pixel = pixelData[0];
-    pxData[pxPos] = pixel;
-    pxData[pxPos + 1] = pixel;
-    pxData[pxPos + 2] = pixel;
-    pxData[pxPos + 3] = maxBit;
-  },
-
-  // 2 - LA
-  // 0: 0, 1: 0, 2: 0, 3: 1
-  function(pxData, pixelData, pxPos) {
-    var pixel = pixelData[0];
-    pxData[pxPos] = pixel;
-    pxData[pxPos + 1] = pixel;
-    pxData[pxPos + 2] = pixel;
-    pxData[pxPos + 3] = pixelData[1];
-  },
-
-  // 3 - RGB
-  // 0: 0, 1: 1, 2: 2, 3: 0xff
-  function(pxData, pixelData, pxPos, maxBit) {
-    pxData[pxPos] = pixelData[0];
-    pxData[pxPos + 1] = pixelData[1];
-    pxData[pxPos + 2] = pixelData[2];
-    pxData[pxPos + 3] = maxBit;
-  },
-
-  // 4 - RGBA
-  // 0: 0, 1: 1, 2: 2, 3: 3
-  function(pxData, pixelData, pxPos) {
-    pxData[pxPos] = pixelData[0];
-    pxData[pxPos + 1] = pixelData[1];
-    pxData[pxPos + 2] = pixelData[2];
-    pxData[pxPos + 3] = pixelData[3];
-  }
-];
-
-function bitRetriever(data, depth) {
-
-  var leftOver = [];
-  var i = 0;
-
-  function split() {
-    if (i === data.length) {
-      throw new Error('Ran out of data');
-    }
-    var byte = data[i];
-    i++;
-    var byte8, byte7, byte6, byte5, byte4, byte3, byte2, byte1;
-    switch (depth) {
-      default:
-        throw new Error('unrecognised depth');
-      case 16:
-        byte2 = data[i];
-        i++;
-        leftOver.push(((byte << 8) + byte2));
-        break;
-      case 4:
-        byte2 = byte & 0x0f;
-        byte1 = byte >> 4;
-        leftOver.push(byte1, byte2);
-        break;
-      case 2:
-        byte4 = byte & 3;
-        byte3 = byte >> 2 & 3;
-        byte2 = byte >> 4 & 3;
-        byte1 = byte >> 6 & 3;
-        leftOver.push(byte1, byte2, byte3, byte4);
-        break;
-      case 1:
-        byte8 = byte & 1;
-        byte7 = byte >> 1 & 1;
-        byte6 = byte >> 2 & 1;
-        byte5 = byte >> 3 & 1;
-        byte4 = byte >> 4 & 1;
-        byte3 = byte >> 5 & 1;
-        byte2 = byte >> 6 & 1;
-        byte1 = byte >> 7 & 1;
-        leftOver.push(byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8);
-        break;
-    }
-  }
-
-  return {
-    get: function(count) {
-      while (leftOver.length < count) {
-        split();
-      }
-      var returner = leftOver.slice(0, count);
-      leftOver = leftOver.slice(count);
-      return returner;
-    },
-    resetAfterLine: function() {
-      leftOver.length = 0;
-    },
-    end: function() {
-      if (i !== data.length) {
-        throw new Error('extra data found');
-      }
-    }
-  };
-}
-
-function mapImage8Bit(image, pxData, getPxPos, bpp, data, rawPos) { // eslint-disable-line max-params
-  var imageWidth = image.width;
-  var imageHeight = image.height;
-  var imagePass = image.index;
-  for (var y = 0; y < imageHeight; y++) {
-    for (var x = 0; x < imageWidth; x++) {
-      var pxPos = getPxPos(x, y, imagePass);
-      pixelBppMapper[bpp](pxData, data, pxPos, rawPos);
-      rawPos += bpp; //eslint-disable-line no-param-reassign
-    }
-  }
-  return rawPos;
-}
-
-function mapImageCustomBit(image, pxData, getPxPos, bpp, bits, maxBit) { // eslint-disable-line max-params
-  var imageWidth = image.width;
-  var imageHeight = image.height;
-  var imagePass = image.index;
-  for (var y = 0; y < imageHeight; y++) {
-    for (var x = 0; x < imageWidth; x++) {
-      var pixelData = bits.get(bpp);
-      var pxPos = getPxPos(x, y, imagePass);
-      pixelBppCustomMapper[bpp](pxData, pixelData, pxPos, maxBit);
-    }
-    bits.resetAfterLine();
-  }
-}
-
-exports.dataToBitMap = function(data, bitmapInfo) {
-
-  var width = bitmapInfo.width;
-  var height = bitmapInfo.height;
-  var depth = bitmapInfo.depth;
-  var bpp = bitmapInfo.bpp;
-  var interlace = bitmapInfo.interlace;
-
-  if (depth !== 8) {
-    var bits = bitRetriever(data, depth);
-  }
-  var pxData;
-  if (depth <= 8) {
-    pxData = new Buffer(width * height * 4);
-  }
-  else {
-    pxData = new Uint16Array(width * height * 4);
-  }
-  var maxBit = Math.pow(2, depth) - 1;
-  var rawPos = 0;
-  var images;
-  var getPxPos;
-
-  if (interlace) {
-    images = interlaceUtils.getImagePasses(width, height);
-    getPxPos = interlaceUtils.getInterlaceIterator(width, height);
-  }
-  else {
-    var nonInterlacedPxPos = 0;
-    getPxPos = function() {
-      var returner = nonInterlacedPxPos;
-      nonInterlacedPxPos += 4;
-      return returner;
-    };
-    images = [{ width: width, height: height }];
-  }
-
-  for (var imageIndex = 0; imageIndex < images.length; imageIndex++) {
-    if (depth === 8) {
-      rawPos = mapImage8Bit(images[imageIndex], pxData, getPxPos, bpp, data, rawPos);
-    }
-    else {
-      mapImageCustomBit(images[imageIndex], pxData, getPxPos, bpp, bits, maxBit);
-    }
-  }
-  if (depth === 8) {
-    if (rawPos !== data.length) {
-      throw new Error('extra data found');
-    }
-  }
-  else {
-    bits.end();
-  }
-
-  return pxData;
-};
-
-}).call(this,require("buffer").Buffer)
-},{"./interlace":11,"buffer":32}],2:[function(require,module,exports){
-(function (Buffer){
-'use strict';
-
-var constants = require('./constants');
-
-module.exports = function(dataIn, width, height, options) {
-  var outHasAlpha = [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf(options.colorType) !== -1;
-  if (options.colorType === options.inputColorType) {
-    var bigEndian = (function() {
-      var buffer = new ArrayBuffer(2);
-      new DataView(buffer).setInt16(0, 256, true /* littleEndian */);
-      // Int16Array uses the platform's endianness.
-      return new Int16Array(buffer)[0] !== 256;
-    })();
-    // If no need to convert to grayscale and alpha is present/absent in both, take a fast route
-    if (options.bitDepth === 8 || (options.bitDepth === 16 && bigEndian)) {
-      return dataIn;
-    }
-  }
-
-  // map to a UInt16 array if data is 16bit, fix endianness below
-  var data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer);
-
-  var maxValue = 255;
-  var inBpp = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType];
-  if (inBpp === 4 && !options.inputHasAlpha) {
-    inBpp = 3;
-  }
-  var outBpp = constants.COLORTYPE_TO_BPP_MAP[options.colorType];
-  if (options.bitDepth === 16) {
-    maxValue = 65535;
-    outBpp *= 2;
-  }
-  var outData = new Buffer(width * height * outBpp);
-
-  var inIndex = 0;
-  var outIndex = 0;
-
-  var bgColor = options.bgColor || {};
-  if (bgColor.red === undefined) {
-    bgColor.red = maxValue;
-  }
-  if (bgColor.green === undefined) {
-    bgColor.green = maxValue;
-  }
-  if (bgColor.blue === undefined) {
-    bgColor.blue = maxValue;
-  }
-
-  function getRGBA() {
-    var red;
-    var green;
-    var blue;
-    var alpha = maxValue;
-    switch (options.inputColorType) {
-      case constants.COLORTYPE_COLOR_ALPHA:
-        alpha = data[inIndex + 3];
-        red = data[inIndex];
-        green = data[inIndex + 1];
-        blue = data[inIndex + 2];
-        break;
-      case constants.COLORTYPE_COLOR:
-        red = data[inIndex];
-        green = data[inIndex + 1];
-        blue = data[inIndex + 2];
-        break;
-      case constants.COLORTYPE_ALPHA:
-        alpha = data[inIndex + 1];
-        red = data[inIndex];
-        green = red;
-        blue = red;
-        break;
-      case constants.COLORTYPE_GRAYSCALE:
-        red = data[inIndex];
-        green = red;
-        blue = red;
-        break;
-      default:
-        throw new Error('input color type:' + options.inputColorType + ' is not supported at present');
-    }
-
-    if (options.inputHasAlpha) {
-      if (!outHasAlpha) {
-        alpha /= maxValue;
-        red = Math.min(Math.max(Math.round((1 - alpha) * bgColor.red + alpha * red), 0), maxValue);
-        green = Math.min(Math.max(Math.round((1 - alpha) * bgColor.green + alpha * green), 0), maxValue);
-        blue = Math.min(Math.max(Math.round((1 - alpha) * bgColor.blue + alpha * blue), 0), maxValue);
-      }
-    }
-    return { red: red, green: green, blue: blue, alpha: alpha };
-  }
-
-  for (var y = 0; y < height; y++) {
-    for (var x = 0; x < width; x++) {
-      var rgba = getRGBA(data, inIndex);
-
-      switch (options.colorType) {
-        case constants.COLORTYPE_COLOR_ALPHA:
-        case constants.COLORTYPE_COLOR:
-          if (options.bitDepth === 8) {
-            outData[outIndex] = rgba.red;
-            outData[outIndex + 1] = rgba.green;
-            outData[outIndex + 2] = rgba.blue;
-            if (outHasAlpha) {
-              outData[outIndex + 3] = rgba.alpha;
-            }
-          }
-          else {
-            outData.writeUInt16BE(rgba.red, outIndex);
-            outData.writeUInt16BE(rgba.green, outIndex + 2);
-            outData.writeUInt16BE(rgba.blue, outIndex + 4);
-            if (outHasAlpha) {
-              outData.writeUInt16BE(rgba.alpha, outIndex + 6);
-            }
-          }
-          break;
-        case constants.COLORTYPE_ALPHA:
-        case constants.COLORTYPE_GRAYSCALE:
-          // Convert to grayscale and alpha
-          var grayscale = (rgba.red + rgba.green + rgba.blue) / 3;
-          if (options.bitDepth === 8) {
-            outData[outIndex] = grayscale;
-            if (outHasAlpha) {
-              outData[outIndex + 1] = rgba.alpha;
-            }
-          }
-          else {
-            outData.writeUInt16BE(grayscale, outIndex);
-            if (outHasAlpha) {
-              outData.writeUInt16BE(rgba.alpha, outIndex + 2);
-            }
-          }
-          break;
-        default:
-          throw new Error('unrecognised color Type ' + options.colorType);
-      }
-
-      inIndex += inBpp;
-      outIndex += outBpp;
-    }
-  }
-
-  return outData;
-};
-
-}).call(this,require("buffer").Buffer)
-},{"./constants":4,"buffer":32}],3:[function(require,module,exports){
-(function (process,Buffer){
-'use strict';
-
-
-var util = require('util');
-var Stream = require('stream');
-
-
-var ChunkStream = module.exports = function() {
-  Stream.call(this);
-
-  this._buffers = [];
-  this._buffered = 0;
-
-  this._reads = [];
-  this._paused = false;
-
-  this._encoding = 'utf8';
-  this.writable = true;
-};
-util.inherits(ChunkStream, Stream);
-
-
-ChunkStream.prototype.read = function(length, callback) {
-
-  this._reads.push({
-    length: Math.abs(length), // if length < 0 then at most this length
-    allowLess: length < 0,
-    func: callback
-  });
-
-  process.nextTick(function() {
-    this._process();
-
-    // its paused and there is not enought data then ask for more
-    if (this._paused && this._reads.length > 0) {
-      this._paused = false;
-
-      this.emit('drain');
-    }
-  }.bind(this));
-};
-
-ChunkStream.prototype.write = function(data, encoding) {
-
-  if (!this.writable) {
-    this.emit('error', new Error('Stream not writable'));
-    return false;
-  }
-
-  var dataBuffer;
-  if (Buffer.isBuffer(data)) {
-    dataBuffer = data;
-  }
-  else {
-    dataBuffer = new Buffer(data, encoding || this._encoding);
-  }
-
-  this._buffers.push(dataBuffer);
-  this._buffered += dataBuffer.length;
-
-  this._process();
-
-  // ok if there are no more read requests
-  if (this._reads && this._reads.length === 0) {
-    this._paused = true;
-  }
-
-  return this.writable && !this._paused;
-};
-
-ChunkStream.prototype.end = function(data, encoding) {
-
-  if (data) {
-    this.write(data, encoding);
-  }
-
-  this.writable = false;
-
-  // already destroyed
-  if (!this._buffers) {
-    return;
-  }
-
-  // enqueue or handle end
-  if (this._buffers.length === 0) {
-    this._end();
-  }
-  else {
-    this._buffers.push(null);
-    this._process();
-  }
-};
-
-ChunkStream.prototype.destroySoon = ChunkStream.prototype.end;
-
-ChunkStream.prototype._end = function() {
-
-  if (this._reads.length > 0) {
-    this.emit('error',
-      new Error('Unexpected end of input')
-    );
-  }
-
-  this.destroy();
-};
-
-ChunkStream.prototype.destroy = function() {
-
-  if (!this._buffers) {
-    return;
-  }
-
-  this.writable = false;
-  this._reads = null;
-  this._buffers = null;
-
-  this.emit('close');
-};
-
-ChunkStream.prototype._processReadAllowingLess = function(read) {
-  // ok there is any data so that we can satisfy this request
-  this._reads.shift(); // == read
-
-  // first we need to peek into first buffer
-  var smallerBuf = this._buffers[0];
-
-  // ok there is more data than we need
-  if (smallerBuf.length > read.length) {
-
-    this._buffered -= read.length;
-    this._buffers[0] = smallerBuf.slice(read.length);
-
-    read.func.call(this, smallerBuf.slice(0, read.length));
-
-  }
-  else {
-    // ok this is less than maximum length so use it all
-    this._buffered -= smallerBuf.length;
-    this._buffers.shift(); // == smallerBuf
-
-    read.func.call(this, smallerBuf);
-  }
-};
-
-ChunkStream.prototype._processRead = function(read) {
-  this._reads.shift(); // == read
-
-  var pos = 0;
-  var count = 0;
-  var data = new Buffer(read.length);
-
-  // create buffer for all data
-  while (pos < read.length) {
-
-    var buf = this._buffers[count++];
-    var len = Math.min(buf.length, read.length - pos);
-
-    buf.copy(data, pos, 0, len);
-    pos += len;
-
-    // last buffer wasn't used all so just slice it and leave
-    if (len !== buf.length) {
-      this._buffers[--count] = buf.slice(len);
-    }
-  }
-
-  // remove all used buffers
-  if (count > 0) {
-    this._buffers.splice(0, count);
-  }
-
-  this._buffered -= read.length;
-
-  read.func.call(this, data);
-};
-
-ChunkStream.prototype._process = function() {
-
-  try {
-    // as long as there is any data and read requests
-    while (this._buffered > 0 && this._reads && this._reads.length > 0) {
-
-      var read = this._reads[0];
-
-      // read any data (but no more than length)
-      if (read.allowLess) {
-        this._processReadAllowingLess(read);
-
-      }
-      else if (this._buffered >= read.length) {
-        // ok we can meet some expectations
-
-        this._processRead(read);
-      }
-      else {
-        // not enought data to satisfy first request in queue
-        // so we need to wait for more
-        break;
-      }
-    }
-
-    if (this._buffers && !this.writable) {
-      this._end();
-    }
-  }
-  catch (ex) {
-    this.emit('error', ex);
-  }
-};
-
-}).call(this,require('_process'),require("buffer").Buffer)
-},{"_process":51,"buffer":32,"stream":64,"util":69}],4:[function(require,module,exports){
-'use strict';
-
-
-module.exports = {
-
-  PNG_SIGNATURE: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a],
-
-  TYPE_IHDR: 0x49484452,
-  TYPE_IEND: 0x49454e44,
-  TYPE_IDAT: 0x49444154,
-  TYPE_PLTE: 0x504c5445,
-  TYPE_tRNS: 0x74524e53, // eslint-disable-line camelcase
-  TYPE_gAMA: 0x67414d41, // eslint-disable-line camelcase
-
-  // color-type bits
-  COLORTYPE_GRAYSCALE: 0,
-  COLORTYPE_PALETTE: 1,
-  COLORTYPE_COLOR: 2,
-  COLORTYPE_ALPHA: 4, // e.g. grayscale and alpha
-
-  // color-type combinations
-  COLORTYPE_PALETTE_COLOR: 3,
-  COLORTYPE_COLOR_ALPHA: 6,
-
-  COLORTYPE_TO_BPP_MAP: {
-    0: 1,
-    2: 3,
-    3: 1,
-    4: 2,
-    6: 4
-  },
-
-  GAMMA_DIVISION: 100000
-};
-
-},{}],5:[function(require,module,exports){
-'use strict';
-
-var crcTable = [];
-
-(function() {
-  for (var i = 0; i < 256; i++) {
-    var currentCrc = i;
-    for (var j = 0; j < 8; j++) {
-      if (currentCrc & 1) {
-        currentCrc = 0xedb88320 ^ (currentCrc >>> 1);
-      }
-      else {
-        currentCrc = currentCrc >>> 1;
-      }
-    }
-    crcTable[i] = currentCrc;
-  }
-}());
-
-var CrcCalculator = module.exports = function() {
-  this._crc = -1;
-};
-
-CrcCalculator.prototype.write = function(data) {
-
-  for (var i = 0; i < data.length; i++) {
-    this._crc = crcTable[(this._crc ^ data[i]) & 0xff] ^ (this._crc >>> 8);
-  }
-  return true;
-};
-
-CrcCalculator.prototype.crc32 = function() {
-  return this._crc ^ -1;
-};
-
-
-CrcCalculator.crc32 = function(buf) {
-
-  var crc = -1;
-  for (var i = 0; i < buf.length; i++) {
-    crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
-  }
-  return crc ^ -1;
-};
-
-},{}],6:[function(require,module,exports){
-(function (Buffer){
-'use strict';
-
-var paethPredictor = require('./paeth-predictor');
-
-function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) {
-
-  for (var x = 0; x < byteWidth; x++) {
-    rawData[rawPos + x] = pxData[pxPos + x];
-  }
-}
-
-function filterSumNone(pxData, pxPos, byteWidth) {
-
-  var sum = 0;
-  var length = pxPos + byteWidth;
-
-  for (var i = pxPos; i < length; i++) {
-    sum += Math.abs(pxData[i]);
-  }
-  return sum;
-}
-
-function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
-
-  for (var x = 0; x < byteWidth; x++) {
-
-    var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
-    var val = pxData[pxPos + x] - left;
-
-    rawData[rawPos + x] = val;
-  }
-}
-
-function filterSumSub(pxData, pxPos, byteWidth, bpp) {
-
-  var sum = 0;
-  for (var x = 0; x < byteWidth; x++) {
-
-    var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
-    var val = pxData[pxPos + x] - left;
-
-    sum += Math.abs(val);
-  }
-
-  return sum;
-}
-
-function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) {
-
-  for (var x = 0; x < byteWidth; x++) {
-
-    var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
-    var val = pxData[pxPos + x] - up;
-
-    rawData[rawPos + x] = val;
-  }
-}
-
-function filterSumUp(pxData, pxPos, byteWidth) {
-
-  var sum = 0;
-  var length = pxPos + byteWidth;
-  for (var x = pxPos; x < length; x++) {
-
-    var up = pxPos > 0 ? pxData[x - byteWidth] : 0;
-    var val = pxData[x] - up;
-
-    sum += Math.abs(val);
-  }
-
-  return sum;
-}
-
-function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
-
-  for (var x = 0; x < byteWidth; x++) {
-
-    var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
-    var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
-    var val = pxData[pxPos + x] - ((left + up) >> 1);
-
-    rawData[rawPos + x] = val;
-  }
-}
-
-function filterSumAvg(pxData, pxPos, byteWidth, bpp) {
-
-  var sum = 0;
-  for (var x = 0; x < byteWidth; x++) {
-
-    var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
-    var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
-    var val = pxData[pxPos + x] - ((left + up) >> 1);
-
-    sum += Math.abs(val);
-  }
-
-  return sum;
-}
-
-function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
-
-  for (var x = 0; x < byteWidth; x++) {
-
-    var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
-    var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
-    var upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
-    var val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
-
-    rawData[rawPos + x] = val;
-  }
-}
-
-function filterSumPaeth(pxData, pxPos, byteWidth, bpp) {
-  var sum = 0;
-  for (var x = 0; x < byteWidth; x++) {
-
-    var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
-    var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
-    var upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
-    var val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
-
-    sum += Math.abs(val);
-  }
-
-  return sum;
-}
-
-var filters = {
-  0: filterNone,
-  1: filterSub,
-  2: filterUp,
-  3: filterAvg,
-  4: filterPaeth
-};
-
-var filterSums = {
-  0: filterSumNone,
-  1: filterSumSub,
-  2: filterSumUp,
-  3: filterSumAvg,
-  4: filterSumPaeth
-};
-
-module.exports = function(pxData, width, height, options, bpp) {
-
-  var filterTypes;
-  if (!('filterType' in options) || options.filterType === -1) {
-    filterTypes = [0, 1, 2, 3, 4];
-  }
-  else if (typeof options.filterType === 'number') {
-    filterTypes = [options.filterType];
-  }
-  else {
-    throw new Error('unrecognised filter types');
-  }
-
-  if (options.bitDepth === 16) {
-    bpp *= 2;
-  }
-  var byteWidth = width * bpp;
-  var rawPos = 0;
-  var pxPos = 0;
-  var rawData = new Buffer((byteWidth + 1) * height);
-
-  var sel = filterTypes[0];
-
-  for (var y = 0; y < height; y++) {
-
-    if (filterTypes.length > 1) {
-      // find best filter for this line (with lowest sum of values)
-      var min = Infinity;
-
-      for (var i = 0; i < filterTypes.length; i++) {
-        var sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp);
-        if (sum < min) {
-          sel = filterTypes[i];
-          min = sum;
-        }
-      }
-    }
-
-    rawData[rawPos] = sel;
-    rawPos++;
-    filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp);
-    rawPos += byteWidth;
-    pxPos += byteWidth;
-  }
-  return rawData;
-};
-
-}).call(this,require("buffer").Buffer)
-},{"./paeth-predictor":15,"buffer":32}],7:[function(require,module,exports){
-(function (Buffer){
-'use strict';
-
-var util = require('util');
-var ChunkStream = require('./chunkstream');
-var Filter = require('./filter-parse');
-
-
-var FilterAsync = module.exports = function(bitmapInfo) {
-  ChunkStream.call(this);
-
-  var buffers = [];
-  var that = this;
-  this._filter = new Filter(bitmapInfo, {
-    read: this.read.bind(this),
-    write: function(buffer) {
-      buffers.push(buffer);
-    },
-    complete: function() {
-      that.emit('complete', Buffer.concat(buffers));
-    }
-  });
-
-  this._filter.start();
-};
-util.inherits(FilterAsync, ChunkStream);
-
-}).call(this,require("buffer").Buffer)
-},{"./chunkstream":3,"./filter-parse":9,"buffer":32,"util":69}],8:[function(require,module,exports){
-(function (Buffer){
-'use strict';
-
-var SyncReader = require('./sync-reader');
-var Filter = require('./filter-parse');
-
-
-exports.process = function(inBuffer, bitmapInfo) {
-
-  var outBuffers = [];
-  var reader = new SyncReader(inBuffer);
-  var filter = new Filter(bitmapInfo, {
-    read: reader.read.bind(reader),
-    write: function(bufferPart) {
-      outBuffers.push(bufferPart);
-    },
-    complete: function() {
-    }
-  });
-
-  filter.start();
-  reader.process();
-
-  return Buffer.concat(outBuffers);
-};
-}).call(this,require("buffer").Buffer)
-},{"./filter-parse":9,"./sync-reader":22,"buffer":32}],9:[function(require,module,exports){
-(function (Buffer){
-'use strict';
-
-var interlaceUtils = require('./interlace');
-var paethPredictor = require('./paeth-predictor');
-
-function getByteWidth(width, bpp, depth) {
-  var byteWidth = width * bpp;
-  if (depth !== 8) {
-    byteWidth = Math.ceil(byteWidth / (8 / depth));
-  }
-  return byteWidth;
-}
-
-var Filter = module.exports = function(bitmapInfo, dependencies) {
-
-  var width = bitmapInfo.width;
-  var height = bitmapInfo.height;
-  var interlace = bitmapInfo.interlace;
-  var bpp = bitmapInfo.bpp;
-  var depth = bitmapInfo.depth;
-
-  this.read = dependencies.read;
-  this.write = dependencies.write;
-  this.complete = dependencies.complete;
-
-  this._imageIndex = 0;
-  this._images = [];
-  if (interlace) {
-    var passes = interlaceUtils.getImagePasses(width, height);
-    for (var i = 0; i < passes.length; i++) {
-      this._images.push({
-        byteWidth: getByteWidth(passes[i].width, bpp, depth),
-        height: passes[i].height,
-        lineIndex: 0
-      });
-    }
-  }
-  else {
-    this._images.push({
-      byteWidth: getByteWidth(width, bpp, depth),
-      height: height,
-      lineIndex: 0
-    });
-  }
-
-  // when filtering the line we look at the pixel to the left
-  // the spec also says it is done on a byte level regardless of the number of pixels
-  // so if the depth is byte compatible (8 or 16) we subtract the bpp in order to compare back
-  // a pixel rather than just a different byte part. However if we are sub byte, we ignore.
-  if (depth === 8) {
-    this._xComparison = bpp;
-  }
-  else if (depth === 16) {
-    this._xComparison = bpp * 2;
-  }
-  else {
-    this._xComparison = 1;
-  }
-};
-
-Filter.prototype.start = function() {
-  this.read(this._images[this._imageIndex].byteWidth + 1, this._reverseFilterLine.bind(this));
-};
-
-Filter.prototype._unFilterType1 = function(rawData, unfilteredLine, byteWidth) {
-
-  var xComparison = this._xComparison;
-  var xBiggerThan = xComparison - 1;
-
-  for (var x = 0; x < byteWidth; x++) {
-    var rawByte = rawData[1 + x];
-    var f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
-    unfilteredLine[x] = rawByte + f1Left;
-  }
-};
-
-Filter.prototype._unFilterType2 = function(rawData, unfilteredLine, byteWidth) {
-
-  var lastLine = this._lastLine;
-
-  for (var x = 0; x < byteWidth; x++) {
-    var rawByte = rawData[1 + x];
-    var f2Up = lastLine ? lastLine[x] : 0;
-    unfilteredLine[x] = rawByte + f2Up;
-  }
-};
-
-Filter.prototype._unFilterType3 = function(rawData, unfilteredLine, byteWidth) {
-
-  var xComparison = this._xComparison;
-  var xBiggerThan = xComparison - 1;
-  var lastLine = this._lastLine;
-
-  for (var x = 0; x < byteWidth; x++) {
-    var rawByte = rawData[1 + x];
-    var f3Up = lastLine ? lastLine[x] : 0;
-    var f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
-    var f3Add = Math.floor((f3Left + f3Up) / 2);
-    unfilteredLine[x] = rawByte + f3Add;
-  }
-};
-
-Filter.prototype._unFilterType4 = function(rawData, unfilteredLine, byteWidth) {
-
-  var xComparison = this._xComparison;
-  var xBiggerThan = xComparison - 1;
-  var lastLine = this._lastLine;
-
-  for (var x = 0; x < byteWidth; x++) {
-    var rawByte = rawData[1 + x];
-    var f4Up = lastLine ? lastLine[x] : 0;
-    var f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
-    var f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0;
-    var f4Add = paethPredictor(f4Left, f4Up, f4UpLeft);
-    unfilteredLine[x] = rawByte + f4Add;
-  }
-};
-
-Filter.prototype._reverseFilterLine = function(rawData) {
-
-  var filter = rawData[0];
-  var unfilteredLine;
-  var currentImage = this._images[this._imageIndex];
-  var byteWidth = currentImage.byteWidth;
-
-  if (filter === 0) {
-    unfilteredLine = rawData.slice(1, byteWidth + 1);
-  }
-  else {
-
-    unfilteredLine = new Buffer(byteWidth);
-
-    switch (filter) {
-      case 1:
-        this._unFilterType1(rawData, unfilteredLine, byteWidth);
-        break;
-      case 2:
-        this._unFilterType2(rawData, unfilteredLine, byteWidth);
-        break;
-      case 3:
-        this._unFilterType3(rawData, unfilteredLine, byteWidth);
-        break;
-      case 4:
-        this._unFilterType4(rawData, unfilteredLine, byteWidth);
-        break;
-      default:
-        throw new Error('Unrecognised filter type - ' + filter);
-    }
-  }
-
-  this.write(unfilteredLine);
-
-  currentImage.lineIndex++;
-  if (currentImage.lineIndex >= currentImage.height) {
-    this._lastLine = null;
-    this._imageIndex++;
-    currentImage = this._images[this._imageIndex];
-  }
-  else {
-    this._lastLine = unfilteredLine;
-  }
-
-  if (currentImage) {
-    // read, using the byte width that may be from the new current image
-    this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this));
-  }
-  else {
-    this._lastLine = null;
-    this.complete();
-  }
-};
-
-}).call(this,require("buffer").Buffer)
-},{"./interlace":11,"./paeth-predictor":15,"buffer":32}],10:[function(require,module,exports){
-(function (Buffer){
-'use strict';
-
-function dePalette(indata, outdata, width, height, palette) {
-  var pxPos = 0;
-  // use values from palette
-  for (var y = 0; y < height; y++) {
-    for (var x = 0; x < width; x++) {
-      var color = palette[indata[pxPos]];
-
-      if (!color) {
-        throw new Error('index ' + indata[pxPos] + ' not in palette');
-      }
-
-      for (var i = 0; i < 4; i++) {
-        outdata[pxPos + i] = color[i];
-      }
-      pxPos += 4;
-    }
-  }
-}
-
-function replaceTransparentColor(indata, outdata, width, height, transColor) {
-  var pxPos = 0;
-  for (var y = 0; y < height; y++) {
-    for (var x = 0; x < width; x++) {
-      var makeTrans = false;
-
-      if (transColor.length === 1) {
-        if (transColor[0] === indata[pxPos]) {
-          makeTrans = true;
-        }
-      }
-      else if (transColor[0] === indata[pxPos] && transColor[1] === indata[pxPos + 1] && transColor[2] === indata[pxPos + 2]) {
-        makeTrans = true;
-      }
-      if (makeTrans) {
-        for (var i = 0; i < 4; i++) {
-          outdata[pxPos + i] = 0;
-        }
-      }
-      pxPos += 4;
-    }
-  }
-}
-
-function scaleDepth(indata, outdata, width, height, depth) {
-  var maxOutSample = 255;
-  var maxInSample = Math.pow(2, depth) - 1;
-  var pxPos = 0;
-
-  for (var y = 0; y < height; y++) {
-    for (var x = 0; x < width; x++) {
-      for (var i = 0; i < 4; i++) {
-        outdata[pxPos + i] = Math.floor((indata[pxPos + i] * maxOutSample) / maxInSample + 0.5);
-      }
-      pxPos += 4;
-    }
-  }
-}
-
-module.exports = function(indata, imageData) {
-
-  var depth = imageData.depth;
-  var width = imageData.width;
-  var height = imageData.height;
-  var colorType = imageData.colorType;
-  var transColor = imageData.transColor;
-  var palette = imageData.palette;
-
-  var outdata = indata; // only different for 16 bits
-
-  if (colorType === 3) { // paletted
-    dePalette(indata, outdata, width, height, palette);
-  }
-  else {
-    if (transColor) {
-      replaceTransparentColor(indata, outdata, width, height, transColor);
-    }
-    // if it needs scaling
-    if (depth !== 8) {
-      // if we need to change the buffer size
-      if (depth === 16) {
-        outdata = new Buffer(width * height * 4);
-      }
-      scaleDepth(indata, outdata, width, height, depth);
-    }
-  }
-  return outdata;
-};
-
-}).call(this,require("buffer").Buffer)
-},{"buffer":32}],11:[function(require,module,exports){
-'use strict';
-
-// Adam 7
-//   0 1 2 3 4 5 6 7
-// 0 x 6 4 6 x 6 4 6
-// 1 7 7 7 7 7 7 7 7
-// 2 5 6 5 6 5 6 5 6
-// 3 7 7 7 7 7 7 7 7
-// 4 3 6 4 6 3 6 4 6
-// 5 7 7 7 7 7 7 7 7
-// 6 5 6 5 6 5 6 5 6
-// 7 7 7 7 7 7 7 7 7
-
-
-var imagePasses = [
-  { // pass 1 - 1px
-    x: [0],
-    y: [0]
-  },
-  { // pass 2 - 1px
-    x: [4],
-    y: [0]
-  },
-  { // pass 3 - 2px
-    x: [0, 4],
-    y: [4]
-  },
-  { // pass 4 - 4px
-    x: [2, 6],
-    y: [0, 4]
-  },
-  { // pass 5 - 8px
-    x: [0, 2, 4, 6],
-    y: [2, 6]
-  },
-  { // pass 6 - 16px
-    x: [1, 3, 5, 7],
-    y: [0, 2, 4, 6]
-  },
-  { // pass 7 - 32px
-    x: [0, 1, 2, 3, 4, 5, 6, 7],
-    y: [1, 3, 5, 7]
-  }
-];
-
-exports.getImagePasses = function(width, height) {
-  var images = [];
-  var xLeftOver = width % 8;
-  var yLeftOver = height % 8;
-  var xRepeats = (width - xLeftOver) / 8;
-  var yRepeats = (height - yLeftOver) / 8;
-  for (var i = 0; i < imagePasses.length; i++) {
-    var pass = imagePasses[i];
-    var passWidth = xRepeats * pass.x.length;
-    var passHeight = yRepeats * pass.y.length;
-    for (var j = 0; j < pass.x.length; j++) {
-      if (pass.x[j] < xLeftOver) {
-        passWidth++;
-      }
-      else {
-        break;
-      }
-    }
-    for (j = 0; j < pass.y.length; j++) {
-      if (pass.y[j] < yLeftOver) {
-        passHeight++;
-      }
-      else {
-        break;
-      }
-    }
-    if (passWidth > 0 && passHeight > 0) {
-      images.push({ width: passWidth, height: passHeight, index: i });
-    }
-  }
-  return images;
-};
-
-exports.getInterlaceIterator = function(width) {
-  return function(x, y, pass) {
-    var outerXLeftOver = x % imagePasses[pass].x.length;
-    var outerX = (((x - outerXLeftOver) / imagePasses[pass].x.length) * 8) + imagePasses[pass].x[outerXLeftOver];
-    var outerYLeftOver = y % imagePasses[pass].y.length;
-    var outerY = (((y - outerYLeftOver) / imagePasses[pass].y.length) * 8) + imagePasses[pass].y[outerYLeftOver];
-    return (outerX * 4) + (outerY * width * 4);
-  };
-};
-},{}],12:[function(require,module,exports){
-(function (Buffer){
-'use strict';
-
-var util = require('util');
-var Stream = require('stream');
-var constants = require('./constants');
-var Packer = require('./packer');
-
-var PackerAsync = module.exports = function(opt) {
-  Stream.call(this);
-
-  var options = opt || {};
-
-  this._packer = new Packer(options);
-  this._deflate = this._packer.createDeflate();
-
-  this.readable = true;
-};
-util.inherits(PackerAsync, Stream);
-
-
-PackerAsync.prototype.pack = function(data, width, height, gamma) {
-  // Signature
-  this.emit('data', new Buffer(constants.PNG_SIGNATURE));
-  this.emit('data', this._packer.packIHDR(width, height));
-
-  if (gamma) {
-    this.emit('data', this._packer.packGAMA(gamma));
-  }
-
-  var filteredData = this._packer.filterData(data, width, height);
-
-  // compress it
-  this._deflate.on('error', this.emit.bind(this, 'error'));
-
-  this._deflate.on('data', function(compressedData) {
-    this.emit('data', this._packer.packIDAT(compressedData));
-  }.bind(this));
-
-  this._deflate.on('end', function() {
-    this.emit('data', this._packer.packIEND());
-    this.emit('end');
-  }.bind(this));
-
-  this._deflate.end(filteredData);
-};
-
-}).call(this,require("buffer").Buffer)
-},{"./constants":4,"./packer":14,"buffer":32,"stream":64,"util":69}],13:[function(require,module,exports){
-(function (Buffer){
-'use strict';
-
-var hasSyncZlib = true;
-var zlib = require('zlib');
-if (!zlib.deflateSync) {
-  hasSyncZlib = false;
-}
-var constants = require('./constants');
-var Packer = require('./packer');
-
-module.exports = function(metaData, opt) {
-
-  if (!hasSyncZlib) {
-    throw new Error('To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0');
-  }
-
-  var options = opt || {};
-
-  var packer = new Packer(options);
-
-  var chunks = [];
-
-  // Signature
-  chunks.push(new Buffer(constants.PNG_SIGNATURE));
-
-  // Header
-  chunks.push(packer.packIHDR(metaData.width, metaData.height));
-
-  if (metaData.gamma) {
-    chunks.push(packer.packGAMA(metaData.gamma));
-  }
-
-  var filteredData = packer.filterData(metaData.data, metaData.width, metaData.height);
-
-  // compress it
-  var compressedData = zlib.deflateSync(filteredData, packer.getDeflateOptions());
-  filteredData = null;
-
-  if (!compressedData || !compressedData.length) {
-    throw new Error('bad png - invalid compressed data response');
-  }
-  chunks.push(packer.packIDAT(compressedData));
-
-  // End
-  chunks.push(packer.packIEND());
-
-  return Buffer.concat(chunks);
-};
-
-}).call(this,require("buffer").Buffer)
-},{"./constants":4,"./packer":14,"buffer":32,"zlib":30}],14:[function(require,module,exports){
-(function (Buffer){
-'use strict';
-
-var constants = require('./constants');
-var CrcStream = require('./crc');
-var bitPacker = require('./bitpacker');
-var filter = require('./filter-pack');
-var zlib = require('zlib');
-
-var Packer = module.exports = function(options) {
-  this._options = options;
-
-  options.deflateChunkSize = options.deflateChunkSize || 32 * 1024;
-  options.deflateLevel = options.deflateLevel != null ? options.deflateLevel : 9;
-  options.deflateStrategy = options.deflateStrategy != null ? options.deflateStrategy : 3;
-  options.inputHasAlpha = options.inputHasAlpha != null ? options.inputHasAlpha : true;
-  options.deflateFactory = options.deflateFactory || zlib.createDeflate;
-  options.bitDepth = options.bitDepth || 8;
-  // This is outputColorType
-  options.colorType = (typeof options.colorType === 'number') ? options.colorType : constants.COLORTYPE_COLOR_ALPHA;
-  options.inputColorType = (typeof options.inputColorType === 'number') ? options.inputColorType : constants.COLORTYPE_COLOR_ALPHA;
-
-  if ([
-    constants.COLORTYPE_GRAYSCALE,
-    constants.COLORTYPE_COLOR,
-    constants.COLORTYPE_COLOR_ALPHA,
-    constants.COLORTYPE_ALPHA
-  ].indexOf(options.colorType) === -1) {
-    throw new Error('option color type:' + options.colorType + ' is not supported at present');
-  }
-  if ([
-    constants.COLORTYPE_GRAYSCALE,
-    constants.COLORTYPE_COLOR,
-    constants.COLORTYPE_COLOR_ALPHA,
-    constants.COLORTYPE_ALPHA
-  ].indexOf(options.inputColorType) === -1) {
-    throw new Error('option input color type:' + options.inputColorType + ' is not supported at present');
-  }
-  if (options.bitDepth !== 8 && options.bitDepth !== 16) {
-    throw new Error('option bit depth:' + options.bitDepth + ' is not supported at present');
-  }
-};
-
-Packer.prototype.getDeflateOptions = function() {
-  return {
-    chunkSize: this._options.deflateChunkSize,
-    level: this._options.deflateLevel,
-    strategy: this._options.deflateStrategy
-  };
-};
-
-Packer.prototype.createDeflate = function() {
-  return this._options.deflateFactory(this.getDeflateOptions());
-};
-
-Packer.prototype.filterData = function(data, width, height) {
-  // convert to correct format for filtering (e.g. right bpp and bit depth)
-  var packedData = bitPacker(data, width, height, this._options);
-
-  // filter pixel data
-  var bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];
-  var filteredData = filter(packedData, width, height, this._options, bpp);
-  return filteredData;
-};
-
-Packer.prototype._packChunk = function(type, data) {
-
-  var len = (data ? data.length : 0);
-  var buf = new Buffer(len + 12);
-
-  buf.writeUInt32BE(len, 0);
-  buf.writeUInt32BE(type, 4);
-
-  if (data) {
-    data.copy(buf, 8);
-  }
-
-  buf.writeInt32BE(CrcStream.crc32(buf.slice(4, buf.length - 4)), buf.length - 4);
-  return buf;
-};
-
-Packer.prototype.packGAMA = function(gamma) {
-  var buf = new Buffer(4);
-  buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0);
-  return this._packChunk(constants.TYPE_gAMA, buf);
-};
-
-Packer.prototype.packIHDR = function(width, height) {
-
-  var buf = new Buffer(13);
-  buf.writeUInt32BE(width, 0);
-  buf.writeUInt32BE(height, 4);
-  buf[8] = this._options.bitDepth; // Bit depth
-  buf[9] = this._options.colorType; // colorType
-  buf[10] = 0; // compression
-  buf[11] = 0; // filter
-  buf[12] = 0; // interlace
-
-  return this._packChunk(constants.TYPE_IHDR, buf);
-};
-
-Packer.prototype.packIDAT = function(data) {
-  return this._packChunk(constants.TYPE_IDAT, data);
-};
-
-Packer.prototype.packIEND = function() {
-  return this._packChunk(constants.TYPE_IEND, null);
-};
-
-}).call(this,require("buffer").Buffer)
-},{"./bitpacker":2,"./constants":4,"./crc":5,"./filter-pack":6,"buffer":32,"zlib":30}],15:[function(require,module,exports){
-'use strict';\r
-\r
-module.exports = function paethPredictor(left, above, upLeft) {\r
-\r
-  var paeth = left + above - upLeft;\r
-  var pLeft = Math.abs(paeth - left);\r
-  var pAbove = Math.abs(paeth - above);\r
-  var pUpLeft = Math.abs(paeth - upLeft);\r
-\r
-  if (pLeft <= pAbove && pLeft <= pUpLeft) {\r
-    return left;\r
-  }\r
-  if (pAbove <= pUpLeft) {\r
-    return above;\r
-  }\r
-  return upLeft;\r
-};
-},{}],16:[function(require,module,exports){
-'use strict';
-
-var util = require('util');
-var zlib = require('zlib');
-var ChunkStream = require('./chunkstream');
-var FilterAsync = require('./filter-parse-async');
-var Parser = require('./parser');
-var bitmapper = require('./bitmapper');
-var formatNormaliser = require('./format-normaliser');
-
-var ParserAsync = module.exports = function(options) {
-  ChunkStream.call(this);
-
-  this._parser = new Parser(options, {
-    read: this.read.bind(this),
-    error: this._handleError.bind(this),
-    metadata: this._handleMetaData.bind(this),
-    gamma: this.emit.bind(this, 'gamma'),
-    palette: this._handlePalette.bind(this),
-    transColor: this._handleTransColor.bind(this),
-    finished: this._finished.bind(this),
-    inflateData: this._inflateData.bind(this),
-    simpleTransparency: this._simpleTransparency.bind(this),
-    headersFinished: this._headersFinished.bind(this)
-  });
-  this._options = options;
-  this.writable = true;
-
-  this._parser.start();
-};
-util.inherits(ParserAsync, ChunkStream);
-
-
-ParserAsync.prototype._handleError = function(err) {
-
-  this.emit('error', err);
-
-  this.writable = false;
-
-  this.destroy();
-
-  if (this._inflate && this._inflate.destroy) {
-    this._inflate.destroy();
-  }
-
-  if (this._filter) {
-    this._filter.destroy();
-    // For backward compatibility with Node 7 and below.
-    // Suppress errors due to _inflate calling write() even after
-    // it's destroy()'ed.
-    this._filter.on('error', function() {});
-  }
-
-  this.errord = true;
-};
-
-ParserAsync.prototype._inflateData = function(data) {
-  if (!this._inflate) {
-    if (this._bitmapInfo.interlace) {
-      this._inflate = zlib.createInflate();
-
-      this._inflate.on('error', this.emit.bind(this, 'error'));
-      this._filter.on('complete', this._complete.bind(this));
-
-      this._inflate.pipe(this._filter);
-    }
-    else {
-      var rowSize = ((this._bitmapInfo.width * this._bitmapInfo.bpp * this._bitmapInfo.depth + 7) >> 3) + 1;
-      var imageSize = rowSize * this._bitmapInfo.height;
-      var chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK);
-
-      this._inflate = zlib.createInflate({ chunkSize: chunkSize });
-      var leftToInflate = imageSize;
-
-      var emitError = this.emit.bind(this, 'error');
-      this._inflate.on('error', function(err) {
-        if (!leftToInflate) {
-          return;
-        }
-
-        emitError(err);
-      });
-      this._filter.on('complete', this._complete.bind(this));
-
-      var filterWrite = this._filter.write.bind(this._filter);
-      this._inflate.on('data', function(chunk) {
-        if (!leftToInflate) {
-          return;
-        }
-
-        if (chunk.length > leftToInflate) {
-          chunk = chunk.slice(0, leftToInflate);
-        }
-
-        leftToInflate -= chunk.length;
-
-        filterWrite(chunk);
-      });
-
-      this._inflate.on('end', this._filter.end.bind(this._filter));
-    }
-  }
-  this._inflate.write(data);
-};
-
-ParserAsync.prototype._handleMetaData = function(metaData) {
-  this._metaData = metaData;
-  this._bitmapInfo = Object.create(metaData);
-
-  this._filter = new FilterAsync(this._bitmapInfo);
-};
-
-ParserAsync.prototype._handleTransColor = function(transColor) {
-  this._bitmapInfo.transColor = transColor;
-};
-
-ParserAsync.prototype._handlePalette = function(palette) {
-  this._bitmapInfo.palette = palette;
-};
-
-ParserAsync.prototype._simpleTransparency = function() {
-  this._metaData.alpha = true;
-};
-
-ParserAsync.prototype._headersFinished = function() {
-  // Up until this point, we don't know if we have a tRNS chunk (alpha)
-  // so we can't emit metadata any earlier
-  this.emit('metadata', this._metaData);
-};
-
-ParserAsync.prototype._finished = function() {
-  if (this.errord) {
-    return;
-  }
-
-  if (!this._inflate) {
-    this.emit('error', 'No Inflate block');
-  }
-  else {
-    // no more data to inflate
-    this._inflate.end();
-  }
-  this.destroySoon();
-};
-
-ParserAsync.prototype._complete = function(filteredData) {
-
-  if (this.errord) {
-    return;
-  }
-
-  try {
-    var bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo);
-
-    var normalisedBitmapData = formatNormaliser(bitmapData, this._bitmapInfo);
-    bitmapData = null;
-  }
-  catch (ex) {
-    this._handleError(ex);
-    return;
-  }
-
-  this.emit('parsed', normalisedBitmapData);
-};
-
-},{"./bitmapper":1,"./chunkstream":3,"./filter-parse-async":7,"./format-normaliser":10,"./parser":18,"util":69,"zlib":30}],17:[function(require,module,exports){
-(function (Buffer){
-'use strict';
-
-var hasSyncZlib = true;
-var zlib = require('zlib');
-var inflateSync = require('./sync-inflate');
-if (!zlib.deflateSync) {
-  hasSyncZlib = false;
-}
-var SyncReader = require('./sync-reader');
-var FilterSync = require('./filter-parse-sync');
-var Parser = require('./parser');
-var bitmapper = require('./bitmapper');
-var formatNormaliser = require('./format-normaliser');
-
-
-module.exports = function(buffer, options) {
-
-  if (!hasSyncZlib) {
-    throw new Error('To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0');
-  }
-
-  var err;
-  function handleError(_err_) {
-    err = _err_;
-  }
-
-  var metaData;
-  function handleMetaData(_metaData_) {
-    metaData = _metaData_;
-  }
-
-  function handleTransColor(transColor) {
-    metaData.transColor = transColor;
-  }
-
-  function handlePalette(palette) {
-    metaData.palette = palette;
-  }
-
-  function handleSimpleTransparency() {
-    metaData.alpha = true;
-  }
-
-  var gamma;
-  function handleGamma(_gamma_) {
-    gamma = _gamma_;
-  }
-
-  var inflateDataList = [];
-  function handleInflateData(inflatedData) {
-    inflateDataList.push(inflatedData);
-  }
-
-  var reader = new SyncReader(buffer);
-
-  var parser = new Parser(options, {
-    read: reader.read.bind(reader),
-    error: handleError,
-    metadata: handleMetaData,
-    gamma: handleGamma,
-    palette: handlePalette,
-    transColor: handleTransColor,
-    inflateData: handleInflateData,
-    simpleTransparency: handleSimpleTransparency
-  });
-
-  parser.start();
-  reader.process();
-
-  if (err) {
-    throw err;
-  }
-
-  //join together the inflate datas
-  var inflateData = Buffer.concat(inflateDataList);
-  inflateDataList.length = 0;
-
-  var inflatedData;
-  if (metaData.interlace) {
-    inflatedData = zlib.inflateSync(inflateData);
-  }
-  else {
-    var rowSize = ((metaData.width * metaData.bpp * metaData.depth + 7) >> 3) + 1;
-    var imageSize = rowSize * metaData.height;
-    inflatedData = inflateSync(inflateData, { chunkSize: imageSize, maxLength: imageSize });
-  }
-  inflateData = null;
-
-  if (!inflatedData || !inflatedData.length) {
-    throw new Error('bad png - invalid inflate data response');
-  }
-
-  var unfilteredData = FilterSync.process(inflatedData, metaData);
-  inflateData = null;
-
-  var bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData);
-  unfilteredData = null;
-
-  var normalisedBitmapData = formatNormaliser(bitmapData, metaData);
-
-  metaData.data = normalisedBitmapData;
-  metaData.gamma = gamma || 0;
-
-  return metaData;
-};
-
-}).call(this,require("buffer").Buffer)
-},{"./bitmapper":1,"./filter-parse-sync":8,"./format-normaliser":10,"./parser":18,"./sync-inflate":21,"./sync-reader":22,"buffer":32,"zlib":30}],18:[function(require,module,exports){
-(function (Buffer){
-'use strict';
-
-var constants = require('./constants');
-var CrcCalculator = require('./crc');
-
-
-var Parser = module.exports = function(options, dependencies) {
-
-  this._options = options;
-  options.checkCRC = options.checkCRC !== false;
-
-  this._hasIHDR = false;
-  this._hasIEND = false;
-  this._emittedHeadersFinished = false;
-
-  // input flags/metadata
-  this._palette = [];
-  this._colorType = 0;
-
-  this._chunks = {};
-  this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this);
-  this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this);
-  this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this);
-  this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this);
-  this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this);
-  this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this);
-
-  this.read = dependencies.read;
-  this.error = dependencies.error;
-  this.metadata = dependencies.metadata;
-  this.gamma = dependencies.gamma;
-  this.transColor = dependencies.transColor;
-  this.palette = dependencies.palette;
-  this.parsed = dependencies.parsed;
-  this.inflateData = dependencies.inflateData;
-  this.finished = dependencies.finished;
-  this.simpleTransparency = dependencies.simpleTransparency;
-  this.headersFinished = dependencies.headersFinished || function() {};
-};
-
-Parser.prototype.start = function() {
-  this.read(constants.PNG_SIGNATURE.length,
-    this._parseSignature.bind(this)
-  );
-};
-
-Parser.prototype._parseSignature = function(data) {
-
-  var signature = constants.PNG_SIGNATURE;
-
-  for (var i = 0; i < signature.length; i++) {
-    if (data[i] !== signature[i]) {
-      this.error(new Error('Invalid file signature'));
-      return;
-    }
-  }
-  this.read(8, this._parseChunkBegin.bind(this));
-};
-
-Parser.prototype._parseChunkBegin = function(data) {
-
-  // chunk content length
-  var length = data.readUInt32BE(0);
-
-  // chunk type
-  var type = data.readUInt32BE(4);
-  var name = '';
-  for (var i = 4; i < 8; i++) {
-    name += String.fromCharCode(data[i]);
-  }
-
-  //console.log('chunk ', name, length);
-
-  // chunk flags
-  var ancillary = Boolean(data[4] & 0x20); // or critical
-  //    priv = Boolean(data[5] & 0x20), // or public
-  //    safeToCopy = Boolean(data[7] & 0x20); // or unsafe
-
-  if (!this._hasIHDR && type !== constants.TYPE_IHDR) {
-    this.error(new Error('Expected IHDR on beggining'));
-    return;
-  }
-
-  this._crc = new CrcCalculator();
-  this._crc.write(new Buffer(name));
-
-  if (this._chunks[type]) {
-    return this._chunks[type](length);
-  }
-
-  if (!ancillary) {
-    this.error(new Error('Unsupported critical chunk type ' + name));
-    return;
-  }
-
-  this.read(length + 4, this._skipChunk.bind(this));
-};
-
-Parser.prototype._skipChunk = function(/*data*/) {
-  this.read(8, this._parseChunkBegin.bind(this));
-};
-
-Parser.prototype._handleChunkEnd = function() {
-  this.read(4, this._parseChunkEnd.bind(this));
-};
-
-Parser.prototype._parseChunkEnd = function(data) {
-
-  var fileCrc = data.readInt32BE(0);
-  var calcCrc = this._crc.crc32();
-
-  // check CRC
-  if (this._options.checkCRC && calcCrc !== fileCrc) {
-    this.error(new Error('Crc error - ' + fileCrc + ' - ' + calcCrc));
-    return;
-  }
-
-  if (!this._hasIEND) {
-    this.read(8, this._parseChunkBegin.bind(this));
-  }
-};
-
-Parser.prototype._handleIHDR = function(length) {
-  this.read(length, this._parseIHDR.bind(this));
-};
-Parser.prototype._parseIHDR = function(data) {
-
-  this._crc.write(data);
-
-  var width = data.readUInt32BE(0);
-  var height = data.readUInt32BE(4);
-  var depth = data[8];
-  var colorType = data[9]; // bits: 1 palette, 2 color, 4 alpha
-  var compr = data[10];
-  var filter = data[11];
-  var interlace = data[12];
-
-  // console.log('    width', width, 'height', height,
-  //     'depth', depth, 'colorType', colorType,
-  //     'compr', compr, 'filter', filter, 'interlace', interlace
-  // );
-
-  if (depth !== 8 && depth !== 4 && depth !== 2 && depth !== 1 && depth !== 16) {
-    this.error(new Error('Unsupported bit depth ' + depth));
-    return;
-  }
-  if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) {
-    this.error(new Error('Unsupported color type'));
-    return;
-  }
-  if (compr !== 0) {
-    this.error(new Error('Unsupported compression method'));
-    return;
-  }
-  if (filter !== 0) {
-    this.error(new Error('Unsupported filter method'));
-    return;
-  }
-  if (interlace !== 0 && interlace !== 1) {
-    this.error(new Error('Unsupported interlace method'));
-    return;
-  }
-
-  this._colorType = colorType;
-
-  var bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType];
-
-  this._hasIHDR = true;
-
-  this.metadata({
-    width: width,
-    height: height,
-    depth: depth,
-    interlace: Boolean(interlace),
-    palette: Boolean(colorType & constants.COLORTYPE_PALETTE),
-    color: Boolean(colorType & constants.COLORTYPE_COLOR),
-    alpha: Boolean(colorType & constants.COLORTYPE_ALPHA),
-    bpp: bpp,
-    colorType: colorType
-  });
-
-  this._handleChunkEnd();
-};
-
-
-Parser.prototype._handlePLTE = function(length) {
-  this.read(length, this._parsePLTE.bind(this));
-};
-Parser.prototype._parsePLTE = function(data) {
-
-  this._crc.write(data);
-
-  var entries = Math.floor(data.length / 3);
-  // console.log('Palette:', entries);
-
-  for (var i = 0; i < entries; i++) {
-    this._palette.push([
-      data[i * 3],
-      data[i * 3 + 1],
-      data[i * 3 + 2],
-      0xff
-    ]);
-  }
-
-  this.palette(this._palette);
-
-  this._handleChunkEnd();
-};
-
-Parser.prototype._handleTRNS = function(length) {
-  this.simpleTransparency();
-  this.read(length, this._parseTRNS.bind(this));
-};
-Parser.prototype._parseTRNS = function(data) {
-
-  this._crc.write(data);
-
-  // palette
-  if (this._colorType === constants.COLORTYPE_PALETTE_COLOR) {
-    if (this._palette.length === 0) {
-      this.error(new Error('Transparency chunk must be after palette'));
-      return;
-    }
-    if (data.length > this._palette.length) {
-      this.error(new Error('More transparent colors than palette size'));
-      return;
-    }
-    for (var i = 0; i < data.length; i++) {
-      this._palette[i][3] = data[i];
-    }
-    this.palette(this._palette);
-  }
-
-  // for colorType 0 (grayscale) and 2 (rgb)
-  // there might be one gray/color defined as transparent
-  if (this._colorType === constants.COLORTYPE_GRAYSCALE) {
-    // grey, 2 bytes
-    this.transColor([data.readUInt16BE(0)]);
-  }
-  if (this._colorType === constants.COLORTYPE_COLOR) {
-    this.transColor([data.readUInt16BE(0), data.readUInt16BE(2), data.readUInt16BE(4)]);
-  }
-
-  this._handleChunkEnd();
-};
-
-Parser.prototype._handleGAMA = function(length) {
-  this.read(length, this._parseGAMA.bind(this));
-};
-Parser.prototype._parseGAMA = function(data) {
-
-  this._crc.write(data);
-  this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION);
-
-  this._handleChunkEnd();
-};
-
-Parser.prototype._handleIDAT = function(length) {
-  if (!this._emittedHeadersFinished) {
-    this._emittedHeadersFinished = true;
-    this.headersFinished();
-  }
-  this.read(-length, this._parseIDAT.bind(this, length));
-};
-Parser.prototype._parseIDAT = function(length, data) {
-
-  this._crc.write(data);
-
-  if (this._colorType === constants.COLORTYPE_PALETTE_COLOR && this._palette.length === 0) {
-    throw new Error('Expected palette not found');
-  }
-
-  this.inflateData(data);
-  var leftOverLength = length - data.length;
-
-  if (leftOverLength > 0) {
-    this._handleIDAT(leftOverLength);
-  }
-  else {
-    this._handleChunkEnd();
-  }
-};
-
-Parser.prototype._handleIEND = function(length) {
-  this.read(length, this._parseIEND.bind(this));
-};
-Parser.prototype._parseIEND = function(data) {
-
-  this._crc.write(data);
-
-  this._hasIEND = true;
-  this._handleChunkEnd();
-
-  if (this.finished) {
-    this.finished();
-  }
-};
-
-}).call(this,require("buffer").Buffer)
-},{"./constants":4,"./crc":5,"buffer":32}],19:[function(require,module,exports){
-'use strict';
-
-
-var parse = require('./parser-sync');
-var pack = require('./packer-sync');
-
-
-exports.read = function(buffer, options) {
-
-  return parse(buffer, options || {});
-};
-
-exports.write = function(png, options) {
-
-  return pack(png, options);
-};
-
-},{"./packer-sync":13,"./parser-sync":17}],20:[function(require,module,exports){
-(function (process,Buffer){
-'use strict';
-
-var util = require('util');
-var Stream = require('stream');
-var Parser = require('./parser-async');
-var Packer = require('./packer-async');
-var PNGSync = require('./png-sync');
-
-
-var PNG = exports.PNG = function(options) {
-  Stream.call(this);
-
-  options = options || {}; // eslint-disable-line no-param-reassign
-
-  // coerce pixel dimensions to integers (also coerces undefined -> 0):
-  this.width = options.width | 0;
-  this.height = options.height | 0;
-
-  this.data = this.width > 0 && this.height > 0 ?
-    new Buffer(4 * this.width * this.height) : null;
-
-  if (options.fill && this.data) {
-    this.data.fill(0);
-  }
-
-  this.gamma = 0;
-  this.readable = this.writable = true;
-
-  this._parser = new Parser(options);
-
-  this._parser.on('error', this.emit.bind(this, 'error'));
-  this._parser.on('close', this._handleClose.bind(this));
-  this._parser.on('metadata', this._metadata.bind(this));
-  this._parser.on('gamma', this._gamma.bind(this));
-  this._parser.on('parsed', function(data) {
-    this.data = data;
-    this.emit('parsed', data);
-  }.bind(this));
-
-  this._packer = new Packer(options);
-  this._packer.on('data', this.emit.bind(this, 'data'));
-  this._packer.on('end', this.emit.bind(this, 'end'));
-  this._parser.on('close', this._handleClose.bind(this));
-  this._packer.on('error', this.emit.bind(this, 'error'));
-
-};
-util.inherits(PNG, Stream);
-
-PNG.sync = PNGSync;
-
-PNG.prototype.pack = function() {
-
-  if (!this.data || !this.data.length) {
-    this.emit('error', 'No data provided');
-    return this;
-  }
-
-  process.nextTick(function() {
-    this._packer.pack(this.data, this.width, this.height, this.gamma);
-  }.bind(this));
-
-  return this;
-};
-
-
-PNG.prototype.parse = function(data, callback) {
-
-  if (callback) {
-    var onParsed, onError;
-
-    onParsed = function(parsedData) {
-      this.removeListener('error', onError);
-
-      this.data = parsedData;
-      callback(null, this);
-    }.bind(this);
-
-    onError = function(err) {
-      this.removeListener('parsed', onParsed);
-
-      callback(err, null);
-    }.bind(this);
-
-    this.once('parsed', onParsed);
-    this.once('error', onError);
-  }
-
-  this.end(data);
-  return this;
-};
-
-PNG.prototype.write = function(data) {
-  this._parser.write(data);
-  return true;
-};
-
-PNG.prototype.end = function(data) {
-  this._parser.end(data);
-};
-
-PNG.prototype._metadata = function(metadata) {
-  this.width = metadata.width;
-  this.height = metadata.height;
-
-  this.emit('metadata', metadata);
-};
-
-PNG.prototype._gamma = function(gamma) {
-  this.gamma = gamma;
-};
-
-PNG.prototype._handleClose = function() {
-  if (!this._parser.writable && !this._packer.readable) {
-    this.emit('close');
-  }
-};
-
-
-PNG.bitblt = function(src, dst, srcX, srcY, width, height, deltaX, deltaY) { // eslint-disable-line max-params
-  // coerce pixel dimensions to integers (also coerces undefined -> 0):
-  /* eslint-disable no-param-reassign */
-  srcX |= 0;
-  srcY |= 0;
-  width |= 0;
-  height |= 0;
-  deltaX |= 0;
-  deltaY |= 0;
-  /* eslint-enable no-param-reassign */
-
-  if (srcX > src.width || srcY > src.height || srcX + width > src.width || srcY + height > src.height) {
-    throw new Error('bitblt reading outside image');
-  }
-
-  if (deltaX > dst.width || deltaY > dst.height || deltaX + width > dst.width || deltaY + height > dst.height) {
-    throw new Error('bitblt writing outside image');
-  }
-
-  for (var y = 0; y < height; y++) {
-    src.data.copy(dst.data,
-      ((deltaY + y) * dst.width + deltaX) << 2,
-      ((srcY + y) * src.width + srcX) << 2,
-      ((srcY + y) * src.width + srcX + width) << 2
-    );
-  }
-};
-
-
-PNG.prototype.bitblt = function(dst, srcX, srcY, width, height, deltaX, deltaY) { // eslint-disable-line max-params
-
-  PNG.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY);
-  return this;
-};
-
-PNG.adjustGamma = function(src) {
-  if (src.gamma) {
-    for (var y = 0; y < src.height; y++) {
-      for (var x = 0; x < src.width; x++) {
-        var idx = (src.width * y + x) << 2;
-
-        for (var i = 0; i < 3; i++) {
-          var sample = src.data[idx + i] / 255;
-          sample = Math.pow(sample, 1 / 2.2 / src.gamma);
-          src.data[idx + i] = Math.round(sample * 255);
-        }
-      }
-    }
-    src.gamma = 0;
-  }
-};
-
-PNG.prototype.adjustGamma = function() {
-  PNG.adjustGamma(this);
-};
-
-}).call(this,require('_process'),require("buffer").Buffer)
-},{"./packer-async":12,"./parser-async":16,"./png-sync":19,"_process":51,"buffer":32,"stream":64,"util":69}],21:[function(require,module,exports){
-(function (process,Buffer){
-'use strict';
-
-var assert = require('assert').ok;
-var zlib = require('zlib');
-var util = require('util');
-
-var kMaxLength = require('buffer').kMaxLength;
-
-function Inflate(opts) {
-  if (!(this instanceof Inflate)) {
-    return new Inflate(opts);
-  }
-
-  if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) {
-    opts.chunkSize = zlib.Z_MIN_CHUNK;
-  }
-
-  zlib.Inflate.call(this, opts);
-
-  // Node 8 --> 9 compatibility check
-  this._offset = this._offset === undefined ? this._outOffset : this._offset;
-  this._buffer = this._buffer || this._outBuffer;
-
-  if (opts && opts.maxLength != null) {
-    this._maxLength = opts.maxLength;
-  }
-}
-
-function createInflate(opts) {
-  return new Inflate(opts);
-}
-
-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;
-}
-
-Inflate.prototype._processChunk = function(chunk, flushFlag, asyncCb) {
-  if (typeof asyncCb === 'function') {
-    return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb);
-  }
-
-  var self = this;
-
-  var availInBefore = chunk && chunk.length;
-  var availOutBefore = this._chunkSize - this._offset;
-  var leftToInflate = this._maxLength;
-  var inOff = 0;
-
-  var buffers = [];
-  var nread = 0;
-
-  var error;
-  this.on('error', function(err) {
-    error = err;
-  });
-
-  function handleChunk(availInAfter, availOutAfter) {
-    if (self._hadError) {
-      return;
-    }
-
-    var have = availOutBefore - availOutAfter;
-    assert(have >= 0, 'have should not go down');
-
-    if (have > 0) {
-      var out = self._buffer.slice(self._offset, self._offset + have);
-      self._offset += have;
-
-      if (out.length > leftToInflate) {
-        out = out.slice(0, leftToInflate);
-      }
-
-      buffers.push(out);
-      nread += out.length;
-      leftToInflate -= out.length;
-
-      if (leftToInflate === 0) {
-        return false;
-      }
-    }
-
-    if (availOutAfter === 0 || self._offset >= self._chunkSize) {
-      availOutBefore = self._chunkSize;
-      self._offset = 0;
-      self._buffer = Buffer.allocUnsafe(self._chunkSize);
-    }
-
-    if (availOutAfter === 0) {
-      inOff += (availInBefore - availInAfter);
-      availInBefore = availInAfter;
-
-      return true;
-    }
-
-    return false;
-  }
-
-  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
-    // Node 8 --> 9 compatibility check
-    res = res || this._writeState;
-  } while (!this._hadError && handleChunk(res[0], res[1]));
-
-  if (this._hadError) {
-    throw error;
-  }
-
-  if (nread >= kMaxLength) {
-    _close(this);
-    throw new RangeError('Cannot create final Buffer. It would be larger than 0x' + kMaxLength.toString(16) + ' bytes');
-  }
-
-  var buf = Buffer.concat(buffers, nread);
-  _close(this);
-
-  return buf;
-};
-
-util.inherits(Inflate, zlib.Inflate);
-
-function zlibBufferSync(engine, buffer) {
-  if (typeof buffer === 'string') {
-    buffer = Buffer.from(buffer);
-  }
-  if (!(buffer instanceof Buffer)) {
-    throw new TypeError('Not a string or buffer');
-  }
-
-  var flushFlag = engine._finishFlushFlag;
-  if (flushFlag == null) {
-    flushFlag = zlib.Z_FINISH;
-  }
-
-  return engine._processChunk(buffer, flushFlag);
-}
-
-function inflateSync(buffer, opts) {
-  return zlibBufferSync(new Inflate(opts), buffer);
-}
-
-module.exports = exports = inflateSync;
-exports.Inflate = Inflate;
-exports.createInflate = createInflate;
-exports.inflateSync = inflateSync;
-
-}).call(this,require('_process'),require("buffer").Buffer)
-},{"_process":51,"assert":23,"buffer":32,"util":69,"zlib":30}],22:[function(require,module,exports){
-'use strict';
-
-var SyncReader = module.exports = function(buffer) {
-
-  this._buffer = buffer;
-  this._reads = [];
-};
-
-SyncReader.prototype.read = function(length, callback) {
-
-  this._reads.push({
-    length: Math.abs(length), // if length < 0 then at most this length
-    allowLess: length < 0,
-    func: callback
-  });
-};
-
-SyncReader.prototype.process = function() {
-
-  // as long as there is any data and read requests
-  while (this._reads.length > 0 && this._buffer.length) {
-
-    var read = this._reads[0];
-
-    if (this._buffer.length && (this._buffer.length >= read.length || read.allowLess)) {
-
-      // ok there is any data so that we can satisfy this request
-      this._reads.shift(); // == read
-
-      var buf = this._buffer;
-
-      this._buffer = buf.slice(read.length);
-
-      read.func.call(this, buf.slice(0, read.length));
-
-    }
-    else {
-      break;
-    }
-
-  }
-
-  if (this._reads.length > 0) {
-    return new Error('There are some read requests waitng on finished stream');
-  }
-
-  if (this._buffer.length > 0) {
-    return new Error('unrecognised content at end of stream');
-  }
-
-};
-
-},{}],23:[function(require,module,exports){
-(function (global){
-'use strict';
-
-// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
-// original notice:
-
+!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).png=t()}}((function(){return function t(e,r,n){function i(a,o){if(!r[a]){if(!e[a]){var h="function"==typeof require&&require;if(!o&&h)return h(a,!0);if(s)return s(a,!0);var f=new Error("Cannot find module '"+a+"'");throw f.code="MODULE_NOT_FOUND",f}var l=r[a]={exports:{}};e[a][0].call(l.exports,(function(t){return i(e[a][1][t]||t)}),l,l.exports,t,e,r,n)}return r[a].exports}for(var s="function"==typeof require&&require,a=0;a<n.length;a++)i(n[a]);return i}({1:[function(t,e,r){(function(e){"use strict";var n=t("./interlace"),i=[function(){},function(t,e,r,n){if(n===e.length)throw new Error("Ran out of data");var i=e[n];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=255},function(t,e,r,n){if(n+1>=e.length)throw new Error("Ran out of data");var i=e[n];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=e[n+1]},function(t,e,r,n){if(n+2>=e.length)throw new Error("Ran out of data");t[r]=e[n],t[r+1]=e[n+1],t[r+2]=e[n+2],t[r+3]=255},function(t,e,r,n){if(n+3>=e.length)throw new Error("Ran out of data");t[r]=e[n],t[r+1]=e[n+1],t[r+2]=e[n+2],t[r+3]=e[n+3]}],s=[function(){},function(t,e,r,n){var i=e[0];t[r]=i,t[r+1]=i,t[r+2]=i,t[r+3]=n},function(t,e,r){var n=e[0];t[r]=n,t[r+1]=n,t[r+2]=n,t[r+3]=e[1]},function(t,e,r,n){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=n},function(t,e,r){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=e[3]}];function a(t,e,r,n,s,a){for(var o=t.width,h=t.height,f=t.index,l=0;l<h;l++)for(var u=0;u<o;u++){var c=r(u,l,f);i[n](e,s,c,a),a+=n}return a}function o(t,e,r,n,i,a){for(var o=t.width,h=t.height,f=t.index,l=0;l<h;l++){for(var u=0;u<o;u++){var c=i.get(n),d=r(u,l,f);s[n](e,c,d,a)}i.resetAfterLine()}}r.dataToBitMap=function(t,r){var i,s=r.width,h=r.height,f=r.depth,l=r.bpp,u=r.interlace;if(8!==f)var c=function(t,e){var r=[],n=0;function i(){if(n===t.length)throw new Error("Ran out of data");var i,s,a,o,h,f,l,u,c=t[n];switch(n++,e){default:throw new Error("unrecognised depth");case 16:l=t[n],n++,r.push((c<<8)+l);break;case 4:l=15&c,u=c>>4,r.push(u,l);break;case 2:h=3&c,f=c>>2&3,l=c>>4&3,u=c>>6&3,r.push(u,l,f,h);break;case 1:i=1&c,s=c>>1&1,a=c>>2&1,o=c>>3&1,h=c>>4&1,f=c>>5&1,l=c>>6&1,u=c>>7&1,r.push(u,l,f,h,o,a,s,i)}}return{get:function(t){for(;r.length<t;)i();var e=r.slice(0,t);return r=r.slice(t),e},resetAfterLine:function(){r.length=0},end:function(){if(n!==t.length)throw new Error("extra data found")}}}(t,f);i=f<=8?new e(s*h*4):new Uint16Array(s*h*4);var d,p,_=Math.pow(2,f)-1,g=0;if(u)d=n.getImagePasses(s,h),p=n.getInterlaceIterator(s,h);else{var b=0;p=function(){var t=b;return b+=4,t},d=[{width:s,height:h}]}for(var w=0;w<d.length;w++)8===f?g=a(d[w],i,p,l,t,g):o(d[w],i,p,l,c,_);if(8===f){if(g!==t.length)throw new Error("extra data found")}else c.end();return i}}).call(this,t("buffer").Buffer)},{"./interlace":11,buffer:32}],2:[function(t,e,r){(function(r){"use strict";var n=t("./constants");e.exports=function(t,e,i,s){var a,o=-1!==[n.COLORTYPE_COLOR_ALPHA,n.COLORTYPE_ALPHA].indexOf(s.colorType);if(s.colorType===s.inputColorType){var h=(a=new ArrayBuffer(2),new DataView(a).setInt16(0,256,!0),256!==new Int16Array(a)[0]);if(8===s.bitDepth||16===s.bitDepth&&h)return t}var f=16!==s.bitDepth?t:new Uint16Array(t.buffer),l=255,u=n.COLORTYPE_TO_BPP_MAP[s.inputColorType];4!==u||s.inputHasAlpha||(u=3);var c=n.COLORTYPE_TO_BPP_MAP[s.colorType];16===s.bitDepth&&(l=65535,c*=2);var d=new r(e*i*c),p=0,_=0,g=s.bgColor||{};function b(){var t,e,r,i=l;switch(s.inputColorType){case n.COLORTYPE_COLOR_ALPHA:i=f[p+3],t=f[p],e=f[p+1],r=f[p+2];break;case n.COLORTYPE_COLOR:t=f[p],e=f[p+1],r=f[p+2];break;case n.COLORTYPE_ALPHA:i=f[p+1],e=t=f[p],r=t;break;case n.COLORTYPE_GRAYSCALE:e=t=f[p],r=t;break;default:throw new Error("input color type:"+s.inputColorType+" is not supported at present")}return s.inputHasAlpha&&(o||(i/=l,t=Math.min(Math.max(Math.round((1-i)*g.red+i*t),0),l),e=Math.min(Math.max(Math.round((1-i)*g.green+i*e),0),l),r=Math.min(Math.max(Math.round((1-i)*g.blue+i*r),0),l))),{red:t,green:e,blue:r,alpha:i}}void 0===g.red&&(g.red=l),void 0===g.green&&(g.green=l),void 0===g.blue&&(g.blue=l);for(var w=0;w<i;w++)for(var m=0;m<e;m++){var y=b();switch(s.colorType){case n.COLORTYPE_COLOR_ALPHA:case n.COLORTYPE_COLOR:8===s.bitDepth?(d[_]=y.red,d[_+1]=y.green,d[_+2]=y.blue,o&&(d[_+3]=y.alpha)):(d.writeUInt16BE(y.red,_),d.writeUInt16BE(y.green,_+2),d.writeUInt16BE(y.blue,_+4),o&&d.writeUInt16BE(y.alpha,_+6));break;case n.COLORTYPE_ALPHA:case n.COLORTYPE_GRAYSCALE:var v=(y.red+y.green+y.blue)/3;8===s.bitDepth?(d[_]=v,o&&(d[_+1]=y.alpha)):(d.writeUInt16BE(v,_),o&&d.writeUInt16BE(y.alpha,_+2));break;default:throw new Error("unrecognised color Type "+s.colorType)}p+=u,_+=c}return d}}).call(this,t("buffer").Buffer)},{"./constants":4,buffer:32}],3:[function(t,e,r){(function(r,n){"use strict";var i=t("util"),s=t("stream"),a=e.exports=function(){s.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};i.inherits(a,s),a.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),r.nextTick(function(){this._process(),this._paused&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))},a.prototype.write=function(t,e){return this.writable?(r=n.isBuffer(t)?t:new n(t,e||this._encoding),this._buffers.push(r),this._buffered+=r.length,this._process(),this._reads&&0===this._reads.length&&(this._paused=!0),this.writable&&!this._paused):(this.emit("error",new Error("Stream not writable")),!1);var r},a.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(0===this._buffers.length?this._end():(this._buffers.push(null),this._process()))},a.prototype.destroySoon=a.prototype.end,a.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()},a.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))},a.prototype._processReadAllowingLess=function(t){this._reads.shift();var e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))},a.prototype._processRead=function(t){this._reads.shift();for(var e=0,r=0,i=new n(t.length);e<t.length;){var s=this._buffers[r++],a=Math.min(s.length,t.length-e);s.copy(i,e,0,a),e+=a,a!==s.length&&(this._buffers[--r]=s.slice(a))}r>0&&this._buffers.splice(0,r),this._buffered-=t.length,t.func.call(this,i)},a.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){var t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else{if(!(this._buffered>=t.length))break;this._processRead(t)}}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}}).call(this,t("_process"),t("buffer").Buffer)},{_process:51,buffer:32,stream:64,util:69}],4:[function(t,e,r){"use strict";e.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}},{}],5:[function(t,e,r){"use strict";var n=[];!function(){for(var t=0;t<256;t++){for(var e=t,r=0;r<8;r++)1&e?e=3988292384^e>>>1:e>>>=1;n[t]=e}}();var i=e.exports=function(){this._crc=-1};i.prototype.write=function(t){for(var e=0;e<t.length;e++)this._crc=n[255&(this._crc^t[e])]^this._crc>>>8;return!0},i.prototype.crc32=function(){return-1^this._crc},i.crc32=function(t){for(var e=-1,r=0;r<t.length;r++)e=n[255&(e^t[r])]^e>>>8;return-1^e}},{}],6:[function(t,e,r){(function(r){"use strict";var n=t("./paeth-predictor");var i={0:function(t,e,r,n,i){for(var s=0;s<r;s++)n[i+s]=t[e+s]},1:function(t,e,r,n,i,s){for(var a=0;a<r;a++){var o=a>=s?t[e+a-s]:0,h=t[e+a]-o;n[i+a]=h}},2:function(t,e,r,n,i){for(var s=0;s<r;s++){var a=e>0?t[e+s-r]:0,o=t[e+s]-a;n[i+s]=o}},3:function(t,e,r,n,i,s){for(var a=0;a<r;a++){var o=a>=s?t[e+a-s]:0,h=e>0?t[e+a-r]:0,f=t[e+a]-(o+h>>1);n[i+a]=f}},4:function(t,e,r,i,s,a){for(var o=0;o<r;o++){var h=o>=a?t[e+o-a]:0,f=e>0?t[e+o-r]:0,l=e>0&&o>=a?t[e+o-(r+a)]:0,u=t[e+o]-n(h,f,l);i[s+o]=u}}},s={0:function(t,e,r){for(var n=0,i=e+r,s=e;s<i;s++)n+=Math.abs(t[s]);return n},1:function(t,e,r,n){for(var i=0,s=0;s<r;s++){var a=s>=n?t[e+s-n]:0,o=t[e+s]-a;i+=Math.abs(o)}return i},2:function(t,e,r){for(var n=0,i=e+r,s=e;s<i;s++){var a=e>0?t[s-r]:0,o=t[s]-a;n+=Math.abs(o)}return n},3:function(t,e,r,n){for(var i=0,s=0;s<r;s++){var a=s>=n?t[e+s-n]:0,o=e>0?t[e+s-r]:0,h=t[e+s]-(a+o>>1);i+=Math.abs(h)}return i},4:function(t,e,r,i){for(var s=0,a=0;a<r;a++){var o=a>=i?t[e+a-i]:0,h=e>0?t[e+a-r]:0,f=e>0&&a>=i?t[e+a-(r+i)]:0,l=t[e+a]-n(o,h,f);s+=Math.abs(l)}return s}};e.exports=function(t,e,n,a,o){var h;if("filterType"in a&&-1!==a.filterType){if("number"!=typeof a.filterType)throw new Error("unrecognised filter types");h=[a.filterType]}else h=[0,1,2,3,4];16===a.bitDepth&&(o*=2);for(var f=e*o,l=0,u=0,c=new r((f+1)*n),d=h[0],p=0;p<n;p++){if(h.length>1)for(var _=1/0,g=0;g<h.length;g++){var b=s[h[g]](t,u,f,o);b<_&&(d=h[g],_=b)}c[l]=d,l++,i[d](t,u,f,c,l,o),l+=f,u+=f}return c}}).call(this,t("buffer").Buffer)},{"./paeth-predictor":15,buffer:32}],7:[function(t,e,r){(function(r){"use strict";var n=t("util"),i=t("./chunkstream"),s=t("./filter-parse"),a=e.exports=function(t){i.call(this);var e=[],n=this;this._filter=new s(t,{read:this.read.bind(this),write:function(t){e.push(t)},complete:function(){n.emit("complete",r.concat(e))}}),this._filter.start()};n.inherits(a,i)}).call(this,t("buffer").Buffer)},{"./chunkstream":3,"./filter-parse":9,buffer:32,util:69}],8:[function(t,e,r){(function(e){"use strict";var n=t("./sync-reader"),i=t("./filter-parse");r.process=function(t,r){var s=[],a=new n(t);return new i(r,{read:a.read.bind(a),write:function(t){s.push(t)},complete:function(){}}).start(),a.process(),e.concat(s)}}).call(this,t("buffer").Buffer)},{"./filter-parse":9,"./sync-reader":22,buffer:32}],9:[function(t,e,r){(function(r){"use strict";var n=t("./interlace"),i=t("./paeth-predictor");function s(t,e,r){var n=t*e;return 8!==r&&(n=Math.ceil(n/(8/r))),n}var a=e.exports=function(t,e){var r=t.width,i=t.height,a=t.interlace,o=t.bpp,h=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],a)for(var f=n.getImagePasses(r,i),l=0;l<f.length;l++)this._images.push({byteWidth:s(f[l].width,o,h),height:f[l].height,lineIndex:0});else this._images.push({byteWidth:s(r,o,h),height:i,lineIndex:0});this._xComparison=8===h?o:16===h?2*o:1};a.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))},a.prototype._unFilterType1=function(t,e,r){for(var n=this._xComparison,i=n-1,s=0;s<r;s++){var a=t[1+s],o=s>i?e[s-n]:0;e[s]=a+o}},a.prototype._unFilterType2=function(t,e,r){for(var n=this._lastLine,i=0;i<r;i++){var s=t[1+i],a=n?n[i]:0;e[i]=s+a}},a.prototype._unFilterType3=function(t,e,r){for(var n=this._xComparison,i=n-1,s=this._lastLine,a=0;a<r;a++){var o=t[1+a],h=s?s[a]:0,f=a>i?e[a-n]:0,l=Math.floor((f+h)/2);e[a]=o+l}},a.prototype._unFilterType4=function(t,e,r){for(var n=this._xComparison,s=n-1,a=this._lastLine,o=0;o<r;o++){var h=t[1+o],f=a?a[o]:0,l=o>s?e[o-n]:0,u=o>s&&a?a[o-n]:0,c=i(l,f,u);e[o]=h+c}},a.prototype._reverseFilterLine=function(t){var e,n=t[0],i=this._images[this._imageIndex],s=i.byteWidth;if(0===n)e=t.slice(1,s+1);else switch(e=new r(s),n){case 1:this._unFilterType1(t,e,s);break;case 2:this._unFilterType2(t,e,s);break;case 3:this._unFilterType3(t,e,s);break;case 4:this._unFilterType4(t,e,s);break;default:throw new Error("Unrecognised filter type - "+n)}this.write(e),i.lineIndex++,i.lineIndex>=i.height?(this._lastLine=null,this._imageIndex++,i=this._images[this._imageIndex]):this._lastLine=e,i?this.read(i.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}}).call(this,t("buffer").Buffer)},{"./interlace":11,"./paeth-predictor":15,buffer:32}],10:[function(t,e,r){(function(t){"use strict";e.exports=function(e,r){var n=r.depth,i=r.width,s=r.height,a=r.colorType,o=r.transColor,h=r.palette,f=e;return 3===a?function(t,e,r,n,i){for(var s=0,a=0;a<n;a++)for(var o=0;o<r;o++){var h=i[t[s]];if(!h)throw new Error("index "+t[s]+" not in palette");for(var f=0;f<4;f++)e[s+f]=h[f];s+=4}}(e,f,i,s,h):(o&&function(t,e,r,n,i){for(var s=0,a=0;a<n;a++)for(var o=0;o<r;o++){var h=!1;if(1===i.length?i[0]===t[s]&&(h=!0):i[0]===t[s]&&i[1]===t[s+1]&&i[2]===t[s+2]&&(h=!0),h)for(var f=0;f<4;f++)e[s+f]=0;s+=4}}(e,f,i,s,o),8!==n&&(16===n&&(f=new t(i*s*4)),function(t,e,r,n,i){for(var s=Math.pow(2,i)-1,a=0,o=0;o<n;o++)for(var h=0;h<r;h++){for(var f=0;f<4;f++)e[a+f]=Math.floor(255*t[a+f]/s+.5);a+=4}}(e,f,i,s,n))),f}}).call(this,t("buffer").Buffer)},{buffer:32}],11:[function(t,e,r){"use strict";var n=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];r.getImagePasses=function(t,e){for(var r=[],i=t%8,s=e%8,a=(t-i)/8,o=(e-s)/8,h=0;h<n.length;h++){for(var f=n[h],l=a*f.x.length,u=o*f.y.length,c=0;c<f.x.length&&f.x[c]<i;c++)l++;for(c=0;c<f.y.length&&f.y[c]<s;c++)u++;l>0&&u>0&&r.push({width:l,height:u,index:h})}return r},r.getInterlaceIterator=function(t){return function(e,r,i){var s=e%n[i].x.length,a=(e-s)/n[i].x.length*8+n[i].x[s],o=r%n[i].y.length;return 4*a+((r-o)/n[i].y.length*8+n[i].y[o])*t*4}}},{}],12:[function(t,e,r){(function(r){"use strict";var n=t("util"),i=t("stream"),s=t("./constants"),a=t("./packer"),o=e.exports=function(t){i.call(this);var e=t||{};this._packer=new a(e),this._deflate=this._packer.createDeflate(),this.readable=!0};n.inherits(o,i),o.prototype.pack=function(t,e,n,i){this.emit("data",new r(s.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),i&&this.emit("data",this._packer.packGAMA(i));var a=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(t){this.emit("data",this._packer.packIDAT(t))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(a)}}).call(this,t("buffer").Buffer)},{"./constants":4,"./packer":14,buffer:32,stream:64,util:69}],13:[function(t,e,r){(function(r){"use strict";var n=!0,i=t("zlib");i.deflateSync||(n=!1);var s=t("./constants"),a=t("./packer");e.exports=function(t,e){if(!n)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");var o=new a(e||{}),h=[];h.push(new r(s.PNG_SIGNATURE)),h.push(o.packIHDR(t.width,t.height)),t.gamma&&h.push(o.packGAMA(t.gamma));var f=o.filterData(t.data,t.width,t.height),l=i.deflateSync(f,o.getDeflateOptions());if(f=null,!l||!l.length)throw new Error("bad png - invalid compressed data response");return h.push(o.packIDAT(l)),h.push(o.packIEND()),r.concat(h)}}).call(this,t("buffer").Buffer)},{"./constants":4,"./packer":14,buffer:32,zlib:30}],14:[function(t,e,r){(function(r){"use strict";var n=t("./constants"),i=t("./crc"),s=t("./bitpacker"),a=t("./filter-pack"),o=t("zlib"),h=e.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32768,t.deflateLevel=null!=t.deflateLevel?t.deflateLevel:9,t.deflateStrategy=null!=t.deflateStrategy?t.deflateStrategy:3,t.inputHasAlpha=null==t.inputHasAlpha||t.inputHasAlpha,t.deflateFactory=t.deflateFactory||o.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType="number"==typeof t.colorType?t.colorType:n.COLORTYPE_COLOR_ALPHA,t.inputColorType="number"==typeof t.inputColorType?t.inputColorType:n.COLORTYPE_COLOR_ALPHA,-1===[n.COLORTYPE_GRAYSCALE,n.COLORTYPE_COLOR,n.COLORTYPE_COLOR_ALPHA,n.COLORTYPE_ALPHA].indexOf(t.colorType))throw new Error("option color type:"+t.colorType+" is not supported at present");if(-1===[n.COLORTYPE_GRAYSCALE,n.COLORTYPE_COLOR,n.COLORTYPE_COLOR_ALPHA,n.COLORTYPE_ALPHA].indexOf(t.inputColorType))throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(8!==t.bitDepth&&16!==t.bitDepth)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};h.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}},h.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())},h.prototype.filterData=function(t,e,r){var i=s(t,e,r,this._options),o=n.COLORTYPE_TO_BPP_MAP[this._options.colorType];return a(i,e,r,this._options,o)},h.prototype._packChunk=function(t,e){var n=e?e.length:0,s=new r(n+12);return s.writeUInt32BE(n,0),s.writeUInt32BE(t,4),e&&e.copy(s,8),s.writeInt32BE(i.crc32(s.slice(4,s.length-4)),s.length-4),s},h.prototype.packGAMA=function(t){var e=new r(4);return e.writeUInt32BE(Math.floor(t*n.GAMMA_DIVISION),0),this._packChunk(n.TYPE_gAMA,e)},h.prototype.packIHDR=function(t,e){var i=new r(13);return i.writeUInt32BE(t,0),i.writeUInt32BE(e,4),i[8]=this._options.bitDepth,i[9]=this._options.colorType,i[10]=0,i[11]=0,i[12]=0,this._packChunk(n.TYPE_IHDR,i)},h.prototype.packIDAT=function(t){return this._packChunk(n.TYPE_IDAT,t)},h.prototype.packIEND=function(){return this._packChunk(n.TYPE_IEND,null)}}).call(this,t("buffer").Buffer)},{"./bitpacker":2,"./constants":4,"./crc":5,"./filter-pack":6,buffer:32,zlib:30}],15:[function(t,e,r){"use strict";e.exports=function(t,e,r){var n=t+e-r,i=Math.abs(n-t),s=Math.abs(n-e),a=Math.abs(n-r);return i<=s&&i<=a?t:s<=a?e:r}},{}],16:[function(t,e,r){"use strict";var n=t("util"),i=t("zlib"),s=t("./chunkstream"),a=t("./filter-parse-async"),o=t("./parser"),h=t("./bitmapper"),f=t("./format-normaliser"),l=e.exports=function(t){s.call(this),this._parser=new o(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};n.inherits(l,s),l.prototype._handleError=function(t){this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",(function(){}))),this.errord=!0},l.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=i.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{var e=(1+(this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3))*this._bitmapInfo.height,r=Math.max(e,i.Z_MIN_CHUNK);this._inflate=i.createInflate({chunkSize:r});var n=e,s=this.emit.bind(this,"error");this._inflate.on("error",(function(t){n&&s(t)})),this._filter.on("complete",this._complete.bind(this));var a=this._filter.write.bind(this._filter);this._inflate.on("data",(function(t){n&&(t.length>n&&(t=t.slice(0,n)),n-=t.length,a(t))})),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)},l.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new a(this._bitmapInfo)},l.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t},l.prototype._handlePalette=function(t){this._bitmapInfo.palette=t},l.prototype._simpleTransparency=function(){this._metaData.alpha=!0},l.prototype._headersFinished=function(){this.emit("metadata",this._metaData)},l.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"),this.destroySoon())},l.prototype._complete=function(t){if(!this.errord){try{var e=h.dataToBitMap(t,this._bitmapInfo),r=f(e,this._bitmapInfo);e=null}catch(t){return void this._handleError(t)}this.emit("parsed",r)}}},{"./bitmapper":1,"./chunkstream":3,"./filter-parse-async":7,"./format-normaliser":10,"./parser":18,util:69,zlib:30}],17:[function(t,e,r){(function(r){"use strict";var n=!0,i=t("zlib"),s=t("./sync-inflate");i.deflateSync||(n=!1);var a=t("./sync-reader"),o=t("./filter-parse-sync"),h=t("./parser"),f=t("./bitmapper"),l=t("./format-normaliser");e.exports=function(t,e){if(!n)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");var u,c,d;var p=[];var _=new a(t);if(new h(e,{read:_.read.bind(_),error:function(t){u=t},metadata:function(t){c=t},gamma:function(t){d=t},palette:function(t){c.palette=t},transColor:function(t){c.transColor=t},inflateData:function(t){p.push(t)},simpleTransparency:function(){c.alpha=!0}}).start(),_.process(),u)throw u;var g,b=r.concat(p);if(p.length=0,c.interlace)g=i.inflateSync(b);else{var w=(1+(c.width*c.bpp*c.depth+7>>3))*c.height;g=s(b,{chunkSize:w,maxLength:w})}if(b=null,!g||!g.length)throw new Error("bad png - invalid inflate data response");var m=o.process(g,c);b=null;var y=f.dataToBitMap(m,c);m=null;var v=l(y,c);return c.data=v,c.gamma=d||0,c}}).call(this,t("buffer").Buffer)},{"./bitmapper":1,"./filter-parse-sync":8,"./format-normaliser":10,"./parser":18,"./sync-inflate":21,"./sync-reader":22,buffer:32,zlib:30}],18:[function(t,e,r){(function(r){"use strict";var n=t("./constants"),i=t("./crc"),s=e.exports=function(t,e){this._options=t,t.checkCRC=!1!==t.checkCRC,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[n.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[n.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[n.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[n.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[n.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[n.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};s.prototype.start=function(){this.read(n.PNG_SIGNATURE.length,this._parseSignature.bind(this))},s.prototype._parseSignature=function(t){for(var e=n.PNG_SIGNATURE,r=0;r<e.length;r++)if(t[r]!==e[r])return void this.error(new Error("Invalid file signature"));this.read(8,this._parseChunkBegin.bind(this))},s.prototype._parseChunkBegin=function(t){for(var e=t.readUInt32BE(0),s=t.readUInt32BE(4),a="",o=4;o<8;o++)a+=String.fromCharCode(t[o]);var h=Boolean(32&t[4]);if(this._hasIHDR||s===n.TYPE_IHDR){if(this._crc=new i,this._crc.write(new r(a)),this._chunks[s])return this._chunks[s](e);h?this.read(e+4,this._skipChunk.bind(this)):this.error(new Error("Unsupported critical chunk type "+a))}else this.error(new Error("Expected IHDR on beggining"))},s.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))},s.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))},s.prototype._parseChunkEnd=function(t){var e=t.readInt32BE(0),r=this._crc.crc32();this._options.checkCRC&&r!==e?this.error(new Error("Crc error - "+e+" - "+r)):this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))},s.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))},s.prototype._parseIHDR=function(t){this._crc.write(t);var e=t.readUInt32BE(0),r=t.readUInt32BE(4),i=t[8],s=t[9],a=t[10],o=t[11],h=t[12];if(8===i||4===i||2===i||1===i||16===i)if(s in n.COLORTYPE_TO_BPP_MAP)if(0===a)if(0===o)if(0===h||1===h){this._colorType=s;var f=n.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:r,depth:i,interlace:Boolean(h),palette:Boolean(s&n.COLORTYPE_PALETTE),color:Boolean(s&n.COLORTYPE_COLOR),alpha:Boolean(s&n.COLORTYPE_ALPHA),bpp:f,colorType:s}),this._handleChunkEnd()}else this.error(new Error("Unsupported interlace method"));else this.error(new Error("Unsupported filter method"));else this.error(new Error("Unsupported compression method"));else this.error(new Error("Unsupported color type"));else this.error(new Error("Unsupported bit depth "+i))},s.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))},s.prototype._parsePLTE=function(t){this._crc.write(t);for(var e=Math.floor(t.length/3),r=0;r<e;r++)this._palette.push([t[3*r],t[3*r+1],t[3*r+2],255]);this.palette(this._palette),this._handleChunkEnd()},s.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))},s.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===n.COLORTYPE_PALETTE_COLOR){if(0===this._palette.length)return void this.error(new Error("Transparency chunk must be after palette"));if(t.length>this._palette.length)return void this.error(new Error("More transparent colors than palette size"));for(var e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}this._colorType===n.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===n.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()},s.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))},s.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/n.GAMMA_DIVISION),this._handleChunkEnd()},s.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))},s.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===n.COLORTYPE_PALETTE_COLOR&&0===this._palette.length)throw new Error("Expected palette not found");this.inflateData(e);var r=t-e.length;r>0?this._handleIDAT(r):this._handleChunkEnd()},s.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))},s.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}}).call(this,t("buffer").Buffer)},{"./constants":4,"./crc":5,buffer:32}],19:[function(t,e,r){"use strict";var n=t("./parser-sync"),i=t("./packer-sync");r.read=function(t,e){return n(t,e||{})},r.write=function(t,e){return i(t,e)}},{"./packer-sync":13,"./parser-sync":17}],20:[function(t,e,r){(function(e,n){"use strict";var i=t("util"),s=t("stream"),a=t("./parser-async"),o=t("./packer-async"),h=t("./png-sync"),f=r.PNG=function(t){s.call(this),t=t||{},this.width=0|t.width,this.height=0|t.height,this.data=this.width>0&&this.height>0?new n(4*this.width*this.height):null,t.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new a(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(t){this.data=t,this.emit("parsed",t)}.bind(this)),this._packer=new o(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};i.inherits(f,s),f.sync=h,f.prototype.pack=function(){return this.data&&this.data.length?(e.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this):(this.emit("error","No data provided"),this)},f.prototype.parse=function(t,e){var r,n;e&&(r=function(t){this.removeListener("error",n),this.data=t,e(null,this)}.bind(this),n=function(t){this.removeListener("parsed",r),e(t,null)}.bind(this),this.once("parsed",r),this.once("error",n));return this.end(t),this},f.prototype.write=function(t){return this._parser.write(t),!0},f.prototype.end=function(t){this._parser.end(t)},f.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)},f.prototype._gamma=function(t){this.gamma=t},f.prototype._handleClose=function(){this._parser.writable||this._packer.readable||this.emit("close")},f.bitblt=function(t,e,r,n,i,s,a,o){if(n|=0,i|=0,s|=0,a|=0,o|=0,(r|=0)>t.width||n>t.height||r+i>t.width||n+s>t.height)throw new Error("bitblt reading outside image");if(a>e.width||o>e.height||a+i>e.width||o+s>e.height)throw new Error("bitblt writing outside image");for(var h=0;h<s;h++)t.data.copy(e.data,(o+h)*e.width+a<<2,(n+h)*t.width+r<<2,(n+h)*t.width+r+i<<2)},f.prototype.bitblt=function(t,e,r,n,i,s,a){return f.bitblt(this,t,e,r,n,i,s,a),this},f.adjustGamma=function(t){if(t.gamma){for(var e=0;e<t.height;e++)for(var r=0;r<t.width;r++)for(var n=t.width*e+r<<2,i=0;i<3;i++){var s=t.data[n+i]/255;s=Math.pow(s,1/2.2/t.gamma),t.data[n+i]=Math.round(255*s)}t.gamma=0}},f.prototype.adjustGamma=function(){f.adjustGamma(this)}}).call(this,t("_process"),t("buffer").Buffer)},{"./packer-async":12,"./parser-async":16,"./png-sync":19,_process:51,buffer:32,stream:64,util:69}],21:[function(t,e,r){(function(n,i){"use strict";var s=t("assert").ok,a=t("zlib"),o=t("util"),h=t("buffer").kMaxLength;function f(t){if(!(this instanceof f))return new f(t);t&&t.chunkSize<a.Z_MIN_CHUNK&&(t.chunkSize=a.Z_MIN_CHUNK),a.Inflate.call(this,t),this._offset=void 0===this._offset?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,t&&null!=t.maxLength&&(this._maxLength=t.maxLength)}function l(t,e){e&&n.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}function u(t,e){return function(t,e){if("string"==typeof e&&(e=i.from(e)),!(e instanceof i))throw new TypeError("Not a string or buffer");var r=t._finishFlushFlag;return null==r&&(r=a.Z_FINISH),t._processChunk(e,r)}(new f(e),t)}f.prototype._processChunk=function(t,e,r){if("function"==typeof r)return a.Inflate._processChunk.call(this,t,e,r);var n,o=this,f=t&&t.length,u=this._chunkSize-this._offset,c=this._maxLength,d=0,p=[],_=0;function g(t,e){if(!o._hadError){var r=u-e;if(s(r>=0,"have should not go down"),r>0){var n=o._buffer.slice(o._offset,o._offset+r);if(o._offset+=r,n.length>c&&(n=n.slice(0,c)),p.push(n),_+=n.length,0===(c-=n.length))return!1}return(0===e||o._offset>=o._chunkSize)&&(u=o._chunkSize,o._offset=0,o._buffer=i.allocUnsafe(o._chunkSize)),0===e&&(d+=f-t,f=t,!0)}}this.on("error",(function(t){n=t})),s(this._handle,"zlib binding closed");do{var b=this._handle.writeSync(e,t,d,f,this._buffer,this._offset,u);b=b||this._writeState}while(!this._hadError&&g(b[0],b[1]));if(this._hadError)throw n;if(_>=h)throw l(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+h.toString(16)+" bytes");var w=i.concat(p,_);return l(this),w},o.inherits(f,a.Inflate),e.exports=r=u,r.Inflate=f,r.createInflate=function(t){return new f(t)},r.inflateSync=u}).call(this,t("_process"),t("buffer").Buffer)},{_process:51,assert:23,buffer:32,util:69,zlib:30}],22:[function(t,e,r){"use strict";var n=e.exports=function(t){this._buffer=t,this._reads=[]};n.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})},n.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){var t=this._reads[0];if(!this._buffer.length||!(this._buffer.length>=t.length||t.allowLess))break;this._reads.shift();var e=this._buffer;this._buffer=e.slice(t.length),t.func.call(this,e.slice(0,t.length))}return this._reads.length>0?new Error("There are some read requests waitng on finished stream"):this._buffer.length>0?new Error("unrecognised content at end of stream"):void 0}},{}],23:[function(t,e,r){(function(r){"use strict";
 /*!
  * The buffer module from node.js, for the browser.
  *
  * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  * @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);
-}
-
-// based on node assert, original notice:
-
-// 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;
-}
-// 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;
-
-// 2. The AssertionError is defined in assert.
-// new assert.AssertionError({ message: message,
-//                             actual: actual,
-//                             expected: expected })
-
-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;
-  }
-  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;
-    }
-  }
-};
-
-// assert.AssertionError instanceof Error
-util.inherits(assert.AssertionError, Error);
-
-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);
-}
-
-// 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
-  });
-}
-
-// 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);
-}
-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);
-};
-
-// 6. The non-equality assertion tests for whether two objects are not equal
-// with != assert.notEqual(actual, expected, message_opt);
-
-assert.notEqual = function notEqual(actual, expected, message) {
-  if (actual == expected) {
-    fail(actual, expected, message, '!=', assert.notEqual);
-  }
-};
-
-// 7. The equivalence assertion tests a deep equality relation.
-// assert.deepEqual(actual, expected, message_opt);
-
-assert.deepEqual = function deepEqual(actual, expected, message) {
-  if (!_deepEqual(actual, expected, false)) {
-    fail(actual, expected, message, 'deepEqual', assert.deepEqual);
-  }
-};
-
-assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
-  if (!_deepEqual(actual, expected, true)) {
-    fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
-  }
-};
-
-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);
-  }
-}
-
-function isArguments(object) {
-  return Object.prototype.toString.call(object) == '[object Arguments]';
-}
-
-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;
-}
-
-// 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);
-  }
-}
-
-
-// 9. The strict equality assertion tests strict equality, as determined by ===.
-// assert.strictEqual(actual, expected, message_opt);
-
-assert.strictEqual = function strictEqual(actual, expected, message) {
-  if (actual !== expected) {
-    fail(actual, expected, message, '===', assert.strictEqual);
-  }
-};
-
-// 10. The strict non-equality assertion tests for strict inequality, as
-// determined by !==.  assert.notStrictEqual(actual, expected, message_opt);
-
-assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
-  if (actual === expected) {
-    fail(actual, expected, message, '!==', assert.notStrictEqual);
-  }
-};
-
-function expectedException(actual, expected) {
-  if (!actual || !expected) {
-    return false;
-  }
-
-  if (Object.prototype.toString.call(expected) == '[object RegExp]') {
-    return expected.test(actual);
-  }
-
-  try {
-    if (actual instanceof expected) {
-      return true;
-    }
-  } catch (e) {
-    // Ignore.  The instanceof check doesn't work for arrow functions.
-  }
-
-  if (Error.isPrototypeOf(expected)) {
-    return false;
-  }
-
-  return expected.call({}, actual) === true;
-}
-
-function _tryBlock(block) {
-  var error;
-  try {
-    block();
-  } catch (e) {
-    error = e;
-  }
-  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);
-  }
-
-  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);
-  }
-
-  if ((shouldThrow && actual && expected &&
-      !expectedException(actual, expected)) || (!shouldThrow && actual)) {
-    throw actual;
-  }
-}
-
-// 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);
-};
-
-assert.ifError = function(err) { if (err) throw err; };
-
-var objectKeys = Object.keys || function (obj) {
-  var keys = [];
-  for (var key in obj) {
-    if (hasOwn.call(obj, key)) keys.push(key);
-  }
-  return keys;
-};
-
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"util/":26}],24:[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
-  }
-}
-
-},{}],25:[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';
-}
-},{}],26:[function(require,module,exports){
-(function (process,global){
-// 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);
-    }
-  }
-  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 (process.noDeprecation === true) {
-    return fn;
-  }
-
-  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);
-  }
-
-  return deprecated;
-};
-
-
-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() {};
-    }
-  }
-  return debugs[set];
-};
-
-
-/**
- * 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);
-}
-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];
-
-  if (style) {
-    return '\u001b[' + inspect.colors[style][0] + 'm' + str +
-           '\u001b[' + inspect.colors[style][1] + 'm';
-  } else {
-    return str;
-  }
-}
-
-
-function stylizeNoColor(str, styleType) {
-  return str;
-}
-
-
-function arrayToHash(array) {
-  var hash = {};
-
-  array.forEach(function(val, idx) {
-    hash[val] = true;
-  });
-
-  return hash;
-}
-
-
-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;
-  }
-
-  // Primitive types cannot have properties
-  var primitive = formatPrimitive(ctx, value);
-  if (primitive) {
-    return primitive;
-  }
-
-  // Look up the keys of the object.
-  var keys = Object.keys(value);
-  var visibleKeys = arrayToHash(keys);
-
-  if (ctx.showHidden) {
-    keys = Object.getOwnPropertyNames(value);
-  }
-
-  // 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);
-  }
-
-  // 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);
-    }
-  }
-
-  var base = '', array = false, braces = ['{', '}'];
-
-  // Make Array say that they are Array
-  if (isArray(value)) {
-    array = true;
-    braces = ['[', ']'];
-  }
-
-  // Make functions say that they are functions
-  if (isFunction(value)) {
-    var n = value.name ? ': ' + value.name : '';
-    base = ' [Function' + n + ']';
-  }
-
-  // Make RegExps say that they are RegExps
-  if (isRegExp(value)) {
-    base = ' ' + RegExp.prototype.toString.call(value);
-  }
-
-  // Make dates with properties first say the date
-  if (isDate(value)) {
-    base = ' ' + Date.prototype.toUTCString.call(value);
-  }
-
-  // Make error with message first say the error
-  if (isError(value)) {
-    base = ' ' + formatError(value);
-  }
-
-  if (keys.length === 0 && (!array || value.length == 0)) {
-    return braces[0] + base + braces[1];
-  }
-
-  if (recurseTimes < 0) {
-    if (isRegExp(value)) {
-      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
-    } else {
-      return ctx.stylize('[Object]', 'special');
-    }
-  }
-
-  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);
-    });
-  }
-
-  ctx.seen.pop();
-
-  return reduceToSingleString(output, base, braces);
-}
-
-
-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 formatError(value) {
-  return '[' + Error.prototype.toString.call(value) + ']';
-}
-
-
-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('');
-    }
-  }
-  keys.forEach(function(key) {
-    if (!key.match(/^\d+$/)) {
-      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
-          key, true));
-    }
-  });
-  return output;
-}
-
-
-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');
-    }
-  }
-  if (!hasOwnProperty(visibleKeys, key)) {
-    name = '[' + key + ']';
-  }
-  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');
-    }
-  }
-  if (isUndefined(name)) {
-    if (array && key.match(/^\d+$/)) {
-      return str;
-    }
-    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');
-    }
-  }
-
-  return name + ': ' + str;
-}
-
-
-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];
-  }
-
-  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;
-
-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 isObject(re) && objectToString(re) === '[object RegExp]';
-}
-exports.isRegExp = isRegExp;
-
-function isObject(arg) {
-  return typeof arg === 'object' && arg !== null;
-}
-exports.isObject = isObject;
-
-function isDate(d) {
-  return isObject(d) && objectToString(d) === '[object Date]';
-}
-exports.isDate = isDate;
-
-function isError(e) {
-  return isObject(e) &&
-      (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 = require('./support/isBuffer');
-
-function objectToString(o) {
-  return Object.prototype.toString.call(o);
-}
-
-
-function pad(n) {
-  return n < 10 ? '0' + n.toString(10) : n.toString(10);
-}
-
-
-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(' ');
-}
-
-
-// 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]];
-  }
-  return origin;
-};
-
-function hasOwnProperty(obj, prop) {
-  return Object.prototype.hasOwnProperty.call(obj, prop);
-}
-
-}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"./support/isBuffer":25,"_process":51,"inherits":24}],27:[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')
-  }
-
-  // Trim off extra bytes after placeholder bytes are found
-  // See: https://github.com/beatgammit/base64-js/issues/42
-  var validLen = b64.indexOf('=')
-  if (validLen === -1) validLen = len
-
-  var placeHoldersLen = validLen === len
-    ? 0
-    : 4 - (validLen % 4)
-
-  return [validLen, placeHoldersLen]
-}
-
-// base64 is 4/3 + up to two characters of the original data
-function byteLength (b64) {
-  var lens = getLens(b64)
-  var validLen = lens[0]
-  var placeHoldersLen = lens[1]
-  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
-}
-
-function _byteLength (b64, validLen, placeHoldersLen) {
-  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
-}
-
-function toByteArray (b64) {
-  var tmp
-  var lens = getLens(b64)
-  var validLen = lens[0]
-  var placeHoldersLen = lens[1]
-
-  var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
-
-  var curByte = 0
-
-  // if there are placeholders, only get up to the last complete 4 chars
-  var len = placeHoldersLen > 0
-    ? validLen - 4
-    : validLen
-
-  for (var i = 0; i < len; i += 4) {
-    tmp =
-      (revLookup[b64.charCodeAt(i)] << 18) |
-      (revLookup[b64.charCodeAt(i + 1)] << 12) |
-      (revLookup[b64.charCodeAt(i + 2)] << 6) |
-      revLookup[b64.charCodeAt(i + 3)]
-    arr[curByte++] = (tmp >> 16) & 0xFF
-    arr[curByte++] = (tmp >> 8) & 0xFF
-    arr[curByte++] = tmp & 0xFF
-  }
-
-  if (placeHoldersLen === 2) {
-    tmp =
-      (revLookup[b64.charCodeAt(i)] << 2) |
-      (revLookup[b64.charCodeAt(i + 1)] >> 4)
-    arr[curByte++] = tmp & 0xFF
-  }
-
-  if (placeHoldersLen === 1) {
-    tmp =
-      (revLookup[b64.charCodeAt(i)] << 10) |
-      (revLookup[b64.charCodeAt(i + 1)] << 4) |
-      (revLookup[b64.charCodeAt(i + 2)] >> 2)
-    arr[curByte++] = (tmp >> 8) & 0xFF
-    arr[curByte++] = tmp & 0xFF
-  }
-
-  return arr
-}
-
-function tripletToBase64 (num) {
-  return lookup[num >> 18 & 0x3F] +
-    lookup[num >> 12 & 0x3F] +
-    lookup[num >> 6 & 0x3F] +
-    lookup[num & 0x3F]
-}
-
-function encodeChunk (uint8, start, end) {
-  var tmp
-  var output = []
-  for (var i = start; i < end; i += 3) {
-    tmp =
-      ((uint8[i] << 16) & 0xFF0000) +
-      ((uint8[i + 1] << 8) & 0xFF00) +
-      (uint8[i + 2] & 0xFF)
-    output.push(tripletToBase64(tmp))
-  }
-  return output.join('')
-}
-
-function fromByteArray (uint8) {
-  var tmp
-  var len = uint8.length
-  var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
-  var parts = []
-  var maxChunkLength = 16383 // must be multiple of 3
-
-  // go through the array every three bytes, we'll deal with trailing stuff later
-  for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
-    parts.push(encodeChunk(
-      uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
-    ))
-  }
-
-  // pad the end with zeros, but make sure to not forget the extra bytes
-  if (extraBytes === 1) {
-    tmp = uint8[len - 1]
-    parts.push(
-      lookup[tmp >> 2] +
-      lookup[(tmp << 4) & 0x3F] +
-      '=='
-    )
-  } else if (extraBytes === 2) {
-    tmp = (uint8[len - 2] << 8) + uint8[len - 1]
-    parts.push(
-      lookup[tmp >> 10] +
-      lookup[(tmp >> 4) & 0x3F] +
-      lookup[(tmp << 2) & 0x3F] +
-      '='
-    )
-  }
-
-  return parts.join('')
-}
-
-},{}],28:[function(require,module,exports){
-
-},{}],29:[function(require,module,exports){
-(function (process,Buffer){
-'use strict';
-/* eslint camelcase: "off" */
-
-var assert = require('assert');
-
-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');
-
-for (var key in constants) {
-  exports[key] = constants[key];
-}
-
-// 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 GZIP_HEADER_ID1 = 0x1f;
-var GZIP_HEADER_ID2 = 0x8b;
-
-/**
- * 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;
-}
-
-Zlib.prototype.close = function () {
-  if (this.write_in_progress) {
-    this.pending_close = true;
-    return;
-  }
-
-  this.pending_close = false;
-
-  assert(this.init_done, 'close before init');
-  assert(this.mode <= exports.UNZIP);
-
-  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);
-  }
-
-  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;
-  }
-
-  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;
-
-  if (!async) {
-    // sync version
-    this._process();
-
-    if (this._checkError()) {
-      return this._afterSync();
-    }
-    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];
-};
-
-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;
-      }
-
-      switch (this.gzip_id_bytes_read) {
-        case 0:
-          if (next_expected_header_byte === null) {
-            break;
-          }
-
-          if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) {
-            this.gzip_id_bytes_read = 1;
-            next_expected_header_byte++;
-
-            if (this.strm.avail_in === 1) {
-              // The only available byte was already read.
-              break;
-            }
-          } else {
-            this.mode = exports.INFLATE;
-            break;
-          }
-
-        // fallthrough
-        case 1:
-          if (next_expected_header_byte === null) {
-            break;
-          }
-
-          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;
-          }
-
-          break;
-        default:
-          throw new Error('invalid number of gzip magic number bytes read');
-      }
-
-    // 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);
-  }
-};
-
-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;
-  }
-
-  return true;
-};
-
-Zlib.prototype._after = function () {
-  if (!this._checkError()) {
-    return;
-  }
-
-  var avail_out = this.strm.avail_out;
-  var avail_in = this.strm.avail_in;
-
-  this.write_in_progress = false;
-
-  // call the write() cb
-  this.callback(avail_in, avail_out);
-
-  if (this.pending_close) {
-    this.close();
-  }
-};
-
-Zlib.prototype._error = function (message) {
-  if (this.strm.msg) {
-    message = this.strm.msg;
-  }
-  this.onerror(message, this.err
-
-  // no hope of rescue.
-  );this.write_in_progress = false;
-  if (this.pending_close) {
-    this.close();
-  }
-};
-
-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');
-
-  this._init(level, windowBits, memLevel, strategy, dictionary);
-  this._setDictionary();
-};
-
-Zlib.prototype.params = function () {
-  throw new Error('deflateParams Not supported');
-};
-
-Zlib.prototype.reset = function () {
-  this._reset();
-  this._setDictionary();
-};
-
-Zlib.prototype._init = function (level, windowBits, memLevel, strategy, dictionary) {
-  this.level = level;
-  this.windowBits = windowBits;
-  this.memLevel = memLevel;
-  this.strategy = strategy;
-
-  this.flush = exports.Z_NO_FLUSH;
-
-  this.err = exports.Z_OK;
-
-  if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) {
-    this.windowBits += 16;
-  }
-
-  if (this.mode === exports.UNZIP) {
-    this.windowBits += 32;
-  }
-
-  if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) {
-    this.windowBits = -1 * this.windowBits;
-  }
-
-  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);
-  }
-
-  if (this.err !== exports.Z_OK) {
-    this._error('Init error');
-  }
-
-  this.dictionary = dictionary;
-
-  this.write_in_progress = false;
-  this.init_done = true;
-};
-
-Zlib.prototype._setDictionary = function () {
-  if (this.dictionary == null) {
-    return;
-  }
-
-  this.err = exports.Z_OK;
-
-  switch (this.mode) {
-    case exports.DEFLATE:
-    case exports.DEFLATERAW:
-      this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary);
-      break;
-    default:
-      break;
-  }
-
-  if (this.err !== exports.Z_OK) {
-    this._error('Failed to set dictionary');
-  }
-};
-
-Zlib.prototype._reset = function () {
-  this.err = exports.Z_OK;
-
-  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;
-  }
-
-  if (this.err !== exports.Z_OK) {
-    this._error('Failed to reset stream');
-  }
-};
-
-exports.Zlib = Zlib;
-}).call(this,require('_process'),require("buffer").Buffer)
-},{"_process":51,"assert":23,"buffer":32,"pako/lib/zlib/constants":41,"pako/lib/zlib/deflate.js":43,"pako/lib/zlib/inflate.js":45,"pako/lib/zlib/zstream":49}],30:[function(require,module,exports){
-(function (process){
-'use strict';
-
-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
-    });
-  }
-}
-
-// 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
-};
-
-var ckeys = Object.keys(codes);
-for (var ck = 0; ck < ckeys.length; ck++) {
-  var ckey = ckeys[ck];
-  codes[codes[ckey]] = ckey;
-}
-
-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);
-};
-
-exports.createUnzip = function (o) {
-  return new Unzip(o);
-};
-
-// Convenience methods.
-// compress/decompress a string or buffer in one step.
-exports.deflate = function (buffer, opts, callback) {
-  if (typeof opts === 'function') {
-    callback = opts;
-    opts = {};
-  }
-  return zlibBuffer(new Deflate(opts), buffer, callback);
-};
-
-exports.deflateSync = function (buffer, opts) {
-  return zlibBufferSync(new Deflate(opts), buffer);
-};
-
-exports.gzip = function (buffer, opts, callback) {
-  if (typeof opts === 'function') {
-    callback = opts;
-    opts = {};
-  }
-  return zlibBuffer(new Gzip(opts), buffer, callback);
-};
-
-exports.gzipSync = function (buffer, opts) {
-  return zlibBufferSync(new Gzip(opts), buffer);
-};
-
-exports.deflateRaw = function (buffer, opts, callback) {
-  if (typeof opts === 'function') {
-    callback = opts;
-    opts = {};
-  }
-  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 = {};
-  }
-  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);
-};
-
-exports.inflateSync = function (buffer, opts) {
-  return zlibBufferSync(new Inflate(opts), buffer);
-};
-
-exports.gunzip = function (buffer, opts, callback) {
-  if (typeof opts === 'function') {
-    callback = opts;
-    opts = {};
-  }
-  return zlibBuffer(new Gunzip(opts), buffer, callback);
-};
-
-exports.gunzipSync = function (buffer, opts) {
-  return zlibBufferSync(new Gunzip(opts), buffer);
-};
-
-exports.inflateRaw = function (buffer, opts, callback) {
-  if (typeof opts === 'function') {
-    callback = opts;
-    opts = {};
-  }
-  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);
-  }
-
-  function onError(err) {
-    engine.removeListener('end', onEnd);
-    engine.removeListener('readable', flow);
-    callback(err);
-  }
-
-  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);
-  }
-}
-
-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);
-}
-
-function Inflate(opts) {
-  if (!(this instanceof Inflate)) return new Inflate(opts);
-  Zlib.call(this, opts, binding.INFLATE);
-}
-
-// gzip - bigger header, same deflate compression
-function Gzip(opts) {
-  if (!(this instanceof Gzip)) return new Gzip(opts);
-  Zlib.call(this, opts, binding.GZIP);
-}
-
-function Gunzip(opts) {
-  if (!(this instanceof Gunzip)) return new Gunzip(opts);
-  Zlib.call(this, opts, binding.GUNZIP);
-}
-
-// raw - no header
-function DeflateRaw(opts) {
-  if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
-  Zlib.call(this, opts, binding.DEFLATERAW);
-}
-
-function InflateRaw(opts) {
-  if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
-  Zlib.call(this, opts, binding.INFLATERAW);
-}
-
-// auto-detect header.
-function Unzip(opts) {
-  if (!(this instanceof Unzip)) return new Unzip(opts);
-  Zlib.call(this, opts, binding.UNZIP);
-}
-
-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;
-}
-
-// 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.
-
-function Zlib(opts, mode) {
-  var _this = this;
-
-  this._opts = opts = opts || {};
-  this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
-
-  Transform.call(this, opts);
-
-  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;
-
-  if (opts.chunkSize) {
-    if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) {
-      throw new Error('Invalid chunk size: ' + opts.chunkSize);
-    }
-  }
-
-  if (opts.windowBits) {
-    if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) {
-      throw new Error('Invalid windowBits: ' + opts.windowBits);
-    }
-  }
-
-  if (opts.level) {
-    if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) {
-      throw new Error('Invalid compression level: ' + opts.level);
-    }
-  }
-
-  if (opts.memLevel) {
-    if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) {
-      throw new Error('Invalid memLevel: ' + opts.memLevel);
-    }
-  }
-
-  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);
-    }
-  }
-
-  if (opts.dictionary) {
-    if (!Buffer.isBuffer(opts.dictionary)) {
-      throw new Error('Invalid dictionary: it should be a Buffer instance');
-    }
-  }
-
-  this._handle = new binding.Zlib(mode);
-
-  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);
-  };
-
-  var level = exports.Z_DEFAULT_COMPRESSION;
-  if (typeof opts.level === 'number') level = opts.level;
-
-  var strategy = exports.Z_DEFAULT_STRATEGY;
-  if (typeof opts.strategy === 'number') strategy = opts.strategy;
-
-  this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary);
-
-  this._buffer = Buffer.allocUnsafe(this._chunkSize);
-  this._offset = 0;
-  this._level = level;
-  this._strategy = strategy;
-
-  this.once('end', this.close);
-
-  Object.defineProperty(this, '_closed', {
-    get: function () {
-      return !_this._handle;
-    },
-    configurable: true,
-    enumerable: true
-  });
-}
-
-util.inherits(Zlib, Transform);
-
-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);
-  }
-
-  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);
-  }
-};
-
-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;
-
-  if (typeof kind === 'function' || kind === undefined && !callback) {
-    callback = kind;
-    kind = binding.Z_FULL_FLUSH;
-  }
-
-  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);
-  }
-};
-
-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;
-}
-
-function emitCloseNT(self) {
-  self.emit('close');
-}
-
-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;
-
-    var error;
-    this.on('error', function (er) {
-      error = er;
-    });
-
-    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;
-    }
-
-    if (nread >= kMaxLength) {
-      _close(this);
-      throw new RangeError(kRangeErrorMessage);
-    }
-
-    var buf = Buffer.concat(buffers, nread);
-    _close(this);
-
-    return buf;
-  }
-
-  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;
-    }
-
-    if (self._hadError) return;
-
-    var have = availOutBefore - availOutAfter;
-    assert(have >= 0, 'have should not go down');
-
-    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;
-      }
-    }
-
-    // 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);
-    }
-
-    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;
-
-      if (!async) return true;
-
-      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;
-    }
-
-    if (!async) return false;
-
-    // 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,require('_process'))
-},{"./binding":29,"_process":51,"assert":23,"buffer":32,"stream":64,"util":69}],31:[function(require,module,exports){
-(function (global){
-'use strict';
-
-var buffer = require('buffer');
-var Buffer = buffer.Buffer;
-var SlowBuffer = buffer.SlowBuffer;
-var MAX_LEN = buffer.kMaxLength || 2147483647;
-exports.alloc = function alloc(size, fill, encoding) {
-  if (typeof Buffer.alloc === 'function') {
-    return Buffer.alloc(size, fill, encoding);
-  }
-  if (typeof encoding === 'number') {
-    throw new TypeError('encoding must not be number');
-  }
-  if (typeof size !== 'number') {
-    throw new TypeError('size must be a number');
-  }
-  if (size > MAX_LEN) {
-    throw new RangeError('size is too large');
-  }
-  var enc = encoding;
-  var _fill = fill;
-  if (_fill === undefined) {
-    enc = undefined;
-    _fill = 0;
-  }
-  var buf = new Buffer(size);
-  if (typeof _fill === 'string') {
-    var fillBuf = new Buffer(_fill, enc);
-    var flen = fillBuf.length;
-    var i = -1;
-    while (++i < size) {
-      buf[i] = fillBuf[i % flen];
-    }
-  } else {
-    buf.fill(_fill);
-  }
-  return buf;
-}
-exports.allocUnsafe = function allocUnsafe(size) {
-  if (typeof Buffer.allocUnsafe === 'function') {
-    return Buffer.allocUnsafe(size);
-  }
-  if (typeof size !== 'number') {
-    throw new TypeError('size must be a number');
-  }
-  if (size > MAX_LEN) {
-    throw new RangeError('size is too large');
-  }
-  return new Buffer(size);
-}
-exports.from = function from(value, encodingOrOffset, length) {
-  if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) {
-    return Buffer.from(value, encodingOrOffset, length);
-  }
-  if (typeof value === 'number') {
-    throw new TypeError('"value" argument must not be a number');
-  }
-  if (typeof value === 'string') {
-    return new Buffer(value, encodingOrOffset);
-  }
-  if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
-    var offset = encodingOrOffset;
-    if (arguments.length === 1) {
-      return new Buffer(value);
-    }
-    if (typeof offset === 'undefined') {
-      offset = 0;
-    }
-    var len = length;
-    if (typeof len === 'undefined') {
-      len = value.byteLength - offset;
-    }
-    if (offset >= value.byteLength) {
-      throw new RangeError('\'offset\' is out of bounds');
-    }
-    if (len > value.byteLength - offset) {
-      throw new RangeError('\'length\' is out of bounds');
-    }
-    return new Buffer(value.slice(offset, offset + len));
-  }
-  if (Buffer.isBuffer(value)) {
-    var out = new Buffer(value.length);
-    value.copy(out, 0, 0, value.length);
-    return out;
-  }
-  if (value) {
-    if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) {
-      return new Buffer(value);
-    }
-    if (value.type === 'Buffer' && Array.isArray(value.data)) {
-      return new Buffer(value.data);
-    }
-  }
-
-  throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.');
-}
-exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
-  if (typeof Buffer.allocUnsafeSlow === 'function') {
-    return Buffer.allocUnsafeSlow(size);
-  }
-  if (typeof size !== 'number') {
-    throw new TypeError('size must be a number');
-  }
-  if (size >= MAX_LEN) {
-    throw new RangeError('size is too large');
-  }
-  return new SlowBuffer(size);
-}
-
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"buffer":32}],32:[function(require,module,exports){
-(function (Buffer){
+ */function n(t,e){if(t===e)return 0;for(var r=t.length,n=e.length,i=0,s=Math.min(r,n);i<s;++i)if(t[i]!==e[i]){r=t[i],n=e[i];break}return r<n?-1:n<r?1:0}function i(t){return r.Buffer&&"function"==typeof r.Buffer.isBuffer?r.Buffer.isBuffer(t):!(null==t||!t._isBuffer)}var s=t("util/"),a=Object.prototype.hasOwnProperty,o=Array.prototype.slice,h="foo"===function(){}.name;function f(t){return Object.prototype.toString.call(t)}function l(t){return!i(t)&&("function"==typeof r.ArrayBuffer&&("function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):!!t&&(t instanceof DataView||!!(t.buffer&&t.buffer instanceof ArrayBuffer))))}var u=e.exports=b,c=/\s*function\s+([^\(\s]*)\s*/;function d(t){if(s.isFunction(t)){if(h)return t.name;var e=t.toString().match(c);return e&&e[1]}}function p(t,e){return"string"==typeof t?t.length<e?t:t.slice(0,e):t}function _(t){if(h||!s.isFunction(t))return s.inspect(t);var e=d(t);return"[Function"+(e?": "+e:"")+"]"}function g(t,e,r,n,i){throw new u.AssertionError({message:r,actual:t,expected:e,operator:n,stackStartFunction:i})}function b(t,e){t||g(t,!0,e,"==",u.ok)}function w(t,e,r,a){if(t===e)return!0;if(i(t)&&i(e))return 0===n(t,e);if(s.isDate(t)&&s.isDate(e))return t.getTime()===e.getTime();if(s.isRegExp(t)&&s.isRegExp(e))return t.source===e.source&&t.global===e.global&&t.multiline===e.multiline&&t.lastIndex===e.lastIndex&&t.ignoreCase===e.ignoreCase;if(null!==t&&"object"==typeof t||null!==e&&"object"==typeof e){if(l(t)&&l(e)&&f(t)===f(e)&&!(t instanceof Float32Array||t instanceof Float64Array))return 0===n(new Uint8Array(t.buffer),new Uint8Array(e.buffer));if(i(t)!==i(e))return!1;var h=(a=a||{actual:[],expected:[]}).actual.indexOf(t);return-1!==h&&h===a.expected.indexOf(e)||(a.actual.push(t),a.expected.push(e),function(t,e,r,n){if(null==t||null==e)return!1;if(s.isPrimitive(t)||s.isPrimitive(e))return t===e;if(r&&Object.getPrototypeOf(t)!==Object.getPrototypeOf(e))return!1;var i=m(t),a=m(e);if(i&&!a||!i&&a)return!1;if(i)return w(t=o.call(t),e=o.call(e),r);var h,f,l=E(t),u=E(e);if(l.length!==u.length)return!1;for(l.sort(),u.sort(),f=l.length-1;f>=0;f--)if(l[f]!==u[f])return!1;for(f=l.length-1;f>=0;f--)if(!w(t[h=l[f]],e[h],r,n))return!1;return!0}(t,e,r,a))}return r?t===e:t==e}function m(t){return"[object Arguments]"==Object.prototype.toString.call(t)}function y(t,e){if(!t||!e)return!1;if("[object RegExp]"==Object.prototype.toString.call(e))return e.test(t);try{if(t instanceof e)return!0}catch(t){}return!Error.isPrototypeOf(e)&&!0===e.call({},t)}function v(t,e,r,n){var i;if("function"!=typeof e)throw new TypeError('"block" argument must be a function');"string"==typeof r&&(n=r,r=null),i=function(t){var e;try{t()}catch(t){e=t}return e}(e),n=(r&&r.name?" ("+r.name+").":".")+(n?" "+n:"."),t&&!i&&g(i,r,"Missing expected exception"+n);var a="string"==typeof n,o=!t&&i&&!r;if((!t&&s.isError(i)&&a&&y(i,r)||o)&&g(i,r,"Got unwanted exception"+n),t&&i&&r&&!y(i,r)||!t&&i)throw i}u.AssertionError=function(t){this.name="AssertionError",this.actual=t.actual,this.expected=t.expected,this.operator=t.operator,t.message?(this.message=t.message,this.generatedMessage=!1):(this.message=function(t){return p(_(t.actual),128)+" "+t.operator+" "+p(_(t.expected),128)}(this),this.generatedMessage=!0);var e=t.stackStartFunction||g;if(Error.captureStackTrace)Error.captureStackTrace(this,e);else{var r=new Error;if(r.stack){var n=r.stack,i=d(e),s=n.indexOf("\n"+i);if(s>=0){var a=n.indexOf("\n",s+1);n=n.substring(a+1)}this.stack=n}}},s.inherits(u.AssertionError,Error),u.fail=g,u.ok=b,u.equal=function(t,e,r){t!=e&&g(t,e,r,"==",u.equal)},u.notEqual=function(t,e,r){t==e&&g(t,e,r,"!=",u.notEqual)},u.deepEqual=function(t,e,r){w(t,e,!1)||g(t,e,r,"deepEqual",u.deepEqual)},u.deepStrictEqual=function(t,e,r){w(t,e,!0)||g(t,e,r,"deepStrictEqual",u.deepStrictEqual)},u.notDeepEqual=function(t,e,r){w(t,e,!1)&&g(t,e,r,"notDeepEqual",u.notDeepEqual)},u.notDeepStrictEqual=function t(e,r,n){w(e,r,!0)&&g(e,r,n,"notDeepStrictEqual",t)},u.strictEqual=function(t,e,r){t!==e&&g(t,e,r,"===",u.strictEqual)},u.notStrictEqual=function(t,e,r){t===e&&g(t,e,r,"!==",u.notStrictEqual)},u.throws=function(t,e,r){v(!0,t,e,r)},u.doesNotThrow=function(t,e,r){v(!1,t,e,r)},u.ifError=function(t){if(t)throw t};var E=Object.keys||function(t){var e=[];for(var r in t)a.call(t,r)&&e.push(r);return e}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"util/":26}],24:[function(t,e,r){"function"==typeof Object.create?e.exports=function(t,e){t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}})}:e.exports=function(t,e){t.super_=e;var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}},{}],25:[function(t,e,r){e.exports=function(t){return t&&"object"==typeof t&&"function"==typeof t.copy&&"function"==typeof t.fill&&"function"==typeof t.readUInt8}},{}],26:[function(t,e,r){(function(e,n){var i=/%[sdj%]/g;r.format=function(t){if(!b(t)){for(var e=[],r=0;r<arguments.length;r++)e.push(o(arguments[r]));return e.join(" ")}r=1;for(var n=arguments,s=n.length,a=String(t).replace(i,(function(t){if("%%"===t)return"%";if(r>=s)return t;switch(t){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(t){return"[Circular]"}default:return t}})),h=n[r];r<s;h=n[++r])_(h)||!y(h)?a+=" "+h:a+=" "+o(h);return a},r.deprecate=function(t,i){if(w(n.process))return function(){return r.deprecate(t,i).apply(this,arguments)};if(!0===e.noDeprecation)return t;var s=!1;return function(){if(!s){if(e.throwDeprecation)throw new Error(i);e.traceDeprecation?console.trace(i):console.error(i),s=!0}return t.apply(this,arguments)}};var s,a={};function o(t,e){var n={seen:[],stylize:f};return arguments.length>=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),p(e)?n.showHidden=e:e&&r._extend(n,e),w(n.showHidden)&&(n.showHidden=!1),w(n.depth)&&(n.depth=2),w(n.colors)&&(n.colors=!1),w(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=h),l(n,t,n.depth)}function h(t,e){var r=o.styles[e];return r?"\e["+o.colors[r][0]+"m"+t+"\e["+o.colors[r][1]+"m":t}function f(t,e){return t}function l(t,e,n){if(t.customInspect&&e&&k(e.inspect)&&e.inspect!==r.inspect&&(!e.constructor||e.constructor.prototype!==e)){var i=e.inspect(n,t);return b(i)||(i=l(t,i,n)),i}var s=function(t,e){if(w(e))return t.stylize("undefined","undefined");if(b(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(r,"string")}if(g(e))return t.stylize(""+e,"number");if(p(e))return t.stylize(""+e,"boolean");if(_(e))return t.stylize("null","null")}(t,e);if(s)return s;var a=Object.keys(e),o=function(t){var e={};return t.forEach((function(t,r){e[t]=!0})),e}(a);if(t.showHidden&&(a=Object.getOwnPropertyNames(e)),E(e)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return u(e);if(0===a.length){if(k(e)){var h=e.name?": "+e.name:"";return t.stylize("[Function"+h+"]","special")}if(m(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(v(e))return t.stylize(Date.prototype.toString.call(e),"date");if(E(e))return u(e)}var f,y="",T=!1,x=["{","}"];(d(e)&&(T=!0,x=["[","]"]),k(e))&&(y=" [Function"+(e.name?": "+e.name:"")+"]");return m(e)&&(y=" "+RegExp.prototype.toString.call(e)),v(e)&&(y=" "+Date.prototype.toUTCString.call(e)),E(e)&&(y=" "+u(e)),0!==a.length||T&&0!=e.length?n<0?m(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special"):(t.seen.push(e),f=T?function(t,e,r,n,i){for(var s=[],a=0,o=e.length;a<o;++a)R(e,String(a))?s.push(c(t,e,r,n,String(a),!0)):s.push("");return i.forEach((function(i){i.match(/^\d+$/)||s.push(c(t,e,r,n,i,!0))})),s}(t,e,n,o,a):a.map((function(r){return c(t,e,n,o,r,T)})),t.seen.pop(),function(t,e,r){if(t.reduce((function(t,e){return e.indexOf("\n")>=0&&0,t+e.replace(/\u001b\[\d\d?m/g,"").length+1}),0)>60)return r[0]+(""===e?"":e+"\n ")+" "+t.join(",\n  ")+" "+r[1];return r[0]+e+" "+t.join(", ")+" "+r[1]}(f,y,x)):x[0]+y+x[1]}function u(t){return"["+Error.prototype.toString.call(t)+"]"}function c(t,e,r,n,i,s){var a,o,h;if((h=Object.getOwnPropertyDescriptor(e,i)||{value:e[i]}).get?o=h.set?t.stylize("[Getter/Setter]","special"):t.stylize("[Getter]","special"):h.set&&(o=t.stylize("[Setter]","special")),R(n,i)||(a="["+i+"]"),o||(t.seen.indexOf(h.value)<0?(o=_(r)?l(t,h.value,null):l(t,h.value,r-1)).indexOf("\n")>-1&&(o=s?o.split("\n").map((function(t){return"  "+t})).join("\n").substr(2):"\n"+o.split("\n").map((function(t){return"   "+t})).join("\n")):o=t.stylize("[Circular]","special")),w(a)){if(s&&i.match(/^\d+$/))return o;(a=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+o}function d(t){return Array.isArray(t)}function p(t){return"boolean"==typeof t}function _(t){return null===t}function g(t){return"number"==typeof t}function b(t){return"string"==typeof t}function w(t){return void 0===t}function m(t){return y(t)&&"[object RegExp]"===T(t)}function y(t){return"object"==typeof t&&null!==t}function v(t){return y(t)&&"[object Date]"===T(t)}function E(t){return y(t)&&("[object Error]"===T(t)||t instanceof Error)}function k(t){return"function"==typeof t}function T(t){return Object.prototype.toString.call(t)}function x(t){return t<10?"0"+t.toString(10):t.toString(10)}r.debuglog=function(t){if(w(s)&&(s=e.env.NODE_DEBUG||""),t=t.toUpperCase(),!a[t])if(new RegExp("\\b"+t+"\\b","i").test(s)){var n=e.pid;a[t]=function(){var e=r.format.apply(r,arguments);console.error("%s %d: %s",t,n,e)}}else a[t]=function(){};return a[t]},r.inspect=o,o.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]},o.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},r.isArray=d,r.isBoolean=p,r.isNull=_,r.isNullOrUndefined=function(t){return null==t},r.isNumber=g,r.isString=b,r.isSymbol=function(t){return"symbol"==typeof t},r.isUndefined=w,r.isRegExp=m,r.isObject=y,r.isDate=v,r.isError=E,r.isFunction=k,r.isPrimitive=function(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t},r.isBuffer=t("./support/isBuffer");var A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function L(){var t=new Date,e=[x(t.getHours()),x(t.getMinutes()),x(t.getSeconds())].join(":");return[t.getDate(),A[t.getMonth()],e].join(" ")}function R(t,e){return Object.prototype.hasOwnProperty.call(t,e)}r.log=function(){console.log("%s - %s",L(),r.format.apply(r,arguments))},r.inherits=t("inherits"),r._extend=function(t,e){if(!e||!y(e))return t;for(var r=Object.keys(e),n=r.length;n--;)t[r[n]]=e[r[n]];return t}}).call(this,t("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./support/isBuffer":25,_process:51,inherits:24}],27:[function(t,e,r){"use strict";r.byteLength=function(t){var e=f(t),r=e[0],n=e[1];return 3*(r+n)/4-n},r.toByteArray=function(t){for(var e,r=f(t),n=r[0],a=r[1],o=new s(function(t,e,r){return 3*(e+r)/4-r}(0,n,a)),h=0,l=a>0?n-4:n,u=0;u<l;u+=4)e=i[t.charCodeAt(u)]<<18|i[t.charCodeAt(u+1)]<<12|i[t.charCodeAt(u+2)]<<6|i[t.charCodeAt(u+3)],o[h++]=e>>16&255,o[h++]=e>>8&255,o[h++]=255&e;2===a&&(e=i[t.charCodeAt(u)]<<2|i[t.charCodeAt(u+1)]>>4,o[h++]=255&e);1===a&&(e=i[t.charCodeAt(u)]<<10|i[t.charCodeAt(u+1)]<<4|i[t.charCodeAt(u+2)]>>2,o[h++]=e>>8&255,o[h++]=255&e);return o},r.fromByteArray=function(t){for(var e,r=t.length,i=r%3,s=[],a=16383,o=0,h=r-i;o<h;o+=a)s.push(l(t,o,o+a>h?h:o+a));1===i?(e=t[r-1],s.push(n[e>>2]+n[e<<4&63]+"==")):2===i&&(e=(t[r-2]<<8)+t[r-1],s.push(n[e>>10]+n[e>>4&63]+n[e<<2&63]+"="));return s.join("")};for(var n=[],i=[],s="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,h=a.length;o<h;++o)n[o]=a[o],i[a.charCodeAt(o)]=o;function f(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function l(t,e,r){for(var i,s,a=[],o=e;o<r;o+=3)i=(t[o]<<16&16711680)+(t[o+1]<<8&65280)+(255&t[o+2]),a.push(n[(s=i)>>18&63]+n[s>>12&63]+n[s>>6&63]+n[63&s]);return a.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63},{}],28:[function(t,e,r){},{}],29:[function(t,e,r){(function(e,n){"use strict";var i=t("assert"),s=t("pako/lib/zlib/zstream"),a=t("pako/lib/zlib/deflate.js"),o=t("pako/lib/zlib/inflate.js"),h=t("pako/lib/zlib/constants");for(var f in h)r[f]=h[f];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 l(t){if("number"!=typeof t||t<r.DEFLATE||t>r.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=t,this.strategy=0,this.windowBits=0,this.write_in_progress=!1,this.pending_close=!1,this.gzip_id_bytes_read=0}l.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||o.inflateEnd(this.strm),this.mode=r.NONE,this.dictionary=null)},l.prototype.write=function(t,e,r,n,i,s,a){return this._write(!0,t,e,r,n,i,s,a)},l.prototype.writeSync=function(t,e,r,n,i,s,a){return this._write(!1,t,e,r,n,i,s,a)},l.prototype._write=function(t,s,a,o,h,f,l,u){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===s,"must provide flush value"),this.write_in_progress=!0,s!==r.Z_NO_FLUSH&&s!==r.Z_PARTIAL_FLUSH&&s!==r.Z_SYNC_FLUSH&&s!==r.Z_FULL_FLUSH&&s!==r.Z_FINISH&&s!==r.Z_BLOCK)throw new Error("Invalid flush value");if(null==a&&(a=n.alloc(0),h=0,o=0),this.strm.avail_in=h,this.strm.input=a,this.strm.next_in=o,this.strm.avail_out=u,this.strm.output=f,this.strm.next_out=l,this.flush=s,!t)return this._process(),this._checkError()?this._afterSync():void 0;var c=this;return e.nextTick((function(){c._process(),c._after()})),this},l.prototype._afterSync=function(){var t=this.strm.avail_out,e=this.strm.avail_in;return this.write_in_progress=!1,[e,t]},l.prototype._process=function(){var t=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&&(t=this.strm.next_in),this.gzip_id_bytes_read){case 0:if(null===t)break;if(31!==this.strm.input[t]){this.mode=r.INFLATE;break}if(this.gzip_id_bytes_read=1,t++,1===this.strm.avail_in)break;case 1:if(null===t)break;139===this.strm.input[t]?(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=o.inflate(this.strm,this.flush),this.err===r.Z_NEED_DICT&&this.dictionary&&(this.err=o.inflateSetDictionary(this.strm,this.dictionary),this.err===r.Z_OK?this.err=o.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=o.inflate(this.strm,this.flush);break;default:throw new Error("Unknown mode "+this.mode)}},l.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},l.prototype._after=function(){if(this._checkError()){var t=this.strm.avail_out,e=this.strm.avail_in;this.write_in_progress=!1,this.callback(e,t),this.pending_close&&this.close()}},l.prototype._error=function(t){this.strm.msg&&(t=this.strm.msg),this.onerror(t,this.err),this.write_in_progress=!1,this.pending_close&&this.close()},l.prototype.init=function(t,e,n,s,a){i(4===arguments.length||5===arguments.length,"init(windowBits, level, memLevel, strategy, [dictionary])"),i(t>=8&&t<=15,"invalid windowBits"),i(e>=-1&&e<=9,"invalid compression level"),i(n>=1&&n<=9,"invalid memlevel"),i(s===r.Z_FILTERED||s===r.Z_HUFFMAN_ONLY||s===r.Z_RLE||s===r.Z_FIXED||s===r.Z_DEFAULT_STRATEGY,"invalid strategy"),this._init(e,t,n,s,a),this._setDictionary()},l.prototype.params=function(){throw new Error("deflateParams Not supported")},l.prototype.reset=function(){this._reset(),this._setDictionary()},l.prototype._init=function(t,e,n,i,h){switch(this.level=t,this.windowBits=e,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 s,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=o.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=h,this.write_in_progress=!1,this.init_done=!0},l.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")}},l.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=o.inflateReset(this.strm)}this.err!==r.Z_OK&&this._error("Failed to reset stream")},r.Zlib=l}).call(this,t("_process"),t("buffer").Buffer)},{_process:51,assert:23,buffer:32,"pako/lib/zlib/constants":41,"pako/lib/zlib/deflate.js":43,"pako/lib/zlib/inflate.js":45,"pako/lib/zlib/zstream":49}],30:[function(t,e,r){(function(e){"use strict";var n=t("buffer").Buffer,i=t("stream").Transform,s=t("./binding"),a=t("util"),o=t("assert").ok,h=t("buffer").kMaxLength,f="Cannot create final Buffer. It would be larger than 0x"+h.toString(16)+" bytes";s.Z_MIN_WINDOWBITS=8,s.Z_MAX_WINDOWBITS=15,s.Z_DEFAULT_WINDOWBITS=15,s.Z_MIN_CHUNK=64,s.Z_MAX_CHUNK=1/0,s.Z_DEFAULT_CHUNK=16384,s.Z_MIN_MEMLEVEL=1,s.Z_MAX_MEMLEVEL=9,s.Z_DEFAULT_MEMLEVEL=8,s.Z_MIN_LEVEL=-1,s.Z_MAX_LEVEL=9,s.Z_DEFAULT_LEVEL=s.Z_DEFAULT_COMPRESSION;for(var l=Object.keys(s),u=0;u<l.length;u++){var c=l[u];c.match(/^Z/)&&Object.defineProperty(r,c,{enumerable:!0,value:s[c],writable:!1})}for(var d={Z_OK:s.Z_OK,Z_STREAM_END:s.Z_STREAM_END,Z_NEED_DICT:s.Z_NEED_DICT,Z_ERRNO:s.Z_ERRNO,Z_STREAM_ERROR:s.Z_STREAM_ERROR,Z_DATA_ERROR:s.Z_DATA_ERROR,Z_MEM_ERROR:s.Z_MEM_ERROR,Z_BUF_ERROR:s.Z_BUF_ERROR,Z_VERSION_ERROR:s.Z_VERSION_ERROR},p=Object.keys(d),_=0;_<p.length;_++){var g=p[_];d[d[g]]=g}function b(t,e,r){var i=[],s=0;function a(){for(var e;null!==(e=t.read());)i.push(e),s+=e.length;t.once("readable",a)}function o(){var e,a=null;s>=h?a=new RangeError(f):e=n.concat(i,s),i=[],t.close(),r(a,e)}t.on("error",(function(e){t.removeListener("end",o),t.removeListener("readable",a),r(e)})),t.on("end",o),t.end(e),a()}function w(t,e){if("string"==typeof e&&(e=n.from(e)),!n.isBuffer(e))throw new TypeError("Not a string or buffer");var r=t._finishFlushFlag;return t._processChunk(e,r)}function m(t){if(!(this instanceof m))return new m(t);L.call(this,t,s.DEFLATE)}function y(t){if(!(this instanceof y))return new y(t);L.call(this,t,s.INFLATE)}function v(t){if(!(this instanceof v))return new v(t);L.call(this,t,s.GZIP)}function E(t){if(!(this instanceof E))return new E(t);L.call(this,t,s.GUNZIP)}function k(t){if(!(this instanceof k))return new k(t);L.call(this,t,s.DEFLATERAW)}function T(t){if(!(this instanceof T))return new T(t);L.call(this,t,s.INFLATERAW)}function x(t){if(!(this instanceof x))return new x(t);L.call(this,t,s.UNZIP)}function A(t){return t===s.Z_NO_FLUSH||t===s.Z_PARTIAL_FLUSH||t===s.Z_SYNC_FLUSH||t===s.Z_FULL_FLUSH||t===s.Z_FINISH||t===s.Z_BLOCK}function L(t,e){var a=this;if(this._opts=t=t||{},this._chunkSize=t.chunkSize||r.Z_DEFAULT_CHUNK,i.call(this,t),t.flush&&!A(t.flush))throw new Error("Invalid flush flag: "+t.flush);if(t.finishFlush&&!A(t.finishFlush))throw new Error("Invalid flush flag: "+t.finishFlush);if(this._flushFlag=t.flush||s.Z_NO_FLUSH,this._finishFlushFlag=void 0!==t.finishFlush?t.finishFlush:s.Z_FINISH,t.chunkSize&&(t.chunkSize<r.Z_MIN_CHUNK||t.chunkSize>r.Z_MAX_CHUNK))throw new Error("Invalid chunk size: "+t.chunkSize);if(t.windowBits&&(t.windowBits<r.Z_MIN_WINDOWBITS||t.windowBits>r.Z_MAX_WINDOWBITS))throw new Error("Invalid windowBits: "+t.windowBits);if(t.level&&(t.level<r.Z_MIN_LEVEL||t.level>r.Z_MAX_LEVEL))throw new Error("Invalid compression level: "+t.level);if(t.memLevel&&(t.memLevel<r.Z_MIN_MEMLEVEL||t.memLevel>r.Z_MAX_MEMLEVEL))throw new Error("Invalid memLevel: "+t.memLevel);if(t.strategy&&t.strategy!=r.Z_FILTERED&&t.strategy!=r.Z_HUFFMAN_ONLY&&t.strategy!=r.Z_RLE&&t.strategy!=r.Z_FIXED&&t.strategy!=r.Z_DEFAULT_STRATEGY)throw new Error("Invalid strategy: "+t.strategy);if(t.dictionary&&!n.isBuffer(t.dictionary))throw new Error("Invalid dictionary: it should be a Buffer instance");this._handle=new s.Zlib(e);var o=this;this._hadError=!1,this._handle.onerror=function(t,e){R(o),o._hadError=!0;var n=new Error(t);n.errno=e,n.code=r.codes[e],o.emit("error",n)};var h=r.Z_DEFAULT_COMPRESSION;"number"==typeof t.level&&(h=t.level);var f=r.Z_DEFAULT_STRATEGY;"number"==typeof t.strategy&&(f=t.strategy),this._handle.init(t.windowBits||r.Z_DEFAULT_WINDOWBITS,h,t.memLevel||r.Z_DEFAULT_MEMLEVEL,f,t.dictionary),this._buffer=n.allocUnsafe(this._chunkSize),this._offset=0,this._level=h,this._strategy=f,this.once("end",this.close),Object.defineProperty(this,"_closed",{get:function(){return!a._handle},configurable:!0,enumerable:!0})}function R(t,r){r&&e.nextTick(r),t._handle&&(t._handle.close(),t._handle=null)}function S(t){t.emit("close")}Object.defineProperty(r,"codes",{enumerable:!0,value:Object.freeze(d),writable:!1}),r.Deflate=m,r.Inflate=y,r.Gzip=v,r.Gunzip=E,r.DeflateRaw=k,r.InflateRaw=T,r.Unzip=x,r.createDeflate=function(t){return new m(t)},r.createInflate=function(t){return new y(t)},r.createDeflateRaw=function(t){return new k(t)},r.createInflateRaw=function(t){return new T(t)},r.createGzip=function(t){return new v(t)},r.createGunzip=function(t){return new E(t)},r.createUnzip=function(t){return new x(t)},r.deflate=function(t,e,r){return"function"==typeof e&&(r=e,e={}),b(new m(e),t,r)},r.deflateSync=function(t,e){return w(new m(e),t)},r.gzip=function(t,e,r){return"function"==typeof e&&(r=e,e={}),b(new v(e),t,r)},r.gzipSync=function(t,e){return w(new v(e),t)},r.deflateRaw=function(t,e,r){return"function"==typeof e&&(r=e,e={}),b(new k(e),t,r)},r.deflateRawSync=function(t,e){return w(new k(e),t)},r.unzip=function(t,e,r){return"function"==typeof e&&(r=e,e={}),b(new x(e),t,r)},r.unzipSync=function(t,e){return w(new x(e),t)},r.inflate=function(t,e,r){return"function"==typeof e&&(r=e,e={}),b(new y(e),t,r)},r.inflateSync=function(t,e){return w(new y(e),t)},r.gunzip=function(t,e,r){return"function"==typeof e&&(r=e,e={}),b(new E(e),t,r)},r.gunzipSync=function(t,e){return w(new E(e),t)},r.inflateRaw=function(t,e,r){return"function"==typeof e&&(r=e,e={}),b(new T(e),t,r)},r.inflateRawSync=function(t,e){return w(new T(e),t)},a.inherits(L,i),L.prototype.params=function(t,n,i){if(t<r.Z_MIN_LEVEL||t>r.Z_MAX_LEVEL)throw new RangeError("Invalid compression level: "+t);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!==t||this._strategy!==n){var a=this;this.flush(s.Z_SYNC_FLUSH,(function(){o(a._handle,"zlib binding closed"),a._handle.params(t,n),a._hadError||(a._level=t,a._strategy=n,i&&i())}))}else e.nextTick(i)},L.prototype.reset=function(){return o(this._handle,"zlib binding closed"),this._handle.reset()},L.prototype._flush=function(t){this._transform(n.alloc(0),"",t)},L.prototype.flush=function(t,r){var i=this,a=this._writableState;("function"==typeof t||void 0===t&&!r)&&(r=t,t=s.Z_FULL_FLUSH),a.ended?r&&e.nextTick(r):a.ending?r&&this.once("end",r):a.needDrain?r&&this.once("drain",(function(){return i.flush(t,r)})):(this._flushFlag=t,this.write(n.alloc(0),"",r))},L.prototype.close=function(t){R(this,t),e.nextTick(S,this)},L.prototype._transform=function(t,e,r){var i,a=this._writableState,o=(a.ending||a.ended)&&(!t||a.length===t.length);return null===t||n.isBuffer(t)?this._handle?(o?i=this._finishFlushFlag:(i=this._flushFlag,t.length>=a.length&&(this._flushFlag=this._opts.flush||s.Z_NO_FLUSH)),void this._processChunk(t,i,r)):r(new Error("zlib binding closed")):r(new Error("invalid input"))},L.prototype._processChunk=function(t,e,r){var i=t&&t.length,s=this._chunkSize-this._offset,a=0,l=this,u="function"==typeof r;if(!u){var c,d=[],p=0;this.on("error",(function(t){c=t})),o(this._handle,"zlib binding closed");do{var _=this._handle.writeSync(e,t,a,i,this._buffer,this._offset,s)}while(!this._hadError&&w(_[0],_[1]));if(this._hadError)throw c;if(p>=h)throw R(this),new RangeError(f);var g=n.concat(d,p);return R(this),g}o(this._handle,"zlib binding closed");var b=this._handle.write(e,t,a,i,this._buffer,this._offset,s);function w(h,f){if(this&&(this.buffer=null,this.callback=null),!l._hadError){var c=s-f;if(o(c>=0,"have should not go down"),c>0){var _=l._buffer.slice(l._offset,l._offset+c);l._offset+=c,u?l.push(_):(d.push(_),p+=_.length)}if((0===f||l._offset>=l._chunkSize)&&(s=l._chunkSize,l._offset=0,l._buffer=n.allocUnsafe(l._chunkSize)),0===f){if(a+=i-h,i=h,!u)return!0;var g=l._handle.write(e,t,a,i,l._buffer,l._offset,l._chunkSize);return g.callback=w,void(g.buffer=t)}if(!u)return!1;r()}}b.buffer=t,b.callback=w},a.inherits(m,L),a.inherits(y,L),a.inherits(v,L),a.inherits(E,L),a.inherits(k,L),a.inherits(T,L),a.inherits(x,L)}).call(this,t("_process"))},{"./binding":29,_process:51,assert:23,buffer:32,stream:64,util:69}],31:[function(t,e,r){(function(e){"use strict";var n=t("buffer"),i=n.Buffer,s=n.SlowBuffer,a=n.kMaxLength||2147483647;r.alloc=function(t,e,r){if("function"==typeof i.alloc)return i.alloc(t,e,r);if("number"==typeof r)throw new TypeError("encoding must not be number");if("number"!=typeof t)throw new TypeError("size must be a number");if(t>a)throw new RangeError("size is too large");var n=r,s=e;void 0===s&&(n=void 0,s=0);var o=new i(t);if("string"==typeof s)for(var h=new i(s,n),f=h.length,l=-1;++l<t;)o[l]=h[l%f];else o.fill(s);return o},r.allocUnsafe=function(t){if("function"==typeof i.allocUnsafe)return i.allocUnsafe(t);if("number"!=typeof t)throw new TypeError("size must be a number");if(t>a)throw new RangeError("size is too large");return new i(t)},r.from=function(t,r,n){if("function"==typeof i.from&&(!e.Uint8Array||Uint8Array.from!==i.from))return i.from(t,r,n);if("number"==typeof t)throw new TypeError('"value" argument must not be a number');if("string"==typeof t)return new i(t,r);if("undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer){var s=r;if(1===arguments.length)return new i(t);void 0===s&&(s=0);var a=n;if(void 0===a&&(a=t.byteLength-s),s>=t.byteLength)throw new RangeError("'offset' is out of bounds");if(a>t.byteLength-s)throw new RangeError("'length' is out of bounds");return new i(t.slice(s,s+a))}if(i.isBuffer(t)){var o=new i(t.length);return t.copy(o,0,0,t.length),o}if(t){if(Array.isArray(t)||"undefined"!=typeof ArrayBuffer&&t.buffer instanceof ArrayBuffer||"length"in t)return new i(t);if("Buffer"===t.type&&Array.isArray(t.data))return new i(t.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")},r.allocUnsafeSlow=function(t){if("function"==typeof i.allocUnsafeSlow)return i.allocUnsafeSlow(t);if("number"!=typeof t)throw new TypeError("size must be a number");if(t>=a)throw new RangeError("size is too large");return new s(t)}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{buffer:32}],32:[function(t,e,r){(function(e){
 /*!
  * The buffer module from node.js, for the browser.
  *
  * @author   Feross Aboukhadijeh <https://feross.org>
  * @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
-
-/**
- * If `Buffer.TYPED_ARRAY_SUPPORT`:
- *   === true    Use Uint8Array implementation (fastest)
- *   === false   Print warning and recommend using `buffer` v4.x which has an Object
- *               implementation (most compatible, even IE6)
- *
- * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
- * Opera 11.6+, iOS 4.2+.
- *
- * We report that the browser does not support typed arrays if the are not subclassable
- * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
- * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
- * for __proto__ and has a buggy typed array implementation.
- */
-Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
-
-if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
-    typeof console.error === 'function') {
-  console.error(
-    'This browser lacks typed array (Uint8Array) support which is required by ' +
-    '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
-  )
-}
-
-function typedArraySupport () {
-  // Can typed array instances can be augmented?
-  try {
-    var arr = new Uint8Array(1)
-    arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
-    return arr.foo() === 42
-  } catch (e) {
-    return false
-  }
-}
-
-Object.defineProperty(Buffer.prototype, 'parent', {
-  enumerable: true,
-  get: function () {
-    if (!Buffer.isBuffer(this)) return undefined
-    return this.buffer
-  }
-})
-
-Object.defineProperty(Buffer.prototype, 'offset', {
-  enumerable: true,
-  get: function () {
-    if (!Buffer.isBuffer(this)) return undefined
-    return this.byteOffset
-  }
-})
-
-function createBuffer (length) {
-  if (length > K_MAX_LENGTH) {
-    throw new RangeError('The value "' + length + '" is invalid for option "size"')
-  }
-  // Return an augmented `Uint8Array` instance
-  var buf = new Uint8Array(length)
-  buf.__proto__ = Buffer.prototype
-  return buf
-}
-
-/**
- * The Buffer constructor returns instances of `Uint8Array` that have their
- * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
- * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
- * and the `Uint8Array` methods. Square bracket notation works as expected -- it
- * returns a single octet.
- *
- * The `Uint8Array` prototype remains unmodified.
- */
-
-function Buffer (arg, encodingOrOffset, length) {
-  // Common case.
-  if (typeof arg === 'number') {
-    if (typeof encodingOrOffset === 'string') {
-      throw new TypeError(
-        'The "string" argument must be of type string. Received type number'
-      )
-    }
-    return allocUnsafe(arg)
-  }
-  return from(arg, encodingOrOffset, length)
-}
-
-// 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.poolSize = 8192 // not used by this implementation
-
-function from (value, encodingOrOffset, length) {
-  if (typeof value === 'string') {
-    return fromString(value, encodingOrOffset)
-  }
-
-  if (ArrayBuffer.isView(value)) {
-    return fromArrayLike(value)
-  }
-
-  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 (isInstance(value, ArrayBuffer) ||
-      (value && isInstance(value.buffer, ArrayBuffer))) {
-    return fromArrayBuffer(value, encodingOrOffset, length)
-  }
-
-  if (typeof value === 'number') {
-    throw new TypeError(
-      'The "value" argument must not be of type number. Received type number'
-    )
-  }
-
-  var valueOf = value.valueOf && value.valueOf()
-  if (valueOf != null && valueOf !== value) {
-    return Buffer.from(valueOf, encodingOrOffset, length)
-  }
-
-  var b = fromObject(value)
-  if (b) return b
-
-  if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
-      typeof value[Symbol.toPrimitive] === 'function') {
-    return Buffer.from(
-      value[Symbol.toPrimitive]('string'), encodingOrOffset, length
-    )
-  }
-
-  throw new TypeError(
-    'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
-    'or Array-like Object. Received type ' + (typeof value)
-  )
-}
-
-/**
- * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
- * if value is a number.
- * Buffer.from(str[, encoding])
- * Buffer.from(array)
- * Buffer.from(buffer)
- * Buffer.from(arrayBuffer[, byteOffset[, length]])
- **/
-Buffer.from = function (value, encodingOrOffset, length) {
-  return from(value, encodingOrOffset, length)
-}
-
-// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
-// https://github.com/feross/buffer/pull/148
-Buffer.prototype.__proto__ = Uint8Array.prototype
-Buffer.__proto__ = Uint8Array
-
-function assertSize (size) {
-  if (typeof size !== 'number') {
-    throw new TypeError('"size" argument must be of type number')
-  } else if (size < 0) {
-    throw new RangeError('The value "' + size + '" is invalid for option "size"')
-  }
-}
-
-function alloc (size, fill, encoding) {
-  assertSize(size)
-  if (size <= 0) {
-    return createBuffer(size)
-  }
-  if (fill !== undefined) {
-    // Only pay attention to encoding if it's a string. This
-    // prevents accidentally sending in a number that would
-    // be 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 allocUnsafe (size) {
-  assertSize(size)
-  return createBuffer(size < 0 ? 0 : checked(size) | 0)
-}
-
-/**
- * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
- * */
-Buffer.allocUnsafe = function (size) {
-  return allocUnsafe(size)
-}
-/**
- * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
- */
-Buffer.allocUnsafeSlow = function (size) {
-  return allocUnsafe(size)
-}
-
-function fromString (string, encoding) {
-  if (typeof encoding !== 'string' || encoding === '') {
-    encoding = 'utf8'
-  }
-
-  if (!Buffer.isEncoding(encoding)) {
-    throw new TypeError('Unknown encoding: ' + encoding)
-  }
-
-  var length = byteLength(string, encoding) | 0
-  var buf = createBuffer(length)
-
-  var actual = buf.write(string, encoding)
-
-  if (actual !== length) {
-    // Writing a hex string, for example, that contains invalid characters will
-    // cause everything after the first invalid character to be ignored. (e.g.
-    // 'abxxcd' will be treated as 'ab')
-    buf = buf.slice(0, actual)
-  }
-
-  return buf
-}
-
-function fromArrayLike (array) {
-  var length = array.length < 0 ? 0 : checked(array.length) | 0
-  var buf = createBuffer(length)
-  for (var i = 0; i < length; i += 1) {
-    buf[i] = array[i] & 255
-  }
-  return buf
-}
-
-function fromArrayBuffer (array, byteOffset, length) {
-  if (byteOffset < 0 || array.byteLength < byteOffset) {
-    throw new RangeError('"offset" is outside of buffer bounds')
-  }
-
-  if (array.byteLength < byteOffset + (length || 0)) {
-    throw new RangeError('"length" is outside of buffer bounds')
-  }
-
-  var buf
-  if (byteOffset === undefined && length === undefined) {
-    buf = new Uint8Array(array)
-  } else if (length === undefined) {
-    buf = new Uint8Array(array, byteOffset)
-  } else {
-    buf = new Uint8Array(array, byteOffset, length)
-  }
-
-  // Return an augmented `Uint8Array` instance
-  buf.__proto__ = Buffer.prototype
-  return buf
-}
-
-function fromObject (obj) {
-  if (Buffer.isBuffer(obj)) {
-    var len = checked(obj.length) | 0
-    var buf = createBuffer(len)
-
-    if (buf.length === 0) {
-      return buf
-    }
-
-    obj.copy(buf, 0, 0, len)
-    return buf
-  }
-
-  if (obj.length !== undefined) {
-    if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
-      return createBuffer(0)
-    }
-    return fromArrayLike(obj)
-  }
-
-  if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
-    return fromArrayLike(obj.data)
-  }
-}
-
-function checked (length) {
-  // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
-  // length is NaN (which is otherwise coerced to zero.)
-  if (length >= K_MAX_LENGTH) {
-    throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
-                         'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
-  }
-  return length | 0
-}
-
-function SlowBuffer (length) {
-  if (+length != length) { // eslint-disable-line eqeqeq
-    length = 0
-  }
-  return Buffer.alloc(+length)
-}
-
-Buffer.isBuffer = function isBuffer (b) {
-  return b != null && b._isBuffer === true &&
-    b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
-}
-
-Buffer.compare = function compare (a, b) {
-  if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
-  if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
-  if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
-    throw new TypeError(
-      'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
-    )
-  }
-
-  if (a === b) return 0
-
-  var x = a.length
-  var y = b.length
-
-  for (var i = 0, len = Math.min(x, y); i < len; ++i) {
-    if (a[i] !== b[i]) {
-      x = a[i]
-      y = b[i]
-      break
-    }
-  }
-
-  if (x < y) return -1
-  if (y < x) return 1
-  return 0
-}
-
-Buffer.isEncoding = function isEncoding (encoding) {
-  switch (String(encoding).toLowerCase()) {
-    case 'hex':
-    case 'utf8':
-    case 'utf-8':
-    case 'ascii':
-    case 'latin1':
-    case 'binary':
-    case 'base64':
-    case 'ucs2':
-    case 'ucs-2':
-    case 'utf16le':
-    case 'utf-16le':
-      return true
-    default:
-      return false
-  }
-}
-
-Buffer.concat = function concat (list, length) {
-  if (!Array.isArray(list)) {
-    throw new TypeError('"list" argument must be an Array of Buffers')
-  }
-
-  if (list.length === 0) {
-    return Buffer.alloc(0)
-  }
-
-  var i
-  if (length === undefined) {
-    length = 0
-    for (i = 0; i < list.length; ++i) {
-      length += list[i].length
-    }
-  }
-
-  var buffer = Buffer.allocUnsafe(length)
-  var pos = 0
-  for (i = 0; i < list.length; ++i) {
-    var buf = list[i]
-    if (isInstance(buf, Uint8Array)) {
-      buf = Buffer.from(buf)
-    }
-    if (!Buffer.isBuffer(buf)) {
-      throw new TypeError('"list" argument must be an Array of Buffers')
-    }
-    buf.copy(buffer, pos)
-    pos += buf.length
-  }
-  return buffer
-}
-
-function byteLength (string, encoding) {
-  if (Buffer.isBuffer(string)) {
-    return string.length
-  }
-  if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
-    return string.byteLength
-  }
-  if (typeof string !== 'string') {
-    throw new TypeError(
-      'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
-      'Received type ' + typeof string
-    )
-  }
-
-  var len = string.length
-  var mustMatch = (arguments.length > 2 && arguments[2] === true)
-  if (!mustMatch && len === 0) return 0
-
-  // Use a for loop to avoid recursion
-  var loweredCase = false
-  for (;;) {
-    switch (encoding) {
-      case 'ascii':
-      case 'latin1':
-      case 'binary':
-        return len
-      case 'utf8':
-      case 'utf-8':
-        return utf8ToBytes(string).length
-      case 'ucs2':
-      case 'ucs-2':
-      case 'utf16le':
-      case 'utf-16le':
-        return len * 2
-      case 'hex':
-        return len >>> 1
-      case 'base64':
-        return base64ToBytes(string).length
-      default:
-        if (loweredCase) {
-          return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
-        }
-        encoding = ('' + encoding).toLowerCase()
-        loweredCase = true
-    }
-  }
-}
-Buffer.byteLength = byteLength
-
-function slowToString (encoding, start, end) {
-  var loweredCase = false
-
-  // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
-  // property of a typed array.
-
-  // This behaves neither like String nor Uint8Array in that we set start/end
-  // to their upper/lower bounds if the value passed is out of range.
-  // undefined is handled specially as per ECMA-262 6th Edition,
-  // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
-  if (start === undefined || start < 0) {
-    start = 0
-  }
-  // Return early if start > this.length. Done here to prevent potential uint32
-  // coercion fail below.
-  if (start > this.length) {
-    return ''
-  }
-
-  if (end === undefined || end > this.length) {
-    end = this.length
-  }
-
-  if (end <= 0) {
-    return ''
-  }
-
-  // Force 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)
-
-      case 'ascii':
-        return asciiSlice(this, start, end)
-
-      case 'latin1':
-      case 'binary':
-        return latin1Slice(this, start, end)
-
-      case 'base64':
-        return base64Slice(this, start, end)
-
-      case 'ucs2':
-      case 'ucs-2':
-      case 'utf16le':
-      case 'utf-16le':
-        return utf16leSlice(this, start, end)
-
-      default:
-        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
-        encoding = (encoding + '').toLowerCase()
-        loweredCase = true
-    }
-  }
-}
-
-// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
-// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
-// reliably in a browserify context because there could be multiple different
-// copies of the 'buffer' package in use. This method works even for Buffer
-// instances that were created from another copy of the `buffer` package.
-// See: https://github.com/feross/buffer/issues/154
-Buffer.prototype._isBuffer = true
-
-function swap (b, n, m) {
-  var i = b[n]
-  b[n] = b[m]
-  b[m] = i
-}
-
-Buffer.prototype.swap16 = function swap16 () {
-  var len = this.length
-  if (len % 2 !== 0) {
-    throw new RangeError('Buffer size must be a multiple of 16-bits')
-  }
-  for (var i = 0; i < len; i += 2) {
-    swap(this, i, i + 1)
-  }
-  return this
-}
-
-Buffer.prototype.swap32 = function swap32 () {
-  var len = this.length
-  if (len % 4 !== 0) {
-    throw new RangeError('Buffer size must be a multiple of 32-bits')
-  }
-  for (var i = 0; i < len; i += 4) {
-    swap(this, i, i + 3)
-    swap(this, i + 1, i + 2)
-  }
-  return this
-}
-
-Buffer.prototype.swap64 = function swap64 () {
-  var len = this.length
-  if (len % 8 !== 0) {
-    throw new RangeError('Buffer size must be a multiple of 64-bits')
-  }
-  for (var i = 0; i < len; i += 8) {
-    swap(this, i, i + 7)
-    swap(this, i + 1, i + 6)
-    swap(this, i + 2, i + 5)
-    swap(this, i + 3, i + 4)
-  }
-  return this
-}
-
-Buffer.prototype.toString = function toString () {
-  var length = this.length
-  if (length === 0) return ''
-  if (arguments.length === 0) return utf8Slice(this, 0, length)
-  return slowToString.apply(this, arguments)
-}
-
-Buffer.prototype.toLocaleString = Buffer.prototype.toString
-
-Buffer.prototype.equals = function equals (b) {
-  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
-  if (this === b) return true
-  return Buffer.compare(this, b) === 0
-}
-
-Buffer.prototype.inspect = function inspect () {
-  var str = ''
-  var max = exports.INSPECT_MAX_BYTES
-  str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
-  if (this.length > max) str += ' ... '
-  return '<Buffer ' + str + '>'
-}
-
-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,require("buffer").Buffer)
-},{"base64-js":27,"buffer":32,"ieee754":35}],33:[function(require,module,exports){
-(function (Buffer){
-// 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,{"isBuffer":require("../../is-buffer/index.js")})
-},{"../../is-buffer/index.js":37}],34:[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.
-
-function EventEmitter() {
-  this._events = this._events || {};
-  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.
-EventEmitter.defaultMaxListeners = 10;
-
-// 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(n) {
-  if (!isNumber(n) || n < 0 || isNaN(n))
-    throw TypeError('n must be a positive number');
-  this._maxListeners = n;
-  return this;
-};
-
-EventEmitter.prototype.emit = function(type) {
-  var er, handler, len, args, i, listeners;
-
-  if (!this._events)
-    this._events = {};
-
-  // If there is no 'error' event listener then throw.
-  if (type === 'error') {
-    if (!this._events.error ||
-        (isObject(this._events.error) && !this._events.error.length)) {
-      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('Uncaught, unspecified "error" event. (' + er + ')');
-        err.context = er;
-        throw err;
-      }
-    }
-  }
-
-  handler = this._events[type];
-
-  if (isUndefined(handler))
-    return false;
-
-  if (isFunction(handler)) {
-    switch (arguments.length) {
-      // fast cases
-      case 1:
-        handler.call(this);
-        break;
-      case 2:
-        handler.call(this, arguments[1]);
-        break;
-      case 3:
-        handler.call(this, arguments[1], arguments[2]);
-        break;
-      // slower
-      default:
-        args = Array.prototype.slice.call(arguments, 1);
-        handler.apply(this, args);
-    }
-  } else if (isObject(handler)) {
-    args = Array.prototype.slice.call(arguments, 1);
-    listeners = handler.slice();
-    len = listeners.length;
-    for (i = 0; i < len; i++)
-      listeners[i].apply(this, args);
-  }
-
-  return true;
-};
-
-EventEmitter.prototype.addListener = function(type, listener) {
-  var m;
-
-  if (!isFunction(listener))
-    throw TypeError('listener must be a function');
-
-  if (!this._events)
-    this._events = {};
-
-  // To avoid recursion in the case that type === "newListener"! Before
-  // adding it to the listeners, first emit "newListener".
-  if (this._events.newListener)
-    this.emit('newListener', type,
-              isFunction(listener.listener) ?
-              listener.listener : listener);
-
-  if (!this._events[type])
-    // Optimize the case of one listener. Don't need the extra array object.
-    this._events[type] = listener;
-  else if (isObject(this._events[type]))
-    // If we've already got an array, just append.
-    this._events[type].push(listener);
-  else
-    // Adding the second element, need to change to array.
-    this._events[type] = [this._events[type], listener];
-
-  // Check for listener leak
-  if (isObject(this._events[type]) && !this._events[type].warned) {
-    if (!isUndefined(this._maxListeners)) {
-      m = this._maxListeners;
-    } else {
-      m = EventEmitter.defaultMaxListeners;
-    }
-
-    if (m && m > 0 && this._events[type].length > m) {
-      this._events[type].warned = true;
-      console.error('(node) warning: possible EventEmitter memory ' +
-                    'leak detected. %d listeners added. ' +
-                    'Use emitter.setMaxListeners() to increase limit.',
-                    this._events[type].length);
-      if (typeof console.trace === 'function') {
-        // not supported in IE 10
-        console.trace();
-      }
-    }
-  }
-
-  return this;
-};
-
-EventEmitter.prototype.on = EventEmitter.prototype.addListener;
-
-EventEmitter.prototype.once = function(type, listener) {
-  if (!isFunction(listener))
-    throw TypeError('listener must be a function');
-
-  var fired = false;
-
-  function g() {
-    this.removeListener(type, g);
-
-    if (!fired) {
-      fired = true;
-      listener.apply(this, arguments);
-    }
-  }
-
-  g.listener = listener;
-  this.on(type, g);
-
-  return this;
-};
-
-// emits a 'removeListener' event iff the listener was removed
-EventEmitter.prototype.removeListener = function(type, listener) {
-  var list, position, length, i;
-
-  if (!isFunction(listener))
-    throw TypeError('listener must be a function');
-
-  if (!this._events || !this._events[type])
-    return this;
-
-  list = this._events[type];
-  length = list.length;
-  position = -1;
-
-  if (list === listener ||
-      (isFunction(list.listener) && list.listener === listener)) {
-    delete this._events[type];
-    if (this._events.removeListener)
-      this.emit('removeListener', type, listener);
-
-  } else if (isObject(list)) {
-    for (i = length; i-- > 0;) {
-      if (list[i] === listener ||
-          (list[i].listener && list[i].listener === listener)) {
-        position = i;
-        break;
-      }
-    }
-
-    if (position < 0)
-      return this;
-
-    if (list.length === 1) {
-      list.length = 0;
-      delete this._events[type];
-    } else {
-      list.splice(position, 1);
-    }
-
-    if (this._events.removeListener)
-      this.emit('removeListener', type, listener);
-  }
-
-  return this;
-};
-
-EventEmitter.prototype.removeAllListeners = function(type) {
-  var key, listeners;
-
-  if (!this._events)
-    return this;
-
-  // not listening for removeListener, no need to emit
-  if (!this._events.removeListener) {
-    if (arguments.length === 0)
-      this._events = {};
-    else if (this._events[type])
-      delete this._events[type];
-    return this;
-  }
-
-  // emit removeListener for all listeners on all events
-  if (arguments.length === 0) {
-    for (key in this._events) {
-      if (key === 'removeListener') continue;
-      this.removeAllListeners(key);
-    }
-    this.removeAllListeners('removeListener');
-    this._events = {};
-    return this;
-  }
-
-  listeners = this._events[type];
-
-  if (isFunction(listeners)) {
-    this.removeListener(type, listeners);
-  } else if (listeners) {
-    // LIFO order
-    while (listeners.length)
-      this.removeListener(type, listeners[listeners.length - 1]);
-  }
-  delete this._events[type];
-
-  return this;
-};
-
-EventEmitter.prototype.listeners = function(type) {
-  var ret;
-  if (!this._events || !this._events[type])
-    ret = [];
-  else if (isFunction(this._events[type]))
-    ret = [this._events[type]];
-  else
-    ret = this._events[type].slice();
-  return ret;
-};
-
-EventEmitter.prototype.listenerCount = function(type) {
-  if (this._events) {
-    var evlistener = this._events[type];
-
-    if (isFunction(evlistener))
-      return 1;
-    else if (evlistener)
-      return evlistener.length;
-  }
-  return 0;
-};
-
-EventEmitter.listenerCount = function(emitter, type) {
-  return emitter.listenerCount(type);
-};
-
-function isFunction(arg) {
-  return typeof arg === 'function';
-}
-
-function isNumber(arg) {
-  return typeof arg === 'number';
-}
-
-function isObject(arg) {
-  return typeof arg === 'object' && arg !== null;
-}
-
-function isUndefined(arg) {
-  return arg === void 0;
-}
-
-},{}],35:[function(require,module,exports){
-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
-}
-
-},{}],36:[function(require,module,exports){
-arguments[4][24][0].apply(exports,arguments)
-},{"dup":24}],37:[function(require,module,exports){
+"use strict";var n=t("base64-js"),i=t("ieee754");r.Buffer=e,r.SlowBuffer=function(t){+t!=t&&(t=0);return e.alloc(+t)},r.INSPECT_MAX_BYTES=50;var s=2147483647;function a(t){if(t>s)throw new RangeError('The value "'+t+'" is invalid for option "size"');var r=new Uint8Array(t);return r.__proto__=e.prototype,r}function e(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 f(t)}return o(t,e,r)}function o(t,r,n){if("string"==typeof t)return function(t,r){"string"==typeof r&&""!==r||(r="utf8");if(!e.isEncoding(r))throw new TypeError("Unknown encoding: "+r);var n=0|c(t,r),i=a(n),s=i.write(t,r);s!==n&&(i=i.slice(0,s));return i}(t,r);if(ArrayBuffer.isView(t))return l(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(F(t,ArrayBuffer)||t&&F(t.buffer,ArrayBuffer))return function(t,r,n){if(r<0||t.byteLength<r)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<r+(n||0))throw new RangeError('"length" is outside of buffer bounds');var i;i=void 0===r&&void 0===n?new Uint8Array(t):void 0===n?new Uint8Array(t,r):new Uint8Array(t,r,n);return i.__proto__=e.prototype,i}(t,r,n);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');var i=t.valueOf&&t.valueOf();if(null!=i&&i!==t)return e.from(i,r,n);var s=function(t){if(e.isBuffer(t)){var r=0|u(t.length),n=a(r);return 0===n.length||t.copy(n,0,0,r),n}if(void 0!==t.length)return"number"!=typeof t.length||Z(t.length)?a(0):l(t);if("Buffer"===t.type&&Array.isArray(t.data))return l(t.data)}(t);if(s)return s;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return e.from(t[Symbol.toPrimitive]("string"),r,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function h(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function f(t){return h(t),a(t<0?0:0|u(t))}function l(t){for(var e=t.length<0?0:0|u(t.length),r=a(e),n=0;n<e;n+=1)r[n]=255&t[n];return r}function u(t){if(t>=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|t}function c(t,r){if(e.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||F(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 n=t.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===n)return 0;for(var s=!1;;)switch(r){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return M(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return U(t).length;default:if(s)return i?-1:M(t).length;r=(""+r).toLowerCase(),s=!0}}function d(t,e,r){var n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return R(this,e,r);case"utf8":case"utf-8":return T(this,e,r);case"ascii":return A(this,e,r);case"latin1":case"binary":return L(this,e,r);case"base64":return k(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}}function p(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function _(t,r,n,i,s){if(0===t.length)return-1;if("string"==typeof n?(i=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),Z(n=+n)&&(n=s?0:t.length-1),n<0&&(n=t.length+n),n>=t.length){if(s)return-1;n=t.length-1}else if(n<0){if(!s)return-1;n=0}if("string"==typeof r&&(r=e.from(r,i)),e.isBuffer(r))return 0===r.length?-1:g(t,r,n,i,s);if("number"==typeof r)return r&=255,"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(t,r,n):Uint8Array.prototype.lastIndexOf.call(t,r,n):g(t,[r],n,i,s);throw new TypeError("val must be string, number or Buffer")}function g(t,e,r,n,i){var s,a=1,o=t.length,h=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;a=2,o/=2,h/=2,r/=2}function f(t,e){return 1===a?t[e]:t.readUInt16BE(e*a)}if(i){var l=-1;for(s=r;s<o;s++)if(f(t,s)===f(e,-1===l?0:s-l)){if(-1===l&&(l=s),s-l+1===h)return l*a}else-1!==l&&(s-=s-l),l=-1}else for(r+h>o&&(r=o-h),s=r;s>=0;s--){for(var u=!0,c=0;c<h;c++)if(f(t,s+c)!==f(e,c)){u=!1;break}if(u)return s}return-1}function b(t,e,r,n){r=Number(r)||0;var i=t.length-r;n?(n=Number(n))>i&&(n=i):n=i;var s=e.length;n>s/2&&(n=s/2);for(var a=0;a<n;++a){var o=parseInt(e.substr(2*a,2),16);if(Z(o))return a;t[r+a]=o}return a}function w(t,e,r,n){return P(M(e,t.length-r),t,r,n)}function m(t,e,r,n){return P(function(t){for(var e=[],r=0;r<t.length;++r)e.push(255&t.charCodeAt(r));return e}(e),t,r,n)}function y(t,e,r,n){return m(t,e,r,n)}function v(t,e,r,n){return P(U(e),t,r,n)}function E(t,e,r,n){return P(function(t,e){for(var r,n,i,s=[],a=0;a<t.length&&!((e-=2)<0);++a)n=(r=t.charCodeAt(a))>>8,i=r%256,s.push(i),s.push(n);return s}(e,t.length-r),t,r,n)}function k(t,e,r){return 0===e&&r===t.length?n.fromByteArray(t):n.fromByteArray(t.slice(e,r))}function T(t,e,r){r=Math.min(t.length,r);for(var n=[],i=e;i<r;){var s,a,o,h,f=t[i],l=null,u=f>239?4:f>223?3:f>191?2:1;if(i+u<=r)switch(u){case 1:f<128&&(l=f);break;case 2:128==(192&(s=t[i+1]))&&(h=(31&f)<<6|63&s)>127&&(l=h);break;case 3:s=t[i+1],a=t[i+2],128==(192&s)&&128==(192&a)&&(h=(15&f)<<12|(63&s)<<6|63&a)>2047&&(h<55296||h>57343)&&(l=h);break;case 4:s=t[i+1],a=t[i+2],o=t[i+3],128==(192&s)&&128==(192&a)&&128==(192&o)&&(h=(15&f)<<18|(63&s)<<12|(63&a)<<6|63&o)>65535&&h<1114112&&(l=h)}null===l?(l=65533,u=1):l>65535&&(l-=65536,n.push(l>>>10&1023|55296),l=56320|1023&l),n.push(l),i+=u}return function(t){var e=t.length;if(e<=x)return String.fromCharCode.apply(String,t);var r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=x));return r}(n)}r.kMaxLength=s,e.TYPED_ARRAY_SUPPORT=function(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()}catch(t){return!1}}(),e.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||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."),Object.defineProperty(e.prototype,"parent",{enumerable:!0,get:function(){if(e.isBuffer(this))return this.buffer}}),Object.defineProperty(e.prototype,"offset",{enumerable:!0,get:function(){if(e.isBuffer(this))return this.byteOffset}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&e[Symbol.species]===e&&Object.defineProperty(e,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),e.poolSize=8192,e.from=function(t,e,r){return o(t,e,r)},e.prototype.__proto__=Uint8Array.prototype,e.__proto__=Uint8Array,e.alloc=function(t,e,r){return function(t,e,r){return h(t),t<=0?a(t):void 0!==e?"string"==typeof r?a(t).fill(e,r):a(t).fill(e):a(t)}(t,e,r)},e.allocUnsafe=function(t){return f(t)},e.allocUnsafeSlow=function(t){return f(t)},e.isBuffer=function(t){return null!=t&&!0===t._isBuffer&&t!==e.prototype},e.compare=function(t,r){if(F(t,Uint8Array)&&(t=e.from(t,t.offset,t.byteLength)),F(r,Uint8Array)&&(r=e.from(r,r.offset,r.byteLength)),!e.isBuffer(t)||!e.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(t===r)return 0;for(var n=t.length,i=r.length,s=0,a=Math.min(n,i);s<a;++s)if(t[s]!==r[s]){n=t[s],i=r[s];break}return n<i?-1:i<n?1:0},e.isEncoding=function(t){switch(String(t).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!0;default:return!1}},e.concat=function(t,r){if(!Array.isArray(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return e.alloc(0);var n;if(void 0===r)for(r=0,n=0;n<t.length;++n)r+=t[n].length;var i=e.allocUnsafe(r),s=0;for(n=0;n<t.length;++n){var a=t[n];if(F(a,Uint8Array)&&(a=e.from(a)),!e.isBuffer(a))throw new TypeError('"list" argument must be an Array of Buffers');a.copy(i,s),s+=a.length}return i},e.byteLength=c,e.prototype._isBuffer=!0,e.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var e=0;e<t;e+=2)p(this,e,e+1);return this},e.prototype.swap32=function(){var t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var e=0;e<t;e+=4)p(this,e,e+3),p(this,e+1,e+2);return this},e.prototype.swap64=function(){var t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var e=0;e<t;e+=8)p(this,e,e+7),p(this,e+1,e+6),p(this,e+2,e+5),p(this,e+3,e+4);return this},e.prototype.toString=function(){var t=this.length;return 0===t?"":0===arguments.length?T(this,0,t):d.apply(this,arguments)},e.prototype.toLocaleString=e.prototype.toString,e.prototype.equals=function(t){if(!e.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===e.compare(this,t)},e.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+=" ... "),"<Buffer "+t+">"},e.prototype.compare=function(t,r,n,i,s){if(F(t,Uint8Array)&&(t=e.from(t,t.offset,t.byteLength)),!e.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===r&&(r=0),void 0===n&&(n=t?t.length:0),void 0===i&&(i=0),void 0===s&&(s=this.length),r<0||n>t.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&r>=n)return 0;if(i>=s)return-1;if(r>=n)return 1;if(this===t)return 0;for(var a=(s>>>=0)-(i>>>=0),o=(n>>>=0)-(r>>>=0),h=Math.min(a,o),f=this.slice(i,s),l=t.slice(r,n),u=0;u<h;++u)if(f[u]!==l[u]){a=f[u],o=l[u];break}return a<o?-1:o<a?1:0},e.prototype.includes=function(t,e,r){return-1!==this.indexOf(t,e,r)},e.prototype.indexOf=function(t,e,r){return _(this,t,e,r,!0)},e.prototype.lastIndexOf=function(t,e,r){return _(this,t,e,r,!1)},e.prototype.write=function(t,e,r,n){if(void 0===e)n="utf8",r=this.length,e=0;else if(void 0===r&&"string"==typeof e)n=e,r=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e>>>=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 s=!1;;)switch(n){case"hex":return b(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 y(this,t,e,r);case"base64":return v(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,t,e,r);default:if(s)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),s=!0}},e.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var x=4096;function A(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;i<r;++i)n+=String.fromCharCode(127&t[i]);return n}function L(t,e,r){var n="";r=Math.min(t.length,r);for(var i=e;i<r;++i)n+=String.fromCharCode(t[i]);return n}function R(t,e,r){var n=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>n)&&(r=n);for(var i="",s=e;s<r;++s)i+=D(t[s]);return i}function S(t,e,r){for(var n=t.slice(e,r),i="",s=0;s<n.length;s+=2)i+=String.fromCharCode(n[s]+256*n[s+1]);return i}function I(t,e,r){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function O(t,r,n,i,s,a){if(!e.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(r>s||r<a)throw new RangeError('"value" argument is out of bounds');if(n+i>t.length)throw new RangeError("Index out of range")}function C(t,e,r,n,i,s){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,n,s){return e=+e,r>>>=0,s||C(t,0,r,4),i.write(t,e,r,n,23,4),r+4}function z(t,e,r,n,s){return e=+e,r>>>=0,s||C(t,0,r,8),i.write(t,e,r,n,52,8),r+8}e.prototype.slice=function(t,r){var n=this.length;(t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(r=void 0===r?n:~~r)<0?(r+=n)<0&&(r=0):r>n&&(r=n),r<t&&(r=t);var i=this.subarray(t,r);return i.__proto__=e.prototype,i},e.prototype.readUIntLE=function(t,e,r){t>>>=0,e>>>=0,r||I(t,e,this.length);for(var n=this[t],i=1,s=0;++s<e&&(i*=256);)n+=this[t+s]*i;return n},e.prototype.readUIntBE=function(t,e,r){t>>>=0,e>>>=0,r||I(t,e,this.length);for(var n=this[t+--e],i=1;e>0&&(i*=256);)n+=this[t+--e]*i;return n},e.prototype.readUInt8=function(t,e){return t>>>=0,e||I(t,1,this.length),this[t]},e.prototype.readUInt16LE=function(t,e){return t>>>=0,e||I(t,2,this.length),this[t]|this[t+1]<<8},e.prototype.readUInt16BE=function(t,e){return t>>>=0,e||I(t,2,this.length),this[t]<<8|this[t+1]},e.prototype.readUInt32LE=function(t,e){return t>>>=0,e||I(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},e.prototype.readUInt32BE=function(t,e){return t>>>=0,e||I(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},e.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||I(t,e,this.length);for(var n=this[t],i=1,s=0;++s<e&&(i*=256);)n+=this[t+s]*i;return n>=(i*=128)&&(n-=Math.pow(2,8*e)),n},e.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||I(t,e,this.length);for(var n=e,i=1,s=this[t+--n];n>0&&(i*=256);)s+=this[t+--n]*i;return s>=(i*=128)&&(s-=Math.pow(2,8*e)),s},e.prototype.readInt8=function(t,e){return t>>>=0,e||I(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},e.prototype.readInt16LE=function(t,e){t>>>=0,e||I(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},e.prototype.readInt16BE=function(t,e){t>>>=0,e||I(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},e.prototype.readInt32LE=function(t,e){return t>>>=0,e||I(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},e.prototype.readInt32BE=function(t,e){return t>>>=0,e||I(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},e.prototype.readFloatLE=function(t,e){return t>>>=0,e||I(t,4,this.length),i.read(this,t,!0,23,4)},e.prototype.readFloatBE=function(t,e){return t>>>=0,e||I(t,4,this.length),i.read(this,t,!1,23,4)},e.prototype.readDoubleLE=function(t,e){return t>>>=0,e||I(t,8,this.length),i.read(this,t,!0,52,8)},e.prototype.readDoubleBE=function(t,e){return t>>>=0,e||I(t,8,this.length),i.read(this,t,!1,52,8)},e.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e>>>=0,r>>>=0,n)||O(this,t,e,r,Math.pow(2,8*r)-1,0);var i=1,s=0;for(this[e]=255&t;++s<r&&(i*=256);)this[e+s]=t/i&255;return e+r},e.prototype.writeUIntBE=function(t,e,r,n){(t=+t,e>>>=0,r>>>=0,n)||O(this,t,e,r,Math.pow(2,8*r)-1,0);var i=r-1,s=1;for(this[e+i]=255&t;--i>=0&&(s*=256);)this[e+i]=t/s&255;return e+r},e.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,1,255,0),this[e]=255&t,e+1},e.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},e.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},e.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||O(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},e.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||O(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},e.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);O(this,t,e,r,i-1,-i)}var s=0,a=1,o=0;for(this[e]=255&t;++s<r&&(a*=256);)t<0&&0===o&&0!==this[e+s-1]&&(o=1),this[e+s]=(t/a>>0)-o&255;return e+r},e.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){var i=Math.pow(2,8*r-1);O(this,t,e,r,i-1,-i)}var s=r-1,a=1,o=0;for(this[e+s]=255&t;--s>=0&&(a*=256);)t<0&&0===o&&0!==this[e+s+1]&&(o=1),this[e+s]=(t/a>>0)-o&255;return e+r},e.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},e.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},e.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},e.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||O(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},e.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||O(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},e.prototype.writeFloatLE=function(t,e,r){return B(this,t,e,!0,r)},e.prototype.writeFloatBE=function(t,e,r){return B(this,t,e,!1,r)},e.prototype.writeDoubleLE=function(t,e,r){return z(this,t,e,!0,r)},e.prototype.writeDoubleBE=function(t,e,r){return z(this,t,e,!1,r)},e.prototype.copy=function(t,r,n,i){if(!e.isBuffer(t))throw new TypeError("argument should be a Buffer");if(n||(n=0),i||0===i||(i=this.length),r>=t.length&&(r=t.length),r||(r=0),i>0&&i<n&&(i=n),i===n)return 0;if(0===t.length||0===this.length)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),t.length-r<i-n&&(i=t.length-r+n);var s=i-n;if(this===t&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(r,n,i);else if(this===t&&n<r&&r<i)for(var a=s-1;a>=0;--a)t[a+r]=this[a+n];else Uint8Array.prototype.set.call(t,this.subarray(n,i),r);return s},e.prototype.fill=function(t,r,n,i){if("string"==typeof t){if("string"==typeof r?(i=r,r=0,n=this.length):"string"==typeof n&&(i=n,n=this.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!e.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(1===t.length){var s=t.charCodeAt(0);("utf8"===i&&s<128||"latin1"===i)&&(t=s)}}else"number"==typeof t&&(t&=255);if(r<0||this.length<r||this.length<n)throw new RangeError("Out of range index");if(n<=r)return this;var a;if(r>>>=0,n=void 0===n?this.length:n>>>0,t||(t=0),"number"==typeof t)for(a=r;a<n;++a)this[a]=t;else{var o=e.isBuffer(t)?t:e.from(t,i),h=o.length;if(0===h)throw new TypeError('The value "'+t+'" is invalid for argument "value"');for(a=0;a<n-r;++a)this[a+r]=o[a%h]}return this};var N=/[^+/0-9A-Za-z-_]/g;function D(t){return t<16?"0"+t.toString(16):t.toString(16)}function M(t,e){var r;e=e||1/0;for(var n=t.length,i=null,s=[],a=0;a<n;++a){if((r=t.charCodeAt(a))>55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}if(a+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return s}function U(t){return n.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(N,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function P(t,e,r,n){for(var i=0;i<n&&!(i+r>=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function F(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function Z(t){return t!=t}}).call(this,t("buffer").Buffer)},{"base64-js":27,buffer:32,ieee754:35}],33:[function(t,e,r){(function(t){function e(t){return Object.prototype.toString.call(t)}r.isArray=function(t){return Array.isArray?Array.isArray(t):"[object Array]"===e(t)},r.isBoolean=function(t){return"boolean"==typeof t},r.isNull=function(t){return null===t},r.isNullOrUndefined=function(t){return null==t},r.isNumber=function(t){return"number"==typeof t},r.isString=function(t){return"string"==typeof t},r.isSymbol=function(t){return"symbol"==typeof t},r.isUndefined=function(t){return void 0===t},r.isRegExp=function(t){return"[object RegExp]"===e(t)},r.isObject=function(t){return"object"==typeof t&&null!==t},r.isDate=function(t){return"[object Date]"===e(t)},r.isError=function(t){return"[object Error]"===e(t)||t instanceof Error},r.isFunction=function(t){return"function"==typeof t},r.isPrimitive=function(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t},r.isBuffer=t.isBuffer}).call(this,{isBuffer:t("../../is-buffer/index.js")})},{"../../is-buffer/index.js":37}],34:[function(t,e,r){function n(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function i(t){return"function"==typeof t}function s(t){return"object"==typeof t&&null!==t}function a(t){return void 0===t}e.exports=n,n.EventEmitter=n,n.prototype._events=void 0,n.prototype._maxListeners=void 0,n.defaultMaxListeners=10,n.prototype.setMaxListeners=function(t){if("number"!=typeof t||t<0||isNaN(t))throw TypeError("n must be a positive number");return this._maxListeners=t,this},n.prototype.emit=function(t){var e,r,n,o,h,f;if(this._events||(this._events={}),"error"===t&&(!this._events.error||s(this._events.error)&&!this._events.error.length)){if((e=arguments[1])instanceof Error)throw e;var l=new Error('Uncaught, unspecified "error" event. ('+e+")");throw l.context=e,l}if(a(r=this._events[t]))return!1;if(i(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:o=Array.prototype.slice.call(arguments,1),r.apply(this,o)}else if(s(r))for(o=Array.prototype.slice.call(arguments,1),n=(f=r.slice()).length,h=0;h<n;h++)f[h].apply(this,o);return!0},n.prototype.addListener=function(t,e){var r;if(!i(e))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",t,i(e.listener)?e.listener:e),this._events[t]?s(this._events[t])?this._events[t].push(e):this._events[t]=[this._events[t],e]:this._events[t]=e,s(this._events[t])&&!this._events[t].warned&&(r=a(this._maxListeners)?n.defaultMaxListeners:this._maxListeners)&&r>0&&this._events[t].length>r&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace()),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(t,e){if(!i(e))throw TypeError("listener must be a function");var r=!1;function n(){this.removeListener(t,n),r||(r=!0,e.apply(this,arguments))}return n.listener=e,this.on(t,n),this},n.prototype.removeListener=function(t,e){var r,n,a,o;if(!i(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(a=(r=this._events[t]).length,n=-1,r===e||i(r.listener)&&r.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(s(r)){for(o=a;o-- >0;)if(r[o]===e||r[o].listener&&r[o].listener===e){n=o;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[t]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},n.prototype.removeAllListeners=function(t){var e,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(i(r=this._events[t]))this.removeListener(t,r);else if(r)for(;r.length;)this.removeListener(t,r[r.length-1]);return delete this._events[t],this},n.prototype.listeners=function(t){return this._events&&this._events[t]?i(this._events[t])?[this._events[t]]:this._events[t].slice():[]},n.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(i(e))return 1;if(e)return e.length}return 0},n.listenerCount=function(t,e){return t.listenerCount(e)}},{}],35:[function(t,e,r){r.read=function(t,e,r,n,i){var s,a,o=8*i-n-1,h=(1<<o)-1,f=h>>1,l=-7,u=r?i-1:0,c=r?-1:1,d=t[e+u];for(u+=c,s=d&(1<<-l)-1,d>>=-l,l+=o;l>0;s=256*s+t[e+u],u+=c,l-=8);for(a=s&(1<<-l)-1,s>>=-l,l+=n;l>0;a=256*a+t[e+u],u+=c,l-=8);if(0===s)s=1-f;else{if(s===h)return a?NaN:1/0*(d?-1:1);a+=Math.pow(2,n),s-=f}return(d?-1:1)*a*Math.pow(2,s-n)},r.write=function(t,e,r,n,i,s){var a,o,h,f=8*s-i-1,l=(1<<f)-1,u=l>>1,c=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,d=n?0:s-1,p=n?1:-1,_=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(o=isNaN(e)?1:0,a=l):(a=Math.floor(Math.log(e)/Math.LN2),e*(h=Math.pow(2,-a))<1&&(a--,h*=2),(e+=a+u>=1?c/h:c*Math.pow(2,1-u))*h>=2&&(a++,h/=2),a+u>=l?(o=0,a=l):a+u>=1?(o=(e*h-1)*Math.pow(2,i),a+=u):(o=e*Math.pow(2,u-1)*Math.pow(2,i),a=0));i>=8;t[r+d]=255&o,d+=p,o/=256,i-=8);for(a=a<<i|o,f+=i;f>0;t[r+d]=255&a,d+=p,a/=256,f-=8);t[r+d-p]|=128*_}},{}],36:[function(t,e,r){arguments[4][24][0].apply(r,arguments)},{dup:24}],37:[function(t,e,r){function n(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}
 /*!
  * Determine if an object is a Buffer
  *
  * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  * @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))
-}
-
-},{}],38:[function(require,module,exports){
-var toString = {}.toString;
-
-module.exports = Array.isArray || function (arr) {
-  return toString.call(arr) == '[object Array]';
-};
-
-},{}],39:[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);
-
-},{}],40:[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;
-
-},{}],41:[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
-};
-
-},{}],42:[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;
-
-},{}],43:[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":39,"./adler32":40,"./crc32":42,"./messages":47,"./trees":48}],44:[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;
-};
-
-},{}],45:[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":39,"./adler32":40,"./crc32":42,"./inffast":44,"./inftrees":46}],46:[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":39}],47:[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) */
-};
-
-},{}],48:[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<<MAX_BITS)-1,
-  //        "inconsistent bit counts");
-  //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
-
-  for (n = 0;  n <= max_code; n++) {
-    var len = tree[n * 2 + 1]/*.Len*/;
-    if (len === 0) { continue; }
-    /* Now reverse the bits */
-    tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
-
-    //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
-    //     n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
-  }
-}
-
-
-/* ===========================================================================
- * Initialize the various 'constant' tables.
- */
-function tr_static_init() {
-  var n;        /* iterates over tree elements */
-  var bits;     /* bit counter */
-  var length;   /* length value */
-  var code;     /* code value */
-  var dist;     /* distance index */
-  var bl_count = new Array(MAX_BITS + 1);
-  /* number of codes at each bit length for an optimal tree */
-
-  // do check in _tr_init()
-  //if (static_init_done) return;
-
-  /* For some embedded targets, global variables are not initialized: */
-/*#ifdef NO_INIT_GLOBAL_POINTERS
-  static_l_desc.static_tree = static_ltree;
-  static_l_desc.extra_bits = extra_lbits;
-  static_d_desc.static_tree = static_dtree;
-  static_d_desc.extra_bits = extra_dbits;
-  static_bl_desc.extra_bits = extra_blbits;
-#endif*/
-
-  /* Initialize the mapping length (0..255) -> 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":39}],49:[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;
-
-},{}],50:[function(require,module,exports){
-(function (process){
-'use strict';
-
-if (!process.version ||
-    process.version.indexOf('v0.') === 0 ||
-    process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
-  module.exports = nextTick;
-} else {
-  module.exports = process.nextTick;
-}
-
-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,require('_process'))
-},{"_process":51}],51:[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; };
-
-},{}],52:[function(require,module,exports){
-module.exports = require('./lib/_stream_duplex.js');
-
-},{"./lib/_stream_duplex.js":53}],53:[function(require,module,exports){
-// 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';
-
-/*<replacement>*/
-
-var objectKeys = Object.keys || function (obj) {
-  var keys = [];
-  for (var key in obj) {
-    keys.push(key);
-  }return keys;
-};
-/*</replacement>*/
-
-module.exports = Duplex;
-
-/*<replacement>*/
-var processNextTick = require('process-nextick-args');
-/*</replacement>*/
-
-/*<replacement>*/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/*</replacement>*/
-
-var Readable = require('./_stream_readable');
-var Writable = require('./_stream_writable');
-
-util.inherits(Duplex, Readable);
-
-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);
-}
-
-// 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.
-  processNextTick(onEndNT, this);
-}
-
-function onEndNT(self) {
-  self.end();
-}
-
-function forEach(xs, f) {
-  for (var i = 0, l = xs.length; i < l; i++) {
-    f(xs[i], i);
-  }
-}
-},{"./_stream_readable":55,"./_stream_writable":57,"core-util-is":33,"inherits":36,"process-nextick-args":50}],54:[function(require,module,exports){
-// 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');
-
-/*<replacement>*/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/*</replacement>*/
-
-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":56,"core-util-is":33,"inherits":36}],55:[function(require,module,exports){
-(function (process){
-'use strict';
-
-module.exports = Readable;
-
-/*<replacement>*/
-var processNextTick = require('process-nextick-args');
-/*</replacement>*/
-
-/*<replacement>*/
-var isArray = require('isarray');
-/*</replacement>*/
-
-/*<replacement>*/
-var Duplex;
-/*</replacement>*/
-
-Readable.ReadableState = ReadableState;
-
-/*<replacement>*/
-var EE = require('events').EventEmitter;
-
-var EElistenerCount = function (emitter, type) {
-  return emitter.listeners(type).length;
-};
-/*</replacement>*/
-
-/*<replacement>*/
-var Stream = require('./internal/streams/stream');
-/*</replacement>*/
-
-var Buffer = require('buffer').Buffer;
-/*<replacement>*/
-var bufferShim = require('buffer-shims');
-/*</replacement>*/
-
-/*<replacement>*/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/*</replacement>*/
-
-/*<replacement>*/
-var debugUtil = require('util');
-var debug = void 0;
-if (debugUtil && debugUtil.debuglog) {
-  debug = debugUtil.debuglog('stream');
-} else {
-  debug = function () {};
-}
-/*</replacement>*/
-
-var BufferList = require('./internal/streams/BufferList');
-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);
-  } else {
-    // 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 || {};
-
-  // 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 (stream instanceof Duplex) 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 defaultHwm = this.objectMode ? 16 : 16 * 1024;
-  this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
-
-  // cast to ints.
-  this.highWaterMark = ~~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 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;
-
-  // 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;
-
-  // 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';
-
-  // when piping, we only care about 'readable' events that happen
-  // after read()ing all the bytes and not getting any pushback.
-  this.ranOut = false;
-
-  // 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 && typeof options.read === 'function') this._read = options.read;
-
-  Stream.call(this);
-}
-
-// 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;
-
-  if (!state.objectMode && typeof chunk === 'string') {
-    encoding = encoding || state.defaultEncoding;
-    if (encoding !== state.encoding) {
-      chunk = bufferShim.from(chunk, encoding);
-      encoding = '';
-    }
-  }
-
-  return readableAddChunk(this, state, chunk, encoding, false);
-};
-
-// Unshift should *always* be something directly out of read()
-Readable.prototype.unshift = function (chunk) {
-  var state = this._readableState;
-  return readableAddChunk(this, state, chunk, '', true);
-};
-
-Readable.prototype.isPaused = function () {
-  return this._readableState.flowing === false;
-};
-
-function readableAddChunk(stream, state, chunk, encoding, addToFront) {
-  var er = chunkInvalid(state, chunk);
-  if (er) {
-    stream.emit('error', er);
-  } else if (chunk === null) {
-    state.reading = false;
-    onEofChunk(stream, state);
-  } else if (state.objectMode || chunk && chunk.length > 0) {
-    if (state.ended && !addToFront) {
-      var e = new Error('stream.push() after EOF');
-      stream.emit('error', e);
-    } else if (state.endEmitted && addToFront) {
-      var _e = new Error('stream.unshift() after end event');
-      stream.emit('error', _e);
-    } else {
-      var skipAdd;
-      if (state.decoder && !addToFront && !encoding) {
-        chunk = state.decoder.write(chunk);
-        skipAdd = !state.objectMode && chunk.length === 0;
-      }
-
-      if (!addToFront) state.reading = false;
-
-      // Don't add to the buffer if we've decoded to an empty string chunk and
-      // we're not in object mode
-      if (!skipAdd) {
-        // if we want the data now, just emit it.
-        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);
-    }
-  } else if (!addToFront) {
-    state.reading = false;
-  }
-
-  return needMoreData(state);
-}
-
-// 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);
-}
-
-// 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 chunkInvalid(state, chunk) {
-  var er = null;
-  if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
-    er = new TypeError('Invalid non-string/buffer chunk');
-  }
-  return er;
-}
-
-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) processNextTick(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;
-    processNextTick(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 : cleanup;
-  if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
-
-  dest.on('unpipe', onunpipe);
-  function onunpipe(readable) {
-    debug('onunpipe');
-    if (readable === src) {
-      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', cleanup);
-    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;
-
-  // 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);
-    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);
-    }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);
-
-  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) {
-        processNextTick(nReadingNextTick, this);
-      } else if (state.length) {
-        emitReadable(this, state);
-      }
-    }
-  }
-
-  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;
-    processNextTick(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 state = this._readableState;
-  var paused = false;
-
-  var self = this;
-  stream.on('end', function () {
-    debug('wrapped end');
-    if (state.decoder && !state.ended) {
-      var chunk = state.decoder.end();
-      if (chunk && chunk.length) self.push(chunk);
-    }
-
-    self.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 = self.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], self.emit.bind(self, kProxyEvents[n]));
-  }
-
-  // when we try to consume some more bytes, simply unpause the
-  // underlying stream.
-  self._read = function (n) {
-    debug('wrapped _read', n);
-    if (paused) {
-      paused = false;
-      stream.resume();
-    }
-  };
-
-  return self;
-};
-
-// 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 = bufferShim.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;
-    processNextTick(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 forEach(xs, f) {
-  for (var i = 0, l = xs.length; i < l; i++) {
-    f(xs[i], i);
-  }
-}
-
-function indexOf(xs, x) {
-  for (var i = 0, l = xs.length; i < l; i++) {
-    if (xs[i] === x) return i;
-  }
-  return -1;
-}
-}).call(this,require('_process'))
-},{"./_stream_duplex":53,"./internal/streams/BufferList":58,"./internal/streams/stream":59,"_process":51,"buffer":32,"buffer-shims":31,"core-util-is":33,"events":34,"inherits":36,"isarray":38,"process-nextick-args":50,"string_decoder/":65,"util":28}],56:[function(require,module,exports){
-// 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');
-
-/*<replacement>*/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/*</replacement>*/
-
-util.inherits(Transform, Duplex);
-
-function TransformState(stream) {
-  this.afterTransform = function (er, data) {
-    return afterTransform(stream, er, data);
-  };
-
-  this.needTransform = false;
-  this.transforming = false;
-  this.writecb = null;
-  this.writechunk = null;
-  this.writeencoding = null;
-}
-
-function afterTransform(stream, er, data) {
-  var ts = stream._transformState;
-  ts.transforming = false;
-
-  var cb = ts.writecb;
-
-  if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
-
-  ts.writechunk = null;
-  ts.writecb = null;
-
-  if (data !== null && data !== undefined) stream.push(data);
-
-  cb(er);
-
-  var rs = stream._readableState;
-  rs.reading = false;
-  if (rs.needReadable || rs.length < rs.highWaterMark) {
-    stream._read(rs.highWaterMark);
-  }
-}
-
-function Transform(options) {
-  if (!(this instanceof Transform)) return new Transform(options);
-
-  Duplex.call(this, options);
-
-  this._transformState = new TransformState(this);
-
-  var stream = this;
-
-  // 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.once('prefinish', function () {
-    if (typeof this._flush === 'function') this._flush(function (er, data) {
-      done(stream, er, data);
-    });else done(stream);
-  });
-}
-
-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;
-  }
-};
-
-function done(stream, er, data) {
-  if (er) return stream.emit('error', er);
-
-  if (data !== null && data !== undefined) stream.push(data);
-
-  // if there's nothing in the write buffer, then that means
-  // that nothing more will ever be provided
-  var ws = stream._writableState;
-  var ts = stream._transformState;
-
-  if (ws.length) throw new Error('Calling transform done when ws.length != 0');
-
-  if (ts.transforming) throw new Error('Calling transform done when still transforming');
-
-  return stream.push(null);
-}
-},{"./_stream_duplex":53,"core-util-is":33,"inherits":36}],57:[function(require,module,exports){
-(function (process,setImmediate){
-// 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;
-
-/*<replacement>*/
-var processNextTick = require('process-nextick-args');
-/*</replacement>*/
-
-/*<replacement>*/
-var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
-/*</replacement>*/
-
-/*<replacement>*/
-var Duplex;
-/*</replacement>*/
-
-Writable.WritableState = WritableState;
-
-/*<replacement>*/
-var util = require('core-util-is');
-util.inherits = require('inherits');
-/*</replacement>*/
-
-/*<replacement>*/
-var internalUtil = {
-  deprecate: require('util-deprecate')
-};
-/*</replacement>*/
-
-/*<replacement>*/
-var Stream = require('./internal/streams/stream');
-/*</replacement>*/
-
-var Buffer = require('buffer').Buffer;
-/*<replacement>*/
-var bufferShim = require('buffer-shims');
-/*</replacement>*/
-
-util.inherits(Writable, Stream);
-
-function nop() {}
-
-function WriteReq(chunk, encoding, cb) {
-  this.chunk = chunk;
-  this.encoding = encoding;
-  this.callback = cb;
-  this.next = null;
-}
-
-function WritableState(options, stream) {
-  Duplex = Duplex || require('./_stream_duplex');
-
-  options = options || {};
-
-  // object stream flag to indicate whether or not this stream
-  // contains buffers or objects.
-  this.objectMode = !!options.objectMode;
-
-  if (stream instanceof Duplex) 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 defaultHwm = this.objectMode ? 16 : 16 * 1024;
-  this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
-
-  // cast to ints.
-  this.highWaterMark = ~~this.highWaterMark;
-
-  // 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;
-
-  // 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.')
-    });
-  } 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;
-
-      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;
-  }
-
-  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);
-  processNextTick(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);
-    processNextTick(cb, er);
-    valid = false;
-  }
-  return valid;
-}
-
-Writable.prototype.write = function (chunk, encoding, cb) {
-  var state = this._writableState;
-  var ret = false;
-  var isBuf = Buffer.isBuffer(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 = bufferShim.from(chunk, encoding);
-  }
-  return chunk;
-}
-
-// 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) {
-    chunk = decodeChunk(state, chunk, encoding);
-    if (Buffer.isBuffer(chunk)) encoding = 'buffer';
-  }
-  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 = new WriteReq(chunk, encoding, cb);
-    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) processNextTick(cb, er);else cb(er);
-
-  stream._writableState.errorEmitted = true;
-  stream.emit('error', er);
-}
-
-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) {
-      /*<replacement>*/
-      asyncWrite(afterWrite, stream, state, finished, cb);
-      /*</replacement>*/
-    } 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;
-    while (entry) {
-      buffer[count] = entry;
-      entry = entry.next;
-      count += 1;
-    }
-
-    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);
-    }
-  } 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;
-      // 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.bufferedRequestCount = 0;
-  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 prefinish(stream, state) {
-  if (!state.prefinished) {
-    state.prefinished = true;
-    stream.emit('prefinish');
-  }
-}
-
-function finishMaybe(stream, state) {
-  var need = needFinish(state);
-  if (need) {
-    if (state.pendingcb === 0) {
-      prefinish(stream, state);
-      state.finished = true;
-      stream.emit('finish');
-    } else {
-      prefinish(stream, state);
-    }
-  }
-  return need;
-}
-
-function endWritable(stream, state, cb) {
-  state.ending = true;
-  finishMaybe(stream, state);
-  if (cb) {
-    if (state.finished) processNextTick(cb);else stream.once('finish', cb);
-  }
-  state.ended = true;
-  stream.writable = false;
-}
-
-// 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 (err) {
-    var entry = _this.entry;
-    _this.entry = null;
-    while (entry) {
-      var cb = entry.callback;
-      state.pendingcb--;
-      cb(err);
-      entry = entry.next;
-    }
-    if (state.corkedRequestsFree) {
-      state.corkedRequestsFree.next = _this;
-    } else {
-      state.corkedRequestsFree = _this;
-    }
-  };
-}
-}).call(this,require('_process'),require("timers").setImmediate)
-},{"./_stream_duplex":53,"./internal/streams/stream":59,"_process":51,"buffer":32,"buffer-shims":31,"core-util-is":33,"inherits":36,"process-nextick-args":50,"timers":66,"util-deprecate":67}],58:[function(require,module,exports){
-'use strict';
-
-var Buffer = require('buffer').Buffer;
-/*<replacement>*/
-var bufferShim = require('buffer-shims');
-/*</replacement>*/
-
-module.exports = BufferList;
-
-function BufferList() {
-  this.head = null;
-  this.tail = null;
-  this.length = 0;
-}
-
-BufferList.prototype.push = function (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 (v) {
-  var entry = { data: v, next: this.head };
-  if (this.length === 0) this.tail = entry;
-  this.head = entry;
-  ++this.length;
-};
-
-BufferList.prototype.shift = function () {
-  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 () {
-  this.head = this.tail = null;
-  this.length = 0;
-};
-
-BufferList.prototype.join = function (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 (n) {
-  if (this.length === 0) return bufferShim.alloc(0);
-  if (this.length === 1) return this.head.data;
-  var ret = bufferShim.allocUnsafe(n >>> 0);
-  var p = this.head;
-  var i = 0;
-  while (p) {
-    p.data.copy(ret, i);
-    i += p.data.length;
-    p = p.next;
-  }
-  return ret;
-};
-},{"buffer":32,"buffer-shims":31}],59:[function(require,module,exports){
-module.exports = require('events').EventEmitter;
-
-},{"events":34}],60:[function(require,module,exports){
-module.exports = require('./readable').PassThrough
-
-},{"./readable":61}],61:[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":53,"./lib/_stream_passthrough.js":54,"./lib/_stream_readable.js":55,"./lib/_stream_transform.js":56,"./lib/_stream_writable.js":57}],62:[function(require,module,exports){
-module.exports = require('./readable').Transform
-
-},{"./readable":61}],63:[function(require,module,exports){
-module.exports = require('./lib/_stream_writable.js');
-
-},{"./lib/_stream_writable.js":57}],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.
-
-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":34,"inherits":36,"readable-stream/duplex.js":52,"readable-stream/passthrough.js":60,"readable-stream/readable.js":61,"readable-stream/transform.js":62,"readable-stream/writable.js":63}],65:[function(require,module,exports){
-'use strict';
-
-var Buffer = require('buffer').Buffer;
-var bufferShim = require('buffer-shims');
-
-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 = bufferShim.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.
-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 -1;
-}
-
-// 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) return 0;
-  nb = utf8CheckByte(buf[j]);
-  if (nb >= 0) {
-    if (nb > 0) self.lastNeed = nb - 2;
-    return nb;
-  }
-  if (--j < i) 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
-// UTF-8 replacement characters ('\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'.repeat(p);
-  }
-  if (self.lastNeed > 1 && buf.length > 1) {
-    if ((buf[1] & 0xC0) !== 0x80) {
-      self.lastNeed = 1;
-      return '\ufffd'.repeat(p + 1);
-    }
-    if (self.lastNeed > 2 && buf.length > 2) {
-      if ((buf[2] & 0xC0) !== 0x80) {
-        self.lastNeed = 2;
-        return '\ufffd'.repeat(p + 2);
-      }
-    }
-  }
-}
-
-// 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 for each buffered byte of a (partial)
-// character needs to be added to the output.
-function utf8End(buf) {
-  var r = buf && buf.length ? this.write(buf) : '';
-  if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed);
-  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) : '';
-}
-},{"buffer":32,"buffer-shims":31}],66:[function(require,module,exports){
-(function (setImmediate,clearImmediate){
-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,require("timers").setImmediate,require("timers").clearImmediate)
-},{"process/browser.js":51,"timers":66}],67:[function(require,module,exports){
-(function (global){
-
-/**
- * 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,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{}],68:[function(require,module,exports){
-arguments[4][25][0].apply(exports,arguments)
-},{"dup":25}],69:[function(require,module,exports){
-arguments[4][26][0].apply(exports,arguments)
-},{"./support/isBuffer":68,"_process":51,"dup":26,"inherits":36}]},{},[20])(20)
-});
+e.exports=function(t){return null!=t&&(n(t)||function(t){return"function"==typeof t.readFloatLE&&"function"==typeof t.slice&&n(t.slice(0,0))}(t)||!!t._isBuffer)}},{}],38:[function(t,e,r){var n={}.toString;e.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},{}],39:[function(t,e,r){"use strict";var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function i(t,e){return Object.prototype.hasOwnProperty.call(t,e)}r.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var r=e.shift();if(r){if("object"!=typeof r)throw new TypeError(r+"must be non-object");for(var n in r)i(r,n)&&(t[n]=r[n])}}return t},r.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var s={arraySet:function(t,e,r,n,i){if(e.subarray&&t.subarray)t.set(e.subarray(r,r+n),i);else for(var s=0;s<n;s++)t[i+s]=e[r+s]},flattenChunks:function(t){var e,r,n,i,s,a;for(n=0,e=0,r=t.length;e<r;e++)n+=t[e].length;for(a=new Uint8Array(n),i=0,e=0,r=t.length;e<r;e++)s=t[e],a.set(s,i),i+=s.length;return a}},a={arraySet:function(t,e,r,n,i){for(var s=0;s<n;s++)t[i+s]=e[r+s]},flattenChunks:function(t){return[].concat.apply([],t)}};r.setTyped=function(t){t?(r.Buf8=Uint8Array,r.Buf16=Uint16Array,r.Buf32=Int32Array,r.assign(r,s)):(r.Buf8=Array,r.Buf16=Array,r.Buf32=Array,r.assign(r,a))},r.setTyped(n)},{}],40:[function(t,e,r){"use strict";e.exports=function(t,e,r,n){for(var i=65535&t|0,s=t>>>16&65535|0,a=0;0!==r;){r-=a=r>2e3?2e3:r;do{s=s+(i=i+e[n++]|0)|0}while(--a);i%=65521,s%=65521}return i|s<<16|0}},{}],41:[function(t,e,r){"use strict";e.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}},{}],42:[function(t,e,r){"use strict";var n=function(){for(var t,e=[],r=0;r<256;r++){t=r;for(var n=0;n<8;n++)t=1&t?3988292384^t>>>1:t>>>1;e[r]=t}return e}();e.exports=function(t,e,r,i){var s=n,a=i+r;t^=-1;for(var o=i;o<a;o++)t=t>>>8^s[255&(t^e[o])];return-1^t}},{}],43:[function(t,e,r){"use strict";var n,i=t("../utils/common"),s=t("./trees"),a=t("./adler32"),o=t("./crc32"),h=t("./messages"),f=-2,l=258,u=262,c=103,d=113,p=666;function _(t,e){return t.msg=h[e],e}function g(t){return(t<<1)-(t>4?9:0)}function b(t){for(var e=t.length;--e>=0;)t[e]=0}function w(t){var e=t.state,r=e.pending;r>t.avail_out&&(r=t.avail_out),0!==r&&(i.arraySet(t.output,e.pending_buf,e.pending_out,r,t.next_out),t.next_out+=r,e.pending_out+=r,t.total_out+=r,t.avail_out-=r,e.pending-=r,0===e.pending&&(e.pending_out=0))}function m(t,e){s._tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,w(t.strm)}function y(t,e){t.pending_buf[t.pending++]=e}function v(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function E(t,e){var r,n,i=t.max_chain_length,s=t.strstart,a=t.prev_length,o=t.nice_match,h=t.strstart>t.w_size-u?t.strstart-(t.w_size-u):0,f=t.window,c=t.w_mask,d=t.prev,p=t.strstart+l,_=f[s+a-1],g=f[s+a];t.prev_length>=t.good_match&&(i>>=2),o>t.lookahead&&(o=t.lookahead);do{if(f[(r=e)+a]===g&&f[r+a-1]===_&&f[r]===f[s]&&f[++r]===f[s+1]){s+=2,r++;do{}while(f[++s]===f[++r]&&f[++s]===f[++r]&&f[++s]===f[++r]&&f[++s]===f[++r]&&f[++s]===f[++r]&&f[++s]===f[++r]&&f[++s]===f[++r]&&f[++s]===f[++r]&&s<p);if(n=l-(p-s),s=p-l,n>a){if(t.match_start=e,a=n,n>=o)break;_=f[s+a-1],g=f[s+a]}}}while((e=d[e&c])>h&&0!=--i);return a<=t.lookahead?a:t.lookahead}function k(t){var e,r,n,s,h,f,l,c,d,p,_=t.w_size;do{if(s=t.window_size-t.lookahead-t.strstart,t.strstart>=_+(_-u)){i.arraySet(t.window,t.window,_,_,0),t.match_start-=_,t.strstart-=_,t.block_start-=_,e=r=t.hash_size;do{n=t.head[--e],t.head[e]=n>=_?n-_:0}while(--r);e=r=_;do{n=t.prev[--e],t.prev[e]=n>=_?n-_:0}while(--r);s+=_}if(0===t.strm.avail_in)break;if(f=t.strm,l=t.window,c=t.strstart+t.lookahead,d=s,p=void 0,(p=f.avail_in)>d&&(p=d),r=0===p?0:(f.avail_in-=p,i.arraySet(l,f.input,f.next_in,p,c),1===f.state.wrap?f.adler=a(f.adler,l,p,c):2===f.state.wrap&&(f.adler=o(f.adler,l,p,c)),f.next_in+=p,f.total_in+=p,p),t.lookahead+=r,t.lookahead+t.insert>=3)for(h=t.strstart-t.insert,t.ins_h=t.window[h],t.ins_h=(t.ins_h<<t.hash_shift^t.window[h+1])&t.hash_mask;t.insert&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[h+3-1])&t.hash_mask,t.prev[h&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=h,h++,t.insert--,!(t.lookahead+t.insert<3)););}while(t.lookahead<u&&0!==t.strm.avail_in)}function T(t,e){for(var r,n;;){if(t.lookahead<u){if(k(t),t.lookahead<u&&0===e)return 1;if(0===t.lookahead)break}if(r=0,t.lookahead>=3&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+3-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==r&&t.strstart-r<=t.w_size-u&&(t.match_length=E(t,r)),t.match_length>=3)if(n=s._tr_tally(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+3-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart}while(0!=--t.match_length);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+1])&t.hash_mask;else n=s._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(n&&(m(t,!1),0===t.strm.avail_out))return 1}return t.insert=t.strstart<2?t.strstart:2,4===e?(m(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(m(t,!1),0===t.strm.avail_out)?1:2}function x(t,e){for(var r,n,i;;){if(t.lookahead<u){if(k(t),t.lookahead<u&&0===e)return 1;if(0===t.lookahead)break}if(r=0,t.lookahead>=3&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+3-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==r&&t.prev_length<t.max_lazy_match&&t.strstart-r<=t.w_size-u&&(t.match_length=E(t,r),t.match_length<=5&&(1===t.strategy||3===t.match_length&&t.strstart-t.match_start>4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){i=t.strstart+t.lookahead-3,n=s._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=i&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+3-1])&t.hash_mask,r=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart)}while(0!=--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,n&&(m(t,!1),0===t.strm.avail_out))return 1}else if(t.match_available){if((n=s._tr_tally(t,0,t.window[t.strstart-1]))&&m(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(n=s._tr_tally(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,4===e?(m(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(m(t,!1),0===t.strm.avail_out)?1:2}function A(t,e,r,n,i){this.good_length=t,this.max_lazy=e,this.nice_length=r,this.max_chain=n,this.func=i}function L(){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=8,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(1146),this.dyn_dtree=new i.Buf16(122),this.bl_tree=new i.Buf16(78),b(this.dyn_ltree),b(this.dyn_dtree),b(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new i.Buf16(16),this.heap=new i.Buf16(573),b(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new i.Buf16(573),b(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}function R(t){var e;return t&&t.state?(t.total_in=t.total_out=0,t.data_type=2,(e=t.state).pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?42:d,t.adler=2===e.wrap?0:1,e.last_flush=0,s._tr_init(e),0):_(t,f)}function S(t){var e,r=R(t);return 0===r&&((e=t.state).window_size=2*e.w_size,b(e.head),e.max_lazy_match=n[e.level].max_lazy,e.good_match=n[e.level].good_length,e.nice_match=n[e.level].nice_length,e.max_chain_length=n[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=2,e.match_available=0,e.ins_h=0),r}function I(t,e,r,n,s,a){if(!t)return f;var o=1;if(-1===e&&(e=6),n<0?(o=0,n=-n):n>15&&(o=2,n-=16),s<1||s>9||8!==r||n<8||n>15||e<0||e>9||a<0||a>4)return _(t,f);8===n&&(n=9);var h=new L;return t.state=h,h.strm=t,h.wrap=o,h.gzhead=null,h.w_bits=n,h.w_size=1<<h.w_bits,h.w_mask=h.w_size-1,h.hash_bits=s+7,h.hash_size=1<<h.hash_bits,h.hash_mask=h.hash_size-1,h.hash_shift=~~((h.hash_bits+3-1)/3),h.window=new i.Buf8(2*h.w_size),h.head=new i.Buf16(h.hash_size),h.prev=new i.Buf16(h.w_size),h.lit_bufsize=1<<s+6,h.pending_buf_size=4*h.lit_bufsize,h.pending_buf=new i.Buf8(h.pending_buf_size),h.d_buf=1*h.lit_bufsize,h.l_buf=3*h.lit_bufsize,h.level=e,h.strategy=a,h.method=r,S(t)}n=[new A(0,0,0,0,(function(t,e){var r=65535;for(r>t.pending_buf_size-5&&(r=t.pending_buf_size-5);;){if(t.lookahead<=1){if(k(t),0===t.lookahead&&0===e)return 1;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var n=t.block_start+r;if((0===t.strstart||t.strstart>=n)&&(t.lookahead=t.strstart-n,t.strstart=n,m(t,!1),0===t.strm.avail_out))return 1;if(t.strstart-t.block_start>=t.w_size-u&&(m(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,4===e?(m(t,!0),0===t.strm.avail_out?3:4):(t.strstart>t.block_start&&(m(t,!1),t.strm.avail_out),1)})),new A(4,4,8,4,T),new A(4,5,16,8,T),new A(4,6,32,32,T),new A(4,4,16,16,x),new A(8,16,32,32,x),new A(8,16,128,128,x),new A(8,32,128,256,x),new A(32,128,258,1024,x),new A(32,258,258,4096,x)],r.deflateInit=function(t,e){return I(t,e,8,15,8,0)},r.deflateInit2=I,r.deflateReset=S,r.deflateResetKeep=R,r.deflateSetHeader=function(t,e){return t&&t.state?2!==t.state.wrap?f:(t.state.gzhead=e,0):f},r.deflate=function(t,e){var r,i,a,h;if(!t||!t.state||e>5||e<0)return t?_(t,f):f;if(i=t.state,!t.output||!t.input&&0!==t.avail_in||i.status===p&&4!==e)return _(t,0===t.avail_out?-5:f);if(i.strm=t,r=i.last_flush,i.last_flush=e,42===i.status)if(2===i.wrap)t.adler=0,y(i,31),y(i,139),y(i,8),i.gzhead?(y(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)),y(i,255&i.gzhead.time),y(i,i.gzhead.time>>8&255),y(i,i.gzhead.time>>16&255),y(i,i.gzhead.time>>24&255),y(i,9===i.level?2:i.strategy>=2||i.level<2?4:0),y(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(y(i,255&i.gzhead.extra.length),y(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(t.adler=o(t.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69):(y(i,0),y(i,0),y(i,0),y(i,0),y(i,0),y(i,9===i.level?2:i.strategy>=2||i.level<2?4:0),y(i,3),i.status=d);else{var u=8+(i.w_bits-8<<4)<<8;u|=(i.strategy>=2||i.level<2?0:i.level<6?1:6===i.level?2:3)<<6,0!==i.strstart&&(u|=32),u+=31-u%31,i.status=d,v(i,u),0!==i.strstart&&(v(i,t.adler>>>16),v(i,65535&t.adler)),t.adler=1}if(69===i.status)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&&(t.adler=o(t.adler,i.pending_buf,i.pending-a,a)),w(t),a=i.pending,i.pending!==i.pending_buf_size));)y(i,255&i.gzhead.extra[i.gzindex]),i.gzindex++;i.gzhead.hcrc&&i.pending>a&&(t.adler=o(t.adler,i.pending_buf,i.pending-a,a)),i.gzindex===i.gzhead.extra.length&&(i.gzindex=0,i.status=73)}else i.status=73;if(73===i.status)if(i.gzhead.name){a=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>a&&(t.adler=o(t.adler,i.pending_buf,i.pending-a,a)),w(t),a=i.pending,i.pending===i.pending_buf_size)){h=1;break}h=i.gzindex<i.gzhead.name.length?255&i.gzhead.name.charCodeAt(i.gzindex++):0,y(i,h)}while(0!==h);i.gzhead.hcrc&&i.pending>a&&(t.adler=o(t.adler,i.pending_buf,i.pending-a,a)),0===h&&(i.gzindex=0,i.status=91)}else i.status=91;if(91===i.status)if(i.gzhead.comment){a=i.pending;do{if(i.pending===i.pending_buf_size&&(i.gzhead.hcrc&&i.pending>a&&(t.adler=o(t.adler,i.pending_buf,i.pending-a,a)),w(t),a=i.pending,i.pending===i.pending_buf_size)){h=1;break}h=i.gzindex<i.gzhead.comment.length?255&i.gzhead.comment.charCodeAt(i.gzindex++):0,y(i,h)}while(0!==h);i.gzhead.hcrc&&i.pending>a&&(t.adler=o(t.adler,i.pending_buf,i.pending-a,a)),0===h&&(i.status=c)}else i.status=c;if(i.status===c&&(i.gzhead.hcrc?(i.pending+2>i.pending_buf_size&&w(t),i.pending+2<=i.pending_buf_size&&(y(i,255&t.adler),y(i,t.adler>>8&255),t.adler=0,i.status=d)):i.status=d),0!==i.pending){if(w(t),0===t.avail_out)return i.last_flush=-1,0}else if(0===t.avail_in&&g(e)<=g(r)&&4!==e)return _(t,-5);if(i.status===p&&0!==t.avail_in)return _(t,-5);if(0!==t.avail_in||0!==i.lookahead||0!==e&&i.status!==p){var E=2===i.strategy?function(t,e){for(var r;;){if(0===t.lookahead&&(k(t),0===t.lookahead)){if(0===e)return 1;break}if(t.match_length=0,r=s._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,r&&(m(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,4===e?(m(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(m(t,!1),0===t.strm.avail_out)?1:2}(i,e):3===i.strategy?function(t,e){for(var r,n,i,a,o=t.window;;){if(t.lookahead<=l){if(k(t),t.lookahead<=l&&0===e)return 1;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(n=o[i=t.strstart-1])===o[++i]&&n===o[++i]&&n===o[++i]){a=t.strstart+l;do{}while(n===o[++i]&&n===o[++i]&&n===o[++i]&&n===o[++i]&&n===o[++i]&&n===o[++i]&&n===o[++i]&&n===o[++i]&&i<a);t.match_length=l-(a-i),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=3?(r=s._tr_tally(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(r=s._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),r&&(m(t,!1),0===t.strm.avail_out))return 1}return t.insert=0,4===e?(m(t,!0),0===t.strm.avail_out?3:4):t.last_lit&&(m(t,!1),0===t.strm.avail_out)?1:2}(i,e):n[i.level].func(i,e);if(3!==E&&4!==E||(i.status=p),1===E||3===E)return 0===t.avail_out&&(i.last_flush=-1),0;if(2===E&&(1===e?s._tr_align(i):5!==e&&(s._tr_stored_block(i,0,0,!1),3===e&&(b(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),w(t),0===t.avail_out))return i.last_flush=-1,0}return 4!==e?0:i.wrap<=0?1:(2===i.wrap?(y(i,255&t.adler),y(i,t.adler>>8&255),y(i,t.adler>>16&255),y(i,t.adler>>24&255),y(i,255&t.total_in),y(i,t.total_in>>8&255),y(i,t.total_in>>16&255),y(i,t.total_in>>24&255)):(v(i,t.adler>>>16),v(i,65535&t.adler)),w(t),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?0:1)},r.deflateEnd=function(t){var e;return t&&t.state?42!==(e=t.state.status)&&69!==e&&73!==e&&91!==e&&e!==c&&e!==d&&e!==p?_(t,f):(t.state=null,e===d?_(t,-3):0):f},r.deflateSetDictionary=function(t,e){var r,n,s,o,h,l,u,c,d=e.length;if(!t||!t.state)return f;if(2===(o=(r=t.state).wrap)||1===o&&42!==r.status||r.lookahead)return f;for(1===o&&(t.adler=a(t.adler,e,d,0)),r.wrap=0,d>=r.w_size&&(0===o&&(b(r.head),r.strstart=0,r.block_start=0,r.insert=0),c=new i.Buf8(r.w_size),i.arraySet(c,e,d-r.w_size,r.w_size,0),e=c,d=r.w_size),h=t.avail_in,l=t.next_in,u=t.input,t.avail_in=d,t.next_in=0,t.input=e,k(r);r.lookahead>=3;){n=r.strstart,s=r.lookahead-2;do{r.ins_h=(r.ins_h<<r.hash_shift^r.window[n+3-1])&r.hash_mask,r.prev[n&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=n,n++}while(--s);r.strstart=n,r.lookahead=2,k(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=2,r.match_available=0,t.next_in=l,t.input=u,t.avail_in=h,r.wrap=o,0},r.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":39,"./adler32":40,"./crc32":42,"./messages":47,"./trees":48}],44:[function(t,e,r){"use strict";e.exports=function(t,e){var r,n,i,s,a,o,h,f,l,u,c,d,p,_,g,b,w,m,y,v,E,k,T,x,A;r=t.state,n=t.next_in,x=t.input,i=n+(t.avail_in-5),s=t.next_out,A=t.output,a=s-(e-t.avail_out),o=s+(t.avail_out-257),h=r.dmax,f=r.wsize,l=r.whave,u=r.wnext,c=r.window,d=r.hold,p=r.bits,_=r.lencode,g=r.distcode,b=(1<<r.lenbits)-1,w=(1<<r.distbits)-1;t:do{p<15&&(d+=x[n++]<<p,p+=8,d+=x[n++]<<p,p+=8),m=_[d&b];e:for(;;){if(d>>>=y=m>>>24,p-=y,0===(y=m>>>16&255))A[s++]=65535&m;else{if(!(16&y)){if(0==(64&y)){m=_[(65535&m)+(d&(1<<y)-1)];continue e}if(32&y){r.mode=12;break t}t.msg="invalid literal/length code",r.mode=30;break t}v=65535&m,(y&=15)&&(p<y&&(d+=x[n++]<<p,p+=8),v+=d&(1<<y)-1,d>>>=y,p-=y),p<15&&(d+=x[n++]<<p,p+=8,d+=x[n++]<<p,p+=8),m=g[d&w];r:for(;;){if(d>>>=y=m>>>24,p-=y,!(16&(y=m>>>16&255))){if(0==(64&y)){m=g[(65535&m)+(d&(1<<y)-1)];continue r}t.msg="invalid distance code",r.mode=30;break t}if(E=65535&m,p<(y&=15)&&(d+=x[n++]<<p,(p+=8)<y&&(d+=x[n++]<<p,p+=8)),(E+=d&(1<<y)-1)>h){t.msg="invalid distance too far back",r.mode=30;break t}if(d>>>=y,p-=y,E>(y=s-a)){if((y=E-y)>l&&r.sane){t.msg="invalid distance too far back",r.mode=30;break t}if(k=0,T=c,0===u){if(k+=f-y,y<v){v-=y;do{A[s++]=c[k++]}while(--y);k=s-E,T=A}}else if(u<y){if(k+=f+u-y,(y-=u)<v){v-=y;do{A[s++]=c[k++]}while(--y);if(k=0,u<v){v-=y=u;do{A[s++]=c[k++]}while(--y);k=s-E,T=A}}}else if(k+=u-y,y<v){v-=y;do{A[s++]=c[k++]}while(--y);k=s-E,T=A}for(;v>2;)A[s++]=T[k++],A[s++]=T[k++],A[s++]=T[k++],v-=3;v&&(A[s++]=T[k++],v>1&&(A[s++]=T[k++]))}else{k=s-E;do{A[s++]=A[k++],A[s++]=A[k++],A[s++]=A[k++],v-=3}while(v>2);v&&(A[s++]=A[k++],v>1&&(A[s++]=A[k++]))}break}}break}}while(n<i&&s<o);n-=v=p>>3,d&=(1<<(p-=v<<3))-1,t.next_in=n,t.next_out=s,t.avail_in=n<i?i-n+5:5-(n-i),t.avail_out=s<o?o-s+257:257-(s-o),r.hold=d,r.bits=p}},{}],45:[function(t,e,r){"use strict";var n=t("../utils/common"),i=t("./adler32"),s=t("./crc32"),a=t("./inffast"),o=t("./inftrees"),h=-2,f=12,l=30;function u(t){return(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function c(){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}function d(t){var e;return t&&t.state?(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=1,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new n.Buf32(852),e.distcode=e.distdyn=new n.Buf32(592),e.sane=1,e.back=-1,0):h}function p(t){var e;return t&&t.state?((e=t.state).wsize=0,e.whave=0,e.wnext=0,d(t)):h}function _(t,e){var r,n;return t&&t.state?(n=t.state,e<0?(r=0,e=-e):(r=1+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?h:(null!==n.window&&n.wbits!==e&&(n.window=null),n.wrap=r,n.wbits=e,p(t))):h}function g(t,e){var r,n;return t?(n=new c,t.state=n,n.window=null,0!==(r=_(t,e))&&(t.state=null),r):h}var b,w,m=!0;function y(t){if(m){var e;for(b=new n.Buf32(512),w=new n.Buf32(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(o(1,t.lens,0,288,b,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;o(2,t.lens,0,32,w,0,t.work,{bits:5}),m=!1}t.lencode=b,t.lenbits=9,t.distcode=w,t.distbits=5}function v(t,e,r,i){var s,a=t.state;return null===a.window&&(a.wsize=1<<a.wbits,a.wnext=0,a.whave=0,a.window=new n.Buf8(a.wsize)),i>=a.wsize?(n.arraySet(a.window,e,r-a.wsize,a.wsize,0),a.wnext=0,a.whave=a.wsize):((s=a.wsize-a.wnext)>i&&(s=i),n.arraySet(a.window,e,r-i,s,a.wnext),(i-=s)?(n.arraySet(a.window,e,r-i,i,0),a.wnext=i,a.whave=a.wsize):(a.wnext+=s,a.wnext===a.wsize&&(a.wnext=0),a.whave<a.wsize&&(a.whave+=s))),0}r.inflateReset=p,r.inflateReset2=_,r.inflateResetKeep=d,r.inflateInit=function(t){return g(t,15)},r.inflateInit2=g,r.inflate=function(t,e){var r,c,d,p,_,g,b,w,m,E,k,T,x,A,L,R,S,I,O,C,B,z,N,D,M=0,U=new n.Buf8(4),P=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!t||!t.state||!t.output||!t.input&&0!==t.avail_in)return h;(r=t.state).mode===f&&(r.mode=13),_=t.next_out,d=t.output,b=t.avail_out,p=t.next_in,c=t.input,g=t.avail_in,w=r.hold,m=r.bits,E=g,k=b,z=0;t:for(;;)switch(r.mode){case 1:if(0===r.wrap){r.mode=13;break}for(;m<16;){if(0===g)break t;g--,w+=c[p++]<<m,m+=8}if(2&r.wrap&&35615===w){r.check=0,U[0]=255&w,U[1]=w>>>8&255,r.check=s(r.check,U,2,0),w=0,m=0,r.mode=2;break}if(r.flags=0,r.head&&(r.head.done=!1),!(1&r.wrap)||(((255&w)<<8)+(w>>8))%31){t.msg="incorrect header check",r.mode=l;break}if(8!=(15&w)){t.msg="unknown compression method",r.mode=l;break}if(m-=4,B=8+(15&(w>>>=4)),0===r.wbits)r.wbits=B;else if(B>r.wbits){t.msg="invalid window size",r.mode=l;break}r.dmax=1<<B,t.adler=r.check=1,r.mode=512&w?10:f,w=0,m=0;break;case 2:for(;m<16;){if(0===g)break t;g--,w+=c[p++]<<m,m+=8}if(r.flags=w,8!=(255&r.flags)){t.msg="unknown compression method",r.mode=l;break}if(57344&r.flags){t.msg="unknown header flags set",r.mode=l;break}r.head&&(r.head.text=w>>8&1),512&r.flags&&(U[0]=255&w,U[1]=w>>>8&255,r.check=s(r.check,U,2,0)),w=0,m=0,r.mode=3;case 3:for(;m<32;){if(0===g)break t;g--,w+=c[p++]<<m,m+=8}r.head&&(r.head.time=w),512&r.flags&&(U[0]=255&w,U[1]=w>>>8&255,U[2]=w>>>16&255,U[3]=w>>>24&255,r.check=s(r.check,U,4,0)),w=0,m=0,r.mode=4;case 4:for(;m<16;){if(0===g)break t;g--,w+=c[p++]<<m,m+=8}r.head&&(r.head.xflags=255&w,r.head.os=w>>8),512&r.flags&&(U[0]=255&w,U[1]=w>>>8&255,r.check=s(r.check,U,2,0)),w=0,m=0,r.mode=5;case 5:if(1024&r.flags){for(;m<16;){if(0===g)break t;g--,w+=c[p++]<<m,m+=8}r.length=w,r.head&&(r.head.extra_len=w),512&r.flags&&(U[0]=255&w,U[1]=w>>>8&255,r.check=s(r.check,U,2,0)),w=0,m=0}else r.head&&(r.head.extra=null);r.mode=6;case 6:if(1024&r.flags&&((T=r.length)>g&&(T=g),T&&(r.head&&(B=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),n.arraySet(r.head.extra,c,p,T,B)),512&r.flags&&(r.check=s(r.check,c,T,p)),g-=T,p+=T,r.length-=T),r.length))break t;r.length=0,r.mode=7;case 7:if(2048&r.flags){if(0===g)break t;T=0;do{B=c[p+T++],r.head&&B&&r.length<65536&&(r.head.name+=String.fromCharCode(B))}while(B&&T<g);if(512&r.flags&&(r.check=s(r.check,c,T,p)),g-=T,p+=T,B)break t}else r.head&&(r.head.name=null);r.length=0,r.mode=8;case 8:if(4096&r.flags){if(0===g)break t;T=0;do{B=c[p+T++],r.head&&B&&r.length<65536&&(r.head.comment+=String.fromCharCode(B))}while(B&&T<g);if(512&r.flags&&(r.check=s(r.check,c,T,p)),g-=T,p+=T,B)break t}else r.head&&(r.head.comment=null);r.mode=9;case 9:if(512&r.flags){for(;m<16;){if(0===g)break t;g--,w+=c[p++]<<m,m+=8}if(w!==(65535&r.check)){t.msg="header crc mismatch",r.mode=l;break}w=0,m=0}r.head&&(r.head.hcrc=r.flags>>9&1,r.head.done=!0),t.adler=r.check=0,r.mode=f;break;case 10:for(;m<32;){if(0===g)break t;g--,w+=c[p++]<<m,m+=8}t.adler=r.check=u(w),w=0,m=0,r.mode=11;case 11:if(0===r.havedict)return t.next_out=_,t.avail_out=b,t.next_in=p,t.avail_in=g,r.hold=w,r.bits=m,2;t.adler=r.check=1,r.mode=f;case f:if(5===e||6===e)break t;case 13:if(r.last){w>>>=7&m,m-=7&m,r.mode=27;break}for(;m<3;){if(0===g)break t;g--,w+=c[p++]<<m,m+=8}switch(r.last=1&w,m-=1,3&(w>>>=1)){case 0:r.mode=14;break;case 1:if(y(r),r.mode=20,6===e){w>>>=2,m-=2;break t}break;case 2:r.mode=17;break;case 3:t.msg="invalid block type",r.mode=l}w>>>=2,m-=2;break;case 14:for(w>>>=7&m,m-=7&m;m<32;){if(0===g)break t;g--,w+=c[p++]<<m,m+=8}if((65535&w)!=(w>>>16^65535)){t.msg="invalid stored block lengths",r.mode=l;break}if(r.length=65535&w,w=0,m=0,r.mode=15,6===e)break t;case 15:r.mode=16;case 16:if(T=r.length){if(T>g&&(T=g),T>b&&(T=b),0===T)break t;n.arraySet(d,c,p,T,_),g-=T,p+=T,b-=T,_+=T,r.length-=T;break}r.mode=f;break;case 17:for(;m<14;){if(0===g)break t;g--,w+=c[p++]<<m,m+=8}if(r.nlen=257+(31&w),w>>>=5,m-=5,r.ndist=1+(31&w),w>>>=5,m-=5,r.ncode=4+(15&w),w>>>=4,m-=4,r.nlen>286||r.ndist>30){t.msg="too many length or distance symbols",r.mode=l;break}r.have=0,r.mode=18;case 18:for(;r.have<r.ncode;){for(;m<3;){if(0===g)break t;g--,w+=c[p++]<<m,m+=8}r.lens[P[r.have++]]=7&w,w>>>=3,m-=3}for(;r.have<19;)r.lens[P[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,N={bits:r.lenbits},z=o(0,r.lens,0,19,r.lencode,0,r.work,N),r.lenbits=N.bits,z){t.msg="invalid code lengths set",r.mode=l;break}r.have=0,r.mode=19;case 19:for(;r.have<r.nlen+r.ndist;){for(;R=(M=r.lencode[w&(1<<r.lenbits)-1])>>>16&255,S=65535&M,!((L=M>>>24)<=m);){if(0===g)break t;g--,w+=c[p++]<<m,m+=8}if(S<16)w>>>=L,m-=L,r.lens[r.have++]=S;else{if(16===S){for(D=L+2;m<D;){if(0===g)break t;g--,w+=c[p++]<<m,m+=8}if(w>>>=L,m-=L,0===r.have){t.msg="invalid bit length repeat",r.mode=l;break}B=r.lens[r.have-1],T=3+(3&w),w>>>=2,m-=2}else if(17===S){for(D=L+3;m<D;){if(0===g)break t;g--,w+=c[p++]<<m,m+=8}m-=L,B=0,T=3+(7&(w>>>=L)),w>>>=3,m-=3}else{for(D=L+7;m<D;){if(0===g)break t;g--,w+=c[p++]<<m,m+=8}m-=L,B=0,T=11+(127&(w>>>=L)),w>>>=7,m-=7}if(r.have+T>r.nlen+r.ndist){t.msg="invalid bit length repeat",r.mode=l;break}for(;T--;)r.lens[r.have++]=B}}if(r.mode===l)break;if(0===r.lens[256]){t.msg="invalid code -- missing end-of-block",r.mode=l;break}if(r.lenbits=9,N={bits:r.lenbits},z=o(1,r.lens,0,r.nlen,r.lencode,0,r.work,N),r.lenbits=N.bits,z){t.msg="invalid literal/lengths set",r.mode=l;break}if(r.distbits=6,r.distcode=r.distdyn,N={bits:r.distbits},z=o(2,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,N),r.distbits=N.bits,z){t.msg="invalid distances set",r.mode=l;break}if(r.mode=20,6===e)break t;case 20:r.mode=21;case 21:if(g>=6&&b>=258){t.next_out=_,t.avail_out=b,t.next_in=p,t.avail_in=g,r.hold=w,r.bits=m,a(t,k),_=t.next_out,d=t.output,b=t.avail_out,p=t.next_in,c=t.input,g=t.avail_in,w=r.hold,m=r.bits,r.mode===f&&(r.back=-1);break}for(r.back=0;R=(M=r.lencode[w&(1<<r.lenbits)-1])>>>16&255,S=65535&M,!((L=M>>>24)<=m);){if(0===g)break t;g--,w+=c[p++]<<m,m+=8}if(R&&0==(240&R)){for(I=L,O=R,C=S;R=(M=r.lencode[C+((w&(1<<I+O)-1)>>I)])>>>16&255,S=65535&M,!(I+(L=M>>>24)<=m);){if(0===g)break t;g--,w+=c[p++]<<m,m+=8}w>>>=I,m-=I,r.back+=I}if(w>>>=L,m-=L,r.back+=L,r.length=S,0===R){r.mode=26;break}if(32&R){r.back=-1,r.mode=f;break}if(64&R){t.msg="invalid literal/length code",r.mode=l;break}r.extra=15&R,r.mode=22;case 22:if(r.extra){for(D=r.extra;m<D;){if(0===g)break t;g--,w+=c[p++]<<m,m+=8}r.length+=w&(1<<r.extra)-1,w>>>=r.extra,m-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=23;case 23:for(;R=(M=r.distcode[w&(1<<r.distbits)-1])>>>16&255,S=65535&M,!((L=M>>>24)<=m);){if(0===g)break t;g--,w+=c[p++]<<m,m+=8}if(0==(240&R)){for(I=L,O=R,C=S;R=(M=r.distcode[C+((w&(1<<I+O)-1)>>I)])>>>16&255,S=65535&M,!(I+(L=M>>>24)<=m);){if(0===g)break t;g--,w+=c[p++]<<m,m+=8}w>>>=I,m-=I,r.back+=I}if(w>>>=L,m-=L,r.back+=L,64&R){t.msg="invalid distance code",r.mode=l;break}r.offset=S,r.extra=15&R,r.mode=24;case 24:if(r.extra){for(D=r.extra;m<D;){if(0===g)break t;g--,w+=c[p++]<<m,m+=8}r.offset+=w&(1<<r.extra)-1,w>>>=r.extra,m-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){t.msg="invalid distance too far back",r.mode=l;break}r.mode=25;case 25:if(0===b)break t;if(T=k-b,r.offset>T){if((T=r.offset-T)>r.whave&&r.sane){t.msg="invalid distance too far back",r.mode=l;break}T>r.wnext?(T-=r.wnext,x=r.wsize-T):x=r.wnext-T,T>r.length&&(T=r.length),A=r.window}else A=d,x=_-r.offset,T=r.length;T>b&&(T=b),b-=T,r.length-=T;do{d[_++]=A[x++]}while(--T);0===r.length&&(r.mode=21);break;case 26:if(0===b)break t;d[_++]=r.length,b--,r.mode=21;break;case 27:if(r.wrap){for(;m<32;){if(0===g)break t;g--,w|=c[p++]<<m,m+=8}if(k-=b,t.total_out+=k,r.total+=k,k&&(t.adler=r.check=r.flags?s(r.check,d,k,_-k):i(r.check,d,k,_-k)),k=b,(r.flags?w:u(w))!==r.check){t.msg="incorrect data check",r.mode=l;break}w=0,m=0}r.mode=28;case 28:if(r.wrap&&r.flags){for(;m<32;){if(0===g)break t;g--,w+=c[p++]<<m,m+=8}if(w!==(4294967295&r.total)){t.msg="incorrect length check",r.mode=l;break}w=0,m=0}r.mode=29;case 29:z=1;break t;case l:z=-3;break t;case 31:return-4;case 32:default:return h}return t.next_out=_,t.avail_out=b,t.next_in=p,t.avail_in=g,r.hold=w,r.bits=m,(r.wsize||k!==t.avail_out&&r.mode<l&&(r.mode<27||4!==e))&&v(t,t.output,t.next_out,k-t.avail_out)?(r.mode=31,-4):(E-=t.avail_in,k-=t.avail_out,t.total_in+=E,t.total_out+=k,r.total+=k,r.wrap&&k&&(t.adler=r.check=r.flags?s(r.check,d,k,t.next_out-k):i(r.check,d,k,t.next_out-k)),t.data_type=r.bits+(r.last?64:0)+(r.mode===f?128:0)+(20===r.mode||15===r.mode?256:0),(0===E&&0===k||4===e)&&0===z&&(z=-5),z)},r.inflateEnd=function(t){if(!t||!t.state)return h;var e=t.state;return e.window&&(e.window=null),t.state=null,0},r.inflateGetHeader=function(t,e){var r;return t&&t.state?0==(2&(r=t.state).wrap)?h:(r.head=e,e.done=!1,0):h},r.inflateSetDictionary=function(t,e){var r,n=e.length;return t&&t.state?0!==(r=t.state).wrap&&11!==r.mode?h:11===r.mode&&i(1,e,n,0)!==r.check?-3:v(t,e,n,n)?(r.mode=31,-4):(r.havedict=1,0):h},r.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":39,"./adler32":40,"./crc32":42,"./inffast":44,"./inftrees":46}],46:[function(t,e,r){"use strict";var n=t("../utils/common"),i=15,s=[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],a=[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],o=[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],h=[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];e.exports=function(t,e,r,f,l,u,c,d){var p,_,g,b,w,m,y,v,E,k=d.bits,T=0,x=0,A=0,L=0,R=0,S=0,I=0,O=0,C=0,B=0,z=null,N=0,D=new n.Buf16(16),M=new n.Buf16(16),U=null,P=0;for(T=0;T<=i;T++)D[T]=0;for(x=0;x<f;x++)D[e[r+x]]++;for(R=k,L=i;L>=1&&0===D[L];L--);if(R>L&&(R=L),0===L)return l[u++]=20971520,l[u++]=20971520,d.bits=1,0;for(A=1;A<L&&0===D[A];A++);for(R<A&&(R=A),O=1,T=1;T<=i;T++)if(O<<=1,(O-=D[T])<0)return-1;if(O>0&&(0===t||1!==L))return-1;for(M[1]=0,T=1;T<i;T++)M[T+1]=M[T]+D[T];for(x=0;x<f;x++)0!==e[r+x]&&(c[M[e[r+x]]++]=x);if(0===t?(z=U=c,m=19):1===t?(z=s,N-=257,U=a,P-=257,m=256):(z=o,U=h,m=-1),B=0,x=0,T=A,w=u,S=R,I=0,g=-1,b=(C=1<<R)-1,1===t&&C>852||2===t&&C>592)return 1;for(;;){y=T-I,c[x]<m?(v=0,E=c[x]):c[x]>m?(v=U[P+c[x]],E=z[N+c[x]]):(v=96,E=0),p=1<<T-I,A=_=1<<S;do{l[w+(B>>I)+(_-=p)]=y<<24|v<<16|E|0}while(0!==_);for(p=1<<T-1;B&p;)p>>=1;if(0!==p?(B&=p-1,B+=p):B=0,x++,0==--D[T]){if(T===L)break;T=e[r+c[x]]}if(T>R&&(B&b)!==g){for(0===I&&(I=R),w+=A,O=1<<(S=T-I);S+I<L&&!((O-=D[S+I])<=0);)S++,O<<=1;if(C+=1<<S,1===t&&C>852||2===t&&C>592)return 1;l[g=B&b]=R<<24|S<<16|w-u|0}}return 0!==B&&(l[w+B]=T-I<<24|64<<16|0),d.bits=R,0}},{"../utils/common":39}],47:[function(t,e,r){"use strict";e.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"}},{}],48:[function(t,e,r){"use strict";var n=t("../utils/common");function i(t){for(var e=t.length;--e>=0;)t[e]=0}var s=256,a=286,o=30,h=15,f=[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],l=[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],u=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],c=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],d=new Array(576);i(d);var p=new Array(60);i(p);var _=new Array(512);i(_);var g=new Array(256);i(g);var b=new Array(29);i(b);var w,m,y,v=new Array(o);function E(t,e,r,n,i){this.static_tree=t,this.extra_bits=e,this.extra_base=r,this.elems=n,this.max_length=i,this.has_stree=t&&t.length}function k(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function T(t){return t<256?_[t]:_[256+(t>>>7)]}function x(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function A(t,e,r){t.bi_valid>16-r?(t.bi_buf|=e<<t.bi_valid&65535,x(t,t.bi_buf),t.bi_buf=e>>16-t.bi_valid,t.bi_valid+=r-16):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=r)}function L(t,e,r){A(t,r[2*e],r[2*e+1])}function R(t,e){var r=0;do{r|=1&t,t>>>=1,r<<=1}while(--e>0);return r>>>1}function S(t,e,r){var n,i,s=new Array(16),a=0;for(n=1;n<=h;n++)s[n]=a=a+r[n-1]<<1;for(i=0;i<=e;i++){var o=t[2*i+1];0!==o&&(t[2*i]=R(s[o]++,o))}}function I(t){var e;for(e=0;e<a;e++)t.dyn_ltree[2*e]=0;for(e=0;e<o;e++)t.dyn_dtree[2*e]=0;for(e=0;e<19;e++)t.bl_tree[2*e]=0;t.dyn_ltree[512]=1,t.opt_len=t.static_len=0,t.last_lit=t.matches=0}function O(t){t.bi_valid>8?x(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function C(t,e,r,n){var i=2*e,s=2*r;return t[i]<t[s]||t[i]===t[s]&&n[e]<=n[r]}function B(t,e,r){for(var n=t.heap[r],i=r<<1;i<=t.heap_len&&(i<t.heap_len&&C(e,t.heap[i+1],t.heap[i],t.depth)&&i++,!C(e,n,t.heap[i],t.depth));)t.heap[r]=t.heap[i],r=i,i<<=1;t.heap[r]=n}function z(t,e,r){var n,i,a,o,h=0;if(0!==t.last_lit)do{n=t.pending_buf[t.d_buf+2*h]<<8|t.pending_buf[t.d_buf+2*h+1],i=t.pending_buf[t.l_buf+h],h++,0===n?L(t,i,e):(L(t,(a=g[i])+s+1,e),0!==(o=f[a])&&A(t,i-=b[a],o),L(t,a=T(--n),r),0!==(o=l[a])&&A(t,n-=v[a],o))}while(h<t.last_lit);L(t,256,e)}function N(t,e){var r,n,i,s=e.dyn_tree,a=e.stat_desc.static_tree,o=e.stat_desc.has_stree,f=e.stat_desc.elems,l=-1;for(t.heap_len=0,t.heap_max=573,r=0;r<f;r++)0!==s[2*r]?(t.heap[++t.heap_len]=l=r,t.depth[r]=0):s[2*r+1]=0;for(;t.heap_len<2;)s[2*(i=t.heap[++t.heap_len]=l<2?++l:0)]=1,t.depth[i]=0,t.opt_len--,o&&(t.static_len-=a[2*i+1]);for(e.max_code=l,r=t.heap_len>>1;r>=1;r--)B(t,s,r);i=f;do{r=t.heap[1],t.heap[1]=t.heap[t.heap_len--],B(t,s,1),n=t.heap[1],t.heap[--t.heap_max]=r,t.heap[--t.heap_max]=n,s[2*i]=s[2*r]+s[2*n],t.depth[i]=(t.depth[r]>=t.depth[n]?t.depth[r]:t.depth[n])+1,s[2*r+1]=s[2*n+1]=i,t.heap[1]=i++,B(t,s,1)}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],function(t,e){var r,n,i,s,a,o,f=e.dyn_tree,l=e.max_code,u=e.stat_desc.static_tree,c=e.stat_desc.has_stree,d=e.stat_desc.extra_bits,p=e.stat_desc.extra_base,_=e.stat_desc.max_length,g=0;for(s=0;s<=h;s++)t.bl_count[s]=0;for(f[2*t.heap[t.heap_max]+1]=0,r=t.heap_max+1;r<573;r++)(s=f[2*f[2*(n=t.heap[r])+1]+1]+1)>_&&(s=_,g++),f[2*n+1]=s,n>l||(t.bl_count[s]++,a=0,n>=p&&(a=d[n-p]),o=f[2*n],t.opt_len+=o*(s+a),c&&(t.static_len+=o*(u[2*n+1]+a)));if(0!==g){do{for(s=_-1;0===t.bl_count[s];)s--;t.bl_count[s]--,t.bl_count[s+1]+=2,t.bl_count[_]--,g-=2}while(g>0);for(s=_;0!==s;s--)for(n=t.bl_count[s];0!==n;)(i=t.heap[--r])>l||(f[2*i+1]!==s&&(t.opt_len+=(s-f[2*i+1])*f[2*i],f[2*i+1]=s),n--)}}(t,e),S(s,l,t.bl_count)}function D(t,e,r){var n,i,s=-1,a=e[1],o=0,h=7,f=4;for(0===a&&(h=138,f=3),e[2*(r+1)+1]=65535,n=0;n<=r;n++)i=a,a=e[2*(n+1)+1],++o<h&&i===a||(o<f?t.bl_tree[2*i]+=o:0!==i?(i!==s&&t.bl_tree[2*i]++,t.bl_tree[32]++):o<=10?t.bl_tree[34]++:t.bl_tree[36]++,o=0,s=i,0===a?(h=138,f=3):i===a?(h=6,f=3):(h=7,f=4))}function M(t,e,r){var n,i,s=-1,a=e[1],o=0,h=7,f=4;for(0===a&&(h=138,f=3),n=0;n<=r;n++)if(i=a,a=e[2*(n+1)+1],!(++o<h&&i===a)){if(o<f)do{L(t,i,t.bl_tree)}while(0!=--o);else 0!==i?(i!==s&&(L(t,i,t.bl_tree),o--),L(t,16,t.bl_tree),A(t,o-3,2)):o<=10?(L(t,17,t.bl_tree),A(t,o-3,3)):(L(t,18,t.bl_tree),A(t,o-11,7));o=0,s=i,0===a?(h=138,f=3):i===a?(h=6,f=3):(h=7,f=4)}}i(v);var U=!1;function P(t,e,r,i){A(t,0+(i?1:0),3),function(t,e,r,i){O(t),i&&(x(t,r),x(t,~r)),n.arraySet(t.pending_buf,t.window,e,r,t.pending),t.pending+=r}(t,e,r,!0)}r._tr_init=function(t){U||(!function(){var t,e,r,n,i,s=new Array(16);for(r=0,n=0;n<28;n++)for(b[n]=r,t=0;t<1<<f[n];t++)g[r++]=n;for(g[r-1]=n,i=0,n=0;n<16;n++)for(v[n]=i,t=0;t<1<<l[n];t++)_[i++]=n;for(i>>=7;n<o;n++)for(v[n]=i<<7,t=0;t<1<<l[n]-7;t++)_[256+i++]=n;for(e=0;e<=h;e++)s[e]=0;for(t=0;t<=143;)d[2*t+1]=8,t++,s[8]++;for(;t<=255;)d[2*t+1]=9,t++,s[9]++;for(;t<=279;)d[2*t+1]=7,t++,s[7]++;for(;t<=287;)d[2*t+1]=8,t++,s[8]++;for(S(d,287,s),t=0;t<o;t++)p[2*t+1]=5,p[2*t]=R(t,5);w=new E(d,f,257,a,h),m=new E(p,l,0,o,h),y=new E(new Array(0),u,0,19,7)}(),U=!0),t.l_desc=new k(t.dyn_ltree,w),t.d_desc=new k(t.dyn_dtree,m),t.bl_desc=new k(t.bl_tree,y),t.bi_buf=0,t.bi_valid=0,I(t)},r._tr_stored_block=P,r._tr_flush_block=function(t,e,r,n){var i,a,o=0;t.level>0?(2===t.strm.data_type&&(t.strm.data_type=function(t){var e,r=4093624447;for(e=0;e<=31;e++,r>>>=1)if(1&r&&0!==t.dyn_ltree[2*e])return 0;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e<s;e++)if(0!==t.dyn_ltree[2*e])return 1;return 0}(t)),N(t,t.l_desc),N(t,t.d_desc),o=function(t){var e;for(D(t,t.dyn_ltree,t.l_desc.max_code),D(t,t.dyn_dtree,t.d_desc.max_code),N(t,t.bl_desc),e=18;e>=3&&0===t.bl_tree[2*c[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}(t),i=t.opt_len+3+7>>>3,(a=t.static_len+3+7>>>3)<=i&&(i=a)):i=a=r+5,r+4<=i&&-1!==e?P(t,e,r,n):4===t.strategy||a===i?(A(t,2+(n?1:0),3),z(t,d,p)):(A(t,4+(n?1:0),3),function(t,e,r,n){var i;for(A(t,e-257,5),A(t,r-1,5),A(t,n-4,4),i=0;i<n;i++)A(t,t.bl_tree[2*c[i]+1],3);M(t,t.dyn_ltree,e-1),M(t,t.dyn_dtree,r-1)}(t,t.l_desc.max_code+1,t.d_desc.max_code+1,o+1),z(t,t.dyn_ltree,t.dyn_dtree)),I(t),n&&O(t)},r._tr_tally=function(t,e,r){return t.pending_buf[t.d_buf+2*t.last_lit]=e>>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&r,t.last_lit++,0===e?t.dyn_ltree[2*r]++:(t.matches++,e--,t.dyn_ltree[2*(g[r]+s+1)]++,t.dyn_dtree[2*T(e)]++),t.last_lit===t.lit_bufsize-1},r._tr_align=function(t){A(t,2,3),L(t,256,d),function(t){16===t.bi_valid?(x(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}(t)}},{"../utils/common":39}],49:[function(t,e,r){"use strict";e.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}},{}],50:[function(t,e,r){(function(t){"use strict";!t.version||0===t.version.indexOf("v0.")||0===t.version.indexOf("v1.")&&0!==t.version.indexOf("v1.8.")?e.exports=function(e,r,n,i){if("function"!=typeof e)throw new TypeError('"callback" argument must be a function');var s,a,o=arguments.length;switch(o){case 0:case 1:return t.nextTick(e);case 2:return t.nextTick((function(){e.call(null,r)}));case 3:return t.nextTick((function(){e.call(null,r,n)}));case 4:return t.nextTick((function(){e.call(null,r,n,i)}));default:for(s=new Array(o-1),a=0;a<s.length;)s[a++]=arguments[a];return t.nextTick((function(){e.apply(null,s)}))}}:e.exports=t.nextTick}).call(this,t("_process"))},{_process:51}],51:[function(t,e,r){var n,i,s=e.exports={};function a(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function h(t){if(n===setTimeout)return setTimeout(t,0);if((n===a||!n)&&setTimeout)return n=setTimeout,setTimeout(t,0);try{return n(t,0)}catch(e){try{return n.call(null,t,0)}catch(e){return n.call(this,t,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:a}catch(t){n=a}try{i="function"==typeof clearTimeout?clearTimeout:o}catch(t){i=o}}();var f,l=[],u=!1,c=-1;function d(){u&&f&&(u=!1,f.length?l=f.concat(l):c=-1,l.length&&p())}function p(){if(!u){var t=h(d);u=!0;for(var e=l.length;e;){for(f=l,l=[];++c<e;)f&&f[c].run();c=-1,e=l.length}f=null,u=!1,function(t){if(i===clearTimeout)return clearTimeout(t);if((i===o||!i)&&clearTimeout)return i=clearTimeout,clearTimeout(t);try{i(t)}catch(e){try{return i.call(null,t)}catch(e){return i.call(this,t)}}}(t)}}function _(t,e){this.fun=t,this.array=e}function g(){}s.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)e[r-1]=arguments[r];l.push(new _(t,e)),1!==l.length||u||h(p)},_.prototype.run=function(){this.fun.apply(null,this.array)},s.title="browser",s.browser=!0,s.env={},s.argv=[],s.version="",s.versions={},s.on=g,s.addListener=g,s.once=g,s.off=g,s.removeListener=g,s.removeAllListeners=g,s.emit=g,s.prependListener=g,s.prependOnceListener=g,s.listeners=function(t){return[]},s.binding=function(t){throw new Error("process.binding is not supported")},s.cwd=function(){return"/"},s.chdir=function(t){throw new Error("process.chdir is not supported")},s.umask=function(){return 0}},{}],52:[function(t,e,r){e.exports=t("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":53}],53:[function(t,e,r){"use strict";var n=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e};e.exports=u;var i=t("process-nextick-args"),s=t("core-util-is");s.inherits=t("inherits");var a=t("./_stream_readable"),o=t("./_stream_writable");s.inherits(u,a);for(var h=n(o.prototype),f=0;f<h.length;f++){var l=h[f];u.prototype[l]||(u.prototype[l]=o.prototype[l])}function u(t){if(!(this instanceof u))return new u(t);a.call(this,t),o.call(this,t),t&&!1===t.readable&&(this.readable=!1),t&&!1===t.writable&&(this.writable=!1),this.allowHalfOpen=!0,t&&!1===t.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",c)}function c(){this.allowHalfOpen||this._writableState.ended||i(d,this)}function d(t){t.end()}},{"./_stream_readable":55,"./_stream_writable":57,"core-util-is":33,inherits:36,"process-nextick-args":50}],54:[function(t,e,r){"use strict";e.exports=s;var n=t("./_stream_transform"),i=t("core-util-is");function s(t){if(!(this instanceof s))return new s(t);n.call(this,t)}i.inherits=t("inherits"),i.inherits(s,n),s.prototype._transform=function(t,e,r){r(null,t)}},{"./_stream_transform":56,"core-util-is":33,inherits:36}],55:[function(t,e,r){(function(r){"use strict";e.exports=b;var n,i=t("process-nextick-args"),s=t("isarray");b.ReadableState=g;t("events").EventEmitter;var a=function(t,e){return t.listeners(e).length},o=t("./internal/streams/stream"),h=t("buffer").Buffer,f=t("buffer-shims"),l=t("core-util-is");l.inherits=t("inherits");var u=t("util"),c=void 0;c=u&&u.debuglog?u.debuglog("stream"):function(){};var d,p=t("./internal/streams/BufferList");l.inherits(b,o);var _=["error","close","destroy","pause","resume"];function g(e,r){n=n||t("./_stream_duplex"),e=e||{},this.objectMode=!!e.objectMode,r instanceof n&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var i=e.highWaterMark,s=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:s,this.highWaterMark=~~this.highWaterMark,this.buffer=new p,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(d||(d=t("string_decoder/").StringDecoder),this.decoder=new d(e.encoding),this.encoding=e.encoding)}function b(e){if(n=n||t("./_stream_duplex"),!(this instanceof b))return new b(e);this._readableState=new g(e,this),this.readable=!0,e&&"function"==typeof e.read&&(this._read=e.read),o.call(this)}function w(t,e,r,n,s){var a=function(t,e){var r=null;h.isBuffer(e)||"string"==typeof e||null==e||t.objectMode||(r=new TypeError("Invalid non-string/buffer chunk"));return r}(e,r);if(a)t.emit("error",a);else if(null===r)e.reading=!1,function(t,e){if(e.ended)return;if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,v(t)}(t,e);else if(e.objectMode||r&&r.length>0)if(e.ended&&!s){var o=new Error("stream.push() after EOF");t.emit("error",o)}else if(e.endEmitted&&s){var f=new Error("stream.unshift() after end event");t.emit("error",f)}else{var l;!e.decoder||s||n||(r=e.decoder.write(r),l=!e.objectMode&&0===r.length),s||(e.reading=!1),l||(e.flowing&&0===e.length&&!e.sync?(t.emit("data",r),t.read(0)):(e.length+=e.objectMode?1:r.length,s?e.buffer.unshift(r):e.buffer.push(r),e.needReadable&&v(t))),function(t,e){e.readingMore||(e.readingMore=!0,i(k,t,e))}(t,e)}else s||(e.reading=!1);return function(t){return!t.ended&&(t.needReadable||t.length<t.highWaterMark||0===t.length)}(e)}b.prototype.push=function(t,e){var r=this._readableState;return r.objectMode||"string"!=typeof t||(e=e||r.defaultEncoding)!==r.encoding&&(t=f.from(t,e),e=""),w(this,r,t,e,!1)},b.prototype.unshift=function(t){return w(this,this._readableState,t,"",!0)},b.prototype.isPaused=function(){return!1===this._readableState.flowing},b.prototype.setEncoding=function(e){return d||(d=t("string_decoder/").StringDecoder),this._readableState.decoder=new d(e),this._readableState.encoding=e,this};var m=8388608;function y(t,e){return t<=0||0===e.length&&e.ended?0:e.objectMode?1:t!=t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=function(t){return t>=m?t=m:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}function v(t){var e=t._readableState;e.needReadable=!1,e.emittedReadable||(c("emitReadable",e.flowing),e.emittedReadable=!0,e.sync?i(E,t):E(t))}function E(t){c("emit readable"),t.emit("readable"),A(t)}function k(t,e){for(var r=e.length;!e.reading&&!e.flowing&&!e.ended&&e.length<e.highWaterMark&&(c("maybeReadMore read 0"),t.read(0),r!==e.length);)r=e.length;e.readingMore=!1}function T(t){c("readable nexttick read 0"),t.read(0)}function x(t,e){e.reading||(c("resume read 0"),t.read(0)),e.resumeScheduled=!1,e.awaitDrain=0,t.emit("resume"),A(t),e.flowing&&!e.reading&&t.read(0)}function A(t){var e=t._readableState;for(c("flow",e.flowing);e.flowing&&null!==t.read(););}function L(t,e){return 0===e.length?null:(e.objectMode?r=e.buffer.shift():!t||t>=e.length?(r=e.decoder?e.buffer.join(""):1===e.buffer.length?e.buffer.head.data:e.buffer.concat(e.length),e.buffer.clear()):r=function(t,e,r){var n;t<e.head.data.length?(n=e.head.data.slice(0,t),e.head.data=e.head.data.slice(t)):n=t===e.head.data.length?e.shift():r?function(t,e){var r=e.head,n=1,i=r.data;t-=i.length;for(;r=r.next;){var s=r.data,a=t>s.length?s.length:t;if(a===s.length?i+=s:i+=s.slice(0,t),0===(t-=a)){a===s.length?(++n,r.next?e.head=r.next:e.head=e.tail=null):(e.head=r,r.data=s.slice(a));break}++n}return e.length-=n,i}(t,e):function(t,e){var r=f.allocUnsafe(t),n=e.head,i=1;n.data.copy(r),t-=n.data.length;for(;n=n.next;){var s=n.data,a=t>s.length?s.length:t;if(s.copy(r,r.length-t,0,a),0===(t-=a)){a===s.length?(++i,n.next?e.head=n.next:e.head=e.tail=null):(e.head=n,n.data=s.slice(a));break}++i}return e.length-=i,r}(t,e);return n}(t,e.buffer,e.decoder),r);var r}function R(t){var e=t._readableState;if(e.length>0)throw new Error('"endReadable()" called on non-empty stream');e.endEmitted||(e.ended=!0,i(S,e,t))}function S(t,e){t.endEmitted||0!==t.length||(t.endEmitted=!0,e.readable=!1,e.emit("end"))}function I(t,e){for(var r=0,n=t.length;r<n;r++)if(t[r]===e)return r;return-1}b.prototype.read=function(t){c("read",t),t=parseInt(t,10);var e=this._readableState,r=t;if(0!==t&&(e.emittedReadable=!1),0===t&&e.needReadable&&(e.length>=e.highWaterMark||e.ended))return c("read: emitReadable",e.length,e.ended),0===e.length&&e.ended?R(this):v(this),null;if(0===(t=y(t,e))&&e.ended)return 0===e.length&&R(this),null;var n,i=e.needReadable;return c("need readable",i),(0===e.length||e.length-t<e.highWaterMark)&&c("length less than watermark",i=!0),e.ended||e.reading?c("reading or ended",i=!1):i&&(c("do read"),e.reading=!0,e.sync=!0,0===e.length&&(e.needReadable=!0),this._read(e.highWaterMark),e.sync=!1,e.reading||(t=y(r,e))),null===(n=t>0?L(t,e):null)?(e.needReadable=!0,t=0):e.length-=t,0===e.length&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&R(this)),null!==n&&this.emit("data",n),n},b.prototype._read=function(t){this.emit("error",new Error("_read() is not implemented"))},b.prototype.pipe=function(t,e){var n=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=t;break;case 1:o.pipes=[o.pipes,t];break;default:o.pipes.push(t)}o.pipesCount+=1,c("pipe count=%d opts=%j",o.pipesCount,e);var h=(!e||!1!==e.end)&&t!==r.stdout&&t!==r.stderr?l:p;function f(t){c("onunpipe"),t===n&&p()}function l(){c("onend"),t.end()}o.endEmitted?i(h):n.once("end",h),t.on("unpipe",f);var u=function(t){return function(){var e=t._readableState;c("pipeOnDrain",e.awaitDrain),e.awaitDrain&&e.awaitDrain--,0===e.awaitDrain&&a(t,"data")&&(e.flowing=!0,A(t))}}(n);t.on("drain",u);var d=!1;function p(){c("cleanup"),t.removeListener("close",w),t.removeListener("finish",m),t.removeListener("drain",u),t.removeListener("error",b),t.removeListener("unpipe",f),n.removeListener("end",l),n.removeListener("end",p),n.removeListener("data",g),d=!0,!o.awaitDrain||t._writableState&&!t._writableState.needDrain||u()}var _=!1;function g(e){c("ondata"),_=!1,!1!==t.write(e)||_||((1===o.pipesCount&&o.pipes===t||o.pipesCount>1&&-1!==I(o.pipes,t))&&!d&&(c("false write response, pause",n._readableState.awaitDrain),n._readableState.awaitDrain++,_=!0),n.pause())}function b(e){c("onerror",e),y(),t.removeListener("error",b),0===a(t,"error")&&t.emit("error",e)}function w(){t.removeListener("finish",m),y()}function m(){c("onfinish"),t.removeListener("close",w),y()}function y(){c("unpipe"),n.unpipe(t)}return n.on("data",g),function(t,e,r){if("function"==typeof t.prependListener)return t.prependListener(e,r);t._events&&t._events[e]?s(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]:t.on(e,r)}(t,"error",b),t.once("close",w),t.once("finish",m),t.emit("pipe",n),o.flowing||(c("pipe resume"),n.resume()),t},b.prototype.unpipe=function(t){var e=this._readableState;if(0===e.pipesCount)return this;if(1===e.pipesCount)return t&&t!==e.pipes||(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit("unpipe",this)),this;if(!t){var r=e.pipes,n=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var i=0;i<n;i++)r[i].emit("unpipe",this);return this}var s=I(e.pipes,t);return-1===s||(e.pipes.splice(s,1),e.pipesCount-=1,1===e.pipesCount&&(e.pipes=e.pipes[0]),t.emit("unpipe",this)),this},b.prototype.on=function(t,e){var r=o.prototype.on.call(this,t,e);if("data"===t)!1!==this._readableState.flowing&&this.resume();else if("readable"===t){var n=this._readableState;n.endEmitted||n.readableListening||(n.readableListening=n.needReadable=!0,n.emittedReadable=!1,n.reading?n.length&&v(this):i(T,this))}return r},b.prototype.addListener=b.prototype.on,b.prototype.resume=function(){var t=this._readableState;return t.flowing||(c("resume"),t.flowing=!0,function(t,e){e.resumeScheduled||(e.resumeScheduled=!0,i(x,t,e))}(this,t)),this},b.prototype.pause=function(){return c("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(c("pause"),this._readableState.flowing=!1,this.emit("pause")),this},b.prototype.wrap=function(t){var e=this._readableState,r=!1,n=this;for(var i in t.on("end",(function(){if(c("wrapped end"),e.decoder&&!e.ended){var t=e.decoder.end();t&&t.length&&n.push(t)}n.push(null)})),t.on("data",(function(i){(c("wrapped data"),e.decoder&&(i=e.decoder.write(i)),e.objectMode&&null==i)||(e.objectMode||i&&i.length)&&(n.push(i)||(r=!0,t.pause()))})),t)void 0===this[i]&&"function"==typeof t[i]&&(this[i]=function(e){return function(){return t[e].apply(t,arguments)}}(i));for(var s=0;s<_.length;s++)t.on(_[s],n.emit.bind(n,_[s]));return n._read=function(e){c("wrapped _read",e),r&&(r=!1,t.resume())},n},b._fromList=L}).call(this,t("_process"))},{"./_stream_duplex":53,"./internal/streams/BufferList":58,"./internal/streams/stream":59,_process:51,buffer:32,"buffer-shims":31,"core-util-is":33,events:34,inherits:36,isarray:38,"process-nextick-args":50,"string_decoder/":65,util:28}],56:[function(t,e,r){"use strict";e.exports=a;var n=t("./_stream_duplex"),i=t("core-util-is");function s(t){this.afterTransform=function(e,r){return function(t,e,r){var n=t._transformState;n.transforming=!1;var i=n.writecb;if(!i)return t.emit("error",new Error("no writecb in Transform class"));n.writechunk=null,n.writecb=null,null!=r&&t.push(r);i(e);var s=t._readableState;s.reading=!1,(s.needReadable||s.length<s.highWaterMark)&&t._read(s.highWaterMark)}(t,e,r)},this.needTransform=!1,this.transforming=!1,this.writecb=null,this.writechunk=null,this.writeencoding=null}function a(t){if(!(this instanceof a))return new a(t);n.call(this,t),this._transformState=new s(this);var e=this;this._readableState.needReadable=!0,this._readableState.sync=!1,t&&("function"==typeof t.transform&&(this._transform=t.transform),"function"==typeof t.flush&&(this._flush=t.flush)),this.once("prefinish",(function(){"function"==typeof this._flush?this._flush((function(t,r){o(e,t,r)})):o(e)}))}function o(t,e,r){if(e)return t.emit("error",e);null!=r&&t.push(r);var n=t._writableState,i=t._transformState;if(n.length)throw new Error("Calling transform done when ws.length != 0");if(i.transforming)throw new Error("Calling transform done when still transforming");return t.push(null)}i.inherits=t("inherits"),i.inherits(a,n),a.prototype.push=function(t,e){return this._transformState.needTransform=!1,n.prototype.push.call(this,t,e)},a.prototype._transform=function(t,e,r){throw new Error("_transform() is not implemented")},a.prototype._write=function(t,e,r){var n=this._transformState;if(n.writecb=r,n.writechunk=t,n.writeencoding=e,!n.transforming){var i=this._readableState;(n.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},a.prototype._read=function(t){var e=this._transformState;null!==e.writechunk&&e.writecb&&!e.transforming?(e.transforming=!0,this._transform(e.writechunk,e.writeencoding,e.afterTransform)):e.needTransform=!0}},{"./_stream_duplex":53,"core-util-is":33,inherits:36}],57:[function(t,e,r){(function(r,n){"use strict";e.exports=g;var i,s=t("process-nextick-args"),a=!r.browser&&["v0.10","v0.9."].indexOf(r.version.slice(0,5))>-1?n:s;g.WritableState=_;var o=t("core-util-is");o.inherits=t("inherits");var h,f={deprecate:t("util-deprecate")},l=t("./internal/streams/stream"),u=t("buffer").Buffer,c=t("buffer-shims");function d(){}function p(t,e,r){this.chunk=t,this.encoding=e,this.callback=r,this.next=null}function _(e,r){i=i||t("./_stream_duplex"),e=e||{},this.objectMode=!!e.objectMode,r instanceof i&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var n=e.highWaterMark,o=this.objectMode?16:16384;this.highWaterMark=n||0===n?n:o,this.highWaterMark=~~this.highWaterMark,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1;var h=!1===e.decodeStrings;this.decodeStrings=!h,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(t){!function(t,e){var r=t._writableState,n=r.sync,i=r.writecb;if(function(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}(r),e)!function(t,e,r,n,i){--e.pendingcb,r?s(i,n):i(n);t._writableState.errorEmitted=!0,t.emit("error",n)}(t,r,n,e,i);else{var o=y(r);o||r.corked||r.bufferProcessing||!r.bufferedRequest||m(t,r),n?a(w,t,r,o,i):w(t,r,o,i)}}(r,t)},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 k(this)}function g(e){if(i=i||t("./_stream_duplex"),!(h.call(g,this)||this instanceof i))return new g(e);this._writableState=new _(e,this),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev)),l.call(this)}function b(t,e,r,n,i,s,a){e.writelen=n,e.writecb=a,e.writing=!0,e.sync=!0,r?t._writev(i,e.onwrite):t._write(i,s,e.onwrite),e.sync=!1}function w(t,e,r,n){r||function(t,e){0===e.length&&e.needDrain&&(e.needDrain=!1,t.emit("drain"))}(t,e),e.pendingcb--,n(),E(t,e)}function m(t,e){e.bufferProcessing=!0;var r=e.bufferedRequest;if(t._writev&&r&&r.next){var n=e.bufferedRequestCount,i=new Array(n),s=e.corkedRequestsFree;s.entry=r;for(var a=0;r;)i[a]=r,r=r.next,a+=1;b(t,e,!0,e.length,i,"",s.finish),e.pendingcb++,e.lastBufferedRequest=null,s.next?(e.corkedRequestsFree=s.next,s.next=null):e.corkedRequestsFree=new k(e)}else{for(;r;){var o=r.chunk,h=r.encoding,f=r.callback;if(b(t,e,!1,e.objectMode?1:o.length,o,h,f),r=r.next,e.writing)break}null===r&&(e.lastBufferedRequest=null)}e.bufferedRequestCount=0,e.bufferedRequest=r,e.bufferProcessing=!1}function y(t){return t.ending&&0===t.length&&null===t.bufferedRequest&&!t.finished&&!t.writing}function v(t,e){e.prefinished||(e.prefinished=!0,t.emit("prefinish"))}function E(t,e){var r=y(e);return r&&(0===e.pendingcb?(v(t,e),e.finished=!0,t.emit("finish")):v(t,e)),r}function k(t){var e=this;this.next=null,this.entry=null,this.finish=function(r){var n=e.entry;for(e.entry=null;n;){var i=n.callback;t.pendingcb--,i(r),n=n.next}t.corkedRequestsFree?t.corkedRequestsFree.next=e:t.corkedRequestsFree=e}}o.inherits(g,l),_.prototype.getBuffer=function(){for(var t=this.bufferedRequest,e=[];t;)e.push(t),t=t.next;return e},function(){try{Object.defineProperty(_.prototype,"buffer",{get:f.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.")})}catch(t){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(h=Function.prototype[Symbol.hasInstance],Object.defineProperty(g,Symbol.hasInstance,{value:function(t){return!!h.call(this,t)||t&&t._writableState instanceof _}})):h=function(t){return t instanceof this},g.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},g.prototype.write=function(t,e,r){var n=this._writableState,i=!1,a=u.isBuffer(t);return"function"==typeof e&&(r=e,e=null),a?e="buffer":e||(e=n.defaultEncoding),"function"!=typeof r&&(r=d),n.ended?function(t,e){var r=new Error("write after end");t.emit("error",r),s(e,r)}(this,r):(a||function(t,e,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||e.objectMode||(a=new TypeError("Invalid non-string/buffer chunk")),a&&(t.emit("error",a),s(n,a),i=!1),i}(this,n,t,r))&&(n.pendingcb++,i=function(t,e,r,n,i,s){r||(n=function(t,e,r){t.objectMode||!1===t.decodeStrings||"string"!=typeof e||(e=c.from(e,r));return e}(e,n,i),u.isBuffer(n)&&(i="buffer"));var a=e.objectMode?1:n.length;e.length+=a;var o=e.length<e.highWaterMark;o||(e.needDrain=!0);if(e.writing||e.corked){var h=e.lastBufferedRequest;e.lastBufferedRequest=new p(n,i,s),h?h.next=e.lastBufferedRequest:e.bufferedRequest=e.lastBufferedRequest,e.bufferedRequestCount+=1}else b(t,e,!1,a,n,i,s);return o}(this,n,a,t,e,r)),i},g.prototype.cork=function(){this._writableState.corked++},g.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,t.writing||t.corked||t.finished||t.bufferProcessing||!t.bufferedRequest||m(this,t))},g.prototype.setDefaultEncoding=function(t){if("string"==typeof t&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this},g.prototype._write=function(t,e,r){r(new Error("_write() is not implemented"))},g.prototype._writev=null,g.prototype.end=function(t,e,r){var n=this._writableState;"function"==typeof t?(r=t,t=null,e=null):"function"==typeof e&&(r=e,e=null),null!=t&&this.write(t,e),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||function(t,e,r){e.ending=!0,E(t,e),r&&(e.finished?s(r):t.once("finish",r));e.ended=!0,t.writable=!1}(this,n,r)}}).call(this,t("_process"),t("timers").setImmediate)},{"./_stream_duplex":53,"./internal/streams/stream":59,_process:51,buffer:32,"buffer-shims":31,"core-util-is":33,inherits:36,"process-nextick-args":50,timers:66,"util-deprecate":67}],58:[function(t,e,r){"use strict";t("buffer").Buffer;var n=t("buffer-shims");function i(){this.head=null,this.tail=null,this.length=0}e.exports=i,i.prototype.push=function(t){var e={data:t,next:null};this.length>0?this.tail.next=e:this.head=e,this.tail=e,++this.length},i.prototype.unshift=function(t){var e={data:t,next:this.head};0===this.length&&(this.tail=e),this.head=e,++this.length},i.prototype.shift=function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}},i.prototype.clear=function(){this.head=this.tail=null,this.length=0},i.prototype.join=function(t){if(0===this.length)return"";for(var e=this.head,r=""+e.data;e=e.next;)r+=t+e.data;return r},i.prototype.concat=function(t){if(0===this.length)return n.alloc(0);if(1===this.length)return this.head.data;for(var e=n.allocUnsafe(t>>>0),r=this.head,i=0;r;)r.data.copy(e,i),i+=r.data.length,r=r.next;return e}},{buffer:32,"buffer-shims":31}],59:[function(t,e,r){e.exports=t("events").EventEmitter},{events:34}],60:[function(t,e,r){e.exports=t("./readable").PassThrough},{"./readable":61}],61:[function(t,e,r){(r=e.exports=t("./lib/_stream_readable.js")).Stream=r,r.Readable=r,r.Writable=t("./lib/_stream_writable.js"),r.Duplex=t("./lib/_stream_duplex.js"),r.Transform=t("./lib/_stream_transform.js"),r.PassThrough=t("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":53,"./lib/_stream_passthrough.js":54,"./lib/_stream_readable.js":55,"./lib/_stream_transform.js":56,"./lib/_stream_writable.js":57}],62:[function(t,e,r){e.exports=t("./readable").Transform},{"./readable":61}],63:[function(t,e,r){e.exports=t("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":57}],64:[function(t,e,r){e.exports=i;var n=t("events").EventEmitter;function i(){n.call(this)}t("inherits")(i,n),i.Readable=t("readable-stream/readable.js"),i.Writable=t("readable-stream/writable.js"),i.Duplex=t("readable-stream/duplex.js"),i.Transform=t("readable-stream/transform.js"),i.PassThrough=t("readable-stream/passthrough.js"),i.Stream=i,i.prototype.pipe=function(t,e){var r=this;function i(e){t.writable&&!1===t.write(e)&&r.pause&&r.pause()}function s(){r.readable&&r.resume&&r.resume()}r.on("data",i),t.on("drain",s),t._isStdio||e&&!1===e.end||(r.on("end",o),r.on("close",h));var a=!1;function o(){a||(a=!0,t.end())}function h(){a||(a=!0,"function"==typeof t.destroy&&t.destroy())}function f(t){if(l(),0===n.listenerCount(this,"error"))throw t}function l(){r.removeListener("data",i),t.removeListener("drain",s),r.removeListener("end",o),r.removeListener("close",h),r.removeListener("error",f),t.removeListener("error",f),r.removeListener("end",l),r.removeListener("close",l),t.removeListener("close",l)}return r.on("error",f),t.on("error",f),r.on("end",l),r.on("close",l),t.on("close",l),t.emit("pipe",r),t}},{events:34,inherits:36,"readable-stream/duplex.js":52,"readable-stream/passthrough.js":60,"readable-stream/readable.js":61,"readable-stream/transform.js":62,"readable-stream/writable.js":63}],65:[function(t,e,r){"use strict";var n=t("buffer").Buffer,i=t("buffer-shims"),s=n.isEncoding||function(t){switch((t=""+t)&&t.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 a(t){var e;switch(this.encoding=function(t){var e=function(t){if(!t)return"utf8";for(var e;;)switch(t){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 t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}(t);if("string"!=typeof e&&(n.isEncoding===s||!s(t)))throw new Error("Unknown encoding: "+t);return e||t}(t),this.encoding){case"utf16le":this.text=f,this.end=l,e=4;break;case"utf8":this.fillLast=h,e=4;break;case"base64":this.text=u,this.end=c,e=3;break;default:return this.write=d,void(this.end=p)}this.lastNeed=0,this.lastTotal=0,this.lastChar=i.allocUnsafe(e)}function o(t){return t<=127?0:t>>5==6?2:t>>4==14?3:t>>3==30?4:-1}function h(t){var e=this.lastTotal-this.lastNeed,r=function(t,e,r){if(128!=(192&e[0]))return t.lastNeed=0,"�".repeat(r);if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�".repeat(r+1);if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�".repeat(r+2)}}(this,t,e);return void 0!==r?r:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function f(t,e){if((t.length-e)%2==0){var r=t.toString("utf16le",e);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function l(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,r)}return e}function u(t,e){var r=(t.length-e)%3;return 0===r?t.toString("base64",e):(this.lastNeed=3-r,this.lastTotal=3,1===r?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-r))}function c(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function d(t){return t.toString(this.encoding)}function p(t){return t&&t.length?this.write(t):""}r.StringDecoder=a,a.prototype.write=function(t){if(0===t.length)return"";var e,r;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r<t.length?e?e+this.text(t,r):this.text(t,r):e||""},a.prototype.end=function(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"�".repeat(this.lastTotal-this.lastNeed):e},a.prototype.text=function(t,e){var r=function(t,e,r){var n=e.length-1;if(n<r)return 0;var i=o(e[n]);if(i>=0)return i>0&&(t.lastNeed=i-1),i;if(--n<r)return 0;if((i=o(e[n]))>=0)return i>0&&(t.lastNeed=i-2),i;if(--n<r)return 0;if((i=o(e[n]))>=0)return i>0&&(2===i?i=0:t.lastNeed=i-3),i;return 0}(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=r;var n=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,n),t.toString("utf8",e,n)},a.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length}},{buffer:32,"buffer-shims":31}],66:[function(t,e,r){(function(e,n){var i=t("process/browser.js").nextTick,s=Function.prototype.apply,a=Array.prototype.slice,o={},h=0;function f(t,e){this._id=t,this._clearFn=e}r.setTimeout=function(){return new f(s.call(setTimeout,window,arguments),clearTimeout)},r.setInterval=function(){return new f(s.call(setInterval,window,arguments),clearInterval)},r.clearTimeout=r.clearInterval=function(t){t.close()},f.prototype.unref=f.prototype.ref=function(){},f.prototype.close=function(){this._clearFn.call(window,this._id)},r.enroll=function(t,e){clearTimeout(t._idleTimeoutId),t._idleTimeout=e},r.unenroll=function(t){clearTimeout(t._idleTimeoutId),t._idleTimeout=-1},r._unrefActive=r.active=function(t){clearTimeout(t._idleTimeoutId);var e=t._idleTimeout;e>=0&&(t._idleTimeoutId=setTimeout((function(){t._onTimeout&&t._onTimeout()}),e))},r.setImmediate="function"==typeof e?e:function(t){var e=h++,n=!(arguments.length<2)&&a.call(arguments,1);return o[e]=!0,i((function(){o[e]&&(n?t.apply(null,n):t.call(null),r.clearImmediate(e))})),e},r.clearImmediate="function"==typeof n?n:function(t){delete o[t]}}).call(this,t("timers").setImmediate,t("timers").clearImmediate)},{"process/browser.js":51,timers:66}],67:[function(t,e,r){(function(t){function r(e){try{if(!t.localStorage)return!1}catch(t){return!1}var r=t.localStorage[e];return null!=r&&"true"===String(r).toLowerCase()}e.exports=function(t,e){if(r("noDeprecation"))return t;var n=!1;return function(){if(!n){if(r("throwDeprecation"))throw new Error(e);r("traceDeprecation")?console.trace(e):console.warn(e),n=!0}return t.apply(this,arguments)}}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],68:[function(t,e,r){arguments[4][25][0].apply(r,arguments)},{dup:25}],69:[function(t,e,r){arguments[4][26][0].apply(r,arguments)},{"./support/isBuffer":68,_process:51,dup:26,inherits:36}]},{},[20])(20)}));
\ No newline at end of file
index e84111f..a990a30 100644 (file)
@@ -1,256 +1 @@
-'use strict';
-
-var interlaceUtils = require('./interlace');
-
-var pixelBppMapper = [
-  // 0 - dummy entry
-  function() {},
-
-  // 1 - L
-  // 0: 0, 1: 0, 2: 0, 3: 0xff
-  function(pxData, data, pxPos, rawPos) {
-    if (rawPos === data.length) {
-      throw new Error('Ran out of data');
-    }
-
-    var pixel = data[rawPos];
-    pxData[pxPos] = pixel;
-    pxData[pxPos + 1] = pixel;
-    pxData[pxPos + 2] = pixel;
-    pxData[pxPos + 3] = 0xff;
-  },
-
-  // 2 - LA
-  // 0: 0, 1: 0, 2: 0, 3: 1
-  function(pxData, data, pxPos, rawPos) {
-    if (rawPos + 1 >= data.length) {
-      throw new Error('Ran out of data');
-    }
-
-    var pixel = data[rawPos];
-    pxData[pxPos] = pixel;
-    pxData[pxPos + 1] = pixel;
-    pxData[pxPos + 2] = pixel;
-    pxData[pxPos + 3] = data[rawPos + 1];
-  },
-
-  // 3 - RGB
-  // 0: 0, 1: 1, 2: 2, 3: 0xff
-  function(pxData, data, pxPos, rawPos) {
-    if (rawPos + 2 >= data.length) {
-      throw new Error('Ran out of data');
-    }
-
-    pxData[pxPos] = data[rawPos];
-    pxData[pxPos + 1] = data[rawPos + 1];
-    pxData[pxPos + 2] = data[rawPos + 2];
-    pxData[pxPos + 3] = 0xff;
-  },
-
-  // 4 - RGBA
-  // 0: 0, 1: 1, 2: 2, 3: 3
-  function(pxData, data, pxPos, rawPos) {
-    if (rawPos + 3 >= data.length) {
-      throw new Error('Ran out of data');
-    }
-
-    pxData[pxPos] = data[rawPos];
-    pxData[pxPos + 1] = data[rawPos + 1];
-    pxData[pxPos + 2] = data[rawPos + 2];
-    pxData[pxPos + 3] = data[rawPos + 3];
-  }
-];
-
-var pixelBppCustomMapper = [
-  // 0 - dummy entry
-  function() {},
-
-  // 1 - L
-  // 0: 0, 1: 0, 2: 0, 3: 0xff
-  function(pxData, pixelData, pxPos, maxBit) {
-    var pixel = pixelData[0];
-    pxData[pxPos] = pixel;
-    pxData[pxPos + 1] = pixel;
-    pxData[pxPos + 2] = pixel;
-    pxData[pxPos + 3] = maxBit;
-  },
-
-  // 2 - LA
-  // 0: 0, 1: 0, 2: 0, 3: 1
-  function(pxData, pixelData, pxPos) {
-    var pixel = pixelData[0];
-    pxData[pxPos] = pixel;
-    pxData[pxPos + 1] = pixel;
-    pxData[pxPos + 2] = pixel;
-    pxData[pxPos + 3] = pixelData[1];
-  },
-
-  // 3 - RGB
-  // 0: 0, 1: 1, 2: 2, 3: 0xff
-  function(pxData, pixelData, pxPos, maxBit) {
-    pxData[pxPos] = pixelData[0];
-    pxData[pxPos + 1] = pixelData[1];
-    pxData[pxPos + 2] = pixelData[2];
-    pxData[pxPos + 3] = maxBit;
-  },
-
-  // 4 - RGBA
-  // 0: 0, 1: 1, 2: 2, 3: 3
-  function(pxData, pixelData, pxPos) {
-    pxData[pxPos] = pixelData[0];
-    pxData[pxPos + 1] = pixelData[1];
-    pxData[pxPos + 2] = pixelData[2];
-    pxData[pxPos + 3] = pixelData[3];
-  }
-];
-
-function bitRetriever(data, depth) {
-
-  var leftOver = [];
-  var i = 0;
-
-  function split() {
-    if (i === data.length) {
-      throw new Error('Ran out of data');
-    }
-    var byte = data[i];
-    i++;
-    var byte8, byte7, byte6, byte5, byte4, byte3, byte2, byte1;
-    switch (depth) {
-      default:
-        throw new Error('unrecognised depth');
-      case 16:
-        byte2 = data[i];
-        i++;
-        leftOver.push(((byte << 8) + byte2));
-        break;
-      case 4:
-        byte2 = byte & 0x0f;
-        byte1 = byte >> 4;
-        leftOver.push(byte1, byte2);
-        break;
-      case 2:
-        byte4 = byte & 3;
-        byte3 = byte >> 2 & 3;
-        byte2 = byte >> 4 & 3;
-        byte1 = byte >> 6 & 3;
-        leftOver.push(byte1, byte2, byte3, byte4);
-        break;
-      case 1:
-        byte8 = byte & 1;
-        byte7 = byte >> 1 & 1;
-        byte6 = byte >> 2 & 1;
-        byte5 = byte >> 3 & 1;
-        byte4 = byte >> 4 & 1;
-        byte3 = byte >> 5 & 1;
-        byte2 = byte >> 6 & 1;
-        byte1 = byte >> 7 & 1;
-        leftOver.push(byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8);
-        break;
-    }
-  }
-
-  return {
-    get: function(count) {
-      while (leftOver.length < count) {
-        split();
-      }
-      var returner = leftOver.slice(0, count);
-      leftOver = leftOver.slice(count);
-      return returner;
-    },
-    resetAfterLine: function() {
-      leftOver.length = 0;
-    },
-    end: function() {
-      if (i !== data.length) {
-        throw new Error('extra data found');
-      }
-    }
-  };
-}
-
-function mapImage8Bit(image, pxData, getPxPos, bpp, data, rawPos) { // eslint-disable-line max-params
-  var imageWidth = image.width;
-  var imageHeight = image.height;
-  var imagePass = image.index;
-  for (var y = 0; y < imageHeight; y++) {
-    for (var x = 0; x < imageWidth; x++) {
-      var pxPos = getPxPos(x, y, imagePass);
-      pixelBppMapper[bpp](pxData, data, pxPos, rawPos);
-      rawPos += bpp; //eslint-disable-line no-param-reassign
-    }
-  }
-  return rawPos;
-}
-
-function mapImageCustomBit(image, pxData, getPxPos, bpp, bits, maxBit) { // eslint-disable-line max-params
-  var imageWidth = image.width;
-  var imageHeight = image.height;
-  var imagePass = image.index;
-  for (var y = 0; y < imageHeight; y++) {
-    for (var x = 0; x < imageWidth; x++) {
-      var pixelData = bits.get(bpp);
-      var pxPos = getPxPos(x, y, imagePass);
-      pixelBppCustomMapper[bpp](pxData, pixelData, pxPos, maxBit);
-    }
-    bits.resetAfterLine();
-  }
-}
-
-exports.dataToBitMap = function(data, bitmapInfo) {
-
-  var width = bitmapInfo.width;
-  var height = bitmapInfo.height;
-  var depth = bitmapInfo.depth;
-  var bpp = bitmapInfo.bpp;
-  var interlace = bitmapInfo.interlace;
-
-  if (depth !== 8) {
-    var bits = bitRetriever(data, depth);
-  }
-  var pxData;
-  if (depth <= 8) {
-    pxData = new Buffer(width * height * 4);
-  }
-  else {
-    pxData = new Uint16Array(width * height * 4);
-  }
-  var maxBit = Math.pow(2, depth) - 1;
-  var rawPos = 0;
-  var images;
-  var getPxPos;
-
-  if (interlace) {
-    images = interlaceUtils.getImagePasses(width, height);
-    getPxPos = interlaceUtils.getInterlaceIterator(width, height);
-  }
-  else {
-    var nonInterlacedPxPos = 0;
-    getPxPos = function() {
-      var returner = nonInterlacedPxPos;
-      nonInterlacedPxPos += 4;
-      return returner;
-    };
-    images = [{ width: width, height: height }];
-  }
-
-  for (var imageIndex = 0; imageIndex < images.length; imageIndex++) {
-    if (depth === 8) {
-      rawPos = mapImage8Bit(images[imageIndex], pxData, getPxPos, bpp, data, rawPos);
-    }
-    else {
-      mapImageCustomBit(images[imageIndex], pxData, getPxPos, bpp, bits, maxBit);
-    }
-  }
-  if (depth === 8) {
-    if (rawPos !== data.length) {
-      throw new Error('extra data found');
-    }
-  }
-  else {
-    bits.end();
-  }
-
-  return pxData;
-};
+"use strict";var interlaceUtils=require("./interlace"),pixelBppMapper=[function(){},function(t,e,r,n){if(n===e.length)throw new Error("Ran out of data");var a=e[n];t[r]=a,t[r+1]=a,t[r+2]=a,t[r+3]=255},function(t,e,r,n){if(n+1>=e.length)throw new Error("Ran out of data");var a=e[n];t[r]=a,t[r+1]=a,t[r+2]=a,t[r+3]=e[n+1]},function(t,e,r,n){if(n+2>=e.length)throw new Error("Ran out of data");t[r]=e[n],t[r+1]=e[n+1],t[r+2]=e[n+2],t[r+3]=255},function(t,e,r,n){if(n+3>=e.length)throw new Error("Ran out of data");t[r]=e[n],t[r+1]=e[n+1],t[r+2]=e[n+2],t[r+3]=e[n+3]}],pixelBppCustomMapper=[function(){},function(t,e,r,n){var a=e[0];t[r]=a,t[r+1]=a,t[r+2]=a,t[r+3]=n},function(t,e,r){var n=e[0];t[r]=n,t[r+1]=n,t[r+2]=n,t[r+3]=e[1]},function(t,e,r,n){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=n},function(t,e,r){t[r]=e[0],t[r+1]=e[1],t[r+2]=e[2],t[r+3]=e[3]}];function bitRetriever(t,e){var r=[],n=0;function a(){if(n===t.length)throw new Error("Ran out of data");var a,i,o,f,u,h,p,c,s=t[n];switch(n++,e){default:throw new Error("unrecognised depth");case 16:p=t[n],n++,r.push((s<<8)+p);break;case 4:p=15&s,c=s>>4,r.push(c,p);break;case 2:u=3&s,h=s>>2&3,p=s>>4&3,c=s>>6&3,r.push(c,p,h,u);break;case 1:a=1&s,i=s>>1&1,o=s>>2&1,f=s>>3&1,u=s>>4&1,h=s>>5&1,p=s>>6&1,c=s>>7&1,r.push(c,p,h,u,f,o,i,a)}}return{get:function(t){for(;r.length<t;)a();var e=r.slice(0,t);return r=r.slice(t),e},resetAfterLine:function(){r.length=0},end:function(){if(n!==t.length)throw new Error("extra data found")}}}function mapImage8Bit(t,e,r,n,a,i){for(var o=t.width,f=t.height,u=t.index,h=0;h<f;h++)for(var p=0;p<o;p++){var c=r(p,h,u);pixelBppMapper[n](e,a,c,i),i+=n}return i}function mapImageCustomBit(t,e,r,n,a,i){for(var o=t.width,f=t.height,u=t.index,h=0;h<f;h++){for(var p=0;p<o;p++){var c=a.get(n),s=r(p,h,u);pixelBppCustomMapper[n](e,c,s,i)}a.resetAfterLine()}}exports.dataToBitMap=function(t,e){var r,n=e.width,a=e.height,i=e.depth,o=e.bpp,f=e.interlace;if(8!==i)var u=bitRetriever(t,i);r=i<=8?new Buffer(n*a*4):new Uint16Array(n*a*4);var h,p,c=Math.pow(2,i)-1,s=0;if(f)h=interlaceUtils.getImagePasses(n,a),p=interlaceUtils.getInterlaceIterator(n,a);else{var l=0;p=function(){var t=l;return l+=4,t},h=[{width:n,height:a}]}for(var g=0;g<h.length;g++)8===i?s=mapImage8Bit(h[g],r,p,o,t,s):mapImageCustomBit(h[g],r,p,o,u,c);if(8===i){if(s!==t.length)throw new Error("extra data found")}else u.end();return r};
\ No newline at end of file
index 788bf42..a90cbce 100644 (file)
@@ -1,143 +1 @@
-'use strict';
-
-var constants = require('./constants');
-
-module.exports = function(dataIn, width, height, options) {
-  var outHasAlpha = [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf(options.colorType) !== -1;
-  if (options.colorType === options.inputColorType) {
-    var bigEndian = (function() {
-      var buffer = new ArrayBuffer(2);
-      new DataView(buffer).setInt16(0, 256, true /* littleEndian */);
-      // Int16Array uses the platform's endianness.
-      return new Int16Array(buffer)[0] !== 256;
-    })();
-    // If no need to convert to grayscale and alpha is present/absent in both, take a fast route
-    if (options.bitDepth === 8 || (options.bitDepth === 16 && bigEndian)) {
-      return dataIn;
-    }
-  }
-
-  // map to a UInt16 array if data is 16bit, fix endianness below
-  var data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer);
-
-  var maxValue = 255;
-  var inBpp = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType];
-  if (inBpp === 4 && !options.inputHasAlpha) {
-    inBpp = 3;
-  }
-  var outBpp = constants.COLORTYPE_TO_BPP_MAP[options.colorType];
-  if (options.bitDepth === 16) {
-    maxValue = 65535;
-    outBpp *= 2;
-  }
-  var outData = new Buffer(width * height * outBpp);
-
-  var inIndex = 0;
-  var outIndex = 0;
-
-  var bgColor = options.bgColor || {};
-  if (bgColor.red === undefined) {
-    bgColor.red = maxValue;
-  }
-  if (bgColor.green === undefined) {
-    bgColor.green = maxValue;
-  }
-  if (bgColor.blue === undefined) {
-    bgColor.blue = maxValue;
-  }
-
-  function getRGBA() {
-    var red;
-    var green;
-    var blue;
-    var alpha = maxValue;
-    switch (options.inputColorType) {
-      case constants.COLORTYPE_COLOR_ALPHA:
-        alpha = data[inIndex + 3];
-        red = data[inIndex];
-        green = data[inIndex + 1];
-        blue = data[inIndex + 2];
-        break;
-      case constants.COLORTYPE_COLOR:
-        red = data[inIndex];
-        green = data[inIndex + 1];
-        blue = data[inIndex + 2];
-        break;
-      case constants.COLORTYPE_ALPHA:
-        alpha = data[inIndex + 1];
-        red = data[inIndex];
-        green = red;
-        blue = red;
-        break;
-      case constants.COLORTYPE_GRAYSCALE:
-        red = data[inIndex];
-        green = red;
-        blue = red;
-        break;
-      default:
-        throw new Error('input color type:' + options.inputColorType + ' is not supported at present');
-    }
-
-    if (options.inputHasAlpha) {
-      if (!outHasAlpha) {
-        alpha /= maxValue;
-        red = Math.min(Math.max(Math.round((1 - alpha) * bgColor.red + alpha * red), 0), maxValue);
-        green = Math.min(Math.max(Math.round((1 - alpha) * bgColor.green + alpha * green), 0), maxValue);
-        blue = Math.min(Math.max(Math.round((1 - alpha) * bgColor.blue + alpha * blue), 0), maxValue);
-      }
-    }
-    return { red: red, green: green, blue: blue, alpha: alpha };
-  }
-
-  for (var y = 0; y < height; y++) {
-    for (var x = 0; x < width; x++) {
-      var rgba = getRGBA(data, inIndex);
-
-      switch (options.colorType) {
-        case constants.COLORTYPE_COLOR_ALPHA:
-        case constants.COLORTYPE_COLOR:
-          if (options.bitDepth === 8) {
-            outData[outIndex] = rgba.red;
-            outData[outIndex + 1] = rgba.green;
-            outData[outIndex + 2] = rgba.blue;
-            if (outHasAlpha) {
-              outData[outIndex + 3] = rgba.alpha;
-            }
-          }
-          else {
-            outData.writeUInt16BE(rgba.red, outIndex);
-            outData.writeUInt16BE(rgba.green, outIndex + 2);
-            outData.writeUInt16BE(rgba.blue, outIndex + 4);
-            if (outHasAlpha) {
-              outData.writeUInt16BE(rgba.alpha, outIndex + 6);
-            }
-          }
-          break;
-        case constants.COLORTYPE_ALPHA:
-        case constants.COLORTYPE_GRAYSCALE:
-          // Convert to grayscale and alpha
-          var grayscale = (rgba.red + rgba.green + rgba.blue) / 3;
-          if (options.bitDepth === 8) {
-            outData[outIndex] = grayscale;
-            if (outHasAlpha) {
-              outData[outIndex + 1] = rgba.alpha;
-            }
-          }
-          else {
-            outData.writeUInt16BE(grayscale, outIndex);
-            if (outHasAlpha) {
-              outData.writeUInt16BE(rgba.alpha, outIndex + 2);
-            }
-          }
-          break;
-        default:
-          throw new Error('unrecognised color Type ' + options.colorType);
-      }
-
-      inIndex += inBpp;
-      outIndex += outBpp;
-    }
-  }
-
-  return outData;
-};
+"use strict";var constants=require("./constants");module.exports=function(e,t,r,n){var a,o=-1!==[constants.COLORTYPE_COLOR_ALPHA,constants.COLORTYPE_ALPHA].indexOf(n.colorType);if(n.colorType===n.inputColorType){var s=(a=new ArrayBuffer(2),new DataView(a).setInt16(0,256,!0),256!==new Int16Array(a)[0]);if(8===n.bitDepth||16===n.bitDepth&&s)return e}var i=16!==n.bitDepth?e:new Uint16Array(e.buffer),O=255,c=constants.COLORTYPE_TO_BPP_MAP[n.inputColorType];4!==c||n.inputHasAlpha||(c=3);var p=constants.COLORTYPE_TO_BPP_MAP[n.colorType];16===n.bitDepth&&(O=65535,p*=2);var u=new Buffer(t*r*p),l=0,h=0,L=n.bgColor||{};function C(){var e,t,r,a=O;switch(n.inputColorType){case constants.COLORTYPE_COLOR_ALPHA:a=i[l+3],e=i[l],t=i[l+1],r=i[l+2];break;case constants.COLORTYPE_COLOR:e=i[l],t=i[l+1],r=i[l+2];break;case constants.COLORTYPE_ALPHA:a=i[l+1],t=e=i[l],r=e;break;case constants.COLORTYPE_GRAYSCALE:t=e=i[l],r=e;break;default:throw new Error("input color type:"+n.inputColorType+" is not supported at present")}return n.inputHasAlpha&&(o||(a/=O,e=Math.min(Math.max(Math.round((1-a)*L.red+a*e),0),O),t=Math.min(Math.max(Math.round((1-a)*L.green+a*t),0),O),r=Math.min(Math.max(Math.round((1-a)*L.blue+a*r),0),O))),{red:e,green:t,blue:r,alpha:a}}void 0===L.red&&(L.red=O),void 0===L.green&&(L.green=O),void 0===L.blue&&(L.blue=O);for(var P=0;P<r;P++)for(var T=0;T<t;T++){var A=C();switch(n.colorType){case constants.COLORTYPE_COLOR_ALPHA:case constants.COLORTYPE_COLOR:8===n.bitDepth?(u[h]=A.red,u[h+1]=A.green,u[h+2]=A.blue,o&&(u[h+3]=A.alpha)):(u.writeUInt16BE(A.red,h),u.writeUInt16BE(A.green,h+2),u.writeUInt16BE(A.blue,h+4),o&&u.writeUInt16BE(A.alpha,h+6));break;case constants.COLORTYPE_ALPHA:case constants.COLORTYPE_GRAYSCALE:var E=(A.red+A.green+A.blue)/3;8===n.bitDepth?(u[h]=E,o&&(u[h+1]=A.alpha)):(u.writeUInt16BE(E,h),o&&u.writeUInt16BE(A.alpha,h+2));break;default:throw new Error("unrecognised color Type "+n.colorType)}l+=c,h+=p}return u};
\ No newline at end of file
index 0e542de..926a861 100644 (file)
@@ -1,209 +1 @@
-'use strict';
-
-
-var util = require('util');
-var Stream = require('stream');
-
-
-var ChunkStream = module.exports = function() {
-  Stream.call(this);
-
-  this._buffers = [];
-  this._buffered = 0;
-
-  this._reads = [];
-  this._paused = false;
-
-  this._encoding = 'utf8';
-  this.writable = true;
-};
-util.inherits(ChunkStream, Stream);
-
-
-ChunkStream.prototype.read = function(length, callback) {
-
-  this._reads.push({
-    length: Math.abs(length), // if length < 0 then at most this length
-    allowLess: length < 0,
-    func: callback
-  });
-
-  process.nextTick(function() {
-    this._process();
-
-    // its paused and there is not enought data then ask for more
-    if (this._paused && this._reads.length > 0) {
-      this._paused = false;
-
-      this.emit('drain');
-    }
-  }.bind(this));
-};
-
-ChunkStream.prototype.write = function(data, encoding) {
-
-  if (!this.writable) {
-    this.emit('error', new Error('Stream not writable'));
-    return false;
-  }
-
-  var dataBuffer;
-  if (Buffer.isBuffer(data)) {
-    dataBuffer = data;
-  }
-  else {
-    dataBuffer = new Buffer(data, encoding || this._encoding);
-  }
-
-  this._buffers.push(dataBuffer);
-  this._buffered += dataBuffer.length;
-
-  this._process();
-
-  // ok if there are no more read requests
-  if (this._reads && this._reads.length === 0) {
-    this._paused = true;
-  }
-
-  return this.writable && !this._paused;
-};
-
-ChunkStream.prototype.end = function(data, encoding) {
-
-  if (data) {
-    this.write(data, encoding);
-  }
-
-  this.writable = false;
-
-  // already destroyed
-  if (!this._buffers) {
-    return;
-  }
-
-  // enqueue or handle end
-  if (this._buffers.length === 0) {
-    this._end();
-  }
-  else {
-    this._buffers.push(null);
-    this._process();
-  }
-};
-
-ChunkStream.prototype.destroySoon = ChunkStream.prototype.end;
-
-ChunkStream.prototype._end = function() {
-
-  if (this._reads.length > 0) {
-    this.emit('error',
-      new Error('Unexpected end of input')
-    );
-  }
-
-  this.destroy();
-};
-
-ChunkStream.prototype.destroy = function() {
-
-  if (!this._buffers) {
-    return;
-  }
-
-  this.writable = false;
-  this._reads = null;
-  this._buffers = null;
-
-  this.emit('close');
-};
-
-ChunkStream.prototype._processReadAllowingLess = function(read) {
-  // ok there is any data so that we can satisfy this request
-  this._reads.shift(); // == read
-
-  // first we need to peek into first buffer
-  var smallerBuf = this._buffers[0];
-
-  // ok there is more data than we need
-  if (smallerBuf.length > read.length) {
-
-    this._buffered -= read.length;
-    this._buffers[0] = smallerBuf.slice(read.length);
-
-    read.func.call(this, smallerBuf.slice(0, read.length));
-
-  }
-  else {
-    // ok this is less than maximum length so use it all
-    this._buffered -= smallerBuf.length;
-    this._buffers.shift(); // == smallerBuf
-
-    read.func.call(this, smallerBuf);
-  }
-};
-
-ChunkStream.prototype._processRead = function(read) {
-  this._reads.shift(); // == read
-
-  var pos = 0;
-  var count = 0;
-  var data = new Buffer(read.length);
-
-  // create buffer for all data
-  while (pos < read.length) {
-
-    var buf = this._buffers[count++];
-    var len = Math.min(buf.length, read.length - pos);
-
-    buf.copy(data, pos, 0, len);
-    pos += len;
-
-    // last buffer wasn't used all so just slice it and leave
-    if (len !== buf.length) {
-      this._buffers[--count] = buf.slice(len);
-    }
-  }
-
-  // remove all used buffers
-  if (count > 0) {
-    this._buffers.splice(0, count);
-  }
-
-  this._buffered -= read.length;
-
-  read.func.call(this, data);
-};
-
-ChunkStream.prototype._process = function() {
-
-  try {
-    // as long as there is any data and read requests
-    while (this._buffered > 0 && this._reads && this._reads.length > 0) {
-
-      var read = this._reads[0];
-
-      // read any data (but no more than length)
-      if (read.allowLess) {
-        this._processReadAllowingLess(read);
-
-      }
-      else if (this._buffered >= read.length) {
-        // ok we can meet some expectations
-
-        this._processRead(read);
-      }
-      else {
-        // not enought data to satisfy first request in queue
-        // so we need to wait for more
-        break;
-      }
-    }
-
-    if (this._buffers && !this.writable) {
-      this._end();
-    }
-  }
-  catch (ex) {
-    this.emit('error', ex);
-  }
-};
+"use strict";var util=require("util"),Stream=require("stream"),ChunkStream=module.exports=function(){Stream.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};util.inherits(ChunkStream,Stream),ChunkStream.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e}),process.nextTick(function(){this._process(),this._paused&&this._reads.length>0&&(this._paused=!1,this.emit("drain"))}.bind(this))},ChunkStream.prototype.write=function(t,e){return this.writable?(s=Buffer.isBuffer(t)?t:new Buffer(t,e||this._encoding),this._buffers.push(s),this._buffered+=s.length,this._process(),this._reads&&0===this._reads.length&&(this._paused=!0),this.writable&&!this._paused):(this.emit("error",new Error("Stream not writable")),!1);var s},ChunkStream.prototype.end=function(t,e){t&&this.write(t,e),this.writable=!1,this._buffers&&(0===this._buffers.length?this._end():(this._buffers.push(null),this._process()))},ChunkStream.prototype.destroySoon=ChunkStream.prototype.end,ChunkStream.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()},ChunkStream.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))},ChunkStream.prototype._processReadAllowingLess=function(t){this._reads.shift();var e=this._buffers[0];e.length>t.length?(this._buffered-=t.length,this._buffers[0]=e.slice(t.length),t.func.call(this,e.slice(0,t.length))):(this._buffered-=e.length,this._buffers.shift(),t.func.call(this,e))},ChunkStream.prototype._processRead=function(t){this._reads.shift();for(var e=0,s=0,r=new Buffer(t.length);e<t.length;){var i=this._buffers[s++],h=Math.min(i.length,t.length-e);i.copy(r,e,0,h),e+=h,h!==i.length&&(this._buffers[--s]=i.slice(h))}s>0&&this._buffers.splice(0,s),this._buffered-=t.length,t.func.call(this,r)},ChunkStream.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){var t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else{if(!(this._buffered>=t.length))break;this._processRead(t)}}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}};
\ No newline at end of file
index 22d919d..63cf18e 100644 (file)
@@ -1,34 +1 @@
-'use strict';
-
-
-module.exports = {
-
-  PNG_SIGNATURE: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a],
-
-  TYPE_IHDR: 0x49484452,
-  TYPE_IEND: 0x49454e44,
-  TYPE_IDAT: 0x49444154,
-  TYPE_PLTE: 0x504c5445,
-  TYPE_tRNS: 0x74524e53, // eslint-disable-line camelcase
-  TYPE_gAMA: 0x67414d41, // eslint-disable-line camelcase
-
-  // color-type bits
-  COLORTYPE_GRAYSCALE: 0,
-  COLORTYPE_PALETTE: 1,
-  COLORTYPE_COLOR: 2,
-  COLORTYPE_ALPHA: 4, // e.g. grayscale and alpha
-
-  // color-type combinations
-  COLORTYPE_PALETTE_COLOR: 3,
-  COLORTYPE_COLOR_ALPHA: 6,
-
-  COLORTYPE_TO_BPP_MAP: {
-    0: 1,
-    2: 3,
-    3: 1,
-    4: 2,
-    6: 4
-  },
-
-  GAMMA_DIVISION: 100000
-};
+"use strict";module.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5};
\ No newline at end of file
index 0705ed2..c9400f6 100644 (file)
@@ -1,44 +1 @@
-'use strict';
-
-var crcTable = [];
-
-(function() {
-  for (var i = 0; i < 256; i++) {
-    var currentCrc = i;
-    for (var j = 0; j < 8; j++) {
-      if (currentCrc & 1) {
-        currentCrc = 0xedb88320 ^ (currentCrc >>> 1);
-      }
-      else {
-        currentCrc = currentCrc >>> 1;
-      }
-    }
-    crcTable[i] = currentCrc;
-  }
-}());
-
-var CrcCalculator = module.exports = function() {
-  this._crc = -1;
-};
-
-CrcCalculator.prototype.write = function(data) {
-
-  for (var i = 0; i < data.length; i++) {
-    this._crc = crcTable[(this._crc ^ data[i]) & 0xff] ^ (this._crc >>> 8);
-  }
-  return true;
-};
-
-CrcCalculator.prototype.crc32 = function() {
-  return this._crc ^ -1;
-};
-
-
-CrcCalculator.crc32 = function(buf) {
-
-  var crc = -1;
-  for (var i = 0; i < buf.length; i++) {
-    crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
-  }
-  return crc ^ -1;
-};
+"use strict";var crcTable=[];!function(){for(var r=0;r<256;r++){for(var c=r,t=0;t<8;t++)1&c?c=3988292384^c>>>1:c>>>=1;crcTable[r]=c}}();var CrcCalculator=module.exports=function(){this._crc=-1};CrcCalculator.prototype.write=function(r){for(var c=0;c<r.length;c++)this._crc=crcTable[255&(this._crc^r[c])]^this._crc>>>8;return!0},CrcCalculator.prototype.crc32=function(){return-1^this._crc},CrcCalculator.crc32=function(r){for(var c=-1,t=0;t<r.length;t++)c=crcTable[255&(c^r[t])]^c>>>8;return-1^c};
\ No newline at end of file
index 0a3eac8..b641374 100644 (file)
@@ -1,190 +1 @@
-'use strict';
-
-var paethPredictor = require('./paeth-predictor');
-
-function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) {
-
-  for (var x = 0; x < byteWidth; x++) {
-    rawData[rawPos + x] = pxData[pxPos + x];
-  }
-}
-
-function filterSumNone(pxData, pxPos, byteWidth) {
-
-  var sum = 0;
-  var length = pxPos + byteWidth;
-
-  for (var i = pxPos; i < length; i++) {
-    sum += Math.abs(pxData[i]);
-  }
-  return sum;
-}
-
-function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
-
-  for (var x = 0; x < byteWidth; x++) {
-
-    var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
-    var val = pxData[pxPos + x] - left;
-
-    rawData[rawPos + x] = val;
-  }
-}
-
-function filterSumSub(pxData, pxPos, byteWidth, bpp) {
-
-  var sum = 0;
-  for (var x = 0; x < byteWidth; x++) {
-
-    var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
-    var val = pxData[pxPos + x] - left;
-
-    sum += Math.abs(val);
-  }
-
-  return sum;
-}
-
-function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) {
-
-  for (var x = 0; x < byteWidth; x++) {
-
-    var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
-    var val = pxData[pxPos + x] - up;
-
-    rawData[rawPos + x] = val;
-  }
-}
-
-function filterSumUp(pxData, pxPos, byteWidth) {
-
-  var sum = 0;
-  var length = pxPos + byteWidth;
-  for (var x = pxPos; x < length; x++) {
-
-    var up = pxPos > 0 ? pxData[x - byteWidth] : 0;
-    var val = pxData[x] - up;
-
-    sum += Math.abs(val);
-  }
-
-  return sum;
-}
-
-function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
-
-  for (var x = 0; x < byteWidth; x++) {
-
-    var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
-    var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
-    var val = pxData[pxPos + x] - ((left + up) >> 1);
-
-    rawData[rawPos + x] = val;
-  }
-}
-
-function filterSumAvg(pxData, pxPos, byteWidth, bpp) {
-
-  var sum = 0;
-  for (var x = 0; x < byteWidth; x++) {
-
-    var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
-    var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
-    var val = pxData[pxPos + x] - ((left + up) >> 1);
-
-    sum += Math.abs(val);
-  }
-
-  return sum;
-}
-
-function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
-
-  for (var x = 0; x < byteWidth; x++) {
-
-    var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
-    var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
-    var upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
-    var val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
-
-    rawData[rawPos + x] = val;
-  }
-}
-
-function filterSumPaeth(pxData, pxPos, byteWidth, bpp) {
-  var sum = 0;
-  for (var x = 0; x < byteWidth; x++) {
-
-    var left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
-    var up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
-    var upleft = pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
-    var val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
-
-    sum += Math.abs(val);
-  }
-
-  return sum;
-}
-
-var filters = {
-  0: filterNone,
-  1: filterSub,
-  2: filterUp,
-  3: filterAvg,
-  4: filterPaeth
-};
-
-var filterSums = {
-  0: filterSumNone,
-  1: filterSumSub,
-  2: filterSumUp,
-  3: filterSumAvg,
-  4: filterSumPaeth
-};
-
-module.exports = function(pxData, width, height, options, bpp) {
-
-  var filterTypes;
-  if (!('filterType' in options) || options.filterType === -1) {
-    filterTypes = [0, 1, 2, 3, 4];
-  }
-  else if (typeof options.filterType === 'number') {
-    filterTypes = [options.filterType];
-  }
-  else {
-    throw new Error('unrecognised filter types');
-  }
-
-  if (options.bitDepth === 16) {
-    bpp *= 2;
-  }
-  var byteWidth = width * bpp;
-  var rawPos = 0;
-  var pxPos = 0;
-  var rawData = new Buffer((byteWidth + 1) * height);
-
-  var sel = filterTypes[0];
-
-  for (var y = 0; y < height; y++) {
-
-    if (filterTypes.length > 1) {
-      // find best filter for this line (with lowest sum of values)
-      var min = Infinity;
-
-      for (var i = 0; i < filterTypes.length; i++) {
-        var sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp);
-        if (sum < min) {
-          sel = filterTypes[i];
-          min = sum;
-        }
-      }
-    }
-
-    rawData[rawPos] = sel;
-    rawPos++;
-    filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp);
-    rawPos += byteWidth;
-    pxPos += byteWidth;
-  }
-  return rawData;
-};
+"use strict";var paethPredictor=require("./paeth-predictor");function filterNone(r,e,t,f,i){for(var a=0;a<t;a++)f[i+a]=r[e+a]}function filterSumNone(r,e,t){for(var f=0,i=e+t,a=e;a<i;a++)f+=Math.abs(r[a]);return f}function filterSub(r,e,t,f,i,a){for(var n=0;n<t;n++){var u=n>=a?r[e+n-a]:0,o=r[e+n]-u;f[i+n]=o}}function filterSumSub(r,e,t,f){for(var i=0,a=0;a<t;a++){var n=a>=f?r[e+a-f]:0,u=r[e+a]-n;i+=Math.abs(u)}return i}function filterUp(r,e,t,f,i){for(var a=0;a<t;a++){var n=e>0?r[e+a-t]:0,u=r[e+a]-n;f[i+a]=u}}function filterSumUp(r,e,t){for(var f=0,i=e+t,a=e;a<i;a++){var n=e>0?r[a-t]:0,u=r[a]-n;f+=Math.abs(u)}return f}function filterAvg(r,e,t,f,i,a){for(var n=0;n<t;n++){var u=n>=a?r[e+n-a]:0,o=e>0?r[e+n-t]:0,l=r[e+n]-(u+o>>1);f[i+n]=l}}function filterSumAvg(r,e,t,f){for(var i=0,a=0;a<t;a++){var n=a>=f?r[e+a-f]:0,u=e>0?r[e+a-t]:0,o=r[e+a]-(n+u>>1);i+=Math.abs(o)}return i}function filterPaeth(r,e,t,f,i,a){for(var n=0;n<t;n++){var u=n>=a?r[e+n-a]:0,o=e>0?r[e+n-t]:0,l=e>0&&n>=a?r[e+n-(t+a)]:0,v=r[e+n]-paethPredictor(u,o,l);f[i+n]=v}}function filterSumPaeth(r,e,t,f){for(var i=0,a=0;a<t;a++){var n=a>=f?r[e+a-f]:0,u=e>0?r[e+a-t]:0,o=e>0&&a>=f?r[e+a-(t+f)]:0,l=r[e+a]-paethPredictor(n,u,o);i+=Math.abs(l)}return i}var filters={0:filterNone,1:filterSub,2:filterUp,3:filterAvg,4:filterPaeth},filterSums={0:filterSumNone,1:filterSumSub,2:filterSumUp,3:filterSumAvg,4:filterSumPaeth};module.exports=function(r,e,t,f,i){var a;if("filterType"in f&&-1!==f.filterType){if("number"!=typeof f.filterType)throw new Error("unrecognised filter types");a=[f.filterType]}else a=[0,1,2,3,4];16===f.bitDepth&&(i*=2);for(var n=e*i,u=0,o=0,l=new Buffer((n+1)*t),v=a[0],c=0;c<t;c++){if(a.length>1)for(var h=1/0,p=0;p<a.length;p++){var S=filterSums[a[p]](r,o,n,i);S<h&&(v=a[p],h=S)}l[u]=v,u++,filters[v](r,o,n,l,u,i),u+=n,o+=n}return l};
\ No newline at end of file
index 560c30e..8f604e0 100644 (file)
@@ -1,25 +1 @@
-'use strict';
-
-var util = require('util');
-var ChunkStream = require('./chunkstream');
-var Filter = require('./filter-parse');
-
-
-var FilterAsync = module.exports = function(bitmapInfo) {
-  ChunkStream.call(this);
-
-  var buffers = [];
-  var that = this;
-  this._filter = new Filter(bitmapInfo, {
-    read: this.read.bind(this),
-    write: function(buffer) {
-      buffers.push(buffer);
-    },
-    complete: function() {
-      that.emit('complete', Buffer.concat(buffers));
-    }
-  });
-
-  this._filter.start();
-};
-util.inherits(FilterAsync, ChunkStream);
+"use strict";var util=require("util"),ChunkStream=require("./chunkstream"),Filter=require("./filter-parse"),FilterAsync=module.exports=function(t){ChunkStream.call(this);var e=[],i=this;this._filter=new Filter(t,{read:this.read.bind(this),write:function(t){e.push(t)},complete:function(){i.emit("complete",Buffer.concat(e))}}),this._filter.start()};util.inherits(FilterAsync,ChunkStream);
\ No newline at end of file
index 958c676..b7abc5a 100644 (file)
@@ -1,24 +1 @@
-'use strict';
-
-var SyncReader = require('./sync-reader');
-var Filter = require('./filter-parse');
-
-
-exports.process = function(inBuffer, bitmapInfo) {
-
-  var outBuffers = [];
-  var reader = new SyncReader(inBuffer);
-  var filter = new Filter(bitmapInfo, {
-    read: reader.read.bind(reader),
-    write: function(bufferPart) {
-      outBuffers.push(bufferPart);
-    },
-    complete: function() {
-    }
-  });
-
-  filter.start();
-  reader.process();
-
-  return Buffer.concat(outBuffers);
-};
\ No newline at end of file
+"use strict";var SyncReader=require("./sync-reader"),Filter=require("./filter-parse");exports.process=function(e,r){var t=[],n=new SyncReader(e);return new Filter(r,{read:n.read.bind(n),write:function(e){t.push(e)},complete:function(){}}).start(),n.process(),Buffer.concat(t)};
\ No newline at end of file
index 3f0e14b..b36b823 100644 (file)
@@ -1,171 +1 @@
-'use strict';
-
-var interlaceUtils = require('./interlace');
-var paethPredictor = require('./paeth-predictor');
-
-function getByteWidth(width, bpp, depth) {
-  var byteWidth = width * bpp;
-  if (depth !== 8) {
-    byteWidth = Math.ceil(byteWidth / (8 / depth));
-  }
-  return byteWidth;
-}
-
-var Filter = module.exports = function(bitmapInfo, dependencies) {
-
-  var width = bitmapInfo.width;
-  var height = bitmapInfo.height;
-  var interlace = bitmapInfo.interlace;
-  var bpp = bitmapInfo.bpp;
-  var depth = bitmapInfo.depth;
-
-  this.read = dependencies.read;
-  this.write = dependencies.write;
-  this.complete = dependencies.complete;
-
-  this._imageIndex = 0;
-  this._images = [];
-  if (interlace) {
-    var passes = interlaceUtils.getImagePasses(width, height);
-    for (var i = 0; i < passes.length; i++) {
-      this._images.push({
-        byteWidth: getByteWidth(passes[i].width, bpp, depth),
-        height: passes[i].height,
-        lineIndex: 0
-      });
-    }
-  }
-  else {
-    this._images.push({
-      byteWidth: getByteWidth(width, bpp, depth),
-      height: height,
-      lineIndex: 0
-    });
-  }
-
-  // when filtering the line we look at the pixel to the left
-  // the spec also says it is done on a byte level regardless of the number of pixels
-  // so if the depth is byte compatible (8 or 16) we subtract the bpp in order to compare back
-  // a pixel rather than just a different byte part. However if we are sub byte, we ignore.
-  if (depth === 8) {
-    this._xComparison = bpp;
-  }
-  else if (depth === 16) {
-    this._xComparison = bpp * 2;
-  }
-  else {
-    this._xComparison = 1;
-  }
-};
-
-Filter.prototype.start = function() {
-  this.read(this._images[this._imageIndex].byteWidth + 1, this._reverseFilterLine.bind(this));
-};
-
-Filter.prototype._unFilterType1 = function(rawData, unfilteredLine, byteWidth) {
-
-  var xComparison = this._xComparison;
-  var xBiggerThan = xComparison - 1;
-
-  for (var x = 0; x < byteWidth; x++) {
-    var rawByte = rawData[1 + x];
-    var f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
-    unfilteredLine[x] = rawByte + f1Left;
-  }
-};
-
-Filter.prototype._unFilterType2 = function(rawData, unfilteredLine, byteWidth) {
-
-  var lastLine = this._lastLine;
-
-  for (var x = 0; x < byteWidth; x++) {
-    var rawByte = rawData[1 + x];
-    var f2Up = lastLine ? lastLine[x] : 0;
-    unfilteredLine[x] = rawByte + f2Up;
-  }
-};
-
-Filter.prototype._unFilterType3 = function(rawData, unfilteredLine, byteWidth) {
-
-  var xComparison = this._xComparison;
-  var xBiggerThan = xComparison - 1;
-  var lastLine = this._lastLine;
-
-  for (var x = 0; x < byteWidth; x++) {
-    var rawByte = rawData[1 + x];
-    var f3Up = lastLine ? lastLine[x] : 0;
-    var f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
-    var f3Add = Math.floor((f3Left + f3Up) / 2);
-    unfilteredLine[x] = rawByte + f3Add;
-  }
-};
-
-Filter.prototype._unFilterType4 = function(rawData, unfilteredLine, byteWidth) {
-
-  var xComparison = this._xComparison;
-  var xBiggerThan = xComparison - 1;
-  var lastLine = this._lastLine;
-
-  for (var x = 0; x < byteWidth; x++) {
-    var rawByte = rawData[1 + x];
-    var f4Up = lastLine ? lastLine[x] : 0;
-    var f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
-    var f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0;
-    var f4Add = paethPredictor(f4Left, f4Up, f4UpLeft);
-    unfilteredLine[x] = rawByte + f4Add;
-  }
-};
-
-Filter.prototype._reverseFilterLine = function(rawData) {
-
-  var filter = rawData[0];
-  var unfilteredLine;
-  var currentImage = this._images[this._imageIndex];
-  var byteWidth = currentImage.byteWidth;
-
-  if (filter === 0) {
-    unfilteredLine = rawData.slice(1, byteWidth + 1);
-  }
-  else {
-
-    unfilteredLine = new Buffer(byteWidth);
-
-    switch (filter) {
-      case 1:
-        this._unFilterType1(rawData, unfilteredLine, byteWidth);
-        break;
-      case 2:
-        this._unFilterType2(rawData, unfilteredLine, byteWidth);
-        break;
-      case 3:
-        this._unFilterType3(rawData, unfilteredLine, byteWidth);
-        break;
-      case 4:
-        this._unFilterType4(rawData, unfilteredLine, byteWidth);
-        break;
-      default:
-        throw new Error('Unrecognised filter type - ' + filter);
-    }
-  }
-
-  this.write(unfilteredLine);
-
-  currentImage.lineIndex++;
-  if (currentImage.lineIndex >= currentImage.height) {
-    this._lastLine = null;
-    this._imageIndex++;
-    currentImage = this._images[this._imageIndex];
-  }
-  else {
-    this._lastLine = unfilteredLine;
-  }
-
-  if (currentImage) {
-    // read, using the byte width that may be from the new current image
-    this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this));
-  }
-  else {
-    this._lastLine = null;
-    this.complete();
-  }
-};
+"use strict";var interlaceUtils=require("./interlace"),paethPredictor=require("./paeth-predictor");function getByteWidth(e,t,i){var r=e*t;return 8!==i&&(r=Math.ceil(r/(8/i))),r}var Filter=module.exports=function(e,t){var i=e.width,r=e.height,s=e.interlace,h=e.bpp,n=e.depth;if(this.read=t.read,this.write=t.write,this.complete=t.complete,this._imageIndex=0,this._images=[],s)for(var a=interlaceUtils.getImagePasses(i,r),l=0;l<a.length;l++)this._images.push({byteWidth:getByteWidth(a[l].width,h,n),height:a[l].height,lineIndex:0});else this._images.push({byteWidth:getByteWidth(i,h,n),height:r,lineIndex:0});this._xComparison=8===n?h:16===n?2*h:1};Filter.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))},Filter.prototype._unFilterType1=function(e,t,i){for(var r=this._xComparison,s=r-1,h=0;h<i;h++){var n=e[1+h],a=h>s?t[h-r]:0;t[h]=n+a}},Filter.prototype._unFilterType2=function(e,t,i){for(var r=this._lastLine,s=0;s<i;s++){var h=e[1+s],n=r?r[s]:0;t[s]=h+n}},Filter.prototype._unFilterType3=function(e,t,i){for(var r=this._xComparison,s=r-1,h=this._lastLine,n=0;n<i;n++){var a=e[1+n],l=h?h[n]:0,o=n>s?t[n-r]:0,p=Math.floor((o+l)/2);t[n]=a+p}},Filter.prototype._unFilterType4=function(e,t,i){for(var r=this._xComparison,s=r-1,h=this._lastLine,n=0;n<i;n++){var a=e[1+n],l=h?h[n]:0,o=n>s?t[n-r]:0,p=n>s&&h?h[n-r]:0,d=paethPredictor(o,l,p);t[n]=a+d}},Filter.prototype._reverseFilterLine=function(e){var t,i=e[0],r=this._images[this._imageIndex],s=r.byteWidth;if(0===i)t=e.slice(1,s+1);else switch(t=new Buffer(s),i){case 1:this._unFilterType1(e,t,s);break;case 2:this._unFilterType2(e,t,s);break;case 3:this._unFilterType3(e,t,s);break;case 4:this._unFilterType4(e,t,s);break;default:throw new Error("Unrecognised filter type - "+i)}this.write(t),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=t,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())};
\ No newline at end of file
index 378373f..c5f4400 100644 (file)
@@ -1,89 +1 @@
-'use strict';
-
-function dePalette(indata, outdata, width, height, palette) {
-  var pxPos = 0;
-  // use values from palette
-  for (var y = 0; y < height; y++) {
-    for (var x = 0; x < width; x++) {
-      var color = palette[indata[pxPos]];
-
-      if (!color) {
-        throw new Error('index ' + indata[pxPos] + ' not in palette');
-      }
-
-      for (var i = 0; i < 4; i++) {
-        outdata[pxPos + i] = color[i];
-      }
-      pxPos += 4;
-    }
-  }
-}
-
-function replaceTransparentColor(indata, outdata, width, height, transColor) {
-  var pxPos = 0;
-  for (var y = 0; y < height; y++) {
-    for (var x = 0; x < width; x++) {
-      var makeTrans = false;
-
-      if (transColor.length === 1) {
-        if (transColor[0] === indata[pxPos]) {
-          makeTrans = true;
-        }
-      }
-      else if (transColor[0] === indata[pxPos] && transColor[1] === indata[pxPos + 1] && transColor[2] === indata[pxPos + 2]) {
-        makeTrans = true;
-      }
-      if (makeTrans) {
-        for (var i = 0; i < 4; i++) {
-          outdata[pxPos + i] = 0;
-        }
-      }
-      pxPos += 4;
-    }
-  }
-}
-
-function scaleDepth(indata, outdata, width, height, depth) {
-  var maxOutSample = 255;
-  var maxInSample = Math.pow(2, depth) - 1;
-  var pxPos = 0;
-
-  for (var y = 0; y < height; y++) {
-    for (var x = 0; x < width; x++) {
-      for (var i = 0; i < 4; i++) {
-        outdata[pxPos + i] = Math.floor((indata[pxPos + i] * maxOutSample) / maxInSample + 0.5);
-      }
-      pxPos += 4;
-    }
-  }
-}
-
-module.exports = function(indata, imageData) {
-
-  var depth = imageData.depth;
-  var width = imageData.width;
-  var height = imageData.height;
-  var colorType = imageData.colorType;
-  var transColor = imageData.transColor;
-  var palette = imageData.palette;
-
-  var outdata = indata; // only different for 16 bits
-
-  if (colorType === 3) { // paletted
-    dePalette(indata, outdata, width, height, palette);
-  }
-  else {
-    if (transColor) {
-      replaceTransparentColor(indata, outdata, width, height, transColor);
-    }
-    // if it needs scaling
-    if (depth !== 8) {
-      // if we need to change the buffer size
-      if (depth === 16) {
-        outdata = new Buffer(width * height * 4);
-      }
-      scaleDepth(indata, outdata, width, height, depth);
-    }
-  }
-  return outdata;
-};
+"use strict";function dePalette(r,e,o,t,a){for(var n=0,f=0;f<t;f++)for(var l=0;l<o;l++){var p=a[r[n]];if(!p)throw new Error("index "+r[n]+" not in palette");for(var v=0;v<4;v++)e[n+v]=p[v];n+=4}}function replaceTransparentColor(r,e,o,t,a){for(var n=0,f=0;f<t;f++)for(var l=0;l<o;l++){var p=!1;if(1===a.length?a[0]===r[n]&&(p=!0):a[0]===r[n]&&a[1]===r[n+1]&&a[2]===r[n+2]&&(p=!0),p)for(var v=0;v<4;v++)e[n+v]=0;n+=4}}function scaleDepth(r,e,o,t,a){for(var n=Math.pow(2,a)-1,f=0,l=0;l<t;l++)for(var p=0;p<o;p++){for(var v=0;v<4;v++)e[f+v]=Math.floor(255*r[f+v]/n+.5);f+=4}}module.exports=function(r,e){var o=e.depth,t=e.width,a=e.height,n=e.colorType,f=e.transColor,l=e.palette,p=r;return 3===n?dePalette(r,p,t,a,l):(f&&replaceTransparentColor(r,p,t,a,f),8!==o&&(16===o&&(p=new Buffer(t*a*4)),scaleDepth(r,p,t,a,o))),p};
\ No newline at end of file
index 734ea23..4616ff0 100644 (file)
@@ -1,87 +1 @@
-'use strict';
-
-// Adam 7
-//   0 1 2 3 4 5 6 7
-// 0 x 6 4 6 x 6 4 6
-// 1 7 7 7 7 7 7 7 7
-// 2 5 6 5 6 5 6 5 6
-// 3 7 7 7 7 7 7 7 7
-// 4 3 6 4 6 3 6 4 6
-// 5 7 7 7 7 7 7 7 7
-// 6 5 6 5 6 5 6 5 6
-// 7 7 7 7 7 7 7 7 7
-
-
-var imagePasses = [
-  { // pass 1 - 1px
-    x: [0],
-    y: [0]
-  },
-  { // pass 2 - 1px
-    x: [4],
-    y: [0]
-  },
-  { // pass 3 - 2px
-    x: [0, 4],
-    y: [4]
-  },
-  { // pass 4 - 4px
-    x: [2, 6],
-    y: [0, 4]
-  },
-  { // pass 5 - 8px
-    x: [0, 2, 4, 6],
-    y: [2, 6]
-  },
-  { // pass 6 - 16px
-    x: [1, 3, 5, 7],
-    y: [0, 2, 4, 6]
-  },
-  { // pass 7 - 32px
-    x: [0, 1, 2, 3, 4, 5, 6, 7],
-    y: [1, 3, 5, 7]
-  }
-];
-
-exports.getImagePasses = function(width, height) {
-  var images = [];
-  var xLeftOver = width % 8;
-  var yLeftOver = height % 8;
-  var xRepeats = (width - xLeftOver) / 8;
-  var yRepeats = (height - yLeftOver) / 8;
-  for (var i = 0; i < imagePasses.length; i++) {
-    var pass = imagePasses[i];
-    var passWidth = xRepeats * pass.x.length;
-    var passHeight = yRepeats * pass.y.length;
-    for (var j = 0; j < pass.x.length; j++) {
-      if (pass.x[j] < xLeftOver) {
-        passWidth++;
-      }
-      else {
-        break;
-      }
-    }
-    for (j = 0; j < pass.y.length; j++) {
-      if (pass.y[j] < yLeftOver) {
-        passHeight++;
-      }
-      else {
-        break;
-      }
-    }
-    if (passWidth > 0 && passHeight > 0) {
-      images.push({ width: passWidth, height: passHeight, index: i });
-    }
-  }
-  return images;
-};
-
-exports.getInterlaceIterator = function(width) {
-  return function(x, y, pass) {
-    var outerXLeftOver = x % imagePasses[pass].x.length;
-    var outerX = (((x - outerXLeftOver) / imagePasses[pass].x.length) * 8) + imagePasses[pass].x[outerXLeftOver];
-    var outerYLeftOver = y % imagePasses[pass].y.length;
-    var outerY = (((y - outerYLeftOver) / imagePasses[pass].y.length) * 8) + imagePasses[pass].y[outerYLeftOver];
-    return (outerX * 4) + (outerY * width * 4);
-  };
-};
\ No newline at end of file
+"use strict";var imagePasses=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];exports.getImagePasses=function(e,s){for(var a=[],t=e%8,g=s%8,n=(e-t)/8,r=(s-g)/8,i=0;i<imagePasses.length;i++){for(var x=imagePasses[i],h=n*x.x.length,y=r*x.y.length,l=0;l<x.x.length&&x.x[l]<t;l++)h++;for(l=0;l<x.y.length&&x.y[l]<g;l++)y++;h>0&&y>0&&a.push({width:h,height:y,index:i})}return a},exports.getInterlaceIterator=function(e){return function(s,a,t){var g=s%imagePasses[t].x.length,n=(s-g)/imagePasses[t].x.length*8+imagePasses[t].x[g],r=a%imagePasses[t].y.length;return 4*n+((a-r)/imagePasses[t].y.length*8+imagePasses[t].y[r])*e*4}};
\ No newline at end of file
index 92294c8..b063ca3 100644 (file)
@@ -1,45 +1 @@
-'use strict';
-
-var util = require('util');
-var Stream = require('stream');
-var constants = require('./constants');
-var Packer = require('./packer');
-
-var PackerAsync = module.exports = function(opt) {
-  Stream.call(this);
-
-  var options = opt || {};
-
-  this._packer = new Packer(options);
-  this._deflate = this._packer.createDeflate();
-
-  this.readable = true;
-};
-util.inherits(PackerAsync, Stream);
-
-
-PackerAsync.prototype.pack = function(data, width, height, gamma) {
-  // Signature
-  this.emit('data', new Buffer(constants.PNG_SIGNATURE));
-  this.emit('data', this._packer.packIHDR(width, height));
-
-  if (gamma) {
-    this.emit('data', this._packer.packGAMA(gamma));
-  }
-
-  var filteredData = this._packer.filterData(data, width, height);
-
-  // compress it
-  this._deflate.on('error', this.emit.bind(this, 'error'));
-
-  this._deflate.on('data', function(compressedData) {
-    this.emit('data', this._packer.packIDAT(compressedData));
-  }.bind(this));
-
-  this._deflate.on('end', function() {
-    this.emit('data', this._packer.packIEND());
-    this.emit('end');
-  }.bind(this));
-
-  this._deflate.end(filteredData);
-};
+"use strict";var util=require("util"),Stream=require("stream"),constants=require("./constants"),Packer=require("./packer"),PackerAsync=module.exports=function(t){Stream.call(this);var e=t||{};this._packer=new Packer(e),this._deflate=this._packer.createDeflate(),this.readable=!0};util.inherits(PackerAsync,Stream),PackerAsync.prototype.pack=function(t,e,a,i){this.emit("data",new Buffer(constants.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,a)),i&&this.emit("data",this._packer.packGAMA(i));var r=this._packer.filterData(t,e,a);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(t){this.emit("data",this._packer.packIDAT(t))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(r)};
\ No newline at end of file
index 6129098..97a1fce 100644 (file)
@@ -1,48 +1 @@
-'use strict';
-
-var hasSyncZlib = true;
-var zlib = require('zlib');
-if (!zlib.deflateSync) {
-  hasSyncZlib = false;
-}
-var constants = require('./constants');
-var Packer = require('./packer');
-
-module.exports = function(metaData, opt) {
-
-  if (!hasSyncZlib) {
-    throw new Error('To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0');
-  }
-
-  var options = opt || {};
-
-  var packer = new Packer(options);
-
-  var chunks = [];
-
-  // Signature
-  chunks.push(new Buffer(constants.PNG_SIGNATURE));
-
-  // Header
-  chunks.push(packer.packIHDR(metaData.width, metaData.height));
-
-  if (metaData.gamma) {
-    chunks.push(packer.packGAMA(metaData.gamma));
-  }
-
-  var filteredData = packer.filterData(metaData.data, metaData.width, metaData.height);
-
-  // compress it
-  var compressedData = zlib.deflateSync(filteredData, packer.getDeflateOptions());
-  filteredData = null;
-
-  if (!compressedData || !compressedData.length) {
-    throw new Error('bad png - invalid compressed data response');
-  }
-  chunks.push(packer.packIDAT(compressedData));
-
-  // End
-  chunks.push(packer.packIEND());
-
-  return Buffer.concat(chunks);
-};
+"use strict";var hasSyncZlib=!0,zlib=require("zlib");zlib.deflateSync||(hasSyncZlib=!1);var constants=require("./constants"),Packer=require("./packer");module.exports=function(e,a){if(!hasSyncZlib)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");var r=new Packer(a||{}),t=[];t.push(new Buffer(constants.PNG_SIGNATURE)),t.push(r.packIHDR(e.width,e.height)),e.gamma&&t.push(r.packGAMA(e.gamma));var n=r.filterData(e.data,e.width,e.height),i=zlib.deflateSync(n,r.getDeflateOptions());if(n=null,!i||!i.length)throw new Error("bad png - invalid compressed data response");return t.push(r.packIDAT(i)),t.push(r.packIEND()),Buffer.concat(t)};
\ No newline at end of file
index b3f435d..0820c2c 100644 (file)
@@ -1,107 +1 @@
-'use strict';
-
-var constants = require('./constants');
-var CrcStream = require('./crc');
-var bitPacker = require('./bitpacker');
-var filter = require('./filter-pack');
-var zlib = require('zlib');
-
-var Packer = module.exports = function(options) {
-  this._options = options;
-
-  options.deflateChunkSize = options.deflateChunkSize || 32 * 1024;
-  options.deflateLevel = options.deflateLevel != null ? options.deflateLevel : 9;
-  options.deflateStrategy = options.deflateStrategy != null ? options.deflateStrategy : 3;
-  options.inputHasAlpha = options.inputHasAlpha != null ? options.inputHasAlpha : true;
-  options.deflateFactory = options.deflateFactory || zlib.createDeflate;
-  options.bitDepth = options.bitDepth || 8;
-  // This is outputColorType
-  options.colorType = (typeof options.colorType === 'number') ? options.colorType : constants.COLORTYPE_COLOR_ALPHA;
-  options.inputColorType = (typeof options.inputColorType === 'number') ? options.inputColorType : constants.COLORTYPE_COLOR_ALPHA;
-
-  if ([
-    constants.COLORTYPE_GRAYSCALE,
-    constants.COLORTYPE_COLOR,
-    constants.COLORTYPE_COLOR_ALPHA,
-    constants.COLORTYPE_ALPHA
-  ].indexOf(options.colorType) === -1) {
-    throw new Error('option color type:' + options.colorType + ' is not supported at present');
-  }
-  if ([
-    constants.COLORTYPE_GRAYSCALE,
-    constants.COLORTYPE_COLOR,
-    constants.COLORTYPE_COLOR_ALPHA,
-    constants.COLORTYPE_ALPHA
-  ].indexOf(options.inputColorType) === -1) {
-    throw new Error('option input color type:' + options.inputColorType + ' is not supported at present');
-  }
-  if (options.bitDepth !== 8 && options.bitDepth !== 16) {
-    throw new Error('option bit depth:' + options.bitDepth + ' is not supported at present');
-  }
-};
-
-Packer.prototype.getDeflateOptions = function() {
-  return {
-    chunkSize: this._options.deflateChunkSize,
-    level: this._options.deflateLevel,
-    strategy: this._options.deflateStrategy
-  };
-};
-
-Packer.prototype.createDeflate = function() {
-  return this._options.deflateFactory(this.getDeflateOptions());
-};
-
-Packer.prototype.filterData = function(data, width, height) {
-  // convert to correct format for filtering (e.g. right bpp and bit depth)
-  var packedData = bitPacker(data, width, height, this._options);
-
-  // filter pixel data
-  var bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];
-  var filteredData = filter(packedData, width, height, this._options, bpp);
-  return filteredData;
-};
-
-Packer.prototype._packChunk = function(type, data) {
-
-  var len = (data ? data.length : 0);
-  var buf = new Buffer(len + 12);
-
-  buf.writeUInt32BE(len, 0);
-  buf.writeUInt32BE(type, 4);
-
-  if (data) {
-    data.copy(buf, 8);
-  }
-
-  buf.writeInt32BE(CrcStream.crc32(buf.slice(4, buf.length - 4)), buf.length - 4);
-  return buf;
-};
-
-Packer.prototype.packGAMA = function(gamma) {
-  var buf = new Buffer(4);
-  buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0);
-  return this._packChunk(constants.TYPE_gAMA, buf);
-};
-
-Packer.prototype.packIHDR = function(width, height) {
-
-  var buf = new Buffer(13);
-  buf.writeUInt32BE(width, 0);
-  buf.writeUInt32BE(height, 4);
-  buf[8] = this._options.bitDepth; // Bit depth
-  buf[9] = this._options.colorType; // colorType
-  buf[10] = 0; // compression
-  buf[11] = 0; // filter
-  buf[12] = 0; // interlace
-
-  return this._packChunk(constants.TYPE_IHDR, buf);
-};
-
-Packer.prototype.packIDAT = function(data) {
-  return this._packChunk(constants.TYPE_IDAT, data);
-};
-
-Packer.prototype.packIEND = function() {
-  return this._packChunk(constants.TYPE_IEND, null);
-};
+"use strict";var constants=require("./constants"),CrcStream=require("./crc"),bitPacker=require("./bitpacker"),filter=require("./filter-pack"),zlib=require("zlib"),Packer=module.exports=function(t){if(this._options=t,t.deflateChunkSize=t.deflateChunkSize||32768,t.deflateLevel=null!=t.deflateLevel?t.deflateLevel:9,t.deflateStrategy=null!=t.deflateStrategy?t.deflateStrategy:3,t.inputHasAlpha=null==t.inputHasAlpha||t.inputHasAlpha,t.deflateFactory=t.deflateFactory||zlib.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType="number"==typeof t.colorType?t.colorType:constants.COLORTYPE_COLOR_ALPHA,t.inputColorType="number"==typeof t.inputColorType?t.inputColorType:constants.COLORTYPE_COLOR_ALPHA,-1===[constants.COLORTYPE_GRAYSCALE,constants.COLORTYPE_COLOR,constants.COLORTYPE_COLOR_ALPHA,constants.COLORTYPE_ALPHA].indexOf(t.colorType))throw new Error("option color type:"+t.colorType+" is not supported at present");if(-1===[constants.COLORTYPE_GRAYSCALE,constants.COLORTYPE_COLOR,constants.COLORTYPE_COLOR_ALPHA,constants.COLORTYPE_ALPHA].indexOf(t.inputColorType))throw new Error("option input color type:"+t.inputColorType+" is not supported at present");if(8!==t.bitDepth&&16!==t.bitDepth)throw new Error("option bit depth:"+t.bitDepth+" is not supported at present")};Packer.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}},Packer.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())},Packer.prototype.filterData=function(t,e,n){var o=bitPacker(t,e,n,this._options),r=constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];return filter(o,e,n,this._options,r)},Packer.prototype._packChunk=function(t,e){var n=e?e.length:0,o=new Buffer(n+12);return o.writeUInt32BE(n,0),o.writeUInt32BE(t,4),e&&e.copy(o,8),o.writeInt32BE(CrcStream.crc32(o.slice(4,o.length-4)),o.length-4),o},Packer.prototype.packGAMA=function(t){var e=new Buffer(4);return e.writeUInt32BE(Math.floor(t*constants.GAMMA_DIVISION),0),this._packChunk(constants.TYPE_gAMA,e)},Packer.prototype.packIHDR=function(t,e){var n=new Buffer(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(constants.TYPE_IHDR,n)},Packer.prototype.packIDAT=function(t){return this._packChunk(constants.TYPE_IDAT,t)},Packer.prototype.packIEND=function(){return this._packChunk(constants.TYPE_IEND,null)};
\ No newline at end of file
index 74d254e..e127b41 100644 (file)
@@ -1,17 +1 @@
-'use strict';\r
-\r
-module.exports = function paethPredictor(left, above, upLeft) {\r
-\r
-  var paeth = left + above - upLeft;\r
-  var pLeft = Math.abs(paeth - left);\r
-  var pAbove = Math.abs(paeth - above);\r
-  var pUpLeft = Math.abs(paeth - upLeft);\r
-\r
-  if (pLeft <= pAbove && pLeft <= pUpLeft) {\r
-    return left;\r
-  }\r
-  if (pAbove <= pUpLeft) {\r
-    return above;\r
-  }\r
-  return upLeft;\r
-};
\ No newline at end of file
+"use strict";module.exports=function(t,a,s){var r=t+a-s,e=Math.abs(r-t),u=Math.abs(r-a),b=Math.abs(r-s);return e<=u&&e<=b?t:u<=b?a:s};
\ No newline at end of file
index 9c27353..b5eb6d0 100644 (file)
@@ -1,164 +1 @@
-'use strict';
-
-var util = require('util');
-var zlib = require('zlib');
-var ChunkStream = require('./chunkstream');
-var FilterAsync = require('./filter-parse-async');
-var Parser = require('./parser');
-var bitmapper = require('./bitmapper');
-var formatNormaliser = require('./format-normaliser');
-
-var ParserAsync = module.exports = function(options) {
-  ChunkStream.call(this);
-
-  this._parser = new Parser(options, {
-    read: this.read.bind(this),
-    error: this._handleError.bind(this),
-    metadata: this._handleMetaData.bind(this),
-    gamma: this.emit.bind(this, 'gamma'),
-    palette: this._handlePalette.bind(this),
-    transColor: this._handleTransColor.bind(this),
-    finished: this._finished.bind(this),
-    inflateData: this._inflateData.bind(this),
-    simpleTransparency: this._simpleTransparency.bind(this),
-    headersFinished: this._headersFinished.bind(this)
-  });
-  this._options = options;
-  this.writable = true;
-
-  this._parser.start();
-};
-util.inherits(ParserAsync, ChunkStream);
-
-
-ParserAsync.prototype._handleError = function(err) {
-
-  this.emit('error', err);
-
-  this.writable = false;
-
-  this.destroy();
-
-  if (this._inflate && this._inflate.destroy) {
-    this._inflate.destroy();
-  }
-
-  if (this._filter) {
-    this._filter.destroy();
-    // For backward compatibility with Node 7 and below.
-    // Suppress errors due to _inflate calling write() even after
-    // it's destroy()'ed.
-    this._filter.on('error', function() {});
-  }
-
-  this.errord = true;
-};
-
-ParserAsync.prototype._inflateData = function(data) {
-  if (!this._inflate) {
-    if (this._bitmapInfo.interlace) {
-      this._inflate = zlib.createInflate();
-
-      this._inflate.on('error', this.emit.bind(this, 'error'));
-      this._filter.on('complete', this._complete.bind(this));
-
-      this._inflate.pipe(this._filter);
-    }
-    else {
-      var rowSize = ((this._bitmapInfo.width * this._bitmapInfo.bpp * this._bitmapInfo.depth + 7) >> 3) + 1;
-      var imageSize = rowSize * this._bitmapInfo.height;
-      var chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK);
-
-      this._inflate = zlib.createInflate({ chunkSize: chunkSize });
-      var leftToInflate = imageSize;
-
-      var emitError = this.emit.bind(this, 'error');
-      this._inflate.on('error', function(err) {
-        if (!leftToInflate) {
-          return;
-        }
-
-        emitError(err);
-      });
-      this._filter.on('complete', this._complete.bind(this));
-
-      var filterWrite = this._filter.write.bind(this._filter);
-      this._inflate.on('data', function(chunk) {
-        if (!leftToInflate) {
-          return;
-        }
-
-        if (chunk.length > leftToInflate) {
-          chunk = chunk.slice(0, leftToInflate);
-        }
-
-        leftToInflate -= chunk.length;
-
-        filterWrite(chunk);
-      });
-
-      this._inflate.on('end', this._filter.end.bind(this._filter));
-    }
-  }
-  this._inflate.write(data);
-};
-
-ParserAsync.prototype._handleMetaData = function(metaData) {
-  this._metaData = metaData;
-  this._bitmapInfo = Object.create(metaData);
-
-  this._filter = new FilterAsync(this._bitmapInfo);
-};
-
-ParserAsync.prototype._handleTransColor = function(transColor) {
-  this._bitmapInfo.transColor = transColor;
-};
-
-ParserAsync.prototype._handlePalette = function(palette) {
-  this._bitmapInfo.palette = palette;
-};
-
-ParserAsync.prototype._simpleTransparency = function() {
-  this._metaData.alpha = true;
-};
-
-ParserAsync.prototype._headersFinished = function() {
-  // Up until this point, we don't know if we have a tRNS chunk (alpha)
-  // so we can't emit metadata any earlier
-  this.emit('metadata', this._metaData);
-};
-
-ParserAsync.prototype._finished = function() {
-  if (this.errord) {
-    return;
-  }
-
-  if (!this._inflate) {
-    this.emit('error', 'No Inflate block');
-  }
-  else {
-    // no more data to inflate
-    this._inflate.end();
-  }
-  this.destroySoon();
-};
-
-ParserAsync.prototype._complete = function(filteredData) {
-
-  if (this.errord) {
-    return;
-  }
-
-  try {
-    var bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo);
-
-    var normalisedBitmapData = formatNormaliser(bitmapData, this._bitmapInfo);
-    bitmapData = null;
-  }
-  catch (ex) {
-    this._handleError(ex);
-    return;
-  }
-
-  this.emit('parsed', normalisedBitmapData);
-};
+"use strict";var util=require("util"),zlib=require("zlib"),ChunkStream=require("./chunkstream"),FilterAsync=require("./filter-parse-async"),Parser=require("./parser"),bitmapper=require("./bitmapper"),formatNormaliser=require("./format-normaliser"),ParserAsync=module.exports=function(t){ChunkStream.call(this),this._parser=new Parser(t,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=t,this.writable=!0,this._parser.start()};util.inherits(ParserAsync,ChunkStream),ParserAsync.prototype._handleError=function(t){this.emit("error",t),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on("error",(function(){}))),this.errord=!0},ParserAsync.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=zlib.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{var i=(1+(this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3))*this._bitmapInfo.height,e=Math.max(i,zlib.Z_MIN_CHUNK);this._inflate=zlib.createInflate({chunkSize:e});var r=i,s=this.emit.bind(this,"error");this._inflate.on("error",(function(t){r&&s(t)})),this._filter.on("complete",this._complete.bind(this));var a=this._filter.write.bind(this._filter);this._inflate.on("data",(function(t){r&&(t.length>r&&(t=t.slice(0,r)),r-=t.length,a(t))})),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)},ParserAsync.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new FilterAsync(this._bitmapInfo)},ParserAsync.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t},ParserAsync.prototype._handlePalette=function(t){this._bitmapInfo.palette=t},ParserAsync.prototype._simpleTransparency=function(){this._metaData.alpha=!0},ParserAsync.prototype._headersFinished=function(){this.emit("metadata",this._metaData)},ParserAsync.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"),this.destroySoon())},ParserAsync.prototype._complete=function(t){if(!this.errord){try{var i=bitmapper.dataToBitMap(t,this._bitmapInfo),e=formatNormaliser(i,this._bitmapInfo);i=null}catch(t){return void this._handleError(t)}this.emit("parsed",e)}};
\ No newline at end of file
index ed899a4..7fe92cf 100644 (file)
@@ -1,105 +1 @@
-'use strict';
-
-var hasSyncZlib = true;
-var zlib = require('zlib');
-var inflateSync = require('./sync-inflate');
-if (!zlib.deflateSync) {
-  hasSyncZlib = false;
-}
-var SyncReader = require('./sync-reader');
-var FilterSync = require('./filter-parse-sync');
-var Parser = require('./parser');
-var bitmapper = require('./bitmapper');
-var formatNormaliser = require('./format-normaliser');
-
-
-module.exports = function(buffer, options) {
-
-  if (!hasSyncZlib) {
-    throw new Error('To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0');
-  }
-
-  var err;
-  function handleError(_err_) {
-    err = _err_;
-  }
-
-  var metaData;
-  function handleMetaData(_metaData_) {
-    metaData = _metaData_;
-  }
-
-  function handleTransColor(transColor) {
-    metaData.transColor = transColor;
-  }
-
-  function handlePalette(palette) {
-    metaData.palette = palette;
-  }
-
-  function handleSimpleTransparency() {
-    metaData.alpha = true;
-  }
-
-  var gamma;
-  function handleGamma(_gamma_) {
-    gamma = _gamma_;
-  }
-
-  var inflateDataList = [];
-  function handleInflateData(inflatedData) {
-    inflateDataList.push(inflatedData);
-  }
-
-  var reader = new SyncReader(buffer);
-
-  var parser = new Parser(options, {
-    read: reader.read.bind(reader),
-    error: handleError,
-    metadata: handleMetaData,
-    gamma: handleGamma,
-    palette: handlePalette,
-    transColor: handleTransColor,
-    inflateData: handleInflateData,
-    simpleTransparency: handleSimpleTransparency
-  });
-
-  parser.start();
-  reader.process();
-
-  if (err) {
-    throw err;
-  }
-
-  //join together the inflate datas
-  var inflateData = Buffer.concat(inflateDataList);
-  inflateDataList.length = 0;
-
-  var inflatedData;
-  if (metaData.interlace) {
-    inflatedData = zlib.inflateSync(inflateData);
-  }
-  else {
-    var rowSize = ((metaData.width * metaData.bpp * metaData.depth + 7) >> 3) + 1;
-    var imageSize = rowSize * metaData.height;
-    inflatedData = inflateSync(inflateData, { chunkSize: imageSize, maxLength: imageSize });
-  }
-  inflateData = null;
-
-  if (!inflatedData || !inflatedData.length) {
-    throw new Error('bad png - invalid inflate data response');
-  }
-
-  var unfilteredData = FilterSync.process(inflatedData, metaData);
-  inflateData = null;
-
-  var bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData);
-  unfilteredData = null;
-
-  var normalisedBitmapData = formatNormaliser(bitmapData, metaData);
-
-  metaData.data = normalisedBitmapData;
-  metaData.gamma = gamma || 0;
-
-  return metaData;
-};
+"use strict";var hasSyncZlib=!0,zlib=require("zlib"),inflateSync=require("./sync-inflate");zlib.deflateSync||(hasSyncZlib=!1);var SyncReader=require("./sync-reader"),FilterSync=require("./filter-parse-sync"),Parser=require("./parser"),bitmapper=require("./bitmapper"),formatNormaliser=require("./format-normaliser");module.exports=function(r,e){if(!hasSyncZlib)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");var a,n,i;var t=[];var l=new SyncReader(r);if(new Parser(e,{read:l.read.bind(l),error:function(r){a=r},metadata:function(r){n=r},gamma:function(r){i=r},palette:function(r){n.palette=r},transColor:function(r){n.transColor=r},inflateData:function(r){t.push(r)},simpleTransparency:function(){n.alpha=!0}}).start(),l.process(),a)throw a;var o,s=Buffer.concat(t);if(t.length=0,n.interlace)o=zlib.inflateSync(s);else{var c=(1+(n.width*n.bpp*n.depth+7>>3))*n.height;o=inflateSync(s,{chunkSize:c,maxLength:c})}if(s=null,!o||!o.length)throw new Error("bad png - invalid inflate data response");var p=FilterSync.process(o,n);s=null;var f=bitmapper.dataToBitMap(p,n);p=null;var u=formatNormaliser(f,n);return n.data=u,n.gamma=i||0,n};
\ No newline at end of file
index 9724443..737076f 100644 (file)
@@ -1,297 +1 @@
-'use strict';
-
-var constants = require('./constants');
-var CrcCalculator = require('./crc');
-
-
-var Parser = module.exports = function(options, dependencies) {
-
-  this._options = options;
-  options.checkCRC = options.checkCRC !== false;
-
-  this._hasIHDR = false;
-  this._hasIEND = false;
-  this._emittedHeadersFinished = false;
-
-  // input flags/metadata
-  this._palette = [];
-  this._colorType = 0;
-
-  this._chunks = {};
-  this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this);
-  this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this);
-  this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this);
-  this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this);
-  this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this);
-  this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this);
-
-  this.read = dependencies.read;
-  this.error = dependencies.error;
-  this.metadata = dependencies.metadata;
-  this.gamma = dependencies.gamma;
-  this.transColor = dependencies.transColor;
-  this.palette = dependencies.palette;
-  this.parsed = dependencies.parsed;
-  this.inflateData = dependencies.inflateData;
-  this.finished = dependencies.finished;
-  this.simpleTransparency = dependencies.simpleTransparency;
-  this.headersFinished = dependencies.headersFinished || function() {};
-};
-
-Parser.prototype.start = function() {
-  this.read(constants.PNG_SIGNATURE.length,
-    this._parseSignature.bind(this)
-  );
-};
-
-Parser.prototype._parseSignature = function(data) {
-
-  var signature = constants.PNG_SIGNATURE;
-
-  for (var i = 0; i < signature.length; i++) {
-    if (data[i] !== signature[i]) {
-      this.error(new Error('Invalid file signature'));
-      return;
-    }
-  }
-  this.read(8, this._parseChunkBegin.bind(this));
-};
-
-Parser.prototype._parseChunkBegin = function(data) {
-
-  // chunk content length
-  var length = data.readUInt32BE(0);
-
-  // chunk type
-  var type = data.readUInt32BE(4);
-  var name = '';
-  for (var i = 4; i < 8; i++) {
-    name += String.fromCharCode(data[i]);
-  }
-
-  //console.log('chunk ', name, length);
-
-  // chunk flags
-  var ancillary = Boolean(data[4] & 0x20); // or critical
-  //    priv = Boolean(data[5] & 0x20), // or public
-  //    safeToCopy = Boolean(data[7] & 0x20); // or unsafe
-
-  if (!this._hasIHDR && type !== constants.TYPE_IHDR) {
-    this.error(new Error('Expected IHDR on beggining'));
-    return;
-  }
-
-  this._crc = new CrcCalculator();
-  this._crc.write(new Buffer(name));
-
-  if (this._chunks[type]) {
-    return this._chunks[type](length);
-  }
-
-  if (!ancillary) {
-    this.error(new Error('Unsupported critical chunk type ' + name));
-    return;
-  }
-
-  this.read(length + 4, this._skipChunk.bind(this));
-};
-
-Parser.prototype._skipChunk = function(/*data*/) {
-  this.read(8, this._parseChunkBegin.bind(this));
-};
-
-Parser.prototype._handleChunkEnd = function() {
-  this.read(4, this._parseChunkEnd.bind(this));
-};
-
-Parser.prototype._parseChunkEnd = function(data) {
-
-  var fileCrc = data.readInt32BE(0);
-  var calcCrc = this._crc.crc32();
-
-  // check CRC
-  if (this._options.checkCRC && calcCrc !== fileCrc) {
-    this.error(new Error('Crc error - ' + fileCrc + ' - ' + calcCrc));
-    return;
-  }
-
-  if (!this._hasIEND) {
-    this.read(8, this._parseChunkBegin.bind(this));
-  }
-};
-
-Parser.prototype._handleIHDR = function(length) {
-  this.read(length, this._parseIHDR.bind(this));
-};
-Parser.prototype._parseIHDR = function(data) {
-
-  this._crc.write(data);
-
-  var width = data.readUInt32BE(0);
-  var height = data.readUInt32BE(4);
-  var depth = data[8];
-  var colorType = data[9]; // bits: 1 palette, 2 color, 4 alpha
-  var compr = data[10];
-  var filter = data[11];
-  var interlace = data[12];
-
-  // console.log('    width', width, 'height', height,
-  //     'depth', depth, 'colorType', colorType,
-  //     'compr', compr, 'filter', filter, 'interlace', interlace
-  // );
-
-  if (depth !== 8 && depth !== 4 && depth !== 2 && depth !== 1 && depth !== 16) {
-    this.error(new Error('Unsupported bit depth ' + depth));
-    return;
-  }
-  if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) {
-    this.error(new Error('Unsupported color type'));
-    return;
-  }
-  if (compr !== 0) {
-    this.error(new Error('Unsupported compression method'));
-    return;
-  }
-  if (filter !== 0) {
-    this.error(new Error('Unsupported filter method'));
-    return;
-  }
-  if (interlace !== 0 && interlace !== 1) {
-    this.error(new Error('Unsupported interlace method'));
-    return;
-  }
-
-  this._colorType = colorType;
-
-  var bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType];
-
-  this._hasIHDR = true;
-
-  this.metadata({
-    width: width,
-    height: height,
-    depth: depth,
-    interlace: Boolean(interlace),
-    palette: Boolean(colorType & constants.COLORTYPE_PALETTE),
-    color: Boolean(colorType & constants.COLORTYPE_COLOR),
-    alpha: Boolean(colorType & constants.COLORTYPE_ALPHA),
-    bpp: bpp,
-    colorType: colorType
-  });
-
-  this._handleChunkEnd();
-};
-
-
-Parser.prototype._handlePLTE = function(length) {
-  this.read(length, this._parsePLTE.bind(this));
-};
-Parser.prototype._parsePLTE = function(data) {
-
-  this._crc.write(data);
-
-  var entries = Math.floor(data.length / 3);
-  // console.log('Palette:', entries);
-
-  for (var i = 0; i < entries; i++) {
-    this._palette.push([
-      data[i * 3],
-      data[i * 3 + 1],
-      data[i * 3 + 2],
-      0xff
-    ]);
-  }
-
-  this.palette(this._palette);
-
-  this._handleChunkEnd();
-};
-
-Parser.prototype._handleTRNS = function(length) {
-  this.simpleTransparency();
-  this.read(length, this._parseTRNS.bind(this));
-};
-Parser.prototype._parseTRNS = function(data) {
-
-  this._crc.write(data);
-
-  // palette
-  if (this._colorType === constants.COLORTYPE_PALETTE_COLOR) {
-    if (this._palette.length === 0) {
-      this.error(new Error('Transparency chunk must be after palette'));
-      return;
-    }
-    if (data.length > this._palette.length) {
-      this.error(new Error('More transparent colors than palette size'));
-      return;
-    }
-    for (var i = 0; i < data.length; i++) {
-      this._palette[i][3] = data[i];
-    }
-    this.palette(this._palette);
-  }
-
-  // for colorType 0 (grayscale) and 2 (rgb)
-  // there might be one gray/color defined as transparent
-  if (this._colorType === constants.COLORTYPE_GRAYSCALE) {
-    // grey, 2 bytes
-    this.transColor([data.readUInt16BE(0)]);
-  }
-  if (this._colorType === constants.COLORTYPE_COLOR) {
-    this.transColor([data.readUInt16BE(0), data.readUInt16BE(2), data.readUInt16BE(4)]);
-  }
-
-  this._handleChunkEnd();
-};
-
-Parser.prototype._handleGAMA = function(length) {
-  this.read(length, this._parseGAMA.bind(this));
-};
-Parser.prototype._parseGAMA = function(data) {
-
-  this._crc.write(data);
-  this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION);
-
-  this._handleChunkEnd();
-};
-
-Parser.prototype._handleIDAT = function(length) {
-  if (!this._emittedHeadersFinished) {
-    this._emittedHeadersFinished = true;
-    this.headersFinished();
-  }
-  this.read(-length, this._parseIDAT.bind(this, length));
-};
-Parser.prototype._parseIDAT = function(length, data) {
-
-  this._crc.write(data);
-
-  if (this._colorType === constants.COLORTYPE_PALETTE_COLOR && this._palette.length === 0) {
-    throw new Error('Expected palette not found');
-  }
-
-  this.inflateData(data);
-  var leftOverLength = length - data.length;
-
-  if (leftOverLength > 0) {
-    this._handleIDAT(leftOverLength);
-  }
-  else {
-    this._handleChunkEnd();
-  }
-};
-
-Parser.prototype._handleIEND = function(length) {
-  this.read(length, this._parseIEND.bind(this));
-};
-Parser.prototype._parseIEND = function(data) {
-
-  this._crc.write(data);
-
-  this._hasIEND = true;
-  this._handleChunkEnd();
-
-  if (this.finished) {
-    this.finished();
-  }
-};
+"use strict";var constants=require("./constants"),CrcCalculator=require("./crc"),Parser=module.exports=function(t,e){this._options=t,t.checkCRC=!1!==t.checkCRC,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[constants.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[constants.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[constants.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[constants.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[constants.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[constants.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=e.read,this.error=e.error,this.metadata=e.metadata,this.gamma=e.gamma,this.transColor=e.transColor,this.palette=e.palette,this.parsed=e.parsed,this.inflateData=e.inflateData,this.finished=e.finished,this.simpleTransparency=e.simpleTransparency,this.headersFinished=e.headersFinished||function(){}};Parser.prototype.start=function(){this.read(constants.PNG_SIGNATURE.length,this._parseSignature.bind(this))},Parser.prototype._parseSignature=function(t){for(var e=constants.PNG_SIGNATURE,r=0;r<e.length;r++)if(t[r]!==e[r])return void this.error(new Error("Invalid file signature"));this.read(8,this._parseChunkBegin.bind(this))},Parser.prototype._parseChunkBegin=function(t){for(var e=t.readUInt32BE(0),r=t.readUInt32BE(4),s="",i=4;i<8;i++)s+=String.fromCharCode(t[i]);var n=Boolean(32&t[4]);if(this._hasIHDR||r===constants.TYPE_IHDR){if(this._crc=new CrcCalculator,this._crc.write(new Buffer(s)),this._chunks[r])return this._chunks[r](e);n?this.read(e+4,this._skipChunk.bind(this)):this.error(new Error("Unsupported critical chunk type "+s))}else this.error(new Error("Expected IHDR on beggining"))},Parser.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))},Parser.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))},Parser.prototype._parseChunkEnd=function(t){var e=t.readInt32BE(0),r=this._crc.crc32();this._options.checkCRC&&r!==e?this.error(new Error("Crc error - "+e+" - "+r)):this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))},Parser.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))},Parser.prototype._parseIHDR=function(t){this._crc.write(t);var e=t.readUInt32BE(0),r=t.readUInt32BE(4),s=t[8],i=t[9],n=t[10],h=t[11],a=t[12];if(8===s||4===s||2===s||1===s||16===s)if(i in constants.COLORTYPE_TO_BPP_MAP)if(0===n)if(0===h)if(0===a||1===a){this._colorType=i;var o=constants.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:r,depth:s,interlace:Boolean(a),palette:Boolean(i&constants.COLORTYPE_PALETTE),color:Boolean(i&constants.COLORTYPE_COLOR),alpha:Boolean(i&constants.COLORTYPE_ALPHA),bpp:o,colorType:i}),this._handleChunkEnd()}else this.error(new Error("Unsupported interlace method"));else this.error(new Error("Unsupported filter method"));else this.error(new Error("Unsupported compression method"));else this.error(new Error("Unsupported color type"));else this.error(new Error("Unsupported bit depth "+s))},Parser.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))},Parser.prototype._parsePLTE=function(t){this._crc.write(t);for(var e=Math.floor(t.length/3),r=0;r<e;r++)this._palette.push([t[3*r],t[3*r+1],t[3*r+2],255]);this.palette(this._palette),this._handleChunkEnd()},Parser.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))},Parser.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===constants.COLORTYPE_PALETTE_COLOR){if(0===this._palette.length)return void this.error(new Error("Transparency chunk must be after palette"));if(t.length>this._palette.length)return void this.error(new Error("More transparent colors than palette size"));for(var e=0;e<t.length;e++)this._palette[e][3]=t[e];this.palette(this._palette)}this._colorType===constants.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===constants.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()},Parser.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))},Parser.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/constants.GAMMA_DIVISION),this._handleChunkEnd()},Parser.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))},Parser.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===constants.COLORTYPE_PALETTE_COLOR&&0===this._palette.length)throw new Error("Expected palette not found");this.inflateData(e);var r=t-e.length;r>0?this._handleIDAT(r):this._handleChunkEnd()},Parser.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))},Parser.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()};
\ No newline at end of file
index 81d04a4..b8c0676 100644 (file)
@@ -1,16 +1 @@
-'use strict';
-
-
-var parse = require('./parser-sync');
-var pack = require('./packer-sync');
-
-
-exports.read = function(buffer, options) {
-
-  return parse(buffer, options || {});
-};
-
-exports.write = function(png, options) {
-
-  return pack(png, options);
-};
+"use strict";var parse=require("./parser-sync"),pack=require("./packer-sync");exports.read=function(r,e){return parse(r,e||{})},exports.write=function(r,e){return pack(r,e)};
\ No newline at end of file
index 1e407a7..8514902 100644 (file)
@@ -1,173 +1 @@
-'use strict';
-
-var util = require('util');
-var Stream = require('stream');
-var Parser = require('./parser-async');
-var Packer = require('./packer-async');
-var PNGSync = require('./png-sync');
-
-
-var PNG = exports.PNG = function(options) {
-  Stream.call(this);
-
-  options = options || {}; // eslint-disable-line no-param-reassign
-
-  // coerce pixel dimensions to integers (also coerces undefined -> 0):
-  this.width = options.width | 0;
-  this.height = options.height | 0;
-
-  this.data = this.width > 0 && this.height > 0 ?
-    new Buffer(4 * this.width * this.height) : null;
-
-  if (options.fill && this.data) {
-    this.data.fill(0);
-  }
-
-  this.gamma = 0;
-  this.readable = this.writable = true;
-
-  this._parser = new Parser(options);
-
-  this._parser.on('error', this.emit.bind(this, 'error'));
-  this._parser.on('close', this._handleClose.bind(this));
-  this._parser.on('metadata', this._metadata.bind(this));
-  this._parser.on('gamma', this._gamma.bind(this));
-  this._parser.on('parsed', function(data) {
-    this.data = data;
-    this.emit('parsed', data);
-  }.bind(this));
-
-  this._packer = new Packer(options);
-  this._packer.on('data', this.emit.bind(this, 'data'));
-  this._packer.on('end', this.emit.bind(this, 'end'));
-  this._parser.on('close', this._handleClose.bind(this));
-  this._packer.on('error', this.emit.bind(this, 'error'));
-
-};
-util.inherits(PNG, Stream);
-
-PNG.sync = PNGSync;
-
-PNG.prototype.pack = function() {
-
-  if (!this.data || !this.data.length) {
-    this.emit('error', 'No data provided');
-    return this;
-  }
-
-  process.nextTick(function() {
-    this._packer.pack(this.data, this.width, this.height, this.gamma);
-  }.bind(this));
-
-  return this;
-};
-
-
-PNG.prototype.parse = function(data, callback) {
-
-  if (callback) {
-    var onParsed, onError;
-
-    onParsed = function(parsedData) {
-      this.removeListener('error', onError);
-
-      this.data = parsedData;
-      callback(null, this);
-    }.bind(this);
-
-    onError = function(err) {
-      this.removeListener('parsed', onParsed);
-
-      callback(err, null);
-    }.bind(this);
-
-    this.once('parsed', onParsed);
-    this.once('error', onError);
-  }
-
-  this.end(data);
-  return this;
-};
-
-PNG.prototype.write = function(data) {
-  this._parser.write(data);
-  return true;
-};
-
-PNG.prototype.end = function(data) {
-  this._parser.end(data);
-};
-
-PNG.prototype._metadata = function(metadata) {
-  this.width = metadata.width;
-  this.height = metadata.height;
-
-  this.emit('metadata', metadata);
-};
-
-PNG.prototype._gamma = function(gamma) {
-  this.gamma = gamma;
-};
-
-PNG.prototype._handleClose = function() {
-  if (!this._parser.writable && !this._packer.readable) {
-    this.emit('close');
-  }
-};
-
-
-PNG.bitblt = function(src, dst, srcX, srcY, width, height, deltaX, deltaY) { // eslint-disable-line max-params
-  // coerce pixel dimensions to integers (also coerces undefined -> 0):
-  /* eslint-disable no-param-reassign */
-  srcX |= 0;
-  srcY |= 0;
-  width |= 0;
-  height |= 0;
-  deltaX |= 0;
-  deltaY |= 0;
-  /* eslint-enable no-param-reassign */
-
-  if (srcX > src.width || srcY > src.height || srcX + width > src.width || srcY + height > src.height) {
-    throw new Error('bitblt reading outside image');
-  }
-
-  if (deltaX > dst.width || deltaY > dst.height || deltaX + width > dst.width || deltaY + height > dst.height) {
-    throw new Error('bitblt writing outside image');
-  }
-
-  for (var y = 0; y < height; y++) {
-    src.data.copy(dst.data,
-      ((deltaY + y) * dst.width + deltaX) << 2,
-      ((srcY + y) * src.width + srcX) << 2,
-      ((srcY + y) * src.width + srcX + width) << 2
-    );
-  }
-};
-
-
-PNG.prototype.bitblt = function(dst, srcX, srcY, width, height, deltaX, deltaY) { // eslint-disable-line max-params
-
-  PNG.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY);
-  return this;
-};
-
-PNG.adjustGamma = function(src) {
-  if (src.gamma) {
-    for (var y = 0; y < src.height; y++) {
-      for (var x = 0; x < src.width; x++) {
-        var idx = (src.width * y + x) << 2;
-
-        for (var i = 0; i < 3; i++) {
-          var sample = src.data[idx + i] / 255;
-          sample = Math.pow(sample, 1 / 2.2 / src.gamma);
-          src.data[idx + i] = Math.round(sample * 255);
-        }
-      }
-    }
-    src.gamma = 0;
-  }
-};
-
-PNG.prototype.adjustGamma = function() {
-  PNG.adjustGamma(this);
-};
+"use strict";var util=require("util"),Stream=require("stream"),Parser=require("./parser-async"),Packer=require("./packer-async"),PNGSync=require("./png-sync"),PNG=exports.PNG=function(t){Stream.call(this),t=t||{},this.width=0|t.width,this.height=0|t.height,this.data=this.width>0&&this.height>0?new Buffer(4*this.width*this.height):null,t.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new Parser(t),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(t){this.data=t,this.emit("parsed",t)}.bind(this)),this._packer=new Packer(t),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};util.inherits(PNG,Stream),PNG.sync=PNGSync,PNG.prototype.pack=function(){return this.data&&this.data.length?(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this):(this.emit("error","No data provided"),this)},PNG.prototype.parse=function(t,i){var e,r;i&&(e=function(t){this.removeListener("error",r),this.data=t,i(null,this)}.bind(this),r=function(t){this.removeListener("parsed",e),i(t,null)}.bind(this),this.once("parsed",e),this.once("error",r));return this.end(t),this},PNG.prototype.write=function(t){return this._parser.write(t),!0},PNG.prototype.end=function(t){this._parser.end(t)},PNG.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)},PNG.prototype._gamma=function(t){this.gamma=t},PNG.prototype._handleClose=function(){this._parser.writable||this._packer.readable||this.emit("close")},PNG.bitblt=function(t,i,e,r,a,h,s,n){if(r|=0,a|=0,h|=0,s|=0,n|=0,(e|=0)>t.width||r>t.height||e+a>t.width||r+h>t.height)throw new Error("bitblt reading outside image");if(s>i.width||n>i.height||s+a>i.width||n+h>i.height)throw new Error("bitblt writing outside image");for(var o=0;o<h;o++)t.data.copy(i.data,(n+o)*i.width+s<<2,(r+o)*t.width+e<<2,(r+o)*t.width+e+a<<2)},PNG.prototype.bitblt=function(t,i,e,r,a,h,s){return PNG.bitblt(this,t,i,e,r,a,h,s),this},PNG.adjustGamma=function(t){if(t.gamma){for(var i=0;i<t.height;i++)for(var e=0;e<t.width;e++)for(var r=t.width*i+e<<2,a=0;a<3;a++){var h=t.data[r+a]/255;h=Math.pow(h,1/2.2/t.gamma),t.data[r+a]=Math.round(255*h)}t.gamma=0}},PNG.prototype.adjustGamma=function(){PNG.adjustGamma(this)};
\ No newline at end of file
index 87c19a1..3e9d2a6 100644 (file)
@@ -1,161 +1 @@
-'use strict';
-
-var assert = require('assert').ok;
-var zlib = require('zlib');
-var util = require('util');
-
-var kMaxLength = require('buffer').kMaxLength;
-
-function Inflate(opts) {
-  if (!(this instanceof Inflate)) {
-    return new Inflate(opts);
-  }
-
-  if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) {
-    opts.chunkSize = zlib.Z_MIN_CHUNK;
-  }
-
-  zlib.Inflate.call(this, opts);
-
-  // Node 8 --> 9 compatibility check
-  this._offset = this._offset === undefined ? this._outOffset : this._offset;
-  this._buffer = this._buffer || this._outBuffer;
-
-  if (opts && opts.maxLength != null) {
-    this._maxLength = opts.maxLength;
-  }
-}
-
-function createInflate(opts) {
-  return new Inflate(opts);
-}
-
-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;
-}
-
-Inflate.prototype._processChunk = function(chunk, flushFlag, asyncCb) {
-  if (typeof asyncCb === 'function') {
-    return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb);
-  }
-
-  var self = this;
-
-  var availInBefore = chunk && chunk.length;
-  var availOutBefore = this._chunkSize - this._offset;
-  var leftToInflate = this._maxLength;
-  var inOff = 0;
-
-  var buffers = [];
-  var nread = 0;
-
-  var error;
-  this.on('error', function(err) {
-    error = err;
-  });
-
-  function handleChunk(availInAfter, availOutAfter) {
-    if (self._hadError) {
-      return;
-    }
-
-    var have = availOutBefore - availOutAfter;
-    assert(have >= 0, 'have should not go down');
-
-    if (have > 0) {
-      var out = self._buffer.slice(self._offset, self._offset + have);
-      self._offset += have;
-
-      if (out.length > leftToInflate) {
-        out = out.slice(0, leftToInflate);
-      }
-
-      buffers.push(out);
-      nread += out.length;
-      leftToInflate -= out.length;
-
-      if (leftToInflate === 0) {
-        return false;
-      }
-    }
-
-    if (availOutAfter === 0 || self._offset >= self._chunkSize) {
-      availOutBefore = self._chunkSize;
-      self._offset = 0;
-      self._buffer = Buffer.allocUnsafe(self._chunkSize);
-    }
-
-    if (availOutAfter === 0) {
-      inOff += (availInBefore - availInAfter);
-      availInBefore = availInAfter;
-
-      return true;
-    }
-
-    return false;
-  }
-
-  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
-    // Node 8 --> 9 compatibility check
-    res = res || this._writeState;
-  } while (!this._hadError && handleChunk(res[0], res[1]));
-
-  if (this._hadError) {
-    throw error;
-  }
-
-  if (nread >= kMaxLength) {
-    _close(this);
-    throw new RangeError('Cannot create final Buffer. It would be larger than 0x' + kMaxLength.toString(16) + ' bytes');
-  }
-
-  var buf = Buffer.concat(buffers, nread);
-  _close(this);
-
-  return buf;
-};
-
-util.inherits(Inflate, zlib.Inflate);
-
-function zlibBufferSync(engine, buffer) {
-  if (typeof buffer === 'string') {
-    buffer = Buffer.from(buffer);
-  }
-  if (!(buffer instanceof Buffer)) {
-    throw new TypeError('Not a string or buffer');
-  }
-
-  var flushFlag = engine._finishFlushFlag;
-  if (flushFlag == null) {
-    flushFlag = zlib.Z_FINISH;
-  }
-
-  return engine._processChunk(buffer, flushFlag);
-}
-
-function inflateSync(buffer, opts) {
-  return zlibBufferSync(new Inflate(opts), buffer);
-}
-
-module.exports = exports = inflateSync;
-exports.Inflate = Inflate;
-exports.createInflate = createInflate;
-exports.inflateSync = inflateSync;
+"use strict";var assert=require("assert").ok,zlib=require("zlib"),util=require("util"),kMaxLength=require("buffer").kMaxLength;function Inflate(e){if(!(this instanceof Inflate))return new Inflate(e);e&&e.chunkSize<zlib.Z_MIN_CHUNK&&(e.chunkSize=zlib.Z_MIN_CHUNK),zlib.Inflate.call(this,e),this._offset=void 0===this._offset?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,e&&null!=e.maxLength&&(this._maxLength=e.maxLength)}function createInflate(e){return new Inflate(e)}function _close(e,t){t&&process.nextTick(t),e._handle&&(e._handle.close(),e._handle=null)}function zlibBufferSync(e,t){if("string"==typeof t&&(t=Buffer.from(t)),!(t instanceof Buffer))throw new TypeError("Not a string or buffer");var n=e._finishFlushFlag;return null==n&&(n=zlib.Z_FINISH),e._processChunk(t,n)}function inflateSync(e,t){return zlibBufferSync(new Inflate(t),e)}Inflate.prototype._processChunk=function(e,t,n){if("function"==typeof n)return zlib.Inflate._processChunk.call(this,e,t,n);var f,r=this,i=e&&e.length,s=this._chunkSize-this._offset,l=this._maxLength,o=0,a=[],h=0;function u(e,t){if(!r._hadError){var n=s-t;if(assert(n>=0,"have should not go down"),n>0){var f=r._buffer.slice(r._offset,r._offset+n);if(r._offset+=n,f.length>l&&(f=f.slice(0,l)),a.push(f),h+=f.length,0===(l-=f.length))return!1}return(0===t||r._offset>=r._chunkSize)&&(s=r._chunkSize,r._offset=0,r._buffer=Buffer.allocUnsafe(r._chunkSize)),0===t&&(o+=i-e,i=e,!0)}}this.on("error",(function(e){f=e})),assert(this._handle,"zlib binding closed");do{var c=this._handle.writeSync(t,e,o,i,this._buffer,this._offset,s);c=c||this._writeState}while(!this._hadError&&u(c[0],c[1]));if(this._hadError)throw f;if(h>=kMaxLength)throw _close(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+kMaxLength.toString(16)+" bytes");var _=Buffer.concat(a,h);return _close(this),_},util.inherits(Inflate,zlib.Inflate),module.exports=exports=inflateSync,exports.Inflate=Inflate,exports.createInflate=createInflate,exports.inflateSync=inflateSync;
\ No newline at end of file
index 70ee2db..7234260 100644 (file)
@@ -1,51 +1 @@
-'use strict';
-
-var SyncReader = module.exports = function(buffer) {
-
-  this._buffer = buffer;
-  this._reads = [];
-};
-
-SyncReader.prototype.read = function(length, callback) {
-
-  this._reads.push({
-    length: Math.abs(length), // if length < 0 then at most this length
-    allowLess: length < 0,
-    func: callback
-  });
-};
-
-SyncReader.prototype.process = function() {
-
-  // as long as there is any data and read requests
-  while (this._reads.length > 0 && this._buffer.length) {
-
-    var read = this._reads[0];
-
-    if (this._buffer.length && (this._buffer.length >= read.length || read.allowLess)) {
-
-      // ok there is any data so that we can satisfy this request
-      this._reads.shift(); // == read
-
-      var buf = this._buffer;
-
-      this._buffer = buf.slice(read.length);
-
-      read.func.call(this, buf.slice(0, read.length));
-
-    }
-    else {
-      break;
-    }
-
-  }
-
-  if (this._reads.length > 0) {
-    return new Error('There are some read requests waitng on finished stream');
-  }
-
-  if (this._buffer.length > 0) {
-    return new Error('unrecognised content at end of stream');
-  }
-
-};
+"use strict";var SyncReader=module.exports=function(e){this._buffer=e,this._reads=[]};SyncReader.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t})},SyncReader.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){var e=this._reads[0];if(!this._buffer.length||!(this._buffer.length>=e.length||e.allowLess))break;this._reads.shift();var t=this._buffer;this._buffer=t.slice(e.length),e.func.call(this,t.slice(0,e.length))}return this._reads.length>0?new Error("There are some read requests waitng on finished stream"):this._buffer.length>0?new Error("unrecognised content at end of stream"):void 0};
\ No newline at end of file
index a909b05..47fa4cc 100644 (file)
@@ -3,325 +3,4 @@
  * Copyright(c) 2014-2016 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = proxyaddr
-module.exports.all = alladdrs
-module.exports.compile = compile
-
-/**
- * Module dependencies.
- * @private
- */
-
-var forwarded = require('forwarded')
-var ipaddr = require('ipaddr.js')
-
-/**
- * Variables.
- * @private
- */
-
-var DIGIT_REGEXP = /^[0-9]+$/
-var isip = ipaddr.isValid
-var parseip = ipaddr.parse
-
-/**
- * Pre-defined IP ranges.
- * @private
- */
-
-var IP_RANGES = {
-  linklocal: ['169.254.0.0/16', 'fe80::/10'],
-  loopback: ['127.0.0.1/8', '::1/128'],
-  uniquelocal: ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', 'fc00::/7']
-}
-
-/**
- * Get all addresses in the request, optionally stopping
- * at the first untrusted.
- *
- * @param {Object} request
- * @param {Function|Array|String} [trust]
- * @public
- */
-
-function alladdrs (req, trust) {
-  // get addresses
-  var addrs = forwarded(req)
-
-  if (!trust) {
-    // Return all addresses
-    return addrs
-  }
-
-  if (typeof trust !== 'function') {
-    trust = compile(trust)
-  }
-
-  for (var i = 0; i < addrs.length - 1; i++) {
-    if (trust(addrs[i], i)) continue
-
-    addrs.length = i + 1
-  }
-
-  return addrs
-}
-
-/**
- * Compile argument into trust function.
- *
- * @param {Array|String} val
- * @private
- */
-
-function compile (val) {
-  if (!val) {
-    throw new TypeError('argument is required')
-  }
-
-  var trust
-
-  if (typeof val === 'string') {
-    trust = [val]
-  } else if (Array.isArray(val)) {
-    trust = val.slice()
-  } else {
-    throw new TypeError('unsupported trust argument')
-  }
-
-  for (var i = 0; i < trust.length; i++) {
-    val = trust[i]
-
-    if (!Object.prototype.hasOwnProperty.call(IP_RANGES, val)) {
-      continue
-    }
-
-    // Splice in pre-defined range
-    val = IP_RANGES[val]
-    trust.splice.apply(trust, [i, 1].concat(val))
-    i += val.length - 1
-  }
-
-  return compileTrust(compileRangeSubnets(trust))
-}
-
-/**
- * Compile `arr` elements into range subnets.
- *
- * @param {Array} arr
- * @private
- */
-
-function compileRangeSubnets (arr) {
-  var rangeSubnets = new Array(arr.length)
-
-  for (var i = 0; i < arr.length; i++) {
-    rangeSubnets[i] = parseipNotation(arr[i])
-  }
-
-  return rangeSubnets
-}
-
-/**
- * Compile range subnet array into trust function.
- *
- * @param {Array} rangeSubnets
- * @private
- */
-
-function compileTrust (rangeSubnets) {
-  // Return optimized function based on length
-  var len = rangeSubnets.length
-  return len === 0
-    ? trustNone
-    : len === 1
-      ? trustSingle(rangeSubnets[0])
-      : trustMulti(rangeSubnets)
-}
-
-/**
- * Parse IP notation string into range subnet.
- *
- * @param {String} note
- * @private
- */
-
-function parseipNotation (note) {
-  var pos = note.lastIndexOf('/')
-  var str = pos !== -1
-    ? note.substring(0, pos)
-    : note
-
-  if (!isip(str)) {
-    throw new TypeError('invalid IP address: ' + str)
-  }
-
-  var ip = parseip(str)
-
-  if (pos === -1 && ip.kind() === 'ipv6' && ip.isIPv4MappedAddress()) {
-    // Store as IPv4
-    ip = ip.toIPv4Address()
-  }
-
-  var max = ip.kind() === 'ipv6'
-    ? 128
-    : 32
-
-  var range = pos !== -1
-    ? note.substring(pos + 1, note.length)
-    : null
-
-  if (range === null) {
-    range = max
-  } else if (DIGIT_REGEXP.test(range)) {
-    range = parseInt(range, 10)
-  } else if (ip.kind() === 'ipv4' && isip(range)) {
-    range = parseNetmask(range)
-  } else {
-    range = null
-  }
-
-  if (range <= 0 || range > max) {
-    throw new TypeError('invalid range on address: ' + note)
-  }
-
-  return [ip, range]
-}
-
-/**
- * Parse netmask string into CIDR range.
- *
- * @param {String} netmask
- * @private
- */
-
-function parseNetmask (netmask) {
-  var ip = parseip(netmask)
-  var kind = ip.kind()
-
-  return kind === 'ipv4'
-    ? ip.prefixLengthFromSubnetMask()
-    : null
-}
-
-/**
- * Determine address of proxied request.
- *
- * @param {Object} request
- * @param {Function|Array|String} trust
- * @public
- */
-
-function proxyaddr (req, trust) {
-  if (!req) {
-    throw new TypeError('req argument is required')
-  }
-
-  if (!trust) {
-    throw new TypeError('trust argument is required')
-  }
-
-  var addrs = alladdrs(req, trust)
-  var addr = addrs[addrs.length - 1]
-
-  return addr
-}
-
-/**
- * Static trust function to trust nothing.
- *
- * @private
- */
-
-function trustNone () {
-  return false
-}
-
-/**
- * Compile trust function for multiple subnets.
- *
- * @param {Array} subnets
- * @private
- */
-
-function trustMulti (subnets) {
-  return function trust (addr) {
-    if (!isip(addr)) return false
-
-    var ip = parseip(addr)
-    var ipconv
-    var kind = ip.kind()
-
-    for (var i = 0; i < subnets.length; i++) {
-      var subnet = subnets[i]
-      var subnetip = subnet[0]
-      var subnetkind = subnetip.kind()
-      var subnetrange = subnet[1]
-      var trusted = ip
-
-      if (kind !== subnetkind) {
-        if (subnetkind === 'ipv4' && !ip.isIPv4MappedAddress()) {
-          // Incompatible IP addresses
-          continue
-        }
-
-        if (!ipconv) {
-          // Convert IP to match subnet IP kind
-          ipconv = subnetkind === 'ipv4'
-            ? ip.toIPv4Address()
-            : ip.toIPv4MappedAddress()
-        }
-
-        trusted = ipconv
-      }
-
-      if (trusted.match(subnetip, subnetrange)) {
-        return true
-      }
-    }
-
-    return false
-  }
-}
-
-/**
- * Compile trust function for single subnet.
- *
- * @param {Object} subnet
- * @private
- */
-
-function trustSingle (subnet) {
-  var subnetip = subnet[0]
-  var subnetkind = subnetip.kind()
-  var subnetisipv4 = subnetkind === 'ipv4'
-  var subnetrange = subnet[1]
-
-  return function trust (addr) {
-    if (!isip(addr)) return false
-
-    var ip = parseip(addr)
-    var kind = ip.kind()
-
-    if (kind !== subnetkind) {
-      if (subnetisipv4 && !ip.isIPv4MappedAddress()) {
-        // Incompatible IP addresses
-        return false
-      }
-
-      // Convert IP to match subnet IP kind
-      ip = subnetisipv4
-        ? ip.toIPv4Address()
-        : ip.toIPv4MappedAddress()
-    }
-
-    return ip.match(subnetip, subnetrange)
-  }
-}
+"use strict";module.exports=proxyaddr,module.exports.all=alladdrs,module.exports.compile=compile;var forwarded=require("forwarded"),ipaddr=require("ipaddr.js"),DIGIT_REGEXP=/^[0-9]+$/,isip=ipaddr.isValid,parseip=ipaddr.parse,IP_RANGES={linklocal:["169.254.0.0/16","fe80::/10"],loopback:["127.0.0.1/8","::1/128"],uniquelocal:["10.0.0.0/8","172.16.0.0/12","192.168.0.0/16","fc00::/7"]};function alladdrs(r,e){var t=forwarded(r);if(!e)return t;"function"!=typeof e&&(e=compile(e));for(var i=0;i<t.length-1;i++)e(t[i],i)||(t.length=i+1);return t}function compile(r){if(!r)throw new TypeError("argument is required");var e;if("string"==typeof r)e=[r];else{if(!Array.isArray(r))throw new TypeError("unsupported trust argument");e=r.slice()}for(var t=0;t<e.length;t++)r=e[t],Object.prototype.hasOwnProperty.call(IP_RANGES,r)&&(r=IP_RANGES[r],e.splice.apply(e,[t,1].concat(r)),t+=r.length-1);return compileTrust(compileRangeSubnets(e))}function compileRangeSubnets(r){for(var e=new Array(r.length),t=0;t<r.length;t++)e[t]=parseipNotation(r[t]);return e}function compileTrust(r){var e=r.length;return 0===e?trustNone:1===e?trustSingle(r[0]):trustMulti(r)}function parseipNotation(r){var e=r.lastIndexOf("/"),t=-1!==e?r.substring(0,e):r;if(!isip(t))throw new TypeError("invalid IP address: "+t);var i=parseip(t);-1===e&&"ipv6"===i.kind()&&i.isIPv4MappedAddress()&&(i=i.toIPv4Address());var n="ipv6"===i.kind()?128:32,s=-1!==e?r.substring(e+1,r.length):null;if((s=null===s?n:DIGIT_REGEXP.test(s)?parseInt(s,10):"ipv4"===i.kind()&&isip(s)?parseNetmask(s):null)<=0||s>n)throw new TypeError("invalid range on address: "+r);return[i,s]}function parseNetmask(r){var e=parseip(r);return"ipv4"===e.kind()?e.prefixLengthFromSubnetMask():null}function proxyaddr(r,e){if(!r)throw new TypeError("req argument is required");if(!e)throw new TypeError("trust argument is required");var t=alladdrs(r,e);return t[t.length-1]}function trustNone(){return!1}function trustMulti(r){return function(e){if(!isip(e))return!1;for(var t,i=parseip(e),n=i.kind(),s=0;s<r.length;s++){var a=r[s],p=a[0],o=p.kind(),u=a[1],d=i;if(n!==o){if("ipv4"===o&&!i.isIPv4MappedAddress())continue;t||(t="ipv4"===o?i.toIPv4Address():i.toIPv4MappedAddress()),d=t}if(d.match(p,u))return!0}return!1}}function trustSingle(r){var e=r[0],t=e.kind(),i="ipv4"===t,n=r[1];return function(r){if(!isip(r))return!1;var s=parseip(r);if(s.kind()!==t){if(i&&!s.isIPv4MappedAddress())return!1;s=i?s.toIPv4Address():s.toIPv4MappedAddress()}return s.match(e,n)}}
\ No newline at end of file
index c7ee23d..088bf32 100644 (file)
-(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.QRCode = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
-// can-promise has a crash in some versions of react native that dont have
-// standard global objects
-// https://github.com/soldair/node-qrcode/issues/157
-
-module.exports = function () {
-  return typeof Promise === 'function' && Promise.prototype && Promise.prototype.then
-}
-
-},{}],2:[function(require,module,exports){
-/**
- * Alignment pattern are fixed reference pattern in defined positions
- * in a matrix symbology, which enables the decode software to re-synchronise
- * the coordinate mapping of the image modules in the event of moderate amounts
- * of distortion of the image.
- *
- * Alignment patterns are present only in QR Code symbols of version 2 or larger
- * and their number depends on the symbol version.
- */
-
-var getSymbolSize = require('./utils').getSymbolSize
-
-/**
- * Calculate the row/column coordinates of the center module of each alignment pattern
- * for the specified QR Code version.
- *
- * The alignment patterns are positioned symmetrically on either side of the diagonal
- * running from the top left corner of the symbol to the bottom right corner.
- *
- * Since positions are simmetrical only half of the coordinates are returned.
- * Each item of the array will represent in turn the x and y coordinate.
- * @see {@link getPositions}
- *
- * @param  {Number} version QR Code version
- * @return {Array}          Array of coordinate
- */
-exports.getRowColCoords = function getRowColCoords (version) {
-  if (version === 1) return []
-
-  var posCount = Math.floor(version / 7) + 2
-  var size = getSymbolSize(version)
-  var intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2
-  var positions = [size - 7] // Last coord is always (size - 7)
-
-  for (var i = 1; i < posCount - 1; i++) {
-    positions[i] = positions[i - 1] - intervals
-  }
-
-  positions.push(6) // First coord is always 6
-
-  return positions.reverse()
-}
-
-/**
- * Returns an array containing the positions of each alignment pattern.
- * Each array's element represent the center point of the pattern as (x, y) coordinates
- *
- * Coordinates are calculated expanding the row/column coordinates returned by {@link getRowColCoords}
- * and filtering out the items that overlaps with finder pattern
- *
- * @example
- * For a Version 7 symbol {@link getRowColCoords} returns values 6, 22 and 38.
- * The alignment patterns, therefore, are to be centered on (row, column)
- * positions (6,22), (22,6), (22,22), (22,38), (38,22), (38,38).
- * Note that the coordinates (6,6), (6,38), (38,6) are occupied by finder patterns
- * and are not therefore used for alignment patterns.
- *
- * var pos = getPositions(7)
- * // [[6,22], [22,6], [22,22], [22,38], [38,22], [38,38]]
- *
- * @param  {Number} version QR Code version
- * @return {Array}          Array of coordinates
- */
-exports.getPositions = function getPositions (version) {
-  var coords = []
-  var pos = exports.getRowColCoords(version)
-  var posLength = pos.length
-
-  for (var i = 0; i < posLength; i++) {
-    for (var j = 0; j < posLength; j++) {
-      // Skip if position is occupied by finder patterns
-      if ((i === 0 && j === 0) ||             // top-left
-          (i === 0 && j === posLength - 1) || // bottom-left
-          (i === posLength - 1 && j === 0)) { // top-right
-        continue
-      }
-
-      coords.push([pos[i], pos[j]])
-    }
-  }
-
-  return coords
-}
-
-},{"./utils":21}],3:[function(require,module,exports){
-var Mode = require('./mode')
-
-/**
- * Array of characters available in alphanumeric mode
- *
- * As per QR Code specification, to each character
- * is assigned a value from 0 to 44 which in this case coincides
- * with the array index
- *
- * @type {Array}
- */
-var ALPHA_NUM_CHARS = [
-  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
-  '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',
-  ' ', '$', '%', '*', '+', '-', '.', '/', ':'
-]
-
-function AlphanumericData (data) {
-  this.mode = Mode.ALPHANUMERIC
-  this.data = data
-}
-
-AlphanumericData.getBitsLength = function getBitsLength (length) {
-  return 11 * Math.floor(length / 2) + 6 * (length % 2)
-}
-
-AlphanumericData.prototype.getLength = function getLength () {
-  return this.data.length
-}
-
-AlphanumericData.prototype.getBitsLength = function getBitsLength () {
-  return AlphanumericData.getBitsLength(this.data.length)
-}
-
-AlphanumericData.prototype.write = function write (bitBuffer) {
-  var i
-
-  // Input data characters are divided into groups of two characters
-  // and encoded as 11-bit binary codes.
-  for (i = 0; i + 2 <= this.data.length; i += 2) {
-    // The character value of the first character is multiplied by 45
-    var value = ALPHA_NUM_CHARS.indexOf(this.data[i]) * 45
-
-    // The character value of the second digit is added to the product
-    value += ALPHA_NUM_CHARS.indexOf(this.data[i + 1])
-
-    // The sum is then stored as 11-bit binary number
-    bitBuffer.put(value, 11)
-  }
-
-  // If the number of input data characters is not a multiple of two,
-  // the character value of the final character is encoded as a 6-bit binary number.
-  if (this.data.length % 2) {
-    bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i]), 6)
-  }
-}
-
-module.exports = AlphanumericData
-
-},{"./mode":14}],4:[function(require,module,exports){
-function BitBuffer () {
-  this.buffer = []
-  this.length = 0
-}
-
-BitBuffer.prototype = {
-
-  get: function (index) {
-    var bufIndex = Math.floor(index / 8)
-    return ((this.buffer[bufIndex] >>> (7 - index % 8)) & 1) === 1
-  },
-
-  put: function (num, length) {
-    for (var i = 0; i < length; i++) {
-      this.putBit(((num >>> (length - i - 1)) & 1) === 1)
-    }
-  },
-
-  getLengthInBits: function () {
-    return this.length
-  },
-
-  putBit: function (bit) {
-    var bufIndex = Math.floor(this.length / 8)
-    if (this.buffer.length <= bufIndex) {
-      this.buffer.push(0)
-    }
-
-    if (bit) {
-      this.buffer[bufIndex] |= (0x80 >>> (this.length % 8))
-    }
-
-    this.length++
-  }
-}
-
-module.exports = BitBuffer
-
-},{}],5:[function(require,module,exports){
-var BufferUtil = require('../utils/buffer')
-
-/**
- * Helper class to handle QR Code symbol modules
- *
- * @param {Number} size Symbol size
- */
-function BitMatrix (size) {
-  if (!size || size < 1) {
-    throw new Error('BitMatrix size must be defined and greater than 0')
-  }
-
-  this.size = size
-  this.data = BufferUtil.alloc(size * size)
-  this.reservedBit = BufferUtil.alloc(size * size)
-}
-
-/**
- * Set bit value at specified location
- * If reserved flag is set, this bit will be ignored during masking process
- *
- * @param {Number}  row
- * @param {Number}  col
- * @param {Boolean} value
- * @param {Boolean} reserved
- */
-BitMatrix.prototype.set = function (row, col, value, reserved) {
-  var index = row * this.size + col
-  this.data[index] = value
-  if (reserved) this.reservedBit[index] = true
-}
-
-/**
- * Returns bit value at specified location
- *
- * @param  {Number}  row
- * @param  {Number}  col
- * @return {Boolean}
- */
-BitMatrix.prototype.get = function (row, col) {
-  return this.data[row * this.size + col]
-}
-
-/**
- * Applies xor operator at specified location
- * (used during masking process)
- *
- * @param {Number}  row
- * @param {Number}  col
- * @param {Boolean} value
- */
-BitMatrix.prototype.xor = function (row, col, value) {
-  this.data[row * this.size + col] ^= value
-}
-
-/**
- * Check if bit at specified location is reserved
- *
- * @param {Number}   row
- * @param {Number}   col
- * @return {Boolean}
- */
-BitMatrix.prototype.isReserved = function (row, col) {
-  return this.reservedBit[row * this.size + col]
-}
-
-module.exports = BitMatrix
-
-},{"../utils/buffer":28}],6:[function(require,module,exports){
-var BufferUtil = require('../utils/buffer')
-var Mode = require('./mode')
-
-function ByteData (data) {
-  this.mode = Mode.BYTE
-  this.data = BufferUtil.from(data)
-}
-
-ByteData.getBitsLength = function getBitsLength (length) {
-  return length * 8
-}
-
-ByteData.prototype.getLength = function getLength () {
-  return this.data.length
-}
-
-ByteData.prototype.getBitsLength = function getBitsLength () {
-  return ByteData.getBitsLength(this.data.length)
-}
-
-ByteData.prototype.write = function (bitBuffer) {
-  for (var i = 0, l = this.data.length; i < l; i++) {
-    bitBuffer.put(this.data[i], 8)
-  }
-}
-
-module.exports = ByteData
-
-},{"../utils/buffer":28,"./mode":14}],7:[function(require,module,exports){
-var ECLevel = require('./error-correction-level')\r
-\r
-var EC_BLOCKS_TABLE = [\r
-// L  M  Q  H\r
-  1, 1, 1, 1,\r
-  1, 1, 1, 1,\r
-  1, 1, 2, 2,\r
-  1, 2, 2, 4,\r
-  1, 2, 4, 4,\r
-  2, 4, 4, 4,\r
-  2, 4, 6, 5,\r
-  2, 4, 6, 6,\r
-  2, 5, 8, 8,\r
-  4, 5, 8, 8,\r
-  4, 5, 8, 11,\r
-  4, 8, 10, 11,\r
-  4, 9, 12, 16,\r
-  4, 9, 16, 16,\r
-  6, 10, 12, 18,\r
-  6, 10, 17, 16,\r
-  6, 11, 16, 19,\r
-  6, 13, 18, 21,\r
-  7, 14, 21, 25,\r
-  8, 16, 20, 25,\r
-  8, 17, 23, 25,\r
-  9, 17, 23, 34,\r
-  9, 18, 25, 30,\r
-  10, 20, 27, 32,\r
-  12, 21, 29, 35,\r
-  12, 23, 34, 37,\r
-  12, 25, 34, 40,\r
-  13, 26, 35, 42,\r
-  14, 28, 38, 45,\r
-  15, 29, 40, 48,\r
-  16, 31, 43, 51,\r
-  17, 33, 45, 54,\r
-  18, 35, 48, 57,\r
-  19, 37, 51, 60,\r
-  19, 38, 53, 63,\r
-  20, 40, 56, 66,\r
-  21, 43, 59, 70,\r
-  22, 45, 62, 74,\r
-  24, 47, 65, 77,\r
-  25, 49, 68, 81\r
-]\r
-\r
-var EC_CODEWORDS_TABLE = [\r
-// L  M  Q  H\r
-  7, 10, 13, 17,\r
-  10, 16, 22, 28,\r
-  15, 26, 36, 44,\r
-  20, 36, 52, 64,\r
-  26, 48, 72, 88,\r
-  36, 64, 96, 112,\r
-  40, 72, 108, 130,\r
-  48, 88, 132, 156,\r
-  60, 110, 160, 192,\r
-  72, 130, 192, 224,\r
-  80, 150, 224, 264,\r
-  96, 176, 260, 308,\r
-  104, 198, 288, 352,\r
-  120, 216, 320, 384,\r
-  132, 240, 360, 432,\r
-  144, 280, 408, 480,\r
-  168, 308, 448, 532,\r
-  180, 338, 504, 588,\r
-  196, 364, 546, 650,\r
-  224, 416, 600, 700,\r
-  224, 442, 644, 750,\r
-  252, 476, 690, 816,\r
-  270, 504, 750, 900,\r
-  300, 560, 810, 960,\r
-  312, 588, 870, 1050,\r
-  336, 644, 952, 1110,\r
-  360, 700, 1020, 1200,\r
-  390, 728, 1050, 1260,\r
-  420, 784, 1140, 1350,\r
-  450, 812, 1200, 1440,\r
-  480, 868, 1290, 1530,\r
-  510, 924, 1350, 1620,\r
-  540, 980, 1440, 1710,\r
-  570, 1036, 1530, 1800,\r
-  570, 1064, 1590, 1890,\r
-  600, 1120, 1680, 1980,\r
-  630, 1204, 1770, 2100,\r
-  660, 1260, 1860, 2220,\r
-  720, 1316, 1950, 2310,\r
-  750, 1372, 2040, 2430\r
-]\r
-\r
-/**\r
- * Returns the number of error correction block that the QR Code should contain\r
- * for the specified version and error correction level.\r
- *\r
- * @param  {Number} version              QR Code version\r
- * @param  {Number} errorCorrectionLevel Error correction level\r
- * @return {Number}                      Number of error correction blocks\r
- */\r
-exports.getBlocksCount = function getBlocksCount (version, errorCorrectionLevel) {\r
-  switch (errorCorrectionLevel) {\r
-    case ECLevel.L:\r
-      return EC_BLOCKS_TABLE[(version - 1) * 4 + 0]\r
-    case ECLevel.M:\r
-      return EC_BLOCKS_TABLE[(version - 1) * 4 + 1]\r
-    case ECLevel.Q:\r
-      return EC_BLOCKS_TABLE[(version - 1) * 4 + 2]\r
-    case ECLevel.H:\r
-      return EC_BLOCKS_TABLE[(version - 1) * 4 + 3]\r
-    default:\r
-      return undefined\r
-  }\r
-}\r
-\r
-/**\r
- * Returns the number of error correction codewords to use for the specified\r
- * version and error correction level.\r
- *\r
- * @param  {Number} version              QR Code version\r
- * @param  {Number} errorCorrectionLevel Error correction level\r
- * @return {Number}                      Number of error correction codewords\r
- */\r
-exports.getTotalCodewordsCount = function getTotalCodewordsCount (version, errorCorrectionLevel) {\r
-  switch (errorCorrectionLevel) {\r
-    case ECLevel.L:\r
-      return EC_CODEWORDS_TABLE[(version - 1) * 4 + 0]\r
-    case ECLevel.M:\r
-      return EC_CODEWORDS_TABLE[(version - 1) * 4 + 1]\r
-    case ECLevel.Q:\r
-      return EC_CODEWORDS_TABLE[(version - 1) * 4 + 2]\r
-    case ECLevel.H:\r
-      return EC_CODEWORDS_TABLE[(version - 1) * 4 + 3]\r
-    default:\r
-      return undefined\r
-  }\r
-}\r
-
-},{"./error-correction-level":8}],8:[function(require,module,exports){
-exports.L = { bit: 1 }
-exports.M = { bit: 0 }
-exports.Q = { bit: 3 }
-exports.H = { bit: 2 }
-
-function fromString (string) {
-  if (typeof string !== 'string') {
-    throw new Error('Param is not a string')
-  }
-
-  var lcStr = string.toLowerCase()
-
-  switch (lcStr) {
-    case 'l':
-    case 'low':
-      return exports.L
-
-    case 'm':
-    case 'medium':
-      return exports.M
-
-    case 'q':
-    case 'quartile':
-      return exports.Q
-
-    case 'h':
-    case 'high':
-      return exports.H
-
-    default:
-      throw new Error('Unknown EC Level: ' + string)
-  }
-}
-
-exports.isValid = function isValid (level) {
-  return level && typeof level.bit !== 'undefined' &&
-    level.bit >= 0 && level.bit < 4
-}
-
-exports.from = function from (value, defaultValue) {
-  if (exports.isValid(value)) {
-    return value
-  }
-
-  try {
-    return fromString(value)
-  } catch (e) {
-    return defaultValue
-  }
-}
-
-},{}],9:[function(require,module,exports){
-var getSymbolSize = require('./utils').getSymbolSize
-var FINDER_PATTERN_SIZE = 7
-
-/**
- * Returns an array containing the positions of each finder pattern.
- * Each array's element represent the top-left point of the pattern as (x, y) coordinates
- *
- * @param  {Number} version QR Code version
- * @return {Array}          Array of coordinates
- */
-exports.getPositions = function getPositions (version) {
-  var size = getSymbolSize(version)
-
-  return [
-    // top-left
-    [0, 0],
-    // top-right
-    [size - FINDER_PATTERN_SIZE, 0],
-    // bottom-left
-    [0, size - FINDER_PATTERN_SIZE]
-  ]
-}
-
-},{"./utils":21}],10:[function(require,module,exports){
-var Utils = require('./utils')
-
-var G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0)
-var G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1)
-var G15_BCH = Utils.getBCHDigit(G15)
-
-/**
- * Returns format information with relative error correction bits
- *
- * The format information is a 15-bit sequence containing 5 data bits,
- * with 10 error correction bits calculated using the (15, 5) BCH code.
- *
- * @param  {Number} errorCorrectionLevel Error correction level
- * @param  {Number} mask                 Mask pattern
- * @return {Number}                      Encoded format information bits
- */
-exports.getEncodedBits = function getEncodedBits (errorCorrectionLevel, mask) {
-  var data = ((errorCorrectionLevel.bit << 3) | mask)
-  var d = data << 10
-
-  while (Utils.getBCHDigit(d) - G15_BCH >= 0) {
-    d ^= (G15 << (Utils.getBCHDigit(d) - G15_BCH))
-  }
-
-  // xor final data with mask pattern in order to ensure that
-  // no combination of Error Correction Level and data mask pattern
-  // will result in an all-zero data string
-  return ((data << 10) | d) ^ G15_MASK
-}
-
-},{"./utils":21}],11:[function(require,module,exports){
-var BufferUtil = require('../utils/buffer')
-
-var EXP_TABLE = BufferUtil.alloc(512)
-var LOG_TABLE = BufferUtil.alloc(256)
-/**
- * Precompute the log and anti-log tables for faster computation later
- *
- * For each possible value in the galois field 2^8, we will pre-compute
- * the logarithm and anti-logarithm (exponential) of this value
- *
- * ref {@link https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Introduction_to_mathematical_fields}
- */
-;(function initTables () {
-  var x = 1
-  for (var i = 0; i < 255; i++) {
-    EXP_TABLE[i] = x
-    LOG_TABLE[x] = i
-
-    x <<= 1 // multiply by 2
-
-    // The QR code specification says to use byte-wise modulo 100011101 arithmetic.
-    // This means that when a number is 256 or larger, it should be XORed with 0x11D.
-    if (x & 0x100) { // similar to x >= 256, but a lot faster (because 0x100 == 256)
-      x ^= 0x11D
-    }
-  }
-
-  // Optimization: double the size of the anti-log table so that we don't need to mod 255 to
-  // stay inside the bounds (because we will mainly use this table for the multiplication of
-  // two GF numbers, no more).
-  // @see {@link mul}
-  for (i = 255; i < 512; i++) {
-    EXP_TABLE[i] = EXP_TABLE[i - 255]
-  }
-}())
-
-/**
- * Returns log value of n inside Galois Field
- *
- * @param  {Number} n
- * @return {Number}
- */
-exports.log = function log (n) {
-  if (n < 1) throw new Error('log(' + n + ')')
-  return LOG_TABLE[n]
-}
-
-/**
- * Returns anti-log value of n inside Galois Field
- *
- * @param  {Number} n
- * @return {Number}
- */
-exports.exp = function exp (n) {
-  return EXP_TABLE[n]
-}
-
-/**
- * Multiplies two number inside Galois Field
- *
- * @param  {Number} x
- * @param  {Number} y
- * @return {Number}
- */
-exports.mul = function mul (x, y) {
-  if (x === 0 || y === 0) return 0
-
-  // should be EXP_TABLE[(LOG_TABLE[x] + LOG_TABLE[y]) % 255] if EXP_TABLE wasn't oversized
-  // @see {@link initTables}
-  return EXP_TABLE[LOG_TABLE[x] + LOG_TABLE[y]]
-}
-
-},{"../utils/buffer":28}],12:[function(require,module,exports){
-var Mode = require('./mode')
-var Utils = require('./utils')
-
-function KanjiData (data) {
-  this.mode = Mode.KANJI
-  this.data = data
-}
-
-KanjiData.getBitsLength = function getBitsLength (length) {
-  return length * 13
-}
-
-KanjiData.prototype.getLength = function getLength () {
-  return this.data.length
-}
-
-KanjiData.prototype.getBitsLength = function getBitsLength () {
-  return KanjiData.getBitsLength(this.data.length)
-}
-
-KanjiData.prototype.write = function (bitBuffer) {
-  var i
-
-  // In the Shift JIS system, Kanji characters are represented by a two byte combination.
-  // These byte values are shifted from the JIS X 0208 values.
-  // JIS X 0208 gives details of the shift coded representation.
-  for (i = 0; i < this.data.length; i++) {
-    var value = Utils.toSJIS(this.data[i])
-
-    // For characters with Shift JIS values from 0x8140 to 0x9FFC:
-    if (value >= 0x8140 && value <= 0x9FFC) {
-      // Subtract 0x8140 from Shift JIS value
-      value -= 0x8140
-
-    // For characters with Shift JIS values from 0xE040 to 0xEBBF
-    } else if (value >= 0xE040 && value <= 0xEBBF) {
-      // Subtract 0xC140 from Shift JIS value
-      value -= 0xC140
-    } else {
-      throw new Error(
-        'Invalid SJIS character: ' + this.data[i] + '\n' +
-        'Make sure your charset is UTF-8')
-    }
-
-    // Multiply most significant byte of result by 0xC0
-    // and add least significant byte to product
-    value = (((value >>> 8) & 0xff) * 0xC0) + (value & 0xff)
-
-    // Convert result to a 13-bit binary string
-    bitBuffer.put(value, 13)
-  }
-}
-
-module.exports = KanjiData
-
-},{"./mode":14,"./utils":21}],13:[function(require,module,exports){
-/**
- * Data mask pattern reference
- * @type {Object}
- */
-exports.Patterns = {
-  PATTERN000: 0,
-  PATTERN001: 1,
-  PATTERN010: 2,
-  PATTERN011: 3,
-  PATTERN100: 4,
-  PATTERN101: 5,
-  PATTERN110: 6,
-  PATTERN111: 7
-}
-
-/**
- * Weighted penalty scores for the undesirable features
- * @type {Object}
- */
-var PenaltyScores = {
-  N1: 3,
-  N2: 3,
-  N3: 40,
-  N4: 10
-}
-
-/**
- * Check if mask pattern value is valid
- *
- * @param  {Number}  mask    Mask pattern
- * @return {Boolean}         true if valid, false otherwise
- */
-exports.isValid = function isValid (mask) {
-  return mask != null && mask !== '' && !isNaN(mask) && mask >= 0 && mask <= 7
-}
-
-/**
- * Returns mask pattern from a value.
- * If value is not valid, returns undefined
- *
- * @param  {Number|String} value        Mask pattern value
- * @return {Number}                     Valid mask pattern or undefined
- */
-exports.from = function from (value) {
-  return exports.isValid(value) ? parseInt(value, 10) : undefined
-}
-
-/**
-* Find adjacent modules in row/column with the same color
-* and assign a penalty value.
-*
-* Points: N1 + i
-* i is the amount by which the number of adjacent modules of the same color exceeds 5
-*/
-exports.getPenaltyN1 = function getPenaltyN1 (data) {
-  var size = data.size
-  var points = 0
-  var sameCountCol = 0
-  var sameCountRow = 0
-  var lastCol = null
-  var lastRow = null
-
-  for (var row = 0; row < size; row++) {
-    sameCountCol = sameCountRow = 0
-    lastCol = lastRow = null
-
-    for (var col = 0; col < size; col++) {
-      var module = data.get(row, col)
-      if (module === lastCol) {
-        sameCountCol++
-      } else {
-        if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5)
-        lastCol = module
-        sameCountCol = 1
-      }
-
-      module = data.get(col, row)
-      if (module === lastRow) {
-        sameCountRow++
-      } else {
-        if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5)
-        lastRow = module
-        sameCountRow = 1
-      }
-    }
-
-    if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5)
-    if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5)
-  }
-
-  return points
-}
-
-/**
- * Find 2x2 blocks with the same color and assign a penalty value
- *
- * Points: N2 * (m - 1) * (n - 1)
- */
-exports.getPenaltyN2 = function getPenaltyN2 (data) {
-  var size = data.size
-  var points = 0
-
-  for (var row = 0; row < size - 1; row++) {
-    for (var col = 0; col < size - 1; col++) {
-      var last = data.get(row, col) +
-        data.get(row, col + 1) +
-        data.get(row + 1, col) +
-        data.get(row + 1, col + 1)
-
-      if (last === 4 || last === 0) points++
-    }
-  }
-
-  return points * PenaltyScores.N2
-}
-
-/**
- * Find 1:1:3:1:1 ratio (dark:light:dark:light:dark) pattern in row/column,
- * preceded or followed by light area 4 modules wide
- *
- * Points: N3 * number of pattern found
- */
-exports.getPenaltyN3 = function getPenaltyN3 (data) {
-  var size = data.size
-  var points = 0
-  var bitsCol = 0
-  var bitsRow = 0
-
-  for (var row = 0; row < size; row++) {
-    bitsCol = bitsRow = 0
-    for (var col = 0; col < size; col++) {
-      bitsCol = ((bitsCol << 1) & 0x7FF) | data.get(row, col)
-      if (col >= 10 && (bitsCol === 0x5D0 || bitsCol === 0x05D)) points++
-
-      bitsRow = ((bitsRow << 1) & 0x7FF) | data.get(col, row)
-      if (col >= 10 && (bitsRow === 0x5D0 || bitsRow === 0x05D)) points++
-    }
-  }
-
-  return points * PenaltyScores.N3
-}
-
-/**
- * Calculate proportion of dark modules in entire symbol
- *
- * Points: N4 * k
- *
- * k is the rating of the deviation of the proportion of dark modules
- * in the symbol from 50% in steps of 5%
- */
-exports.getPenaltyN4 = function getPenaltyN4 (data) {
-  var darkCount = 0
-  var modulesCount = data.data.length
-
-  for (var i = 0; i < modulesCount; i++) darkCount += data.data[i]
-
-  var k = Math.abs(Math.ceil((darkCount * 100 / modulesCount) / 5) - 10)
-
-  return k * PenaltyScores.N4
-}
-
-/**
- * Return mask value at given position
- *
- * @param  {Number} maskPattern Pattern reference value
- * @param  {Number} i           Row
- * @param  {Number} j           Column
- * @return {Boolean}            Mask value
- */
-function getMaskAt (maskPattern, i, j) {
-  switch (maskPattern) {
-    case exports.Patterns.PATTERN000: return (i + j) % 2 === 0
-    case exports.Patterns.PATTERN001: return i % 2 === 0
-    case exports.Patterns.PATTERN010: return j % 3 === 0
-    case exports.Patterns.PATTERN011: return (i + j) % 3 === 0
-    case exports.Patterns.PATTERN100: return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 === 0
-    case exports.Patterns.PATTERN101: return (i * j) % 2 + (i * j) % 3 === 0
-    case exports.Patterns.PATTERN110: return ((i * j) % 2 + (i * j) % 3) % 2 === 0
-    case exports.Patterns.PATTERN111: return ((i * j) % 3 + (i + j) % 2) % 2 === 0
-
-    default: throw new Error('bad maskPattern:' + maskPattern)
-  }
-}
-
-/**
- * Apply a mask pattern to a BitMatrix
- *
- * @param  {Number}    pattern Pattern reference number
- * @param  {BitMatrix} data    BitMatrix data
- */
-exports.applyMask = function applyMask (pattern, data) {
-  var size = data.size
-
-  for (var col = 0; col < size; col++) {
-    for (var row = 0; row < size; row++) {
-      if (data.isReserved(row, col)) continue
-      data.xor(row, col, getMaskAt(pattern, row, col))
-    }
-  }
-}
-
-/**
- * Returns the best mask pattern for data
- *
- * @param  {BitMatrix} data
- * @return {Number} Mask pattern reference number
- */
-exports.getBestMask = function getBestMask (data, setupFormatFunc) {
-  var numPatterns = Object.keys(exports.Patterns).length
-  var bestPattern = 0
-  var lowerPenalty = Infinity
-
-  for (var p = 0; p < numPatterns; p++) {
-    setupFormatFunc(p)
-    exports.applyMask(p, data)
-
-    // Calculate penalty
-    var penalty =
-      exports.getPenaltyN1(data) +
-      exports.getPenaltyN2(data) +
-      exports.getPenaltyN3(data) +
-      exports.getPenaltyN4(data)
-
-    // Undo previously applied mask
-    exports.applyMask(p, data)
-
-    if (penalty < lowerPenalty) {
-      lowerPenalty = penalty
-      bestPattern = p
-    }
-  }
-
-  return bestPattern
-}
-
-},{}],14:[function(require,module,exports){
-var VersionCheck = require('./version-check')
-var Regex = require('./regex')
-
-/**
- * Numeric mode encodes data from the decimal digit set (0 - 9)
- * (byte values 30HEX to 39HEX).
- * Normally, 3 data characters are represented by 10 bits.
- *
- * @type {Object}
- */
-exports.NUMERIC = {
-  id: 'Numeric',
-  bit: 1 << 0,
-  ccBits: [10, 12, 14]
-}
-
-/**
- * Alphanumeric mode encodes data from a set of 45 characters,
- * i.e. 10 numeric digits (0 - 9),
- *      26 alphabetic characters (A - Z),
- *   and 9 symbols (SP, $, %, *, +, -, ., /, :).
- * Normally, two input characters are represented by 11 bits.
- *
- * @type {Object}
- */
-exports.ALPHANUMERIC = {
-  id: 'Alphanumeric',
-  bit: 1 << 1,
-  ccBits: [9, 11, 13]
-}
-
-/**
- * In byte mode, data is encoded at 8 bits per character.
- *
- * @type {Object}
- */
-exports.BYTE = {
-  id: 'Byte',
-  bit: 1 << 2,
-  ccBits: [8, 16, 16]
-}
-
-/**
- * The Kanji mode efficiently encodes Kanji characters in accordance with
- * the Shift JIS system based on JIS X 0208.
- * The Shift JIS values are shifted from the JIS X 0208 values.
- * JIS X 0208 gives details of the shift coded representation.
- * Each two-byte character value is compacted to a 13-bit binary codeword.
- *
- * @type {Object}
- */
-exports.KANJI = {
-  id: 'Kanji',
-  bit: 1 << 3,
-  ccBits: [8, 10, 12]
-}
-
-/**
- * Mixed mode will contain a sequences of data in a combination of any of
- * the modes described above
- *
- * @type {Object}
- */
-exports.MIXED = {
-  bit: -1
-}
-
-/**
- * Returns the number of bits needed to store the data length
- * according to QR Code specifications.
- *
- * @param  {Mode}   mode    Data mode
- * @param  {Number} version QR Code version
- * @return {Number}         Number of bits
- */
-exports.getCharCountIndicator = function getCharCountIndicator (mode, version) {
-  if (!mode.ccBits) throw new Error('Invalid mode: ' + mode)
-
-  if (!VersionCheck.isValid(version)) {
-    throw new Error('Invalid version: ' + version)
-  }
-
-  if (version >= 1 && version < 10) return mode.ccBits[0]
-  else if (version < 27) return mode.ccBits[1]
-  return mode.ccBits[2]
-}
-
-/**
- * Returns the most efficient mode to store the specified data
- *
- * @param  {String} dataStr Input data string
- * @return {Mode}           Best mode
- */
-exports.getBestModeForData = function getBestModeForData (dataStr) {
-  if (Regex.testNumeric(dataStr)) return exports.NUMERIC
-  else if (Regex.testAlphanumeric(dataStr)) return exports.ALPHANUMERIC
-  else if (Regex.testKanji(dataStr)) return exports.KANJI
-  else return exports.BYTE
-}
-
-/**
- * Return mode name as string
- *
- * @param {Mode} mode Mode object
- * @returns {String}  Mode name
- */
-exports.toString = function toString (mode) {
-  if (mode && mode.id) return mode.id
-  throw new Error('Invalid mode')
-}
-
-/**
- * Check if input param is a valid mode object
- *
- * @param   {Mode}    mode Mode object
- * @returns {Boolean} True if valid mode, false otherwise
- */
-exports.isValid = function isValid (mode) {
-  return mode && mode.bit && mode.ccBits
-}
-
-/**
- * Get mode object from its name
- *
- * @param   {String} string Mode name
- * @returns {Mode}          Mode object
- */
-function fromString (string) {
-  if (typeof string !== 'string') {
-    throw new Error('Param is not a string')
-  }
-
-  var lcStr = string.toLowerCase()
-
-  switch (lcStr) {
-    case 'numeric':
-      return exports.NUMERIC
-    case 'alphanumeric':
-      return exports.ALPHANUMERIC
-    case 'kanji':
-      return exports.KANJI
-    case 'byte':
-      return exports.BYTE
-    default:
-      throw new Error('Unknown mode: ' + string)
-  }
-}
-
-/**
- * Returns mode from a value.
- * If value is not a valid mode, returns defaultValue
- *
- * @param  {Mode|String} value        Encoding mode
- * @param  {Mode}        defaultValue Fallback value
- * @return {Mode}                     Encoding mode
- */
-exports.from = function from (value, defaultValue) {
-  if (exports.isValid(value)) {
-    return value
-  }
-
-  try {
-    return fromString(value)
-  } catch (e) {
-    return defaultValue
-  }
-}
-
-},{"./regex":19,"./version-check":22}],15:[function(require,module,exports){
-var Mode = require('./mode')
-
-function NumericData (data) {
-  this.mode = Mode.NUMERIC
-  this.data = data.toString()
-}
-
-NumericData.getBitsLength = function getBitsLength (length) {
-  return 10 * Math.floor(length / 3) + ((length % 3) ? ((length % 3) * 3 + 1) : 0)
-}
-
-NumericData.prototype.getLength = function getLength () {
-  return this.data.length
-}
-
-NumericData.prototype.getBitsLength = function getBitsLength () {
-  return NumericData.getBitsLength(this.data.length)
-}
-
-NumericData.prototype.write = function write (bitBuffer) {
-  var i, group, value
-
-  // The input data string is divided into groups of three digits,
-  // and each group is converted to its 10-bit binary equivalent.
-  for (i = 0; i + 3 <= this.data.length; i += 3) {
-    group = this.data.substr(i, 3)
-    value = parseInt(group, 10)
-
-    bitBuffer.put(value, 10)
-  }
-
-  // If the number of input digits is not an exact multiple of three,
-  // the final one or two digits are converted to 4 or 7 bits respectively.
-  var remainingNum = this.data.length - i
-  if (remainingNum > 0) {
-    group = this.data.substr(i)
-    value = parseInt(group, 10)
-
-    bitBuffer.put(value, remainingNum * 3 + 1)
-  }
-}
-
-module.exports = NumericData
-
-},{"./mode":14}],16:[function(require,module,exports){
-var BufferUtil = require('../utils/buffer')
-var GF = require('./galois-field')
-
-/**
- * Multiplies two polynomials inside Galois Field
- *
- * @param  {Buffer} p1 Polynomial
- * @param  {Buffer} p2 Polynomial
- * @return {Buffer}    Product of p1 and p2
- */
-exports.mul = function mul (p1, p2) {
-  var coeff = BufferUtil.alloc(p1.length + p2.length - 1)
-
-  for (var i = 0; i < p1.length; i++) {
-    for (var j = 0; j < p2.length; j++) {
-      coeff[i + j] ^= GF.mul(p1[i], p2[j])
-    }
-  }
-
-  return coeff
-}
-
-/**
- * Calculate the remainder of polynomials division
- *
- * @param  {Buffer} divident Polynomial
- * @param  {Buffer} divisor  Polynomial
- * @return {Buffer}          Remainder
- */
-exports.mod = function mod (divident, divisor) {
-  var result = BufferUtil.from(divident)
-
-  while ((result.length - divisor.length) >= 0) {
-    var coeff = result[0]
-
-    for (var i = 0; i < divisor.length; i++) {
-      result[i] ^= GF.mul(divisor[i], coeff)
-    }
-
-    // remove all zeros from buffer head
-    var offset = 0
-    while (offset < result.length && result[offset] === 0) offset++
-    result = result.slice(offset)
-  }
-
-  return result
-}
-
-/**
- * Generate an irreducible generator polynomial of specified degree
- * (used by Reed-Solomon encoder)
- *
- * @param  {Number} degree Degree of the generator polynomial
- * @return {Buffer}        Buffer containing polynomial coefficients
- */
-exports.generateECPolynomial = function generateECPolynomial (degree) {
-  var poly = BufferUtil.from([1])
-  for (var i = 0; i < degree; i++) {
-    poly = exports.mul(poly, [1, GF.exp(i)])
-  }
-
-  return poly
-}
-
-},{"../utils/buffer":28,"./galois-field":11}],17:[function(require,module,exports){
-var BufferUtil = require('../utils/buffer')
-var Utils = require('./utils')
-var ECLevel = require('./error-correction-level')
-var BitBuffer = require('./bit-buffer')
-var BitMatrix = require('./bit-matrix')
-var AlignmentPattern = require('./alignment-pattern')
-var FinderPattern = require('./finder-pattern')
-var MaskPattern = require('./mask-pattern')
-var ECCode = require('./error-correction-code')
-var ReedSolomonEncoder = require('./reed-solomon-encoder')
-var Version = require('./version')
-var FormatInfo = require('./format-info')
-var Mode = require('./mode')
-var Segments = require('./segments')
-var isArray = require('isarray')
-
-/**
- * QRCode for JavaScript
- *
- * modified by Ryan Day for nodejs support
- * Copyright (c) 2011 Ryan Day
- *
- * Licensed under the MIT license:
- *   http://www.opensource.org/licenses/mit-license.php
- *
-//---------------------------------------------------------------------
-// QRCode for JavaScript
-//
-// Copyright (c) 2009 Kazuhiko Arase
-//
-// URL: http://www.d-project.com/
-//
-// Licensed under the MIT license:
-//   http://www.opensource.org/licenses/mit-license.php
-//
-// The word "QR Code" is registered trademark of
-// DENSO WAVE INCORPORATED
-//   http://www.denso-wave.com/qrcode/faqpatent-e.html
-//
-//---------------------------------------------------------------------
-*/
-
-/**
- * Add finder patterns bits to matrix
- *
- * @param  {BitMatrix} matrix  Modules matrix
- * @param  {Number}    version QR Code version
- */
-function setupFinderPattern (matrix, version) {
-  var size = matrix.size
-  var pos = FinderPattern.getPositions(version)
-
-  for (var i = 0; i < pos.length; i++) {
-    var row = pos[i][0]
-    var col = pos[i][1]
-
-    for (var r = -1; r <= 7; r++) {
-      if (row + r <= -1 || size <= row + r) continue
-
-      for (var c = -1; c <= 7; c++) {
-        if (col + c <= -1 || size <= col + c) continue
-
-        if ((r >= 0 && r <= 6 && (c === 0 || c === 6)) ||
-          (c >= 0 && c <= 6 && (r === 0 || r === 6)) ||
-          (r >= 2 && r <= 4 && c >= 2 && c <= 4)) {
-          matrix.set(row + r, col + c, true, true)
-        } else {
-          matrix.set(row + r, col + c, false, true)
-        }
-      }
-    }
-  }
-}
-
-/**
- * Add timing pattern bits to matrix
- *
- * Note: this function must be called before {@link setupAlignmentPattern}
- *
- * @param  {BitMatrix} matrix Modules matrix
- */
-function setupTimingPattern (matrix) {
-  var size = matrix.size
-
-  for (var r = 8; r < size - 8; r++) {
-    var value = r % 2 === 0
-    matrix.set(r, 6, value, true)
-    matrix.set(6, r, value, true)
-  }
-}
-
-/**
- * Add alignment patterns bits to matrix
- *
- * Note: this function must be called after {@link setupTimingPattern}
- *
- * @param  {BitMatrix} matrix  Modules matrix
- * @param  {Number}    version QR Code version
- */
-function setupAlignmentPattern (matrix, version) {
-  var pos = AlignmentPattern.getPositions(version)
-
-  for (var i = 0; i < pos.length; i++) {
-    var row = pos[i][0]
-    var col = pos[i][1]
-
-    for (var r = -2; r <= 2; r++) {
-      for (var c = -2; c <= 2; c++) {
-        if (r === -2 || r === 2 || c === -2 || c === 2 ||
-          (r === 0 && c === 0)) {
-          matrix.set(row + r, col + c, true, true)
-        } else {
-          matrix.set(row + r, col + c, false, true)
-        }
-      }
-    }
-  }
-}
-
-/**
- * Add version info bits to matrix
- *
- * @param  {BitMatrix} matrix  Modules matrix
- * @param  {Number}    version QR Code version
- */
-function setupVersionInfo (matrix, version) {
-  var size = matrix.size
-  var bits = Version.getEncodedBits(version)
-  var row, col, mod
-
-  for (var i = 0; i < 18; i++) {
-    row = Math.floor(i / 3)
-    col = i % 3 + size - 8 - 3
-    mod = ((bits >> i) & 1) === 1
-
-    matrix.set(row, col, mod, true)
-    matrix.set(col, row, mod, true)
-  }
-}
-
-/**
- * Add format info bits to matrix
- *
- * @param  {BitMatrix} matrix               Modules matrix
- * @param  {ErrorCorrectionLevel}    errorCorrectionLevel Error correction level
- * @param  {Number}    maskPattern          Mask pattern reference value
- */
-function setupFormatInfo (matrix, errorCorrectionLevel, maskPattern) {
-  var size = matrix.size
-  var bits = FormatInfo.getEncodedBits(errorCorrectionLevel, maskPattern)
-  var i, mod
-
-  for (i = 0; i < 15; i++) {
-    mod = ((bits >> i) & 1) === 1
-
-    // vertical
-    if (i < 6) {
-      matrix.set(i, 8, mod, true)
-    } else if (i < 8) {
-      matrix.set(i + 1, 8, mod, true)
-    } else {
-      matrix.set(size - 15 + i, 8, mod, true)
-    }
-
-    // horizontal
-    if (i < 8) {
-      matrix.set(8, size - i - 1, mod, true)
-    } else if (i < 9) {
-      matrix.set(8, 15 - i - 1 + 1, mod, true)
-    } else {
-      matrix.set(8, 15 - i - 1, mod, true)
-    }
-  }
-
-  // fixed module
-  matrix.set(size - 8, 8, 1, true)
-}
-
-/**
- * Add encoded data bits to matrix
- *
- * @param  {BitMatrix} matrix Modules matrix
- * @param  {Buffer}    data   Data codewords
- */
-function setupData (matrix, data) {
-  var size = matrix.size
-  var inc = -1
-  var row = size - 1
-  var bitIndex = 7
-  var byteIndex = 0
-
-  for (var col = size - 1; col > 0; col -= 2) {
-    if (col === 6) col--
-
-    while (true) {
-      for (var c = 0; c < 2; c++) {
-        if (!matrix.isReserved(row, col - c)) {
-          var dark = false
-
-          if (byteIndex < data.length) {
-            dark = (((data[byteIndex] >>> bitIndex) & 1) === 1)
-          }
-
-          matrix.set(row, col - c, dark)
-          bitIndex--
-
-          if (bitIndex === -1) {
-            byteIndex++
-            bitIndex = 7
-          }
-        }
-      }
-
-      row += inc
-
-      if (row < 0 || size <= row) {
-        row -= inc
-        inc = -inc
-        break
-      }
-    }
-  }
-}
-
-/**
- * Create encoded codewords from data input
- *
- * @param  {Number}   version              QR Code version
- * @param  {ErrorCorrectionLevel}   errorCorrectionLevel Error correction level
- * @param  {ByteData} data                 Data input
- * @return {Buffer}                        Buffer containing encoded codewords
- */
-function createData (version, errorCorrectionLevel, segments) {
-  // Prepare data buffer
-  var buffer = new BitBuffer()
-
-  segments.forEach(function (data) {
-    // prefix data with mode indicator (4 bits)
-    buffer.put(data.mode.bit, 4)
-
-    // Prefix data with character count indicator.
-    // The character count indicator is a string of bits that represents the
-    // number of characters that are being encoded.
-    // The character count indicator must be placed after the mode indicator
-    // and must be a certain number of bits long, depending on the QR version
-    // and data mode
-    // @see {@link Mode.getCharCountIndicator}.
-    buffer.put(data.getLength(), Mode.getCharCountIndicator(data.mode, version))
-
-    // add binary data sequence to buffer
-    data.write(buffer)
-  })
-
-  // Calculate required number of bits
-  var totalCodewords = Utils.getSymbolTotalCodewords(version)
-  var ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)
-  var dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8
-
-  // Add a terminator.
-  // If the bit string is shorter than the total number of required bits,
-  // a terminator of up to four 0s must be added to the right side of the string.
-  // If the bit string is more than four bits shorter than the required number of bits,
-  // add four 0s to the end.
-  if (buffer.getLengthInBits() + 4 <= dataTotalCodewordsBits) {
-    buffer.put(0, 4)
-  }
-
-  // If the bit string is fewer than four bits shorter, add only the number of 0s that
-  // are needed to reach the required number of bits.
-
-  // After adding the terminator, if the number of bits in the string is not a multiple of 8,
-  // pad the string on the right with 0s to make the string's length a multiple of 8.
-  while (buffer.getLengthInBits() % 8 !== 0) {
-    buffer.putBit(0)
-  }
-
-  // Add pad bytes if the string is still shorter than the total number of required bits.
-  // Extend the buffer to fill the data capacity of the symbol corresponding to
-  // the Version and Error Correction Level by adding the Pad Codewords 11101100 (0xEC)
-  // and 00010001 (0x11) alternately.
-  var remainingByte = (dataTotalCodewordsBits - buffer.getLengthInBits()) / 8
-  for (var i = 0; i < remainingByte; i++) {
-    buffer.put(i % 2 ? 0x11 : 0xEC, 8)
-  }
-
-  return createCodewords(buffer, version, errorCorrectionLevel)
-}
-
-/**
- * Encode input data with Reed-Solomon and return codewords with
- * relative error correction bits
- *
- * @param  {BitBuffer} bitBuffer            Data to encode
- * @param  {Number}    version              QR Code version
- * @param  {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
- * @return {Buffer}                         Buffer containing encoded codewords
- */
-function createCodewords (bitBuffer, version, errorCorrectionLevel) {
-  // Total codewords for this QR code version (Data + Error correction)
-  var totalCodewords = Utils.getSymbolTotalCodewords(version)
-
-  // Total number of error correction codewords
-  var ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)
-
-  // Total number of data codewords
-  var dataTotalCodewords = totalCodewords - ecTotalCodewords
-
-  // Total number of blocks
-  var ecTotalBlocks = ECCode.getBlocksCount(version, errorCorrectionLevel)
-
-  // Calculate how many blocks each group should contain
-  var blocksInGroup2 = totalCodewords % ecTotalBlocks
-  var blocksInGroup1 = ecTotalBlocks - blocksInGroup2
-
-  var totalCodewordsInGroup1 = Math.floor(totalCodewords / ecTotalBlocks)
-
-  var dataCodewordsInGroup1 = Math.floor(dataTotalCodewords / ecTotalBlocks)
-  var dataCodewordsInGroup2 = dataCodewordsInGroup1 + 1
-
-  // Number of EC codewords is the same for both groups
-  var ecCount = totalCodewordsInGroup1 - dataCodewordsInGroup1
-
-  // Initialize a Reed-Solomon encoder with a generator polynomial of degree ecCount
-  var rs = new ReedSolomonEncoder(ecCount)
-
-  var offset = 0
-  var dcData = new Array(ecTotalBlocks)
-  var ecData = new Array(ecTotalBlocks)
-  var maxDataSize = 0
-  var buffer = BufferUtil.from(bitBuffer.buffer)
-
-  // Divide the buffer into the required number of blocks
-  for (var b = 0; b < ecTotalBlocks; b++) {
-    var dataSize = b < blocksInGroup1 ? dataCodewordsInGroup1 : dataCodewordsInGroup2
-
-    // extract a block of data from buffer
-    dcData[b] = buffer.slice(offset, offset + dataSize)
-
-    // Calculate EC codewords for this data block
-    ecData[b] = rs.encode(dcData[b])
-
-    offset += dataSize
-    maxDataSize = Math.max(maxDataSize, dataSize)
-  }
-
-  // Create final data
-  // Interleave the data and error correction codewords from each block
-  var data = BufferUtil.alloc(totalCodewords)
-  var index = 0
-  var i, r
-
-  // Add data codewords
-  for (i = 0; i < maxDataSize; i++) {
-    for (r = 0; r < ecTotalBlocks; r++) {
-      if (i < dcData[r].length) {
-        data[index++] = dcData[r][i]
-      }
-    }
-  }
-
-  // Apped EC codewords
-  for (i = 0; i < ecCount; i++) {
-    for (r = 0; r < ecTotalBlocks; r++) {
-      data[index++] = ecData[r][i]
-    }
-  }
-
-  return data
-}
-
-/**
- * Build QR Code symbol
- *
- * @param  {String} data                 Input string
- * @param  {Number} version              QR Code version
- * @param  {ErrorCorretionLevel} errorCorrectionLevel Error level
- * @param  {MaskPattern} maskPattern     Mask pattern
- * @return {Object}                      Object containing symbol data
- */
-function createSymbol (data, version, errorCorrectionLevel, maskPattern) {
-  var segments
-
-  if (isArray(data)) {
-    segments = Segments.fromArray(data)
-  } else if (typeof data === 'string') {
-    var estimatedVersion = version
-
-    if (!estimatedVersion) {
-      var rawSegments = Segments.rawSplit(data)
-
-      // Estimate best version that can contain raw splitted segments
-      estimatedVersion = Version.getBestVersionForData(rawSegments,
-        errorCorrectionLevel)
-    }
-
-    // Build optimized segments
-    // If estimated version is undefined, try with the highest version
-    segments = Segments.fromString(data, estimatedVersion || 40)
-  } else {
-    throw new Error('Invalid data')
-  }
-
-  // Get the min version that can contain data
-  var bestVersion = Version.getBestVersionForData(segments,
-      errorCorrectionLevel)
-
-  // If no version is found, data cannot be stored
-  if (!bestVersion) {
-    throw new Error('The amount of data is too big to be stored in a QR Code')
-  }
-
-  // If not specified, use min version as default
-  if (!version) {
-    version = bestVersion
-
-  // Check if the specified version can contain the data
-  } else if (version < bestVersion) {
-    throw new Error('\n' +
-      'The chosen QR Code version cannot contain this amount of data.\n' +
-      'Minimum version required to store current data is: ' + bestVersion + '.\n'
-    )
-  }
-
-  var dataBits = createData(version, errorCorrectionLevel, segments)
-
-  // Allocate matrix buffer
-  var moduleCount = Utils.getSymbolSize(version)
-  var modules = new BitMatrix(moduleCount)
-
-  // Add function modules
-  setupFinderPattern(modules, version)
-  setupTimingPattern(modules)
-  setupAlignmentPattern(modules, version)
-
-  // Add temporary dummy bits for format info just to set them as reserved.
-  // This is needed to prevent these bits from being masked by {@link MaskPattern.applyMask}
-  // since the masking operation must be performed only on the encoding region.
-  // These blocks will be replaced with correct values later in code.
-  setupFormatInfo(modules, errorCorrectionLevel, 0)
-
-  if (version >= 7) {
-    setupVersionInfo(modules, version)
-  }
-
-  // Add data codewords
-  setupData(modules, dataBits)
-
-  if (isNaN(maskPattern)) {
-    // Find best mask pattern
-    maskPattern = MaskPattern.getBestMask(modules,
-      setupFormatInfo.bind(null, modules, errorCorrectionLevel))
-  }
-
-  // Apply mask pattern
-  MaskPattern.applyMask(maskPattern, modules)
-
-  // Replace format info bits with correct values
-  setupFormatInfo(modules, errorCorrectionLevel, maskPattern)
-
-  return {
-    modules: modules,
-    version: version,
-    errorCorrectionLevel: errorCorrectionLevel,
-    maskPattern: maskPattern,
-    segments: segments
-  }
-}
-
-/**
- * QR Code
- *
- * @param {String | Array} data                 Input data
- * @param {Object} options                      Optional configurations
- * @param {Number} options.version              QR Code version
- * @param {String} options.errorCorrectionLevel Error correction level
- * @param {Function} options.toSJISFunc         Helper func to convert utf8 to sjis
- */
-exports.create = function create (data, options) {
-  if (typeof data === 'undefined' || data === '') {
-    throw new Error('No input text')
-  }
-
-  var errorCorrectionLevel = ECLevel.M
-  var version
-  var mask
-
-  if (typeof options !== 'undefined') {
-    // Use higher error correction level as default
-    errorCorrectionLevel = ECLevel.from(options.errorCorrectionLevel, ECLevel.M)
-    version = Version.from(options.version)
-    mask = MaskPattern.from(options.maskPattern)
-
-    if (options.toSJISFunc) {
-      Utils.setToSJISFunction(options.toSJISFunc)
-    }
-  }
-
-  return createSymbol(data, version, errorCorrectionLevel, mask)
-}
-
-},{"../utils/buffer":28,"./alignment-pattern":2,"./bit-buffer":4,"./bit-matrix":5,"./error-correction-code":7,"./error-correction-level":8,"./finder-pattern":9,"./format-info":10,"./mask-pattern":13,"./mode":14,"./reed-solomon-encoder":18,"./segments":20,"./utils":21,"./version":23,"isarray":33}],18:[function(require,module,exports){
-var BufferUtil = require('../utils/buffer')
-var Polynomial = require('./polynomial')
-var Buffer = require('buffer').Buffer
-
-function ReedSolomonEncoder (degree) {
-  this.genPoly = undefined
-  this.degree = degree
-
-  if (this.degree) this.initialize(this.degree)
-}
-
-/**
- * Initialize the encoder.
- * The input param should correspond to the number of error correction codewords.
- *
- * @param  {Number} degree
- */
-ReedSolomonEncoder.prototype.initialize = function initialize (degree) {
-  // create an irreducible generator polynomial
-  this.degree = degree
-  this.genPoly = Polynomial.generateECPolynomial(this.degree)
-}
-
-/**
- * Encodes a chunk of data
- *
- * @param  {Buffer} data Buffer containing input data
- * @return {Buffer}      Buffer containing encoded data
- */
-ReedSolomonEncoder.prototype.encode = function encode (data) {
-  if (!this.genPoly) {
-    throw new Error('Encoder not initialized')
-  }
-
-  // Calculate EC for this data block
-  // extends data size to data+genPoly size
-  var pad = BufferUtil.alloc(this.degree)
-  var paddedData = Buffer.concat([data, pad], data.length + this.degree)
-
-  // The error correction codewords are the remainder after dividing the data codewords
-  // by a generator polynomial
-  var remainder = Polynomial.mod(paddedData, this.genPoly)
-
-  // return EC data blocks (last n byte, where n is the degree of genPoly)
-  // If coefficients number in remainder are less than genPoly degree,
-  // pad with 0s to the left to reach the needed number of coefficients
-  var start = this.degree - remainder.length
-  if (start > 0) {
-    var buff = BufferUtil.alloc(this.degree)
-    remainder.copy(buff, start)
-
-    return buff
-  }
-
-  return remainder
-}
-
-module.exports = ReedSolomonEncoder
-
-},{"../utils/buffer":28,"./polynomial":16,"buffer":30}],19:[function(require,module,exports){
-var numeric = '[0-9]+'
-var alphanumeric = '[A-Z $%*+\\-./:]+'
-var kanji = '(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|' +
-  '[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|' +
-  '[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|' +
-  '[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+'
-kanji = kanji.replace(/u/g, '\\u')
-
-var byte = '(?:(?![A-Z0-9 $%*+\\-./:]|' + kanji + ')(?:.|[\r\n]))+'
-
-exports.KANJI = new RegExp(kanji, 'g')
-exports.BYTE_KANJI = new RegExp('[^A-Z0-9 $%*+\\-./:]+', 'g')
-exports.BYTE = new RegExp(byte, 'g')
-exports.NUMERIC = new RegExp(numeric, 'g')
-exports.ALPHANUMERIC = new RegExp(alphanumeric, 'g')
-
-var TEST_KANJI = new RegExp('^' + kanji + '$')
-var TEST_NUMERIC = new RegExp('^' + numeric + '$')
-var TEST_ALPHANUMERIC = new RegExp('^[A-Z0-9 $%*+\\-./:]+$')
-
-exports.testKanji = function testKanji (str) {
-  return TEST_KANJI.test(str)
-}
-
-exports.testNumeric = function testNumeric (str) {
-  return TEST_NUMERIC.test(str)
-}
-
-exports.testAlphanumeric = function testAlphanumeric (str) {
-  return TEST_ALPHANUMERIC.test(str)
-}
-
-},{}],20:[function(require,module,exports){
-var Mode = require('./mode')
-var NumericData = require('./numeric-data')
-var AlphanumericData = require('./alphanumeric-data')
-var ByteData = require('./byte-data')
-var KanjiData = require('./kanji-data')
-var Regex = require('./regex')
-var Utils = require('./utils')
-var dijkstra = require('dijkstrajs')
-
-/**
- * Returns UTF8 byte length
- *
- * @param  {String} str Input string
- * @return {Number}     Number of byte
- */
-function getStringByteLength (str) {
-  return unescape(encodeURIComponent(str)).length
-}
-
-/**
- * Get a list of segments of the specified mode
- * from a string
- *
- * @param  {Mode}   mode Segment mode
- * @param  {String} str  String to process
- * @return {Array}       Array of object with segments data
- */
-function getSegments (regex, mode, str) {
-  var segments = []
-  var result
-
-  while ((result = regex.exec(str)) !== null) {
-    segments.push({
-      data: result[0],
-      index: result.index,
-      mode: mode,
-      length: result[0].length
-    })
-  }
-
-  return segments
-}
-
-/**
- * Extracts a series of segments with the appropriate
- * modes from a string
- *
- * @param  {String} dataStr Input string
- * @return {Array}          Array of object with segments data
- */
-function getSegmentsFromString (dataStr) {
-  var numSegs = getSegments(Regex.NUMERIC, Mode.NUMERIC, dataStr)
-  var alphaNumSegs = getSegments(Regex.ALPHANUMERIC, Mode.ALPHANUMERIC, dataStr)
-  var byteSegs
-  var kanjiSegs
-
-  if (Utils.isKanjiModeEnabled()) {
-    byteSegs = getSegments(Regex.BYTE, Mode.BYTE, dataStr)
-    kanjiSegs = getSegments(Regex.KANJI, Mode.KANJI, dataStr)
-  } else {
-    byteSegs = getSegments(Regex.BYTE_KANJI, Mode.BYTE, dataStr)
-    kanjiSegs = []
-  }
-
-  var segs = numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs)
-
-  return segs
-    .sort(function (s1, s2) {
-      return s1.index - s2.index
-    })
-    .map(function (obj) {
-      return {
-        data: obj.data,
-        mode: obj.mode,
-        length: obj.length
-      }
-    })
-}
-
-/**
- * Returns how many bits are needed to encode a string of
- * specified length with the specified mode
- *
- * @param  {Number} length String length
- * @param  {Mode} mode     Segment mode
- * @return {Number}        Bit length
- */
-function getSegmentBitsLength (length, mode) {
-  switch (mode) {
-    case Mode.NUMERIC:
-      return NumericData.getBitsLength(length)
-    case Mode.ALPHANUMERIC:
-      return AlphanumericData.getBitsLength(length)
-    case Mode.KANJI:
-      return KanjiData.getBitsLength(length)
-    case Mode.BYTE:
-      return ByteData.getBitsLength(length)
-  }
-}
-
-/**
- * Merges adjacent segments which have the same mode
- *
- * @param  {Array} segs Array of object with segments data
- * @return {Array}      Array of object with segments data
- */
-function mergeSegments (segs) {
-  return segs.reduce(function (acc, curr) {
-    var prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null
-    if (prevSeg && prevSeg.mode === curr.mode) {
-      acc[acc.length - 1].data += curr.data
-      return acc
-    }
-
-    acc.push(curr)
-    return acc
-  }, [])
-}
-
-/**
- * Generates a list of all possible nodes combination which
- * will be used to build a segments graph.
- *
- * Nodes are divided by groups. Each group will contain a list of all the modes
- * in which is possible to encode the given text.
- *
- * For example the text '12345' can be encoded as Numeric, Alphanumeric or Byte.
- * The group for '12345' will contain then 3 objects, one for each
- * possible encoding mode.
- *
- * Each node represents a possible segment.
- *
- * @param  {Array} segs Array of object with segments data
- * @return {Array}      Array of object with segments data
- */
-function buildNodes (segs) {
-  var nodes = []
-  for (var i = 0; i < segs.length; i++) {
-    var seg = segs[i]
-
-    switch (seg.mode) {
-      case Mode.NUMERIC:
-        nodes.push([seg,
-          { data: seg.data, mode: Mode.ALPHANUMERIC, length: seg.length },
-          { data: seg.data, mode: Mode.BYTE, length: seg.length }
-        ])
-        break
-      case Mode.ALPHANUMERIC:
-        nodes.push([seg,
-          { data: seg.data, mode: Mode.BYTE, length: seg.length }
-        ])
-        break
-      case Mode.KANJI:
-        nodes.push([seg,
-          { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }
-        ])
-        break
-      case Mode.BYTE:
-        nodes.push([
-          { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }
-        ])
-    }
-  }
-
-  return nodes
-}
-
-/**
- * Builds a graph from a list of nodes.
- * All segments in each node group will be connected with all the segments of
- * the next group and so on.
- *
- * At each connection will be assigned a weight depending on the
- * segment's byte length.
- *
- * @param  {Array} nodes    Array of object with segments data
- * @param  {Number} version QR Code version
- * @return {Object}         Graph of all possible segments
- */
-function buildGraph (nodes, version) {
-  var table = {}
-  var graph = {'start': {}}
-  var prevNodeIds = ['start']
-
-  for (var i = 0; i < nodes.length; i++) {
-    var nodeGroup = nodes[i]
-    var currentNodeIds = []
-
-    for (var j = 0; j < nodeGroup.length; j++) {
-      var node = nodeGroup[j]
-      var key = '' + i + j
-
-      currentNodeIds.push(key)
-      table[key] = { node: node, lastCount: 0 }
-      graph[key] = {}
-
-      for (var n = 0; n < prevNodeIds.length; n++) {
-        var prevNodeId = prevNodeIds[n]
-
-        if (table[prevNodeId] && table[prevNodeId].node.mode === node.mode) {
-          graph[prevNodeId][key] =
-            getSegmentBitsLength(table[prevNodeId].lastCount + node.length, node.mode) -
-            getSegmentBitsLength(table[prevNodeId].lastCount, node.mode)
-
-          table[prevNodeId].lastCount += node.length
-        } else {
-          if (table[prevNodeId]) table[prevNodeId].lastCount = node.length
-
-          graph[prevNodeId][key] = getSegmentBitsLength(node.length, node.mode) +
-            4 + Mode.getCharCountIndicator(node.mode, version) // switch cost
-        }
-      }
-    }
-
-    prevNodeIds = currentNodeIds
-  }
-
-  for (n = 0; n < prevNodeIds.length; n++) {
-    graph[prevNodeIds[n]]['end'] = 0
-  }
-
-  return { map: graph, table: table }
-}
-
-/**
- * Builds a segment from a specified data and mode.
- * If a mode is not specified, the more suitable will be used.
- *
- * @param  {String} data             Input data
- * @param  {Mode | String} modesHint Data mode
- * @return {Segment}                 Segment
- */
-function buildSingleSegment (data, modesHint) {
-  var mode
-  var bestMode = Mode.getBestModeForData(data)
-
-  mode = Mode.from(modesHint, bestMode)
-
-  // Make sure data can be encoded
-  if (mode !== Mode.BYTE && mode.bit < bestMode.bit) {
-    throw new Error('"' + data + '"' +
-      ' cannot be encoded with mode ' + Mode.toString(mode) +
-      '.\n Suggested mode is: ' + Mode.toString(bestMode))
-  }
-
-  // Use Mode.BYTE if Kanji support is disabled
-  if (mode === Mode.KANJI && !Utils.isKanjiModeEnabled()) {
-    mode = Mode.BYTE
-  }
-
-  switch (mode) {
-    case Mode.NUMERIC:
-      return new NumericData(data)
-
-    case Mode.ALPHANUMERIC:
-      return new AlphanumericData(data)
-
-    case Mode.KANJI:
-      return new KanjiData(data)
-
-    case Mode.BYTE:
-      return new ByteData(data)
-  }
-}
-
-/**
- * Builds a list of segments from an array.
- * Array can contain Strings or Objects with segment's info.
- *
- * For each item which is a string, will be generated a segment with the given
- * string and the more appropriate encoding mode.
- *
- * For each item which is an object, will be generated a segment with the given
- * data and mode.
- * Objects must contain at least the property "data".
- * If property "mode" is not present, the more suitable mode will be used.
- *
- * @param  {Array} array Array of objects with segments data
- * @return {Array}       Array of Segments
- */
-exports.fromArray = function fromArray (array) {
-  return array.reduce(function (acc, seg) {
-    if (typeof seg === 'string') {
-      acc.push(buildSingleSegment(seg, null))
-    } else if (seg.data) {
-      acc.push(buildSingleSegment(seg.data, seg.mode))
-    }
-
-    return acc
-  }, [])
-}
-
-/**
- * Builds an optimized sequence of segments from a string,
- * which will produce the shortest possible bitstream.
- *
- * @param  {String} data    Input string
- * @param  {Number} version QR Code version
- * @return {Array}          Array of segments
- */
-exports.fromString = function fromString (data, version) {
-  var segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled())
-
-  var nodes = buildNodes(segs)
-  var graph = buildGraph(nodes, version)
-  var path = dijkstra.find_path(graph.map, 'start', 'end')
-
-  var optimizedSegs = []
-  for (var i = 1; i < path.length - 1; i++) {
-    optimizedSegs.push(graph.table[path[i]].node)
-  }
-
-  return exports.fromArray(mergeSegments(optimizedSegs))
-}
-
-/**
- * Splits a string in various segments with the modes which
- * best represent their content.
- * The produced segments are far from being optimized.
- * The output of this function is only used to estimate a QR Code version
- * which may contain the data.
- *
- * @param  {string} data Input string
- * @return {Array}       Array of segments
- */
-exports.rawSplit = function rawSplit (data) {
-  return exports.fromArray(
-    getSegmentsFromString(data, Utils.isKanjiModeEnabled())
-  )
-}
-
-},{"./alphanumeric-data":3,"./byte-data":6,"./kanji-data":12,"./mode":14,"./numeric-data":15,"./regex":19,"./utils":21,"dijkstrajs":31}],21:[function(require,module,exports){
-var toSJISFunction
-var CODEWORDS_COUNT = [
-  0, // Not used
-  26, 44, 70, 100, 134, 172, 196, 242, 292, 346,
-  404, 466, 532, 581, 655, 733, 815, 901, 991, 1085,
-  1156, 1258, 1364, 1474, 1588, 1706, 1828, 1921, 2051, 2185,
-  2323, 2465, 2611, 2761, 2876, 3034, 3196, 3362, 3532, 3706
-]
-
-/**
- * Returns the QR Code size for the specified version
- *
- * @param  {Number} version QR Code version
- * @return {Number}         size of QR code
- */
-exports.getSymbolSize = function getSymbolSize (version) {
-  if (!version) throw new Error('"version" cannot be null or undefined')
-  if (version < 1 || version > 40) throw new Error('"version" should be in range from 1 to 40')
-  return version * 4 + 17
-}
-
-/**
- * Returns the total number of codewords used to store data and EC information.
- *
- * @param  {Number} version QR Code version
- * @return {Number}         Data length in bits
- */
-exports.getSymbolTotalCodewords = function getSymbolTotalCodewords (version) {
-  return CODEWORDS_COUNT[version]
-}
-
-/**
- * Encode data with Bose-Chaudhuri-Hocquenghem
- *
- * @param  {Number} data Value to encode
- * @return {Number}      Encoded value
- */
-exports.getBCHDigit = function (data) {
-  var digit = 0
-
-  while (data !== 0) {
-    digit++
-    data >>>= 1
-  }
-
-  return digit
-}
-
-exports.setToSJISFunction = function setToSJISFunction (f) {
-  if (typeof f !== 'function') {
-    throw new Error('"toSJISFunc" is not a valid function.')
-  }
-
-  toSJISFunction = f
-}
-
-exports.isKanjiModeEnabled = function () {
-  return typeof toSJISFunction !== 'undefined'
-}
-
-exports.toSJIS = function toSJIS (kanji) {
-  return toSJISFunction(kanji)
-}
-
-},{}],22:[function(require,module,exports){
-/**
- * Check if QR Code version is valid
- *
- * @param  {Number}  version QR Code version
- * @return {Boolean}         true if valid version, false otherwise
- */
-exports.isValid = function isValid (version) {
-  return !isNaN(version) && version >= 1 && version <= 40
-}
-
-},{}],23:[function(require,module,exports){
-var Utils = require('./utils')
-var ECCode = require('./error-correction-code')
-var ECLevel = require('./error-correction-level')
-var Mode = require('./mode')
-var VersionCheck = require('./version-check')
-var isArray = require('isarray')
-
-// Generator polynomial used to encode version information
-var G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0)
-var G18_BCH = Utils.getBCHDigit(G18)
-
-function getBestVersionForDataLength (mode, length, errorCorrectionLevel) {
-  for (var currentVersion = 1; currentVersion <= 40; currentVersion++) {
-    if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, mode)) {
-      return currentVersion
-    }
-  }
-
-  return undefined
-}
-
-function getReservedBitsCount (mode, version) {
-  // Character count indicator + mode indicator bits
-  return Mode.getCharCountIndicator(mode, version) + 4
-}
-
-function getTotalBitsFromDataArray (segments, version) {
-  var totalBits = 0
-
-  segments.forEach(function (data) {
-    var reservedBits = getReservedBitsCount(data.mode, version)
-    totalBits += reservedBits + data.getBitsLength()
-  })
-
-  return totalBits
-}
-
-function getBestVersionForMixedData (segments, errorCorrectionLevel) {
-  for (var currentVersion = 1; currentVersion <= 40; currentVersion++) {
-    var length = getTotalBitsFromDataArray(segments, currentVersion)
-    if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, Mode.MIXED)) {
-      return currentVersion
-    }
-  }
-
-  return undefined
-}
-
-/**
- * Returns version number from a value.
- * If value is not a valid version, returns defaultValue
- *
- * @param  {Number|String} value        QR Code version
- * @param  {Number}        defaultValue Fallback value
- * @return {Number}                     QR Code version number
- */
-exports.from = function from (value, defaultValue) {
-  if (VersionCheck.isValid(value)) {
-    return parseInt(value, 10)
-  }
-
-  return defaultValue
-}
-
-/**
- * Returns how much data can be stored with the specified QR code version
- * and error correction level
- *
- * @param  {Number} version              QR Code version (1-40)
- * @param  {Number} errorCorrectionLevel Error correction level
- * @param  {Mode}   mode                 Data mode
- * @return {Number}                      Quantity of storable data
- */
-exports.getCapacity = function getCapacity (version, errorCorrectionLevel, mode) {
-  if (!VersionCheck.isValid(version)) {
-    throw new Error('Invalid QR Code version')
-  }
-
-  // Use Byte mode as default
-  if (typeof mode === 'undefined') mode = Mode.BYTE
-
-  // Total codewords for this QR code version (Data + Error correction)
-  var totalCodewords = Utils.getSymbolTotalCodewords(version)
-
-  // Total number of error correction codewords
-  var ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)
-
-  // Total number of data codewords
-  var dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8
-
-  if (mode === Mode.MIXED) return dataTotalCodewordsBits
-
-  var usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode, version)
-
-  // Return max number of storable codewords
-  switch (mode) {
-    case Mode.NUMERIC:
-      return Math.floor((usableBits / 10) * 3)
-
-    case Mode.ALPHANUMERIC:
-      return Math.floor((usableBits / 11) * 2)
-
-    case Mode.KANJI:
-      return Math.floor(usableBits / 13)
-
-    case Mode.BYTE:
-    default:
-      return Math.floor(usableBits / 8)
-  }
-}
-
-/**
- * Returns the minimum version needed to contain the amount of data
- *
- * @param  {Segment} data                    Segment of data
- * @param  {Number} [errorCorrectionLevel=H] Error correction level
- * @param  {Mode} mode                       Data mode
- * @return {Number}                          QR Code version
- */
-exports.getBestVersionForData = function getBestVersionForData (data, errorCorrectionLevel) {
-  var seg
-
-  var ecl = ECLevel.from(errorCorrectionLevel, ECLevel.M)
-
-  if (isArray(data)) {
-    if (data.length > 1) {
-      return getBestVersionForMixedData(data, ecl)
-    }
-
-    if (data.length === 0) {
-      return 1
-    }
-
-    seg = data[0]
-  } else {
-    seg = data
-  }
-
-  return getBestVersionForDataLength(seg.mode, seg.getLength(), ecl)
-}
-
-/**
- * Returns version information with relative error correction bits
- *
- * The version information is included in QR Code symbols of version 7 or larger.
- * It consists of an 18-bit sequence containing 6 data bits,
- * with 12 error correction bits calculated using the (18, 6) Golay code.
- *
- * @param  {Number} version QR Code version
- * @return {Number}         Encoded version info bits
- */
-exports.getEncodedBits = function getEncodedBits (version) {
-  if (!VersionCheck.isValid(version) || version < 7) {
-    throw new Error('Invalid QR Code version')
-  }
-
-  var d = version << 12
-
-  while (Utils.getBCHDigit(d) - G18_BCH >= 0) {
-    d ^= (G18 << (Utils.getBCHDigit(d) - G18_BCH))
-  }
-
-  return (version << 12) | d
-}
-
-},{"./error-correction-code":7,"./error-correction-level":8,"./mode":14,"./utils":21,"./version-check":22,"isarray":33}],24:[function(require,module,exports){
-
-var canPromise = require('./can-promise')
-
-var QRCode = require('./core/qrcode')
-var CanvasRenderer = require('./renderer/canvas')
-var SvgRenderer = require('./renderer/svg-tag.js')
-
-function renderCanvas (renderFunc, canvas, text, opts, cb) {
-  var args = [].slice.call(arguments, 1)
-  var argsNum = args.length
-  var isLastArgCb = typeof args[argsNum - 1] === 'function'
-
-  if (!isLastArgCb && !canPromise()) {
-    throw new Error('Callback required as last argument')
-  }
-
-  if (isLastArgCb) {
-    if (argsNum < 2) {
-      throw new Error('Too few arguments provided')
-    }
-
-    if (argsNum === 2) {
-      cb = text
-      text = canvas
-      canvas = opts = undefined
-    } else if (argsNum === 3) {
-      if (canvas.getContext && typeof cb === 'undefined') {
-        cb = opts
-        opts = undefined
-      } else {
-        cb = opts
-        opts = text
-        text = canvas
-        canvas = undefined
-      }
-    }
-  } else {
-    if (argsNum < 1) {
-      throw new Error('Too few arguments provided')
-    }
-
-    if (argsNum === 1) {
-      text = canvas
-      canvas = opts = undefined
-    } else if (argsNum === 2 && !canvas.getContext) {
-      opts = text
-      text = canvas
-      canvas = undefined
-    }
-
-    return new Promise(function (resolve, reject) {
-      try {
-        var data = QRCode.create(text, opts)
-        resolve(renderFunc(data, canvas, opts))
-      } catch (e) {
-        reject(e)
-      }
-    })
-  }
-
-  try {
-    var data = QRCode.create(text, opts)
-    cb(null, renderFunc(data, canvas, opts))
-  } catch (e) {
-    cb(e)
-  }
-}
-
-exports.create = QRCode.create
-exports.toCanvas = renderCanvas.bind(null, CanvasRenderer.render)
-exports.toDataURL = renderCanvas.bind(null, CanvasRenderer.renderToDataURL)
-
-// only svg for now.
-exports.toString = renderCanvas.bind(null, function (data, _, opts) {
-  return SvgRenderer.render(data, opts)
-})
-
-},{"./can-promise":1,"./core/qrcode":17,"./renderer/canvas":25,"./renderer/svg-tag.js":26}],25:[function(require,module,exports){
-var Utils = require('./utils')
-
-function clearCanvas (ctx, canvas, size) {
-  ctx.clearRect(0, 0, canvas.width, canvas.height)
-
-  if (!canvas.style) canvas.style = {}
-  canvas.height = size
-  canvas.width = size
-  canvas.style.height = size + 'px'
-  canvas.style.width = size + 'px'
-}
-
-function getCanvasElement () {
-  try {
-    return document.createElement('canvas')
-  } catch (e) {
-    throw new Error('You need to specify a canvas element')
-  }
-}
-
-exports.render = function render (qrData, canvas, options) {
-  var opts = options
-  var canvasEl = canvas
-
-  if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {
-    opts = canvas
-    canvas = undefined
-  }
-
-  if (!canvas) {
-    canvasEl = getCanvasElement()
-  }
-
-  opts = Utils.getOptions(opts)
-  var size = Utils.getImageWidth(qrData.modules.size, opts)
-
-  var ctx = canvasEl.getContext('2d')
-  var image = ctx.createImageData(size, size)
-  Utils.qrToImageData(image.data, qrData, opts)
-
-  clearCanvas(ctx, canvasEl, size)
-  ctx.putImageData(image, 0, 0)
-
-  return canvasEl
-}
-
-exports.renderToDataURL = function renderToDataURL (qrData, canvas, options) {
-  var opts = options
-
-  if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {
-    opts = canvas
-    canvas = undefined
-  }
-
-  if (!opts) opts = {}
-
-  var canvasEl = exports.render(qrData, canvas, opts)
-
-  var type = opts.type || 'image/png'
-  var rendererOpts = opts.rendererOpts || {}
-
-  return canvasEl.toDataURL(type, rendererOpts.quality)
-}
-
-},{"./utils":27}],26:[function(require,module,exports){
-var Utils = require('./utils')
-
-function getColorAttrib (color, attrib) {
-  var alpha = color.a / 255
-  var str = attrib + '="' + color.hex + '"'
-
-  return alpha < 1
-    ? str + ' ' + attrib + '-opacity="' + alpha.toFixed(2).slice(1) + '"'
-    : str
-}
-
-function svgCmd (cmd, x, y) {
-  var str = cmd + x
-  if (typeof y !== 'undefined') str += ' ' + y
-
-  return str
-}
-
-function qrToPath (data, size, margin) {
-  var path = ''
-  var moveBy = 0
-  var newRow = false
-  var lineLength = 0
-
-  for (var i = 0; i < data.length; i++) {
-    var col = Math.floor(i % size)
-    var row = Math.floor(i / size)
-
-    if (!col && !newRow) newRow = true
-
-    if (data[i]) {
-      lineLength++
-
-      if (!(i > 0 && col > 0 && data[i - 1])) {
-        path += newRow
-          ? svgCmd('M', col + margin, 0.5 + row + margin)
-          : svgCmd('m', moveBy, 0)
-
-        moveBy = 0
-        newRow = false
-      }
-
-      if (!(col + 1 < size && data[i + 1])) {
-        path += svgCmd('h', lineLength)
-        lineLength = 0
-      }
-    } else {
-      moveBy++
-    }
-  }
-
-  return path
-}
-
-exports.render = function render (qrData, options, cb) {
-  var opts = Utils.getOptions(options)
-  var size = qrData.modules.size
-  var data = qrData.modules.data
-  var qrcodesize = size + opts.margin * 2
-
-  var bg = !opts.color.light.a
-    ? ''
-    : '<path ' + getColorAttrib(opts.color.light, 'fill') +
-      ' d="M0 0h' + qrcodesize + 'v' + qrcodesize + 'H0z"/>'
-
-  var path =
-    '<path ' + getColorAttrib(opts.color.dark, 'stroke') +
-    ' d="' + qrToPath(data, size, opts.margin) + '"/>'
-
-  var viewBox = 'viewBox="' + '0 0 ' + qrcodesize + ' ' + qrcodesize + '"'
-
-  var width = !opts.width ? '' : 'width="' + opts.width + '" height="' + opts.width + '" '
-
-  var svgTag = '<svg xmlns="http://www.w3.org/2000/svg" ' + width + viewBox + ' shape-rendering="crispEdges">' + bg + path + '</svg>\n'
-
-  if (typeof cb === 'function') {
-    cb(null, svgTag)
-  }
-
-  return svgTag
-}
-
-},{"./utils":27}],27:[function(require,module,exports){
-function hex2rgba (hex) {
-  if (typeof hex === 'number') {
-    hex = hex.toString()
-  }
-
-  if (typeof hex !== 'string') {
-    throw new Error('Color should be defined as hex string')
-  }
-
-  var hexCode = hex.slice().replace('#', '').split('')
-  if (hexCode.length < 3 || hexCode.length === 5 || hexCode.length > 8) {
-    throw new Error('Invalid hex color: ' + hex)
-  }
-
-  // Convert from short to long form (fff -> ffffff)
-  if (hexCode.length === 3 || hexCode.length === 4) {
-    hexCode = Array.prototype.concat.apply([], hexCode.map(function (c) {
-      return [c, c]
-    }))
-  }
-
-  // Add default alpha value
-  if (hexCode.length === 6) hexCode.push('F', 'F')
-
-  var hexValue = parseInt(hexCode.join(''), 16)
-
-  return {
-    r: (hexValue >> 24) & 255,
-    g: (hexValue >> 16) & 255,
-    b: (hexValue >> 8) & 255,
-    a: hexValue & 255,
-    hex: '#' + hexCode.slice(0, 6).join('')
-  }
-}
-
-exports.getOptions = function getOptions (options) {
-  if (!options) options = {}
-  if (!options.color) options.color = {}
-
-  var margin = typeof options.margin === 'undefined' ||
-    options.margin === null ||
-    options.margin < 0 ? 4 : options.margin
-
-  var width = options.width && options.width >= 21 ? options.width : undefined
-  var scale = options.scale || 4
-
-  return {
-    width: width,
-    scale: width ? 4 : scale,
-    margin: margin,
-    color: {
-      dark: hex2rgba(options.color.dark || '#000000ff'),
-      light: hex2rgba(options.color.light || '#ffffffff')
-    },
-    type: options.type,
-    rendererOpts: options.rendererOpts || {}
-  }
-}
-
-exports.getScale = function getScale (qrSize, opts) {
-  return opts.width && opts.width >= qrSize + opts.margin * 2
-    ? opts.width / (qrSize + opts.margin * 2)
-    : opts.scale
-}
-
-exports.getImageWidth = function getImageWidth (qrSize, opts) {
-  var scale = exports.getScale(qrSize, opts)
-  return Math.floor((qrSize + opts.margin * 2) * scale)
-}
-
-exports.qrToImageData = function qrToImageData (imgData, qr, opts) {
-  var size = qr.modules.size
-  var data = qr.modules.data
-  var scale = exports.getScale(size, opts)
-  var symbolSize = Math.floor((size + opts.margin * 2) * scale)
-  var scaledMargin = opts.margin * scale
-  var palette = [opts.color.light, opts.color.dark]
-
-  for (var i = 0; i < symbolSize; i++) {
-    for (var j = 0; j < symbolSize; j++) {
-      var posDst = (i * symbolSize + j) * 4
-      var pxColor = opts.color.light
-
-      if (i >= scaledMargin && j >= scaledMargin &&
-        i < symbolSize - scaledMargin && j < symbolSize - scaledMargin) {
-        var iSrc = Math.floor((i - scaledMargin) / scale)
-        var jSrc = Math.floor((j - scaledMargin) / scale)
-        pxColor = palette[data[iSrc * size + jSrc] ? 1 : 0]
-      }
-
-      imgData[posDst++] = pxColor.r
-      imgData[posDst++] = pxColor.g
-      imgData[posDst++] = pxColor.b
-      imgData[posDst] = pxColor.a
-    }
-  }
-}
-
-},{}],28:[function(require,module,exports){
-/**
- * Implementation of a subset of node.js Buffer methods for the browser.
- * Based on https://github.com/feross/buffer
- */
-
-/* eslint-disable no-proto */
-
-'use strict'
-
-var isArray = require('isarray')
-
-function typedArraySupport () {
-  // Can typed array instances 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
-  }
-}
-
-Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
-
-var K_MAX_LENGTH = Buffer.TYPED_ARRAY_SUPPORT
-    ? 0x7fffffff
-    : 0x3fffffff
-
-function Buffer (arg, offset, length) {
-  if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
-    return new Buffer(arg, offset, length)
-  }
-
-  if (typeof arg === 'number') {
-    return allocUnsafe(this, arg)
-  }
-
-  return from(this, arg, offset, length)
-}
-
-if (Buffer.TYPED_ARRAY_SUPPORT) {
-  Buffer.prototype.__proto__ = Uint8Array.prototype
-  Buffer.__proto__ = Uint8Array
-
-  // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
-  if (typeof Symbol !== 'undefined' && Symbol.species &&
-      Buffer[Symbol.species] === Buffer) {
-    Object.defineProperty(Buffer, Symbol.species, {
-      value: null,
-      configurable: true,
-      enumerable: false,
-      writable: false
-    })
-  }
-}
-
-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 isnan (val) {
-  return val !== val // eslint-disable-line no-self-compare
-}
-
-function createBuffer (that, length) {
-  var buf
-  if (Buffer.TYPED_ARRAY_SUPPORT) {
-    buf = new Uint8Array(length)
-    buf.__proto__ = Buffer.prototype
-  } else {
-    // Fallback: Return an object instance of the Buffer class
-    buf = that
-    if (buf === null) {
-      buf = new Buffer(length)
-    }
-    buf.length = length
-  }
-
-  return buf
-}
-
-function allocUnsafe (that, size) {
-  var buf = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
-
-  if (!Buffer.TYPED_ARRAY_SUPPORT) {
-    for (var i = 0; i < size; ++i) {
-      buf[i] = 0
-    }
-  }
-
-  return buf
-}
-
-function fromString (that, string) {
-  var length = byteLength(string) | 0
-  var buf = createBuffer(that, length)
-
-  var actual = buf.write(string)
-
-  if (actual !== length) {
-    // Writing a hex string, for example, that contains invalid characters will
-    // cause everything after the first invalid character to be ignored. (e.g.
-    // 'abxxcd' will be treated as 'ab')
-    buf = buf.slice(0, actual)
-  }
-
-  return buf
-}
-
-function fromArrayLike (that, array) {
-  var length = array.length < 0 ? 0 : checked(array.length) | 0
-  var buf = createBuffer(that, length)
-  for (var i = 0; i < length; i += 1) {
-    buf[i] = array[i] & 255
-  }
-  return buf
-}
-
-function fromArrayBuffer (that, array, byteOffset, length) {
-  if (byteOffset < 0 || array.byteLength < byteOffset) {
-    throw new RangeError('\'offset\' is out of bounds')
-  }
-
-  if (array.byteLength < byteOffset + (length || 0)) {
-    throw new RangeError('\'length\' is out of bounds')
-  }
-
-  var buf
-  if (byteOffset === undefined && length === undefined) {
-    buf = new Uint8Array(array)
-  } else if (length === undefined) {
-    buf = new Uint8Array(array, byteOffset)
-  } else {
-    buf = new Uint8Array(array, byteOffset, length)
-  }
-
-  if (Buffer.TYPED_ARRAY_SUPPORT) {
-    // Return an augmented `Uint8Array` instance, for best performance
-    buf.__proto__ = Buffer.prototype
-  } else {
-    // Fallback: Return an object instance of the Buffer class
-    buf = fromArrayLike(that, buf)
-  }
-
-  return buf
-}
-
-function fromObject (that, obj) {
-  if (Buffer.isBuffer(obj)) {
-    var len = checked(obj.length) | 0
-    var buf = createBuffer(that, len)
-
-    if (buf.length === 0) {
-      return buf
-    }
-
-    obj.copy(buf, 0, 0, len)
-    return buf
-  }
-
-  if (obj) {
-    if ((typeof ArrayBuffer !== 'undefined' &&
-        obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
-      if (typeof obj.length !== 'number' || isnan(obj.length)) {
-        return createBuffer(that, 0)
-      }
-      return fromArrayLike(that, obj)
-    }
-
-    if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
-      return fromArrayLike(that, obj.data)
-    }
-  }
-
-  throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
-}
-
-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 byteLength (string) {
-  if (Buffer.isBuffer(string)) {
-    return string.length
-  }
-  if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
-      (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
-    return string.byteLength
-  }
-  if (typeof string !== 'string') {
-    string = '' + string
-  }
-
-  var len = string.length
-  if (len === 0) return 0
-
-  return utf8ToBytes(string).length
-}
-
-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 utf8Write (buf, string, offset, length) {
-  return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
-}
-
-function from (that, value, offset, length) {
-  if (typeof value === 'number') {
-    throw new TypeError('"value" argument must not be a number')
-  }
-
-  if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
-    return fromArrayBuffer(that, value, offset, length)
-  }
-
-  if (typeof value === 'string') {
-    return fromString(that, value, offset)
-  }
-
-  return fromObject(that, value)
-}
-
-Buffer.prototype.write = function write (string, offset, length) {
-  // Buffer#write(string)
-  if (offset === undefined) {
-    length = this.length
-    offset = 0
-  // Buffer#write(string, encoding)
-  } else if (length === undefined && typeof offset === 'string') {
-    length = this.length
-    offset = 0
-  // Buffer#write(string, offset[, length])
-  } else if (isFinite(offset)) {
-    offset = offset | 0
-    if (isFinite(length)) {
-      length = length | 0
-    } else {
-      length = undefined
-    }
-  }
-
-  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')
-  }
-
-  return utf8Write(this, string, offset, length)
-}
-
-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
-  if (Buffer.TYPED_ARRAY_SUPPORT) {
-    newBuf = this.subarray(start, end)
-    // Return an augmented `Uint8Array` instance
-    newBuf.__proto__ = Buffer.prototype
-  } else {
-    var sliceLen = end - start
-    newBuf = new Buffer(sliceLen, undefined)
-    for (var i = 0; i < sliceLen; ++i) {
-      newBuf[i] = this[i + start]
-    }
-  }
-
-  return newBuf
-}
-
-Buffer.prototype.copy = function copy (target, targetStart, start, end) {
-  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('sourceStart out of bounds')
-  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
-  var i
-
-  if (this === target && start < targetStart && targetStart < end) {
-    // descending copy from end
-    for (i = len - 1; i >= 0; --i) {
-      target[i + targetStart] = this[i + start]
-    }
-  } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
-    // ascending copy from start
-    for (i = 0; i < len; ++i) {
-      target[i + targetStart] = this[i + start]
-    }
-  } else {
-    Uint8Array.prototype.set.call(
-      target,
-      this.subarray(start, start + len),
-      targetStart
-    )
-  }
-
-  return len
-}
-
-Buffer.prototype.fill = function fill (val, start, end) {
-  // Handle string cases:
-  if (typeof val === 'string') {
-    if (typeof start === 'string') {
-      start = 0
-      end = this.length
-    } else if (typeof end === 'string') {
-      end = this.length
-    }
-    if (val.length === 1) {
-      var code = val.charCodeAt(0)
-      if (code < 256) {
-        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
-      : new Buffer(val)
-    var len = bytes.length
-    for (i = 0; i < end - start; ++i) {
-      this[i + start] = bytes[i % len]
-    }
-  }
-
-  return this
-}
-
-Buffer.concat = function concat (list, length) {
-  if (!isArray(list)) {
-    throw new TypeError('"list" argument must be an Array of Buffers')
-  }
-
-  if (list.length === 0) {
-    return createBuffer(null, 0)
-  }
-
-  var i
-  if (length === undefined) {
-    length = 0
-    for (i = 0; i < list.length; ++i) {
-      length += list[i].length
-    }
-  }
-
-  var buffer = allocUnsafe(null, length)
-  var pos = 0
-  for (i = 0; i < list.length; ++i) {
-    var buf = list[i]
-    if (!Buffer.isBuffer(buf)) {
-      throw new TypeError('"list" argument must be an Array of Buffers')
-    }
-    buf.copy(buffer, pos)
-    pos += buf.length
-  }
-  return buffer
-}
-
-Buffer.byteLength = byteLength
-
-Buffer.prototype._isBuffer = true
-Buffer.isBuffer = function isBuffer (b) {
-  return !!(b != null && b._isBuffer)
-}
-
-module.exports.alloc = function (size) {
-  var buffer = new Buffer(size)
-  buffer.fill(0)
-  return buffer
-}
-
-module.exports.from = function (data) {
-  return new Buffer(data)
-}
-
-},{"isarray":33}],29:[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')
-  }
-
-  // Trim off extra bytes after placeholder bytes are found
-  // See: https://github.com/beatgammit/base64-js/issues/42
-  var validLen = b64.indexOf('=')
-  if (validLen === -1) validLen = len
-
-  var placeHoldersLen = validLen === len
-    ? 0
-    : 4 - (validLen % 4)
-
-  return [validLen, placeHoldersLen]
-}
-
-// base64 is 4/3 + up to two characters of the original data
-function byteLength (b64) {
-  var lens = getLens(b64)
-  var validLen = lens[0]
-  var placeHoldersLen = lens[1]
-  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
-}
-
-function _byteLength (b64, validLen, placeHoldersLen) {
-  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
-}
-
-function toByteArray (b64) {
-  var tmp
-  var lens = getLens(b64)
-  var validLen = lens[0]
-  var placeHoldersLen = lens[1]
-
-  var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
-
-  var curByte = 0
-
-  // if there are placeholders, only get up to the last complete 4 chars
-  var len = placeHoldersLen > 0
-    ? validLen - 4
-    : validLen
-
-  var i
-  for (i = 0; i < len; i += 4) {
-    tmp =
-      (revLookup[b64.charCodeAt(i)] << 18) |
-      (revLookup[b64.charCodeAt(i + 1)] << 12) |
-      (revLookup[b64.charCodeAt(i + 2)] << 6) |
-      revLookup[b64.charCodeAt(i + 3)]
-    arr[curByte++] = (tmp >> 16) & 0xFF
-    arr[curByte++] = (tmp >> 8) & 0xFF
-    arr[curByte++] = tmp & 0xFF
-  }
-
-  if (placeHoldersLen === 2) {
-    tmp =
-      (revLookup[b64.charCodeAt(i)] << 2) |
-      (revLookup[b64.charCodeAt(i + 1)] >> 4)
-    arr[curByte++] = tmp & 0xFF
-  }
-
-  if (placeHoldersLen === 1) {
-    tmp =
-      (revLookup[b64.charCodeAt(i)] << 10) |
-      (revLookup[b64.charCodeAt(i + 1)] << 4) |
-      (revLookup[b64.charCodeAt(i + 2)] >> 2)
-    arr[curByte++] = (tmp >> 8) & 0xFF
-    arr[curByte++] = tmp & 0xFF
-  }
-
-  return arr
-}
-
-function tripletToBase64 (num) {
-  return lookup[num >> 18 & 0x3F] +
-    lookup[num >> 12 & 0x3F] +
-    lookup[num >> 6 & 0x3F] +
-    lookup[num & 0x3F]
-}
-
-function encodeChunk (uint8, start, end) {
-  var tmp
-  var output = []
-  for (var i = start; i < end; i += 3) {
-    tmp =
-      ((uint8[i] << 16) & 0xFF0000) +
-      ((uint8[i + 1] << 8) & 0xFF00) +
-      (uint8[i + 2] & 0xFF)
-    output.push(tripletToBase64(tmp))
-  }
-  return output.join('')
-}
-
-function fromByteArray (uint8) {
-  var tmp
-  var len = uint8.length
-  var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
-  var parts = []
-  var maxChunkLength = 16383 // must be multiple of 3
-
-  // go through the array every three bytes, we'll deal with trailing stuff later
-  for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
-    parts.push(encodeChunk(
-      uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
-    ))
-  }
-
-  // pad the end with zeros, but make sure to not forget the extra bytes
-  if (extraBytes === 1) {
-    tmp = uint8[len - 1]
-    parts.push(
-      lookup[tmp >> 2] +
-      lookup[(tmp << 4) & 0x3F] +
-      '=='
-    )
-  } else if (extraBytes === 2) {
-    tmp = (uint8[len - 2] << 8) + uint8[len - 1]
-    parts.push(
-      lookup[tmp >> 10] +
-      lookup[(tmp >> 4) & 0x3F] +
-      lookup[(tmp << 2) & 0x3F] +
-      '='
-    )
-  }
-
-  return parts.join('')
-}
-
-},{}],30:[function(require,module,exports){
+!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).QRCode=t()}}((function(){return function t(r,e,n){function o(u,a){if(!e[u]){if(!r[u]){var f="function"==typeof require&&require;if(!a&&f)return f(u,!0);if(i)return i(u,!0);var s=new Error("Cannot find module '"+u+"'");throw s.code="MODULE_NOT_FOUND",s}var h=e[u]={exports:{}};r[u][0].call(h.exports,(function(t){return o(r[u][1][t]||t)}),h,h.exports,t,r,e,n)}return e[u].exports}for(var i="function"==typeof require&&require,u=0;u<n.length;u++)o(n[u]);return o}({1:[function(t,r,e){r.exports=function(){return"function"==typeof Promise&&Promise.prototype&&Promise.prototype.then}},{}],2:[function(t,r,e){var n=t("./utils").getSymbolSize;e.getRowColCoords=function(t){if(1===t)return[];for(var r=Math.floor(t/7)+2,e=n(t),o=145===e?26:2*Math.ceil((e-13)/(2*r-2)),i=[e-7],u=1;u<r-1;u++)i[u]=i[u-1]-o;return i.push(6),i.reverse()},e.getPositions=function(t){for(var r=[],n=e.getRowColCoords(t),o=n.length,i=0;i<o;i++)for(var u=0;u<o;u++)0===i&&0===u||0===i&&u===o-1||i===o-1&&0===u||r.push([n[i],n[u]]);return r}},{"./utils":21}],3:[function(t,r,e){var n=t("./mode"),o=["0","1","2","3","4","5","6","7","8","9","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"," ","$","%","*","+","-",".","/",":"];function i(t){this.mode=n.ALPHANUMERIC,this.data=t}i.getBitsLength=function(t){return 11*Math.floor(t/2)+t%2*6},i.prototype.getLength=function(){return this.data.length},i.prototype.getBitsLength=function(){return i.getBitsLength(this.data.length)},i.prototype.write=function(t){var r;for(r=0;r+2<=this.data.length;r+=2){var e=45*o.indexOf(this.data[r]);e+=o.indexOf(this.data[r+1]),t.put(e,11)}this.data.length%2&&t.put(o.indexOf(this.data[r]),6)},r.exports=i},{"./mode":14}],4:[function(t,r,e){function n(){this.buffer=[],this.length=0}n.prototype={get:function(t){var r=Math.floor(t/8);return 1==(this.buffer[r]>>>7-t%8&1)},put:function(t,r){for(var e=0;e<r;e++)this.putBit(1==(t>>>r-e-1&1))},getLengthInBits:function(){return this.length},putBit:function(t){var r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),t&&(this.buffer[r]|=128>>>this.length%8),this.length++}},r.exports=n},{}],5:[function(t,r,e){var n=t("../utils/buffer");function o(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=n.alloc(t*t),this.reservedBit=n.alloc(t*t)}o.prototype.set=function(t,r,e,n){var o=t*this.size+r;this.data[o]=e,n&&(this.reservedBit[o]=!0)},o.prototype.get=function(t,r){return this.data[t*this.size+r]},o.prototype.xor=function(t,r,e){this.data[t*this.size+r]^=e},o.prototype.isReserved=function(t,r){return this.reservedBit[t*this.size+r]},r.exports=o},{"../utils/buffer":28}],6:[function(t,r,e){var n=t("../utils/buffer"),o=t("./mode");function i(t){this.mode=o.BYTE,this.data=n.from(t)}i.getBitsLength=function(t){return 8*t},i.prototype.getLength=function(){return this.data.length},i.prototype.getBitsLength=function(){return i.getBitsLength(this.data.length)},i.prototype.write=function(t){for(var r=0,e=this.data.length;r<e;r++)t.put(this.data[r],8)},r.exports=i},{"../utils/buffer":28,"./mode":14}],7:[function(t,r,e){var n=t("./error-correction-level"),o=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],i=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];e.getBlocksCount=function(t,r){switch(r){case n.L:return o[4*(t-1)+0];case n.M:return o[4*(t-1)+1];case n.Q:return o[4*(t-1)+2];case n.H:return o[4*(t-1)+3];default:return}},e.getTotalCodewordsCount=function(t,r){switch(r){case n.L:return i[4*(t-1)+0];case n.M:return i[4*(t-1)+1];case n.Q:return i[4*(t-1)+2];case n.H:return i[4*(t-1)+3];default:return}}},{"./error-correction-level":8}],8:[function(t,r,e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2},e.isValid=function(t){return t&&void 0!==t.bit&&t.bit>=0&&t.bit<4},e.from=function(t,r){if(e.isValid(t))return t;try{return function(t){if("string"!=typeof t)throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+t)}}(t)}catch(t){return r}}},{}],9:[function(t,r,e){var n=t("./utils").getSymbolSize;e.getPositions=function(t){var r=n(t);return[[0,0],[r-7,0],[0,r-7]]}},{"./utils":21}],10:[function(t,r,e){var n=t("./utils"),o=n.getBCHDigit(1335);e.getEncodedBits=function(t,r){for(var e=t.bit<<3|r,i=e<<10;n.getBCHDigit(i)-o>=0;)i^=1335<<n.getBCHDigit(i)-o;return 21522^(e<<10|i)}},{"./utils":21}],11:[function(t,r,e){var n=t("../utils/buffer"),o=n.alloc(512),i=n.alloc(256);!function(){for(var t=1,r=0;r<255;r++)o[r]=t,i[t]=r,256&(t<<=1)&&(t^=285);for(r=255;r<512;r++)o[r]=o[r-255]}(),e.log=function(t){if(t<1)throw new Error("log("+t+")");return i[t]},e.exp=function(t){return o[t]},e.mul=function(t,r){return 0===t||0===r?0:o[i[t]+i[r]]}},{"../utils/buffer":28}],12:[function(t,r,e){var n=t("./mode"),o=t("./utils");function i(t){this.mode=n.KANJI,this.data=t}i.getBitsLength=function(t){return 13*t},i.prototype.getLength=function(){return this.data.length},i.prototype.getBitsLength=function(){return i.getBitsLength(this.data.length)},i.prototype.write=function(t){var r;for(r=0;r<this.data.length;r++){var e=o.toSJIS(this.data[r]);if(e>=33088&&e<=40956)e-=33088;else{if(!(e>=57408&&e<=60351))throw new Error("Invalid SJIS character: "+this.data[r]+"\nMake sure your charset is UTF-8");e-=49472}e=192*(e>>>8&255)+(255&e),t.put(e,13)}},r.exports=i},{"./mode":14,"./utils":21}],13:[function(t,r,e){e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var n=3,o=3,i=40,u=10;function a(t,r,n){switch(t){case e.Patterns.PATTERN000:return(r+n)%2==0;case e.Patterns.PATTERN001:return r%2==0;case e.Patterns.PATTERN010:return n%3==0;case e.Patterns.PATTERN011:return(r+n)%3==0;case e.Patterns.PATTERN100:return(Math.floor(r/2)+Math.floor(n/3))%2==0;case e.Patterns.PATTERN101:return r*n%2+r*n%3==0;case e.Patterns.PATTERN110:return(r*n%2+r*n%3)%2==0;case e.Patterns.PATTERN111:return(r*n%3+(r+n)%2)%2==0;default:throw new Error("bad maskPattern:"+t)}}e.isValid=function(t){return null!=t&&""!==t&&!isNaN(t)&&t>=0&&t<=7},e.from=function(t){return e.isValid(t)?parseInt(t,10):void 0},e.getPenaltyN1=function(t){for(var r=t.size,e=0,o=0,i=0,u=null,a=null,f=0;f<r;f++){o=i=0,u=a=null;for(var s=0;s<r;s++){var h=t.get(f,s);h===u?o++:(o>=5&&(e+=n+(o-5)),u=h,o=1),(h=t.get(s,f))===a?i++:(i>=5&&(e+=n+(i-5)),a=h,i=1)}o>=5&&(e+=n+(o-5)),i>=5&&(e+=n+(i-5))}return e},e.getPenaltyN2=function(t){for(var r=t.size,e=0,n=0;n<r-1;n++)for(var i=0;i<r-1;i++){var u=t.get(n,i)+t.get(n,i+1)+t.get(n+1,i)+t.get(n+1,i+1);4!==u&&0!==u||e++}return e*o},e.getPenaltyN3=function(t){for(var r=t.size,e=0,n=0,o=0,u=0;u<r;u++){n=o=0;for(var a=0;a<r;a++)n=n<<1&2047|t.get(u,a),a>=10&&(1488===n||93===n)&&e++,o=o<<1&2047|t.get(a,u),a>=10&&(1488===o||93===o)&&e++}return e*i},e.getPenaltyN4=function(t){for(var r=0,e=t.data.length,n=0;n<e;n++)r+=t.data[n];return Math.abs(Math.ceil(100*r/e/5)-10)*u},e.applyMask=function(t,r){for(var e=r.size,n=0;n<e;n++)for(var o=0;o<e;o++)r.isReserved(o,n)||r.xor(o,n,a(t,o,n))},e.getBestMask=function(t,r){for(var n=Object.keys(e.Patterns).length,o=0,i=1/0,u=0;u<n;u++){r(u),e.applyMask(u,t);var a=e.getPenaltyN1(t)+e.getPenaltyN2(t)+e.getPenaltyN3(t)+e.getPenaltyN4(t);e.applyMask(u,t),a<i&&(i=a,o=u)}return o}},{}],14:[function(t,r,e){var n=t("./version-check"),o=t("./regex");e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(t,r){if(!t.ccBits)throw new Error("Invalid mode: "+t);if(!n.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?t.ccBits[0]:r<27?t.ccBits[1]:t.ccBits[2]},e.getBestModeForData=function(t){return o.testNumeric(t)?e.NUMERIC:o.testAlphanumeric(t)?e.ALPHANUMERIC:o.testKanji(t)?e.KANJI:e.BYTE},e.toString=function(t){if(t&&t.id)return t.id;throw new Error("Invalid mode")},e.isValid=function(t){return t&&t.bit&&t.ccBits},e.from=function(t,r){if(e.isValid(t))return t;try{return function(t){if("string"!=typeof t)throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+t)}}(t)}catch(t){return r}}},{"./regex":19,"./version-check":22}],15:[function(t,r,e){var n=t("./mode");function o(t){this.mode=n.NUMERIC,this.data=t.toString()}o.getBitsLength=function(t){return 10*Math.floor(t/3)+(t%3?t%3*3+1:0)},o.prototype.getLength=function(){return this.data.length},o.prototype.getBitsLength=function(){return o.getBitsLength(this.data.length)},o.prototype.write=function(t){var r,e,n;for(r=0;r+3<=this.data.length;r+=3)e=this.data.substr(r,3),n=parseInt(e,10),t.put(n,10);var o=this.data.length-r;o>0&&(e=this.data.substr(r),n=parseInt(e,10),t.put(n,3*o+1))},r.exports=o},{"./mode":14}],16:[function(t,r,e){var n=t("../utils/buffer"),o=t("./galois-field");e.mul=function(t,r){for(var e=n.alloc(t.length+r.length-1),i=0;i<t.length;i++)for(var u=0;u<r.length;u++)e[i+u]^=o.mul(t[i],r[u]);return e},e.mod=function(t,r){for(var e=n.from(t);e.length-r.length>=0;){for(var i=e[0],u=0;u<r.length;u++)e[u]^=o.mul(r[u],i);for(var a=0;a<e.length&&0===e[a];)a++;e=e.slice(a)}return e},e.generateECPolynomial=function(t){for(var r=n.from([1]),i=0;i<t;i++)r=e.mul(r,[1,o.exp(i)]);return r}},{"../utils/buffer":28,"./galois-field":11}],17:[function(t,r,e){var n=t("../utils/buffer"),o=t("./utils"),i=t("./error-correction-level"),u=t("./bit-buffer"),a=t("./bit-matrix"),f=t("./alignment-pattern"),s=t("./finder-pattern"),h=t("./mask-pattern"),c=t("./error-correction-code"),l=t("./reed-solomon-encoder"),g=t("./version"),p=t("./format-info"),d=t("./mode"),y=t("./segments"),v=t("isarray");function w(t,r,e){var n,o,i=t.size,u=p.getEncodedBits(r,e);for(n=0;n<15;n++)o=1==(u>>n&1),n<6?t.set(n,8,o,!0):n<8?t.set(n+1,8,o,!0):t.set(i-15+n,8,o,!0),n<8?t.set(8,i-n-1,o,!0):n<9?t.set(8,15-n-1+1,o,!0):t.set(8,15-n-1,o,!0);t.set(i-8,8,1,!0)}function m(t,r,e){var i=new u;e.forEach((function(r){i.put(r.mode.bit,4),i.put(r.getLength(),d.getCharCountIndicator(r.mode,t)),r.write(i)}));var a=8*(o.getSymbolTotalCodewords(t)-c.getTotalCodewordsCount(t,r));for(i.getLengthInBits()+4<=a&&i.put(0,4);i.getLengthInBits()%8!=0;)i.putBit(0);for(var f=(a-i.getLengthInBits())/8,s=0;s<f;s++)i.put(s%2?17:236,8);return function(t,r,e){for(var i=o.getSymbolTotalCodewords(r),u=c.getTotalCodewordsCount(r,e),a=i-u,f=c.getBlocksCount(r,e),s=f-i%f,h=Math.floor(i/f),g=Math.floor(a/f),p=g+1,d=h-g,y=new l(d),v=0,w=new Array(f),m=new Array(f),b=0,E=n.from(t.buffer),A=0;A<f;A++){var B=A<s?g:p;w[A]=E.slice(v,v+B),m[A]=y.encode(w[A]),v+=B,b=Math.max(b,B)}var T,R,C=n.alloc(i),P=0;for(T=0;T<b;T++)for(R=0;R<f;R++)T<w[R].length&&(C[P++]=w[R][T]);for(T=0;T<d;T++)for(R=0;R<f;R++)C[P++]=m[R][T];return C}(i,t,r)}function b(t,r,e,n){var i;if(v(t))i=y.fromArray(t);else{if("string"!=typeof t)throw new Error("Invalid data");var u=r;if(!u){var c=y.rawSplit(t);u=g.getBestVersionForData(c,e)}i=y.fromString(t,u||40)}var l=g.getBestVersionForData(i,e);if(!l)throw new Error("The amount of data is too big to be stored in a QR Code");if(r){if(r<l)throw new Error("\nThe chosen QR Code version cannot contain this amount of data.\nMinimum version required to store current data is: "+l+".\n")}else r=l;var p=m(r,e,i),d=o.getSymbolSize(r),b=new a(d);return function(t,r){for(var e=t.size,n=s.getPositions(r),o=0;o<n.length;o++)for(var i=n[o][0],u=n[o][1],a=-1;a<=7;a++)if(!(i+a<=-1||e<=i+a))for(var f=-1;f<=7;f++)u+f<=-1||e<=u+f||(a>=0&&a<=6&&(0===f||6===f)||f>=0&&f<=6&&(0===a||6===a)||a>=2&&a<=4&&f>=2&&f<=4?t.set(i+a,u+f,!0,!0):t.set(i+a,u+f,!1,!0))}(b,r),function(t){for(var r=t.size,e=8;e<r-8;e++){var n=e%2==0;t.set(e,6,n,!0),t.set(6,e,n,!0)}}(b),function(t,r){for(var e=f.getPositions(r),n=0;n<e.length;n++)for(var o=e[n][0],i=e[n][1],u=-2;u<=2;u++)for(var a=-2;a<=2;a++)-2===u||2===u||-2===a||2===a||0===u&&0===a?t.set(o+u,i+a,!0,!0):t.set(o+u,i+a,!1,!0)}(b,r),w(b,e,0),r>=7&&function(t,r){for(var e,n,o,i=t.size,u=g.getEncodedBits(r),a=0;a<18;a++)e=Math.floor(a/3),n=a%3+i-8-3,o=1==(u>>a&1),t.set(e,n,o,!0),t.set(n,e,o,!0)}(b,r),function(t,r){for(var e=t.size,n=-1,o=e-1,i=7,u=0,a=e-1;a>0;a-=2)for(6===a&&a--;;){for(var f=0;f<2;f++)if(!t.isReserved(o,a-f)){var s=!1;u<r.length&&(s=1==(r[u]>>>i&1)),t.set(o,a-f,s),-1==--i&&(u++,i=7)}if((o+=n)<0||e<=o){o-=n,n=-n;break}}}(b,p),isNaN(n)&&(n=h.getBestMask(b,w.bind(null,b,e))),h.applyMask(n,b),w(b,e,n),{modules:b,version:r,errorCorrectionLevel:e,maskPattern:n,segments:i}}e.create=function(t,r){if(void 0===t||""===t)throw new Error("No input text");var e,n,u=i.M;return void 0!==r&&(u=i.from(r.errorCorrectionLevel,i.M),e=g.from(r.version),n=h.from(r.maskPattern),r.toSJISFunc&&o.setToSJISFunction(r.toSJISFunc)),b(t,e,u,n)}},{"../utils/buffer":28,"./alignment-pattern":2,"./bit-buffer":4,"./bit-matrix":5,"./error-correction-code":7,"./error-correction-level":8,"./finder-pattern":9,"./format-info":10,"./mask-pattern":13,"./mode":14,"./reed-solomon-encoder":18,"./segments":20,"./utils":21,"./version":23,isarray:33}],18:[function(t,r,e){var n=t("../utils/buffer"),o=t("./polynomial"),i=t("buffer").Buffer;function u(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}u.prototype.initialize=function(t){this.degree=t,this.genPoly=o.generateECPolynomial(this.degree)},u.prototype.encode=function(t){if(!this.genPoly)throw new Error("Encoder not initialized");var r=n.alloc(this.degree),e=i.concat([t,r],t.length+this.degree),u=o.mod(e,this.genPoly),a=this.degree-u.length;if(a>0){var f=n.alloc(this.degree);return u.copy(f,a),f}return u},r.exports=u},{"../utils/buffer":28,"./polynomial":16,buffer:30}],19:[function(t,r,e){var n="[0-9]+",o="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+",i="(?:(?![A-Z0-9 $%*+\\-./:]|"+(o=o.replace(/u/g,"\\u"))+")(?:.|[\r\n]))+";e.KANJI=new RegExp(o,"g"),e.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),e.BYTE=new RegExp(i,"g"),e.NUMERIC=new RegExp(n,"g"),e.ALPHANUMERIC=new RegExp("[A-Z $%*+\\-./:]+","g");var u=new RegExp("^"+o+"$"),a=new RegExp("^[0-9]+$"),f=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");e.testKanji=function(t){return u.test(t)},e.testNumeric=function(t){return a.test(t)},e.testAlphanumeric=function(t){return f.test(t)}},{}],20:[function(t,r,e){var n=t("./mode"),o=t("./numeric-data"),i=t("./alphanumeric-data"),u=t("./byte-data"),a=t("./kanji-data"),f=t("./regex"),s=t("./utils"),h=t("dijkstrajs");function c(t){return unescape(encodeURIComponent(t)).length}function l(t,r,e){for(var n,o=[];null!==(n=t.exec(e));)o.push({data:n[0],index:n.index,mode:r,length:n[0].length});return o}function g(t){var r,e,o=l(f.NUMERIC,n.NUMERIC,t),i=l(f.ALPHANUMERIC,n.ALPHANUMERIC,t);return s.isKanjiModeEnabled()?(r=l(f.BYTE,n.BYTE,t),e=l(f.KANJI,n.KANJI,t)):(r=l(f.BYTE_KANJI,n.BYTE,t),e=[]),o.concat(i,r,e).sort((function(t,r){return t.index-r.index})).map((function(t){return{data:t.data,mode:t.mode,length:t.length}}))}function p(t,r){switch(r){case n.NUMERIC:return o.getBitsLength(t);case n.ALPHANUMERIC:return i.getBitsLength(t);case n.KANJI:return a.getBitsLength(t);case n.BYTE:return u.getBitsLength(t)}}function d(t,r){var e,f=n.getBestModeForData(t);if((e=n.from(r,f))!==n.BYTE&&e.bit<f.bit)throw new Error('"'+t+'" cannot be encoded with mode '+n.toString(e)+".\n Suggested mode is: "+n.toString(f));switch(e!==n.KANJI||s.isKanjiModeEnabled()||(e=n.BYTE),e){case n.NUMERIC:return new o(t);case n.ALPHANUMERIC:return new i(t);case n.KANJI:return new a(t);case n.BYTE:return new u(t)}}e.fromArray=function(t){return t.reduce((function(t,r){return"string"==typeof r?t.push(d(r,null)):r.data&&t.push(d(r.data,r.mode)),t}),[])},e.fromString=function(t,r){for(var o=function(t,r){for(var e={},o={start:{}},i=["start"],u=0;u<t.length;u++){for(var a=t[u],f=[],s=0;s<a.length;s++){var h=a[s],c=""+u+s;f.push(c),e[c]={node:h,lastCount:0},o[c]={};for(var l=0;l<i.length;l++){var g=i[l];e[g]&&e[g].node.mode===h.mode?(o[g][c]=p(e[g].lastCount+h.length,h.mode)-p(e[g].lastCount,h.mode),e[g].lastCount+=h.length):(e[g]&&(e[g].lastCount=h.length),o[g][c]=p(h.length,h.mode)+4+n.getCharCountIndicator(h.mode,r))}}i=f}for(l=0;l<i.length;l++)o[i[l]].end=0;return{map:o,table:e}}(function(t){for(var r=[],e=0;e<t.length;e++){var o=t[e];switch(o.mode){case n.NUMERIC:r.push([o,{data:o.data,mode:n.ALPHANUMERIC,length:o.length},{data:o.data,mode:n.BYTE,length:o.length}]);break;case n.ALPHANUMERIC:r.push([o,{data:o.data,mode:n.BYTE,length:o.length}]);break;case n.KANJI:r.push([o,{data:o.data,mode:n.BYTE,length:c(o.data)}]);break;case n.BYTE:r.push([{data:o.data,mode:n.BYTE,length:c(o.data)}])}}return r}(g(t,s.isKanjiModeEnabled())),r),i=h.find_path(o.map,"start","end"),u=[],a=1;a<i.length-1;a++)u.push(o.table[i[a]].node);return e.fromArray(function(t){return t.reduce((function(t,r){var e=t.length-1>=0?t[t.length-1]:null;return e&&e.mode===r.mode?(t[t.length-1].data+=r.data,t):(t.push(r),t)}),[])}(u))},e.rawSplit=function(t){return e.fromArray(g(t,s.isKanjiModeEnabled()))}},{"./alphanumeric-data":3,"./byte-data":6,"./kanji-data":12,"./mode":14,"./numeric-data":15,"./regex":19,"./utils":21,dijkstrajs:31}],21:[function(t,r,e){var n,o=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];e.getSymbolSize=function(t){if(!t)throw new Error('"version" cannot be null or undefined');if(t<1||t>40)throw new Error('"version" should be in range from 1 to 40');return 4*t+17},e.getSymbolTotalCodewords=function(t){return o[t]},e.getBCHDigit=function(t){for(var r=0;0!==t;)r++,t>>>=1;return r},e.setToSJISFunction=function(t){if("function"!=typeof t)throw new Error('"toSJISFunc" is not a valid function.');n=t},e.isKanjiModeEnabled=function(){return void 0!==n},e.toSJIS=function(t){return n(t)}},{}],22:[function(t,r,e){e.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}},{}],23:[function(t,r,e){var n=t("./utils"),o=t("./error-correction-code"),i=t("./error-correction-level"),u=t("./mode"),a=t("./version-check"),f=t("isarray"),s=n.getBCHDigit(7973);function h(t,r){return u.getCharCountIndicator(t,r)+4}function c(t,r){var e=0;return t.forEach((function(t){var n=h(t.mode,r);e+=n+t.getBitsLength()})),e}e.from=function(t,r){return a.isValid(t)?parseInt(t,10):r},e.getCapacity=function(t,r,e){if(!a.isValid(t))throw new Error("Invalid QR Code version");void 0===e&&(e=u.BYTE);var i=8*(n.getSymbolTotalCodewords(t)-o.getTotalCodewordsCount(t,r));if(e===u.MIXED)return i;var f=i-h(e,t);switch(e){case u.NUMERIC:return Math.floor(f/10*3);case u.ALPHANUMERIC:return Math.floor(f/11*2);case u.KANJI:return Math.floor(f/13);case u.BYTE:default:return Math.floor(f/8)}},e.getBestVersionForData=function(t,r){var n,o=i.from(r,i.M);if(f(t)){if(t.length>1)return function(t,r){for(var n=1;n<=40;n++)if(c(t,n)<=e.getCapacity(n,r,u.MIXED))return n}(t,o);if(0===t.length)return 1;n=t[0]}else n=t;return function(t,r,n){for(var o=1;o<=40;o++)if(r<=e.getCapacity(o,n,t))return o}(n.mode,n.getLength(),o)},e.getEncodedBits=function(t){if(!a.isValid(t)||t<7)throw new Error("Invalid QR Code version");for(var r=t<<12;n.getBCHDigit(r)-s>=0;)r^=7973<<n.getBCHDigit(r)-s;return t<<12|r}},{"./error-correction-code":7,"./error-correction-level":8,"./mode":14,"./utils":21,"./version-check":22,isarray:33}],24:[function(t,r,e){var n=t("./can-promise"),o=t("./core/qrcode"),i=t("./renderer/canvas"),u=t("./renderer/svg-tag.js");function a(t,r,e,i,u){var a=[].slice.call(arguments,1),f=a.length,s="function"==typeof a[f-1];if(!s&&!n())throw new Error("Callback required as last argument");if(!s){if(f<1)throw new Error("Too few arguments provided");return 1===f?(e=r,r=i=void 0):2!==f||r.getContext||(i=e,e=r,r=void 0),new Promise((function(n,u){try{var a=o.create(e,i);n(t(a,r,i))}catch(t){u(t)}}))}if(f<2)throw new Error("Too few arguments provided");2===f?(u=e,e=r,r=i=void 0):3===f&&(r.getContext&&void 0===u?(u=i,i=void 0):(u=i,i=e,e=r,r=void 0));try{var h=o.create(e,i);u(null,t(h,r,i))}catch(t){u(t)}}e.create=o.create,e.toCanvas=a.bind(null,i.render),e.toDataURL=a.bind(null,i.renderToDataURL),e.toString=a.bind(null,(function(t,r,e){return u.render(t,e)}))},{"./can-promise":1,"./core/qrcode":17,"./renderer/canvas":25,"./renderer/svg-tag.js":26}],25:[function(t,r,e){var n=t("./utils");e.render=function(t,r,e){var o=e,i=r;void 0!==o||r&&r.getContext||(o=r,r=void 0),r||(i=function(){try{return document.createElement("canvas")}catch(t){throw new Error("You need to specify a canvas element")}}()),o=n.getOptions(o);var u=n.getImageWidth(t.modules.size,o),a=i.getContext("2d"),f=a.createImageData(u,u);return n.qrToImageData(f.data,t,o),function(t,r,e){t.clearRect(0,0,r.width,r.height),r.style||(r.style={}),r.height=e,r.width=e,r.style.height=e+"px",r.style.width=e+"px"}(a,i,u),a.putImageData(f,0,0),i},e.renderToDataURL=function(t,r,n){var o=n;void 0!==o||r&&r.getContext||(o=r,r=void 0),o||(o={});var i=e.render(t,r,o),u=o.type||"image/png",a=o.rendererOpts||{};return i.toDataURL(u,a.quality)}},{"./utils":27}],26:[function(t,r,e){var n=t("./utils");function o(t,r){var e=t.a/255,n=r+'="'+t.hex+'"';return e<1?n+" "+r+'-opacity="'+e.toFixed(2).slice(1)+'"':n}function i(t,r,e){var n=t+r;return void 0!==e&&(n+=" "+e),n}e.render=function(t,r,e){var u=n.getOptions(r),a=t.modules.size,f=t.modules.data,s=a+2*u.margin,h=u.color.light.a?"<path "+o(u.color.light,"fill")+' d="M0 0h'+s+"v"+s+'H0z"/>':"",c="<path "+o(u.color.dark,"stroke")+' d="'+function(t,r,e){for(var n="",o=0,u=!1,a=0,f=0;f<t.length;f++){var s=Math.floor(f%r),h=Math.floor(f/r);s||u||(u=!0),t[f]?(a++,f>0&&s>0&&t[f-1]||(n+=u?i("M",s+e,.5+h+e):i("m",o,0),o=0,u=!1),s+1<r&&t[f+1]||(n+=i("h",a),a=0)):o++}return n}(f,a,u.margin)+'"/>',l='viewBox="0 0 '+s+" "+s+'"',g='<svg xmlns="http://www.w3.org/2000/svg" '+(u.width?'width="'+u.width+'" height="'+u.width+'" ':"")+l+' shape-rendering="crispEdges">'+h+c+"</svg>\n";return"function"==typeof e&&e(null,g),g}},{"./utils":27}],27:[function(t,r,e){function n(t){if("number"==typeof t&&(t=t.toString()),"string"!=typeof t)throw new Error("Color should be defined as hex string");var r=t.slice().replace("#","").split("");if(r.length<3||5===r.length||r.length>8)throw new Error("Invalid hex color: "+t);3!==r.length&&4!==r.length||(r=Array.prototype.concat.apply([],r.map((function(t){return[t,t]})))),6===r.length&&r.push("F","F");var e=parseInt(r.join(""),16);return{r:e>>24&255,g:e>>16&255,b:e>>8&255,a:255&e,hex:"#"+r.slice(0,6).join("")}}e.getOptions=function(t){t||(t={}),t.color||(t.color={});var r=void 0===t.margin||null===t.margin||t.margin<0?4:t.margin,e=t.width&&t.width>=21?t.width:void 0,o=t.scale||4;return{width:e,scale:e?4:o,margin:r,color:{dark:n(t.color.dark||"#000000ff"),light:n(t.color.light||"#ffffffff")},type:t.type,rendererOpts:t.rendererOpts||{}}},e.getScale=function(t,r){return r.width&&r.width>=t+2*r.margin?r.width/(t+2*r.margin):r.scale},e.getImageWidth=function(t,r){var n=e.getScale(t,r);return Math.floor((t+2*r.margin)*n)},e.qrToImageData=function(t,r,n){for(var o=r.modules.size,i=r.modules.data,u=e.getScale(o,n),a=Math.floor((o+2*n.margin)*u),f=n.margin*u,s=[n.color.light,n.color.dark],h=0;h<a;h++)for(var c=0;c<a;c++){var l=4*(h*a+c),g=n.color.light;if(h>=f&&c>=f&&h<a-f&&c<a-f)g=s[i[Math.floor((h-f)/u)*o+Math.floor((c-f)/u)]?1:0];t[l++]=g.r,t[l++]=g.g,t[l++]=g.b,t[l]=g.a}}},{}],28:[function(t,r,e){"use strict";var n=t("isarray");i.TYPED_ARRAY_SUPPORT=function(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()}catch(t){return!1}}();var o=i.TYPED_ARRAY_SUPPORT?2147483647:1073741823;function i(t,r,e){return i.TYPED_ARRAY_SUPPORT||this instanceof i?"number"==typeof t?f(this,t):function(t,r,e,n){if("number"==typeof r)throw new TypeError('"value" argument must not be a number');if("undefined"!=typeof ArrayBuffer&&r instanceof ArrayBuffer)return function(t,r,e,n){if(e<0||r.byteLength<e)throw new RangeError("'offset' is out of bounds");if(r.byteLength<e+(n||0))throw new RangeError("'length' is out of bounds");var o;o=void 0===e&&void 0===n?new Uint8Array(r):void 0===n?new Uint8Array(r,e):new Uint8Array(r,e,n);i.TYPED_ARRAY_SUPPORT?o.__proto__=i.prototype:o=s(t,o);return o}(t,r,e,n);if("string"==typeof r)return function(t,r){var e=0|c(r),n=a(t,e),o=n.write(r);o!==e&&(n=n.slice(0,o));return n}(t,r);return function(t,r){if(i.isBuffer(r)){var e=0|u(r.length),n=a(t,e);return 0===n.length||r.copy(n,0,0,e),n}if(r){if("undefined"!=typeof ArrayBuffer&&r.buffer instanceof ArrayBuffer||"length"in r)return"number"!=typeof r.length||(o=r.length)!=o?a(t,0):s(t,r);if("Buffer"===r.type&&Array.isArray(r.data))return s(t,r.data)}var o;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(t,r)}(this,t,r,e):new i(t,r,e)}function u(t){if(t>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|t}function a(t,r){var e;return i.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(r)).__proto__=i.prototype:(null===(e=t)&&(e=new i(r)),e.length=r),e}function f(t,r){var e=a(t,r<0?0:0|u(r));if(!i.TYPED_ARRAY_SUPPORT)for(var n=0;n<r;++n)e[n]=0;return e}function s(t,r){for(var e=r.length<0?0:0|u(r.length),n=a(t,e),o=0;o<e;o+=1)n[o]=255&r[o];return n}function h(t,r){var e;r=r||1/0;for(var n=t.length,o=null,i=[],u=0;u<n;++u){if((e=t.charCodeAt(u))>55295&&e<57344){if(!o){if(e>56319){(r-=3)>-1&&i.push(239,191,189);continue}if(u+1===n){(r-=3)>-1&&i.push(239,191,189);continue}o=e;continue}if(e<56320){(r-=3)>-1&&i.push(239,191,189),o=e;continue}e=65536+(o-55296<<10|e-56320)}else o&&(r-=3)>-1&&i.push(239,191,189);if(o=null,e<128){if((r-=1)<0)break;i.push(e)}else if(e<2048){if((r-=2)<0)break;i.push(e>>6|192,63&e|128)}else if(e<65536){if((r-=3)<0)break;i.push(e>>12|224,e>>6&63|128,63&e|128)}else{if(!(e<1114112))throw new Error("Invalid code point");if((r-=4)<0)break;i.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}}return i}function c(t){return i.isBuffer(t)?t.length:"undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer)?t.byteLength:("string"!=typeof t&&(t=""+t),0===t.length?0:h(t).length)}i.TYPED_ARRAY_SUPPORT&&(i.prototype.__proto__=Uint8Array.prototype,i.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&i[Symbol.species]===i&&Object.defineProperty(i,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1})),i.prototype.write=function(t,r,e){void 0===r||void 0===e&&"string"==typeof r?(e=this.length,r=0):isFinite(r)&&(r|=0,isFinite(e)?e|=0:e=void 0);var n=this.length-r;if((void 0===e||e>n)&&(e=n),t.length>0&&(e<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");return function(t,r,e,n){return function(t,r,e,n){for(var o=0;o<n&&!(o+e>=r.length||o>=t.length);++o)r[o+e]=t[o];return o}(h(r,t.length-e),t,e,n)}(this,t,r,e)},i.prototype.slice=function(t,r){var e,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(r=void 0===r?n:~~r)<0?(r+=n)<0&&(r=0):r>n&&(r=n),r<t&&(r=t),i.TYPED_ARRAY_SUPPORT)(e=this.subarray(t,r)).__proto__=i.prototype;else{var o=r-t;e=new i(o,void 0);for(var u=0;u<o;++u)e[u]=this[u+t]}return e},i.prototype.copy=function(t,r,e,n){if(e||(e=0),n||0===n||(n=this.length),r>=t.length&&(r=t.length),r||(r=0),n>0&&n<e&&(n=e),n===e)return 0;if(0===t.length||0===this.length)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(e<0||e>=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-r<n-e&&(n=t.length-r+e);var o,u=n-e;if(this===t&&e<r&&r<n)for(o=u-1;o>=0;--o)t[o+r]=this[o+e];else if(u<1e3||!i.TYPED_ARRAY_SUPPORT)for(o=0;o<u;++o)t[o+r]=this[o+e];else Uint8Array.prototype.set.call(t,this.subarray(e,e+u),r);return u},i.prototype.fill=function(t,r,e){if("string"==typeof t){if("string"==typeof r?(r=0,e=this.length):"string"==typeof e&&(e=this.length),1===t.length){var n=t.charCodeAt(0);n<256&&(t=n)}}else"number"==typeof t&&(t&=255);if(r<0||this.length<r||this.length<e)throw new RangeError("Out of range index");if(e<=r)return this;var o;if(r>>>=0,e=void 0===e?this.length:e>>>0,t||(t=0),"number"==typeof t)for(o=r;o<e;++o)this[o]=t;else{var u=i.isBuffer(t)?t:new i(t),a=u.length;for(o=0;o<e-r;++o)this[o+r]=u[o%a]}return this},i.concat=function(t,r){if(!n(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return a(null,0);var e;if(void 0===r)for(r=0,e=0;e<t.length;++e)r+=t[e].length;var o=f(null,r),u=0;for(e=0;e<t.length;++e){var s=t[e];if(!i.isBuffer(s))throw new TypeError('"list" argument must be an Array of Buffers');s.copy(o,u),u+=s.length}return o},i.byteLength=c,i.prototype._isBuffer=!0,i.isBuffer=function(t){return!(null==t||!t._isBuffer)},r.exports.alloc=function(t){var r=new i(t);return r.fill(0),r},r.exports.from=function(t){return new i(t)}},{isarray:33}],29:[function(t,r,e){"use strict";e.byteLength=function(t){var r=s(t),e=r[0],n=r[1];return 3*(e+n)/4-n},e.toByteArray=function(t){var r,e,n=s(t),u=n[0],a=n[1],f=new i(function(t,r,e){return 3*(r+e)/4-e}(0,u,a)),h=0,c=a>0?u-4:u;for(e=0;e<c;e+=4)r=o[t.charCodeAt(e)]<<18|o[t.charCodeAt(e+1)]<<12|o[t.charCodeAt(e+2)]<<6|o[t.charCodeAt(e+3)],f[h++]=r>>16&255,f[h++]=r>>8&255,f[h++]=255&r;2===a&&(r=o[t.charCodeAt(e)]<<2|o[t.charCodeAt(e+1)]>>4,f[h++]=255&r);1===a&&(r=o[t.charCodeAt(e)]<<10|o[t.charCodeAt(e+1)]<<4|o[t.charCodeAt(e+2)]>>2,f[h++]=r>>8&255,f[h++]=255&r);return f},e.fromByteArray=function(t){for(var r,e=t.length,o=e%3,i=[],u=16383,a=0,f=e-o;a<f;a+=u)i.push(h(t,a,a+u>f?f:a+u));1===o?(r=t[e-1],i.push(n[r>>2]+n[r<<4&63]+"==")):2===o&&(r=(t[e-2]<<8)+t[e-1],i.push(n[r>>10]+n[r>>4&63]+n[r<<2&63]+"="));return i.join("")};for(var n=[],o=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",a=0,f=u.length;a<f;++a)n[a]=u[a],o[u.charCodeAt(a)]=a;function s(t){var r=t.length;if(r%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var e=t.indexOf("=");return-1===e&&(e=r),[e,e===r?0:4-e%4]}function h(t,r,e){for(var o,i,u=[],a=r;a<e;a+=3)o=(t[a]<<16&16711680)+(t[a+1]<<8&65280)+(255&t[a+2]),u.push(n[(i=o)>>18&63]+n[i>>12&63]+n[i>>6&63]+n[63&i]);return u.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63},{}],30:[function(t,r,e){
 /*!
  * The buffer module from node.js, for the browser.
  *
  * @author   Feross Aboukhadijeh <https://feross.org>
  * @license  MIT
  */
-/* eslint-disable no-proto */
-
-'use strict'
-
-var base64 = require('base64-js')
-var ieee754 = require('ieee754')
-var customInspectSymbol =
-  (typeof Symbol === 'function' && typeof Symbol.for === 'function')
-    ? Symbol.for('nodejs.util.inspect.custom')
-    : null
-
-exports.Buffer = Buffer
-exports.SlowBuffer = SlowBuffer
-exports.INSPECT_MAX_BYTES = 50
-
-var K_MAX_LENGTH = 0x7fffffff
-exports.kMaxLength = K_MAX_LENGTH
-
-/**
- * If `Buffer.TYPED_ARRAY_SUPPORT`:
- *   === true    Use Uint8Array implementation (fastest)
- *   === false   Print warning and recommend using `buffer` v4.x which has an Object
- *               implementation (most compatible, even IE6)
- *
- * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
- * Opera 11.6+, iOS 4.2+.
- *
- * We report that the browser does not support typed arrays if the are not subclassable
- * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
- * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
- * for __proto__ and has a buggy typed array implementation.
- */
-Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
-
-if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
-    typeof console.error === 'function') {
-  console.error(
-    'This browser lacks typed array (Uint8Array) support which is required by ' +
-    '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
-  )
-}
-
-function typedArraySupport () {
-  // Can typed array instances can be augmented?
-  try {
-    var arr = new Uint8Array(1)
-    var proto = { foo: function () { return 42 } }
-    Object.setPrototypeOf(proto, Uint8Array.prototype)
-    Object.setPrototypeOf(arr, proto)
-    return arr.foo() === 42
-  } catch (e) {
-    return false
-  }
-}
-
-Object.defineProperty(Buffer.prototype, 'parent', {
-  enumerable: true,
-  get: function () {
-    if (!Buffer.isBuffer(this)) return undefined
-    return this.buffer
-  }
-})
-
-Object.defineProperty(Buffer.prototype, 'offset', {
-  enumerable: true,
-  get: function () {
-    if (!Buffer.isBuffer(this)) return undefined
-    return this.byteOffset
-  }
-})
-
-function createBuffer (length) {
-  if (length > K_MAX_LENGTH) {
-    throw new RangeError('The value "' + length + '" is invalid for option "size"')
-  }
-  // Return an augmented `Uint8Array` instance
-  var buf = new Uint8Array(length)
-  Object.setPrototypeOf(buf, Buffer.prototype)
-  return buf
-}
-
-/**
- * The Buffer constructor returns instances of `Uint8Array` that have their
- * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
- * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
- * and the `Uint8Array` methods. Square bracket notation works as expected -- it
- * returns a single octet.
- *
- * The `Uint8Array` prototype remains unmodified.
- */
-
-function Buffer (arg, encodingOrOffset, length) {
-  // Common case.
-  if (typeof arg === 'number') {
-    if (typeof encodingOrOffset === 'string') {
-      throw new TypeError(
-        'The "string" argument must be of type string. Received type number'
-      )
-    }
-    return allocUnsafe(arg)
-  }
-  return from(arg, encodingOrOffset, length)
-}
-
-// 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.poolSize = 8192 // not used by this implementation
-
-function from (value, encodingOrOffset, length) {
-  if (typeof value === 'string') {
-    return fromString(value, encodingOrOffset)
-  }
-
-  if (ArrayBuffer.isView(value)) {
-    return fromArrayLike(value)
-  }
-
-  if (value == null) {
-    throw new TypeError(
-      'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
-      'or Array-like Object. Received type ' + (typeof value)
-    )
-  }
-
-  if (isInstance(value, ArrayBuffer) ||
-      (value && isInstance(value.buffer, ArrayBuffer))) {
-    return fromArrayBuffer(value, encodingOrOffset, length)
-  }
-
-  if (typeof value === 'number') {
-    throw new TypeError(
-      'The "value" argument must not be of type number. Received type number'
-    )
-  }
-
-  var valueOf = value.valueOf && value.valueOf()
-  if (valueOf != null && valueOf !== value) {
-    return Buffer.from(valueOf, encodingOrOffset, length)
-  }
-
-  var b = fromObject(value)
-  if (b) return b
-
-  if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
-      typeof value[Symbol.toPrimitive] === 'function') {
-    return Buffer.from(
-      value[Symbol.toPrimitive]('string'), encodingOrOffset, length
-    )
-  }
-
-  throw new TypeError(
-    'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
-    'or Array-like Object. Received type ' + (typeof value)
-  )
-}
-
-/**
- * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
- * if value is a number.
- * Buffer.from(str[, encoding])
- * Buffer.from(array)
- * Buffer.from(buffer)
- * Buffer.from(arrayBuffer[, byteOffset[, length]])
- **/
-Buffer.from = function (value, encodingOrOffset, length) {
-  return from(value, encodingOrOffset, length)
-}
-
-// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
-// https://github.com/feross/buffer/pull/148
-Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)
-Object.setPrototypeOf(Buffer, Uint8Array)
-
-function assertSize (size) {
-  if (typeof size !== 'number') {
-    throw new TypeError('"size" argument must be of type number')
-  } else if (size < 0) {
-    throw new RangeError('The value "' + size + '" is invalid for option "size"')
-  }
-}
-
-function alloc (size, fill, encoding) {
-  assertSize(size)
-  if (size <= 0) {
-    return createBuffer(size)
-  }
-  if (fill !== undefined) {
-    // Only pay attention to encoding if it's a string. This
-    // prevents accidentally sending in a number that would
-    // be 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 allocUnsafe (size) {
-  assertSize(size)
-  return createBuffer(size < 0 ? 0 : checked(size) | 0)
-}
-
-/**
- * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
- * */
-Buffer.allocUnsafe = function (size) {
-  return allocUnsafe(size)
-}
-/**
- * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
- */
-Buffer.allocUnsafeSlow = function (size) {
-  return allocUnsafe(size)
-}
-
-function fromString (string, encoding) {
-  if (typeof encoding !== 'string' || encoding === '') {
-    encoding = 'utf8'
-  }
-
-  if (!Buffer.isEncoding(encoding)) {
-    throw new TypeError('Unknown encoding: ' + encoding)
-  }
-
-  var length = byteLength(string, encoding) | 0
-  var buf = createBuffer(length)
-
-  var actual = buf.write(string, encoding)
-
-  if (actual !== length) {
-    // Writing a hex string, for example, that contains invalid characters will
-    // cause everything after the first invalid character to be ignored. (e.g.
-    // 'abxxcd' will be treated as 'ab')
-    buf = buf.slice(0, actual)
-  }
-
-  return buf
-}
-
-function fromArrayLike (array) {
-  var length = array.length < 0 ? 0 : checked(array.length) | 0
-  var buf = createBuffer(length)
-  for (var i = 0; i < length; i += 1) {
-    buf[i] = array[i] & 255
-  }
-  return buf
-}
-
-function fromArrayBuffer (array, byteOffset, length) {
-  if (byteOffset < 0 || array.byteLength < byteOffset) {
-    throw new RangeError('"offset" is outside of buffer bounds')
-  }
-
-  if (array.byteLength < byteOffset + (length || 0)) {
-    throw new RangeError('"length" is outside of buffer bounds')
-  }
-
-  var buf
-  if (byteOffset === undefined && length === undefined) {
-    buf = new Uint8Array(array)
-  } else if (length === undefined) {
-    buf = new Uint8Array(array, byteOffset)
-  } else {
-    buf = new Uint8Array(array, byteOffset, length)
-  }
-
-  // Return an augmented `Uint8Array` instance
-  Object.setPrototypeOf(buf, Buffer.prototype)
-
-  return buf
-}
-
-function fromObject (obj) {
-  if (Buffer.isBuffer(obj)) {
-    var len = checked(obj.length) | 0
-    var buf = createBuffer(len)
-
-    if (buf.length === 0) {
-      return buf
-    }
-
-    obj.copy(buf, 0, 0, len)
-    return buf
-  }
-
-  if (obj.length !== undefined) {
-    if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
-      return createBuffer(0)
-    }
-    return fromArrayLike(obj)
-  }
-
-  if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
-    return fromArrayLike(obj.data)
-  }
-}
-
-function checked (length) {
-  // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
-  // length is NaN (which is otherwise coerced to zero.)
-  if (length >= K_MAX_LENGTH) {
-    throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
-                         'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
-  }
-  return length | 0
-}
-
-function SlowBuffer (length) {
-  if (+length != length) { // eslint-disable-line eqeqeq
-    length = 0
-  }
-  return Buffer.alloc(+length)
-}
-
-Buffer.isBuffer = function isBuffer (b) {
-  return b != null && b._isBuffer === true &&
-    b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
-}
-
-Buffer.compare = function compare (a, b) {
-  if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
-  if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
-  if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
-    throw new TypeError(
-      'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
-    )
-  }
-
-  if (a === b) return 0
-
-  var x = a.length
-  var y = b.length
-
-  for (var i = 0, len = Math.min(x, y); i < len; ++i) {
-    if (a[i] !== b[i]) {
-      x = a[i]
-      y = b[i]
-      break
-    }
-  }
-
-  if (x < y) return -1
-  if (y < x) return 1
-  return 0
-}
-
-Buffer.isEncoding = function isEncoding (encoding) {
-  switch (String(encoding).toLowerCase()) {
-    case 'hex':
-    case 'utf8':
-    case 'utf-8':
-    case 'ascii':
-    case 'latin1':
-    case 'binary':
-    case 'base64':
-    case 'ucs2':
-    case 'ucs-2':
-    case 'utf16le':
-    case 'utf-16le':
-      return true
-    default:
-      return false
-  }
-}
-
-Buffer.concat = function concat (list, length) {
-  if (!Array.isArray(list)) {
-    throw new TypeError('"list" argument must be an Array of Buffers')
-  }
-
-  if (list.length === 0) {
-    return Buffer.alloc(0)
-  }
-
-  var i
-  if (length === undefined) {
-    length = 0
-    for (i = 0; i < list.length; ++i) {
-      length += list[i].length
-    }
-  }
-
-  var buffer = Buffer.allocUnsafe(length)
-  var pos = 0
-  for (i = 0; i < list.length; ++i) {
-    var buf = list[i]
-    if (isInstance(buf, Uint8Array)) {
-      buf = Buffer.from(buf)
-    }
-    if (!Buffer.isBuffer(buf)) {
-      throw new TypeError('"list" argument must be an Array of Buffers')
-    }
-    buf.copy(buffer, pos)
-    pos += buf.length
-  }
-  return buffer
-}
-
-function byteLength (string, encoding) {
-  if (Buffer.isBuffer(string)) {
-    return string.length
-  }
-  if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
-    return string.byteLength
-  }
-  if (typeof string !== 'string') {
-    throw new TypeError(
-      'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
-      'Received type ' + typeof string
-    )
-  }
-
-  var len = string.length
-  var mustMatch = (arguments.length > 2 && arguments[2] === true)
-  if (!mustMatch && len === 0) return 0
-
-  // Use a for loop to avoid recursion
-  var loweredCase = false
-  for (;;) {
-    switch (encoding) {
-      case 'ascii':
-      case 'latin1':
-      case 'binary':
-        return len
-      case 'utf8':
-      case 'utf-8':
-        return utf8ToBytes(string).length
-      case 'ucs2':
-      case 'ucs-2':
-      case 'utf16le':
-      case 'utf-16le':
-        return len * 2
-      case 'hex':
-        return len >>> 1
-      case 'base64':
-        return base64ToBytes(string).length
-      default:
-        if (loweredCase) {
-          return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
-        }
-        encoding = ('' + encoding).toLowerCase()
-        loweredCase = true
-    }
-  }
-}
-Buffer.byteLength = byteLength
-
-function slowToString (encoding, start, end) {
-  var loweredCase = false
-
-  // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
-  // property of a typed array.
-
-  // This behaves neither like String nor Uint8Array in that we set start/end
-  // to their upper/lower bounds if the value passed is out of range.
-  // undefined is handled specially as per ECMA-262 6th Edition,
-  // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
-  if (start === undefined || start < 0) {
-    start = 0
-  }
-  // Return early if start > this.length. Done here to prevent potential uint32
-  // coercion fail below.
-  if (start > this.length) {
-    return ''
-  }
-
-  if (end === undefined || end > this.length) {
-    end = this.length
-  }
-
-  if (end <= 0) {
-    return ''
-  }
-
-  // Force 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)
-
-      case 'ascii':
-        return asciiSlice(this, start, end)
-
-      case 'latin1':
-      case 'binary':
-        return latin1Slice(this, start, end)
-
-      case 'base64':
-        return base64Slice(this, start, end)
-
-      case 'ucs2':
-      case 'ucs-2':
-      case 'utf16le':
-      case 'utf-16le':
-        return utf16leSlice(this, start, end)
-
-      default:
-        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
-        encoding = (encoding + '').toLowerCase()
-        loweredCase = true
-    }
-  }
-}
-
-// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
-// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
-// reliably in a browserify context because there could be multiple different
-// copies of the 'buffer' package in use. This method works even for Buffer
-// instances that were created from another copy of the `buffer` package.
-// See: https://github.com/feross/buffer/issues/154
-Buffer.prototype._isBuffer = true
-
-function swap (b, n, m) {
-  var i = b[n]
-  b[n] = b[m]
-  b[m] = i
-}
-
-Buffer.prototype.swap16 = function swap16 () {
-  var len = this.length
-  if (len % 2 !== 0) {
-    throw new RangeError('Buffer size must be a multiple of 16-bits')
-  }
-  for (var i = 0; i < len; i += 2) {
-    swap(this, i, i + 1)
-  }
-  return this
-}
-
-Buffer.prototype.swap32 = function swap32 () {
-  var len = this.length
-  if (len % 4 !== 0) {
-    throw new RangeError('Buffer size must be a multiple of 32-bits')
-  }
-  for (var i = 0; i < len; i += 4) {
-    swap(this, i, i + 3)
-    swap(this, i + 1, i + 2)
-  }
-  return this
-}
-
-Buffer.prototype.swap64 = function swap64 () {
-  var len = this.length
-  if (len % 8 !== 0) {
-    throw new RangeError('Buffer size must be a multiple of 64-bits')
-  }
-  for (var i = 0; i < len; i += 8) {
-    swap(this, i, i + 7)
-    swap(this, i + 1, i + 6)
-    swap(this, i + 2, i + 5)
-    swap(this, i + 3, i + 4)
-  }
-  return this
-}
-
-Buffer.prototype.toString = function toString () {
-  var length = this.length
-  if (length === 0) return ''
-  if (arguments.length === 0) return utf8Slice(this, 0, length)
-  return slowToString.apply(this, arguments)
-}
-
-Buffer.prototype.toLocaleString = Buffer.prototype.toString
-
-Buffer.prototype.equals = function equals (b) {
-  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
-  if (this === b) return true
-  return Buffer.compare(this, b) === 0
-}
-
-Buffer.prototype.inspect = function inspect () {
-  var str = ''
-  var max = exports.INSPECT_MAX_BYTES
-  str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
-  if (this.length > max) str += ' ... '
-  return '<Buffer ' + str + '>'
-}
-if (customInspectSymbol) {
-  Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect
-}
-
-Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
-  if (isInstance(target, Uint8Array)) {
-    target = Buffer.from(target, target.offset, target.byteLength)
-  }
-  if (!Buffer.isBuffer(target)) {
-    throw new TypeError(
-      'The "target" argument must be one of type Buffer or Uint8Array. ' +
-      'Received type ' + (typeof target)
-    )
-  }
-
-  if (start === undefined) {
-    start = 0
-  }
-  if (end === undefined) {
-    end = target ? target.length : 0
-  }
-  if (thisStart === undefined) {
-    thisStart = 0
-  }
-  if (thisEnd === undefined) {
-    thisEnd = this.length
-  }
-
-  if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
-    throw new RangeError('out of range index')
-  }
-
-  if (thisStart >= thisEnd && start >= end) {
-    return 0
-  }
-  if (thisStart >= thisEnd) {
-    return -1
-  }
-  if (start >= end) {
-    return 1
-  }
-
-  start >>>= 0
-  end >>>= 0
-  thisStart >>>= 0
-  thisEnd >>>= 0
-
-  if (this === target) return 0
-
-  var x = thisEnd - thisStart
-  var y = end - start
-  var len = Math.min(x, y)
-
-  var thisCopy = this.slice(thisStart, thisEnd)
-  var targetCopy = target.slice(start, end)
-
-  for (var i = 0; i < len; ++i) {
-    if (thisCopy[i] !== targetCopy[i]) {
-      x = thisCopy[i]
-      y = targetCopy[i]
-      break
-    }
-  }
-
-  if (x < y) return -1
-  if (y < x) return 1
-  return 0
-}
-
-// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
-// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
-//
-// Arguments:
-// - buffer - a Buffer to search
-// - val - a string, Buffer, or number
-// - byteOffset - an index into `buffer`; will be clamped to an int32
-// - encoding - an optional encoding, relevant is val is a string
-// - dir - true for indexOf, false for lastIndexOf
-function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
-  // Empty buffer means no match
-  if (buffer.length === 0) return -1
-
-  // Normalize byteOffset
-  if (typeof byteOffset === 'string') {
-    encoding = byteOffset
-    byteOffset = 0
-  } else if (byteOffset > 0x7fffffff) {
-    byteOffset = 0x7fffffff
-  } else if (byteOffset < -0x80000000) {
-    byteOffset = -0x80000000
-  }
-  byteOffset = +byteOffset // Coerce to Number.
-  if (numberIsNaN(byteOffset)) {
-    // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
-    byteOffset = dir ? 0 : (buffer.length - 1)
-  }
-
-  // Normalize byteOffset: negative offsets start from the end of the buffer
-  if (byteOffset < 0) byteOffset = buffer.length + byteOffset
-  if (byteOffset >= buffer.length) {
-    if (dir) return -1
-    else byteOffset = buffer.length - 1
-  } else if (byteOffset < 0) {
-    if (dir) byteOffset = 0
-    else return -1
-  }
-
-  // Normalize val
-  if (typeof val === 'string') {
-    val = Buffer.from(val, encoding)
-  }
-
-  // Finally, search either indexOf (if dir is true) or lastIndexOf
-  if (Buffer.isBuffer(val)) {
-    // Special case: looking for empty string/buffer always fails
-    if (val.length === 0) {
-      return -1
-    }
-    return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
-  } else if (typeof val === 'number') {
-    val = val & 0xFF // Search for a byte value [0-255]
-    if (typeof Uint8Array.prototype.indexOf === 'function') {
-      if (dir) {
-        return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
-      } else {
-        return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
-      }
-    }
-    return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
-  }
-
-  throw new TypeError('val must be string, number or Buffer')
-}
-
-function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
-  var indexSize = 1
-  var arrLength = arr.length
-  var valLength = val.length
-
-  if (encoding !== undefined) {
-    encoding = String(encoding).toLowerCase()
-    if (encoding === 'ucs2' || encoding === 'ucs-2' ||
-        encoding === 'utf16le' || encoding === 'utf-16le') {
-      if (arr.length < 2 || val.length < 2) {
-        return -1
-      }
-      indexSize = 2
-      arrLength /= 2
-      valLength /= 2
-      byteOffset /= 2
-    }
-  }
-
-  function read (buf, i) {
-    if (indexSize === 1) {
-      return buf[i]
-    } else {
-      return buf.readUInt16BE(i * indexSize)
-    }
-  }
-
-  var i
-  if (dir) {
-    var foundIndex = -1
-    for (i = byteOffset; i < arrLength; i++) {
-      if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
-        if (foundIndex === -1) foundIndex = i
-        if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
-      } else {
-        if (foundIndex !== -1) i -= i - foundIndex
-        foundIndex = -1
-      }
-    }
-  } else {
-    if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
-    for (i = byteOffset; i >= 0; i--) {
-      var found = true
-      for (var j = 0; j < valLength; j++) {
-        if (read(arr, i + j) !== read(val, j)) {
-          found = false
-          break
-        }
-      }
-      if (found) return i
-    }
-  }
-
-  return -1
-}
-
-Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
-  return this.indexOf(val, byteOffset, encoding) !== -1
-}
-
-Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
-  return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
-}
-
-Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
-  return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
-}
-
-function hexWrite (buf, string, offset, length) {
-  offset = Number(offset) || 0
-  var remaining = buf.length - offset
-  if (!length) {
-    length = remaining
-  } else {
-    length = Number(length)
-    if (length > remaining) {
-      length = remaining
-    }
-  }
-
-  var strLen = string.length
-
-  if (length > strLen / 2) {
-    length = strLen / 2
-  }
-  for (var i = 0; i < length; ++i) {
-    var parsed = parseInt(string.substr(i * 2, 2), 16)
-    if (numberIsNaN(parsed)) return i
-    buf[offset + i] = parsed
-  }
-  return i
-}
-
-function utf8Write (buf, string, offset, length) {
-  return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
-}
-
-function asciiWrite (buf, string, offset, length) {
-  return blitBuffer(asciiToBytes(string), buf, offset, length)
-}
-
-function 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 += hexSliceLookupTable[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
-  Object.setPrototypeOf(newBuf, Buffer.prototype)
-
-  return newBuf
-}
-
-/*
- * Need to make sure that buffer isn't trying to write out of bounds.
- */
-function checkOffset (offset, ext, length) {
-  if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
-  if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
-}
-
-Buffer.prototype.readUIntLE = 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
-  } else if (typeof val === 'boolean') {
-    val = Number(val)
-  }
-
-  // Invalid ranges are not set to a default, so can range check early.
-  if (start < 0 || this.length < start || this.length < end) {
-    throw new RangeError('Out of range index')
-  }
-
-  if (end <= start) {
-    return this
-  }
-
-  start = start >>> 0
-  end = end === undefined ? this.length : end >>> 0
-
-  if (!val) val = 0
-
-  var i
-  if (typeof val === 'number') {
-    for (i = start; i < end; ++i) {
-      this[i] = val
-    }
-  } else {
-    var bytes = Buffer.isBuffer(val)
-      ? val
-      : Buffer.from(val, encoding)
-    var len = bytes.length
-    if (len === 0) {
-      throw new TypeError('The value "' + val +
-        '" is invalid for argument "value"')
-    }
-    for (i = 0; i < end - start; ++i) {
-      this[i + start] = bytes[i % len]
-    }
-  }
-
-  return this
-}
-
-// HELPER FUNCTIONS
-// ================
-
-var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
-
-function base64clean (str) {
-  // Node takes equal signs as end of the Base64 encoding
-  str = str.split('=')[0]
-  // Node strips out invalid characters like \n and \t from the string, base64-js does not
-  str = str.trim().replace(INVALID_BASE64_RE, '')
-  // Node converts strings with length < 2 to ''
-  if (str.length < 2) return ''
-  // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
-  while (str.length % 4 !== 0) {
-    str = str + '='
-  }
-  return str
-}
-
-function utf8ToBytes (string, units) {
-  units = units || Infinity
-  var codePoint
-  var length = string.length
-  var leadSurrogate = null
-  var bytes = []
-
-  for (var i = 0; i < length; ++i) {
-    codePoint = string.charCodeAt(i)
-
-    // is surrogate component
-    if (codePoint > 0xD7FF && codePoint < 0xE000) {
-      // last char was a lead
-      if (!leadSurrogate) {
-        // no lead yet
-        if (codePoint > 0xDBFF) {
-          // unexpected trail
-          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
-          continue
-        } else if (i + 1 === length) {
-          // unpaired lead
-          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
-          continue
-        }
-
-        // valid lead
-        leadSurrogate = codePoint
-
-        continue
-      }
-
-      // 2 leads in a row
-      if (codePoint < 0xDC00) {
-        if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
-        leadSurrogate = codePoint
-        continue
-      }
-
-      // valid surrogate pair
-      codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
-    } else if (leadSurrogate) {
-      // valid bmp char, but last char was a lead
-      if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
-    }
-
-    leadSurrogate = null
-
-    // encode utf8
-    if (codePoint < 0x80) {
-      if ((units -= 1) < 0) break
-      bytes.push(codePoint)
-    } else if (codePoint < 0x800) {
-      if ((units -= 2) < 0) break
-      bytes.push(
-        codePoint >> 0x6 | 0xC0,
-        codePoint & 0x3F | 0x80
-      )
-    } else if (codePoint < 0x10000) {
-      if ((units -= 3) < 0) break
-      bytes.push(
-        codePoint >> 0xC | 0xE0,
-        codePoint >> 0x6 & 0x3F | 0x80,
-        codePoint & 0x3F | 0x80
-      )
-    } else if (codePoint < 0x110000) {
-      if ((units -= 4) < 0) break
-      bytes.push(
-        codePoint >> 0x12 | 0xF0,
-        codePoint >> 0xC & 0x3F | 0x80,
-        codePoint >> 0x6 & 0x3F | 0x80,
-        codePoint & 0x3F | 0x80
-      )
-    } else {
-      throw new Error('Invalid code point')
-    }
-  }
-
-  return bytes
-}
-
-function asciiToBytes (str) {
-  var byteArray = []
-  for (var i = 0; i < str.length; ++i) {
-    // Node's code seems to be doing this and not & 0x7F..
-    byteArray.push(str.charCodeAt(i) & 0xFF)
-  }
-  return byteArray
-}
-
-function utf16leToBytes (str, units) {
-  var c, hi, lo
-  var byteArray = []
-  for (var i = 0; i < str.length; ++i) {
-    if ((units -= 2) < 0) break
-
-    c = str.charCodeAt(i)
-    hi = c >> 8
-    lo = c % 256
-    byteArray.push(lo)
-    byteArray.push(hi)
-  }
-
-  return byteArray
-}
-
-function base64ToBytes (str) {
-  return base64.toByteArray(base64clean(str))
-}
-
-function blitBuffer (src, dst, offset, length) {
-  for (var i = 0; i < length; ++i) {
-    if ((i + offset >= dst.length) || (i >= src.length)) break
-    dst[i + offset] = src[i]
-  }
-  return i
-}
-
-// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
-// the `instanceof` check but they should be treated as of that type.
-// See: https://github.com/feross/buffer/issues/166
-function isInstance (obj, type) {
-  return obj instanceof type ||
-    (obj != null && obj.constructor != null && obj.constructor.name != null &&
-      obj.constructor.name === type.name)
-}
-function numberIsNaN (obj) {
-  // For IE11 support
-  return obj !== obj // eslint-disable-line no-self-compare
-}
-
-// Create lookup table for `toString('hex')`
-// See: https://github.com/feross/buffer/issues/219
-var hexSliceLookupTable = (function () {
-  var alphabet = '0123456789abcdef'
-  var table = new Array(256)
-  for (var i = 0; i < 16; ++i) {
-    var i16 = i * 16
-    for (var j = 0; j < 16; ++j) {
-      table[i16 + j] = alphabet[i] + alphabet[j]
-    }
-  }
-  return table
-})()
-
-},{"base64-js":29,"ieee754":32}],31:[function(require,module,exports){
-'use strict';
-
-/******************************************************************************
- * Created 2008-08-19.
- *
- * Dijkstra path-finding functions. Adapted from the Dijkstar Python project.
- *
- * Copyright (C) 2008
- *   Wyatt Baldwin <self@wyattbaldwin.com>
- *   All rights reserved
- *
- * Licensed under the MIT license.
- *
- *   http://www.opensource.org/licenses/mit-license.php
- *
- * 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 dijkstra = {
-  single_source_shortest_paths: function(graph, s, d) {
-    // Predecessor map for each node that has been encountered.
-    // node ID => predecessor node ID
-    var predecessors = {};
-
-    // Costs of shortest paths from s to all nodes encountered.
-    // node ID => cost
-    var costs = {};
-    costs[s] = 0;
-
-    // Costs of shortest paths from s to all nodes encountered; differs from
-    // `costs` in that it provides easy access to the node that currently has
-    // the known shortest path from s.
-    // XXX: Do we actually need both `costs` and `open`?
-    var open = dijkstra.PriorityQueue.make();
-    open.push(s, 0);
-
-    var closest,
-        u, v,
-        cost_of_s_to_u,
-        adjacent_nodes,
-        cost_of_e,
-        cost_of_s_to_u_plus_cost_of_e,
-        cost_of_s_to_v,
-        first_visit;
-    while (!open.empty()) {
-      // In the nodes remaining in graph that have a known cost from s,
-      // find the node, u, that currently has the shortest path from s.
-      closest = open.pop();
-      u = closest.value;
-      cost_of_s_to_u = closest.cost;
-
-      // Get nodes adjacent to u...
-      adjacent_nodes = graph[u] || {};
-
-      // ...and explore the edges that connect u to those nodes, updating
-      // the cost of the shortest paths to any or all of those nodes as
-      // necessary. v is the node across the current edge from u.
-      for (v in adjacent_nodes) {
-        if (adjacent_nodes.hasOwnProperty(v)) {
-          // Get the cost of the edge running from u to v.
-          cost_of_e = adjacent_nodes[v];
-
-          // Cost of s to u plus the cost of u to v across e--this is *a*
-          // cost from s to v that may or may not be less than the current
-          // known cost to v.
-          cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e;
-
-          // If we haven't visited v yet OR if the current known cost from s to
-          // v is greater than the new cost we just found (cost of s to u plus
-          // cost of u to v across e), update v's cost in the cost list and
-          // update v's predecessor in the predecessor list (it's now u).
-          cost_of_s_to_v = costs[v];
-          first_visit = (typeof costs[v] === 'undefined');
-          if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) {
-            costs[v] = cost_of_s_to_u_plus_cost_of_e;
-            open.push(v, cost_of_s_to_u_plus_cost_of_e);
-            predecessors[v] = u;
-          }
-        }
-      }
-    }
-
-    if (typeof d !== 'undefined' && typeof costs[d] === 'undefined') {
-      var msg = ['Could not find a path from ', s, ' to ', d, '.'].join('');
-      throw new Error(msg);
-    }
-
-    return predecessors;
-  },
-
-  extract_shortest_path_from_predecessor_list: function(predecessors, d) {
-    var nodes = [];
-    var u = d;
-    var predecessor;
-    while (u) {
-      nodes.push(u);
-      predecessor = predecessors[u];
-      u = predecessors[u];
-    }
-    nodes.reverse();
-    return nodes;
-  },
-
-  find_path: function(graph, s, d) {
-    var predecessors = dijkstra.single_source_shortest_paths(graph, s, d);
-    return dijkstra.extract_shortest_path_from_predecessor_list(
-      predecessors, d);
-  },
-
-  /**
-   * A very naive priority queue implementation.
-   */
-  PriorityQueue: {
-    make: function (opts) {
-      var T = dijkstra.PriorityQueue,
-          t = {},
-          key;
-      opts = opts || {};
-      for (key in T) {
-        if (T.hasOwnProperty(key)) {
-          t[key] = T[key];
-        }
-      }
-      t.queue = [];
-      t.sorter = opts.sorter || T.default_sorter;
-      return t;
-    },
-
-    default_sorter: function (a, b) {
-      return a.cost - b.cost;
-    },
-
-    /**
-     * Add a new item to the queue and ensure the highest priority element
-     * is at the front of the queue.
-     */
-    push: function (value, cost) {
-      var item = {value: value, cost: cost};
-      this.queue.push(item);
-      this.queue.sort(this.sorter);
-    },
-
-    /**
-     * Return the highest priority element in the queue.
-     */
-    pop: function () {
-      return this.queue.shift();
-    },
-
-    empty: function () {
-      return this.queue.length === 0;
-    }
-  }
-};
-
-
-// node.js module exports
-if (typeof module !== 'undefined') {
-  module.exports = dijkstra;
-}
-
-},{}],32:[function(require,module,exports){
-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
-}
-
-},{}],33:[function(require,module,exports){
-var toString = {}.toString;
-
-module.exports = Array.isArray || function (arr) {
-  return toString.call(arr) == '[object Array]';
-};
-
-},{}]},{},[24])(24)
-});
-
-//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9icm93c2VyLXBhY2svX3ByZWx1ZGUuanMiLCJsaWIvY2FuLXByb21pc2UuanMiLCJsaWIvY29yZS9hbGlnbm1lbnQtcGF0dGVybi5qcyIsImxpYi9jb3JlL2FscGhhbnVtZXJpYy1kYXRhLmpzIiwibGliL2NvcmUvYml0LWJ1ZmZlci5qcyIsImxpYi9jb3JlL2JpdC1tYXRyaXguanMiLCJsaWIvY29yZS9ieXRlLWRhdGEuanMiLCJsaWIvY29yZS9lcnJvci1jb3JyZWN0aW9uLWNvZGUuanMiLCJsaWIvY29yZS9lcnJvci1jb3JyZWN0aW9uLWxldmVsLmpzIiwibGliL2NvcmUvZmluZGVyLXBhdHRlcm4uanMiLCJsaWIvY29yZS9mb3JtYXQtaW5mby5qcyIsImxpYi9jb3JlL2dhbG9pcy1maWVsZC5qcyIsImxpYi9jb3JlL2thbmppLWRhdGEuanMiLCJsaWIvY29yZS9tYXNrLXBhdHRlcm4uanMiLCJsaWIvY29yZS9tb2R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DA7IGJ1ZmZlcltvZmZzZXQgKyBpXSA9IGUgJiAweGZmLCBpICs9IGQsIGUgLz0gMjU2LCBlTGVuIC09IDgpIHt9XG5cbiAgYnVmZmVyW29mZnNldCArIGkgLSBkXSB8PSBzICogMTI4XG59XG4iLCJ2YXIgdG9TdHJpbmcgPSB7fS50b1N0cmluZztcblxubW9kdWxlLmV4cG9ydHMgPSBBcnJheS5pc0FycmF5IHx8IGZ1bmN0aW9uIChhcnIpIHtcbiAgcmV0dXJuIHRvU3RyaW5nLmNhbGwoYXJyKSA9PSAnW29iamVjdCBBcnJheV0nO1xufTtcbiJdfQ==
+"use strict";var n=t("base64-js"),o=t("ieee754"),i="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=f,e.SlowBuffer=function(t){+t!=t&&(t=0);return f.alloc(+t)},e.INSPECT_MAX_BYTES=50;var u=2147483647;function a(t){if(t>u)throw new RangeError('The value "'+t+'" is invalid for option "size"');var r=new Uint8Array(t);return Object.setPrototypeOf(r,f.prototype),r}function f(t,r,e){if("number"==typeof t){if("string"==typeof r)throw new TypeError('The "string" argument must be of type string. Received type number');return c(t)}return s(t,r,e)}function s(t,r,e){if("string"==typeof t)return function(t,r){"string"==typeof r&&""!==r||(r="utf8");if(!f.isEncoding(r))throw new TypeError("Unknown encoding: "+r);var e=0|p(t,r),n=a(e),o=n.write(t,r);o!==e&&(n=n.slice(0,o));return n}(t,r);if(ArrayBuffer.isView(t))return l(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(F(t,ArrayBuffer)||t&&F(t.buffer,ArrayBuffer))return function(t,r,e){if(r<0||t.byteLength<r)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<r+(e||0))throw new RangeError('"length" is outside of buffer bounds');var n;n=void 0===r&&void 0===e?new Uint8Array(t):void 0===e?new Uint8Array(t,r):new Uint8Array(t,r,e);return Object.setPrototypeOf(n,f.prototype),n}(t,r,e);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');var n=t.valueOf&&t.valueOf();if(null!=n&&n!==t)return f.from(n,r,e);var o=function(t){if(f.isBuffer(t)){var r=0|g(t.length),e=a(r);return 0===e.length||t.copy(e,0,0,r),e}if(void 0!==t.length)return"number"!=typeof t.length||z(t.length)?a(0):l(t);if("Buffer"===t.type&&Array.isArray(t.data))return l(t.data)}(t);if(o)return o;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return f.from(t[Symbol.toPrimitive]("string"),r,e);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function h(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function c(t){return h(t),a(t<0?0:0|g(t))}function l(t){for(var r=t.length<0?0:0|g(t.length),e=a(r),n=0;n<r;n+=1)e[n]=255&t[n];return e}function g(t){if(t>=u)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+u.toString(16)+" bytes");return 0|t}function p(t,r){if(f.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||F(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 e=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===e)return 0;for(var o=!1;;)switch(r){case"ascii":case"latin1":case"binary":return e;case"utf8":case"utf-8":return Y(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*e;case"hex":return e>>>1;case"base64":return D(t).length;default:if(o)return n?-1:Y(t).length;r=(""+r).toLowerCase(),o=!0}}function d(t,r,e){var n=!1;if((void 0===r||r<0)&&(r=0),r>this.length)return"";if((void 0===e||e>this.length)&&(e=this.length),e<=0)return"";if((e>>>=0)<=(r>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return U(this,r,e);case"utf8":case"utf-8":return C(this,r,e);case"ascii":return I(this,r,e);case"latin1":case"binary":return M(this,r,e);case"base64":return R(this,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,r,e);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function y(t,r,e){var n=t[r];t[r]=t[e],t[e]=n}function v(t,r,e,n,o){if(0===t.length)return-1;if("string"==typeof e?(n=e,e=0):e>2147483647?e=2147483647:e<-2147483648&&(e=-2147483648),z(e=+e)&&(e=o?0:t.length-1),e<0&&(e=t.length+e),e>=t.length){if(o)return-1;e=t.length-1}else if(e<0){if(!o)return-1;e=0}if("string"==typeof r&&(r=f.from(r,n)),f.isBuffer(r))return 0===r.length?-1:w(t,r,e,n,o);if("number"==typeof r)return r&=255,"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(t,r,e):Uint8Array.prototype.lastIndexOf.call(t,r,e):w(t,[r],e,n,o);throw new TypeError("val must be string, number or Buffer")}function w(t,r,e,n,o){var i,u=1,a=t.length,f=r.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||r.length<2)return-1;u=2,a/=2,f/=2,e/=2}function s(t,r){return 1===u?t[r]:t.readUInt16BE(r*u)}if(o){var h=-1;for(i=e;i<a;i++)if(s(t,i)===s(r,-1===h?0:i-h)){if(-1===h&&(h=i),i-h+1===f)return h*u}else-1!==h&&(i-=i-h),h=-1}else for(e+f>a&&(e=a-f),i=e;i>=0;i--){for(var c=!0,l=0;l<f;l++)if(s(t,i+l)!==s(r,l)){c=!1;break}if(c)return i}return-1}function m(t,r,e,n){e=Number(e)||0;var o=t.length-e;n?(n=Number(n))>o&&(n=o):n=o;var i=r.length;n>i/2&&(n=i/2);for(var u=0;u<n;++u){var a=parseInt(r.substr(2*u,2),16);if(z(a))return u;t[e+u]=a}return u}function b(t,r,e,n){return j(Y(r,t.length-e),t,e,n)}function E(t,r,e,n){return j(function(t){for(var r=[],e=0;e<t.length;++e)r.push(255&t.charCodeAt(e));return r}(r),t,e,n)}function A(t,r,e,n){return E(t,r,e,n)}function B(t,r,e,n){return j(D(r),t,e,n)}function T(t,r,e,n){return j(function(t,r){for(var e,n,o,i=[],u=0;u<t.length&&!((r-=2)<0);++u)n=(e=t.charCodeAt(u))>>8,o=e%256,i.push(o),i.push(n);return i}(r,t.length-e),t,e,n)}function R(t,r,e){return 0===r&&e===t.length?n.fromByteArray(t):n.fromByteArray(t.slice(r,e))}function C(t,r,e){e=Math.min(t.length,e);for(var n=[],o=r;o<e;){var i,u,a,f,s=t[o],h=null,c=s>239?4:s>223?3:s>191?2:1;if(o+c<=e)switch(c){case 1:s<128&&(h=s);break;case 2:128==(192&(i=t[o+1]))&&(f=(31&s)<<6|63&i)>127&&(h=f);break;case 3:i=t[o+1],u=t[o+2],128==(192&i)&&128==(192&u)&&(f=(15&s)<<12|(63&i)<<6|63&u)>2047&&(f<55296||f>57343)&&(h=f);break;case 4:i=t[o+1],u=t[o+2],a=t[o+3],128==(192&i)&&128==(192&u)&&128==(192&a)&&(f=(15&s)<<18|(63&i)<<12|(63&u)<<6|63&a)>65535&&f<1114112&&(h=f)}null===h?(h=65533,c=1):h>65535&&(h-=65536,n.push(h>>>10&1023|55296),h=56320|1023&h),n.push(h),o+=c}return function(t){var r=t.length;if(r<=P)return String.fromCharCode.apply(String,t);var e="",n=0;for(;n<r;)e+=String.fromCharCode.apply(String,t.slice(n,n+=P));return e}(n)}e.kMaxLength=u,f.TYPED_ARRAY_SUPPORT=function(){try{var t=new Uint8Array(1),r={foo:function(){return 42}};return Object.setPrototypeOf(r,Uint8Array.prototype),Object.setPrototypeOf(t,r),42===t.foo()}catch(t){return!1}}(),f.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||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."),Object.defineProperty(f.prototype,"parent",{enumerable:!0,get:function(){if(f.isBuffer(this))return this.buffer}}),Object.defineProperty(f.prototype,"offset",{enumerable:!0,get:function(){if(f.isBuffer(this))return this.byteOffset}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&f[Symbol.species]===f&&Object.defineProperty(f,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),f.poolSize=8192,f.from=function(t,r,e){return s(t,r,e)},Object.setPrototypeOf(f.prototype,Uint8Array.prototype),Object.setPrototypeOf(f,Uint8Array),f.alloc=function(t,r,e){return function(t,r,e){return h(t),t<=0?a(t):void 0!==r?"string"==typeof e?a(t).fill(r,e):a(t).fill(r):a(t)}(t,r,e)},f.allocUnsafe=function(t){return c(t)},f.allocUnsafeSlow=function(t){return c(t)},f.isBuffer=function(t){return null!=t&&!0===t._isBuffer&&t!==f.prototype},f.compare=function(t,r){if(F(t,Uint8Array)&&(t=f.from(t,t.offset,t.byteLength)),F(r,Uint8Array)&&(r=f.from(r,r.offset,r.byteLength)),!f.isBuffer(t)||!f.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(t===r)return 0;for(var e=t.length,n=r.length,o=0,i=Math.min(e,n);o<i;++o)if(t[o]!==r[o]){e=t[o],n=r[o];break}return e<n?-1:n<e?1:0},f.isEncoding=function(t){switch(String(t).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!0;default:return!1}},f.concat=function(t,r){if(!Array.isArray(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return f.alloc(0);var e;if(void 0===r)for(r=0,e=0;e<t.length;++e)r+=t[e].length;var n=f.allocUnsafe(r),o=0;for(e=0;e<t.length;++e){var i=t[e];if(F(i,Uint8Array)&&(i=f.from(i)),!f.isBuffer(i))throw new TypeError('"list" argument must be an Array of Buffers');i.copy(n,o),o+=i.length}return n},f.byteLength=p,f.prototype._isBuffer=!0,f.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;r<t;r+=2)y(this,r,r+1);return this},f.prototype.swap32=function(){var t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var r=0;r<t;r+=4)y(this,r,r+3),y(this,r+1,r+2);return this},f.prototype.swap64=function(){var t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var r=0;r<t;r+=8)y(this,r,r+7),y(this,r+1,r+6),y(this,r+2,r+5),y(this,r+3,r+4);return this},f.prototype.toString=function(){var t=this.length;return 0===t?"":0===arguments.length?C(this,0,t):d.apply(this,arguments)},f.prototype.toLocaleString=f.prototype.toString,f.prototype.equals=function(t){if(!f.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===f.compare(this,t)},f.prototype.inspect=function(){var t="",r=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(t+=" ... "),"<Buffer "+t+">"},i&&(f.prototype[i]=f.prototype.inspect),f.prototype.compare=function(t,r,e,n,o){if(F(t,Uint8Array)&&(t=f.from(t,t.offset,t.byteLength)),!f.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===r&&(r=0),void 0===e&&(e=t?t.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),r<0||e>t.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&r>=e)return 0;if(n>=o)return-1;if(r>=e)return 1;if(this===t)return 0;for(var i=(o>>>=0)-(n>>>=0),u=(e>>>=0)-(r>>>=0),a=Math.min(i,u),s=this.slice(n,o),h=t.slice(r,e),c=0;c<a;++c)if(s[c]!==h[c]){i=s[c],u=h[c];break}return i<u?-1:u<i?1:0},f.prototype.includes=function(t,r,e){return-1!==this.indexOf(t,r,e)},f.prototype.indexOf=function(t,r,e){return v(this,t,r,e,!0)},f.prototype.lastIndexOf=function(t,r,e){return v(this,t,r,e,!1)},f.prototype.write=function(t,r,e,n){if(void 0===r)n="utf8",e=this.length,r=0;else if(void 0===e&&"string"==typeof r)n=r,e=this.length,r=0;else{if(!isFinite(r))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");r>>>=0,isFinite(e)?(e>>>=0,void 0===n&&(n="utf8")):(n=e,e=void 0)}var o=this.length-r;if((void 0===e||e>o)&&(e=o),t.length>0&&(e<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return m(this,t,r,e);case"utf8":case"utf-8":return b(this,t,r,e);case"ascii":return E(this,t,r,e);case"latin1":case"binary":return A(this,t,r,e);case"base64":return B(this,t,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return T(this,t,r,e);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},f.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var P=4096;function I(t,r,e){var n="";e=Math.min(t.length,e);for(var o=r;o<e;++o)n+=String.fromCharCode(127&t[o]);return n}function M(t,r,e){var n="";e=Math.min(t.length,e);for(var o=r;o<e;++o)n+=String.fromCharCode(t[o]);return n}function U(t,r,e){var n=t.length;(!r||r<0)&&(r=0),(!e||e<0||e>n)&&(e=n);for(var o="",i=r;i<e;++i)o+=H[t[i]];return o}function S(t,r,e){for(var n=t.slice(r,e),o="",i=0;i<n.length;i+=2)o+=String.fromCharCode(n[i]+256*n[i+1]);return o}function L(t,r,e){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+r>e)throw new RangeError("Trying to access beyond buffer length")}function x(t,r,e,n,o,i){if(!f.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(r>o||r<i)throw new RangeError('"value" argument is out of bounds');if(e+n>t.length)throw new RangeError("Index out of range")}function N(t,r,e,n,o,i){if(e+n>t.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("Index out of range")}function _(t,r,e,n,i){return r=+r,e>>>=0,i||N(t,0,e,4),o.write(t,r,e,n,23,4),e+4}function k(t,r,e,n,i){return r=+r,e>>>=0,i||N(t,0,e,8),o.write(t,r,e,n,52,8),e+8}f.prototype.slice=function(t,r){var e=this.length;(t=~~t)<0?(t+=e)<0&&(t=0):t>e&&(t=e),(r=void 0===r?e:~~r)<0?(r+=e)<0&&(r=0):r>e&&(r=e),r<t&&(r=t);var n=this.subarray(t,r);return Object.setPrototypeOf(n,f.prototype),n},f.prototype.readUIntLE=function(t,r,e){t>>>=0,r>>>=0,e||L(t,r,this.length);for(var n=this[t],o=1,i=0;++i<r&&(o*=256);)n+=this[t+i]*o;return n},f.prototype.readUIntBE=function(t,r,e){t>>>=0,r>>>=0,e||L(t,r,this.length);for(var n=this[t+--r],o=1;r>0&&(o*=256);)n+=this[t+--r]*o;return n},f.prototype.readUInt8=function(t,r){return t>>>=0,r||L(t,1,this.length),this[t]},f.prototype.readUInt16LE=function(t,r){return t>>>=0,r||L(t,2,this.length),this[t]|this[t+1]<<8},f.prototype.readUInt16BE=function(t,r){return t>>>=0,r||L(t,2,this.length),this[t]<<8|this[t+1]},f.prototype.readUInt32LE=function(t,r){return t>>>=0,r||L(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},f.prototype.readUInt32BE=function(t,r){return t>>>=0,r||L(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},f.prototype.readIntLE=function(t,r,e){t>>>=0,r>>>=0,e||L(t,r,this.length);for(var n=this[t],o=1,i=0;++i<r&&(o*=256);)n+=this[t+i]*o;return n>=(o*=128)&&(n-=Math.pow(2,8*r)),n},f.prototype.readIntBE=function(t,r,e){t>>>=0,r>>>=0,e||L(t,r,this.length);for(var n=r,o=1,i=this[t+--n];n>0&&(o*=256);)i+=this[t+--n]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*r)),i},f.prototype.readInt8=function(t,r){return t>>>=0,r||L(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},f.prototype.readInt16LE=function(t,r){t>>>=0,r||L(t,2,this.length);var e=this[t]|this[t+1]<<8;return 32768&e?4294901760|e:e},f.prototype.readInt16BE=function(t,r){t>>>=0,r||L(t,2,this.length);var e=this[t+1]|this[t]<<8;return 32768&e?4294901760|e:e},f.prototype.readInt32LE=function(t,r){return t>>>=0,r||L(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},f.prototype.readInt32BE=function(t,r){return t>>>=0,r||L(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},f.prototype.readFloatLE=function(t,r){return t>>>=0,r||L(t,4,this.length),o.read(this,t,!0,23,4)},f.prototype.readFloatBE=function(t,r){return t>>>=0,r||L(t,4,this.length),o.read(this,t,!1,23,4)},f.prototype.readDoubleLE=function(t,r){return t>>>=0,r||L(t,8,this.length),o.read(this,t,!0,52,8)},f.prototype.readDoubleBE=function(t,r){return t>>>=0,r||L(t,8,this.length),o.read(this,t,!1,52,8)},f.prototype.writeUIntLE=function(t,r,e,n){(t=+t,r>>>=0,e>>>=0,n)||x(this,t,r,e,Math.pow(2,8*e)-1,0);var o=1,i=0;for(this[r]=255&t;++i<e&&(o*=256);)this[r+i]=t/o&255;return r+e},f.prototype.writeUIntBE=function(t,r,e,n){(t=+t,r>>>=0,e>>>=0,n)||x(this,t,r,e,Math.pow(2,8*e)-1,0);var o=e-1,i=1;for(this[r+o]=255&t;--o>=0&&(i*=256);)this[r+o]=t/i&255;return r+e},f.prototype.writeUInt8=function(t,r,e){return t=+t,r>>>=0,e||x(this,t,r,1,255,0),this[r]=255&t,r+1},f.prototype.writeUInt16LE=function(t,r,e){return t=+t,r>>>=0,e||x(this,t,r,2,65535,0),this[r]=255&t,this[r+1]=t>>>8,r+2},f.prototype.writeUInt16BE=function(t,r,e){return t=+t,r>>>=0,e||x(this,t,r,2,65535,0),this[r]=t>>>8,this[r+1]=255&t,r+2},f.prototype.writeUInt32LE=function(t,r,e){return t=+t,r>>>=0,e||x(this,t,r,4,4294967295,0),this[r+3]=t>>>24,this[r+2]=t>>>16,this[r+1]=t>>>8,this[r]=255&t,r+4},f.prototype.writeUInt32BE=function(t,r,e){return t=+t,r>>>=0,e||x(this,t,r,4,4294967295,0),this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t,r+4},f.prototype.writeIntLE=function(t,r,e,n){if(t=+t,r>>>=0,!n){var o=Math.pow(2,8*e-1);x(this,t,r,e,o-1,-o)}var i=0,u=1,a=0;for(this[r]=255&t;++i<e&&(u*=256);)t<0&&0===a&&0!==this[r+i-1]&&(a=1),this[r+i]=(t/u>>0)-a&255;return r+e},f.prototype.writeIntBE=function(t,r,e,n){if(t=+t,r>>>=0,!n){var o=Math.pow(2,8*e-1);x(this,t,r,e,o-1,-o)}var i=e-1,u=1,a=0;for(this[r+i]=255&t;--i>=0&&(u*=256);)t<0&&0===a&&0!==this[r+i+1]&&(a=1),this[r+i]=(t/u>>0)-a&255;return r+e},f.prototype.writeInt8=function(t,r,e){return t=+t,r>>>=0,e||x(this,t,r,1,127,-128),t<0&&(t=255+t+1),this[r]=255&t,r+1},f.prototype.writeInt16LE=function(t,r,e){return t=+t,r>>>=0,e||x(this,t,r,2,32767,-32768),this[r]=255&t,this[r+1]=t>>>8,r+2},f.prototype.writeInt16BE=function(t,r,e){return t=+t,r>>>=0,e||x(this,t,r,2,32767,-32768),this[r]=t>>>8,this[r+1]=255&t,r+2},f.prototype.writeInt32LE=function(t,r,e){return t=+t,r>>>=0,e||x(this,t,r,4,2147483647,-2147483648),this[r]=255&t,this[r+1]=t>>>8,this[r+2]=t>>>16,this[r+3]=t>>>24,r+4},f.prototype.writeInt32BE=function(t,r,e){return t=+t,r>>>=0,e||x(this,t,r,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t,r+4},f.prototype.writeFloatLE=function(t,r,e){return _(this,t,r,!0,e)},f.prototype.writeFloatBE=function(t,r,e){return _(this,t,r,!1,e)},f.prototype.writeDoubleLE=function(t,r,e){return k(this,t,r,!0,e)},f.prototype.writeDoubleBE=function(t,r,e){return k(this,t,r,!1,e)},f.prototype.copy=function(t,r,e,n){if(!f.isBuffer(t))throw new TypeError("argument should be a Buffer");if(e||(e=0),n||0===n||(n=this.length),r>=t.length&&(r=t.length),r||(r=0),n>0&&n<e&&(n=e),n===e)return 0;if(0===t.length||0===this.length)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(e<0||e>=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),t.length-r<n-e&&(n=t.length-r+e);var o=n-e;if(this===t&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(r,e,n);else if(this===t&&e<r&&r<n)for(var i=o-1;i>=0;--i)t[i+r]=this[i+e];else Uint8Array.prototype.set.call(t,this.subarray(e,n),r);return o},f.prototype.fill=function(t,r,e,n){if("string"==typeof t){if("string"==typeof r?(n=r,r=0,e=this.length):"string"==typeof e&&(n=e,e=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!f.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===t.length){var o=t.charCodeAt(0);("utf8"===n&&o<128||"latin1"===n)&&(t=o)}}else"number"==typeof t?t&=255:"boolean"==typeof t&&(t=Number(t));if(r<0||this.length<r||this.length<e)throw new RangeError("Out of range index");if(e<=r)return this;var i;if(r>>>=0,e=void 0===e?this.length:e>>>0,t||(t=0),"number"==typeof t)for(i=r;i<e;++i)this[i]=t;else{var u=f.isBuffer(t)?t:f.from(t,n),a=u.length;if(0===a)throw new TypeError('The value "'+t+'" is invalid for argument "value"');for(i=0;i<e-r;++i)this[i+r]=u[i%a]}return this};var O=/[^+/0-9A-Za-z-_]/g;function Y(t,r){var e;r=r||1/0;for(var n=t.length,o=null,i=[],u=0;u<n;++u){if((e=t.charCodeAt(u))>55295&&e<57344){if(!o){if(e>56319){(r-=3)>-1&&i.push(239,191,189);continue}if(u+1===n){(r-=3)>-1&&i.push(239,191,189);continue}o=e;continue}if(e<56320){(r-=3)>-1&&i.push(239,191,189),o=e;continue}e=65536+(o-55296<<10|e-56320)}else o&&(r-=3)>-1&&i.push(239,191,189);if(o=null,e<128){if((r-=1)<0)break;i.push(e)}else if(e<2048){if((r-=2)<0)break;i.push(e>>6|192,63&e|128)}else if(e<65536){if((r-=3)<0)break;i.push(e>>12|224,e>>6&63|128,63&e|128)}else{if(!(e<1114112))throw new Error("Invalid code point");if((r-=4)<0)break;i.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}}return i}function D(t){return n.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(O,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function j(t,r,e,n){for(var o=0;o<n&&!(o+e>=r.length||o>=t.length);++o)r[o+e]=t[o];return o}function F(t,r){return t instanceof r||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===r.name}function z(t){return t!=t}var H=function(){for(var t="0123456789abcdef",r=new Array(256),e=0;e<16;++e)for(var n=16*e,o=0;o<16;++o)r[n+o]=t[e]+t[o];return r}()},{"base64-js":29,ieee754:32}],31:[function(t,r,e){"use strict";var n={single_source_shortest_paths:function(t,r,e){var o={},i={};i[r]=0;var u,a,f,s,h,c,l,g=n.PriorityQueue.make();for(g.push(r,0);!g.empty();)for(f in a=(u=g.pop()).value,s=u.cost,h=t[a]||{})h.hasOwnProperty(f)&&(c=s+h[f],l=i[f],(void 0===i[f]||l>c)&&(i[f]=c,g.push(f,c),o[f]=a));if(void 0!==e&&void 0===i[e]){var p=["Could not find a path from ",r," to ",e,"."].join("");throw new Error(p)}return o},extract_shortest_path_from_predecessor_list:function(t,r){for(var e=[],n=r;n;)e.push(n),t[n],n=t[n];return e.reverse(),e},find_path:function(t,r,e){var o=n.single_source_shortest_paths(t,r,e);return n.extract_shortest_path_from_predecessor_list(o,e)},PriorityQueue:{make:function(t){var r,e=n.PriorityQueue,o={};for(r in t=t||{},e)e.hasOwnProperty(r)&&(o[r]=e[r]);return o.queue=[],o.sorter=t.sorter||e.default_sorter,o},default_sorter:function(t,r){return t.cost-r.cost},push:function(t,r){var e={value:t,cost:r};this.queue.push(e),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return 0===this.queue.length}}};void 0!==r&&(r.exports=n)},{}],32:[function(t,r,e){e.read=function(t,r,e,n,o){var i,u,a=8*o-n-1,f=(1<<a)-1,s=f>>1,h=-7,c=e?o-1:0,l=e?-1:1,g=t[r+c];for(c+=l,i=g&(1<<-h)-1,g>>=-h,h+=a;h>0;i=256*i+t[r+c],c+=l,h-=8);for(u=i&(1<<-h)-1,i>>=-h,h+=n;h>0;u=256*u+t[r+c],c+=l,h-=8);if(0===i)i=1-s;else{if(i===f)return u?NaN:1/0*(g?-1:1);u+=Math.pow(2,n),i-=s}return(g?-1:1)*u*Math.pow(2,i-n)},e.write=function(t,r,e,n,o,i){var u,a,f,s=8*i-o-1,h=(1<<s)-1,c=h>>1,l=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,g=n?0:i-1,p=n?1:-1,d=r<0||0===r&&1/r<0?1:0;for(r=Math.abs(r),isNaN(r)||r===1/0?(a=isNaN(r)?1:0,u=h):(u=Math.floor(Math.log(r)/Math.LN2),r*(f=Math.pow(2,-u))<1&&(u--,f*=2),(r+=u+c>=1?l/f:l*Math.pow(2,1-c))*f>=2&&(u++,f/=2),u+c>=h?(a=0,u=h):u+c>=1?(a=(r*f-1)*Math.pow(2,o),u+=c):(a=r*Math.pow(2,c-1)*Math.pow(2,o),u=0));o>=8;t[e+g]=255&a,g+=p,a/=256,o-=8);for(u=u<<o|a,s+=o;s>0;t[e+g]=255&u,g+=p,u/=256,s-=8);t[e+g-p]|=128*d}},{}],33:[function(t,r,e){var n={}.toString;r.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},{}]},{},[24])(24)}));
\ No newline at end of file
index 3e16ea9..9c09b6b 100644 (file)
@@ -1,3 +1 @@
-!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var r;r="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,r.QRCode=t()}}(function(){return function(){function t(r,e,n){function o(u,a){if(!e[u]){if(!r[u]){var f="function"==typeof require&&require;if(!a&&f)return f(u,!0);if(i)return i(u,!0);var s=new Error("Cannot find module '"+u+"'");throw s.code="MODULE_NOT_FOUND",s}var h=e[u]={exports:{}};r[u][0].call(h.exports,function(t){return o(r[u][1][t]||t)},h,h.exports,t,r,e,n)}return e[u].exports}for(var i="function"==typeof require&&require,u=0;u<n.length;u++)o(n[u]);return o}return t}()({1:[function(t,r,e){r.exports=function(){return"function"==typeof Promise&&Promise.prototype&&Promise.prototype.then}},{}],2:[function(t,r,e){var n=t("./utils").getSymbolSize;e.getRowColCoords=function(t){if(1===t)return[];for(var r=Math.floor(t/7)+2,e=n(t),o=145===e?26:2*Math.ceil((e-13)/(2*r-2)),i=[e-7],u=1;u<r-1;u++)i[u]=i[u-1]-o;return i.push(6),i.reverse()},e.getPositions=function(t){for(var r=[],n=e.getRowColCoords(t),o=n.length,i=0;i<o;i++)for(var u=0;u<o;u++)0===i&&0===u||0===i&&u===o-1||i===o-1&&0===u||r.push([n[i],n[u]]);return r}},{"./utils":21}],3:[function(t,r,e){function n(t){this.mode=o.ALPHANUMERIC,this.data=t}var o=t("./mode"),i=["0","1","2","3","4","5","6","7","8","9","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"," ","$","%","*","+","-",".","/",":"];n.getBitsLength=function(t){return 11*Math.floor(t/2)+t%2*6},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(t){var r;for(r=0;r+2<=this.data.length;r+=2){var e=45*i.indexOf(this.data[r]);e+=i.indexOf(this.data[r+1]),t.put(e,11)}this.data.length%2&&t.put(i.indexOf(this.data[r]),6)},r.exports=n},{"./mode":14}],4:[function(t,r,e){function n(){this.buffer=[],this.length=0}n.prototype={get:function(t){var r=Math.floor(t/8);return 1==(this.buffer[r]>>>7-t%8&1)},put:function(t,r){for(var e=0;e<r;e++)this.putBit(1==(t>>>r-e-1&1))},getLengthInBits:function(){return this.length},putBit:function(t){var r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),t&&(this.buffer[r]|=128>>>this.length%8),this.length++}},r.exports=n},{}],5:[function(t,r,e){function n(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=o.alloc(t*t),this.reservedBit=o.alloc(t*t)}var o=t("../utils/buffer");n.prototype.set=function(t,r,e,n){var o=t*this.size+r;this.data[o]=e,n&&(this.reservedBit[o]=!0)},n.prototype.get=function(t,r){return this.data[t*this.size+r]},n.prototype.xor=function(t,r,e){this.data[t*this.size+r]^=e},n.prototype.isReserved=function(t,r){return this.reservedBit[t*this.size+r]},r.exports=n},{"../utils/buffer":28}],6:[function(t,r,e){function n(t){this.mode=i.BYTE,this.data=o.from(t)}var o=t("../utils/buffer"),i=t("./mode");n.getBitsLength=function(t){return 8*t},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(t){for(var r=0,e=this.data.length;r<e;r++)t.put(this.data[r],8)},r.exports=n},{"../utils/buffer":28,"./mode":14}],7:[function(t,r,e){var n=t("./error-correction-level"),o=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],i=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];e.getBlocksCount=function(t,r){switch(r){case n.L:return o[4*(t-1)+0];case n.M:return o[4*(t-1)+1];case n.Q:return o[4*(t-1)+2];case n.H:return o[4*(t-1)+3];default:return}},e.getTotalCodewordsCount=function(t,r){switch(r){case n.L:return i[4*(t-1)+0];case n.M:return i[4*(t-1)+1];case n.Q:return i[4*(t-1)+2];case n.H:return i[4*(t-1)+3];default:return}}},{"./error-correction-level":8}],8:[function(t,r,e){function n(t){if("string"!=typeof t)throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+t)}}e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2},e.isValid=function(t){return t&&void 0!==t.bit&&t.bit>=0&&t.bit<4},e.from=function(t,r){if(e.isValid(t))return t;try{return n(t)}catch(t){return r}}},{}],9:[function(t,r,e){var n=t("./utils").getSymbolSize;e.getPositions=function(t){var r=n(t);return[[0,0],[r-7,0],[0,r-7]]}},{"./utils":21}],10:[function(t,r,e){var n=t("./utils"),o=n.getBCHDigit(1335);e.getEncodedBits=function(t,r){for(var e=t.bit<<3|r,i=e<<10;n.getBCHDigit(i)-o>=0;)i^=1335<<n.getBCHDigit(i)-o;return 21522^(e<<10|i)}},{"./utils":21}],11:[function(t,r,e){var n=t("../utils/buffer"),o=n.alloc(512),i=n.alloc(256);!function(){for(var t=1,r=0;r<255;r++)o[r]=t,i[t]=r,256&(t<<=1)&&(t^=285);for(r=255;r<512;r++)o[r]=o[r-255]}(),e.log=function(t){if(t<1)throw new Error("log("+t+")");return i[t]},e.exp=function(t){return o[t]},e.mul=function(t,r){return 0===t||0===r?0:o[i[t]+i[r]]}},{"../utils/buffer":28}],12:[function(t,r,e){function n(t){this.mode=o.KANJI,this.data=t}var o=t("./mode"),i=t("./utils");n.getBitsLength=function(t){return 13*t},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(t){var r;for(r=0;r<this.data.length;r++){var e=i.toSJIS(this.data[r]);if(e>=33088&&e<=40956)e-=33088;else{if(!(e>=57408&&e<=60351))throw new Error("Invalid SJIS character: "+this.data[r]+"\nMake sure your charset is UTF-8");e-=49472}e=192*(e>>>8&255)+(255&e),t.put(e,13)}},r.exports=n},{"./mode":14,"./utils":21}],13:[function(t,r,e){function n(t,r,n){switch(t){case e.Patterns.PATTERN000:return(r+n)%2==0;case e.Patterns.PATTERN001:return r%2==0;case e.Patterns.PATTERN010:return n%3==0;case e.Patterns.PATTERN011:return(r+n)%3==0;case e.Patterns.PATTERN100:return(Math.floor(r/2)+Math.floor(n/3))%2==0;case e.Patterns.PATTERN101:return r*n%2+r*n%3==0;case e.Patterns.PATTERN110:return(r*n%2+r*n%3)%2==0;case e.Patterns.PATTERN111:return(r*n%3+(r+n)%2)%2==0;default:throw new Error("bad maskPattern:"+t)}}e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var o={N1:3,N2:3,N3:40,N4:10};e.isValid=function(t){return null!=t&&""!==t&&!isNaN(t)&&t>=0&&t<=7},e.from=function(t){return e.isValid(t)?parseInt(t,10):void 0},e.getPenaltyN1=function(t){for(var r=t.size,e=0,n=0,i=0,u=null,a=null,f=0;f<r;f++){n=i=0,u=a=null;for(var s=0;s<r;s++){var h=t.get(f,s);h===u?n++:(n>=5&&(e+=o.N1+(n-5)),u=h,n=1),h=t.get(s,f),h===a?i++:(i>=5&&(e+=o.N1+(i-5)),a=h,i=1)}n>=5&&(e+=o.N1+(n-5)),i>=5&&(e+=o.N1+(i-5))}return e},e.getPenaltyN2=function(t){for(var r=t.size,e=0,n=0;n<r-1;n++)for(var i=0;i<r-1;i++){var u=t.get(n,i)+t.get(n,i+1)+t.get(n+1,i)+t.get(n+1,i+1);4!==u&&0!==u||e++}return e*o.N2},e.getPenaltyN3=function(t){for(var r=t.size,e=0,n=0,i=0,u=0;u<r;u++){n=i=0;for(var a=0;a<r;a++)n=n<<1&2047|t.get(u,a),a>=10&&(1488===n||93===n)&&e++,i=i<<1&2047|t.get(a,u),a>=10&&(1488===i||93===i)&&e++}return e*o.N3},e.getPenaltyN4=function(t){for(var r=0,e=t.data.length,n=0;n<e;n++)r+=t.data[n];return Math.abs(Math.ceil(100*r/e/5)-10)*o.N4},e.applyMask=function(t,r){for(var e=r.size,o=0;o<e;o++)for(var i=0;i<e;i++)r.isReserved(i,o)||r.xor(i,o,n(t,i,o))},e.getBestMask=function(t,r){for(var n=Object.keys(e.Patterns).length,o=0,i=1/0,u=0;u<n;u++){r(u),e.applyMask(u,t);var a=e.getPenaltyN1(t)+e.getPenaltyN2(t)+e.getPenaltyN3(t)+e.getPenaltyN4(t);e.applyMask(u,t),a<i&&(i=a,o=u)}return o}},{}],14:[function(t,r,e){function n(t){if("string"!=typeof t)throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+t)}}var o=t("./version-check"),i=t("./regex");e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(t,r){if(!t.ccBits)throw new Error("Invalid mode: "+t);if(!o.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?t.ccBits[0]:r<27?t.ccBits[1]:t.ccBits[2]},e.getBestModeForData=function(t){return i.testNumeric(t)?e.NUMERIC:i.testAlphanumeric(t)?e.ALPHANUMERIC:i.testKanji(t)?e.KANJI:e.BYTE},e.toString=function(t){if(t&&t.id)return t.id;throw new Error("Invalid mode")},e.isValid=function(t){return t&&t.bit&&t.ccBits},e.from=function(t,r){if(e.isValid(t))return t;try{return n(t)}catch(t){return r}}},{"./regex":19,"./version-check":22}],15:[function(t,r,e){function n(t){this.mode=o.NUMERIC,this.data=t.toString()}var o=t("./mode");n.getBitsLength=function(t){return 10*Math.floor(t/3)+(t%3?t%3*3+1:0)},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(t){var r,e,n;for(r=0;r+3<=this.data.length;r+=3)e=this.data.substr(r,3),n=parseInt(e,10),t.put(n,10);var o=this.data.length-r;o>0&&(e=this.data.substr(r),n=parseInt(e,10),t.put(n,3*o+1))},r.exports=n},{"./mode":14}],16:[function(t,r,e){var n=t("../utils/buffer"),o=t("./galois-field");e.mul=function(t,r){for(var e=n.alloc(t.length+r.length-1),i=0;i<t.length;i++)for(var u=0;u<r.length;u++)e[i+u]^=o.mul(t[i],r[u]);return e},e.mod=function(t,r){for(var e=n.from(t);e.length-r.length>=0;){for(var i=e[0],u=0;u<r.length;u++)e[u]^=o.mul(r[u],i);for(var a=0;a<e.length&&0===e[a];)a++;e=e.slice(a)}return e},e.generateECPolynomial=function(t){for(var r=n.from([1]),i=0;i<t;i++)r=e.mul(r,[1,o.exp(i)]);return r}},{"../utils/buffer":28,"./galois-field":11}],17:[function(t,r,e){function n(t,r){for(var e=t.size,n=w.getPositions(r),o=0;o<n.length;o++)for(var i=n[o][0],u=n[o][1],a=-1;a<=7;a++)if(!(i+a<=-1||e<=i+a))for(var f=-1;f<=7;f++)u+f<=-1||e<=u+f||(a>=0&&a<=6&&(0===f||6===f)||f>=0&&f<=6&&(0===a||6===a)||a>=2&&a<=4&&f>=2&&f<=4?t.set(i+a,u+f,!0,!0):t.set(i+a,u+f,!1,!0))}function o(t){for(var r=t.size,e=8;e<r-8;e++){var n=e%2==0;t.set(e,6,n,!0),t.set(6,e,n,!0)}}function i(t,r){for(var e=v.getPositions(r),n=0;n<e.length;n++)for(var o=e[n][0],i=e[n][1],u=-2;u<=2;u++)for(var a=-2;a<=2;a++)-2===u||2===u||-2===a||2===a||0===u&&0===a?t.set(o+u,i+a,!0,!0):t.set(o+u,i+a,!1,!0)}function u(t,r){for(var e,n,o,i=t.size,u=A.getEncodedBits(r),a=0;a<18;a++)e=Math.floor(a/3),n=a%3+i-8-3,o=1==(u>>a&1),t.set(e,n,o,!0),t.set(n,e,o,!0)}function a(t,r,e){var n,o,i=t.size,u=B.getEncodedBits(r,e);for(n=0;n<15;n++)o=1==(u>>n&1),n<6?t.set(n,8,o,!0):n<8?t.set(n+1,8,o,!0):t.set(i-15+n,8,o,!0),n<8?t.set(8,i-n-1,o,!0):n<9?t.set(8,15-n-1+1,o,!0):t.set(8,15-n-1,o,!0);t.set(i-8,8,1,!0)}function f(t,r){for(var e=t.size,n=-1,o=e-1,i=7,u=0,a=e-1;a>0;a-=2)for(6===a&&a--;;){for(var f=0;f<2;f++)if(!t.isReserved(o,a-f)){var s=!1;u<r.length&&(s=1==(r[u]>>>i&1)),t.set(o,a-f,s),i--,-1===i&&(u++,i=7)}if((o+=n)<0||e<=o){o-=n,n=-n;break}}}function s(t,r,e){var n=new d;e.forEach(function(r){n.put(r.mode.bit,4),n.put(r.getLength(),T.getCharCountIndicator(r.mode,t)),r.write(n)});var o=g.getSymbolTotalCodewords(t),i=b.getTotalCodewordsCount(t,r),u=8*(o-i);for(n.getLengthInBits()+4<=u&&n.put(0,4);n.getLengthInBits()%8!=0;)n.putBit(0);for(var a=(u-n.getLengthInBits())/8,f=0;f<a;f++)n.put(f%2?17:236,8);return h(n,t,r)}function h(t,r,e){for(var n=g.getSymbolTotalCodewords(r),o=b.getTotalCodewordsCount(r,e),i=n-o,u=b.getBlocksCount(r,e),a=n%u,f=u-a,s=Math.floor(n/u),h=Math.floor(i/u),c=h+1,p=s-h,d=new E(p),y=0,v=new Array(u),w=new Array(u),m=0,A=l.from(t.buffer),B=0;B<u;B++){var T=B<f?h:c;v[B]=A.slice(y,y+T),w[B]=d.encode(v[B]),y+=T,m=Math.max(m,T)}var R,C,P=l.alloc(n),I=0;for(R=0;R<m;R++)for(C=0;C<u;C++)R<v[C].length&&(P[I++]=v[C][R]);for(R=0;R<p;R++)for(C=0;C<u;C++)P[I++]=w[C][R];return P}function c(t,r,e,h){var c;if(C(t))c=R.fromArray(t);else{if("string"!=typeof t)throw new Error("Invalid data");var l=r;if(!l){var p=R.rawSplit(t);l=A.getBestVersionForData(p,e)}c=R.fromString(t,l||40)}var d=A.getBestVersionForData(c,e);if(!d)throw new Error("The amount of data is too big to be stored in a QR Code");if(r){if(r<d)throw new Error("\nThe chosen QR Code version cannot contain this amount of data.\nMinimum version required to store current data is: "+d+".\n")}else r=d;var v=s(r,e,c),w=g.getSymbolSize(r),b=new y(w);return n(b,r),o(b),i(b,r),a(b,e,0),r>=7&&u(b,r),f(b,v),isNaN(h)&&(h=m.getBestMask(b,a.bind(null,b,e))),m.applyMask(h,b),a(b,e,h),{modules:b,version:r,errorCorrectionLevel:e,maskPattern:h,segments:c}}var l=t("../utils/buffer"),g=t("./utils"),p=t("./error-correction-level"),d=t("./bit-buffer"),y=t("./bit-matrix"),v=t("./alignment-pattern"),w=t("./finder-pattern"),m=t("./mask-pattern"),b=t("./error-correction-code"),E=t("./reed-solomon-encoder"),A=t("./version"),B=t("./format-info"),T=t("./mode"),R=t("./segments"),C=t("isarray");e.create=function(t,r){if(void 0===t||""===t)throw new Error("No input text");var e,n,o=p.M;return void 0!==r&&(o=p.from(r.errorCorrectionLevel,p.M),e=A.from(r.version),n=m.from(r.maskPattern),r.toSJISFunc&&g.setToSJISFunction(r.toSJISFunc)),c(t,e,o,n)}},{"../utils/buffer":28,"./alignment-pattern":2,"./bit-buffer":4,"./bit-matrix":5,"./error-correction-code":7,"./error-correction-level":8,"./finder-pattern":9,"./format-info":10,"./mask-pattern":13,"./mode":14,"./reed-solomon-encoder":18,"./segments":20,"./utils":21,"./version":23,isarray:33}],18:[function(t,r,e){function n(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}var o=t("../utils/buffer"),i=t("./polynomial"),u=t("buffer").Buffer;n.prototype.initialize=function(t){this.degree=t,this.genPoly=i.generateECPolynomial(this.degree)},n.prototype.encode=function(t){if(!this.genPoly)throw new Error("Encoder not initialized");var r=o.alloc(this.degree),e=u.concat([t,r],t.length+this.degree),n=i.mod(e,this.genPoly),a=this.degree-n.length;if(a>0){var f=o.alloc(this.degree);return n.copy(f,a),f}return n},r.exports=n},{"../utils/buffer":28,"./polynomial":16,buffer:30}],19:[function(t,r,e){var n="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";n=n.replace(/u/g,"\\u");var o="(?:(?![A-Z0-9 $%*+\\-./:]|"+n+")(?:.|[\r\n]))+";e.KANJI=new RegExp(n,"g"),e.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),e.BYTE=new RegExp(o,"g"),e.NUMERIC=new RegExp("[0-9]+","g"),e.ALPHANUMERIC=new RegExp("[A-Z $%*+\\-./:]+","g");var i=new RegExp("^"+n+"$"),u=new RegExp("^[0-9]+$"),a=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");e.testKanji=function(t){return i.test(t)},e.testNumeric=function(t){return u.test(t)},e.testAlphanumeric=function(t){return a.test(t)}},{}],20:[function(t,r,e){function n(t){return unescape(encodeURIComponent(t)).length}function o(t,r,e){for(var n,o=[];null!==(n=t.exec(e));)o.push({data:n[0],index:n.index,mode:r,length:n[0].length});return o}function i(t){var r,e,n=o(y.NUMERIC,c.NUMERIC,t),i=o(y.ALPHANUMERIC,c.ALPHANUMERIC,t);return v.isKanjiModeEnabled()?(r=o(y.BYTE,c.BYTE,t),e=o(y.KANJI,c.KANJI,t)):(r=o(y.BYTE_KANJI,c.BYTE,t),e=[]),n.concat(i,r,e).sort(function(t,r){return t.index-r.index}).map(function(t){return{data:t.data,mode:t.mode,length:t.length}})}function u(t,r){switch(r){case c.NUMERIC:return l.getBitsLength(t);case c.ALPHANUMERIC:return g.getBitsLength(t);case c.KANJI:return d.getBitsLength(t);case c.BYTE:return p.getBitsLength(t)}}function a(t){return t.reduce(function(t,r){var e=t.length-1>=0?t[t.length-1]:null;return e&&e.mode===r.mode?(t[t.length-1].data+=r.data,t):(t.push(r),t)},[])}function f(t){for(var r=[],e=0;e<t.length;e++){var o=t[e];switch(o.mode){case c.NUMERIC:r.push([o,{data:o.data,mode:c.ALPHANUMERIC,length:o.length},{data:o.data,mode:c.BYTE,length:o.length}]);break;case c.ALPHANUMERIC:r.push([o,{data:o.data,mode:c.BYTE,length:o.length}]);break;case c.KANJI:r.push([o,{data:o.data,mode:c.BYTE,length:n(o.data)}]);break;case c.BYTE:r.push([{data:o.data,mode:c.BYTE,length:n(o.data)}])}}return r}function s(t,r){for(var e={},n={start:{}},o=["start"],i=0;i<t.length;i++){for(var a=t[i],f=[],s=0;s<a.length;s++){var h=a[s],l=""+i+s;f.push(l),e[l]={node:h,lastCount:0},n[l]={};for(var g=0;g<o.length;g++){var p=o[g];e[p]&&e[p].node.mode===h.mode?(n[p][l]=u(e[p].lastCount+h.length,h.mode)-u(e[p].lastCount,h.mode),e[p].lastCount+=h.length):(e[p]&&(e[p].lastCount=h.length),n[p][l]=u(h.length,h.mode)+4+c.getCharCountIndicator(h.mode,r))}}o=f}for(g=0;g<o.length;g++)n[o[g]].end=0;return{map:n,table:e}}function h(t,r){var e,n=c.getBestModeForData(t);if((e=c.from(r,n))!==c.BYTE&&e.bit<n.bit)throw new Error('"'+t+'" cannot be encoded with mode '+c.toString(e)+".\n Suggested mode is: "+c.toString(n));switch(e!==c.KANJI||v.isKanjiModeEnabled()||(e=c.BYTE),e){case c.NUMERIC:return new l(t);case c.ALPHANUMERIC:return new g(t);case c.KANJI:return new d(t);case c.BYTE:return new p(t)}}var c=t("./mode"),l=t("./numeric-data"),g=t("./alphanumeric-data"),p=t("./byte-data"),d=t("./kanji-data"),y=t("./regex"),v=t("./utils"),w=t("dijkstrajs");e.fromArray=function(t){return t.reduce(function(t,r){return"string"==typeof r?t.push(h(r,null)):r.data&&t.push(h(r.data,r.mode)),t},[])},e.fromString=function(t,r){for(var n=i(t,v.isKanjiModeEnabled()),o=f(n),u=s(o,r),h=w.find_path(u.map,"start","end"),c=[],l=1;l<h.length-1;l++)c.push(u.table[h[l]].node);return e.fromArray(a(c))},e.rawSplit=function(t){return e.fromArray(i(t,v.isKanjiModeEnabled()))}},{"./alphanumeric-data":3,"./byte-data":6,"./kanji-data":12,"./mode":14,"./numeric-data":15,"./regex":19,"./utils":21,dijkstrajs:31}],21:[function(t,r,e){var n,o=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];e.getSymbolSize=function(t){if(!t)throw new Error('"version" cannot be null or undefined');if(t<1||t>40)throw new Error('"version" should be in range from 1 to 40');return 4*t+17},e.getSymbolTotalCodewords=function(t){return o[t]},e.getBCHDigit=function(t){for(var r=0;0!==t;)r++,t>>>=1;return r},e.setToSJISFunction=function(t){if("function"!=typeof t)throw new Error('"toSJISFunc" is not a valid function.');n=t},e.isKanjiModeEnabled=function(){return void 0!==n},e.toSJIS=function(t){return n(t)}},{}],22:[function(t,r,e){e.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}},{}],23:[function(t,r,e){function n(t,r,n){for(var o=1;o<=40;o++)if(r<=e.getCapacity(o,n,t))return o}function o(t,r){return h.getCharCountIndicator(t,r)+4}function i(t,r){var e=0;return t.forEach(function(t){var n=o(t.mode,r);e+=n+t.getBitsLength()}),e}function u(t,r){for(var n=1;n<=40;n++){if(i(t,n)<=e.getCapacity(n,r,h.MIXED))return n}}var a=t("./utils"),f=t("./error-correction-code"),s=t("./error-correction-level"),h=t("./mode"),c=t("./version-check"),l=t("isarray"),g=a.getBCHDigit(7973);e.from=function(t,r){return c.isValid(t)?parseInt(t,10):r},e.getCapacity=function(t,r,e){if(!c.isValid(t))throw new Error("Invalid QR Code version");void 0===e&&(e=h.BYTE);var n=a.getSymbolTotalCodewords(t),i=f.getTotalCodewordsCount(t,r),u=8*(n-i);if(e===h.MIXED)return u;var s=u-o(e,t);switch(e){case h.NUMERIC:return Math.floor(s/10*3);case h.ALPHANUMERIC:return Math.floor(s/11*2);case h.KANJI:return Math.floor(s/13);case h.BYTE:default:return Math.floor(s/8)}},e.getBestVersionForData=function(t,r){var e,o=s.from(r,s.M);if(l(t)){if(t.length>1)return u(t,o);if(0===t.length)return 1;e=t[0]}else e=t;return n(e.mode,e.getLength(),o)},e.getEncodedBits=function(t){if(!c.isValid(t)||t<7)throw new Error("Invalid QR Code version");for(var r=t<<12;a.getBCHDigit(r)-g>=0;)r^=7973<<a.getBCHDigit(r)-g;return t<<12|r}},{"./error-correction-code":7,"./error-correction-level":8,"./mode":14,"./utils":21,"./version-check":22,isarray:33}],24:[function(t,r,e){function n(t,r,e,n,u){var a=[].slice.call(arguments,1),f=a.length,s="function"==typeof a[f-1];if(!s&&!o())throw new Error("Callback required as last argument");if(!s){if(f<1)throw new Error("Too few arguments provided");return 1===f?(e=r,r=n=void 0):2!==f||r.getContext||(n=e,e=r,r=void 0),new Promise(function(o,u){try{var a=i.create(e,n);o(t(a,r,n))}catch(t){u(t)}})}if(f<2)throw new Error("Too few arguments provided");2===f?(u=e,e=r,r=n=void 0):3===f&&(r.getContext&&void 0===u?(u=n,n=void 0):(u=n,n=e,e=r,r=void 0));try{var h=i.create(e,n);u(null,t(h,r,n))}catch(t){u(t)}}var o=t("./can-promise"),i=t("./core/qrcode"),u=t("./renderer/canvas"),a=t("./renderer/svg-tag.js");e.create=i.create,e.toCanvas=n.bind(null,u.render),e.toDataURL=n.bind(null,u.renderToDataURL),e.toString=n.bind(null,function(t,r,e){return a.render(t,e)})},{"./can-promise":1,"./core/qrcode":17,"./renderer/canvas":25,"./renderer/svg-tag.js":26}],25:[function(t,r,e){function n(t,r,e){t.clearRect(0,0,r.width,r.height),r.style||(r.style={}),r.height=e,r.width=e,r.style.height=e+"px",r.style.width=e+"px"}function o(){try{return document.createElement("canvas")}catch(t){throw new Error("You need to specify a canvas element")}}var i=t("./utils");e.render=function(t,r,e){var u=e,a=r;void 0!==u||r&&r.getContext||(u=r,r=void 0),r||(a=o()),u=i.getOptions(u);var f=i.getImageWidth(t.modules.size,u),s=a.getContext("2d"),h=s.createImageData(f,f);return i.qrToImageData(h.data,t,u),n(s,a,f),s.putImageData(h,0,0),a},e.renderToDataURL=function(t,r,n){var o=n;void 0!==o||r&&r.getContext||(o=r,r=void 0),o||(o={});var i=e.render(t,r,o),u=o.type||"image/png",a=o.rendererOpts||{};return i.toDataURL(u,a.quality)}},{"./utils":27}],26:[function(t,r,e){function n(t,r){var e=t.a/255,n=r+'="'+t.hex+'"';return e<1?n+" "+r+'-opacity="'+e.toFixed(2).slice(1)+'"':n}function o(t,r,e){var n=t+r;return void 0!==e&&(n+=" "+e),n}function i(t,r,e){for(var n="",i=0,u=!1,a=0,f=0;f<t.length;f++){var s=Math.floor(f%r),h=Math.floor(f/r);s||u||(u=!0),t[f]?(a++,f>0&&s>0&&t[f-1]||(n+=u?o("M",s+e,.5+h+e):o("m",i,0),i=0,u=!1),s+1<r&&t[f+1]||(n+=o("h",a),a=0)):i++}return n}var u=t("./utils");e.render=function(t,r,e){var o=u.getOptions(r),a=t.modules.size,f=t.modules.data,s=a+2*o.margin,h=o.color.light.a?"<path "+n(o.color.light,"fill")+' d="M0 0h'+s+"v"+s+'H0z"/>':"",c="<path "+n(o.color.dark,"stroke")+' d="'+i(f,a,o.margin)+'"/>',l='viewBox="0 0 '+s+" "+s+'"',g=o.width?'width="'+o.width+'" height="'+o.width+'" ':"",p='<svg xmlns="http://www.w3.org/2000/svg" '+g+l+' shape-rendering="crispEdges">'+h+c+"</svg>\n";return"function"==typeof e&&e(null,p),p}},{"./utils":27}],27:[function(t,r,e){function n(t){if("number"==typeof t&&(t=t.toString()),"string"!=typeof t)throw new Error("Color should be defined as hex string");var r=t.slice().replace("#","").split("");if(r.length<3||5===r.length||r.length>8)throw new Error("Invalid hex color: "+t);3!==r.length&&4!==r.length||(r=Array.prototype.concat.apply([],r.map(function(t){return[t,t]}))),6===r.length&&r.push("F","F");var e=parseInt(r.join(""),16);return{r:e>>24&255,g:e>>16&255,b:e>>8&255,a:255&e,hex:"#"+r.slice(0,6).join("")}}e.getOptions=function(t){t||(t={}),t.color||(t.color={});var r=void 0===t.margin||null===t.margin||t.margin<0?4:t.margin,e=t.width&&t.width>=21?t.width:void 0,o=t.scale||4;return{width:e,scale:e?4:o,margin:r,color:{dark:n(t.color.dark||"#000000ff"),light:n(t.color.light||"#ffffffff")},type:t.type,rendererOpts:t.rendererOpts||{}}},e.getScale=function(t,r){return r.width&&r.width>=t+2*r.margin?r.width/(t+2*r.margin):r.scale},e.getImageWidth=function(t,r){var n=e.getScale(t,r);return Math.floor((t+2*r.margin)*n)},e.qrToImageData=function(t,r,n){for(var o=r.modules.size,i=r.modules.data,u=e.getScale(o,n),a=Math.floor((o+2*n.margin)*u),f=n.margin*u,s=[n.color.light,n.color.dark],h=0;h<a;h++)for(var c=0;c<a;c++){var l=4*(h*a+c),g=n.color.light;if(h>=f&&c>=f&&h<a-f&&c<a-f){var p=Math.floor((h-f)/u),d=Math.floor((c-f)/u);g=s[i[p*o+d]?1:0]}t[l++]=g.r,t[l++]=g.g,t[l++]=g.b,t[l]=g.a}}},{}],28:[function(t,r,e){"use strict";function n(t,r,e){return n.TYPED_ARRAY_SUPPORT||this instanceof n?"number"==typeof t?a(this,t):y(this,t,r,e):new n(t,r,e)}function o(t){if(t>=w)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+w.toString(16)+" bytes");return 0|t}function i(t){return t!==t}function u(t,r){var e;return n.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(r),e.__proto__=n.prototype):(e=t,null===e&&(e=new n(r)),e.length=r),e}function a(t,r){var e=u(t,r<0?0:0|o(r));if(!n.TYPED_ARRAY_SUPPORT)for(var i=0;i<r;++i)e[i]=0;return e}function f(t,r){var e=0|g(r),n=u(t,e),o=n.write(r);return o!==e&&(n=n.slice(0,o)),n}function s(t,r){for(var e=r.length<0?0:0|o(r.length),n=u(t,e),i=0;i<e;i+=1)n[i]=255&r[i];return n}function h(t,r,e,o){if(e<0||r.byteLength<e)throw new RangeError("'offset' is out of bounds");if(r.byteLength<e+(o||0))throw new RangeError("'length' is out of bounds");var i;return i=void 0===e&&void 0===o?new Uint8Array(r):void 0===o?new Uint8Array(r,e):new Uint8Array(r,e,o),n.TYPED_ARRAY_SUPPORT?i.__proto__=n.prototype:i=s(t,i),i}function c(t,r){if(n.isBuffer(r)){var e=0|o(r.length),a=u(t,e);return 0===a.length?a:(r.copy(a,0,0,e),a)}if(r){if("undefined"!=typeof ArrayBuffer&&r.buffer instanceof ArrayBuffer||"length"in r)return"number"!=typeof r.length||i(r.length)?u(t,0):s(t,r);if("Buffer"===r.type&&Array.isArray(r.data))return s(t,r.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function l(t,r){r=r||1/0;for(var e,n=t.length,o=null,i=[],u=0;u<n;++u){if((e=t.charCodeAt(u))>55295&&e<57344){if(!o){if(e>56319){(r-=3)>-1&&i.push(239,191,189);continue}if(u+1===n){(r-=3)>-1&&i.push(239,191,189);continue}o=e;continue}if(e<56320){(r-=3)>-1&&i.push(239,191,189),o=e;continue}e=65536+(o-55296<<10|e-56320)}else o&&(r-=3)>-1&&i.push(239,191,189);if(o=null,e<128){if((r-=1)<0)break;i.push(e)}else if(e<2048){if((r-=2)<0)break;i.push(e>>6|192,63&e|128)}else if(e<65536){if((r-=3)<0)break;i.push(e>>12|224,e>>6&63|128,63&e|128)}else{if(!(e<1114112))throw new Error("Invalid code point");if((r-=4)<0)break;i.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}}return i}function g(t){return n.isBuffer(t)?t.length:"undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer)?t.byteLength:("string"!=typeof t&&(t=""+t),0===t.length?0:l(t).length)}function p(t,r,e,n){for(var o=0;o<n&&!(o+e>=r.length||o>=t.length);++o)r[o+e]=t[o];return o}function d(t,r,e,n){return p(l(r,t.length-e),t,e,n)}function y(t,r,e,n){if("number"==typeof r)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&r instanceof ArrayBuffer?h(t,r,e,n):"string"==typeof r?f(t,r,e):c(t,r)}var v=t("isarray");n.TYPED_ARRAY_SUPPORT=function(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()}catch(t){return!1}}();var w=n.TYPED_ARRAY_SUPPORT?2147483647:1073741823;n.TYPED_ARRAY_SUPPORT&&(n.prototype.__proto__=Uint8Array.prototype,n.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&n[Symbol.species]===n&&Object.defineProperty(n,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1})),n.prototype.write=function(t,r,e){void 0===r?(e=this.length,r=0):void 0===e&&"string"==typeof r?(e=this.length,r=0):isFinite(r)&&(r|=0,isFinite(e)?e|=0:e=void 0);var n=this.length-r;if((void 0===e||e>n)&&(e=n),t.length>0&&(e<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");return d(this,t,r,e)},n.prototype.slice=function(t,r){var e=this.length;t=~~t,r=void 0===r?e:~~r,t<0?(t+=e)<0&&(t=0):t>e&&(t=e),r<0?(r+=e)<0&&(r=0):r>e&&(r=e),r<t&&(r=t);var o;if(n.TYPED_ARRAY_SUPPORT)o=this.subarray(t,r),o.__proto__=n.prototype;else{var i=r-t;o=new n(i,void 0);for(var u=0;u<i;++u)o[u]=this[u+t]}return o},n.prototype.copy=function(t,r,e,o){if(e||(e=0),o||0===o||(o=this.length),r>=t.length&&(r=t.length),r||(r=0),o>0&&o<e&&(o=e),o===e)return 0;if(0===t.length||0===this.length)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(e<0||e>=this.length)throw new RangeError("sourceStart out of bounds");if(o<0)throw new RangeError("sourceEnd out of bounds");o>this.length&&(o=this.length),t.length-r<o-e&&(o=t.length-r+e);var i,u=o-e;if(this===t&&e<r&&r<o)for(i=u-1;i>=0;--i)t[i+r]=this[i+e];else if(u<1e3||!n.TYPED_ARRAY_SUPPORT)for(i=0;i<u;++i)t[i+r]=this[i+e];else Uint8Array.prototype.set.call(t,this.subarray(e,e+u),r);return u},n.prototype.fill=function(t,r,e){if("string"==typeof t){if("string"==typeof r?(r=0,e=this.length):"string"==typeof e&&(e=this.length),1===t.length){var o=t.charCodeAt(0);o<256&&(t=o)}}else"number"==typeof t&&(t&=255);if(r<0||this.length<r||this.length<e)throw new RangeError("Out of range index");if(e<=r)return this;r>>>=0,e=void 0===e?this.length:e>>>0,t||(t=0);var i;if("number"==typeof t)for(i=r;i<e;++i)this[i]=t;else{var u=n.isBuffer(t)?t:new n(t),a=u.length;for(i=0;i<e-r;++i)this[i+r]=u[i%a]}return this},n.concat=function(t,r){if(!v(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return u(null,0);var e;if(void 0===r)for(r=0,e=0;e<t.length;++e)r+=t[e].length;var o=a(null,r),i=0;for(e=0;e<t.length;++e){var f=t[e];if(!n.isBuffer(f))throw new TypeError('"list" argument must be an Array of Buffers');f.copy(o,i),i+=f.length}return o},n.byteLength=g,n.prototype._isBuffer=!0,n.isBuffer=function(t){return!(null==t||!t._isBuffer)},r.exports.alloc=function(t){var r=new n(t);return r.fill(0),r},r.exports.from=function(t){return new n(t)}},{isarray:33}],29:[function(t,r,e){"use strict";function n(t){var r=t.length;if(r%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var e=t.indexOf("=");return-1===e&&(e=r),[e,e===r?0:4-e%4]}function o(t){var r=n(t),e=r[0],o=r[1];return 3*(e+o)/4-o}function i(t,r,e){return 3*(r+e)/4-e}function u(t){var r,e,o=n(t),u=o[0],a=o[1],f=new l(i(t,u,a)),s=0,h=a>0?u-4:u;for(e=0;e<h;e+=4)r=c[t.charCodeAt(e)]<<18|c[t.charCodeAt(e+1)]<<12|c[t.charCodeAt(e+2)]<<6|c[t.charCodeAt(e+3)],f[s++]=r>>16&255,f[s++]=r>>8&255,f[s++]=255&r;return 2===a&&(r=c[t.charCodeAt(e)]<<2|c[t.charCodeAt(e+1)]>>4,f[s++]=255&r),1===a&&(r=c[t.charCodeAt(e)]<<10|c[t.charCodeAt(e+1)]<<4|c[t.charCodeAt(e+2)]>>2,f[s++]=r>>8&255,f[s++]=255&r),f}function a(t){return h[t>>18&63]+h[t>>12&63]+h[t>>6&63]+h[63&t]}function f(t,r,e){for(var n,o=[],i=r;i<e;i+=3)n=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(255&t[i+2]),o.push(a(n));return o.join("")}function s(t){for(var r,e=t.length,n=e%3,o=[],i=0,u=e-n;i<u;i+=16383)o.push(f(t,i,i+16383>u?u:i+16383));return 1===n?(r=t[e-1],o.push(h[r>>2]+h[r<<4&63]+"==")):2===n&&(r=(t[e-2]<<8)+t[e-1],o.push(h[r>>10]+h[r>>4&63]+h[r<<2&63]+"=")),o.join("")}e.byteLength=o,e.toByteArray=u,e.fromByteArray=s
-;for(var h=[],c=[],l="undefined"!=typeof Uint8Array?Uint8Array:Array,g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p=0,d=g.length;p<d;++p)h[p]=g[p],c[g.charCodeAt(p)]=p;c["-".charCodeAt(0)]=62,c["_".charCodeAt(0)]=63},{}],30:[function(t,r,e){"use strict";function n(t){if(t>$)throw new RangeError('The value "'+t+'" is invalid for option "size"');var r=new Uint8Array(t);return Object.setPrototypeOf(r,o.prototype),r}function o(t,r,e){if("number"==typeof t){if("string"==typeof r)throw new TypeError('The "string" argument must be of type string. Received type number');return f(t)}return i(t,r,e)}function i(t,r,e){if("string"==typeof t)return s(t,r);if(ArrayBuffer.isView(t))return h(t);if(null==t)throw new 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 c(t,r,e);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');var n=t.valueOf&&t.valueOf();if(null!=n&&n!==t)return o.from(n,r,e);var i=l(t);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return o.from(t[Symbol.toPrimitive]("string"),r,e);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function u(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function a(t,r,e){return u(t),t<=0?n(t):void 0!==r?"string"==typeof e?n(t).fill(r,e):n(t).fill(r):n(t)}function f(t){return u(t),n(t<0?0:0|g(t))}function s(t,r){if("string"==typeof r&&""!==r||(r="utf8"),!o.isEncoding(r))throw new TypeError("Unknown encoding: "+r);var e=0|d(t,r),i=n(e),u=i.write(t,r);return u!==e&&(i=i.slice(0,u)),i}function h(t){for(var r=t.length<0?0:0|g(t.length),e=n(r),o=0;o<r;o+=1)e[o]=255&t[o];return e}function c(t,r,e){if(r<0||t.byteLength<r)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<r+(e||0))throw new RangeError('"length" is outside of buffer bounds');var n;return n=void 0===r&&void 0===e?new Uint8Array(t):void 0===e?new Uint8Array(t,r):new Uint8Array(t,r,e),Object.setPrototypeOf(n,o.prototype),n}function l(t){if(o.isBuffer(t)){var r=0|g(t.length),e=n(r);return 0===e.length?e:(t.copy(e,0,0,r),e)}return void 0!==t.length?"number"!=typeof t.length||K(t.length)?n(0):h(t):"Buffer"===t.type&&Array.isArray(t.data)?h(t.data):void 0}function g(t){if(t>=$)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+$.toString(16)+" bytes");return 0|t}function p(t){return+t!=t&&(t=0),o.alloc(+t)}function d(t,r){if(o.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 e=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===e)return 0;for(var i=!1;;)switch(r){case"ascii":case"latin1":case"binary":return e;case"utf8":case"utf-8":return D(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*e;case"hex":return e>>>1;case"base64":return z(t).length;default:if(i)return n?-1:D(t).length;r=(""+r).toLowerCase(),i=!0}}function y(t,r,e){var n=!1;if((void 0===r||r<0)&&(r=0),r>this.length)return"";if((void 0===e||e>this.length)&&(e=this.length),e<=0)return"";if(e>>>=0,r>>>=0,e<=r)return"";for(t||(t="utf8");;)switch(t){case"hex":return N(this,r,e);case"utf8":case"utf-8":return P(this,r,e);case"ascii":return M(this,r,e);case"latin1":case"binary":return U(this,r,e);case"base64":return C(this,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,r,e);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function v(t,r,e){var n=t[r];t[r]=t[e],t[e]=n}function w(t,r,e,n,i){if(0===t.length)return-1;if("string"==typeof e?(n=e,e=0):e>2147483647?e=2147483647:e<-2147483648&&(e=-2147483648),e=+e,K(e)&&(e=i?0:t.length-1),e<0&&(e=t.length+e),e>=t.length){if(i)return-1;e=t.length-1}else if(e<0){if(!i)return-1;e=0}if("string"==typeof r&&(r=o.from(r,n)),o.isBuffer(r))return 0===r.length?-1:m(t,r,e,n,i);if("number"==typeof r)return r&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,r,e):Uint8Array.prototype.lastIndexOf.call(t,r,e):m(t,[r],e,n,i);throw new TypeError("val must be string, number or Buffer")}function m(t,r,e,n,o){function i(t,r){return 1===u?t[r]:t.readUInt16BE(r*u)}var u=1,a=t.length,f=r.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||r.length<2)return-1;u=2,a/=2,f/=2,e/=2}var s;if(o){var h=-1;for(s=e;s<a;s++)if(i(t,s)===i(r,-1===h?0:s-h)){if(-1===h&&(h=s),s-h+1===f)return h*u}else-1!==h&&(s-=s-h),h=-1}else for(e+f>a&&(e=a-f),s=e;s>=0;s--){for(var c=!0,l=0;l<f;l++)if(i(t,s+l)!==i(r,l)){c=!1;break}if(c)return s}return-1}function b(t,r,e,n){e=Number(e)||0;var o=t.length-e;n?(n=Number(n))>o&&(n=o):n=o;var i=r.length;n>i/2&&(n=i/2);for(var u=0;u<n;++u){var a=parseInt(r.substr(2*u,2),16);if(K(a))return u;t[e+u]=a}return u}function E(t,r,e,n){return H(D(r,t.length-e),t,e,n)}function A(t,r,e,n){return H(j(r),t,e,n)}function B(t,r,e,n){return A(t,r,e,n)}function T(t,r,e,n){return H(z(r),t,e,n)}function R(t,r,e,n){return H(F(r,t.length-e),t,e,n)}function C(t,r,e){return 0===r&&e===t.length?q.fromByteArray(t):q.fromByteArray(t.slice(r,e))}function P(t,r,e){e=Math.min(t.length,e);for(var n=[],o=r;o<e;){var i=t[o],u=null,a=i>239?4:i>223?3:i>191?2:1;if(o+a<=e){var f,s,h,c;switch(a){case 1:i<128&&(u=i);break;case 2:f=t[o+1],128==(192&f)&&(c=(31&i)<<6|63&f)>127&&(u=c);break;case 3:f=t[o+1],s=t[o+2],128==(192&f)&&128==(192&s)&&(c=(15&i)<<12|(63&f)<<6|63&s)>2047&&(c<55296||c>57343)&&(u=c);break;case 4:f=t[o+1],s=t[o+2],h=t[o+3],128==(192&f)&&128==(192&s)&&128==(192&h)&&(c=(15&i)<<18|(63&f)<<12|(63&s)<<6|63&h)>65535&&c<1114112&&(u=c)}}null===u?(u=65533,a=1):u>65535&&(u-=65536,n.push(u>>>10&1023|55296),u=56320|1023&u),n.push(u),o+=a}return I(n)}function I(t){var r=t.length;if(r<=X)return String.fromCharCode.apply(String,t);for(var e="",n=0;n<r;)e+=String.fromCharCode.apply(String,t.slice(n,n+=X));return e}function M(t,r,e){var n="";e=Math.min(t.length,e);for(var o=r;o<e;++o)n+=String.fromCharCode(127&t[o]);return n}function U(t,r,e){var n="";e=Math.min(t.length,e);for(var o=r;o<e;++o)n+=String.fromCharCode(t[o]);return n}function N(t,r,e){var n=t.length;(!r||r<0)&&(r=0),(!e||e<0||e>n)&&(e=n);for(var o="",i=r;i<e;++i)o+=W[t[i]];return o}function S(t,r,e){for(var n=t.slice(r,e),o="",i=0;i<n.length;i+=2)o+=String.fromCharCode(n[i]+256*n[i+1]);return o}function L(t,r,e){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+r>e)throw new RangeError("Trying to access beyond buffer length")}function x(t,r,e,n,i,u){if(!o.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(r>i||r<u)throw new RangeError('"value" argument is out of bounds');if(e+n>t.length)throw new RangeError("Index out of range")}function _(t,r,e,n,o,i){if(e+n>t.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("Index out of range")}function k(t,r,e,n,o){return r=+r,e>>>=0,o||_(t,r,e,4,3.4028234663852886e38,-3.4028234663852886e38),V.write(t,r,e,n,23,4),e+4}function O(t,r,e,n,o){return r=+r,e>>>=0,o||_(t,r,e,8,1.7976931348623157e308,-1.7976931348623157e308),V.write(t,r,e,n,52,8),e+8}function Y(t){if(t=t.split("=")[0],t=t.trim().replace(Z,""),t.length<2)return"";for(;t.length%4!=0;)t+="=";return t}function D(t,r){r=r||1/0;for(var e,n=t.length,o=null,i=[],u=0;u<n;++u){if((e=t.charCodeAt(u))>55295&&e<57344){if(!o){if(e>56319){(r-=3)>-1&&i.push(239,191,189);continue}if(u+1===n){(r-=3)>-1&&i.push(239,191,189);continue}o=e;continue}if(e<56320){(r-=3)>-1&&i.push(239,191,189),o=e;continue}e=65536+(o-55296<<10|e-56320)}else o&&(r-=3)>-1&&i.push(239,191,189);if(o=null,e<128){if((r-=1)<0)break;i.push(e)}else if(e<2048){if((r-=2)<0)break;i.push(e>>6|192,63&e|128)}else if(e<65536){if((r-=3)<0)break;i.push(e>>12|224,e>>6&63|128,63&e|128)}else{if(!(e<1114112))throw new Error("Invalid code point");if((r-=4)<0)break;i.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}}return i}function j(t){for(var r=[],e=0;e<t.length;++e)r.push(255&t.charCodeAt(e));return r}function F(t,r){for(var e,n,o,i=[],u=0;u<t.length&&!((r-=2)<0);++u)e=t.charCodeAt(u),n=e>>8,o=e%256,i.push(o),i.push(n);return i}function z(t){return q.toByteArray(Y(t))}function H(t,r,e,n){for(var o=0;o<n&&!(o+e>=r.length||o>=t.length);++o)r[o+e]=t[o];return o}function J(t,r){return t instanceof r||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===r.name}function K(t){return t!==t}var q=t("base64-js"),V=t("ieee754"),Q="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=o,e.SlowBuffer=p,e.INSPECT_MAX_BYTES=50;var $=2147483647;e.kMaxLength=$,o.TYPED_ARRAY_SUPPORT=function(){try{var t=new Uint8Array(1),r={foo:function(){return 42}};return Object.setPrototypeOf(r,Uint8Array.prototype),Object.setPrototypeOf(t,r),42===t.foo()}catch(t){return!1}}(),o.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||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."),Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&o[Symbol.species]===o&&Object.defineProperty(o,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),o.poolSize=8192,o.from=function(t,r,e){return i(t,r,e)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array),o.alloc=function(t,r,e){return a(t,r,e)},o.allocUnsafe=function(t){return f(t)},o.allocUnsafeSlow=function(t){return f(t)},o.isBuffer=function(t){return null!=t&&!0===t._isBuffer&&t!==o.prototype},o.compare=function(t,r){if(J(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),J(r,Uint8Array)&&(r=o.from(r,r.offset,r.byteLength)),!o.isBuffer(t)||!o.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(t===r)return 0;for(var e=t.length,n=r.length,i=0,u=Math.min(e,n);i<u;++i)if(t[i]!==r[i]){e=t[i],n=r[i];break}return e<n?-1:n<e?1:0},o.isEncoding=function(t){switch(String(t).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!0;default:return!1}},o.concat=function(t,r){if(!Array.isArray(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return o.alloc(0);var e;if(void 0===r)for(r=0,e=0;e<t.length;++e)r+=t[e].length;var n=o.allocUnsafe(r),i=0;for(e=0;e<t.length;++e){var u=t[e];if(J(u,Uint8Array)&&(u=o.from(u)),!o.isBuffer(u))throw new TypeError('"list" argument must be an Array of Buffers');u.copy(n,i),i+=u.length}return n},o.byteLength=d,o.prototype._isBuffer=!0,o.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;r<t;r+=2)v(this,r,r+1);return this},o.prototype.swap32=function(){var t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var r=0;r<t;r+=4)v(this,r,r+3),v(this,r+1,r+2);return this},o.prototype.swap64=function(){var t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var r=0;r<t;r+=8)v(this,r,r+7),v(this,r+1,r+6),v(this,r+2,r+5),v(this,r+3,r+4);return this},o.prototype.toString=function(){var t=this.length;return 0===t?"":0===arguments.length?P(this,0,t):y.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(t){if(!o.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===o.compare(this,t)},o.prototype.inspect=function(){var t="",r=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(t+=" ... "),"<Buffer "+t+">"},Q&&(o.prototype[Q]=o.prototype.inspect),o.prototype.compare=function(t,r,e,n,i){if(J(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),!o.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===r&&(r=0),void 0===e&&(e=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),r<0||e>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&r>=e)return 0;if(n>=i)return-1;if(r>=e)return 1;if(r>>>=0,e>>>=0,n>>>=0,i>>>=0,this===t)return 0;for(var u=i-n,a=e-r,f=Math.min(u,a),s=this.slice(n,i),h=t.slice(r,e),c=0;c<f;++c)if(s[c]!==h[c]){u=s[c],a=h[c];break}return u<a?-1:a<u?1:0},o.prototype.includes=function(t,r,e){return-1!==this.indexOf(t,r,e)},o.prototype.indexOf=function(t,r,e){return w(this,t,r,e,!0)},o.prototype.lastIndexOf=function(t,r,e){return w(this,t,r,e,!1)},o.prototype.write=function(t,r,e,n){if(void 0===r)n="utf8",e=this.length,r=0;else if(void 0===e&&"string"==typeof r)n=r,e=this.length,r=0;else{if(!isFinite(r))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");r>>>=0,isFinite(e)?(e>>>=0,void 0===n&&(n="utf8")):(n=e,e=void 0)}var o=this.length-r;if((void 0===e||e>o)&&(e=o),t.length>0&&(e<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return b(this,t,r,e);case"utf8":case"utf-8":return E(this,t,r,e);case"ascii":return A(this,t,r,e);case"latin1":case"binary":return B(this,t,r,e);case"base64":return T(this,t,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,r,e);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var X=4096;o.prototype.slice=function(t,r){var e=this.length;t=~~t,r=void 0===r?e:~~r,t<0?(t+=e)<0&&(t=0):t>e&&(t=e),r<0?(r+=e)<0&&(r=0):r>e&&(r=e),r<t&&(r=t);var n=this.subarray(t,r);return Object.setPrototypeOf(n,o.prototype),n},o.prototype.readUIntLE=function(t,r,e){t>>>=0,r>>>=0,e||L(t,r,this.length);for(var n=this[t],o=1,i=0;++i<r&&(o*=256);)n+=this[t+i]*o;return n},o.prototype.readUIntBE=function(t,r,e){t>>>=0,r>>>=0,e||L(t,r,this.length);for(var n=this[t+--r],o=1;r>0&&(o*=256);)n+=this[t+--r]*o;return n},o.prototype.readUInt8=function(t,r){return t>>>=0,r||L(t,1,this.length),this[t]},o.prototype.readUInt16LE=function(t,r){return t>>>=0,r||L(t,2,this.length),this[t]|this[t+1]<<8},o.prototype.readUInt16BE=function(t,r){return t>>>=0,r||L(t,2,this.length),this[t]<<8|this[t+1]},o.prototype.readUInt32LE=function(t,r){return t>>>=0,r||L(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},o.prototype.readUInt32BE=function(t,r){return t>>>=0,r||L(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},o.prototype.readIntLE=function(t,r,e){t>>>=0,r>>>=0,e||L(t,r,this.length);for(var n=this[t],o=1,i=0;++i<r&&(o*=256);)n+=this[t+i]*o;return o*=128,n>=o&&(n-=Math.pow(2,8*r)),n},o.prototype.readIntBE=function(t,r,e){t>>>=0,r>>>=0,e||L(t,r,this.length);for(var n=r,o=1,i=this[t+--n];n>0&&(o*=256);)i+=this[t+--n]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*r)),i},o.prototype.readInt8=function(t,r){return t>>>=0,r||L(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},o.prototype.readInt16LE=function(t,r){t>>>=0,r||L(t,2,this.length);var e=this[t]|this[t+1]<<8;return 32768&e?4294901760|e:e},o.prototype.readInt16BE=function(t,r){t>>>=0,r||L(t,2,this.length);var e=this[t+1]|this[t]<<8;return 32768&e?4294901760|e:e},o.prototype.readInt32LE=function(t,r){return t>>>=0,r||L(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},o.prototype.readInt32BE=function(t,r){return t>>>=0,r||L(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},o.prototype.readFloatLE=function(t,r){return t>>>=0,r||L(t,4,this.length),V.read(this,t,!0,23,4)},o.prototype.readFloatBE=function(t,r){return t>>>=0,r||L(t,4,this.length),V.read(this,t,!1,23,4)},o.prototype.readDoubleLE=function(t,r){return t>>>=0,r||L(t,8,this.length),V.read(this,t,!0,52,8)},o.prototype.readDoubleBE=function(t,r){return t>>>=0,r||L(t,8,this.length),V.read(this,t,!1,52,8)},o.prototype.writeUIntLE=function(t,r,e,n){if(t=+t,r>>>=0,e>>>=0,!n){x(this,t,r,e,Math.pow(2,8*e)-1,0)}var o=1,i=0;for(this[r]=255&t;++i<e&&(o*=256);)this[r+i]=t/o&255;return r+e},o.prototype.writeUIntBE=function(t,r,e,n){if(t=+t,r>>>=0,e>>>=0,!n){x(this,t,r,e,Math.pow(2,8*e)-1,0)}var o=e-1,i=1;for(this[r+o]=255&t;--o>=0&&(i*=256);)this[r+o]=t/i&255;return r+e},o.prototype.writeUInt8=function(t,r,e){return t=+t,r>>>=0,e||x(this,t,r,1,255,0),this[r]=255&t,r+1},o.prototype.writeUInt16LE=function(t,r,e){return t=+t,r>>>=0,e||x(this,t,r,2,65535,0),this[r]=255&t,this[r+1]=t>>>8,r+2},o.prototype.writeUInt16BE=function(t,r,e){return t=+t,r>>>=0,e||x(this,t,r,2,65535,0),this[r]=t>>>8,this[r+1]=255&t,r+2},o.prototype.writeUInt32LE=function(t,r,e){return t=+t,r>>>=0,e||x(this,t,r,4,4294967295,0),this[r+3]=t>>>24,this[r+2]=t>>>16,this[r+1]=t>>>8,this[r]=255&t,r+4},o.prototype.writeUInt32BE=function(t,r,e){return t=+t,r>>>=0,e||x(this,t,r,4,4294967295,0),this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t,r+4},o.prototype.writeIntLE=function(t,r,e,n){if(t=+t,r>>>=0,!n){var o=Math.pow(2,8*e-1);x(this,t,r,e,o-1,-o)}var i=0,u=1,a=0;for(this[r]=255&t;++i<e&&(u*=256);)t<0&&0===a&&0!==this[r+i-1]&&(a=1),this[r+i]=(t/u>>0)-a&255;return r+e},o.prototype.writeIntBE=function(t,r,e,n){if(t=+t,r>>>=0,!n){var o=Math.pow(2,8*e-1);x(this,t,r,e,o-1,-o)}var i=e-1,u=1,a=0;for(this[r+i]=255&t;--i>=0&&(u*=256);)t<0&&0===a&&0!==this[r+i+1]&&(a=1),this[r+i]=(t/u>>0)-a&255;return r+e},o.prototype.writeInt8=function(t,r,e){return t=+t,r>>>=0,e||x(this,t,r,1,127,-128),t<0&&(t=255+t+1),this[r]=255&t,r+1},o.prototype.writeInt16LE=function(t,r,e){return t=+t,r>>>=0,e||x(this,t,r,2,32767,-32768),this[r]=255&t,this[r+1]=t>>>8,r+2},o.prototype.writeInt16BE=function(t,r,e){return t=+t,r>>>=0,e||x(this,t,r,2,32767,-32768),this[r]=t>>>8,this[r+1]=255&t,r+2},o.prototype.writeInt32LE=function(t,r,e){return t=+t,r>>>=0,e||x(this,t,r,4,2147483647,-2147483648),this[r]=255&t,this[r+1]=t>>>8,this[r+2]=t>>>16,this[r+3]=t>>>24,r+4},o.prototype.writeInt32BE=function(t,r,e){return t=+t,r>>>=0,e||x(this,t,r,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t,r+4},o.prototype.writeFloatLE=function(t,r,e){return k(this,t,r,!0,e)},o.prototype.writeFloatBE=function(t,r,e){return k(this,t,r,!1,e)},o.prototype.writeDoubleLE=function(t,r,e){return O(this,t,r,!0,e)},o.prototype.writeDoubleBE=function(t,r,e){return O(this,t,r,!1,e)},o.prototype.copy=function(t,r,e,n){if(!o.isBuffer(t))throw new TypeError("argument should be a Buffer");if(e||(e=0),n||0===n||(n=this.length),r>=t.length&&(r=t.length),r||(r=0),n>0&&n<e&&(n=e),n===e)return 0;if(0===t.length||0===this.length)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(e<0||e>=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),t.length-r<n-e&&(n=t.length-r+e);var i=n-e;if(this===t&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(r,e,n);else if(this===t&&e<r&&r<n)for(var u=i-1;u>=0;--u)t[u+r]=this[u+e];else Uint8Array.prototype.set.call(t,this.subarray(e,n),r);return i},o.prototype.fill=function(t,r,e,n){if("string"==typeof t){if("string"==typeof r?(n=r,r=0,e=this.length):"string"==typeof e&&(n=e,e=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!o.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===t.length){var i=t.charCodeAt(0);("utf8"===n&&i<128||"latin1"===n)&&(t=i)}}else"number"==typeof t?t&=255:"boolean"==typeof t&&(t=Number(t));if(r<0||this.length<r||this.length<e)throw new RangeError("Out of range index");if(e<=r)return this;r>>>=0,e=void 0===e?this.length:e>>>0,t||(t=0);var u;if("number"==typeof t)for(u=r;u<e;++u)this[u]=t;else{var a=o.isBuffer(t)?t:o.from(t,n),f=a.length;if(0===f)throw new TypeError('The value "'+t+'" is invalid for argument "value"');for(u=0;u<e-r;++u)this[u+r]=a[u%f]}return this};var Z=/[^+\/0-9A-Za-z-_]/g,W=function(){for(var t=new Array(256),r=0;r<16;++r)for(var e=16*r,n=0;n<16;++n)t[e+n]="0123456789abcdef"[r]+"0123456789abcdef"[n];return t}()},{"base64-js":29,ieee754:32}],31:[function(t,r,e){"use strict";var n={single_source_shortest_paths:function(t,r,e){var o={},i={};i[r]=0;var u=n.PriorityQueue.make();u.push(r,0);for(var a,f,s,h,c,l,g,p;!u.empty();){a=u.pop(),f=a.value,h=a.cost,c=t[f]||{};for(s in c)c.hasOwnProperty(s)&&(l=c[s],g=h+l,p=i[s],(void 0===i[s]||p>g)&&(i[s]=g,u.push(s,g),o[s]=f))}if(void 0!==e&&void 0===i[e]){var d=["Could not find a path from ",r," to ",e,"."].join("");throw new Error(d)}return o},extract_shortest_path_from_predecessor_list:function(t,r){for(var e=[],n=r;n;)e.push(n),t[n],n=t[n];return e.reverse(),e},find_path:function(t,r,e){var o=n.single_source_shortest_paths(t,r,e);return n.extract_shortest_path_from_predecessor_list(o,e)},PriorityQueue:{make:function(t){var r,e=n.PriorityQueue,o={};t=t||{};for(r in e)e.hasOwnProperty(r)&&(o[r]=e[r]);return o.queue=[],o.sorter=t.sorter||e.default_sorter,o},default_sorter:function(t,r){return t.cost-r.cost},push:function(t,r){var e={value:t,cost:r};this.queue.push(e),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return 0===this.queue.length}}};void 0!==r&&(r.exports=n)},{}],32:[function(t,r,e){e.read=function(t,r,e,n,o){var i,u,a=8*o-n-1,f=(1<<a)-1,s=f>>1,h=-7,c=e?o-1:0,l=e?-1:1,g=t[r+c];for(c+=l,i=g&(1<<-h)-1,g>>=-h,h+=a;h>0;i=256*i+t[r+c],c+=l,h-=8);for(u=i&(1<<-h)-1,i>>=-h,h+=n;h>0;u=256*u+t[r+c],c+=l,h-=8);if(0===i)i=1-s;else{if(i===f)return u?NaN:1/0*(g?-1:1);u+=Math.pow(2,n),i-=s}return(g?-1:1)*u*Math.pow(2,i-n)},e.write=function(t,r,e,n,o,i){var u,a,f,s=8*i-o-1,h=(1<<s)-1,c=h>>1,l=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,g=n?0:i-1,p=n?1:-1,d=r<0||0===r&&1/r<0?1:0;for(r=Math.abs(r),isNaN(r)||r===1/0?(a=isNaN(r)?1:0,u=h):(u=Math.floor(Math.log(r)/Math.LN2),r*(f=Math.pow(2,-u))<1&&(u--,f*=2),r+=u+c>=1?l/f:l*Math.pow(2,1-c),r*f>=2&&(u++,f/=2),u+c>=h?(a=0,u=h):u+c>=1?(a=(r*f-1)*Math.pow(2,o),u+=c):(a=r*Math.pow(2,c-1)*Math.pow(2,o),u=0));o>=8;t[e+g]=255&a,g+=p,a/=256,o-=8);for(u=u<<o|a,s+=o;s>0;t[e+g]=255&u,g+=p,u/=256,s-=8);t[e+g-p]|=128*d}},{}],33:[function(t,r,e){var n={}.toString;r.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},{}]},{},[24])(24)});
-//# sourceMappingURL=qrcode.min.js.map
+!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).QRCode=t()}}((function(){return function t(r,e,n){function o(u,a){if(!e[u]){if(!r[u]){var f="function"==typeof require&&require;if(!a&&f)return f(u,!0);if(i)return i(u,!0);var s=new Error("Cannot find module '"+u+"'");throw s.code="MODULE_NOT_FOUND",s}var h=e[u]={exports:{}};r[u][0].call(h.exports,(function(t){return o(r[u][1][t]||t)}),h,h.exports,t,r,e,n)}return e[u].exports}for(var i="function"==typeof require&&require,u=0;u<n.length;u++)o(n[u]);return o}({1:[function(t,r,e){r.exports=function(){return"function"==typeof Promise&&Promise.prototype&&Promise.prototype.then}},{}],2:[function(t,r,e){var n=t("./utils").getSymbolSize;e.getRowColCoords=function(t){if(1===t)return[];for(var r=Math.floor(t/7)+2,e=n(t),o=145===e?26:2*Math.ceil((e-13)/(2*r-2)),i=[e-7],u=1;u<r-1;u++)i[u]=i[u-1]-o;return i.push(6),i.reverse()},e.getPositions=function(t){for(var r=[],n=e.getRowColCoords(t),o=n.length,i=0;i<o;i++)for(var u=0;u<o;u++)0===i&&0===u||0===i&&u===o-1||i===o-1&&0===u||r.push([n[i],n[u]]);return r}},{"./utils":21}],3:[function(t,r,e){function n(t){this.mode=o.ALPHANUMERIC,this.data=t}var o=t("./mode"),i=["0","1","2","3","4","5","6","7","8","9","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"," ","$","%","*","+","-",".","/",":"];n.getBitsLength=function(t){return 11*Math.floor(t/2)+t%2*6},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(t){var r;for(r=0;r+2<=this.data.length;r+=2){var e=45*i.indexOf(this.data[r]);e+=i.indexOf(this.data[r+1]),t.put(e,11)}this.data.length%2&&t.put(i.indexOf(this.data[r]),6)},r.exports=n},{"./mode":14}],4:[function(t,r,e){function n(){this.buffer=[],this.length=0}n.prototype={get:function(t){var r=Math.floor(t/8);return 1==(this.buffer[r]>>>7-t%8&1)},put:function(t,r){for(var e=0;e<r;e++)this.putBit(1==(t>>>r-e-1&1))},getLengthInBits:function(){return this.length},putBit:function(t){var r=Math.floor(this.length/8);this.buffer.length<=r&&this.buffer.push(0),t&&(this.buffer[r]|=128>>>this.length%8),this.length++}},r.exports=n},{}],5:[function(t,r,e){function n(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=o.alloc(t*t),this.reservedBit=o.alloc(t*t)}var o=t("../utils/buffer");n.prototype.set=function(t,r,e,n){var o=t*this.size+r;this.data[o]=e,n&&(this.reservedBit[o]=!0)},n.prototype.get=function(t,r){return this.data[t*this.size+r]},n.prototype.xor=function(t,r,e){this.data[t*this.size+r]^=e},n.prototype.isReserved=function(t,r){return this.reservedBit[t*this.size+r]},r.exports=n},{"../utils/buffer":28}],6:[function(t,r,e){function n(t){this.mode=i.BYTE,this.data=o.from(t)}var o=t("../utils/buffer"),i=t("./mode");n.getBitsLength=function(t){return 8*t},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(t){for(var r=0,e=this.data.length;r<e;r++)t.put(this.data[r],8)},r.exports=n},{"../utils/buffer":28,"./mode":14}],7:[function(t,r,e){var n=t("./error-correction-level"),o=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],i=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];e.getBlocksCount=function(t,r){switch(r){case n.L:return o[4*(t-1)+0];case n.M:return o[4*(t-1)+1];case n.Q:return o[4*(t-1)+2];case n.H:return o[4*(t-1)+3];default:return}},e.getTotalCodewordsCount=function(t,r){switch(r){case n.L:return i[4*(t-1)+0];case n.M:return i[4*(t-1)+1];case n.Q:return i[4*(t-1)+2];case n.H:return i[4*(t-1)+3];default:return}}},{"./error-correction-level":8}],8:[function(t,r,e){e.L={bit:1},e.M={bit:0},e.Q={bit:3},e.H={bit:2},e.isValid=function(t){return t&&void 0!==t.bit&&t.bit>=0&&t.bit<4},e.from=function(t,r){if(e.isValid(t))return t;try{return function(t){if("string"!=typeof t)throw new Error("Param is not a string");switch(t.toLowerCase()){case"l":case"low":return e.L;case"m":case"medium":return e.M;case"q":case"quartile":return e.Q;case"h":case"high":return e.H;default:throw new Error("Unknown EC Level: "+t)}}(t)}catch(t){return r}}},{}],9:[function(t,r,e){var n=t("./utils").getSymbolSize;e.getPositions=function(t){var r=n(t);return[[0,0],[r-7,0],[0,r-7]]}},{"./utils":21}],10:[function(t,r,e){var n=t("./utils"),o=n.getBCHDigit(1335);e.getEncodedBits=function(t,r){for(var e=t.bit<<3|r,i=e<<10;n.getBCHDigit(i)-o>=0;)i^=1335<<n.getBCHDigit(i)-o;return 21522^(e<<10|i)}},{"./utils":21}],11:[function(t,r,e){var n=t("../utils/buffer"),o=n.alloc(512),i=n.alloc(256);!function(){for(var t=1,r=0;r<255;r++)o[r]=t,i[t]=r,256&(t<<=1)&&(t^=285);for(r=255;r<512;r++)o[r]=o[r-255]}(),e.log=function(t){if(t<1)throw new Error("log("+t+")");return i[t]},e.exp=function(t){return o[t]},e.mul=function(t,r){return 0===t||0===r?0:o[i[t]+i[r]]}},{"../utils/buffer":28}],12:[function(t,r,e){function n(t){this.mode=o.KANJI,this.data=t}var o=t("./mode"),i=t("./utils");n.getBitsLength=function(t){return 13*t},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(t){var r;for(r=0;r<this.data.length;r++){var e=i.toSJIS(this.data[r]);if(e>=33088&&e<=40956)e-=33088;else{if(!(e>=57408&&e<=60351))throw new Error("Invalid SJIS character: "+this.data[r]+"\nMake sure your charset is UTF-8");e-=49472}e=192*(e>>>8&255)+(255&e),t.put(e,13)}},r.exports=n},{"./mode":14,"./utils":21}],13:[function(t,r,e){function n(t,r,n){switch(t){case e.Patterns.PATTERN000:return(r+n)%2==0;case e.Patterns.PATTERN001:return r%2==0;case e.Patterns.PATTERN010:return n%3==0;case e.Patterns.PATTERN011:return(r+n)%3==0;case e.Patterns.PATTERN100:return(Math.floor(r/2)+Math.floor(n/3))%2==0;case e.Patterns.PATTERN101:return r*n%2+r*n%3==0;case e.Patterns.PATTERN110:return(r*n%2+r*n%3)%2==0;case e.Patterns.PATTERN111:return(r*n%3+(r+n)%2)%2==0;default:throw new Error("bad maskPattern:"+t)}}e.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var o=3,i=3,u=40,a=10;e.isValid=function(t){return null!=t&&""!==t&&!isNaN(t)&&t>=0&&t<=7},e.from=function(t){return e.isValid(t)?parseInt(t,10):void 0},e.getPenaltyN1=function(t){for(var r=t.size,e=0,n=0,i=0,u=null,a=null,f=0;f<r;f++){n=i=0,u=a=null;for(var s=0;s<r;s++){var h=t.get(f,s);h===u?n++:(n>=5&&(e+=o+(n-5)),u=h,n=1),(h=t.get(s,f))===a?i++:(i>=5&&(e+=o+(i-5)),a=h,i=1)}n>=5&&(e+=o+(n-5)),i>=5&&(e+=o+(i-5))}return e},e.getPenaltyN2=function(t){for(var r=t.size,e=0,n=0;n<r-1;n++)for(var o=0;o<r-1;o++){var u=t.get(n,o)+t.get(n,o+1)+t.get(n+1,o)+t.get(n+1,o+1);4!==u&&0!==u||e++}return e*i},e.getPenaltyN3=function(t){for(var r=t.size,e=0,n=0,o=0,i=0;i<r;i++){n=o=0;for(var a=0;a<r;a++)n=n<<1&2047|t.get(i,a),a>=10&&(1488===n||93===n)&&e++,o=o<<1&2047|t.get(a,i),a>=10&&(1488===o||93===o)&&e++}return e*u},e.getPenaltyN4=function(t){for(var r=0,e=t.data.length,n=0;n<e;n++)r+=t.data[n];return Math.abs(Math.ceil(100*r/e/5)-10)*a},e.applyMask=function(t,r){for(var e=r.size,o=0;o<e;o++)for(var i=0;i<e;i++)r.isReserved(i,o)||r.xor(i,o,n(t,i,o))},e.getBestMask=function(t,r){for(var n=Object.keys(e.Patterns).length,o=0,i=1/0,u=0;u<n;u++){r(u),e.applyMask(u,t);var a=e.getPenaltyN1(t)+e.getPenaltyN2(t)+e.getPenaltyN3(t)+e.getPenaltyN4(t);e.applyMask(u,t),a<i&&(i=a,o=u)}return o}},{}],14:[function(t,r,e){var n=t("./version-check"),o=t("./regex");e.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},e.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},e.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},e.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},e.MIXED={bit:-1},e.getCharCountIndicator=function(t,r){if(!t.ccBits)throw new Error("Invalid mode: "+t);if(!n.isValid(r))throw new Error("Invalid version: "+r);return r>=1&&r<10?t.ccBits[0]:r<27?t.ccBits[1]:t.ccBits[2]},e.getBestModeForData=function(t){return o.testNumeric(t)?e.NUMERIC:o.testAlphanumeric(t)?e.ALPHANUMERIC:o.testKanji(t)?e.KANJI:e.BYTE},e.toString=function(t){if(t&&t.id)return t.id;throw new Error("Invalid mode")},e.isValid=function(t){return t&&t.bit&&t.ccBits},e.from=function(t,r){if(e.isValid(t))return t;try{return function(t){if("string"!=typeof t)throw new Error("Param is not a string");switch(t.toLowerCase()){case"numeric":return e.NUMERIC;case"alphanumeric":return e.ALPHANUMERIC;case"kanji":return e.KANJI;case"byte":return e.BYTE;default:throw new Error("Unknown mode: "+t)}}(t)}catch(t){return r}}},{"./regex":19,"./version-check":22}],15:[function(t,r,e){function n(t){this.mode=o.NUMERIC,this.data=t.toString()}var o=t("./mode");n.getBitsLength=function(t){return 10*Math.floor(t/3)+(t%3?t%3*3+1:0)},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(t){var r,e,n;for(r=0;r+3<=this.data.length;r+=3)e=this.data.substr(r,3),n=parseInt(e,10),t.put(n,10);var o=this.data.length-r;o>0&&(e=this.data.substr(r),n=parseInt(e,10),t.put(n,3*o+1))},r.exports=n},{"./mode":14}],16:[function(t,r,e){var n=t("../utils/buffer"),o=t("./galois-field");e.mul=function(t,r){for(var e=n.alloc(t.length+r.length-1),i=0;i<t.length;i++)for(var u=0;u<r.length;u++)e[i+u]^=o.mul(t[i],r[u]);return e},e.mod=function(t,r){for(var e=n.from(t);e.length-r.length>=0;){for(var i=e[0],u=0;u<r.length;u++)e[u]^=o.mul(r[u],i);for(var a=0;a<e.length&&0===e[a];)a++;e=e.slice(a)}return e},e.generateECPolynomial=function(t){for(var r=n.from([1]),i=0;i<t;i++)r=e.mul(r,[1,o.exp(i)]);return r}},{"../utils/buffer":28,"./galois-field":11}],17:[function(t,r,e){function n(t,r){for(var e=t.size,n=p.getPositions(r),o=0;o<n.length;o++)for(var i=n[o][0],u=n[o][1],a=-1;a<=7;a++)if(!(i+a<=-1||e<=i+a))for(var f=-1;f<=7;f++)u+f<=-1||e<=u+f||(a>=0&&a<=6&&(0===f||6===f)||f>=0&&f<=6&&(0===a||6===a)||a>=2&&a<=4&&f>=2&&f<=4?t.set(i+a,u+f,!0,!0):t.set(i+a,u+f,!1,!0))}function o(t,r){for(var e=g.getPositions(r),n=0;n<e.length;n++)for(var o=e[n][0],i=e[n][1],u=-2;u<=2;u++)for(var a=-2;a<=2;a++)-2===u||2===u||-2===a||2===a||0===u&&0===a?t.set(o+u,i+a,!0,!0):t.set(o+u,i+a,!1,!0)}function i(t,r,e){var n,o,i=t.size,u=m.getEncodedBits(r,e);for(n=0;n<15;n++)o=1==(u>>n&1),n<6?t.set(n,8,o,!0):n<8?t.set(n+1,8,o,!0):t.set(i-15+n,8,o,!0),n<8?t.set(8,i-n-1,o,!0):n<9?t.set(8,15-n-1+1,o,!0):t.set(8,15-n-1,o,!0);t.set(i-8,8,1,!0)}function u(t,r,e){var n=new c;e.forEach((function(r){n.put(r.mode.bit,4),n.put(r.getLength(),b.getCharCountIndicator(r.mode,t)),r.write(n)}));var o=8*(s.getSymbolTotalCodewords(t)-y.getTotalCodewordsCount(t,r));for(n.getLengthInBits()+4<=o&&n.put(0,4);n.getLengthInBits()%8!=0;)n.putBit(0);for(var i=(o-n.getLengthInBits())/8,u=0;u<i;u++)n.put(u%2?17:236,8);return function(t,r,e){for(var n=s.getSymbolTotalCodewords(r),o=y.getTotalCodewordsCount(r,e),i=n-o,u=y.getBlocksCount(r,e),a=u-n%u,h=Math.floor(n/u),c=Math.floor(i/u),l=c+1,g=h-c,p=new v(g),d=0,w=new Array(u),m=new Array(u),b=0,E=f.from(t.buffer),A=0;A<u;A++){var B=A<a?c:l;w[A]=E.slice(d,d+B),m[A]=p.encode(w[A]),d+=B,b=Math.max(b,B)}var T,R,C=f.alloc(n),P=0;for(T=0;T<b;T++)for(R=0;R<u;R++)T<w[R].length&&(C[P++]=w[R][T]);for(T=0;T<g;T++)for(R=0;R<u;R++)C[P++]=m[R][T];return C}(n,t,r)}function a(t,r,e,a){var f;if(A(t))f=E.fromArray(t);else{if("string"!=typeof t)throw new Error("Invalid data");var h=r;if(!h){var c=E.rawSplit(t);h=w.getBestVersionForData(c,e)}f=E.fromString(t,h||40)}var g=w.getBestVersionForData(f,e);if(!g)throw new Error("The amount of data is too big to be stored in a QR Code");if(r){if(r<g)throw new Error("\nThe chosen QR Code version cannot contain this amount of data.\nMinimum version required to store current data is: "+g+".\n")}else r=g;var p=u(r,e,f),y=s.getSymbolSize(r),v=new l(y);return n(v,r),function(t){for(var r=t.size,e=8;e<r-8;e++){var n=e%2==0;t.set(e,6,n,!0),t.set(6,e,n,!0)}}(v),o(v,r),i(v,e,0),r>=7&&function(t,r){for(var e,n,o,i=t.size,u=w.getEncodedBits(r),a=0;a<18;a++)e=Math.floor(a/3),n=a%3+i-8-3,o=1==(u>>a&1),t.set(e,n,o,!0),t.set(n,e,o,!0)}(v,r),function(t,r){for(var e=t.size,n=-1,o=e-1,i=7,u=0,a=e-1;a>0;a-=2)for(6===a&&a--;;){for(var f=0;f<2;f++)if(!t.isReserved(o,a-f)){var s=!1;u<r.length&&(s=1==(r[u]>>>i&1)),t.set(o,a-f,s),-1==--i&&(u++,i=7)}if((o+=n)<0||e<=o){o-=n,n=-n;break}}}(v,p),isNaN(a)&&(a=d.getBestMask(v,i.bind(null,v,e))),d.applyMask(a,v),i(v,e,a),{modules:v,version:r,errorCorrectionLevel:e,maskPattern:a,segments:f}}var f=t("../utils/buffer"),s=t("./utils"),h=t("./error-correction-level"),c=t("./bit-buffer"),l=t("./bit-matrix"),g=t("./alignment-pattern"),p=t("./finder-pattern"),d=t("./mask-pattern"),y=t("./error-correction-code"),v=t("./reed-solomon-encoder"),w=t("./version"),m=t("./format-info"),b=t("./mode"),E=t("./segments"),A=t("isarray");e.create=function(t,r){if(void 0===t||""===t)throw new Error("No input text");var e,n,o=h.M;return void 0!==r&&(o=h.from(r.errorCorrectionLevel,h.M),e=w.from(r.version),n=d.from(r.maskPattern),r.toSJISFunc&&s.setToSJISFunction(r.toSJISFunc)),a(t,e,o,n)}},{"../utils/buffer":28,"./alignment-pattern":2,"./bit-buffer":4,"./bit-matrix":5,"./error-correction-code":7,"./error-correction-level":8,"./finder-pattern":9,"./format-info":10,"./mask-pattern":13,"./mode":14,"./reed-solomon-encoder":18,"./segments":20,"./utils":21,"./version":23,isarray:33}],18:[function(t,r,e){function n(t){this.genPoly=void 0,this.degree=t,this.degree&&this.initialize(this.degree)}var o=t("../utils/buffer"),i=t("./polynomial"),u=t("buffer").Buffer;n.prototype.initialize=function(t){this.degree=t,this.genPoly=i.generateECPolynomial(this.degree)},n.prototype.encode=function(t){if(!this.genPoly)throw new Error("Encoder not initialized");var r=o.alloc(this.degree),e=u.concat([t,r],t.length+this.degree),n=i.mod(e,this.genPoly),a=this.degree-n.length;if(a>0){var f=o.alloc(this.degree);return n.copy(f,a),f}return n},r.exports=n},{"../utils/buffer":28,"./polynomial":16,buffer:30}],19:[function(t,r,e){var n="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+",o="(?:(?![A-Z0-9 $%*+\\-./:]|"+(n=n.replace(/u/g,"\\u"))+")(?:.|[\r\n]))+";e.KANJI=new RegExp(n,"g"),e.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),e.BYTE=new RegExp(o,"g"),e.NUMERIC=new RegExp("[0-9]+","g"),e.ALPHANUMERIC=new RegExp("[A-Z $%*+\\-./:]+","g");var i=new RegExp("^"+n+"$"),u=new RegExp("^[0-9]+$"),a=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");e.testKanji=function(t){return i.test(t)},e.testNumeric=function(t){return u.test(t)},e.testAlphanumeric=function(t){return a.test(t)}},{}],20:[function(t,r,e){function n(t){return unescape(encodeURIComponent(t)).length}function o(t,r,e){for(var n,o=[];null!==(n=t.exec(e));)o.push({data:n[0],index:n.index,mode:r,length:n[0].length});return o}function i(t){var r,e,n=o(d.NUMERIC,h.NUMERIC,t),i=o(d.ALPHANUMERIC,h.ALPHANUMERIC,t);return y.isKanjiModeEnabled()?(r=o(d.BYTE,h.BYTE,t),e=o(d.KANJI,h.KANJI,t)):(r=o(d.BYTE_KANJI,h.BYTE,t),e=[]),n.concat(i,r,e).sort((function(t,r){return t.index-r.index})).map((function(t){return{data:t.data,mode:t.mode,length:t.length}}))}function u(t,r){switch(r){case h.NUMERIC:return c.getBitsLength(t);case h.ALPHANUMERIC:return l.getBitsLength(t);case h.KANJI:return p.getBitsLength(t);case h.BYTE:return g.getBitsLength(t)}}function a(t){for(var r=[],e=0;e<t.length;e++){var o=t[e];switch(o.mode){case h.NUMERIC:r.push([o,{data:o.data,mode:h.ALPHANUMERIC,length:o.length},{data:o.data,mode:h.BYTE,length:o.length}]);break;case h.ALPHANUMERIC:r.push([o,{data:o.data,mode:h.BYTE,length:o.length}]);break;case h.KANJI:r.push([o,{data:o.data,mode:h.BYTE,length:n(o.data)}]);break;case h.BYTE:r.push([{data:o.data,mode:h.BYTE,length:n(o.data)}])}}return r}function f(t,r){for(var e={},n={start:{}},o=["start"],i=0;i<t.length;i++){for(var a=t[i],f=[],s=0;s<a.length;s++){var c=a[s],l=""+i+s;f.push(l),e[l]={node:c,lastCount:0},n[l]={};for(var g=0;g<o.length;g++){var p=o[g];e[p]&&e[p].node.mode===c.mode?(n[p][l]=u(e[p].lastCount+c.length,c.mode)-u(e[p].lastCount,c.mode),e[p].lastCount+=c.length):(e[p]&&(e[p].lastCount=c.length),n[p][l]=u(c.length,c.mode)+4+h.getCharCountIndicator(c.mode,r))}}o=f}for(g=0;g<o.length;g++)n[o[g]].end=0;return{map:n,table:e}}function s(t,r){var e,n=h.getBestModeForData(t);if((e=h.from(r,n))!==h.BYTE&&e.bit<n.bit)throw new Error('"'+t+'" cannot be encoded with mode '+h.toString(e)+".\n Suggested mode is: "+h.toString(n));switch(e!==h.KANJI||y.isKanjiModeEnabled()||(e=h.BYTE),e){case h.NUMERIC:return new c(t);case h.ALPHANUMERIC:return new l(t);case h.KANJI:return new p(t);case h.BYTE:return new g(t)}}var h=t("./mode"),c=t("./numeric-data"),l=t("./alphanumeric-data"),g=t("./byte-data"),p=t("./kanji-data"),d=t("./regex"),y=t("./utils"),v=t("dijkstrajs");e.fromArray=function(t){return t.reduce((function(t,r){return"string"==typeof r?t.push(s(r,null)):r.data&&t.push(s(r.data,r.mode)),t}),[])},e.fromString=function(t,r){for(var n=f(a(i(t,y.isKanjiModeEnabled())),r),o=v.find_path(n.map,"start","end"),u=[],s=1;s<o.length-1;s++)u.push(n.table[o[s]].node);return e.fromArray(function(t){return t.reduce((function(t,r){var e=t.length-1>=0?t[t.length-1]:null;return e&&e.mode===r.mode?(t[t.length-1].data+=r.data,t):(t.push(r),t)}),[])}(u))},e.rawSplit=function(t){return e.fromArray(i(t,y.isKanjiModeEnabled()))}},{"./alphanumeric-data":3,"./byte-data":6,"./kanji-data":12,"./mode":14,"./numeric-data":15,"./regex":19,"./utils":21,dijkstrajs:31}],21:[function(t,r,e){var n,o=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];e.getSymbolSize=function(t){if(!t)throw new Error('"version" cannot be null or undefined');if(t<1||t>40)throw new Error('"version" should be in range from 1 to 40');return 4*t+17},e.getSymbolTotalCodewords=function(t){return o[t]},e.getBCHDigit=function(t){for(var r=0;0!==t;)r++,t>>>=1;return r},e.setToSJISFunction=function(t){if("function"!=typeof t)throw new Error('"toSJISFunc" is not a valid function.');n=t},e.isKanjiModeEnabled=function(){return void 0!==n},e.toSJIS=function(t){return n(t)}},{}],22:[function(t,r,e){e.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40}},{}],23:[function(t,r,e){function n(t,r,n){for(var o=1;o<=40;o++)if(r<=e.getCapacity(o,n,t))return o}function o(t,r){return h.getCharCountIndicator(t,r)+4}function i(t,r){var e=0;return t.forEach((function(t){var n=o(t.mode,r);e+=n+t.getBitsLength()})),e}function u(t,r){for(var n=1;n<=40;n++)if(i(t,n)<=e.getCapacity(n,r,h.MIXED))return n}var a=t("./utils"),f=t("./error-correction-code"),s=t("./error-correction-level"),h=t("./mode"),c=t("./version-check"),l=t("isarray"),g=a.getBCHDigit(7973);e.from=function(t,r){return c.isValid(t)?parseInt(t,10):r},e.getCapacity=function(t,r,e){if(!c.isValid(t))throw new Error("Invalid QR Code version");void 0===e&&(e=h.BYTE);var n=8*(a.getSymbolTotalCodewords(t)-f.getTotalCodewordsCount(t,r));if(e===h.MIXED)return n;var i=n-o(e,t);switch(e){case h.NUMERIC:return Math.floor(i/10*3);case h.ALPHANUMERIC:return Math.floor(i/11*2);case h.KANJI:return Math.floor(i/13);case h.BYTE:default:return Math.floor(i/8)}},e.getBestVersionForData=function(t,r){var e,o=s.from(r,s.M);if(l(t)){if(t.length>1)return u(t,o);if(0===t.length)return 1;e=t[0]}else e=t;return n(e.mode,e.getLength(),o)},e.getEncodedBits=function(t){if(!c.isValid(t)||t<7)throw new Error("Invalid QR Code version");for(var r=t<<12;a.getBCHDigit(r)-g>=0;)r^=7973<<a.getBCHDigit(r)-g;return t<<12|r}},{"./error-correction-code":7,"./error-correction-level":8,"./mode":14,"./utils":21,"./version-check":22,isarray:33}],24:[function(t,r,e){function n(t,r,e,n,u){var a=[].slice.call(arguments,1),f=a.length,s="function"==typeof a[f-1];if(!s&&!o())throw new Error("Callback required as last argument");if(!s){if(f<1)throw new Error("Too few arguments provided");return 1===f?(e=r,r=n=void 0):2!==f||r.getContext||(n=e,e=r,r=void 0),new Promise((function(o,u){try{var a=i.create(e,n);o(t(a,r,n))}catch(t){u(t)}}))}if(f<2)throw new Error("Too few arguments provided");2===f?(u=e,e=r,r=n=void 0):3===f&&(r.getContext&&void 0===u?(u=n,n=void 0):(u=n,n=e,e=r,r=void 0));try{var h=i.create(e,n);u(null,t(h,r,n))}catch(t){u(t)}}var o=t("./can-promise"),i=t("./core/qrcode"),u=t("./renderer/canvas"),a=t("./renderer/svg-tag.js");e.create=i.create,e.toCanvas=n.bind(null,u.render),e.toDataURL=n.bind(null,u.renderToDataURL),e.toString=n.bind(null,(function(t,r,e){return a.render(t,e)}))},{"./can-promise":1,"./core/qrcode":17,"./renderer/canvas":25,"./renderer/svg-tag.js":26}],25:[function(t,r,e){var n=t("./utils");e.render=function(t,r,e){var o=e,i=r;void 0!==o||r&&r.getContext||(o=r,r=void 0),r||(i=function(){try{return document.createElement("canvas")}catch(t){throw new Error("You need to specify a canvas element")}}()),o=n.getOptions(o);var u=n.getImageWidth(t.modules.size,o),a=i.getContext("2d"),f=a.createImageData(u,u);return n.qrToImageData(f.data,t,o),function(t,r,e){t.clearRect(0,0,r.width,r.height),r.style||(r.style={}),r.height=e,r.width=e,r.style.height=e+"px",r.style.width=e+"px"}(a,i,u),a.putImageData(f,0,0),i},e.renderToDataURL=function(t,r,n){var o=n;void 0!==o||r&&r.getContext||(o=r,r=void 0),o||(o={});var i=e.render(t,r,o),u=o.type||"image/png",a=o.rendererOpts||{};return i.toDataURL(u,a.quality)}},{"./utils":27}],26:[function(t,r,e){function n(t,r){var e=t.a/255,n=r+'="'+t.hex+'"';return e<1?n+" "+r+'-opacity="'+e.toFixed(2).slice(1)+'"':n}function o(t,r,e){var n=t+r;return void 0!==e&&(n+=" "+e),n}function i(t,r,e){for(var n="",i=0,u=!1,a=0,f=0;f<t.length;f++){var s=Math.floor(f%r),h=Math.floor(f/r);s||u||(u=!0),t[f]?(a++,f>0&&s>0&&t[f-1]||(n+=u?o("M",s+e,.5+h+e):o("m",i,0),i=0,u=!1),s+1<r&&t[f+1]||(n+=o("h",a),a=0)):i++}return n}var u=t("./utils");e.render=function(t,r,e){var o=u.getOptions(r),a=t.modules.size,f=t.modules.data,s=a+2*o.margin,h=o.color.light.a?"<path "+n(o.color.light,"fill")+' d="M0 0h'+s+"v"+s+'H0z"/>':"",c="<path "+n(o.color.dark,"stroke")+' d="'+i(f,a,o.margin)+'"/>',l='viewBox="0 0 '+s+" "+s+'"',g='<svg xmlns="http://www.w3.org/2000/svg" '+(o.width?'width="'+o.width+'" height="'+o.width+'" ':"")+l+' shape-rendering="crispEdges">'+h+c+"</svg>\n";return"function"==typeof e&&e(null,g),g}},{"./utils":27}],27:[function(t,r,e){function n(t){if("number"==typeof t&&(t=t.toString()),"string"!=typeof t)throw new Error("Color should be defined as hex string");var r=t.slice().replace("#","").split("");if(r.length<3||5===r.length||r.length>8)throw new Error("Invalid hex color: "+t);3!==r.length&&4!==r.length||(r=Array.prototype.concat.apply([],r.map((function(t){return[t,t]})))),6===r.length&&r.push("F","F");var e=parseInt(r.join(""),16);return{r:e>>24&255,g:e>>16&255,b:e>>8&255,a:255&e,hex:"#"+r.slice(0,6).join("")}}e.getOptions=function(t){t||(t={}),t.color||(t.color={});var r=void 0===t.margin||null===t.margin||t.margin<0?4:t.margin,e=t.width&&t.width>=21?t.width:void 0,o=t.scale||4;return{width:e,scale:e?4:o,margin:r,color:{dark:n(t.color.dark||"#000000ff"),light:n(t.color.light||"#ffffffff")},type:t.type,rendererOpts:t.rendererOpts||{}}},e.getScale=function(t,r){return r.width&&r.width>=t+2*r.margin?r.width/(t+2*r.margin):r.scale},e.getImageWidth=function(t,r){var n=e.getScale(t,r);return Math.floor((t+2*r.margin)*n)},e.qrToImageData=function(t,r,n){for(var o=r.modules.size,i=r.modules.data,u=e.getScale(o,n),a=Math.floor((o+2*n.margin)*u),f=n.margin*u,s=[n.color.light,n.color.dark],h=0;h<a;h++)for(var c=0;c<a;c++){var l=4*(h*a+c),g=n.color.light;if(h>=f&&c>=f&&h<a-f&&c<a-f)g=s[i[Math.floor((h-f)/u)*o+Math.floor((c-f)/u)]?1:0];t[l++]=g.r,t[l++]=g.g,t[l++]=g.b,t[l]=g.a}}},{}],28:[function(t,r,e){"use strict";function n(t,r,e){return n.TYPED_ARRAY_SUPPORT||this instanceof n?"number"==typeof t?u(this,t):function(t,r,e,n){if("number"==typeof r)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&r instanceof ArrayBuffer?f(t,r,e,n):"string"==typeof r?function(t,r){var e=0|c(r),n=i(t,e),o=n.write(r);return o!==e&&(n=n.slice(0,o)),n}(t,r):s(t,r)}(this,t,r,e):new n(t,r,e)}function o(t){if(t>=g)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+g.toString(16)+" bytes");return 0|t}function i(t,r){var e;return n.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(r)).__proto__=n.prototype:(null===(e=t)&&(e=new n(r)),e.length=r),e}function u(t,r){var e=i(t,r<0?0:0|o(r));if(!n.TYPED_ARRAY_SUPPORT)for(var u=0;u<r;++u)e[u]=0;return e}function a(t,r){for(var e=r.length<0?0:0|o(r.length),n=i(t,e),u=0;u<e;u+=1)n[u]=255&r[u];return n}function f(t,r,e,o){if(e<0||r.byteLength<e)throw new RangeError("'offset' is out of bounds");if(r.byteLength<e+(o||0))throw new RangeError("'length' is out of bounds");var i;return i=void 0===e&&void 0===o?new Uint8Array(r):void 0===o?new Uint8Array(r,e):new Uint8Array(r,e,o),n.TYPED_ARRAY_SUPPORT?i.__proto__=n.prototype:i=a(t,i),i}function s(t,r){if(n.isBuffer(r)){var e=0|o(r.length),u=i(t,e);return 0===u.length||r.copy(u,0,0,e),u}if(r){if("undefined"!=typeof ArrayBuffer&&r.buffer instanceof ArrayBuffer||"length"in r)return"number"!=typeof r.length||function(t){return t!=t}(r.length)?i(t,0):a(t,r);if("Buffer"===r.type&&Array.isArray(r.data))return a(t,r.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function h(t,r){r=r||1/0;for(var e,n=t.length,o=null,i=[],u=0;u<n;++u){if((e=t.charCodeAt(u))>55295&&e<57344){if(!o){if(e>56319){(r-=3)>-1&&i.push(239,191,189);continue}if(u+1===n){(r-=3)>-1&&i.push(239,191,189);continue}o=e;continue}if(e<56320){(r-=3)>-1&&i.push(239,191,189),o=e;continue}e=65536+(o-55296<<10|e-56320)}else o&&(r-=3)>-1&&i.push(239,191,189);if(o=null,e<128){if((r-=1)<0)break;i.push(e)}else if(e<2048){if((r-=2)<0)break;i.push(e>>6|192,63&e|128)}else if(e<65536){if((r-=3)<0)break;i.push(e>>12|224,e>>6&63|128,63&e|128)}else{if(!(e<1114112))throw new Error("Invalid code point");if((r-=4)<0)break;i.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}}return i}function c(t){return n.isBuffer(t)?t.length:"undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer)?t.byteLength:("string"!=typeof t&&(t=""+t),0===t.length?0:h(t).length)}var l=t("isarray");n.TYPED_ARRAY_SUPPORT=function(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()}catch(t){return!1}}();var g=n.TYPED_ARRAY_SUPPORT?2147483647:1073741823;n.TYPED_ARRAY_SUPPORT&&(n.prototype.__proto__=Uint8Array.prototype,n.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&n[Symbol.species]===n&&Object.defineProperty(n,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1})),n.prototype.write=function(t,r,e){void 0===r||void 0===e&&"string"==typeof r?(e=this.length,r=0):isFinite(r)&&(r|=0,isFinite(e)?e|=0:e=void 0);var n=this.length-r;if((void 0===e||e>n)&&(e=n),t.length>0&&(e<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");return function(t,r,e,n){return function(t,r,e,n){for(var o=0;o<n&&!(o+e>=r.length||o>=t.length);++o)r[o+e]=t[o];return o}(h(r,t.length-e),t,e,n)}(this,t,r,e)},n.prototype.slice=function(t,r){var e,o=this.length;if((t=~~t)<0?(t+=o)<0&&(t=0):t>o&&(t=o),(r=void 0===r?o:~~r)<0?(r+=o)<0&&(r=0):r>o&&(r=o),r<t&&(r=t),n.TYPED_ARRAY_SUPPORT)(e=this.subarray(t,r)).__proto__=n.prototype;else{var i=r-t;e=new n(i,void 0);for(var u=0;u<i;++u)e[u]=this[u+t]}return e},n.prototype.copy=function(t,r,e,o){if(e||(e=0),o||0===o||(o=this.length),r>=t.length&&(r=t.length),r||(r=0),o>0&&o<e&&(o=e),o===e)return 0;if(0===t.length||0===this.length)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(e<0||e>=this.length)throw new RangeError("sourceStart out of bounds");if(o<0)throw new RangeError("sourceEnd out of bounds");o>this.length&&(o=this.length),t.length-r<o-e&&(o=t.length-r+e);var i,u=o-e;if(this===t&&e<r&&r<o)for(i=u-1;i>=0;--i)t[i+r]=this[i+e];else if(u<1e3||!n.TYPED_ARRAY_SUPPORT)for(i=0;i<u;++i)t[i+r]=this[i+e];else Uint8Array.prototype.set.call(t,this.subarray(e,e+u),r);return u},n.prototype.fill=function(t,r,e){if("string"==typeof t){if("string"==typeof r?(r=0,e=this.length):"string"==typeof e&&(e=this.length),1===t.length){var o=t.charCodeAt(0);o<256&&(t=o)}}else"number"==typeof t&&(t&=255);if(r<0||this.length<r||this.length<e)throw new RangeError("Out of range index");if(e<=r)return this;var i;if(r>>>=0,e=void 0===e?this.length:e>>>0,t||(t=0),"number"==typeof t)for(i=r;i<e;++i)this[i]=t;else{var u=n.isBuffer(t)?t:new n(t),a=u.length;for(i=0;i<e-r;++i)this[i+r]=u[i%a]}return this},n.concat=function(t,r){if(!l(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return i(null,0);var e;if(void 0===r)for(r=0,e=0;e<t.length;++e)r+=t[e].length;var o=u(null,r),a=0;for(e=0;e<t.length;++e){var f=t[e];if(!n.isBuffer(f))throw new TypeError('"list" argument must be an Array of Buffers');f.copy(o,a),a+=f.length}return o},n.byteLength=c,n.prototype._isBuffer=!0,n.isBuffer=function(t){return!(null==t||!t._isBuffer)},r.exports.alloc=function(t){var r=new n(t);return r.fill(0),r},r.exports.from=function(t){return new n(t)}},{isarray:33}],29:[function(t,r,e){"use strict";function n(t){var r=t.length;if(r%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var e=t.indexOf("=");return-1===e&&(e=r),[e,e===r?0:4-e%4]}function o(t){return u[t>>18&63]+u[t>>12&63]+u[t>>6&63]+u[63&t]}function i(t,r,e){for(var n,i=[],u=r;u<e;u+=3)n=(t[u]<<16&16711680)+(t[u+1]<<8&65280)+(255&t[u+2]),i.push(o(n));return i.join("")}e.byteLength=function(t){var r=n(t),e=r[0],o=r[1];return 3*(e+o)/4-o},e.toByteArray=function(t){var r,e,o=n(t),i=o[0],u=o[1],s=new f(function(t,r,e){return 3*(r+e)/4-e}(0,i,u)),h=0,c=u>0?i-4:i;for(e=0;e<c;e+=4)r=a[t.charCodeAt(e)]<<18|a[t.charCodeAt(e+1)]<<12|a[t.charCodeAt(e+2)]<<6|a[t.charCodeAt(e+3)],s[h++]=r>>16&255,s[h++]=r>>8&255,s[h++]=255&r;return 2===u&&(r=a[t.charCodeAt(e)]<<2|a[t.charCodeAt(e+1)]>>4,s[h++]=255&r),1===u&&(r=a[t.charCodeAt(e)]<<10|a[t.charCodeAt(e+1)]<<4|a[t.charCodeAt(e+2)]>>2,s[h++]=r>>8&255,s[h++]=255&r),s},e.fromByteArray=function(t){for(var r,e=t.length,n=e%3,o=[],a=0,f=e-n;a<f;a+=16383)o.push(i(t,a,a+16383>f?f:a+16383));return 1===n?(r=t[e-1],o.push(u[r>>2]+u[r<<4&63]+"==")):2===n&&(r=(t[e-2]<<8)+t[e-1],o.push(u[r>>10]+u[r>>4&63]+u[r<<2&63]+"=")),o.join("")};for(var u=[],a=[],f="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h=0,c=s.length;h<c;++h)u[h]=s[h],a[s.charCodeAt(h)]=h;a["-".charCodeAt(0)]=62,a["_".charCodeAt(0)]=63},{}],30:[function(t,r,e){"use strict";function n(t){if(t>z)throw new RangeError('The value "'+t+'" is invalid for option "size"');var r=new Uint8Array(t);return Object.setPrototypeOf(r,o.prototype),r}function o(t,r,e){if("number"==typeof t){if("string"==typeof r)throw new TypeError('The "string" argument must be of type string. Received type number');return a(t)}return i(t,r,e)}function i(t,r,e){if("string"==typeof t)return f(t,r);if(ArrayBuffer.isView(t))return s(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(O(t,ArrayBuffer)||t&&O(t.buffer,ArrayBuffer))return function(t,r,e){if(r<0||t.byteLength<r)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<r+(e||0))throw new RangeError('"length" is outside of buffer bounds');var n;return n=void 0===r&&void 0===e?new Uint8Array(t):void 0===e?new Uint8Array(t,r):new Uint8Array(t,r,e),Object.setPrototypeOf(n,o.prototype),n}(t,r,e);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');var n=t.valueOf&&t.valueOf();if(null!=n&&n!==t)return o.from(n,r,e);var i=h(t);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return o.from(t[Symbol.toPrimitive]("string"),r,e);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function u(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function a(t){return u(t),n(t<0?0:0|c(t))}function f(t,r){if("string"==typeof r&&""!==r||(r="utf8"),!o.isEncoding(r))throw new TypeError("Unknown encoding: "+r);var e=0|l(t,r),i=n(e),u=i.write(t,r);return u!==e&&(i=i.slice(0,u)),i}function s(t){for(var r=t.length<0?0:0|c(t.length),e=n(r),o=0;o<r;o+=1)e[o]=255&t[o];return e}function h(t){if(o.isBuffer(t)){var r=0|c(t.length),e=n(r);return 0===e.length||t.copy(e,0,0,r),e}return void 0!==t.length?"number"!=typeof t.length||Y(t.length)?n(0):s(t):"Buffer"===t.type&&Array.isArray(t.data)?s(t.data):void 0}function c(t){if(t>=z)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+z.toString(16)+" bytes");return 0|t}function l(t,r){if(o.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||O(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 e=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===e)return 0;for(var i=!1;;)switch(r){case"ascii":case"latin1":case"binary":return e;case"utf8":case"utf-8":return N(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*e;case"hex":return e>>>1;case"base64":return _(t).length;default:if(i)return n?-1:N(t).length;r=(""+r).toLowerCase(),i=!0}}function g(t,r,e){var n=!1;if((void 0===r||r<0)&&(r=0),r>this.length)return"";if((void 0===e||e>this.length)&&(e=this.length),e<=0)return"";if((e>>>=0)<=(r>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return P(this,r,e);case"utf8":case"utf-8":return T(this,r,e);case"ascii":return R(this,r,e);case"latin1":case"binary":return C(this,r,e);case"base64":return B(this,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return I(this,r,e);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function p(t,r,e){var n=t[r];t[r]=t[e],t[e]=n}function d(t,r,e,n,i){if(0===t.length)return-1;if("string"==typeof e?(n=e,e=0):e>2147483647?e=2147483647:e<-2147483648&&(e=-2147483648),Y(e=+e)&&(e=i?0:t.length-1),e<0&&(e=t.length+e),e>=t.length){if(i)return-1;e=t.length-1}else if(e<0){if(!i)return-1;e=0}if("string"==typeof r&&(r=o.from(r,n)),o.isBuffer(r))return 0===r.length?-1:y(t,r,e,n,i);if("number"==typeof r)return r&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,r,e):Uint8Array.prototype.lastIndexOf.call(t,r,e):y(t,[r],e,n,i);throw new TypeError("val must be string, number or Buffer")}function y(t,r,e,n,o){function i(t,r){return 1===a?t[r]:t.readUInt16BE(r*a)}var u,a=1,f=t.length,s=r.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||r.length<2)return-1;a=2,f/=2,s/=2,e/=2}if(o){var h=-1;for(u=e;u<f;u++)if(i(t,u)===i(r,-1===h?0:u-h)){if(-1===h&&(h=u),u-h+1===s)return h*a}else-1!==h&&(u-=u-h),h=-1}else for(e+s>f&&(e=f-s),u=e;u>=0;u--){for(var c=!0,l=0;l<s;l++)if(i(t,u+l)!==i(r,l)){c=!1;break}if(c)return u}return-1}function v(t,r,e,n){e=Number(e)||0;var o=t.length-e;n?(n=Number(n))>o&&(n=o):n=o;var i=r.length;n>i/2&&(n=i/2);for(var u=0;u<n;++u){var a=parseInt(r.substr(2*u,2),16);if(Y(a))return u;t[e+u]=a}return u}function w(t,r,e,n){return k(N(r,t.length-e),t,e,n)}function m(t,r,e,n){return k(function(t){for(var r=[],e=0;e<t.length;++e)r.push(255&t.charCodeAt(e));return r}(r),t,e,n)}function b(t,r,e,n){return m(t,r,e,n)}function E(t,r,e,n){return k(_(r),t,e,n)}function A(t,r,e,n){return k(function(t,r){for(var e,n,o,i=[],u=0;u<t.length&&!((r-=2)<0);++u)e=t.charCodeAt(u),n=e>>8,o=e%256,i.push(o),i.push(n);return i}(r,t.length-e),t,e,n)}function B(t,r,e){return 0===r&&e===t.length?D.fromByteArray(t):D.fromByteArray(t.slice(r,e))}function T(t,r,e){e=Math.min(t.length,e);for(var n=[],o=r;o<e;){var i,u,a,f,s=t[o],h=null,c=s>239?4:s>223?3:s>191?2:1;if(o+c<=e)switch(c){case 1:s<128&&(h=s);break;case 2:128==(192&(i=t[o+1]))&&(f=(31&s)<<6|63&i)>127&&(h=f);break;case 3:i=t[o+1],u=t[o+2],128==(192&i)&&128==(192&u)&&(f=(15&s)<<12|(63&i)<<6|63&u)>2047&&(f<55296||f>57343)&&(h=f);break;case 4:i=t[o+1],u=t[o+2],a=t[o+3],128==(192&i)&&128==(192&u)&&128==(192&a)&&(f=(15&s)<<18|(63&i)<<12|(63&u)<<6|63&a)>65535&&f<1114112&&(h=f)}null===h?(h=65533,c=1):h>65535&&(h-=65536,n.push(h>>>10&1023|55296),h=56320|1023&h),n.push(h),o+=c}return function(t){var r=t.length;if(r<=H)return String.fromCharCode.apply(String,t);for(var e="",n=0;n<r;)e+=String.fromCharCode.apply(String,t.slice(n,n+=H));return e}(n)}function R(t,r,e){var n="";e=Math.min(t.length,e);for(var o=r;o<e;++o)n+=String.fromCharCode(127&t[o]);return n}function C(t,r,e){var n="";e=Math.min(t.length,e);for(var o=r;o<e;++o)n+=String.fromCharCode(t[o]);return n}function P(t,r,e){var n=t.length;(!r||r<0)&&(r=0),(!e||e<0||e>n)&&(e=n);for(var o="",i=r;i<e;++i)o+=K[t[i]];return o}function I(t,r,e){for(var n=t.slice(r,e),o="",i=0;i<n.length;i+=2)o+=String.fromCharCode(n[i]+256*n[i+1]);return o}function M(t,r,e){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+r>e)throw new RangeError("Trying to access beyond buffer length")}function U(t,r,e,n,i,u){if(!o.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(r>i||r<u)throw new RangeError('"value" argument is out of bounds');if(e+n>t.length)throw new RangeError("Index out of range")}function S(t,r,e,n,o,i){if(e+n>t.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("Index out of range")}function L(t,r,e,n,o){return r=+r,e>>>=0,o||S(t,0,e,4),j.write(t,r,e,n,23,4),e+4}function x(t,r,e,n,o){return r=+r,e>>>=0,o||S(t,0,e,8),j.write(t,r,e,n,52,8),e+8}function N(t,r){r=r||1/0;for(var e,n=t.length,o=null,i=[],u=0;u<n;++u){if((e=t.charCodeAt(u))>55295&&e<57344){if(!o){if(e>56319){(r-=3)>-1&&i.push(239,191,189);continue}if(u+1===n){(r-=3)>-1&&i.push(239,191,189);continue}o=e;continue}if(e<56320){(r-=3)>-1&&i.push(239,191,189),o=e;continue}e=65536+(o-55296<<10|e-56320)}else o&&(r-=3)>-1&&i.push(239,191,189);if(o=null,e<128){if((r-=1)<0)break;i.push(e)}else if(e<2048){if((r-=2)<0)break;i.push(e>>6|192,63&e|128)}else if(e<65536){if((r-=3)<0)break;i.push(e>>12|224,e>>6&63|128,63&e|128)}else{if(!(e<1114112))throw new Error("Invalid code point");if((r-=4)<0)break;i.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}}return i}function _(t){return D.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(J,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function k(t,r,e,n){for(var o=0;o<n&&!(o+e>=r.length||o>=t.length);++o)r[o+e]=t[o];return o}function O(t,r){return t instanceof r||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===r.name}function Y(t){return t!=t}var D=t("base64-js"),j=t("ieee754"),F="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=o,e.SlowBuffer=function(t){return+t!=t&&(t=0),o.alloc(+t)},e.INSPECT_MAX_BYTES=50;var z=2147483647;e.kMaxLength=z,o.TYPED_ARRAY_SUPPORT=function(){try{var t=new Uint8Array(1),r={foo:function(){return 42}};return Object.setPrototypeOf(r,Uint8Array.prototype),Object.setPrototypeOf(t,r),42===t.foo()}catch(t){return!1}}(),o.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||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."),Object.defineProperty(o.prototype,"parent",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.buffer}}),Object.defineProperty(o.prototype,"offset",{enumerable:!0,get:function(){if(o.isBuffer(this))return this.byteOffset}}),"undefined"!=typeof Symbol&&null!=Symbol.species&&o[Symbol.species]===o&&Object.defineProperty(o,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1}),o.poolSize=8192,o.from=function(t,r,e){return i(t,r,e)},Object.setPrototypeOf(o.prototype,Uint8Array.prototype),Object.setPrototypeOf(o,Uint8Array),o.alloc=function(t,r,e){return function(t,r,e){return u(t),t<=0?n(t):void 0!==r?"string"==typeof e?n(t).fill(r,e):n(t).fill(r):n(t)}(t,r,e)},o.allocUnsafe=function(t){return a(t)},o.allocUnsafeSlow=function(t){return a(t)},o.isBuffer=function(t){return null!=t&&!0===t._isBuffer&&t!==o.prototype},o.compare=function(t,r){if(O(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),O(r,Uint8Array)&&(r=o.from(r,r.offset,r.byteLength)),!o.isBuffer(t)||!o.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(t===r)return 0;for(var e=t.length,n=r.length,i=0,u=Math.min(e,n);i<u;++i)if(t[i]!==r[i]){e=t[i],n=r[i];break}return e<n?-1:n<e?1:0},o.isEncoding=function(t){switch(String(t).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!0;default:return!1}},o.concat=function(t,r){if(!Array.isArray(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return o.alloc(0);var e;if(void 0===r)for(r=0,e=0;e<t.length;++e)r+=t[e].length;var n=o.allocUnsafe(r),i=0;for(e=0;e<t.length;++e){var u=t[e];if(O(u,Uint8Array)&&(u=o.from(u)),!o.isBuffer(u))throw new TypeError('"list" argument must be an Array of Buffers');u.copy(n,i),i+=u.length}return n},o.byteLength=l,o.prototype._isBuffer=!0,o.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;r<t;r+=2)p(this,r,r+1);return this},o.prototype.swap32=function(){var t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var r=0;r<t;r+=4)p(this,r,r+3),p(this,r+1,r+2);return this},o.prototype.swap64=function(){var t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var r=0;r<t;r+=8)p(this,r,r+7),p(this,r+1,r+6),p(this,r+2,r+5),p(this,r+3,r+4);return this},o.prototype.toString=function(){var t=this.length;return 0===t?"":0===arguments.length?T(this,0,t):g.apply(this,arguments)},o.prototype.toLocaleString=o.prototype.toString,o.prototype.equals=function(t){if(!o.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===o.compare(this,t)},o.prototype.inspect=function(){var t="",r=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(t+=" ... "),"<Buffer "+t+">"},F&&(o.prototype[F]=o.prototype.inspect),o.prototype.compare=function(t,r,e,n,i){if(O(t,Uint8Array)&&(t=o.from(t,t.offset,t.byteLength)),!o.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===r&&(r=0),void 0===e&&(e=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),r<0||e>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&r>=e)return 0;if(n>=i)return-1;if(r>=e)return 1;if(this===t)return 0;for(var u=(i>>>=0)-(n>>>=0),a=(e>>>=0)-(r>>>=0),f=Math.min(u,a),s=this.slice(n,i),h=t.slice(r,e),c=0;c<f;++c)if(s[c]!==h[c]){u=s[c],a=h[c];break}return u<a?-1:a<u?1:0},o.prototype.includes=function(t,r,e){return-1!==this.indexOf(t,r,e)},o.prototype.indexOf=function(t,r,e){return d(this,t,r,e,!0)},o.prototype.lastIndexOf=function(t,r,e){return d(this,t,r,e,!1)},o.prototype.write=function(t,r,e,n){if(void 0===r)n="utf8",e=this.length,r=0;else if(void 0===e&&"string"==typeof r)n=r,e=this.length,r=0;else{if(!isFinite(r))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");r>>>=0,isFinite(e)?(e>>>=0,void 0===n&&(n="utf8")):(n=e,e=void 0)}var o=this.length-r;if((void 0===e||e>o)&&(e=o),t.length>0&&(e<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return v(this,t,r,e);case"utf8":case"utf-8":return w(this,t,r,e);case"ascii":return m(this,t,r,e);case"latin1":case"binary":return b(this,t,r,e);case"base64":return E(this,t,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,t,r,e);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var H=4096;o.prototype.slice=function(t,r){var e=this.length;(t=~~t)<0?(t+=e)<0&&(t=0):t>e&&(t=e),(r=void 0===r?e:~~r)<0?(r+=e)<0&&(r=0):r>e&&(r=e),r<t&&(r=t);var n=this.subarray(t,r);return Object.setPrototypeOf(n,o.prototype),n},o.prototype.readUIntLE=function(t,r,e){t>>>=0,r>>>=0,e||M(t,r,this.length);for(var n=this[t],o=1,i=0;++i<r&&(o*=256);)n+=this[t+i]*o;return n},o.prototype.readUIntBE=function(t,r,e){t>>>=0,r>>>=0,e||M(t,r,this.length);for(var n=this[t+--r],o=1;r>0&&(o*=256);)n+=this[t+--r]*o;return n},o.prototype.readUInt8=function(t,r){return t>>>=0,r||M(t,1,this.length),this[t]},o.prototype.readUInt16LE=function(t,r){return t>>>=0,r||M(t,2,this.length),this[t]|this[t+1]<<8},o.prototype.readUInt16BE=function(t,r){return t>>>=0,r||M(t,2,this.length),this[t]<<8|this[t+1]},o.prototype.readUInt32LE=function(t,r){return t>>>=0,r||M(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},o.prototype.readUInt32BE=function(t,r){return t>>>=0,r||M(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},o.prototype.readIntLE=function(t,r,e){t>>>=0,r>>>=0,e||M(t,r,this.length);for(var n=this[t],o=1,i=0;++i<r&&(o*=256);)n+=this[t+i]*o;return n>=(o*=128)&&(n-=Math.pow(2,8*r)),n},o.prototype.readIntBE=function(t,r,e){t>>>=0,r>>>=0,e||M(t,r,this.length);for(var n=r,o=1,i=this[t+--n];n>0&&(o*=256);)i+=this[t+--n]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*r)),i},o.prototype.readInt8=function(t,r){return t>>>=0,r||M(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},o.prototype.readInt16LE=function(t,r){t>>>=0,r||M(t,2,this.length);var e=this[t]|this[t+1]<<8;return 32768&e?4294901760|e:e},o.prototype.readInt16BE=function(t,r){t>>>=0,r||M(t,2,this.length);var e=this[t+1]|this[t]<<8;return 32768&e?4294901760|e:e},o.prototype.readInt32LE=function(t,r){return t>>>=0,r||M(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},o.prototype.readInt32BE=function(t,r){return t>>>=0,r||M(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},o.prototype.readFloatLE=function(t,r){return t>>>=0,r||M(t,4,this.length),j.read(this,t,!0,23,4)},o.prototype.readFloatBE=function(t,r){return t>>>=0,r||M(t,4,this.length),j.read(this,t,!1,23,4)},o.prototype.readDoubleLE=function(t,r){return t>>>=0,r||M(t,8,this.length),j.read(this,t,!0,52,8)},o.prototype.readDoubleBE=function(t,r){return t>>>=0,r||M(t,8,this.length),j.read(this,t,!1,52,8)},o.prototype.writeUIntLE=function(t,r,e,n){t=+t,r>>>=0,e>>>=0,n||U(this,t,r,e,Math.pow(2,8*e)-1,0);var o=1,i=0;for(this[r]=255&t;++i<e&&(o*=256);)this[r+i]=t/o&255;return r+e},o.prototype.writeUIntBE=function(t,r,e,n){t=+t,r>>>=0,e>>>=0,n||U(this,t,r,e,Math.pow(2,8*e)-1,0);var o=e-1,i=1;for(this[r+o]=255&t;--o>=0&&(i*=256);)this[r+o]=t/i&255;return r+e},o.prototype.writeUInt8=function(t,r,e){return t=+t,r>>>=0,e||U(this,t,r,1,255,0),this[r]=255&t,r+1},o.prototype.writeUInt16LE=function(t,r,e){return t=+t,r>>>=0,e||U(this,t,r,2,65535,0),this[r]=255&t,this[r+1]=t>>>8,r+2},o.prototype.writeUInt16BE=function(t,r,e){return t=+t,r>>>=0,e||U(this,t,r,2,65535,0),this[r]=t>>>8,this[r+1]=255&t,r+2},o.prototype.writeUInt32LE=function(t,r,e){return t=+t,r>>>=0,e||U(this,t,r,4,4294967295,0),this[r+3]=t>>>24,this[r+2]=t>>>16,this[r+1]=t>>>8,this[r]=255&t,r+4},o.prototype.writeUInt32BE=function(t,r,e){return t=+t,r>>>=0,e||U(this,t,r,4,4294967295,0),this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t,r+4},o.prototype.writeIntLE=function(t,r,e,n){if(t=+t,r>>>=0,!n){var o=Math.pow(2,8*e-1);U(this,t,r,e,o-1,-o)}var i=0,u=1,a=0;for(this[r]=255&t;++i<e&&(u*=256);)t<0&&0===a&&0!==this[r+i-1]&&(a=1),this[r+i]=(t/u>>0)-a&255;return r+e},o.prototype.writeIntBE=function(t,r,e,n){if(t=+t,r>>>=0,!n){var o=Math.pow(2,8*e-1);U(this,t,r,e,o-1,-o)}var i=e-1,u=1,a=0;for(this[r+i]=255&t;--i>=0&&(u*=256);)t<0&&0===a&&0!==this[r+i+1]&&(a=1),this[r+i]=(t/u>>0)-a&255;return r+e},o.prototype.writeInt8=function(t,r,e){return t=+t,r>>>=0,e||U(this,t,r,1,127,-128),t<0&&(t=255+t+1),this[r]=255&t,r+1},o.prototype.writeInt16LE=function(t,r,e){return t=+t,r>>>=0,e||U(this,t,r,2,32767,-32768),this[r]=255&t,this[r+1]=t>>>8,r+2},o.prototype.writeInt16BE=function(t,r,e){return t=+t,r>>>=0,e||U(this,t,r,2,32767,-32768),this[r]=t>>>8,this[r+1]=255&t,r+2},o.prototype.writeInt32LE=function(t,r,e){return t=+t,r>>>=0,e||U(this,t,r,4,2147483647,-2147483648),this[r]=255&t,this[r+1]=t>>>8,this[r+2]=t>>>16,this[r+3]=t>>>24,r+4},o.prototype.writeInt32BE=function(t,r,e){return t=+t,r>>>=0,e||U(this,t,r,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t,r+4},o.prototype.writeFloatLE=function(t,r,e){return L(this,t,r,!0,e)},o.prototype.writeFloatBE=function(t,r,e){return L(this,t,r,!1,e)},o.prototype.writeDoubleLE=function(t,r,e){return x(this,t,r,!0,e)},o.prototype.writeDoubleBE=function(t,r,e){return x(this,t,r,!1,e)},o.prototype.copy=function(t,r,e,n){if(!o.isBuffer(t))throw new TypeError("argument should be a Buffer");if(e||(e=0),n||0===n||(n=this.length),r>=t.length&&(r=t.length),r||(r=0),n>0&&n<e&&(n=e),n===e)return 0;if(0===t.length||0===this.length)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(e<0||e>=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),t.length-r<n-e&&(n=t.length-r+e);var i=n-e;if(this===t&&"function"==typeof Uint8Array.prototype.copyWithin)this.copyWithin(r,e,n);else if(this===t&&e<r&&r<n)for(var u=i-1;u>=0;--u)t[u+r]=this[u+e];else Uint8Array.prototype.set.call(t,this.subarray(e,n),r);return i},o.prototype.fill=function(t,r,e,n){if("string"==typeof t){if("string"==typeof r?(n=r,r=0,e=this.length):"string"==typeof e&&(n=e,e=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!o.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===t.length){var i=t.charCodeAt(0);("utf8"===n&&i<128||"latin1"===n)&&(t=i)}}else"number"==typeof t?t&=255:"boolean"==typeof t&&(t=Number(t));if(r<0||this.length<r||this.length<e)throw new RangeError("Out of range index");if(e<=r)return this;var u;if(r>>>=0,e=void 0===e?this.length:e>>>0,t||(t=0),"number"==typeof t)for(u=r;u<e;++u)this[u]=t;else{var a=o.isBuffer(t)?t:o.from(t,n),f=a.length;if(0===f)throw new TypeError('The value "'+t+'" is invalid for argument "value"');for(u=0;u<e-r;++u)this[u+r]=a[u%f]}return this};var J=/[^+\/0-9A-Za-z-_]/g,K=function(){for(var t=new Array(256),r=0;r<16;++r)for(var e=16*r,n=0;n<16;++n)t[e+n]="0123456789abcdef"[r]+"0123456789abcdef"[n];return t}()},{"base64-js":29,ieee754:32}],31:[function(t,r,e){"use strict";var n={single_source_shortest_paths:function(t,r,e){var o={},i={};i[r]=0;var u,a,f,s,h,c,l,g=n.PriorityQueue.make();for(g.push(r,0);!g.empty();)for(f in a=(u=g.pop()).value,s=u.cost,h=t[a]||{})h.hasOwnProperty(f)&&(c=s+h[f],l=i[f],(void 0===i[f]||l>c)&&(i[f]=c,g.push(f,c),o[f]=a));if(void 0!==e&&void 0===i[e]){var p=["Could not find a path from ",r," to ",e,"."].join("");throw new Error(p)}return o},extract_shortest_path_from_predecessor_list:function(t,r){for(var e=[],n=r;n;)e.push(n),t[n],n=t[n];return e.reverse(),e},find_path:function(t,r,e){var o=n.single_source_shortest_paths(t,r,e);return n.extract_shortest_path_from_predecessor_list(o,e)},PriorityQueue:{make:function(t){var r,e=n.PriorityQueue,o={};for(r in t=t||{},e)e.hasOwnProperty(r)&&(o[r]=e[r]);return o.queue=[],o.sorter=t.sorter||e.default_sorter,o},default_sorter:function(t,r){return t.cost-r.cost},push:function(t,r){var e={value:t,cost:r};this.queue.push(e),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return 0===this.queue.length}}};void 0!==r&&(r.exports=n)},{}],32:[function(t,r,e){e.read=function(t,r,e,n,o){var i,u,a=8*o-n-1,f=(1<<a)-1,s=f>>1,h=-7,c=e?o-1:0,l=e?-1:1,g=t[r+c];for(c+=l,i=g&(1<<-h)-1,g>>=-h,h+=a;h>0;i=256*i+t[r+c],c+=l,h-=8);for(u=i&(1<<-h)-1,i>>=-h,h+=n;h>0;u=256*u+t[r+c],c+=l,h-=8);if(0===i)i=1-s;else{if(i===f)return u?NaN:1/0*(g?-1:1);u+=Math.pow(2,n),i-=s}return(g?-1:1)*u*Math.pow(2,i-n)},e.write=function(t,r,e,n,o,i){var u,a,f,s=8*i-o-1,h=(1<<s)-1,c=h>>1,l=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,g=n?0:i-1,p=n?1:-1,d=r<0||0===r&&1/r<0?1:0;for(r=Math.abs(r),isNaN(r)||r===1/0?(a=isNaN(r)?1:0,u=h):(u=Math.floor(Math.log(r)/Math.LN2),r*(f=Math.pow(2,-u))<1&&(u--,f*=2),(r+=u+c>=1?l/f:l*Math.pow(2,1-c))*f>=2&&(u++,f/=2),u+c>=h?(a=0,u=h):u+c>=1?(a=(r*f-1)*Math.pow(2,o),u+=c):(a=r*Math.pow(2,c-1)*Math.pow(2,o),u=0));o>=8;t[e+g]=255&a,g+=p,a/=256,o-=8);for(u=u<<o|a,s+=o;s>0;t[e+g]=255&u,g+=p,u/=256,s-=8);t[e+g-p]|=128*d}},{}],33:[function(t,r,e){var n={}.toString;r.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},{}]},{},[24])(24)}));
\ No newline at end of file
index a6c3390..3932ac3 100644 (file)
@@ -1,106 +1 @@
-(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}(g.QRCode || (g.QRCode = {})).toSJIS = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
-var SJIS_UTF8 = [
-  [0x8140, ' 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈〉《》「」『』【】+-±×'],
-  [0x8180, '÷=≠<>'],
-  [0x818f, '¥$¢£%#&*@§☆★'],
-  [0x81a6, '※〒→←↑↓〓'],
-  [0x81ca, '¬'],
-  [0x824f, '0123456789'],
-  [0x8260, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'],
-  [0x8281, 'abcdefghijklmnopqrstuvwxyz'],
-  [0x829f, 'ぁあぃいぅうぇえぉおかがきぎくぐけげこごさざしじすずせぜそぞただちぢっつづてでとどなにぬねのはばぱひびぴふぶぷへべぺほぼぽまみむめもゃやゅゆょよらりるれろゎわゐゑをん'],
-  [0x8340, 'ァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミ'],
-  [0x8380, 'ムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶ'],
-  [0x839f, 'ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ'],
-  [0x83bf, 'αβγδεζηθικλμνξοπρστυφχψω'],
-  [0x8440, 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ'],
-  [0x8470, 'абвгдеёжзийклмн'],
-  [0x8480, 'опрстуфхцчшщъыьэюя'],
-  [0x8780, '〝〟'],
-  [0x8940, '院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円'],
-  [0x8980, '園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改'],
-  [0x8a40, '魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫'],
-  [0x8a80, '橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄'],
-  [0x8b40, '機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救'],
-  [0x8b80, '朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈'],
-  [0x8c40, '掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨'],
-  [0x8c80, '劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向'],
-  [0x8d40, '后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降'],
-  [0x8d80, '項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷'],
-  [0x8e40, '察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止'],
-  [0x8e80, '死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周'],
-  [0x8f40, '宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳'],
-  [0x8f80, '準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾'],
-  [0x9040, '拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨'],
-  [0x9080, '逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線'],
-  [0x9140, '繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻'],
-  [0x9180, '操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只'],
-  [0x9240, '叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄'],
-  [0x9280, '逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓'],
-  [0x9340, '邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬'],
-  [0x9380, '凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入'],
-  [0x9440, '如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅'],
-  [0x9480, '楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美'],
-  [0x9540, '鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷'],
-  [0x9580, '斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋'],
-  [0x9640, '法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆'],
-  [0x9680, '摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒'],
-  [0x9740, '諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲'],
-  [0x9780, '沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯'],
-  [0x9840, '蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕'],
-  [0x989f, '弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲'],
-  [0x9940, '僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭'],
-  [0x9980, '凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨'],
-  [0x9a40, '咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸'],
-  [0x9a80, '噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩'],
-  [0x9b40, '奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀'],
-  [0x9b80, '它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏'],
-  [0x9c40, '廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠'],
-  [0x9c80, '怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛'],
-  [0x9d40, '戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫'],
-  [0x9d80, '捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼'],
-  [0x9e40, '曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎'],
-  [0x9e80, '梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣'],
-  [0x9f40, '檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯'],
-  [0x9f80, '麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌'],
-  [0xe040, '漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝'],
-  [0xe080, '烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱'],
-  [0xe140, '瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿'],
-  [0xe180, '痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬'],
-  [0xe240, '磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰'],
-  [0xe280, '窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆'],
-  [0xe340, '紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷'],
-  [0xe380, '縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋'],
-  [0xe440, '隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤'],
-  [0xe480, '艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈'],
-  [0xe540, '蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬'],
-  [0xe580, '蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞'],
-  [0xe640, '襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧'],
-  [0xe680, '諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊'],
-  [0xe740, '蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜'],
-  [0xe780, '轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮'],
-  [0xe840, '錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙'],
-  [0xe880, '閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰'],
-  [0xe940, '顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃'],
-  [0xe980, '騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈'],
-  [0xea40, '鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯'],
-  [0xea80, '黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙']
-]
-
-module.exports = function toSJIS (utf8Char) {
-  if (!utf8Char || utf8Char === '') return
-
-  for (var i = 0; i < SJIS_UTF8.length; i++) {
-    var kanji = SJIS_UTF8[i][1]
-
-    var posIndex = kanji.indexOf(utf8Char)
-    if (posIndex >= 0) {
-      return SJIS_UTF8[i][0] + posIndex
-    }
-  }
-}
-
-},{}]},{},[1])(1)
-});
-
-//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9icm93c2VyLXBhY2svX3ByZWx1ZGUuanMiLCJoZWxwZXIvdG8tc2ppcy5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQ0FBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7Q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1nOequuS4keeik+iHvOa4puWYmOWUhOasneiUmumwu+WnpeWOqea1pueTnOmWj+WZguS6kemBi+mbsuiNj+mkjOWPoeWWtuWssOW9seaYoOabs+aghOawuOazs+a0qeeRm+ebiOepjumgtOiLseihm+ipoOmLrea2sueWq+ebiumnheaCpuisgei2iumWsuamjuWOreWGhiddLFxuICBbMHg4OTgwLCAn5ZyS5aCw5aWE5a605bu25oCo5o6p5o+05rK/5ryU54KO54SU54WZ54eV54y/57iB6Im26IuR6JaX6YGg6Ymb6bSb5aGp5pa85rGa55Sl5Ye55aSu5aWl5b6A5b+c5oq85pe65qiq5qyn5q60546L57+B6KWW6bSs6bSO6buE5bKh5rKW6I275YSE5bGL5oa26IeG5qG254mh5LmZ5L+65Y245oGp5rip56mP6Z+z5LiL5YyW5Luu5L2V5Ly95L6h5L2z5Yqg5Y+v5ZiJ5aSP5auB5a625a+h56eR5pqH5p6c5p625q2M5rKz54Gr54+C56aN56a+56i8566H6Iqx6Iub6IyE6I236I+v6I+T6J2m6Kqy5Zip6LKo6L+m6YGO6Zye6JqK5L+E5bOo5oiR54mZ55S76Iel6Iq96Ju+6LOA6ZuF6aST6aeV5LuL5Lya6Kej5Zue5aGK5aOK5bu75b+r5oCq5oKU5oGi5oeQ5oiS5ouQ5pS5J10sXG4gIFsweDhhNDAsICfprYHmmabmorDmtbfngbDnlYznmobntbXoiqXon7nplovpmo7osp3lh7Hlir7lpJblkrPlrrPltJbmhajmpoLmtq/noo3ok4vooZfoqbLpjqfpqrjmtazppqjom5nlnqPmn7/om47piI7lioPlmoflkITlu5Pmi6HmkrnmoLzmoLjmrrvnjbLnorrnqavopprop5LotavovIPpg63plqPpmpTpnanlrablsrPmpb3poY3poY7mjpvnrKDmqKsnXSxcbiAgWzB4OGE4MCwgJ+apv+aitumwjea9n+WJsuWWneaBsOaLrOa0u+a4h+a7keiRm+ikkOi9hOS4lOmwueWPtuakm+aouumehOagquWFnOerg+iSsumHnOmOjOWZm+m0qOagouiMheiQseeypeWIiOiLheeTpuS5vuS+g+WGoOWvkuWIiuWLmOWLp+W3u+WWmuWgquWnpuWujOWumOWvm+W5suW5ueaCo+aEn+aFo+aGvuaPm+aVouafkeahk+ajuuasvuatk+axl+a8oua+l+a9heeSsOeUmOebo+eci+erv+euoeewoee3qee8tue/sOiCneiJpuiOnuims+irjOiyq+mChOmRkemWk+mWkemWoumZpemfk+mkqOiImOS4uOWQq+WyuOW3jOeOqeeZjOecvOWyqee/q+i0i+mbgemgkemhlOmhmOS8geS8juWNseWWnOWZqOWfuuWlh+WsieWvhOWykOW4jOW5vuW/jOaPruacuuaXl+aXouacn+aji+ajhCddLFxuICBbMHg4YjQwLCAn5qmf5biw5q+F5rCX5rG955W/56WI5a2j56iA57SA5b696KaP6KiY6LK06LW36LuM6Lyd6aOi6aiO6ay85LqA5YG95YSA5aaT5a6c5oiv5oqA5pOs5qy654qg55aR56WH576p6J+76Kq86K2w5o6s6I+K6Z6g5ZCJ5ZCD5Zar5qGU5qmY6Kmw56Cn5p216buN5Y205a6i6ISa6JmQ6YCG5LiY5LmF5LuH5LyR5Y+K5ZC45a6u5byT5oCl5pWRJ10sXG4gIFsweDhiODAsICfmnL3msYLmsbLms6PngbjnkIPnqbbnqq7nrIjntJrns77ntabml6fniZvljrvlsYXlt6jmi5Lmi6DmjJnmuKDomZroqLHot53pi7jmvIHnpqbprZrkuqjkuqvkuqzkvpvkvqDlg5HlhYfnq7blhbHlh7bljZTljKHljb/lj6vllqzlooPls6HlvLflvYrmgK/mgZDmga3mjJ/mlZnmqYvms4Hni4Lni63nn6/og7johIXoiIjolY7pg7fpj6Hpn7/ppZfpqZrku7Dlh53lsK3mmoHmpa3lsYDmm7LmpbXnjonmoZDnsoHlg4Xli6TlnYflt77pjKbmlqTmrKPmrL3nkLTnpoHnpr3nrYvnt4roirnoj4zoob/opZ/orLnov5Hph5HlkJ/pioDkuZ3lgLblj6XljLrni5fnjpbnn6noi6bouq/pp4bpp4jpp5LlhbfmhJromZ7llrDn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qTpmY0nXSxcbiAgWzB4OGQ4MCwgJ+mghemmmemrmOm0u+WJm+WKq+WPt+WQiOWjleaLt+a/oOixqui9n+m6ueWFi+WIu+WRiuWbveepgOmFt+m1oOm7kueNhOa8ieiFsOeUkeW/veaDmumqqOeLm+i+vOatpOmgg+S7iuWbsOWdpOWivuWpmuaBqOaHh+aYj+aYhuagueaisea3t+eXlee0uuiJrumtguS6m+S9kOWPieWUhuW1r+W3puW3ruafu+aymeeRs+egguipkOmOluijn+WdkOW6p+aMq+WCteWCrOWGjeacgOWTieWhnuWmu+WusOW9qeaJjeaOoeagveats+a4iOeBvemHh+eKgOegleegpuelreaWjue0sOiPnOijgei8iemam+WJpOWcqOadkOe9quiyoeWGtOWdgumYquWguuamiuiCtOWSsuW0juWfvOeilem3uuS9nOWJiuWSi+aQvuaYqOaclOafteeqhOetlue0oumMr+ahnOmureesueWMmeWGiuWItyddLFxuICBbMHg4ZTQwLCAn5a+f5ou25pKu5pOm5pyt5q666Jap6ZuR55qQ6a+W5o2M6YyG6a6r55q/5pmS5LiJ5YKY5Y+C5bGx5oOo5pKS5pWj5qGf54em54+K55Sj566X57qC6JqV6K6D6LOb6YW46aSQ5pas5pqr5q6L5LuV5LuU5Ly65L2/5Yi65Y+45Y+y5Zej5Zub5aOr5aeL5aeJ5ae/5a2Q5bGN5biC5bir5b+X5oCd5oyH5pSv5a2c5pav5pa95peo5p6d5q2iJ10sXG4gIFsweDhlODAsICfmrbvmsI/njYXnpYnnp4Hns7jntJnntKvogqLohILoh7PoppboqZ7oqanoqaboqozoq67os4fos5zpm4zpo7zmra/kuovkvLzkvo3lhZDlrZflr7rmhYjmjIHmmYLmrKHmu4vmsrvniL7nkr3nl5Tno4HnpLrogIzogLPoh6rokpTovp7msZDpub/lvI/orZjptKvnq7rou7jlro3pm6vkuIPlj7Hln7flpLHlq4nlrqTmgonmub/mvIbnlr7os6rlrp/olIDnr6DlgbLmn7Toip3lsaHolYrnuJ7oiI7lhpnlsITmjajotabmlp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LPnlrnnnJ/npZ7np6bntLPoh6Poiq/olqropqroqLrouqvovpvpgLLph53pnIfkurrku4HliIPlobXlo6zlsIvnlJrlsL3ohY7oqIrov4XpmaPpna3nrKXoq4/poIjphaLlm7PljqgnXSxcbiAgWzB4OTA4MCwgJ+mAl+WQueWeguW4peaOqOawtOeCiuedoeeyi+e/oOihsOmBgumFlOmMkOmMmOmaj+eRnumrhOW0h+W1qeaVsOaeoui2qOmbm+aNruadieakmeiPhemgl+mbgOijvua+hOaRuuWvuOS4lueArOeVneaYr+WHhOWItuWLouWnk+W+geaAp+aIkOaUv+aVtOaYn+aZtOajsuagluato+a4heeJsueUn+ebm+eyvuiBluWjsOijveilv+iqoOiqk+iri+mAnemGkumdkumdmeaWieeojuiEhumau+W4reaDnOaImuaWpeaYlOaekOefs+epjeexjee4vuiEiuiyrOi1pOi3oei5n+eiqeWIh+aLmeaOpeaRguaKmOioreeqg+evgOiqrOmbque1tuiIjOidieS7meWFiOWNg+WNoOWuo+WwguWwluW3neaIpuaJh+aSsOagk+agtOaziea1hea0l+afk+a9nOeFjueFveaXi+epv+euree3middLFxuICBbMHg5MTQwLCAn57mK576o6IW66Iib6Ii56Jam6Kmu6LOO6Le16YG46YG36Yqt6YqR6ZaD6a6u5YmN5ZaE5ry454S25YWo56aF57mV6Iaz57OO5ZmM5aGR5bKo5o6q5pu+5pu95qWa54uZ55aP55aO56SO56WW56ef57KX57Sg57WE6JiH6Ki06Zi76YGh6byg5YOn5Ym15Y+M5Y+i5YCJ5Zaq5aOu5aWP54i95a6L5bGk5Yyd5oOj5oOz5o2c5o6D5oy/5o67J10sXG4gIFsweDkxODAsICfmk43ml6nmm7nlt6Pmp43mp73mvJXnh6Xkuonnl6nnm7jnqpPns5/nt4/ntpzogaHojYnojZjokazokrzol7voo4XotbDpgIHpga3pjpfpnJzpqJLlg4/lopfmho7oh5PolLXotIjpgKDkv4PlgbTliYfljbPmga/mjYnmnZ/muKzotrPpgJ/kv5flsZ7os4rml4/ntprljZLoopblhbbmj4PlrZjlravlsIrmkI3mnZHpgZzku5blpJrlpKrmsbDoqZHllL7loJXlpqXmg7DmiZPmn4HoiLXmpZXpmYDpp4TpqKjkvZPloIblr77ogJDlsrHluK/lvoXmgKDmhYvmiLTmm7/ms7Dmu57og47ohb/oi5TooovosrjpgIDpgK7pmorpu5vpr5vku6Plj7DlpKfnrKzpho3poYzpt7nmu53ngKfljZPllYTlroXmiZjmip7mi5PmsqLmv6/nkKLoqJfpkLjmv4Hoq77ojLjlh6fom7jlj6onXSxcbiAgWzB4OTI0MCwgJ+WPqeS9humBlOi+sOWlquiEseW3veerqui+v+ajmuiwt+eLuOmxiOaoveiqsOS4ueWNmOWYhuWdpuaLheaOouaXpuatjua3oea5m+eCreefreerr+euque2u+iAveiDhuibi+iqlemNm+Wbo+Wjh+W8vuaWreaaluaqgOauteeUt+irh+WApOefpeWcsOW8m+aBpeaZuuaxoOeXtOeomue9ruiHtOicmOmBhemms+evieeVnOerueetkeiThCddLFxuICBbMHg5MjgwLCAn6YCQ56ep56qS6Iy25auh552A5Lit5Luy5a6Z5b+g5oq95pi85p+x5rOo6Jmr6KG36Ki76YWO6Yuz6aeQ5qiX54Cm54yq6Iun6JGX6LKv5LiB5YWG5YeL5ZaL5a+15biW5biz5bqB5byU5by15b2r5b605oey5oyR5pqi5pyd5r2u54mS55S655y66IG06IS56IW46J226Kq/6Kuc6LaF6Lez6Yqa6ZW36aCC6bOl5YuF5o2X55u05pyV5rKI54+N6LOD6Y6u6Zmz5rSl5aKc5qSO5qeM6L+96Y6a55eb6YCa5aGa5qCC5o605qe75L2D5rys5p+Y6L676JSm57a06Y2U5qS/5r2w5Z2q5aO35ays57Ss54iq5ZCK6Yej6ba05Lqt5L2O5YGc5YG15YmD6LKe5ZGI5aCk5a6a5bid5bqV5bqt5bu35byf5oKM5oq15oy65o+Q5qKv5rGA56KH56aO56iL57eg6ImH6KiC6Kum6LmE6YCTJ10sXG4gIFsweDkzNDAsICfpgrjphK3ph5jpvI7ms6XmkZjmk6LmlbXmu7TnmoTnrJvpganpj5Hmurrlk7LlvrnmkqTovY3ov63piYTlhbjloavlpKnlsZXlupfmt7vnuo/nlJzosrzou6LpoZvngrnkvJ3mrr/mvrHnlLDpm7vlhY7lkJDloLXloZflpqzlsaDlvpLmlpfmnZzmuKHnmbvoj5/os63pgJTpg73pjY3noKXnoLrliqrluqblnJ/lpbTmgJLlgJLlhZrlhqwnXSxcbiAgWzB4OTM4MCwgJ+WHjeWIgOWUkOWhlOWhmOWll+WuleWztuW2i+aCvOaKleaQreadseahg+aivOajn+ebl+a3mOa5r+a2m+eBr+eHiOW9k+eXmOelt+etieetlOetkuezlue1seWIsOiRo+iVqeiXpOiojuishOixhui4j+mAg+mAj+mQmemZtumgremosOmXmOWDjeWLleWQjOWgguWwjuaGp+aSnua0nuees+erpeiDtOiQhOmBk+mKheWzoOm0h+WMv+W+l+W+s+a2nOeJueedo+emv+evpOavkueLrOiqreagg+apoeWHuOeqgeaktOWxiumztuiLq+WvhemFieeAnuWZuOWxr+aDh+aVpuayjOixmumBgemgk+WRkeabh+mIjeWliOmCo+WGheS5jeWHquiWmeisjueBmOaNuumNi+aloummtOe4hOeVt+WNl+aloOi7n+mbo+axneS6jOWwvOW8kOi/qeWMguizkeiCieiZueW7v+aXpeS5s+WFpSddLFxuICBbMHg5NDQwLCAn5aaC5bC/6Z+u5Lu75aaK5b+N6KqN5r+h56aw56Wi5a+n6JGx54yr54ax5bm05b+15o275pKa54eD57KY5LmD5bu85LmL5Z+c5Zqi5oKp5r+D57SN6IO96ISz6Ia/6L6y6KaX6Jqk5be05oqK5pKt6KaH5p235rOi5rS+55C256C05amG57216Iqt6aas5L+z5buD5oud5o6S5pWX5p2v55uD54mM6IOM6IK66Lyp6YWN5YCN5Z+55aqS5qKFJ10sXG4gIFsweDk0ODAsICfmpbPnhaTni73osrflo7Los6DpmarpgJnonb/np6Tnn6fokKnkvK/liaXljZrmi43mn4/ms4rnmb3nrpTnspXoiLboloTov6vmm53mvKDniIbnuJvojqvpp4Hpuqblh73nrrHnobLnrrjogofnrYjmq6jluaHogoznlZHnlaDlhavpiaLmuoznmbrphpfpq6rkvJDnvbDmipznrY/plqXps6nlmbrloZnom6TpmrzkvLTliKTljYrlj43lj5vluIbmkKzmlpHmnb/msL7msY7niYjniq/nj63nlZTnuYHoiKzol6nosqnnr4Tph4bnhanpoJLpo6/mjL3mmannlarnm6Tno5DolYPom67ljKrljZHlkKblpoPluoflvbzmgrLmiYnmibnmiqvmlpDmr5Tms4znlrLnmq7nopHnp5jnt4vnvbfogqXooqvoqrnosrvpgb/pnZ7po5vmqIvnsLjlgpnlsL7lvq7mnofmr5jnkLXnnInnvo4nXSxcbiAgWzB4OTU0MCwgJ+m8u+afiueol+WMueeWi+mrreW9puiGneiPseiCmOW8vOW/heeVouethumAvOahp+Wnq+Wqm+e0kOeZvuisrOS/teW9quaomeawt+a8gueTouelqOihqOipleixueW7n+aPj+eXheenkuiLl+mMqOmLsuiSnOibremwreWTgeW9rOaWjOa1nOeAleiyp+izk+mgu+aVj+eTtuS4jeS7mOWfoOWkq+WppuWvjOWGqOW4g+W6nOaAluaJtuaVtyddLFxuICBbMHg5NTgwLCAn5pan5pmu5rWu54i256ym6IWQ6Iaa6IqZ6K2c6LKg6LOm6LW06Zic6ZmE5L6u5pKr5q2m6Iie6JGh6JWq6YOo5bCB5qWT6aKo6JG66JWX5LyP5Ymv5b6p5bmF5pyN56aP6IW56KSH6KaG5re15byX5omV5rK45LuP54mp6a6S5YiG5ZC75Zm05aKz5oak5omu54Sa5aWu57KJ57Oe57Sb6Zuw5paH6IGe5LiZ5L215YW15aGA5bmj5bmz5byK5p+E5Lim6JS96ZaJ6Zmb57Gz6aCB5YO75aOB55mW56Kn5Yil556l6JSR566G5YGP5aSJ54mH56+H57eo6L666L+U6YGN5L6/5YuJ5aip5byB6Z6t5L+d6IiX6Yuq5ZyD5o2V5q2p55Sr6KOc6LyU56mC5Yuf5aKT5oWV5oiK5pqu5q+N57C/6I+p5YCj5L+45YyF5ZGG5aCx5aWJ5a6d5bOw5bOv5bSp5bqW5oqx5o2n5pS+5pa55pyLJ10sXG4gIFsweDk2NDAsICfms5Xms6Hng7nnoLLnuKvog57oirPokIzok6zonILopJLoqKrosYrpgqbpi5Lpo73ps7PptazkuY/kuqHlgo3liZblnYrlpqjluL3lv5jlv5nmiL/mmrTmnJvmn5Dmo5LlhpLntKHogqrohqjorIDosozosr/pib7pmLLlkKDpoKzljJflg5XljZzloqjmkrLmnLTniafnnabnqYbph6bli4PmsqHmrobloIDluYzlpZTmnKznv7vlh6Hnm4YnXSxcbiAgWzB4OTY4MCwgJ+aRqeejqOmtlOm6u+Wfi+WmueaYp+aemuavjuWTqeanmeW5leiGnOaelemuquafvumxkuahneS6puS/o+WPiOaKueacq+ayq+i/hOS+ree5rem6v+S4h+aFoua6gOa8q+iUk+WRs+acqumtheW3s+euleWyrOWvhuicnOa5iuiTkeeolOiEiOWmmeeyjeawkeecoOWLmeWkoueEoeeJn+efm+mcp+m1oeaki+Wpv+WomOWGpeWQjeWRveaYjuebn+i/t+mKmOmztOWnqueJnea7heWFjeajiee2v+e3rOmdoum6uuaRuOaooeiMguWmhOWtn+avm+eMm+ebsue2suiAl+iSmeWEsuacqOm7meebruadouWLv+mkheWwpOaIu+exvuiysOWVj+aCtue0i+mWgOWMgeS5n+WGtuWknOeIuuiAtumHjuW8peefouWOhOW9uee0hOiWrOios+i6jemdluafs+iWrumRk+aEieaEiOayueeZkiddLFxuICBbMHg5NzQwLCAn6Kut6Ly45ZSv5L2R5YSq5YuH5Y+L5a6l5bm95oKg5oaC5o+W5pyJ5p+a5rmn5raM54y254y355Sx56WQ6KOV6KqY6YGK6YKR6YO16ZuE6J6N5aSV5LqI5L2Z5LiO6KqJ6Ly/6aCQ5YKt5bm85aaW5a655bq45o+a5o+65pOB5puc5qWK5qeY5rSL5rq254aU55So56qv576K6ICA6JGJ6JOJ6KaB6Kyh6LiK6YGl6Zm96aSK5oW+5oq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KP5qKt5qKU5qKd5qKb5qKD5qqu5qK55qG05qK15qKg5qK65qSP5qKN5qG+5qSB5qOK5qSI5qOY5qSi5qSm5qOh5qSM5qON5qOU5qOn5qOV5qS25qSS5qSE5qOX5qOj5qSl5qO55qOg5qOv5qSo5qSq5qSa5qSj5qSh5qOG5qW55qW35qWc5qW45qWr5qWU5qW+5qWu5qS55qW05qS95qWZ5qSw5qWh5qWe5qWd5qaB5qWq5qay5qau5qeQ5qa/5qeB5qeT5qa+5qeO5a+o5qeK5qed5qa75qeD5qan5qiu5qaR5qag5qac5qaV5qa05qee5qeo5qiC5qib5qe/5qyK5qe55qey5qen5qiF5qax5qie5qet5qiU5qer5qiK5qiS5quB5qij5qiT5qmE5qiM5qmy5qi25qm45qmH5qmi5qmZ5qmm5qmI5qi45qii5qqQ5qqN5qqg5qqE5qqi5qqjJ10sXG4gIFsweDlmNDAsICfmqpfomJfmqrvmq4Pmq4LmqrjmqrPmqqzmq57mq5Hmq5/mqqrmq5rmq6rmq7vmrIXomJbmq7rmrJLmrJbprLHmrJ/mrLjmrLfnm5zmrLnpo67mrYfmrYPmrYnmrZDmrZnmrZTmrZvmrZ/mraHmrbjmrbnmrb/mroDmroTmroPmro3mrpjmrpXmrp7mrqTmrqrmrqvmrq/mrrLmrrHmrrPmrrfmrrzmr4bmr4vmr5Pmr5/mr6zmr6vmr7Pmr68nXSxcbiAgWzB4OWY4MCwgJ+m6vuawiOawk+awlOawm+awpOawo+axnuaxleaxouaxquayguayjeaymuaygeaym+axvuaxqOaxs+aykuaykOazhOazseazk+ayveazl+azheazneayruayseayvuayuuazm+azr+azmeazqua0n+ihjea0tua0q+a0vea0uOa0mea0tea0s+a0kua0jOa1o+a2k+a1pOa1mua1uea1mea2jua2lea/pOa2hea3uea4lea4iua2tea3h+a3pua2uOa3hua3rOa3nua3jOa3qOa3kua3hea3uua3mea3pOa3lea3qua3rua4rea5rua4rua4mea5sua5n+a4vua4o+a5q+a4q+a5tua5jea4n+a5g+a4uua5jua4pOa7v+a4nea4uOa6gua6qua6mOa7iea6t+a7k+a6vea6r+a7hOa6sua7lOa7lea6j+a6pea7gua6n+a9gea8keeBjOa7rOa7uOa7vua8v+a7sua8sea7r+a8sua7jCddLFxuICBbMHhlMDQwLCAn5ry+5ryT5ru35r6G5r265r245r6B5r6A5r2v5r2b5r+z5r2t5r6C5r285r2Y5r6O5r6R5r+C5r2m5r6z5r6j5r6h5r6k5r655r+G5r6q5r+f5r+V5r+s5r+U5r+Y5r+x5r+u5r+b54CJ54CL5r+654CR54CB54CP5r++54Cb54Ca5r2054Cd54CY54Cf54Cw54C+54Cy54GR54Gj54KZ54KS54Kv54Ox54Ks54K454Kz54Ku54Of54OL54OdJ10sXG4gIFsweGUwODAsICfng5nnhInng73nhJznhJnnhaXnhZXnhojnhabnhaLnhYznhZbnhaznho/nh7vnhoTnhpXnhqjnhqznh5fnhrnnhr7nh5Lnh4nnh5Tnh47nh6Dnh6znh6fnh7Xnh7znh7nnh7/niI3niJDniJvniKjniK3niKzniLDniLLniLvniLzniL/niYDniYbniYvniZjnibTnib7nioLnioHniofnipLnipbniqLniqfnirnnirLni4Pni4bni4Tni47ni5Lni6Lni6Dni6Hni7nni7flgI/njJfnjIrnjJznjJbnjJ3njLTnjK/njKnnjKXnjL7njY7njY/pu5jnjZfnjarnjajnjbDnjbjnjbXnjbvnjbrnj4jnjrPnj47njrvnj4Dnj6Xnj67nj57nkqLnkIXnka/nkKXnj7jnkLLnkLrnkZXnkL/nkZ/nkZnnkYHnkZznkannkbDnkaPnkarnkbbnkb7nkovnkp7nkqfnk4rnk4/nk5Tnj7EnXSxcbiAgWzB4ZTE0MCwgJ+eToOeTo+eTp+eTqeeTrueTsueTsOeTseeTuOeTt+eUhOeUg+eUheeUjOeUjueUjeeUleeUk+eUnueUpueUrOeUvOeVhOeVjeeViueVieeVm+eVhueVmueVqeeVpOeVp+eVq+eVreeVuOeVtueWhueWh+eVtOeWiueWieeWgueWlOeWmueWneeWpeeWo+eXgueWs+eXg+eWteeWveeWuOeWvOeWseeXjeeXiueXkueXmeeXo+eXnueXvueXvyddLFxuICBbMHhlMTgwLCAn55e855iB55ew55e655ey55ez55iL55iN55iJ55if55in55ig55ih55ii55ik55i055iw55i755mH55mI55mG55mc55mY55mh55mi55mo55mp55mq55mn55ms55mw55my55m255m455m855qA55qD55qI55qL55qO55qW55qT55qZ55qa55qw55q055q455q555q655uC55uN55uW55uS55ue55uh55ul55un55uq6Jiv55u755yI55yH55yE55yp55yk55ye55yl55ym55yb55y355y4552H552a552o552r552b552l552/552+5525556O556L556R556g556e556w55625565556/55685569556755+H55+N55+X55+a55+c55+j55+u55+856CM56CS56Sm56Cg56Sq56GF56KO56G056KG56G856Ka56KM56Kj56K156Kq56Kv56OR56OG56OL56OU56K+56K856OF56OK56OsJ10sXG4gIFsweGUyNDAsICfno6fno5rno73no7TnpIfnpJLnpJHnpJnnpKznpKvnpYDnpaDnpZfnpZ/npZrnpZXnpZPnpbrnpb/npornpp3npqfpvYvnpqrnpq7nprPnprnnprrnp4nnp5Xnp6fnp6znp6Hnp6PnqIjnqI3nqJjnqJnnqKDnqJ/npoDnqLHnqLvnqL7nqLfnqYPnqZfnqYnnqaHnqaLnqanpvp3nqbDnqbnnqb3nqojnqpfnqpXnqpjnqpbnqqnnq4jnqrAnXSxcbiAgWzB4ZTI4MCwgJ+eqtuerheerhOeqv+mCg+erh+eriuerjeerj+erleerk+ermeermuerneeroeerouerpuerreersOesguesj+esiueshuess+esmOesmeesnuesteesqOestuetkOetuueshOetjeesi+etjOetheetteetpeettOetp+etsOetseetrOetrueuneeumOeun+eujeeunOeumueui+eukueuj+etneeumeevi+evgeevjOevj+eutOevhuevneevqeewkeewlOevpuevpeexoOewgOewh+ewk+evs+evt+ewl+ewjeevtuewo+ewp+ewquewn+ewt+ewq+ewveexjOexg+exlOexj+exgOexkOexmOexn+expOexluexpeexrOexteeyg+eykOeypOeyreeyoueyq+eyoeeyqOeys+eysueyseeyrueyueeyveezgOezheezguezmOezkueznOezoumsu+ezr+ezsueztOeztuezuue0hiddLFxuICBbMHhlMzQwLCAn57SC57Sc57SV57SK57WF57WL57Su57Sy57S/57S157WG57Wz57WW57WO57Wy57Wo57Wu57WP57Wj57aT57aJ57Wb57aP57W957ab57a657au57aj57a157eH57a957ar57i957ai57av57ec57a457af57aw57eY57ed57ek57ee57e757ey57eh57iF57iK57ij57ih57iS57ix57if57iJ57iL57ii57mG57mm57i757i157i557mD57i3J10sXG4gIFsweGUzODAsICfnuLLnuLrnuafnuZ3nuZbnuZ7nuZnnuZrnubnnuarnuannubznubvnuoPnt5Xnub3ovq7nub/nuojnuonnuoznupLnupDnupPnupTnupbnuo7nupvnupznvLjnvLrnvYXnvYznvY3nvY7nvZDnvZHnvZXnvZTnvZjnvZ/nvaDnvajnvannvafnvbjnvoLnvobnvoPnvojnvofnvoznvpTnvp7nvp3nvprnvqPnvq/nvrLnvrnnvq7nvrbnvrjorbHnv4Xnv4bnv4rnv5Xnv5Tnv6Hnv6bnv6nnv7Pnv7npo5zogIbogITogIvogJLogJjogJnogJzogKHogKjogL/ogLvogYrogYbogZLogZjogZrogZ/ogaLogajogbPogbLogbDogbbogbnogb3ogb/ogoTogobogoXogpvogpPogprogq3lhpDogqzog5vog6Xog5nog53og4Tog5rog5bohInog6/og7HohJvohKnohKPohK/ohYsnXSxcbiAgWzB4ZTQ0MCwgJ+mai+iFhuiEvuiFk+iFkeiDvOiFseiFruiFpeiFpuiFtOiGg+iGiOiGiuiGgOiGguiGoOiGleiGpOiGo+iFn+iGk+iGqeiGsOiGteiGvuiGuOiGveiHgOiHguiGuuiHieiHjeiHkeiHmeiHmOiHiOiHmuiHn+iHoOiHp+iHuuiHu+iHvuiIgeiIguiIheiIh+iIiuiIjeiIkOiIluiIqeiIq+iIuOiIs+iJgOiJmeiJmOiJneiJmuiJn+iJpCddLFxuICBbMHhlNDgwLCAn6Imi6Imo6Imq6Imr6Iiu6Imx6Im36Im46Im+6IqN6IqS6Iqr6Iqf6Iq76Iqs6Iuh6Iuj6Iuf6IuS6Iu06Iuz6Iu66I6T6IyD6Iu76Iu56Iue6IyG6Iuc6IyJ6IuZ6Iy16Iy06IyW6Iyy6Iyx6I2A6Iy56I2Q6I2F6Iyv6Iyr6IyX6IyY6I6F6I6a6I6q6I6f6I6i6I6W6Iyj6I6O6I6H6I6K6I286I616I2z6I216I6g6I6J6I6o6I+06JCT6I+r6I+O6I+96JCD6I+Y6JCL6I+B6I+36JCH6I+g6I+y6JCN6JCi6JCg6I696JC46JSG6I+76JGt6JCq6JC86JWa6JKE6JG36JGr6JKt6JGu6JKC6JGp6JGG6JCs6JGv6JG56JC16JOK6JGi6JK56JK/6JKf6JOZ6JON6JK76JOa6JOQ6JOB6JOG6JOW6JKh6JSh6JO/6JO06JSX6JSY6JSs6JSf6JSV6JSU6JO86JWA6JWj6JWY6JWIJ10sXG4gIFsweGU1NDAsICfolYHomILolYvolZXoloDolqTolojolpHolorolqjola3olpTolpvol6rolofolpzolbfolb7olpDol4nolrrol4/olrnol5Dol5Xol53ol6Xol5zol7nomIromJPomIvol77ol7romIbomKLomJromLDomL/omY3kuZXomZTomZ/omafombHompPomqPomqnomqromovomozomrbomq/om4Tom4bomrDom4nooKPomqvom5Tom57om6nom6wnXSxcbiAgWzB4ZTU4MCwgJ+ibn+ibm+ibr+ickuichuiciOicgOicg+ibu+ickeicieicjeibueiciuictOicv+ict+icu+icpeicqeicmuidoOidn+iduOidjOidjuidtOidl+idqOidruidmeidk+ido+idquigheieouien+ieguier+ifi+ieveifgOifkOmbluieq+ifhOies+ifh+ifhuieu+ifr+ifsuifoOigj+igjeifvuiftuift+igjuifkuigkeigluigleigouigoeigseigtuigueigp+igu+ihhOihguihkuihmeihnuihouihq+iigeihvuiinuihteihveiiteihsuiiguiil+iikuiiruiimeiiouiijeiipOiisOiiv+iiseijg+ijhOijlOijmOijmeijneijueikguijvOijtOijqOijsuikhOikjOikiuikk+ilg+iknuikpeikquikq+ilgeilhOiku+iktuikuOiljOikneiloOilniddLFxuICBbMHhlNjQwLCAn6KWm6KWk6KWt6KWq6KWv6KW06KW36KW+6KaD6KaI6KaK6KaT6KaY6Kah6Kap6Kam6Kas6Kav6Kay6Ka66Ka96Ka/6KeA6Kea6Kec6Ked6Ken6Ke06Ke46KiD6KiW6KiQ6KiM6Kib6Kid6Kil6Ki26KmB6Kmb6KmS6KmG6KmI6Km86Kmt6Kms6Kmi6KqF6KqC6KqE6Kqo6Kqh6KqR6Kql6Kqm6Kqa6Kqj6KuE6KuN6KuC6Kua6Kur6Kuz6KunJ10sXG4gIFsweGU2ODAsICfoq6Toq7HorJToq6Doq6Loq7foq57oq5vorIzorIforJroq6HorJborJDorJforKDorLPpnqvorKborKvorL7orKjorYHorYzorY/orY7orYnorZborZvorZroravorZ/orazora/orbTorb3oroDorozoro7orpLorpPorpborpnorprosLrosYHosL/osYjosYzosY7osZDosZXosaLosazosbjosbrosoLosonosoXosoroso3oso7ospTosbzospjmiJ3osq3osqrosr3osrLosrPosq7osrbos4jos4Hos6Tos6Pos5ros73os7ros7votITotIXotIrotIfotI/otI3otJDpvY7otJPos43otJTotJbotafota3otbHotbPotoHotpnot4Lotr7otrrot4/ot5rot5bot4zot5vot4vot6rot6vot5/ot6Pot7zouIjouInot7/ouJ3ouJ7ouJDouJ/ouYLouLXouLDouLTouYonXSxcbiAgWzB4ZTc0MCwgJ+i5h+i5iei5jOi5kOi5iOi5mei5pOi5oOi4qui5o+i5lei5tui5sui5vOi6gei6h+i6hei6hOi6i+i6iui6k+i6kei6lOi6mei6qui6oei6rOi6sOi7hui6sei6vui7hei7iOi7i+i7m+i7o+i7vOi7u+i7q+i7vui8iui8hei8lei8kui8mei8k+i8nOi8n+i8m+i8jOi8pui8s+i8u+i8uei9hei9gui8vui9jOi9iei9hui9jui9l+i9nCddLFxuICBbMHhlNzgwLCAn6L2i6L2j6L2k6L6c6L6f6L6j6L6t6L6v6L636L+a6L+l6L+i6L+q6L+v6YKH6L+06YCF6L+56L+66YCR6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o+mes+metOmfg+mfhumfiOmfi+mfnOmfrem9j+mfsuern+mftumftemgj+mgjOmguOmgpOmgoemgt+mgvemhhumhj+mhi+mhq+mhr+mhsCddLFxuICBbMHhlOTQwLCAn6aGx6aG06aGz6aKq6aKv6aKx6aK26aOE6aOD6aOG6aOp6aOr6aSD6aSJ6aSS6aSU6aSY6aSh6aSd6aSe6aSk6aSg6aSs6aSu6aS96aS+6aWC6aWJ6aWF6aWQ6aWL6aWR6aWS6aWM6aWV6aaX6aaY6aal6aat6aau6aa86aef6aeb6aed6aeY6aeR6aet6aeu6aex6aey6ae76ae46aiB6aiP6aiF6aei6aiZ6air6ai36amF6amC6amA6amDJ10sXG4gIFsweGU5ODAsICfpqL7pqZXpqY3pqZvpqZfpqZ/pqaLpqaXpqaTpqanpqavpqarpqq3pqrDpqrzpq4Dpq4/pq5Hpq5Ppq5Tpq57pq5/pq6Lpq6Ppq6bpq6/pq6vpq67pq7Tpq7Hpq7fpq7vprIbprJjprJrprJ/prKLprKPprKXprKfprKjprKnprKrprK7prK/prLLprYTprYPprY/prY3prY7prZHprZjprbTprpPproPprpHprpbprpfprp/prqDprqjprrTpr4Dpr4rprrnpr4bpr4/pr5Hpr5Lpr6Ppr6Lpr6Tpr5Tpr6HpsLrpr7Lpr7Hpr7DpsJXpsJTpsInpsJPpsIzpsIbpsIjpsJLpsIrpsITpsK7psJvpsKXpsKTpsKHpsLDpsYfpsLLpsYbpsL7psZrpsaDpsafpsbbpsbjps6fps6zps7DptInptIjps6vptIPptIbptKrptKbptq/ptKPptJ/ptYTptJXptJLptYHptL/ptL7ptYbptYgnXSxcbiAgWzB4ZWE0MCwgJ+m1nem1num1pOm1kem1kOm1mem1sum2iem2h+m2q+m1r+m1uum2mum2pOm2qem2sum3hOm3gem2u+m2uOm2uum3hum3j+m3gum3mem3k+m3uOm3pum3rem3r+m3vem4mum4m+m4num5tem5uem5vem6gem6iOm6i+m6jOm6kum6lem6kem6nem6pem6qem6uOm6qum6remdoem7jOm7jum7j+m7kOm7lOm7nOm7num7nem7oOm7pem7qOm7ryddLFxuICBbMHhlYTgwLCAn6bu06bu26bu36bu56bu76bu86bu96byH6byI55q36byV6byh6bys6by+6b2K6b2S6b2U6b2j6b2f6b2g6b2h6b2m6b2n6b2s6b2q6b236b2y6b226b6V6b6c6b6g5aCv5qeH6YGZ55Gk5Yec54aZJ11cbl1cblxubW9kdWxlLmV4cG9ydHMgPSBmdW5jdGlvbiB0b1NKSVMgKHV0ZjhDaGFyKSB7XG4gIGlmICghdXRmOENoYXIgfHwgdXRmOENoYXIgPT09ICcnKSByZXR1cm5cblxuICBmb3IgKHZhciBpID0gMDsgaSA8IFNKSVNfVVRGOC5sZW5ndGg7IGkrKykge1xuICAgIHZhciBrYW5qaSA9IFNKSVNfVVRGOFtpXVsxXVxuXG4gICAgdmFyIHBvc0luZGV4ID0ga2FuamkuaW5kZXhPZih1dGY4Q2hhcilcbiAgICBpZiAocG9zSW5kZXggPj0gMCkge1xuICAgICAgcmV0dXJuIFNKSVNfVVRGOFtpXVswXSArIHBvc0luZGV4XG4gICAgfVxuICB9XG59XG4iXX0=
+!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var n;((n="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).QRCode||(n.QRCode={})).toSJIS=e()}}((function(){return function e(n,r,o){function f(i,u){if(!r[i]){if(!n[i]){var d="function"==typeof require&&require;if(!u&&d)return d(i,!0);if(t)return t(i,!0);var l=new Error("Cannot find module '"+i+"'");throw l.code="MODULE_NOT_FOUND",l}var p=r[i]={exports:{}};n[i][0].call(p.exports,(function(e){return f(n[i][1][e]||e)}),p,p.exports,e,n,r,o)}return r[i].exports}for(var t="function"==typeof require&&require,i=0;i<o.length;i++)f(o[i]);return f}({1:[function(e,n,r){var o=[[33088," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈〉《》「」『』【】+-±×"],[33152,"÷=≠<>"],[33167,"¥$¢£%#&*@§☆★"],[33190,"※〒→←↑↓〓"],[33226,"¬"],[33359,"0123456789"],[33376,"ABCDEFGHIJKLMNOPQRSTUVWXYZ"],[33409,"abcdefghijklmnopqrstuvwxyz"],[33439,"ぁあぃいぅうぇえぉおかがきぎくぐけげこごさざしじすずせぜそぞただちぢっつづてでとどなにぬねのはばぱひびぴふぶぷへべぺほぼぽまみむめもゃやゅゆょよらりるれろゎわゐゑをん"],[33600,"ァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミ"],[33664,"ムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶ"],[33695,"ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ"],[33727,"αβγδεζηθικλμνξοπρστυφχψω"],[33856,"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"],[33904,"абвгдеёжзийклмн"],[33920,"опрстуфхцчшщъыьэюя"],[34688,"〝〟"],[35136,"院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円"],[35200,"園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"],[35392,"魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫"],[35456,"橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"],[35648,"機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救"],[35712,"朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"],[35904,"掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨"],[35968,"劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"],[36160,"后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降"],[36224,"項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"],[36416,"察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止"],[36480,"死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"],[36672,"宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳"],[36736,"準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"],[36928,"拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨"],[36992,"逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"],[37184,"繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻"],[37248,"操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"],[37440,"叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄"],[37504,"逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"],[37696,"邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬"],[37760,"凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"],[37952,"如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅"],[38016,"楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"],[38208,"鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷"],[38272,"斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"],[38464,"法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆"],[38528,"摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"],[38720,"諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲"],[38784,"沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"],[38976,"蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"],[39071,"弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"],[39232,"僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭"],[39296,"凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"],[39488,"咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸"],[39552,"噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"],[39744,"奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀"],[39808,"它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"],[4e4,"廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠"],[40064,"怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"],[40256,"戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫"],[40320,"捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"],[40512,"曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎"],[40576,"梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"],[40768,"檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯"],[40832,"麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"],[57408,"漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝"],[57472,"烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"],[57664,"瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿"],[57728,"痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"],[57920,"磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰"],[57984,"窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"],[58176,"紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷"],[58240,"縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"],[58432,"隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤"],[58496,"艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"],[58688,"蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬"],[58752,"蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"],[58944,"襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧"],[59008,"諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"],[59200,"蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜"],[59264,"轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"],[59456,"錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙"],[59520,"閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"],[59712,"顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃"],[59776,"騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"],[59968,"鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯"],[60032,"黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙"]];n.exports=function(e){if(e&&""!==e)for(var n=0;n<o.length;n++){var r=o[n][1].indexOf(e);if(r>=0)return o[n][0]+r}}},{}]},{},[1])(1)}));
\ No newline at end of file
index 95f368a..3932ac3 100644 (file)
@@ -1,2 +1 @@
-!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var n;n="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,(n.QRCode||(n.QRCode={})).toSJIS=e()}}(function(){return function(){function e(n,r,o){function t(i,u){if(!r[i]){if(!n[i]){var d="function"==typeof require&&require;if(!u&&d)return d(i,!0);if(f)return f(i,!0);var l=new Error("Cannot find module '"+i+"'");throw l.code="MODULE_NOT_FOUND",l}var p=r[i]={exports:{}};n[i][0].call(p.exports,function(e){return t(n[i][1][e]||e)},p,p.exports,e,n,r,o)}return r[i].exports}for(var f="function"==typeof require&&require,i=0;i<o.length;i++)t(o[i]);return t}return e}()({1:[function(e,n,r){var o=[[33088," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈〉《》「」『』【】+-±×"],[33152,"÷=≠<>"],[33167,"¥$¢£%#&*@§☆★"],[33190,"※〒→←↑↓〓"],[33226,"¬"],[33359,"0123456789"],[33376,"ABCDEFGHIJKLMNOPQRSTUVWXYZ"],[33409,"abcdefghijklmnopqrstuvwxyz"],[33439,"ぁあぃいぅうぇえぉおかがきぎくぐけげこごさざしじすずせぜそぞただちぢっつづてでとどなにぬねのはばぱひびぴふぶぷへべぺほぼぽまみむめもゃやゅゆょよらりるれろゎわゐゑをん"],[33600,"ァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミ"],[33664,"ムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶ"],[33695,"ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ"],[33727,"αβγδεζηθικλμνξοπρστυφχψω"],[33856,"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"],[33904,"абвгдеёжзийклмн"],[33920,"опрстуфхцчшщъыьэюя"],[34688,"〝〟"],[35136,"院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円"],[35200,"園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"],[35392,"魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫"],[35456,"橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"],[35648,"機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救"],[35712,"朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"],[35904,"掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨"],[35968,"劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"],[36160,"后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降"],[36224,"項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"],[36416,"察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止"],[36480,"死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"],[36672,"宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳"],[36736,"準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"],[36928,"拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨"],[36992,"逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"],[37184,"繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻"],[37248,"操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"],[37440,"叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄"],[37504,"逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"],[37696,"邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬"],[37760,"凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"],[37952,"如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅"],[38016,"楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"],[38208,"鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷"],[38272,"斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"],[38464,"法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆"],[38528,"摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"],[38720,"諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲"],[38784,"沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"],[38976,"蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"],[39071,"弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"],[39232,"僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭"],[39296,"凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"],[39488,"咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸"],[39552,"噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"],[39744,"奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀"],[39808,"它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"],[4e4,"廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠"],[40064,"怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"],[40256,"戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫"],[40320,"捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"],[40512,"曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎"],[40576,"梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"],[40768,"檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯"],[40832,"麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"],[57408,"漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝"],[57472,"烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"],[57664,"瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿"],[57728,"痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"],[57920,"磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰"],[57984,"窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"],[58176,"紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷"],[58240,"縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"],[58432,"隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤"],[58496,"艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"],[58688,"蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬"],[58752,"蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"],[58944,"襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧"],[59008,"諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"],[59200,"蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜"],[59264,"轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"],[59456,"錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙"],[59520,"閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"],[59712,"顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃"],[59776,"騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"],[59968,"鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯"],[60032,"黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙"]];n.exports=function(e){if(e&&""!==e)for(var n=0;n<o.length;n++){var r=o[n][1],t=r.indexOf(e);if(t>=0)return o[n][0]+t}}},{}]},{},[1])(1)});
-//# sourceMappingURL=qrcode.tosjis.min.js.map
+!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var n;((n="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).QRCode||(n.QRCode={})).toSJIS=e()}}((function(){return function e(n,r,o){function f(i,u){if(!r[i]){if(!n[i]){var d="function"==typeof require&&require;if(!u&&d)return d(i,!0);if(t)return t(i,!0);var l=new Error("Cannot find module '"+i+"'");throw l.code="MODULE_NOT_FOUND",l}var p=r[i]={exports:{}};n[i][0].call(p.exports,(function(e){return f(n[i][1][e]||e)}),p,p.exports,e,n,r,o)}return r[i].exports}for(var t="function"==typeof require&&require,i=0;i<o.length;i++)f(o[i]);return f}({1:[function(e,n,r){var o=[[33088," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈〉《》「」『』【】+-±×"],[33152,"÷=≠<>"],[33167,"¥$¢£%#&*@§☆★"],[33190,"※〒→←↑↓〓"],[33226,"¬"],[33359,"0123456789"],[33376,"ABCDEFGHIJKLMNOPQRSTUVWXYZ"],[33409,"abcdefghijklmnopqrstuvwxyz"],[33439,"ぁあぃいぅうぇえぉおかがきぎくぐけげこごさざしじすずせぜそぞただちぢっつづてでとどなにぬねのはばぱひびぴふぶぷへべぺほぼぽまみむめもゃやゅゆょよらりるれろゎわゐゑをん"],[33600,"ァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミ"],[33664,"ムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶ"],[33695,"ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ"],[33727,"αβγδεζηθικλμνξοπρστυφχψω"],[33856,"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"],[33904,"абвгдеёжзийклмн"],[33920,"опрстуфхцчшщъыьэюя"],[34688,"〝〟"],[35136,"院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円"],[35200,"園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"],[35392,"魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫"],[35456,"橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"],[35648,"機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救"],[35712,"朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"],[35904,"掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨"],[35968,"劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"],[36160,"后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降"],[36224,"項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"],[36416,"察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止"],[36480,"死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"],[36672,"宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳"],[36736,"準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"],[36928,"拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨"],[36992,"逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"],[37184,"繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻"],[37248,"操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"],[37440,"叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄"],[37504,"逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"],[37696,"邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬"],[37760,"凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"],[37952,"如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅"],[38016,"楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"],[38208,"鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷"],[38272,"斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"],[38464,"法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆"],[38528,"摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"],[38720,"諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲"],[38784,"沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"],[38976,"蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"],[39071,"弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"],[39232,"僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭"],[39296,"凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"],[39488,"咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸"],[39552,"噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"],[39744,"奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀"],[39808,"它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"],[4e4,"廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠"],[40064,"怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"],[40256,"戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫"],[40320,"捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"],[40512,"曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎"],[40576,"梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"],[40768,"檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯"],[40832,"麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"],[57408,"漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝"],[57472,"烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"],[57664,"瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿"],[57728,"痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"],[57920,"磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰"],[57984,"窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"],[58176,"紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷"],[58240,"縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"],[58432,"隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤"],[58496,"艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"],[58688,"蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬"],[58752,"蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"],[58944,"襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧"],[59008,"諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"],[59200,"蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜"],[59264,"轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"],[59456,"錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙"],[59520,"閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"],[59712,"顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃"],[59776,"騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"],[59968,"鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯"],[60032,"黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙"]];n.exports=function(e){if(e&&""!==e)for(var n=0;n<o.length;n++){var r=o[n][1].indexOf(e);if(r>=0)return o[n][0]+r}}},{}]},{},[1])(1)}));
\ No newline at end of file
index 9f44d3e..187ac12 100644 (file)
@@ -1,100 +1 @@
-var SJIS_UTF8 = [
-  [0x8140, ' 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈〉《》「」『』【】+-±×'],
-  [0x8180, '÷=≠<>'],
-  [0x818f, '¥$¢£%#&*@§☆★'],
-  [0x81a6, '※〒→←↑↓〓'],
-  [0x81ca, '¬'],
-  [0x824f, '0123456789'],
-  [0x8260, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'],
-  [0x8281, 'abcdefghijklmnopqrstuvwxyz'],
-  [0x829f, 'ぁあぃいぅうぇえぉおかがきぎくぐけげこごさざしじすずせぜそぞただちぢっつづてでとどなにぬねのはばぱひびぴふぶぷへべぺほぼぽまみむめもゃやゅゆょよらりるれろゎわゐゑをん'],
-  [0x8340, 'ァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミ'],
-  [0x8380, 'ムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶ'],
-  [0x839f, 'ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ'],
-  [0x83bf, 'αβγδεζηθικλμνξοπρστυφχψω'],
-  [0x8440, 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ'],
-  [0x8470, 'абвгдеёжзийклмн'],
-  [0x8480, 'опрстуфхцчшщъыьэюя'],
-  [0x8780, '〝〟'],
-  [0x8940, '院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円'],
-  [0x8980, '園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改'],
-  [0x8a40, '魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫'],
-  [0x8a80, '橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄'],
-  [0x8b40, '機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救'],
-  [0x8b80, '朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈'],
-  [0x8c40, '掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨'],
-  [0x8c80, '劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向'],
-  [0x8d40, '后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降'],
-  [0x8d80, '項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷'],
-  [0x8e40, '察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止'],
-  [0x8e80, '死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周'],
-  [0x8f40, '宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳'],
-  [0x8f80, '準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾'],
-  [0x9040, '拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨'],
-  [0x9080, '逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線'],
-  [0x9140, '繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻'],
-  [0x9180, '操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只'],
-  [0x9240, '叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄'],
-  [0x9280, '逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓'],
-  [0x9340, '邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬'],
-  [0x9380, '凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入'],
-  [0x9440, '如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅'],
-  [0x9480, '楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美'],
-  [0x9540, '鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷'],
-  [0x9580, '斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋'],
-  [0x9640, '法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆'],
-  [0x9680, '摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒'],
-  [0x9740, '諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲'],
-  [0x9780, '沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯'],
-  [0x9840, '蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕'],
-  [0x989f, '弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲'],
-  [0x9940, '僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭'],
-  [0x9980, '凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨'],
-  [0x9a40, '咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸'],
-  [0x9a80, '噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩'],
-  [0x9b40, '奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀'],
-  [0x9b80, '它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏'],
-  [0x9c40, '廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠'],
-  [0x9c80, '怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛'],
-  [0x9d40, '戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫'],
-  [0x9d80, '捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼'],
-  [0x9e40, '曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎'],
-  [0x9e80, '梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣'],
-  [0x9f40, '檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯'],
-  [0x9f80, '麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌'],
-  [0xe040, '漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝'],
-  [0xe080, '烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱'],
-  [0xe140, '瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿'],
-  [0xe180, '痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬'],
-  [0xe240, '磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰'],
-  [0xe280, '窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆'],
-  [0xe340, '紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷'],
-  [0xe380, '縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋'],
-  [0xe440, '隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤'],
-  [0xe480, '艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈'],
-  [0xe540, '蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬'],
-  [0xe580, '蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞'],
-  [0xe640, '襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧'],
-  [0xe680, '諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊'],
-  [0xe740, '蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜'],
-  [0xe780, '轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮'],
-  [0xe840, '錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙'],
-  [0xe880, '閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰'],
-  [0xe940, '顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃'],
-  [0xe980, '騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈'],
-  [0xea40, '鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯'],
-  [0xea80, '黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙']
-]
-
-module.exports = function toSJIS (utf8Char) {
-  if (!utf8Char || utf8Char === '') return
-
-  for (var i = 0; i < SJIS_UTF8.length; i++) {
-    var kanji = SJIS_UTF8[i][1]
-
-    var posIndex = kanji.indexOf(utf8Char)
-    if (posIndex >= 0) {
-      return SJIS_UTF8[i][0] + posIndex
-    }
-  }
-}
+var SJIS_UTF8=[[33088," 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈〉《》「」『』【】+-±×"],[33152,"÷=≠<>"],[33167,"¥$¢£%#&*@§☆★"],[33190,"※〒→←↑↓〓"],[33226,"¬"],[33359,"0123456789"],[33376,"ABCDEFGHIJKLMNOPQRSTUVWXYZ"],[33409,"abcdefghijklmnopqrstuvwxyz"],[33439,"ぁあぃいぅうぇえぉおかがきぎくぐけげこごさざしじすずせぜそぞただちぢっつづてでとどなにぬねのはばぱひびぴふぶぷへべぺほぼぽまみむめもゃやゅゆょよらりるれろゎわゐゑをん"],[33600,"ァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミ"],[33664,"ムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶ"],[33695,"ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ"],[33727,"αβγδεζηθικλμνξοπρστυφχψω"],[33856,"АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ"],[33904,"абвгдеёжзийклмн"],[33920,"опрстуфхцчшщъыьэюя"],[34688,"〝〟"],[35136,"院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円"],[35200,"園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改"],[35392,"魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫"],[35456,"橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄"],[35648,"機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救"],[35712,"朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈"],[35904,"掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨"],[35968,"劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向"],[36160,"后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降"],[36224,"項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷"],[36416,"察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止"],[36480,"死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周"],[36672,"宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳"],[36736,"準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾"],[36928,"拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨"],[36992,"逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線"],[37184,"繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻"],[37248,"操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只"],[37440,"叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄"],[37504,"逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓"],[37696,"邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬"],[37760,"凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入"],[37952,"如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅"],[38016,"楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美"],[38208,"鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷"],[38272,"斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋"],[38464,"法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆"],[38528,"摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒"],[38720,"諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲"],[38784,"沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯"],[38976,"蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕"],[39071,"弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲"],[39232,"僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭"],[39296,"凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨"],[39488,"咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸"],[39552,"噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩"],[39744,"奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀"],[39808,"它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏"],[4e4,"廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠"],[40064,"怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛"],[40256,"戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫"],[40320,"捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼"],[40512,"曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎"],[40576,"梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣"],[40768,"檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯"],[40832,"麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌"],[57408,"漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝"],[57472,"烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱"],[57664,"瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿"],[57728,"痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬"],[57920,"磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰"],[57984,"窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆"],[58176,"紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷"],[58240,"縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋"],[58432,"隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤"],[58496,"艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈"],[58688,"蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬"],[58752,"蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞"],[58944,"襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧"],[59008,"諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊"],[59200,"蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜"],[59264,"轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮"],[59456,"錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙"],[59520,"閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰"],[59712,"顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃"],[59776,"騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈"],[59968,"鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯"],[60032,"黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙"]];module.exports=function(S){if(S&&""!==S)for(var r=0;r<SJIS_UTF8.length;r++){var e=SJIS_UTF8[r][1].indexOf(S);if(e>=0)return SJIS_UTF8[r][0]+e}};
\ No newline at end of file
index 194982d..8720886 100644 (file)
@@ -1,76 +1 @@
-
-var canPromise = require('./can-promise')
-
-var QRCode = require('./core/qrcode')
-var CanvasRenderer = require('./renderer/canvas')
-var SvgRenderer = require('./renderer/svg-tag.js')
-
-function renderCanvas (renderFunc, canvas, text, opts, cb) {
-  var args = [].slice.call(arguments, 1)
-  var argsNum = args.length
-  var isLastArgCb = typeof args[argsNum - 1] === 'function'
-
-  if (!isLastArgCb && !canPromise()) {
-    throw new Error('Callback required as last argument')
-  }
-
-  if (isLastArgCb) {
-    if (argsNum < 2) {
-      throw new Error('Too few arguments provided')
-    }
-
-    if (argsNum === 2) {
-      cb = text
-      text = canvas
-      canvas = opts = undefined
-    } else if (argsNum === 3) {
-      if (canvas.getContext && typeof cb === 'undefined') {
-        cb = opts
-        opts = undefined
-      } else {
-        cb = opts
-        opts = text
-        text = canvas
-        canvas = undefined
-      }
-    }
-  } else {
-    if (argsNum < 1) {
-      throw new Error('Too few arguments provided')
-    }
-
-    if (argsNum === 1) {
-      text = canvas
-      canvas = opts = undefined
-    } else if (argsNum === 2 && !canvas.getContext) {
-      opts = text
-      text = canvas
-      canvas = undefined
-    }
-
-    return new Promise(function (resolve, reject) {
-      try {
-        var data = QRCode.create(text, opts)
-        resolve(renderFunc(data, canvas, opts))
-      } catch (e) {
-        reject(e)
-      }
-    })
-  }
-
-  try {
-    var data = QRCode.create(text, opts)
-    cb(null, renderFunc(data, canvas, opts))
-  } catch (e) {
-    cb(e)
-  }
-}
-
-exports.create = QRCode.create
-exports.toCanvas = renderCanvas.bind(null, CanvasRenderer.render)
-exports.toDataURL = renderCanvas.bind(null, CanvasRenderer.renderToDataURL)
-
-// only svg for now.
-exports.toString = renderCanvas.bind(null, function (data, _, opts) {
-  return SvgRenderer.render(data, opts)
-})
+var canPromise=require("./can-promise"),QRCode=require("./core/qrcode"),CanvasRenderer=require("./renderer/canvas"),SvgRenderer=require("./renderer/svg-tag.js");function renderCanvas(e,r,n,a,o){var t=[].slice.call(arguments,1),d=t.length,i="function"==typeof t[d-1];if(!i&&!canPromise())throw new Error("Callback required as last argument");if(!i){if(d<1)throw new Error("Too few arguments provided");return 1===d?(n=r,r=a=void 0):2!==d||r.getContext||(a=n,n=r,r=void 0),new Promise((function(o,t){try{var d=QRCode.create(n,a);o(e(d,r,a))}catch(e){t(e)}}))}if(d<2)throw new Error("Too few arguments provided");2===d?(o=n,n=r,r=a=void 0):3===d&&(r.getContext&&void 0===o?(o=a,a=void 0):(o=a,a=n,n=r,r=void 0));try{var s=QRCode.create(n,a);o(null,e(s,r,a))}catch(e){o(e)}}exports.create=QRCode.create,exports.toCanvas=renderCanvas.bind(null,CanvasRenderer.render),exports.toDataURL=renderCanvas.bind(null,CanvasRenderer.renderToDataURL),exports.toString=renderCanvas.bind(null,(function(e,r,n){return SvgRenderer.render(e,n)}));
\ No newline at end of file
index 77267f1..be12739 100644 (file)
@@ -1,7 +1 @@
-// can-promise has a crash in some versions of react native that dont have
-// standard global objects
-// https://github.com/soldair/node-qrcode/issues/157
-
-module.exports = function () {
-  return typeof Promise === 'function' && Promise.prototype && Promise.prototype.then
-}
+module.exports=function(){return"function"==typeof Promise&&Promise.prototype&&Promise.prototype.then};
\ No newline at end of file
index 36f1142..d71dd59 100644 (file)
@@ -1,83 +1 @@
-/**
- * Alignment pattern are fixed reference pattern in defined positions
- * in a matrix symbology, which enables the decode software to re-synchronise
- * the coordinate mapping of the image modules in the event of moderate amounts
- * of distortion of the image.
- *
- * Alignment patterns are present only in QR Code symbols of version 2 or larger
- * and their number depends on the symbol version.
- */
-
-var getSymbolSize = require('./utils').getSymbolSize
-
-/**
- * Calculate the row/column coordinates of the center module of each alignment pattern
- * for the specified QR Code version.
- *
- * The alignment patterns are positioned symmetrically on either side of the diagonal
- * running from the top left corner of the symbol to the bottom right corner.
- *
- * Since positions are simmetrical only half of the coordinates are returned.
- * Each item of the array will represent in turn the x and y coordinate.
- * @see {@link getPositions}
- *
- * @param  {Number} version QR Code version
- * @return {Array}          Array of coordinate
- */
-exports.getRowColCoords = function getRowColCoords (version) {
-  if (version === 1) return []
-
-  var posCount = Math.floor(version / 7) + 2
-  var size = getSymbolSize(version)
-  var intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2
-  var positions = [size - 7] // Last coord is always (size - 7)
-
-  for (var i = 1; i < posCount - 1; i++) {
-    positions[i] = positions[i - 1] - intervals
-  }
-
-  positions.push(6) // First coord is always 6
-
-  return positions.reverse()
-}
-
-/**
- * Returns an array containing the positions of each alignment pattern.
- * Each array's element represent the center point of the pattern as (x, y) coordinates
- *
- * Coordinates are calculated expanding the row/column coordinates returned by {@link getRowColCoords}
- * and filtering out the items that overlaps with finder pattern
- *
- * @example
- * For a Version 7 symbol {@link getRowColCoords} returns values 6, 22 and 38.
- * The alignment patterns, therefore, are to be centered on (row, column)
- * positions (6,22), (22,6), (22,22), (22,38), (38,22), (38,38).
- * Note that the coordinates (6,6), (6,38), (38,6) are occupied by finder patterns
- * and are not therefore used for alignment patterns.
- *
- * var pos = getPositions(7)
- * // [[6,22], [22,6], [22,22], [22,38], [38,22], [38,38]]
- *
- * @param  {Number} version QR Code version
- * @return {Array}          Array of coordinates
- */
-exports.getPositions = function getPositions (version) {
-  var coords = []
-  var pos = exports.getRowColCoords(version)
-  var posLength = pos.length
-
-  for (var i = 0; i < posLength; i++) {
-    for (var j = 0; j < posLength; j++) {
-      // Skip if position is occupied by finder patterns
-      if ((i === 0 && j === 0) ||             // top-left
-          (i === 0 && j === posLength - 1) || // bottom-left
-          (i === posLength - 1 && j === 0)) { // top-right
-        continue
-      }
-
-      coords.push([pos[i], pos[j]])
-    }
-  }
-
-  return coords
-}
+var getSymbolSize=require("./utils").getSymbolSize;exports.getRowColCoords=function(o){if(1===o)return[];for(var r=Math.floor(o/7)+2,e=getSymbolSize(o),t=145===e?26:2*Math.ceil((e-13)/(2*r-2)),i=[e-7],s=1;s<r-1;s++)i[s]=i[s-1]-t;return i.push(6),i.reverse()},exports.getPositions=function(o){for(var r=[],e=exports.getRowColCoords(o),t=e.length,i=0;i<t;i++)for(var s=0;s<t;s++)0===i&&0===s||0===i&&s===t-1||i===t-1&&0===s||r.push([e[i],e[s]]);return r};
\ No newline at end of file
index 351d64a..19a9cc1 100644 (file)
@@ -1,59 +1 @@
-var Mode = require('./mode')
-
-/**
- * Array of characters available in alphanumeric mode
- *
- * As per QR Code specification, to each character
- * is assigned a value from 0 to 44 which in this case coincides
- * with the array index
- *
- * @type {Array}
- */
-var ALPHA_NUM_CHARS = [
-  '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
-  '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',
-  ' ', '$', '%', '*', '+', '-', '.', '/', ':'
-]
-
-function AlphanumericData (data) {
-  this.mode = Mode.ALPHANUMERIC
-  this.data = data
-}
-
-AlphanumericData.getBitsLength = function getBitsLength (length) {
-  return 11 * Math.floor(length / 2) + 6 * (length % 2)
-}
-
-AlphanumericData.prototype.getLength = function getLength () {
-  return this.data.length
-}
-
-AlphanumericData.prototype.getBitsLength = function getBitsLength () {
-  return AlphanumericData.getBitsLength(this.data.length)
-}
-
-AlphanumericData.prototype.write = function write (bitBuffer) {
-  var i
-
-  // Input data characters are divided into groups of two characters
-  // and encoded as 11-bit binary codes.
-  for (i = 0; i + 2 <= this.data.length; i += 2) {
-    // The character value of the first character is multiplied by 45
-    var value = ALPHA_NUM_CHARS.indexOf(this.data[i]) * 45
-
-    // The character value of the second digit is added to the product
-    value += ALPHA_NUM_CHARS.indexOf(this.data[i + 1])
-
-    // The sum is then stored as 11-bit binary number
-    bitBuffer.put(value, 11)
-  }
-
-  // If the number of input data characters is not a multiple of two,
-  // the character value of the final character is encoded as a 6-bit binary number.
-  if (this.data.length % 2) {
-    bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i]), 6)
-  }
-}
-
-module.exports = AlphanumericData
+var Mode=require("./mode"),ALPHA_NUM_CHARS=["0","1","2","3","4","5","6","7","8","9","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"," ","$","%","*","+","-",".","/",":"];function AlphanumericData(t){this.mode=Mode.ALPHANUMERIC,this.data=t}AlphanumericData.getBitsLength=function(t){return 11*Math.floor(t/2)+t%2*6},AlphanumericData.prototype.getLength=function(){return this.data.length},AlphanumericData.prototype.getBitsLength=function(){return AlphanumericData.getBitsLength(this.data.length)},AlphanumericData.prototype.write=function(t){var a;for(a=0;a+2<=this.data.length;a+=2){var e=45*ALPHA_NUM_CHARS.indexOf(this.data[a]);e+=ALPHA_NUM_CHARS.indexOf(this.data[a+1]),t.put(e,11)}this.data.length%2&&t.put(ALPHA_NUM_CHARS.indexOf(this.data[a]),6)},module.exports=AlphanumericData;
\ No newline at end of file
index cdb68de..0b05092 100644 (file)
@@ -1,37 +1 @@
-function BitBuffer () {
-  this.buffer = []
-  this.length = 0
-}
-
-BitBuffer.prototype = {
-
-  get: function (index) {
-    var bufIndex = Math.floor(index / 8)
-    return ((this.buffer[bufIndex] >>> (7 - index % 8)) & 1) === 1
-  },
-
-  put: function (num, length) {
-    for (var i = 0; i < length; i++) {
-      this.putBit(((num >>> (length - i - 1)) & 1) === 1)
-    }
-  },
-
-  getLengthInBits: function () {
-    return this.length
-  },
-
-  putBit: function (bit) {
-    var bufIndex = Math.floor(this.length / 8)
-    if (this.buffer.length <= bufIndex) {
-      this.buffer.push(0)
-    }
-
-    if (bit) {
-      this.buffer[bufIndex] |= (0x80 >>> (this.length % 8))
-    }
-
-    this.length++
-  }
-}
-
-module.exports = BitBuffer
+function BitBuffer(){this.buffer=[],this.length=0}BitBuffer.prototype={get:function(t){var f=Math.floor(t/8);return 1==(this.buffer[f]>>>7-t%8&1)},put:function(t,f){for(var e=0;e<f;e++)this.putBit(1==(t>>>f-e-1&1))},getLengthInBits:function(){return this.length},putBit:function(t){var f=Math.floor(this.length/8);this.buffer.length<=f&&this.buffer.push(0),t&&(this.buffer[f]|=128>>>this.length%8),this.length++}},module.exports=BitBuffer;
\ No newline at end of file
index 98c35e9..6daf7bb 100644 (file)
@@ -1,67 +1 @@
-var BufferUtil = require('../utils/buffer')
-
-/**
- * Helper class to handle QR Code symbol modules
- *
- * @param {Number} size Symbol size
- */
-function BitMatrix (size) {
-  if (!size || size < 1) {
-    throw new Error('BitMatrix size must be defined and greater than 0')
-  }
-
-  this.size = size
-  this.data = BufferUtil.alloc(size * size)
-  this.reservedBit = BufferUtil.alloc(size * size)
-}
-
-/**
- * Set bit value at specified location
- * If reserved flag is set, this bit will be ignored during masking process
- *
- * @param {Number}  row
- * @param {Number}  col
- * @param {Boolean} value
- * @param {Boolean} reserved
- */
-BitMatrix.prototype.set = function (row, col, value, reserved) {
-  var index = row * this.size + col
-  this.data[index] = value
-  if (reserved) this.reservedBit[index] = true
-}
-
-/**
- * Returns bit value at specified location
- *
- * @param  {Number}  row
- * @param  {Number}  col
- * @return {Boolean}
- */
-BitMatrix.prototype.get = function (row, col) {
-  return this.data[row * this.size + col]
-}
-
-/**
- * Applies xor operator at specified location
- * (used during masking process)
- *
- * @param {Number}  row
- * @param {Number}  col
- * @param {Boolean} value
- */
-BitMatrix.prototype.xor = function (row, col, value) {
-  this.data[row * this.size + col] ^= value
-}
-
-/**
- * Check if bit at specified location is reserved
- *
- * @param {Number}   row
- * @param {Number}   col
- * @return {Boolean}
- */
-BitMatrix.prototype.isReserved = function (row, col) {
-  return this.reservedBit[row * this.size + col]
-}
-
-module.exports = BitMatrix
+var BufferUtil=require("../utils/buffer");function BitMatrix(t){if(!t||t<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=t,this.data=BufferUtil.alloc(t*t),this.reservedBit=BufferUtil.alloc(t*t)}BitMatrix.prototype.set=function(t,i,e,r){var s=t*this.size+i;this.data[s]=e,r&&(this.reservedBit[s]=!0)},BitMatrix.prototype.get=function(t,i){return this.data[t*this.size+i]},BitMatrix.prototype.xor=function(t,i,e){this.data[t*this.size+i]^=e},BitMatrix.prototype.isReserved=function(t,i){return this.reservedBit[t*this.size+i]},module.exports=BitMatrix;
\ No newline at end of file
index 969990f..362dfd6 100644 (file)
@@ -1,27 +1 @@
-var BufferUtil = require('../utils/buffer')
-var Mode = require('./mode')
-
-function ByteData (data) {
-  this.mode = Mode.BYTE
-  this.data = BufferUtil.from(data)
-}
-
-ByteData.getBitsLength = function getBitsLength (length) {
-  return length * 8
-}
-
-ByteData.prototype.getLength = function getLength () {
-  return this.data.length
-}
-
-ByteData.prototype.getBitsLength = function getBitsLength () {
-  return ByteData.getBitsLength(this.data.length)
-}
-
-ByteData.prototype.write = function (bitBuffer) {
-  for (var i = 0, l = this.data.length; i < l; i++) {
-    bitBuffer.put(this.data[i], 8)
-  }
-}
-
-module.exports = ByteData
+var BufferUtil=require("../utils/buffer"),Mode=require("./mode");function ByteData(t){this.mode=Mode.BYTE,this.data=BufferUtil.from(t)}ByteData.getBitsLength=function(t){return 8*t},ByteData.prototype.getLength=function(){return this.data.length},ByteData.prototype.getBitsLength=function(){return ByteData.getBitsLength(this.data.length)},ByteData.prototype.write=function(t){for(var e=0,a=this.data.length;e<a;e++)t.put(this.data[e],8)},module.exports=ByteData;
\ No newline at end of file
index bf01725..da7e546 100755 (executable)
@@ -1,135 +1 @@
-var ECLevel = require('./error-correction-level')\r
-\r
-var EC_BLOCKS_TABLE = [\r
-// L  M  Q  H\r
-  1, 1, 1, 1,\r
-  1, 1, 1, 1,\r
-  1, 1, 2, 2,\r
-  1, 2, 2, 4,\r
-  1, 2, 4, 4,\r
-  2, 4, 4, 4,\r
-  2, 4, 6, 5,\r
-  2, 4, 6, 6,\r
-  2, 5, 8, 8,\r
-  4, 5, 8, 8,\r
-  4, 5, 8, 11,\r
-  4, 8, 10, 11,\r
-  4, 9, 12, 16,\r
-  4, 9, 16, 16,\r
-  6, 10, 12, 18,\r
-  6, 10, 17, 16,\r
-  6, 11, 16, 19,\r
-  6, 13, 18, 21,\r
-  7, 14, 21, 25,\r
-  8, 16, 20, 25,\r
-  8, 17, 23, 25,\r
-  9, 17, 23, 34,\r
-  9, 18, 25, 30,\r
-  10, 20, 27, 32,\r
-  12, 21, 29, 35,\r
-  12, 23, 34, 37,\r
-  12, 25, 34, 40,\r
-  13, 26, 35, 42,\r
-  14, 28, 38, 45,\r
-  15, 29, 40, 48,\r
-  16, 31, 43, 51,\r
-  17, 33, 45, 54,\r
-  18, 35, 48, 57,\r
-  19, 37, 51, 60,\r
-  19, 38, 53, 63,\r
-  20, 40, 56, 66,\r
-  21, 43, 59, 70,\r
-  22, 45, 62, 74,\r
-  24, 47, 65, 77,\r
-  25, 49, 68, 81\r
-]\r
-\r
-var EC_CODEWORDS_TABLE = [\r
-// L  M  Q  H\r
-  7, 10, 13, 17,\r
-  10, 16, 22, 28,\r
-  15, 26, 36, 44,\r
-  20, 36, 52, 64,\r
-  26, 48, 72, 88,\r
-  36, 64, 96, 112,\r
-  40, 72, 108, 130,\r
-  48, 88, 132, 156,\r
-  60, 110, 160, 192,\r
-  72, 130, 192, 224,\r
-  80, 150, 224, 264,\r
-  96, 176, 260, 308,\r
-  104, 198, 288, 352,\r
-  120, 216, 320, 384,\r
-  132, 240, 360, 432,\r
-  144, 280, 408, 480,\r
-  168, 308, 448, 532,\r
-  180, 338, 504, 588,\r
-  196, 364, 546, 650,\r
-  224, 416, 600, 700,\r
-  224, 442, 644, 750,\r
-  252, 476, 690, 816,\r
-  270, 504, 750, 900,\r
-  300, 560, 810, 960,\r
-  312, 588, 870, 1050,\r
-  336, 644, 952, 1110,\r
-  360, 700, 1020, 1200,\r
-  390, 728, 1050, 1260,\r
-  420, 784, 1140, 1350,\r
-  450, 812, 1200, 1440,\r
-  480, 868, 1290, 1530,\r
-  510, 924, 1350, 1620,\r
-  540, 980, 1440, 1710,\r
-  570, 1036, 1530, 1800,\r
-  570, 1064, 1590, 1890,\r
-  600, 1120, 1680, 1980,\r
-  630, 1204, 1770, 2100,\r
-  660, 1260, 1860, 2220,\r
-  720, 1316, 1950, 2310,\r
-  750, 1372, 2040, 2430\r
-]\r
-\r
-/**\r
- * Returns the number of error correction block that the QR Code should contain\r
- * for the specified version and error correction level.\r
- *\r
- * @param  {Number} version              QR Code version\r
- * @param  {Number} errorCorrectionLevel Error correction level\r
- * @return {Number}                      Number of error correction blocks\r
- */\r
-exports.getBlocksCount = function getBlocksCount (version, errorCorrectionLevel) {\r
-  switch (errorCorrectionLevel) {\r
-    case ECLevel.L:\r
-      return EC_BLOCKS_TABLE[(version - 1) * 4 + 0]\r
-    case ECLevel.M:\r
-      return EC_BLOCKS_TABLE[(version - 1) * 4 + 1]\r
-    case ECLevel.Q:\r
-      return EC_BLOCKS_TABLE[(version - 1) * 4 + 2]\r
-    case ECLevel.H:\r
-      return EC_BLOCKS_TABLE[(version - 1) * 4 + 3]\r
-    default:\r
-      return undefined\r
-  }\r
-}\r
-\r
-/**\r
- * Returns the number of error correction codewords to use for the specified\r
- * version and error correction level.\r
- *\r
- * @param  {Number} version              QR Code version\r
- * @param  {Number} errorCorrectionLevel Error correction level\r
- * @return {Number}                      Number of error correction codewords\r
- */\r
-exports.getTotalCodewordsCount = function getTotalCodewordsCount (version, errorCorrectionLevel) {\r
-  switch (errorCorrectionLevel) {\r
-    case ECLevel.L:\r
-      return EC_CODEWORDS_TABLE[(version - 1) * 4 + 0]\r
-    case ECLevel.M:\r
-      return EC_CODEWORDS_TABLE[(version - 1) * 4 + 1]\r
-    case ECLevel.Q:\r
-      return EC_CODEWORDS_TABLE[(version - 1) * 4 + 2]\r
-    case ECLevel.H:\r
-      return EC_CODEWORDS_TABLE[(version - 1) * 4 + 3]\r
-    default:\r
-      return undefined\r
-  }\r
-}\r
+var ECLevel=require("./error-correction-level"),EC_BLOCKS_TABLE=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],EC_CODEWORDS_TABLE=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];exports.getBlocksCount=function(e,E){switch(E){case ECLevel.L:return EC_BLOCKS_TABLE[4*(e-1)+0];case ECLevel.M:return EC_BLOCKS_TABLE[4*(e-1)+1];case ECLevel.Q:return EC_BLOCKS_TABLE[4*(e-1)+2];case ECLevel.H:return EC_BLOCKS_TABLE[4*(e-1)+3];default:return}},exports.getTotalCodewordsCount=function(e,E){switch(E){case ECLevel.L:return EC_CODEWORDS_TABLE[4*(e-1)+0];case ECLevel.M:return EC_CODEWORDS_TABLE[4*(e-1)+1];case ECLevel.Q:return EC_CODEWORDS_TABLE[4*(e-1)+2];case ECLevel.H:return EC_CODEWORDS_TABLE[4*(e-1)+3];default:return}};
\ No newline at end of file
index 9856f4f..974b3af 100644 (file)
@@ -1,50 +1 @@
-exports.L = { bit: 1 }
-exports.M = { bit: 0 }
-exports.Q = { bit: 3 }
-exports.H = { bit: 2 }
-
-function fromString (string) {
-  if (typeof string !== 'string') {
-    throw new Error('Param is not a string')
-  }
-
-  var lcStr = string.toLowerCase()
-
-  switch (lcStr) {
-    case 'l':
-    case 'low':
-      return exports.L
-
-    case 'm':
-    case 'medium':
-      return exports.M
-
-    case 'q':
-    case 'quartile':
-      return exports.Q
-
-    case 'h':
-    case 'high':
-      return exports.H
-
-    default:
-      throw new Error('Unknown EC Level: ' + string)
-  }
-}
-
-exports.isValid = function isValid (level) {
-  return level && typeof level.bit !== 'undefined' &&
-    level.bit >= 0 && level.bit < 4
-}
-
-exports.from = function from (value, defaultValue) {
-  if (exports.isValid(value)) {
-    return value
-  }
-
-  try {
-    return fromString(value)
-  } catch (e) {
-    return defaultValue
-  }
-}
+function fromString(r){if("string"!=typeof r)throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return exports.L;case"m":case"medium":return exports.M;case"q":case"quartile":return exports.Q;case"h":case"high":return exports.H;default:throw new Error("Unknown EC Level: "+r)}}exports.L={bit:1},exports.M={bit:0},exports.Q={bit:3},exports.H={bit:2},exports.isValid=function(r){return r&&void 0!==r.bit&&r.bit>=0&&r.bit<4},exports.from=function(r,t){if(exports.isValid(r))return r;try{return fromString(r)}catch(r){return t}};
\ No newline at end of file
index 61b2f13..56b96f4 100644 (file)
@@ -1,22 +1 @@
-var getSymbolSize = require('./utils').getSymbolSize
-var FINDER_PATTERN_SIZE = 7
-
-/**
- * Returns an array containing the positions of each finder pattern.
- * Each array's element represent the top-left point of the pattern as (x, y) coordinates
- *
- * @param  {Number} version QR Code version
- * @return {Array}          Array of coordinates
- */
-exports.getPositions = function getPositions (version) {
-  var size = getSymbolSize(version)
-
-  return [
-    // top-left
-    [0, 0],
-    // top-right
-    [size - FINDER_PATTERN_SIZE, 0],
-    // bottom-left
-    [0, size - FINDER_PATTERN_SIZE]
-  ]
-}
+var getSymbolSize=require("./utils").getSymbolSize,FINDER_PATTERN_SIZE=7;exports.getPositions=function(e){var t=getSymbolSize(e);return[[0,0],[t-FINDER_PATTERN_SIZE,0],[0,t-FINDER_PATTERN_SIZE]]};
\ No newline at end of file
index dd57cb6..7b36c37 100644 (file)
@@ -1,29 +1 @@
-var Utils = require('./utils')
-
-var G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0)
-var G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1)
-var G15_BCH = Utils.getBCHDigit(G15)
-
-/**
- * Returns format information with relative error correction bits
- *
- * The format information is a 15-bit sequence containing 5 data bits,
- * with 10 error correction bits calculated using the (15, 5) BCH code.
- *
- * @param  {Number} errorCorrectionLevel Error correction level
- * @param  {Number} mask                 Mask pattern
- * @return {Number}                      Encoded format information bits
- */
-exports.getEncodedBits = function getEncodedBits (errorCorrectionLevel, mask) {
-  var data = ((errorCorrectionLevel.bit << 3) | mask)
-  var d = data << 10
-
-  while (Utils.getBCHDigit(d) - G15_BCH >= 0) {
-    d ^= (G15 << (Utils.getBCHDigit(d) - G15_BCH))
-  }
-
-  // xor final data with mask pattern in order to ensure that
-  // no combination of Error Correction Level and data mask pattern
-  // will result in an all-zero data string
-  return ((data << 10) | d) ^ G15_MASK
-}
+var Utils=require("./utils"),G15=1335,G15_MASK=21522,G15_BCH=Utils.getBCHDigit(G15);exports.getEncodedBits=function(t,i){for(var e=t.bit<<3|i,r=e<<10;Utils.getBCHDigit(r)-G15_BCH>=0;)r^=G15<<Utils.getBCHDigit(r)-G15_BCH;return(e<<10|r)^G15_MASK};
\ No newline at end of file
index 70047e9..ee25027 100644 (file)
@@ -1,71 +1 @@
-var BufferUtil = require('../utils/buffer')
-
-var EXP_TABLE = BufferUtil.alloc(512)
-var LOG_TABLE = BufferUtil.alloc(256)
-/**
- * Precompute the log and anti-log tables for faster computation later
- *
- * For each possible value in the galois field 2^8, we will pre-compute
- * the logarithm and anti-logarithm (exponential) of this value
- *
- * ref {@link https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Introduction_to_mathematical_fields}
- */
-;(function initTables () {
-  var x = 1
-  for (var i = 0; i < 255; i++) {
-    EXP_TABLE[i] = x
-    LOG_TABLE[x] = i
-
-    x <<= 1 // multiply by 2
-
-    // The QR code specification says to use byte-wise modulo 100011101 arithmetic.
-    // This means that when a number is 256 or larger, it should be XORed with 0x11D.
-    if (x & 0x100) { // similar to x >= 256, but a lot faster (because 0x100 == 256)
-      x ^= 0x11D
-    }
-  }
-
-  // Optimization: double the size of the anti-log table so that we don't need to mod 255 to
-  // stay inside the bounds (because we will mainly use this table for the multiplication of
-  // two GF numbers, no more).
-  // @see {@link mul}
-  for (i = 255; i < 512; i++) {
-    EXP_TABLE[i] = EXP_TABLE[i - 255]
-  }
-}())
-
-/**
- * Returns log value of n inside Galois Field
- *
- * @param  {Number} n
- * @return {Number}
- */
-exports.log = function log (n) {
-  if (n < 1) throw new Error('log(' + n + ')')
-  return LOG_TABLE[n]
-}
-
-/**
- * Returns anti-log value of n inside Galois Field
- *
- * @param  {Number} n
- * @return {Number}
- */
-exports.exp = function exp (n) {
-  return EXP_TABLE[n]
-}
-
-/**
- * Multiplies two number inside Galois Field
- *
- * @param  {Number} x
- * @param  {Number} y
- * @return {Number}
- */
-exports.mul = function mul (x, y) {
-  if (x === 0 || y === 0) return 0
-
-  // should be EXP_TABLE[(LOG_TABLE[x] + LOG_TABLE[y]) % 255] if EXP_TABLE wasn't oversized
-  // @see {@link initTables}
-  return EXP_TABLE[LOG_TABLE[x] + LOG_TABLE[y]]
-}
+var BufferUtil=require("../utils/buffer"),EXP_TABLE=BufferUtil.alloc(512),LOG_TABLE=BufferUtil.alloc(256);!function(){for(var r=1,E=0;E<255;E++)EXP_TABLE[E]=r,LOG_TABLE[r]=E,256&(r<<=1)&&(r^=285);for(E=255;E<512;E++)EXP_TABLE[E]=EXP_TABLE[E-255]}(),exports.log=function(r){if(r<1)throw new Error("log("+r+")");return LOG_TABLE[r]},exports.exp=function(r){return EXP_TABLE[r]},exports.mul=function(r,E){return 0===r||0===E?0:EXP_TABLE[LOG_TABLE[r]+LOG_TABLE[E]]};
\ No newline at end of file
index a7909f7..5f2634f 100644 (file)
@@ -1,54 +1 @@
-var Mode = require('./mode')
-var Utils = require('./utils')
-
-function KanjiData (data) {
-  this.mode = Mode.KANJI
-  this.data = data
-}
-
-KanjiData.getBitsLength = function getBitsLength (length) {
-  return length * 13
-}
-
-KanjiData.prototype.getLength = function getLength () {
-  return this.data.length
-}
-
-KanjiData.prototype.getBitsLength = function getBitsLength () {
-  return KanjiData.getBitsLength(this.data.length)
-}
-
-KanjiData.prototype.write = function (bitBuffer) {
-  var i
-
-  // In the Shift JIS system, Kanji characters are represented by a two byte combination.
-  // These byte values are shifted from the JIS X 0208 values.
-  // JIS X 0208 gives details of the shift coded representation.
-  for (i = 0; i < this.data.length; i++) {
-    var value = Utils.toSJIS(this.data[i])
-
-    // For characters with Shift JIS values from 0x8140 to 0x9FFC:
-    if (value >= 0x8140 && value <= 0x9FFC) {
-      // Subtract 0x8140 from Shift JIS value
-      value -= 0x8140
-
-    // For characters with Shift JIS values from 0xE040 to 0xEBBF
-    } else if (value >= 0xE040 && value <= 0xEBBF) {
-      // Subtract 0xC140 from Shift JIS value
-      value -= 0xC140
-    } else {
-      throw new Error(
-        'Invalid SJIS character: ' + this.data[i] + '\n' +
-        'Make sure your charset is UTF-8')
-    }
-
-    // Multiply most significant byte of result by 0xC0
-    // and add least significant byte to product
-    value = (((value >>> 8) & 0xff) * 0xC0) + (value & 0xff)
-
-    // Convert result to a 13-bit binary string
-    bitBuffer.put(value, 13)
-  }
-}
-
-module.exports = KanjiData
+var Mode=require("./mode"),Utils=require("./utils");function KanjiData(t){this.mode=Mode.KANJI,this.data=t}KanjiData.getBitsLength=function(t){return 13*t},KanjiData.prototype.getLength=function(){return this.data.length},KanjiData.prototype.getBitsLength=function(){return KanjiData.getBitsLength(this.data.length)},KanjiData.prototype.write=function(t){var a;for(a=0;a<this.data.length;a++){var e=Utils.toSJIS(this.data[a]);if(e>=33088&&e<=40956)e-=33088;else{if(!(e>=57408&&e<=60351))throw new Error("Invalid SJIS character: "+this.data[a]+"\nMake sure your charset is UTF-8");e-=49472}e=192*(e>>>8&255)+(255&e),t.put(e,13)}},module.exports=KanjiData;
\ No newline at end of file
index d8131e7..411b43c 100644 (file)
@@ -1,234 +1 @@
-/**
- * Data mask pattern reference
- * @type {Object}
- */
-exports.Patterns = {
-  PATTERN000: 0,
-  PATTERN001: 1,
-  PATTERN010: 2,
-  PATTERN011: 3,
-  PATTERN100: 4,
-  PATTERN101: 5,
-  PATTERN110: 6,
-  PATTERN111: 7
-}
-
-/**
- * Weighted penalty scores for the undesirable features
- * @type {Object}
- */
-var PenaltyScores = {
-  N1: 3,
-  N2: 3,
-  N3: 40,
-  N4: 10
-}
-
-/**
- * Check if mask pattern value is valid
- *
- * @param  {Number}  mask    Mask pattern
- * @return {Boolean}         true if valid, false otherwise
- */
-exports.isValid = function isValid (mask) {
-  return mask != null && mask !== '' && !isNaN(mask) && mask >= 0 && mask <= 7
-}
-
-/**
- * Returns mask pattern from a value.
- * If value is not valid, returns undefined
- *
- * @param  {Number|String} value        Mask pattern value
- * @return {Number}                     Valid mask pattern or undefined
- */
-exports.from = function from (value) {
-  return exports.isValid(value) ? parseInt(value, 10) : undefined
-}
-
-/**
-* Find adjacent modules in row/column with the same color
-* and assign a penalty value.
-*
-* Points: N1 + i
-* i is the amount by which the number of adjacent modules of the same color exceeds 5
-*/
-exports.getPenaltyN1 = function getPenaltyN1 (data) {
-  var size = data.size
-  var points = 0
-  var sameCountCol = 0
-  var sameCountRow = 0
-  var lastCol = null
-  var lastRow = null
-
-  for (var row = 0; row < size; row++) {
-    sameCountCol = sameCountRow = 0
-    lastCol = lastRow = null
-
-    for (var col = 0; col < size; col++) {
-      var module = data.get(row, col)
-      if (module === lastCol) {
-        sameCountCol++
-      } else {
-        if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5)
-        lastCol = module
-        sameCountCol = 1
-      }
-
-      module = data.get(col, row)
-      if (module === lastRow) {
-        sameCountRow++
-      } else {
-        if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5)
-        lastRow = module
-        sameCountRow = 1
-      }
-    }
-
-    if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5)
-    if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5)
-  }
-
-  return points
-}
-
-/**
- * Find 2x2 blocks with the same color and assign a penalty value
- *
- * Points: N2 * (m - 1) * (n - 1)
- */
-exports.getPenaltyN2 = function getPenaltyN2 (data) {
-  var size = data.size
-  var points = 0
-
-  for (var row = 0; row < size - 1; row++) {
-    for (var col = 0; col < size - 1; col++) {
-      var last = data.get(row, col) +
-        data.get(row, col + 1) +
-        data.get(row + 1, col) +
-        data.get(row + 1, col + 1)
-
-      if (last === 4 || last === 0) points++
-    }
-  }
-
-  return points * PenaltyScores.N2
-}
-
-/**
- * Find 1:1:3:1:1 ratio (dark:light:dark:light:dark) pattern in row/column,
- * preceded or followed by light area 4 modules wide
- *
- * Points: N3 * number of pattern found
- */
-exports.getPenaltyN3 = function getPenaltyN3 (data) {
-  var size = data.size
-  var points = 0
-  var bitsCol = 0
-  var bitsRow = 0
-
-  for (var row = 0; row < size; row++) {
-    bitsCol = bitsRow = 0
-    for (var col = 0; col < size; col++) {
-      bitsCol = ((bitsCol << 1) & 0x7FF) | data.get(row, col)
-      if (col >= 10 && (bitsCol === 0x5D0 || bitsCol === 0x05D)) points++
-
-      bitsRow = ((bitsRow << 1) & 0x7FF) | data.get(col, row)
-      if (col >= 10 && (bitsRow === 0x5D0 || bitsRow === 0x05D)) points++
-    }
-  }
-
-  return points * PenaltyScores.N3
-}
-
-/**
- * Calculate proportion of dark modules in entire symbol
- *
- * Points: N4 * k
- *
- * k is the rating of the deviation of the proportion of dark modules
- * in the symbol from 50% in steps of 5%
- */
-exports.getPenaltyN4 = function getPenaltyN4 (data) {
-  var darkCount = 0
-  var modulesCount = data.data.length
-
-  for (var i = 0; i < modulesCount; i++) darkCount += data.data[i]
-
-  var k = Math.abs(Math.ceil((darkCount * 100 / modulesCount) / 5) - 10)
-
-  return k * PenaltyScores.N4
-}
-
-/**
- * Return mask value at given position
- *
- * @param  {Number} maskPattern Pattern reference value
- * @param  {Number} i           Row
- * @param  {Number} j           Column
- * @return {Boolean}            Mask value
- */
-function getMaskAt (maskPattern, i, j) {
-  switch (maskPattern) {
-    case exports.Patterns.PATTERN000: return (i + j) % 2 === 0
-    case exports.Patterns.PATTERN001: return i % 2 === 0
-    case exports.Patterns.PATTERN010: return j % 3 === 0
-    case exports.Patterns.PATTERN011: return (i + j) % 3 === 0
-    case exports.Patterns.PATTERN100: return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 === 0
-    case exports.Patterns.PATTERN101: return (i * j) % 2 + (i * j) % 3 === 0
-    case exports.Patterns.PATTERN110: return ((i * j) % 2 + (i * j) % 3) % 2 === 0
-    case exports.Patterns.PATTERN111: return ((i * j) % 3 + (i + j) % 2) % 2 === 0
-
-    default: throw new Error('bad maskPattern:' + maskPattern)
-  }
-}
-
-/**
- * Apply a mask pattern to a BitMatrix
- *
- * @param  {Number}    pattern Pattern reference number
- * @param  {BitMatrix} data    BitMatrix data
- */
-exports.applyMask = function applyMask (pattern, data) {
-  var size = data.size
-
-  for (var col = 0; col < size; col++) {
-    for (var row = 0; row < size; row++) {
-      if (data.isReserved(row, col)) continue
-      data.xor(row, col, getMaskAt(pattern, row, col))
-    }
-  }
-}
-
-/**
- * Returns the best mask pattern for data
- *
- * @param  {BitMatrix} data
- * @return {Number} Mask pattern reference number
- */
-exports.getBestMask = function getBestMask (data, setupFormatFunc) {
-  var numPatterns = Object.keys(exports.Patterns).length
-  var bestPattern = 0
-  var lowerPenalty = Infinity
-
-  for (var p = 0; p < numPatterns; p++) {
-    setupFormatFunc(p)
-    exports.applyMask(p, data)
-
-    // Calculate penalty
-    var penalty =
-      exports.getPenaltyN1(data) +
-      exports.getPenaltyN2(data) +
-      exports.getPenaltyN3(data) +
-      exports.getPenaltyN4(data)
-
-    // Undo previously applied mask
-    exports.applyMask(p, data)
-
-    if (penalty < lowerPenalty) {
-      lowerPenalty = penalty
-      bestPattern = p
-    }
-  }
-
-  return bestPattern
-}
+exports.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var PenaltyScores={N1:3,N2:3,N3:40,N4:10};function getMaskAt(t,e,r){switch(t){case exports.Patterns.PATTERN000:return(e+r)%2==0;case exports.Patterns.PATTERN001:return e%2==0;case exports.Patterns.PATTERN010:return r%3==0;case exports.Patterns.PATTERN011:return(e+r)%3==0;case exports.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(r/3))%2==0;case exports.Patterns.PATTERN101:return e*r%2+e*r%3==0;case exports.Patterns.PATTERN110:return(e*r%2+e*r%3)%2==0;case exports.Patterns.PATTERN111:return(e*r%3+(e+r)%2)%2==0;default:throw new Error("bad maskPattern:"+t)}}exports.isValid=function(t){return null!=t&&""!==t&&!isNaN(t)&&t>=0&&t<=7},exports.from=function(t){return exports.isValid(t)?parseInt(t,10):void 0},exports.getPenaltyN1=function(t){for(var e=t.size,r=0,a=0,s=0,n=null,o=null,P=0;P<e;P++){a=s=0,n=o=null;for(var N=0;N<e;N++){var l=t.get(P,N);l===n?a++:(a>=5&&(r+=PenaltyScores.N1+(a-5)),n=l,a=1),(l=t.get(N,P))===o?s++:(s>=5&&(r+=PenaltyScores.N1+(s-5)),o=l,s=1)}a>=5&&(r+=PenaltyScores.N1+(a-5)),s>=5&&(r+=PenaltyScores.N1+(s-5))}return r},exports.getPenaltyN2=function(t){for(var e=t.size,r=0,a=0;a<e-1;a++)for(var s=0;s<e-1;s++){var n=t.get(a,s)+t.get(a,s+1)+t.get(a+1,s)+t.get(a+1,s+1);4!==n&&0!==n||r++}return r*PenaltyScores.N2},exports.getPenaltyN3=function(t){for(var e=t.size,r=0,a=0,s=0,n=0;n<e;n++){a=s=0;for(var o=0;o<e;o++)a=a<<1&2047|t.get(n,o),o>=10&&(1488===a||93===a)&&r++,s=s<<1&2047|t.get(o,n),o>=10&&(1488===s||93===s)&&r++}return r*PenaltyScores.N3},exports.getPenaltyN4=function(t){for(var e=0,r=t.data.length,a=0;a<r;a++)e+=t.data[a];return Math.abs(Math.ceil(100*e/r/5)-10)*PenaltyScores.N4},exports.applyMask=function(t,e){for(var r=e.size,a=0;a<r;a++)for(var s=0;s<r;s++)e.isReserved(s,a)||e.xor(s,a,getMaskAt(t,s,a))},exports.getBestMask=function(t,e){for(var r=Object.keys(exports.Patterns).length,a=0,s=1/0,n=0;n<r;n++){e(n),exports.applyMask(n,t);var o=exports.getPenaltyN1(t)+exports.getPenaltyN2(t)+exports.getPenaltyN3(t)+exports.getPenaltyN4(t);exports.applyMask(n,t),o<s&&(s=o,a=n)}return a};
\ No newline at end of file
index 01dc5e7..7c246f4 100644 (file)
@@ -1,167 +1 @@
-var VersionCheck = require('./version-check')
-var Regex = require('./regex')
-
-/**
- * Numeric mode encodes data from the decimal digit set (0 - 9)
- * (byte values 30HEX to 39HEX).
- * Normally, 3 data characters are represented by 10 bits.
- *
- * @type {Object}
- */
-exports.NUMERIC = {
-  id: 'Numeric',
-  bit: 1 << 0,
-  ccBits: [10, 12, 14]
-}
-
-/**
- * Alphanumeric mode encodes data from a set of 45 characters,
- * i.e. 10 numeric digits (0 - 9),
- *      26 alphabetic characters (A - Z),
- *   and 9 symbols (SP, $, %, *, +, -, ., /, :).
- * Normally, two input characters are represented by 11 bits.
- *
- * @type {Object}
- */
-exports.ALPHANUMERIC = {
-  id: 'Alphanumeric',
-  bit: 1 << 1,
-  ccBits: [9, 11, 13]
-}
-
-/**
- * In byte mode, data is encoded at 8 bits per character.
- *
- * @type {Object}
- */
-exports.BYTE = {
-  id: 'Byte',
-  bit: 1 << 2,
-  ccBits: [8, 16, 16]
-}
-
-/**
- * The Kanji mode efficiently encodes Kanji characters in accordance with
- * the Shift JIS system based on JIS X 0208.
- * The Shift JIS values are shifted from the JIS X 0208 values.
- * JIS X 0208 gives details of the shift coded representation.
- * Each two-byte character value is compacted to a 13-bit binary codeword.
- *
- * @type {Object}
- */
-exports.KANJI = {
-  id: 'Kanji',
-  bit: 1 << 3,
-  ccBits: [8, 10, 12]
-}
-
-/**
- * Mixed mode will contain a sequences of data in a combination of any of
- * the modes described above
- *
- * @type {Object}
- */
-exports.MIXED = {
-  bit: -1
-}
-
-/**
- * Returns the number of bits needed to store the data length
- * according to QR Code specifications.
- *
- * @param  {Mode}   mode    Data mode
- * @param  {Number} version QR Code version
- * @return {Number}         Number of bits
- */
-exports.getCharCountIndicator = function getCharCountIndicator (mode, version) {
-  if (!mode.ccBits) throw new Error('Invalid mode: ' + mode)
-
-  if (!VersionCheck.isValid(version)) {
-    throw new Error('Invalid version: ' + version)
-  }
-
-  if (version >= 1 && version < 10) return mode.ccBits[0]
-  else if (version < 27) return mode.ccBits[1]
-  return mode.ccBits[2]
-}
-
-/**
- * Returns the most efficient mode to store the specified data
- *
- * @param  {String} dataStr Input data string
- * @return {Mode}           Best mode
- */
-exports.getBestModeForData = function getBestModeForData (dataStr) {
-  if (Regex.testNumeric(dataStr)) return exports.NUMERIC
-  else if (Regex.testAlphanumeric(dataStr)) return exports.ALPHANUMERIC
-  else if (Regex.testKanji(dataStr)) return exports.KANJI
-  else return exports.BYTE
-}
-
-/**
- * Return mode name as string
- *
- * @param {Mode} mode Mode object
- * @returns {String}  Mode name
- */
-exports.toString = function toString (mode) {
-  if (mode && mode.id) return mode.id
-  throw new Error('Invalid mode')
-}
-
-/**
- * Check if input param is a valid mode object
- *
- * @param   {Mode}    mode Mode object
- * @returns {Boolean} True if valid mode, false otherwise
- */
-exports.isValid = function isValid (mode) {
-  return mode && mode.bit && mode.ccBits
-}
-
-/**
- * Get mode object from its name
- *
- * @param   {String} string Mode name
- * @returns {Mode}          Mode object
- */
-function fromString (string) {
-  if (typeof string !== 'string') {
-    throw new Error('Param is not a string')
-  }
-
-  var lcStr = string.toLowerCase()
-
-  switch (lcStr) {
-    case 'numeric':
-      return exports.NUMERIC
-    case 'alphanumeric':
-      return exports.ALPHANUMERIC
-    case 'kanji':
-      return exports.KANJI
-    case 'byte':
-      return exports.BYTE
-    default:
-      throw new Error('Unknown mode: ' + string)
-  }
-}
-
-/**
- * Returns mode from a value.
- * If value is not a valid mode, returns defaultValue
- *
- * @param  {Mode|String} value        Encoding mode
- * @param  {Mode}        defaultValue Fallback value
- * @return {Mode}                     Encoding mode
- */
-exports.from = function from (value, defaultValue) {
-  if (exports.isValid(value)) {
-    return value
-  }
-
-  try {
-    return fromString(value)
-  } catch (e) {
-    return defaultValue
-  }
-}
+var VersionCheck=require("./version-check"),Regex=require("./regex");function fromString(r){if("string"!=typeof r)throw new Error("Param is not a string");switch(r.toLowerCase()){case"numeric":return exports.NUMERIC;case"alphanumeric":return exports.ALPHANUMERIC;case"kanji":return exports.KANJI;case"byte":return exports.BYTE;default:throw new Error("Unknown mode: "+r)}}exports.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},exports.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},exports.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},exports.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},exports.MIXED={bit:-1},exports.getCharCountIndicator=function(r,t){if(!r.ccBits)throw new Error("Invalid mode: "+r);if(!VersionCheck.isValid(t))throw new Error("Invalid version: "+t);return t>=1&&t<10?r.ccBits[0]:t<27?r.ccBits[1]:r.ccBits[2]},exports.getBestModeForData=function(r){return Regex.testNumeric(r)?exports.NUMERIC:Regex.testAlphanumeric(r)?exports.ALPHANUMERIC:Regex.testKanji(r)?exports.KANJI:exports.BYTE},exports.toString=function(r){if(r&&r.id)return r.id;throw new Error("Invalid mode")},exports.isValid=function(r){return r&&r.bit&&r.ccBits},exports.from=function(r,t){if(exports.isValid(r))return r;try{return fromString(r)}catch(r){return t}};
\ No newline at end of file
index 929a7fd..d25050d 100644 (file)
@@ -1,43 +1 @@
-var Mode = require('./mode')
-
-function NumericData (data) {
-  this.mode = Mode.NUMERIC
-  this.data = data.toString()
-}
-
-NumericData.getBitsLength = function getBitsLength (length) {
-  return 10 * Math.floor(length / 3) + ((length % 3) ? ((length % 3) * 3 + 1) : 0)
-}
-
-NumericData.prototype.getLength = function getLength () {
-  return this.data.length
-}
-
-NumericData.prototype.getBitsLength = function getBitsLength () {
-  return NumericData.getBitsLength(this.data.length)
-}
-
-NumericData.prototype.write = function write (bitBuffer) {
-  var i, group, value
-
-  // The input data string is divided into groups of three digits,
-  // and each group is converted to its 10-bit binary equivalent.
-  for (i = 0; i + 3 <= this.data.length; i += 3) {
-    group = this.data.substr(i, 3)
-    value = parseInt(group, 10)
-
-    bitBuffer.put(value, 10)
-  }
-
-  // If the number of input digits is not an exact multiple of three,
-  // the final one or two digits are converted to 4 or 7 bits respectively.
-  var remainingNum = this.data.length - i
-  if (remainingNum > 0) {
-    group = this.data.substr(i)
-    value = parseInt(group, 10)
-
-    bitBuffer.put(value, remainingNum * 3 + 1)
-  }
-}
-
-module.exports = NumericData
+var Mode=require("./mode");function NumericData(t){this.mode=Mode.NUMERIC,this.data=t.toString()}NumericData.getBitsLength=function(t){return 10*Math.floor(t/3)+(t%3?t%3*3+1:0)},NumericData.prototype.getLength=function(){return this.data.length},NumericData.prototype.getBitsLength=function(){return NumericData.getBitsLength(this.data.length)},NumericData.prototype.write=function(t){var e,a,r;for(e=0;e+3<=this.data.length;e+=3)a=this.data.substr(e,3),r=parseInt(a,10),t.put(r,10);var i=this.data.length-e;i>0&&(a=this.data.substr(e),r=parseInt(a,10),t.put(r,3*i+1))},module.exports=NumericData;
\ No newline at end of file
index 725df03..c85ca68 100644 (file)
@@ -1,63 +1 @@
-var BufferUtil = require('../utils/buffer')
-var GF = require('./galois-field')
-
-/**
- * Multiplies two polynomials inside Galois Field
- *
- * @param  {Buffer} p1 Polynomial
- * @param  {Buffer} p2 Polynomial
- * @return {Buffer}    Product of p1 and p2
- */
-exports.mul = function mul (p1, p2) {
-  var coeff = BufferUtil.alloc(p1.length + p2.length - 1)
-
-  for (var i = 0; i < p1.length; i++) {
-    for (var j = 0; j < p2.length; j++) {
-      coeff[i + j] ^= GF.mul(p1[i], p2[j])
-    }
-  }
-
-  return coeff
-}
-
-/**
- * Calculate the remainder of polynomials division
- *
- * @param  {Buffer} divident Polynomial
- * @param  {Buffer} divisor  Polynomial
- * @return {Buffer}          Remainder
- */
-exports.mod = function mod (divident, divisor) {
-  var result = BufferUtil.from(divident)
-
-  while ((result.length - divisor.length) >= 0) {
-    var coeff = result[0]
-
-    for (var i = 0; i < divisor.length; i++) {
-      result[i] ^= GF.mul(divisor[i], coeff)
-    }
-
-    // remove all zeros from buffer head
-    var offset = 0
-    while (offset < result.length && result[offset] === 0) offset++
-    result = result.slice(offset)
-  }
-
-  return result
-}
-
-/**
- * Generate an irreducible generator polynomial of specified degree
- * (used by Reed-Solomon encoder)
- *
- * @param  {Number} degree Degree of the generator polynomial
- * @return {Buffer}        Buffer containing polynomial coefficients
- */
-exports.generateECPolynomial = function generateECPolynomial (degree) {
-  var poly = BufferUtil.from([1])
-  for (var i = 0; i < degree; i++) {
-    poly = exports.mul(poly, [1, GF.exp(i)])
-  }
-
-  return poly
-}
+var BufferUtil=require("../utils/buffer"),GF=require("./galois-field");exports.mul=function(r,e){for(var l=BufferUtil.alloc(r.length+e.length-1),t=0;t<r.length;t++)for(var f=0;f<e.length;f++)l[t+f]^=GF.mul(r[t],e[f]);return l},exports.mod=function(r,e){for(var l=BufferUtil.from(r);l.length-e.length>=0;){for(var t=l[0],f=0;f<e.length;f++)l[f]^=GF.mul(e[f],t);for(var o=0;o<l.length&&0===l[o];)o++;l=l.slice(o)}return l},exports.generateECPolynomial=function(r){for(var e=BufferUtil.from([1]),l=0;l<r;l++)e=exports.mul(e,[1,GF.exp(l)]);return e};
\ No newline at end of file
index 2ddf9ae..a1850a9 100644 (file)
@@ -1,499 +1 @@
-var BufferUtil = require('../utils/buffer')
-var Utils = require('./utils')
-var ECLevel = require('./error-correction-level')
-var BitBuffer = require('./bit-buffer')
-var BitMatrix = require('./bit-matrix')
-var AlignmentPattern = require('./alignment-pattern')
-var FinderPattern = require('./finder-pattern')
-var MaskPattern = require('./mask-pattern')
-var ECCode = require('./error-correction-code')
-var ReedSolomonEncoder = require('./reed-solomon-encoder')
-var Version = require('./version')
-var FormatInfo = require('./format-info')
-var Mode = require('./mode')
-var Segments = require('./segments')
-var isArray = require('isarray')
-
-/**
- * QRCode for JavaScript
- *
- * modified by Ryan Day for nodejs support
- * Copyright (c) 2011 Ryan Day
- *
- * Licensed under the MIT license:
- *   http://www.opensource.org/licenses/mit-license.php
- *
-//---------------------------------------------------------------------
-// QRCode for JavaScript
-//
-// Copyright (c) 2009 Kazuhiko Arase
-//
-// URL: http://www.d-project.com/
-//
-// Licensed under the MIT license:
-//   http://www.opensource.org/licenses/mit-license.php
-//
-// The word "QR Code" is registered trademark of
-// DENSO WAVE INCORPORATED
-//   http://www.denso-wave.com/qrcode/faqpatent-e.html
-//
-//---------------------------------------------------------------------
-*/
-
-/**
- * Add finder patterns bits to matrix
- *
- * @param  {BitMatrix} matrix  Modules matrix
- * @param  {Number}    version QR Code version
- */
-function setupFinderPattern (matrix, version) {
-  var size = matrix.size
-  var pos = FinderPattern.getPositions(version)
-
-  for (var i = 0; i < pos.length; i++) {
-    var row = pos[i][0]
-    var col = pos[i][1]
-
-    for (var r = -1; r <= 7; r++) {
-      if (row + r <= -1 || size <= row + r) continue
-
-      for (var c = -1; c <= 7; c++) {
-        if (col + c <= -1 || size <= col + c) continue
-
-        if ((r >= 0 && r <= 6 && (c === 0 || c === 6)) ||
-          (c >= 0 && c <= 6 && (r === 0 || r === 6)) ||
-          (r >= 2 && r <= 4 && c >= 2 && c <= 4)) {
-          matrix.set(row + r, col + c, true, true)
-        } else {
-          matrix.set(row + r, col + c, false, true)
-        }
-      }
-    }
-  }
-}
-
-/**
- * Add timing pattern bits to matrix
- *
- * Note: this function must be called before {@link setupAlignmentPattern}
- *
- * @param  {BitMatrix} matrix Modules matrix
- */
-function setupTimingPattern (matrix) {
-  var size = matrix.size
-
-  for (var r = 8; r < size - 8; r++) {
-    var value = r % 2 === 0
-    matrix.set(r, 6, value, true)
-    matrix.set(6, r, value, true)
-  }
-}
-
-/**
- * Add alignment patterns bits to matrix
- *
- * Note: this function must be called after {@link setupTimingPattern}
- *
- * @param  {BitMatrix} matrix  Modules matrix
- * @param  {Number}    version QR Code version
- */
-function setupAlignmentPattern (matrix, version) {
-  var pos = AlignmentPattern.getPositions(version)
-
-  for (var i = 0; i < pos.length; i++) {
-    var row = pos[i][0]
-    var col = pos[i][1]
-
-    for (var r = -2; r <= 2; r++) {
-      for (var c = -2; c <= 2; c++) {
-        if (r === -2 || r === 2 || c === -2 || c === 2 ||
-          (r === 0 && c === 0)) {
-          matrix.set(row + r, col + c, true, true)
-        } else {
-          matrix.set(row + r, col + c, false, true)
-        }
-      }
-    }
-  }
-}
-
-/**
- * Add version info bits to matrix
- *
- * @param  {BitMatrix} matrix  Modules matrix
- * @param  {Number}    version QR Code version
- */
-function setupVersionInfo (matrix, version) {
-  var size = matrix.size
-  var bits = Version.getEncodedBits(version)
-  var row, col, mod
-
-  for (var i = 0; i < 18; i++) {
-    row = Math.floor(i / 3)
-    col = i % 3 + size - 8 - 3
-    mod = ((bits >> i) & 1) === 1
-
-    matrix.set(row, col, mod, true)
-    matrix.set(col, row, mod, true)
-  }
-}
-
-/**
- * Add format info bits to matrix
- *
- * @param  {BitMatrix} matrix               Modules matrix
- * @param  {ErrorCorrectionLevel}    errorCorrectionLevel Error correction level
- * @param  {Number}    maskPattern          Mask pattern reference value
- */
-function setupFormatInfo (matrix, errorCorrectionLevel, maskPattern) {
-  var size = matrix.size
-  var bits = FormatInfo.getEncodedBits(errorCorrectionLevel, maskPattern)
-  var i, mod
-
-  for (i = 0; i < 15; i++) {
-    mod = ((bits >> i) & 1) === 1
-
-    // vertical
-    if (i < 6) {
-      matrix.set(i, 8, mod, true)
-    } else if (i < 8) {
-      matrix.set(i + 1, 8, mod, true)
-    } else {
-      matrix.set(size - 15 + i, 8, mod, true)
-    }
-
-    // horizontal
-    if (i < 8) {
-      matrix.set(8, size - i - 1, mod, true)
-    } else if (i < 9) {
-      matrix.set(8, 15 - i - 1 + 1, mod, true)
-    } else {
-      matrix.set(8, 15 - i - 1, mod, true)
-    }
-  }
-
-  // fixed module
-  matrix.set(size - 8, 8, 1, true)
-}
-
-/**
- * Add encoded data bits to matrix
- *
- * @param  {BitMatrix} matrix Modules matrix
- * @param  {Buffer}    data   Data codewords
- */
-function setupData (matrix, data) {
-  var size = matrix.size
-  var inc = -1
-  var row = size - 1
-  var bitIndex = 7
-  var byteIndex = 0
-
-  for (var col = size - 1; col > 0; col -= 2) {
-    if (col === 6) col--
-
-    while (true) {
-      for (var c = 0; c < 2; c++) {
-        if (!matrix.isReserved(row, col - c)) {
-          var dark = false
-
-          if (byteIndex < data.length) {
-            dark = (((data[byteIndex] >>> bitIndex) & 1) === 1)
-          }
-
-          matrix.set(row, col - c, dark)
-          bitIndex--
-
-          if (bitIndex === -1) {
-            byteIndex++
-            bitIndex = 7
-          }
-        }
-      }
-
-      row += inc
-
-      if (row < 0 || size <= row) {
-        row -= inc
-        inc = -inc
-        break
-      }
-    }
-  }
-}
-
-/**
- * Create encoded codewords from data input
- *
- * @param  {Number}   version              QR Code version
- * @param  {ErrorCorrectionLevel}   errorCorrectionLevel Error correction level
- * @param  {ByteData} data                 Data input
- * @return {Buffer}                        Buffer containing encoded codewords
- */
-function createData (version, errorCorrectionLevel, segments) {
-  // Prepare data buffer
-  var buffer = new BitBuffer()
-
-  segments.forEach(function (data) {
-    // prefix data with mode indicator (4 bits)
-    buffer.put(data.mode.bit, 4)
-
-    // Prefix data with character count indicator.
-    // The character count indicator is a string of bits that represents the
-    // number of characters that are being encoded.
-    // The character count indicator must be placed after the mode indicator
-    // and must be a certain number of bits long, depending on the QR version
-    // and data mode
-    // @see {@link Mode.getCharCountIndicator}.
-    buffer.put(data.getLength(), Mode.getCharCountIndicator(data.mode, version))
-
-    // add binary data sequence to buffer
-    data.write(buffer)
-  })
-
-  // Calculate required number of bits
-  var totalCodewords = Utils.getSymbolTotalCodewords(version)
-  var ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)
-  var dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8
-
-  // Add a terminator.
-  // If the bit string is shorter than the total number of required bits,
-  // a terminator of up to four 0s must be added to the right side of the string.
-  // If the bit string is more than four bits shorter than the required number of bits,
-  // add four 0s to the end.
-  if (buffer.getLengthInBits() + 4 <= dataTotalCodewordsBits) {
-    buffer.put(0, 4)
-  }
-
-  // If the bit string is fewer than four bits shorter, add only the number of 0s that
-  // are needed to reach the required number of bits.
-
-  // After adding the terminator, if the number of bits in the string is not a multiple of 8,
-  // pad the string on the right with 0s to make the string's length a multiple of 8.
-  while (buffer.getLengthInBits() % 8 !== 0) {
-    buffer.putBit(0)
-  }
-
-  // Add pad bytes if the string is still shorter than the total number of required bits.
-  // Extend the buffer to fill the data capacity of the symbol corresponding to
-  // the Version and Error Correction Level by adding the Pad Codewords 11101100 (0xEC)
-  // and 00010001 (0x11) alternately.
-  var remainingByte = (dataTotalCodewordsBits - buffer.getLengthInBits()) / 8
-  for (var i = 0; i < remainingByte; i++) {
-    buffer.put(i % 2 ? 0x11 : 0xEC, 8)
-  }
-
-  return createCodewords(buffer, version, errorCorrectionLevel)
-}
-
-/**
- * Encode input data with Reed-Solomon and return codewords with
- * relative error correction bits
- *
- * @param  {BitBuffer} bitBuffer            Data to encode
- * @param  {Number}    version              QR Code version
- * @param  {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
- * @return {Buffer}                         Buffer containing encoded codewords
- */
-function createCodewords (bitBuffer, version, errorCorrectionLevel) {
-  // Total codewords for this QR code version (Data + Error correction)
-  var totalCodewords = Utils.getSymbolTotalCodewords(version)
-
-  // Total number of error correction codewords
-  var ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)
-
-  // Total number of data codewords
-  var dataTotalCodewords = totalCodewords - ecTotalCodewords
-
-  // Total number of blocks
-  var ecTotalBlocks = ECCode.getBlocksCount(version, errorCorrectionLevel)
-
-  // Calculate how many blocks each group should contain
-  var blocksInGroup2 = totalCodewords % ecTotalBlocks
-  var blocksInGroup1 = ecTotalBlocks - blocksInGroup2
-
-  var totalCodewordsInGroup1 = Math.floor(totalCodewords / ecTotalBlocks)
-
-  var dataCodewordsInGroup1 = Math.floor(dataTotalCodewords / ecTotalBlocks)
-  var dataCodewordsInGroup2 = dataCodewordsInGroup1 + 1
-
-  // Number of EC codewords is the same for both groups
-  var ecCount = totalCodewordsInGroup1 - dataCodewordsInGroup1
-
-  // Initialize a Reed-Solomon encoder with a generator polynomial of degree ecCount
-  var rs = new ReedSolomonEncoder(ecCount)
-
-  var offset = 0
-  var dcData = new Array(ecTotalBlocks)
-  var ecData = new Array(ecTotalBlocks)
-  var maxDataSize = 0
-  var buffer = BufferUtil.from(bitBuffer.buffer)
-
-  // Divide the buffer into the required number of blocks
-  for (var b = 0; b < ecTotalBlocks; b++) {
-    var dataSize = b < blocksInGroup1 ? dataCodewordsInGroup1 : dataCodewordsInGroup2
-
-    // extract a block of data from buffer
-    dcData[b] = buffer.slice(offset, offset + dataSize)
-
-    // Calculate EC codewords for this data block
-    ecData[b] = rs.encode(dcData[b])
-
-    offset += dataSize
-    maxDataSize = Math.max(maxDataSize, dataSize)
-  }
-
-  // Create final data
-  // Interleave the data and error correction codewords from each block
-  var data = BufferUtil.alloc(totalCodewords)
-  var index = 0
-  var i, r
-
-  // Add data codewords
-  for (i = 0; i < maxDataSize; i++) {
-    for (r = 0; r < ecTotalBlocks; r++) {
-      if (i < dcData[r].length) {
-        data[index++] = dcData[r][i]
-      }
-    }
-  }
-
-  // Apped EC codewords
-  for (i = 0; i < ecCount; i++) {
-    for (r = 0; r < ecTotalBlocks; r++) {
-      data[index++] = ecData[r][i]
-    }
-  }
-
-  return data
-}
-
-/**
- * Build QR Code symbol
- *
- * @param  {String} data                 Input string
- * @param  {Number} version              QR Code version
- * @param  {ErrorCorretionLevel} errorCorrectionLevel Error level
- * @param  {MaskPattern} maskPattern     Mask pattern
- * @return {Object}                      Object containing symbol data
- */
-function createSymbol (data, version, errorCorrectionLevel, maskPattern) {
-  var segments
-
-  if (isArray(data)) {
-    segments = Segments.fromArray(data)
-  } else if (typeof data === 'string') {
-    var estimatedVersion = version
-
-    if (!estimatedVersion) {
-      var rawSegments = Segments.rawSplit(data)
-
-      // Estimate best version that can contain raw splitted segments
-      estimatedVersion = Version.getBestVersionForData(rawSegments,
-        errorCorrectionLevel)
-    }
-
-    // Build optimized segments
-    // If estimated version is undefined, try with the highest version
-    segments = Segments.fromString(data, estimatedVersion || 40)
-  } else {
-    throw new Error('Invalid data')
-  }
-
-  // Get the min version that can contain data
-  var bestVersion = Version.getBestVersionForData(segments,
-      errorCorrectionLevel)
-
-  // If no version is found, data cannot be stored
-  if (!bestVersion) {
-    throw new Error('The amount of data is too big to be stored in a QR Code')
-  }
-
-  // If not specified, use min version as default
-  if (!version) {
-    version = bestVersion
-
-  // Check if the specified version can contain the data
-  } else if (version < bestVersion) {
-    throw new Error('\n' +
-      'The chosen QR Code version cannot contain this amount of data.\n' +
-      'Minimum version required to store current data is: ' + bestVersion + '.\n'
-    )
-  }
-
-  var dataBits = createData(version, errorCorrectionLevel, segments)
-
-  // Allocate matrix buffer
-  var moduleCount = Utils.getSymbolSize(version)
-  var modules = new BitMatrix(moduleCount)
-
-  // Add function modules
-  setupFinderPattern(modules, version)
-  setupTimingPattern(modules)
-  setupAlignmentPattern(modules, version)
-
-  // Add temporary dummy bits for format info just to set them as reserved.
-  // This is needed to prevent these bits from being masked by {@link MaskPattern.applyMask}
-  // since the masking operation must be performed only on the encoding region.
-  // These blocks will be replaced with correct values later in code.
-  setupFormatInfo(modules, errorCorrectionLevel, 0)
-
-  if (version >= 7) {
-    setupVersionInfo(modules, version)
-  }
-
-  // Add data codewords
-  setupData(modules, dataBits)
-
-  if (isNaN(maskPattern)) {
-    // Find best mask pattern
-    maskPattern = MaskPattern.getBestMask(modules,
-      setupFormatInfo.bind(null, modules, errorCorrectionLevel))
-  }
-
-  // Apply mask pattern
-  MaskPattern.applyMask(maskPattern, modules)
-
-  // Replace format info bits with correct values
-  setupFormatInfo(modules, errorCorrectionLevel, maskPattern)
-
-  return {
-    modules: modules,
-    version: version,
-    errorCorrectionLevel: errorCorrectionLevel,
-    maskPattern: maskPattern,
-    segments: segments
-  }
-}
-
-/**
- * QR Code
- *
- * @param {String | Array} data                 Input data
- * @param {Object} options                      Optional configurations
- * @param {Number} options.version              QR Code version
- * @param {String} options.errorCorrectionLevel Error correction level
- * @param {Function} options.toSJISFunc         Helper func to convert utf8 to sjis
- */
-exports.create = function create (data, options) {
-  if (typeof data === 'undefined' || data === '') {
-    throw new Error('No input text')
-  }
-
-  var errorCorrectionLevel = ECLevel.M
-  var version
-  var mask
-
-  if (typeof options !== 'undefined') {
-    // Use higher error correction level as default
-    errorCorrectionLevel = ECLevel.from(options.errorCorrectionLevel, ECLevel.M)
-    version = Version.from(options.version)
-    mask = MaskPattern.from(options.maskPattern)
-
-    if (options.toSJISFunc) {
-      Utils.setToSJISFunction(options.toSJISFunc)
-    }
-  }
-
-  return createSymbol(data, version, errorCorrectionLevel, mask)
-}
+var BufferUtil=require("../utils/buffer"),Utils=require("./utils"),ECLevel=require("./error-correction-level"),BitBuffer=require("./bit-buffer"),BitMatrix=require("./bit-matrix"),AlignmentPattern=require("./alignment-pattern"),FinderPattern=require("./finder-pattern"),MaskPattern=require("./mask-pattern"),ECCode=require("./error-correction-code"),ReedSolomonEncoder=require("./reed-solomon-encoder"),Version=require("./version"),FormatInfo=require("./format-info"),Mode=require("./mode"),Segments=require("./segments"),isArray=require("isarray");function setupFinderPattern(e,r){for(var t=e.size,o=FinderPattern.getPositions(r),n=0;n<o.length;n++)for(var i=o[n][0],a=o[n][1],s=-1;s<=7;s++)if(!(i+s<=-1||t<=i+s))for(var f=-1;f<=7;f++)a+f<=-1||t<=a+f||(s>=0&&s<=6&&(0===f||6===f)||f>=0&&f<=6&&(0===s||6===s)||s>=2&&s<=4&&f>=2&&f<=4?e.set(i+s,a+f,!0,!0):e.set(i+s,a+f,!1,!0))}function setupTimingPattern(e){for(var r=e.size,t=8;t<r-8;t++){var o=t%2==0;e.set(t,6,o,!0),e.set(6,t,o,!0)}}function setupAlignmentPattern(e,r){for(var t=AlignmentPattern.getPositions(r),o=0;o<t.length;o++)for(var n=t[o][0],i=t[o][1],a=-2;a<=2;a++)for(var s=-2;s<=2;s++)-2===a||2===a||-2===s||2===s||0===a&&0===s?e.set(n+a,i+s,!0,!0):e.set(n+a,i+s,!1,!0)}function setupVersionInfo(e,r){for(var t,o,n,i=e.size,a=Version.getEncodedBits(r),s=0;s<18;s++)t=Math.floor(s/3),o=s%3+i-8-3,n=1==(a>>s&1),e.set(t,o,n,!0),e.set(o,t,n,!0)}function setupFormatInfo(e,r,t){var o,n,i=e.size,a=FormatInfo.getEncodedBits(r,t);for(o=0;o<15;o++)n=1==(a>>o&1),o<6?e.set(o,8,n,!0):o<8?e.set(o+1,8,n,!0):e.set(i-15+o,8,n,!0),o<8?e.set(8,i-o-1,n,!0):o<9?e.set(8,15-o-1+1,n,!0):e.set(8,15-o-1,n,!0);e.set(i-8,8,1,!0)}function setupData(e,r){for(var t=e.size,o=-1,n=t-1,i=7,a=0,s=t-1;s>0;s-=2)for(6===s&&s--;;){for(var f=0;f<2;f++)if(!e.isReserved(n,s-f)){var u=!1;a<r.length&&(u=1==(r[a]>>>i&1)),e.set(n,s-f,u),-1===--i&&(a++,i=7)}if((n+=o)<0||t<=n){n-=o,o=-o;break}}}function createData(e,r,t){var o=new BitBuffer;t.forEach((function(r){o.put(r.mode.bit,4),o.put(r.getLength(),Mode.getCharCountIndicator(r.mode,e)),r.write(o)}));var n=8*(Utils.getSymbolTotalCodewords(e)-ECCode.getTotalCodewordsCount(e,r));for(o.getLengthInBits()+4<=n&&o.put(0,4);o.getLengthInBits()%8!=0;)o.putBit(0);for(var i=(n-o.getLengthInBits())/8,a=0;a<i;a++)o.put(a%2?17:236,8);return createCodewords(o,e,r)}function createCodewords(e,r,t){for(var o=Utils.getSymbolTotalCodewords(r),n=o-ECCode.getTotalCodewordsCount(r,t),i=ECCode.getBlocksCount(r,t),a=i-o%i,s=Math.floor(o/i),f=Math.floor(n/i),u=f+1,l=s-f,d=new ReedSolomonEncoder(l),m=0,c=new Array(i),g=new Array(i),v=0,p=BufferUtil.from(e.buffer),C=0;C<i;C++){var h=C<a?f:u;c[C]=p.slice(m,m+h),g[C]=d.encode(c[C]),m+=h,v=Math.max(v,h)}var w,S,B=BufferUtil.alloc(o),P=0;for(w=0;w<v;w++)for(S=0;S<i;S++)w<c[S].length&&(B[P++]=c[S][w]);for(w=0;w<l;w++)for(S=0;S<i;S++)B[P++]=g[S][w];return B}function createSymbol(e,r,t,o){var n;if(isArray(e))n=Segments.fromArray(e);else{if("string"!=typeof e)throw new Error("Invalid data");var i=r;if(!i){var a=Segments.rawSplit(e);i=Version.getBestVersionForData(a,t)}n=Segments.fromString(e,i||40)}var s=Version.getBestVersionForData(n,t);if(!s)throw new Error("The amount of data is too big to be stored in a QR Code");if(r){if(r<s)throw new Error("\nThe chosen QR Code version cannot contain this amount of data.\nMinimum version required to store current data is: "+s+".\n")}else r=s;var f=createData(r,t,n),u=Utils.getSymbolSize(r),l=new BitMatrix(u);return setupFinderPattern(l,r),setupTimingPattern(l),setupAlignmentPattern(l,r),setupFormatInfo(l,t,0),r>=7&&setupVersionInfo(l,r),setupData(l,f),isNaN(o)&&(o=MaskPattern.getBestMask(l,setupFormatInfo.bind(null,l,t))),MaskPattern.applyMask(o,l),setupFormatInfo(l,t,o),{modules:l,version:r,errorCorrectionLevel:t,maskPattern:o,segments:n}}exports.create=function(e,r){if(void 0===e||""===e)throw new Error("No input text");var t,o,n=ECLevel.M;return void 0!==r&&(n=ECLevel.from(r.errorCorrectionLevel,ECLevel.M),t=Version.from(r.version),o=MaskPattern.from(r.maskPattern),r.toSJISFunc&&Utils.setToSJISFunction(r.toSJISFunc)),createSymbol(e,t,n,o)};
\ No newline at end of file
index b7210b1..52b3356 100644 (file)
@@ -1,58 +1 @@
-var BufferUtil = require('../utils/buffer')
-var Polynomial = require('./polynomial')
-var Buffer = require('buffer').Buffer
-
-function ReedSolomonEncoder (degree) {
-  this.genPoly = undefined
-  this.degree = degree
-
-  if (this.degree) this.initialize(this.degree)
-}
-
-/**
- * Initialize the encoder.
- * The input param should correspond to the number of error correction codewords.
- *
- * @param  {Number} degree
- */
-ReedSolomonEncoder.prototype.initialize = function initialize (degree) {
-  // create an irreducible generator polynomial
-  this.degree = degree
-  this.genPoly = Polynomial.generateECPolynomial(this.degree)
-}
-
-/**
- * Encodes a chunk of data
- *
- * @param  {Buffer} data Buffer containing input data
- * @return {Buffer}      Buffer containing encoded data
- */
-ReedSolomonEncoder.prototype.encode = function encode (data) {
-  if (!this.genPoly) {
-    throw new Error('Encoder not initialized')
-  }
-
-  // Calculate EC for this data block
-  // extends data size to data+genPoly size
-  var pad = BufferUtil.alloc(this.degree)
-  var paddedData = Buffer.concat([data, pad], data.length + this.degree)
-
-  // The error correction codewords are the remainder after dividing the data codewords
-  // by a generator polynomial
-  var remainder = Polynomial.mod(paddedData, this.genPoly)
-
-  // return EC data blocks (last n byte, where n is the degree of genPoly)
-  // If coefficients number in remainder are less than genPoly degree,
-  // pad with 0s to the left to reach the needed number of coefficients
-  var start = this.degree - remainder.length
-  if (start > 0) {
-    var buff = BufferUtil.alloc(this.degree)
-    remainder.copy(buff, start)
-
-    return buff
-  }
-
-  return remainder
-}
-
-module.exports = ReedSolomonEncoder
+var BufferUtil=require("../utils/buffer"),Polynomial=require("./polynomial"),Buffer=require("buffer").Buffer;function ReedSolomonEncoder(e){this.genPoly=void 0,this.degree=e,this.degree&&this.initialize(this.degree)}ReedSolomonEncoder.prototype.initialize=function(e){this.degree=e,this.genPoly=Polynomial.generateECPolynomial(this.degree)},ReedSolomonEncoder.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");var o=BufferUtil.alloc(this.degree),i=Buffer.concat([e,o],e.length+this.degree),r=Polynomial.mod(i,this.genPoly),t=this.degree-r.length;if(t>0){var n=BufferUtil.alloc(this.degree);return r.copy(n,t),n}return r},module.exports=ReedSolomonEncoder;
\ No newline at end of file
index f68bed9..457d8a8 100644 (file)
@@ -1,31 +1 @@
-var numeric = '[0-9]+'
-var alphanumeric = '[A-Z $%*+\\-./:]+'
-var kanji = '(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|' +
-  '[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|' +
-  '[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|' +
-  '[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+'
-kanji = kanji.replace(/u/g, '\\u')
-
-var byte = '(?:(?![A-Z0-9 $%*+\\-./:]|' + kanji + ')(?:.|[\r\n]))+'
-
-exports.KANJI = new RegExp(kanji, 'g')
-exports.BYTE_KANJI = new RegExp('[^A-Z0-9 $%*+\\-./:]+', 'g')
-exports.BYTE = new RegExp(byte, 'g')
-exports.NUMERIC = new RegExp(numeric, 'g')
-exports.ALPHANUMERIC = new RegExp(alphanumeric, 'g')
-
-var TEST_KANJI = new RegExp('^' + kanji + '$')
-var TEST_NUMERIC = new RegExp('^' + numeric + '$')
-var TEST_ALPHANUMERIC = new RegExp('^[A-Z0-9 $%*+\\-./:]+$')
-
-exports.testKanji = function testKanji (str) {
-  return TEST_KANJI.test(str)
-}
-
-exports.testNumeric = function testNumeric (str) {
-  return TEST_NUMERIC.test(str)
-}
-
-exports.testAlphanumeric = function testAlphanumeric (str) {
-  return TEST_ALPHANUMERIC.test(str)
-}
+var numeric="[0-9]+",alphanumeric="[A-Z $%*+\\-./:]+",kanji="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+",byte="(?:(?![A-Z0-9 $%*+\\-./:]|"+(kanji=kanji.replace(/u/g,"\\u"))+")(?:.|[\r\n]))+";exports.KANJI=new RegExp(kanji,"g"),exports.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),exports.BYTE=new RegExp(byte,"g"),exports.NUMERIC=new RegExp(numeric,"g"),exports.ALPHANUMERIC=new RegExp(alphanumeric,"g");var TEST_KANJI=new RegExp("^"+kanji+"$"),TEST_NUMERIC=new RegExp("^"+numeric+"$"),TEST_ALPHANUMERIC=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");exports.testKanji=function(u){return TEST_KANJI.test(u)},exports.testNumeric=function(u){return TEST_NUMERIC.test(u)},exports.testAlphanumeric=function(u){return TEST_ALPHANUMERIC.test(u)};
\ No newline at end of file
index 15ceb66..57cb2b5 100644 (file)
@@ -1,330 +1 @@
-var Mode = require('./mode')
-var NumericData = require('./numeric-data')
-var AlphanumericData = require('./alphanumeric-data')
-var ByteData = require('./byte-data')
-var KanjiData = require('./kanji-data')
-var Regex = require('./regex')
-var Utils = require('./utils')
-var dijkstra = require('dijkstrajs')
-
-/**
- * Returns UTF8 byte length
- *
- * @param  {String} str Input string
- * @return {Number}     Number of byte
- */
-function getStringByteLength (str) {
-  return unescape(encodeURIComponent(str)).length
-}
-
-/**
- * Get a list of segments of the specified mode
- * from a string
- *
- * @param  {Mode}   mode Segment mode
- * @param  {String} str  String to process
- * @return {Array}       Array of object with segments data
- */
-function getSegments (regex, mode, str) {
-  var segments = []
-  var result
-
-  while ((result = regex.exec(str)) !== null) {
-    segments.push({
-      data: result[0],
-      index: result.index,
-      mode: mode,
-      length: result[0].length
-    })
-  }
-
-  return segments
-}
-
-/**
- * Extracts a series of segments with the appropriate
- * modes from a string
- *
- * @param  {String} dataStr Input string
- * @return {Array}          Array of object with segments data
- */
-function getSegmentsFromString (dataStr) {
-  var numSegs = getSegments(Regex.NUMERIC, Mode.NUMERIC, dataStr)
-  var alphaNumSegs = getSegments(Regex.ALPHANUMERIC, Mode.ALPHANUMERIC, dataStr)
-  var byteSegs
-  var kanjiSegs
-
-  if (Utils.isKanjiModeEnabled()) {
-    byteSegs = getSegments(Regex.BYTE, Mode.BYTE, dataStr)
-    kanjiSegs = getSegments(Regex.KANJI, Mode.KANJI, dataStr)
-  } else {
-    byteSegs = getSegments(Regex.BYTE_KANJI, Mode.BYTE, dataStr)
-    kanjiSegs = []
-  }
-
-  var segs = numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs)
-
-  return segs
-    .sort(function (s1, s2) {
-      return s1.index - s2.index
-    })
-    .map(function (obj) {
-      return {
-        data: obj.data,
-        mode: obj.mode,
-        length: obj.length
-      }
-    })
-}
-
-/**
- * Returns how many bits are needed to encode a string of
- * specified length with the specified mode
- *
- * @param  {Number} length String length
- * @param  {Mode} mode     Segment mode
- * @return {Number}        Bit length
- */
-function getSegmentBitsLength (length, mode) {
-  switch (mode) {
-    case Mode.NUMERIC:
-      return NumericData.getBitsLength(length)
-    case Mode.ALPHANUMERIC:
-      return AlphanumericData.getBitsLength(length)
-    case Mode.KANJI:
-      return KanjiData.getBitsLength(length)
-    case Mode.BYTE:
-      return ByteData.getBitsLength(length)
-  }
-}
-
-/**
- * Merges adjacent segments which have the same mode
- *
- * @param  {Array} segs Array of object with segments data
- * @return {Array}      Array of object with segments data
- */
-function mergeSegments (segs) {
-  return segs.reduce(function (acc, curr) {
-    var prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null
-    if (prevSeg && prevSeg.mode === curr.mode) {
-      acc[acc.length - 1].data += curr.data
-      return acc
-    }
-
-    acc.push(curr)
-    return acc
-  }, [])
-}
-
-/**
- * Generates a list of all possible nodes combination which
- * will be used to build a segments graph.
- *
- * Nodes are divided by groups. Each group will contain a list of all the modes
- * in which is possible to encode the given text.
- *
- * For example the text '12345' can be encoded as Numeric, Alphanumeric or Byte.
- * The group for '12345' will contain then 3 objects, one for each
- * possible encoding mode.
- *
- * Each node represents a possible segment.
- *
- * @param  {Array} segs Array of object with segments data
- * @return {Array}      Array of object with segments data
- */
-function buildNodes (segs) {
-  var nodes = []
-  for (var i = 0; i < segs.length; i++) {
-    var seg = segs[i]
-
-    switch (seg.mode) {
-      case Mode.NUMERIC:
-        nodes.push([seg,
-          { data: seg.data, mode: Mode.ALPHANUMERIC, length: seg.length },
-          { data: seg.data, mode: Mode.BYTE, length: seg.length }
-        ])
-        break
-      case Mode.ALPHANUMERIC:
-        nodes.push([seg,
-          { data: seg.data, mode: Mode.BYTE, length: seg.length }
-        ])
-        break
-      case Mode.KANJI:
-        nodes.push([seg,
-          { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }
-        ])
-        break
-      case Mode.BYTE:
-        nodes.push([
-          { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }
-        ])
-    }
-  }
-
-  return nodes
-}
-
-/**
- * Builds a graph from a list of nodes.
- * All segments in each node group will be connected with all the segments of
- * the next group and so on.
- *
- * At each connection will be assigned a weight depending on the
- * segment's byte length.
- *
- * @param  {Array} nodes    Array of object with segments data
- * @param  {Number} version QR Code version
- * @return {Object}         Graph of all possible segments
- */
-function buildGraph (nodes, version) {
-  var table = {}
-  var graph = {'start': {}}
-  var prevNodeIds = ['start']
-
-  for (var i = 0; i < nodes.length; i++) {
-    var nodeGroup = nodes[i]
-    var currentNodeIds = []
-
-    for (var j = 0; j < nodeGroup.length; j++) {
-      var node = nodeGroup[j]
-      var key = '' + i + j
-
-      currentNodeIds.push(key)
-      table[key] = { node: node, lastCount: 0 }
-      graph[key] = {}
-
-      for (var n = 0; n < prevNodeIds.length; n++) {
-        var prevNodeId = prevNodeIds[n]
-
-        if (table[prevNodeId] && table[prevNodeId].node.mode === node.mode) {
-          graph[prevNodeId][key] =
-            getSegmentBitsLength(table[prevNodeId].lastCount + node.length, node.mode) -
-            getSegmentBitsLength(table[prevNodeId].lastCount, node.mode)
-
-          table[prevNodeId].lastCount += node.length
-        } else {
-          if (table[prevNodeId]) table[prevNodeId].lastCount = node.length
-
-          graph[prevNodeId][key] = getSegmentBitsLength(node.length, node.mode) +
-            4 + Mode.getCharCountIndicator(node.mode, version) // switch cost
-        }
-      }
-    }
-
-    prevNodeIds = currentNodeIds
-  }
-
-  for (n = 0; n < prevNodeIds.length; n++) {
-    graph[prevNodeIds[n]]['end'] = 0
-  }
-
-  return { map: graph, table: table }
-}
-
-/**
- * Builds a segment from a specified data and mode.
- * If a mode is not specified, the more suitable will be used.
- *
- * @param  {String} data             Input data
- * @param  {Mode | String} modesHint Data mode
- * @return {Segment}                 Segment
- */
-function buildSingleSegment (data, modesHint) {
-  var mode
-  var bestMode = Mode.getBestModeForData(data)
-
-  mode = Mode.from(modesHint, bestMode)
-
-  // Make sure data can be encoded
-  if (mode !== Mode.BYTE && mode.bit < bestMode.bit) {
-    throw new Error('"' + data + '"' +
-      ' cannot be encoded with mode ' + Mode.toString(mode) +
-      '.\n Suggested mode is: ' + Mode.toString(bestMode))
-  }
-
-  // Use Mode.BYTE if Kanji support is disabled
-  if (mode === Mode.KANJI && !Utils.isKanjiModeEnabled()) {
-    mode = Mode.BYTE
-  }
-
-  switch (mode) {
-    case Mode.NUMERIC:
-      return new NumericData(data)
-
-    case Mode.ALPHANUMERIC:
-      return new AlphanumericData(data)
-
-    case Mode.KANJI:
-      return new KanjiData(data)
-
-    case Mode.BYTE:
-      return new ByteData(data)
-  }
-}
-
-/**
- * Builds a list of segments from an array.
- * Array can contain Strings or Objects with segment's info.
- *
- * For each item which is a string, will be generated a segment with the given
- * string and the more appropriate encoding mode.
- *
- * For each item which is an object, will be generated a segment with the given
- * data and mode.
- * Objects must contain at least the property "data".
- * If property "mode" is not present, the more suitable mode will be used.
- *
- * @param  {Array} array Array of objects with segments data
- * @return {Array}       Array of Segments
- */
-exports.fromArray = function fromArray (array) {
-  return array.reduce(function (acc, seg) {
-    if (typeof seg === 'string') {
-      acc.push(buildSingleSegment(seg, null))
-    } else if (seg.data) {
-      acc.push(buildSingleSegment(seg.data, seg.mode))
-    }
-
-    return acc
-  }, [])
-}
-
-/**
- * Builds an optimized sequence of segments from a string,
- * which will produce the shortest possible bitstream.
- *
- * @param  {String} data    Input string
- * @param  {Number} version QR Code version
- * @return {Array}          Array of segments
- */
-exports.fromString = function fromString (data, version) {
-  var segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled())
-
-  var nodes = buildNodes(segs)
-  var graph = buildGraph(nodes, version)
-  var path = dijkstra.find_path(graph.map, 'start', 'end')
-
-  var optimizedSegs = []
-  for (var i = 1; i < path.length - 1; i++) {
-    optimizedSegs.push(graph.table[path[i]].node)
-  }
-
-  return exports.fromArray(mergeSegments(optimizedSegs))
-}
-
-/**
- * Splits a string in various segments with the modes which
- * best represent their content.
- * The produced segments are far from being optimized.
- * The output of this function is only used to estimate a QR Code version
- * which may contain the data.
- *
- * @param  {string} data Input string
- * @return {Array}       Array of segments
- */
-exports.rawSplit = function rawSplit (data) {
-  return exports.fromArray(
-    getSegmentsFromString(data, Utils.isKanjiModeEnabled())
-  )
-}
+var Mode=require("./mode"),NumericData=require("./numeric-data"),AlphanumericData=require("./alphanumeric-data"),ByteData=require("./byte-data"),KanjiData=require("./kanji-data"),Regex=require("./regex"),Utils=require("./utils"),dijkstra=require("dijkstrajs");function getStringByteLength(e){return unescape(encodeURIComponent(e)).length}function getSegments(e,t,n){for(var a,r=[];null!==(a=e.exec(n));)r.push({data:a[0],index:a.index,mode:t,length:a[0].length});return r}function getSegmentsFromString(e){var t,n,a=getSegments(Regex.NUMERIC,Mode.NUMERIC,e),r=getSegments(Regex.ALPHANUMERIC,Mode.ALPHANUMERIC,e);return Utils.isKanjiModeEnabled()?(t=getSegments(Regex.BYTE,Mode.BYTE,e),n=getSegments(Regex.KANJI,Mode.KANJI,e)):(t=getSegments(Regex.BYTE_KANJI,Mode.BYTE,e),n=[]),a.concat(r,t,n).sort((function(e,t){return e.index-t.index})).map((function(e){return{data:e.data,mode:e.mode,length:e.length}}))}function getSegmentBitsLength(e,t){switch(t){case Mode.NUMERIC:return NumericData.getBitsLength(e);case Mode.ALPHANUMERIC:return AlphanumericData.getBitsLength(e);case Mode.KANJI:return KanjiData.getBitsLength(e);case Mode.BYTE:return ByteData.getBitsLength(e)}}function mergeSegments(e){return e.reduce((function(e,t){var n=e.length-1>=0?e[e.length-1]:null;return n&&n.mode===t.mode?(e[e.length-1].data+=t.data,e):(e.push(t),e)}),[])}function buildNodes(e){for(var t=[],n=0;n<e.length;n++){var a=e[n];switch(a.mode){case Mode.NUMERIC:t.push([a,{data:a.data,mode:Mode.ALPHANUMERIC,length:a.length},{data:a.data,mode:Mode.BYTE,length:a.length}]);break;case Mode.ALPHANUMERIC:t.push([a,{data:a.data,mode:Mode.BYTE,length:a.length}]);break;case Mode.KANJI:t.push([a,{data:a.data,mode:Mode.BYTE,length:getStringByteLength(a.data)}]);break;case Mode.BYTE:t.push([{data:a.data,mode:Mode.BYTE,length:getStringByteLength(a.data)}])}}return t}function buildGraph(e,t){for(var n={},a={start:{}},r=["start"],o=0;o<e.length;o++){for(var d=e[o],g=[],i=0;i<d.length;i++){var u=d[i],s=""+o+i;g.push(s),n[s]={node:u,lastCount:0},a[s]={};for(var l=0;l<r.length;l++){var m=r[l];n[m]&&n[m].node.mode===u.mode?(a[m][s]=getSegmentBitsLength(n[m].lastCount+u.length,u.mode)-getSegmentBitsLength(n[m].lastCount,u.mode),n[m].lastCount+=u.length):(n[m]&&(n[m].lastCount=u.length),a[m][s]=getSegmentBitsLength(u.length,u.mode)+4+Mode.getCharCountIndicator(u.mode,t))}}r=g}for(l=0;l<r.length;l++)a[r[l]].end=0;return{map:a,table:n}}function buildSingleSegment(e,t){var n,a=Mode.getBestModeForData(e);if((n=Mode.from(t,a))!==Mode.BYTE&&n.bit<a.bit)throw new Error('"'+e+'" cannot be encoded with mode '+Mode.toString(n)+".\n Suggested mode is: "+Mode.toString(a));switch(n!==Mode.KANJI||Utils.isKanjiModeEnabled()||(n=Mode.BYTE),n){case Mode.NUMERIC:return new NumericData(e);case Mode.ALPHANUMERIC:return new AlphanumericData(e);case Mode.KANJI:return new KanjiData(e);case Mode.BYTE:return new ByteData(e)}}exports.fromArray=function(e){return e.reduce((function(e,t){return"string"==typeof t?e.push(buildSingleSegment(t,null)):t.data&&e.push(buildSingleSegment(t.data,t.mode)),e}),[])},exports.fromString=function(e,t){for(var n=buildGraph(buildNodes(getSegmentsFromString(e,Utils.isKanjiModeEnabled())),t),a=dijkstra.find_path(n.map,"start","end"),r=[],o=1;o<a.length-1;o++)r.push(n.table[a[o]].node);return exports.fromArray(mergeSegments(r))},exports.rawSplit=function(e){return exports.fromArray(getSegmentsFromString(e,Utils.isKanjiModeEnabled()))};
\ No newline at end of file
index 864bc8e..fa841ba 100644 (file)
@@ -1,63 +1 @@
-var toSJISFunction
-var CODEWORDS_COUNT = [
-  0, // Not used
-  26, 44, 70, 100, 134, 172, 196, 242, 292, 346,
-  404, 466, 532, 581, 655, 733, 815, 901, 991, 1085,
-  1156, 1258, 1364, 1474, 1588, 1706, 1828, 1921, 2051, 2185,
-  2323, 2465, 2611, 2761, 2876, 3034, 3196, 3362, 3532, 3706
-]
-
-/**
- * Returns the QR Code size for the specified version
- *
- * @param  {Number} version QR Code version
- * @return {Number}         size of QR code
- */
-exports.getSymbolSize = function getSymbolSize (version) {
-  if (!version) throw new Error('"version" cannot be null or undefined')
-  if (version < 1 || version > 40) throw new Error('"version" should be in range from 1 to 40')
-  return version * 4 + 17
-}
-
-/**
- * Returns the total number of codewords used to store data and EC information.
- *
- * @param  {Number} version QR Code version
- * @return {Number}         Data length in bits
- */
-exports.getSymbolTotalCodewords = function getSymbolTotalCodewords (version) {
-  return CODEWORDS_COUNT[version]
-}
-
-/**
- * Encode data with Bose-Chaudhuri-Hocquenghem
- *
- * @param  {Number} data Value to encode
- * @return {Number}      Encoded value
- */
-exports.getBCHDigit = function (data) {
-  var digit = 0
-
-  while (data !== 0) {
-    digit++
-    data >>>= 1
-  }
-
-  return digit
-}
-
-exports.setToSJISFunction = function setToSJISFunction (f) {
-  if (typeof f !== 'function') {
-    throw new Error('"toSJISFunc" is not a valid function.')
-  }
-
-  toSJISFunction = f
-}
-
-exports.isKanjiModeEnabled = function () {
-  return typeof toSJISFunction !== 'undefined'
-}
-
-exports.toSJIS = function toSJIS (kanji) {
-  return toSJISFunction(kanji)
-}
+var toSJISFunction,CODEWORDS_COUNT=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];exports.getSymbolSize=function(o){if(!o)throw new Error('"version" cannot be null or undefined');if(o<1||o>40)throw new Error('"version" should be in range from 1 to 40');return 4*o+17},exports.getSymbolTotalCodewords=function(o){return CODEWORDS_COUNT[o]},exports.getBCHDigit=function(o){for(var n=0;0!==o;)n++,o>>>=1;return n},exports.setToSJISFunction=function(o){if("function"!=typeof o)throw new Error('"toSJISFunc" is not a valid function.');toSJISFunction=o},exports.isKanjiModeEnabled=function(){return void 0!==toSJISFunction},exports.toSJIS=function(o){return toSJISFunction(o)};
\ No newline at end of file
index dd32b5a..02c38c9 100644 (file)
@@ -1,9 +1 @@
-/**
- * Check if QR Code version is valid
- *
- * @param  {Number}  version QR Code version
- * @return {Boolean}         true if valid version, false otherwise
- */
-exports.isValid = function isValid (version) {
-  return !isNaN(version) && version >= 1 && version <= 40
-}
+exports.isValid=function(i){return!isNaN(i)&&i>=1&&i<=40};
\ No newline at end of file
index 8baaa55..637424a 100755 (executable)
@@ -1,164 +1 @@
-var Utils = require('./utils')
-var ECCode = require('./error-correction-code')
-var ECLevel = require('./error-correction-level')
-var Mode = require('./mode')
-var VersionCheck = require('./version-check')
-var isArray = require('isarray')
-
-// Generator polynomial used to encode version information
-var G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0)
-var G18_BCH = Utils.getBCHDigit(G18)
-
-function getBestVersionForDataLength (mode, length, errorCorrectionLevel) {
-  for (var currentVersion = 1; currentVersion <= 40; currentVersion++) {
-    if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, mode)) {
-      return currentVersion
-    }
-  }
-
-  return undefined
-}
-
-function getReservedBitsCount (mode, version) {
-  // Character count indicator + mode indicator bits
-  return Mode.getCharCountIndicator(mode, version) + 4
-}
-
-function getTotalBitsFromDataArray (segments, version) {
-  var totalBits = 0
-
-  segments.forEach(function (data) {
-    var reservedBits = getReservedBitsCount(data.mode, version)
-    totalBits += reservedBits + data.getBitsLength()
-  })
-
-  return totalBits
-}
-
-function getBestVersionForMixedData (segments, errorCorrectionLevel) {
-  for (var currentVersion = 1; currentVersion <= 40; currentVersion++) {
-    var length = getTotalBitsFromDataArray(segments, currentVersion)
-    if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, Mode.MIXED)) {
-      return currentVersion
-    }
-  }
-
-  return undefined
-}
-
-/**
- * Returns version number from a value.
- * If value is not a valid version, returns defaultValue
- *
- * @param  {Number|String} value        QR Code version
- * @param  {Number}        defaultValue Fallback value
- * @return {Number}                     QR Code version number
- */
-exports.from = function from (value, defaultValue) {
-  if (VersionCheck.isValid(value)) {
-    return parseInt(value, 10)
-  }
-
-  return defaultValue
-}
-
-/**
- * Returns how much data can be stored with the specified QR code version
- * and error correction level
- *
- * @param  {Number} version              QR Code version (1-40)
- * @param  {Number} errorCorrectionLevel Error correction level
- * @param  {Mode}   mode                 Data mode
- * @return {Number}                      Quantity of storable data
- */
-exports.getCapacity = function getCapacity (version, errorCorrectionLevel, mode) {
-  if (!VersionCheck.isValid(version)) {
-    throw new Error('Invalid QR Code version')
-  }
-
-  // Use Byte mode as default
-  if (typeof mode === 'undefined') mode = Mode.BYTE
-
-  // Total codewords for this QR code version (Data + Error correction)
-  var totalCodewords = Utils.getSymbolTotalCodewords(version)
-
-  // Total number of error correction codewords
-  var ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)
-
-  // Total number of data codewords
-  var dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8
-
-  if (mode === Mode.MIXED) return dataTotalCodewordsBits
-
-  var usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode, version)
-
-  // Return max number of storable codewords
-  switch (mode) {
-    case Mode.NUMERIC:
-      return Math.floor((usableBits / 10) * 3)
-
-    case Mode.ALPHANUMERIC:
-      return Math.floor((usableBits / 11) * 2)
-
-    case Mode.KANJI:
-      return Math.floor(usableBits / 13)
-
-    case Mode.BYTE:
-    default:
-      return Math.floor(usableBits / 8)
-  }
-}
-
-/**
- * Returns the minimum version needed to contain the amount of data
- *
- * @param  {Segment} data                    Segment of data
- * @param  {Number} [errorCorrectionLevel=H] Error correction level
- * @param  {Mode} mode                       Data mode
- * @return {Number}                          QR Code version
- */
-exports.getBestVersionForData = function getBestVersionForData (data, errorCorrectionLevel) {
-  var seg
-
-  var ecl = ECLevel.from(errorCorrectionLevel, ECLevel.M)
-
-  if (isArray(data)) {
-    if (data.length > 1) {
-      return getBestVersionForMixedData(data, ecl)
-    }
-
-    if (data.length === 0) {
-      return 1
-    }
-
-    seg = data[0]
-  } else {
-    seg = data
-  }
-
-  return getBestVersionForDataLength(seg.mode, seg.getLength(), ecl)
-}
-
-/**
- * Returns version information with relative error correction bits
- *
- * The version information is included in QR Code symbols of version 7 or larger.
- * It consists of an 18-bit sequence containing 6 data bits,
- * with 12 error correction bits calculated using the (18, 6) Golay code.
- *
- * @param  {Number} version QR Code version
- * @return {Number}         Encoded version info bits
- */
-exports.getEncodedBits = function getEncodedBits (version) {
-  if (!VersionCheck.isValid(version) || version < 7) {
-    throw new Error('Invalid QR Code version')
-  }
-
-  var d = version << 12
-
-  while (Utils.getBCHDigit(d) - G18_BCH >= 0) {
-    d ^= (G18 << (Utils.getBCHDigit(d) - G18_BCH))
-  }
-
-  return (version << 12) | d
-}
+var Utils=require("./utils"),ECCode=require("./error-correction-code"),ECLevel=require("./error-correction-level"),Mode=require("./mode"),VersionCheck=require("./version-check"),isArray=require("isarray"),G18=7973,G18_BCH=Utils.getBCHDigit(G18);function getBestVersionForDataLength(e,r,t){for(var o=1;o<=40;o++)if(r<=exports.getCapacity(o,t,e))return o}function getReservedBitsCount(e,r){return Mode.getCharCountIndicator(e,r)+4}function getTotalBitsFromDataArray(e,r){var t=0;return e.forEach((function(e){var o=getReservedBitsCount(e.mode,r);t+=o+e.getBitsLength()})),t}function getBestVersionForMixedData(e,r){for(var t=1;t<=40;t++){if(getTotalBitsFromDataArray(e,t)<=exports.getCapacity(t,r,Mode.MIXED))return t}}exports.from=function(e,r){return VersionCheck.isValid(e)?parseInt(e,10):r},exports.getCapacity=function(e,r,t){if(!VersionCheck.isValid(e))throw new Error("Invalid QR Code version");void 0===t&&(t=Mode.BYTE);var o=8*(Utils.getSymbolTotalCodewords(e)-ECCode.getTotalCodewordsCount(e,r));if(t===Mode.MIXED)return o;var i=o-getReservedBitsCount(t,e);switch(t){case Mode.NUMERIC:return Math.floor(i/10*3);case Mode.ALPHANUMERIC:return Math.floor(i/11*2);case Mode.KANJI:return Math.floor(i/13);case Mode.BYTE:default:return Math.floor(i/8)}},exports.getBestVersionForData=function(e,r){var t,o=ECLevel.from(r,ECLevel.M);if(isArray(e)){if(e.length>1)return getBestVersionForMixedData(e,o);if(0===e.length)return 1;t=e[0]}else t=e;return getBestVersionForDataLength(t.mode,t.getLength(),o)},exports.getEncodedBits=function(e){if(!VersionCheck.isValid(e)||e<7)throw new Error("Invalid QR Code version");for(var r=e<<12;Utils.getBCHDigit(r)-G18_BCH>=0;)r^=G18<<Utils.getBCHDigit(r)-G18_BCH;return e<<12|r};
\ No newline at end of file
index 57c8f70..9a5c36c 100644 (file)
@@ -1,12 +1 @@
-/*
-*copyright Ryan Day 2012
-*
-* Licensed under the MIT license:
-*   http://www.opensource.org/licenses/mit-license.php
-*
-* this is the main server side application file for node-qrcode.
-* these exports use serverside canvas api methods for file IO and buffers
-*
-*/
-
-module.exports = require('./server')
+module.exports=require("./server");
\ No newline at end of file
index 34fb6e7..38b29b0 100644 (file)
@@ -1,63 +1 @@
-var Utils = require('./utils')
-
-function clearCanvas (ctx, canvas, size) {
-  ctx.clearRect(0, 0, canvas.width, canvas.height)
-
-  if (!canvas.style) canvas.style = {}
-  canvas.height = size
-  canvas.width = size
-  canvas.style.height = size + 'px'
-  canvas.style.width = size + 'px'
-}
-
-function getCanvasElement () {
-  try {
-    return document.createElement('canvas')
-  } catch (e) {
-    throw new Error('You need to specify a canvas element')
-  }
-}
-
-exports.render = function render (qrData, canvas, options) {
-  var opts = options
-  var canvasEl = canvas
-
-  if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {
-    opts = canvas
-    canvas = undefined
-  }
-
-  if (!canvas) {
-    canvasEl = getCanvasElement()
-  }
-
-  opts = Utils.getOptions(opts)
-  var size = Utils.getImageWidth(qrData.modules.size, opts)
-
-  var ctx = canvasEl.getContext('2d')
-  var image = ctx.createImageData(size, size)
-  Utils.qrToImageData(image.data, qrData, opts)
-
-  clearCanvas(ctx, canvasEl, size)
-  ctx.putImageData(image, 0, 0)
-
-  return canvasEl
-}
-
-exports.renderToDataURL = function renderToDataURL (qrData, canvas, options) {
-  var opts = options
-
-  if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {
-    opts = canvas
-    canvas = undefined
-  }
-
-  if (!opts) opts = {}
-
-  var canvasEl = exports.render(qrData, canvas, opts)
-
-  var type = opts.type || 'image/png'
-  var rendererOpts = opts.rendererOpts || {}
-
-  return canvasEl.toDataURL(type, rendererOpts.quality)
-}
+var Utils=require("./utils");function clearCanvas(e,t,a){e.clearRect(0,0,t.width,t.height),t.style||(t.style={}),t.height=a,t.width=a,t.style.height=a+"px",t.style.width=a+"px"}function getCanvasElement(){try{return document.createElement("canvas")}catch(e){throw new Error("You need to specify a canvas element")}}exports.render=function(e,t,a){var r=a,n=t;void 0!==r||t&&t.getContext||(r=t,t=void 0),t||(n=getCanvasElement()),r=Utils.getOptions(r);var i=Utils.getImageWidth(e.modules.size,r),o=n.getContext("2d"),s=o.createImageData(i,i);return Utils.qrToImageData(s.data,e,r),clearCanvas(o,n,i),o.putImageData(s,0,0),n},exports.renderToDataURL=function(e,t,a){var r=a;void 0!==r||t&&t.getContext||(r=t,t=void 0),r||(r={});var n=exports.render(e,t,r),i=r.type||"image/png",o=r.rendererOpts||{};return n.toDataURL(i,o.quality)};
\ No newline at end of file
index 00d8a33..f7bc8fe 100644 (file)
@@ -1,71 +1 @@
-var fs = require('fs')
-var PNG = require('pngjs').PNG
-var Utils = require('./utils')
-
-exports.render = function render (qrData, options) {
-  var opts = Utils.getOptions(options)
-  var pngOpts = opts.rendererOpts
-  var size = Utils.getImageWidth(qrData.modules.size, opts)
-
-  pngOpts.width = size
-  pngOpts.height = size
-
-  var pngImage = new PNG(pngOpts)
-  Utils.qrToImageData(pngImage.data, qrData, opts)
-
-  return pngImage
-}
-
-exports.renderToDataURL = function renderToDataURL (qrData, options, cb) {
-  if (typeof cb === 'undefined') {
-    cb = options
-    options = undefined
-  }
-
-  exports.renderToBuffer(qrData, options, function (err, output) {
-    if (err) cb(err)
-    var url = 'data:image/png;base64,'
-    url += output.toString('base64')
-    cb(null, url)
-  })
-}
-
-exports.renderToBuffer = function renderToBuffer (qrData, options, cb) {
-  if (typeof cb === 'undefined') {
-    cb = options
-    options = undefined
-  }
-
-  var png = exports.render(qrData, options)
-  var buffer = []
-
-  png.on('error', cb)
-
-  png.on('data', function (data) {
-    buffer.push(data)
-  })
-
-  png.on('end', function () {
-    cb(null, Buffer.concat(buffer))
-  })
-
-  png.pack()
-}
-
-exports.renderToFile = function renderToFile (path, qrData, options, cb) {
-  if (typeof cb === 'undefined') {
-    cb = options
-    options = undefined
-  }
-
-  var stream = fs.createWriteStream(path)
-  stream.on('error', cb)
-  stream.on('close', cb)
-
-  exports.renderToFileStream(stream, qrData, options)
-}
-
-exports.renderToFileStream = function renderToFileStream (stream, qrData, options) {
-  var png = exports.render(qrData, options)
-  png.pack().pipe(stream)
-}
+var fs=require("fs"),PNG=require("pngjs").PNG,Utils=require("./utils");exports.render=function(e,r){var t=Utils.getOptions(r),o=t.rendererOpts,n=Utils.getImageWidth(e.modules.size,t);o.width=n,o.height=n;var i=new PNG(o);return Utils.qrToImageData(i.data,e,t),i},exports.renderToDataURL=function(e,r,t){void 0===t&&(t=r,r=void 0),exports.renderToBuffer(e,r,(function(e,r){e&&t(e);var o="data:image/png;base64,";o+=r.toString("base64"),t(null,o)}))},exports.renderToBuffer=function(e,r,t){void 0===t&&(t=r,r=void 0);var o=exports.render(e,r),n=[];o.on("error",t),o.on("data",(function(e){n.push(e)})),o.on("end",(function(){t(null,Buffer.concat(n))})),o.pack()},exports.renderToFile=function(e,r,t,o){void 0===o&&(o=t,t=void 0);var n=fs.createWriteStream(e);n.on("error",o),n.on("close",o),exports.renderToFileStream(n,r,t)},exports.renderToFileStream=function(e,r,t){exports.render(r,t).pack().pipe(e)};
\ No newline at end of file
index 2e55115..d15fd39 100644 (file)
@@ -1,81 +1 @@
-var Utils = require('./utils')
-
-function getColorAttrib (color, attrib) {
-  var alpha = color.a / 255
-  var str = attrib + '="' + color.hex + '"'
-
-  return alpha < 1
-    ? str + ' ' + attrib + '-opacity="' + alpha.toFixed(2).slice(1) + '"'
-    : str
-}
-
-function svgCmd (cmd, x, y) {
-  var str = cmd + x
-  if (typeof y !== 'undefined') str += ' ' + y
-
-  return str
-}
-
-function qrToPath (data, size, margin) {
-  var path = ''
-  var moveBy = 0
-  var newRow = false
-  var lineLength = 0
-
-  for (var i = 0; i < data.length; i++) {
-    var col = Math.floor(i % size)
-    var row = Math.floor(i / size)
-
-    if (!col && !newRow) newRow = true
-
-    if (data[i]) {
-      lineLength++
-
-      if (!(i > 0 && col > 0 && data[i - 1])) {
-        path += newRow
-          ? svgCmd('M', col + margin, 0.5 + row + margin)
-          : svgCmd('m', moveBy, 0)
-
-        moveBy = 0
-        newRow = false
-      }
-
-      if (!(col + 1 < size && data[i + 1])) {
-        path += svgCmd('h', lineLength)
-        lineLength = 0
-      }
-    } else {
-      moveBy++
-    }
-  }
-
-  return path
-}
-
-exports.render = function render (qrData, options, cb) {
-  var opts = Utils.getOptions(options)
-  var size = qrData.modules.size
-  var data = qrData.modules.data
-  var qrcodesize = size + opts.margin * 2
-
-  var bg = !opts.color.light.a
-    ? ''
-    : '<path ' + getColorAttrib(opts.color.light, 'fill') +
-      ' d="M0 0h' + qrcodesize + 'v' + qrcodesize + 'H0z"/>'
-
-  var path =
-    '<path ' + getColorAttrib(opts.color.dark, 'stroke') +
-    ' d="' + qrToPath(data, size, opts.margin) + '"/>'
-
-  var viewBox = 'viewBox="' + '0 0 ' + qrcodesize + ' ' + qrcodesize + '"'
-
-  var width = !opts.width ? '' : 'width="' + opts.width + '" height="' + opts.width + '" '
-
-  var svgTag = '<svg xmlns="http://www.w3.org/2000/svg" ' + width + viewBox + ' shape-rendering="crispEdges">' + bg + path + '</svg>\n'
-
-  if (typeof cb === 'function') {
-    cb(null, svgTag)
-  }
-
-  return svgTag
-}
+var Utils=require("./utils");function getColorAttrib(t,r){var o=t.a/255,i=r+'="'+t.hex+'"';return o<1?i+" "+r+'-opacity="'+o.toFixed(2).slice(1)+'"':i}function svgCmd(t,r,o){var i=t+r;return void 0!==o&&(i+=" "+o),i}function qrToPath(t,r,o){for(var i="",e=0,n=!1,l=0,a=0;a<t.length;a++){var s=Math.floor(a%r),g=Math.floor(a/r);s||n||(n=!0),t[a]?(l++,a>0&&s>0&&t[a-1]||(i+=n?svgCmd("M",s+o,.5+g+o):svgCmd("m",e,0),e=0,n=!1),s+1<r&&t[a+1]||(i+=svgCmd("h",l),l=0)):e++}return i}exports.render=function(t,r,o){var i=Utils.getOptions(r),e=t.modules.size,n=t.modules.data,l=e+2*i.margin,a=i.color.light.a?"<path "+getColorAttrib(i.color.light,"fill")+' d="M0 0h'+l+"v"+l+'H0z"/>':"",s="<path "+getColorAttrib(i.color.dark,"stroke")+' d="'+qrToPath(n,e,i.margin)+'"/>',g='viewBox="0 0 '+l+" "+l+'"',h='<svg xmlns="http://www.w3.org/2000/svg" '+(i.width?'width="'+i.width+'" height="'+i.width+'" ':"")+g+' shape-rendering="crispEdges">'+a+s+"</svg>\n";return"function"==typeof o&&o(null,h),h};
\ No newline at end of file
index 65715cc..6c258a4 100644 (file)
@@ -1,19 +1 @@
-var svgTagRenderer = require('./svg-tag')
-
-exports.render = svgTagRenderer.render
-
-exports.renderToFile = function renderToFile (path, qrData, options, cb) {
-  if (typeof cb === 'undefined') {
-    cb = options
-    options = undefined
-  }
-
-  var fs = require('fs')
-  var svgTag = exports.render(qrData, options)
-
-  var xmlStr = '<?xml version="1.0" encoding="utf-8"?>' +
-    '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">' +
-    svgTag
-
-  fs.writeFile(path, xmlStr, cb)
-}
+var svgTagRenderer=require("./svg-tag");exports.render=svgTagRenderer.render,exports.renderToFile=function(e,r,d,i){void 0===i&&(i=d,d=void 0);var n=require("fs"),s='<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'+exports.render(r,d);n.writeFile(e,s,i)};
\ No newline at end of file
index f04f2c3..12c422a 100644 (file)
@@ -1,49 +1 @@
-// var Utils = require('./utils')
-
-exports.render = function (qrData, options, cb) {
-  var size = qrData.modules.size
-  var data = qrData.modules.data
-
-  // var opts = Utils.getOptions(options)
-
-  // use same scheme as https://github.com/gtanner/qrcode-terminal because it actually works! =)
-  var black = '\x1b[40m  \x1b[0m'
-  var white = '\x1b[47m  \x1b[0m'
-
-  var output = ''
-  var hMargin = Array(size + 3).join(white)
-  var vMargin = Array(2).join(white)
-
-  output += hMargin + '\n'
-  for (var i = 0; i < size; ++i) {
-    output += white
-    for (var j = 0; j < size; j++) {
-      // var topModule = data[i * size + j]
-      // var bottomModule = data[(i + 1) * size + j]
-
-      output += data[i * size + j] ? black : white// getBlockChar(topModule, bottomModule)
-    }
-    // output += white+'\n'
-    output += vMargin + '\n'
-  }
-
-  output += hMargin + '\n'
-
-  if (typeof cb === 'function') {
-    cb(null, output)
-  }
-
-  return output
-}
-/*
-exports.renderToFile = function renderToFile (path, qrData, options, cb) {
-  if (typeof cb === 'undefined') {
-    cb = options
-    options = undefined
-  }
-
-  var fs = require('fs')
-  var utf8 = exports.render(qrData, options)
-  fs.writeFile(path, utf8, cb)
-}
-*/
+exports.render=function(r,n,o){var e=r.modules.size,a=r.modules.data,m="\e[47m  \e[0m",t="",u=Array(e+3).join(m),f=Array(2).join(m);t+=u+"\n";for(var i=0;i<e;++i){t+=m;for(var d=0;d<e;d++)t+=a[i*e+d]?"\e[40m  \e[0m":m;t+=f+"\n"}return t+=u+"\n","function"==typeof o&&o(null,t),t};
\ No newline at end of file
index 4181ecd..2e73efa 100644 (file)
@@ -1,71 +1 @@
-var Utils = require('./utils')
-
-var BLOCK_CHAR = {
-  WW: ' ',
-  WB: '▄',
-  BB: '█',
-  BW: '▀'
-}
-
-var INVERTED_BLOCK_CHAR = {
-  BB: ' ',
-  BW: '▄',
-  WW: '█',
-  WB: '▀'
-}
-
-function getBlockChar (top, bottom, blocks) {
-  if (top && bottom) return blocks.BB
-  if (top && !bottom) return blocks.BW
-  if (!top && bottom) return blocks.WB
-  return blocks.WW
-}
-
-exports.render = function (qrData, options, cb) {
-  var opts = Utils.getOptions(options)
-  var blocks = BLOCK_CHAR
-  if (opts.color.dark.hex === '#ffffff' || opts.color.light.hex === '#000000') {
-    blocks = INVERTED_BLOCK_CHAR
-  }
-
-  var size = qrData.modules.size
-  var data = qrData.modules.data
-
-  var output = ''
-  var hMargin = Array(size + (opts.margin * 2) + 1).join(blocks.WW)
-  hMargin = Array((opts.margin / 2) + 1).join(hMargin + '\n')
-
-  var vMargin = Array(opts.margin + 1).join(blocks.WW)
-
-  output += hMargin
-  for (var i = 0; i < size; i += 2) {
-    output += vMargin
-    for (var j = 0; j < size; j++) {
-      var topModule = data[i * size + j]
-      var bottomModule = data[(i + 1) * size + j]
-
-      output += getBlockChar(topModule, bottomModule, blocks)
-    }
-
-    output += vMargin + '\n'
-  }
-
-  output += hMargin.slice(0, -1)
-
-  if (typeof cb === 'function') {
-    cb(null, output)
-  }
-
-  return output
-}
-
-exports.renderToFile = function renderToFile (path, qrData, options, cb) {
-  if (typeof cb === 'undefined') {
-    cb = options
-    options = undefined
-  }
-
-  var fs = require('fs')
-  var utf8 = exports.render(qrData, options)
-  fs.writeFile(path, utf8, cb)
-}
+var Utils=require("./utils"),BLOCK_CHAR={WW:" ",WB:"▄",BB:"█",BW:"▀"},INVERTED_BLOCK_CHAR={BB:" ",BW:"▄",WW:"█",WB:"▀"};function getBlockChar(r,e,o){return r&&e?o.BB:r&&!e?o.BW:!r&&e?o.WB:o.WW}exports.render=function(r,e,o){var i=Utils.getOptions(e),n=BLOCK_CHAR;"#ffffff"!==i.color.dark.hex&&"#000000"!==i.color.light.hex||(n=INVERTED_BLOCK_CHAR);var t=r.modules.size,a=r.modules.data,B="",W=Array(t+2*i.margin+1).join(n.WW);W=Array(i.margin/2+1).join(W+"\n");var l=Array(i.margin+1).join(n.WW);B+=W;for(var f=0;f<t;f+=2){B+=l;for(var s=0;s<t;s++){B+=getBlockChar(a[f*t+s],a[(f+1)*t+s],n)}B+=l+"\n"}return B+=W.slice(0,-1),"function"==typeof o&&o(null,B),B},exports.renderToFile=function(r,e,o,i){void 0===i&&(i=o,o=void 0);var n=require("fs"),t=exports.render(e,o);n.writeFile(r,t,i)};
\ No newline at end of file
index 633136d..8bc81f8 100644 (file)
@@ -1,97 +1 @@
-function hex2rgba (hex) {
-  if (typeof hex === 'number') {
-    hex = hex.toString()
-  }
-
-  if (typeof hex !== 'string') {
-    throw new Error('Color should be defined as hex string')
-  }
-
-  var hexCode = hex.slice().replace('#', '').split('')
-  if (hexCode.length < 3 || hexCode.length === 5 || hexCode.length > 8) {
-    throw new Error('Invalid hex color: ' + hex)
-  }
-
-  // Convert from short to long form (fff -> ffffff)
-  if (hexCode.length === 3 || hexCode.length === 4) {
-    hexCode = Array.prototype.concat.apply([], hexCode.map(function (c) {
-      return [c, c]
-    }))
-  }
-
-  // Add default alpha value
-  if (hexCode.length === 6) hexCode.push('F', 'F')
-
-  var hexValue = parseInt(hexCode.join(''), 16)
-
-  return {
-    r: (hexValue >> 24) & 255,
-    g: (hexValue >> 16) & 255,
-    b: (hexValue >> 8) & 255,
-    a: hexValue & 255,
-    hex: '#' + hexCode.slice(0, 6).join('')
-  }
-}
-
-exports.getOptions = function getOptions (options) {
-  if (!options) options = {}
-  if (!options.color) options.color = {}
-
-  var margin = typeof options.margin === 'undefined' ||
-    options.margin === null ||
-    options.margin < 0 ? 4 : options.margin
-
-  var width = options.width && options.width >= 21 ? options.width : undefined
-  var scale = options.scale || 4
-
-  return {
-    width: width,
-    scale: width ? 4 : scale,
-    margin: margin,
-    color: {
-      dark: hex2rgba(options.color.dark || '#000000ff'),
-      light: hex2rgba(options.color.light || '#ffffffff')
-    },
-    type: options.type,
-    rendererOpts: options.rendererOpts || {}
-  }
-}
-
-exports.getScale = function getScale (qrSize, opts) {
-  return opts.width && opts.width >= qrSize + opts.margin * 2
-    ? opts.width / (qrSize + opts.margin * 2)
-    : opts.scale
-}
-
-exports.getImageWidth = function getImageWidth (qrSize, opts) {
-  var scale = exports.getScale(qrSize, opts)
-  return Math.floor((qrSize + opts.margin * 2) * scale)
-}
-
-exports.qrToImageData = function qrToImageData (imgData, qr, opts) {
-  var size = qr.modules.size
-  var data = qr.modules.data
-  var scale = exports.getScale(size, opts)
-  var symbolSize = Math.floor((size + opts.margin * 2) * scale)
-  var scaledMargin = opts.margin * scale
-  var palette = [opts.color.light, opts.color.dark]
-
-  for (var i = 0; i < symbolSize; i++) {
-    for (var j = 0; j < symbolSize; j++) {
-      var posDst = (i * symbolSize + j) * 4
-      var pxColor = opts.color.light
-
-      if (i >= scaledMargin && j >= scaledMargin &&
-        i < symbolSize - scaledMargin && j < symbolSize - scaledMargin) {
-        var iSrc = Math.floor((i - scaledMargin) / scale)
-        var jSrc = Math.floor((j - scaledMargin) / scale)
-        pxColor = palette[data[iSrc * size + jSrc] ? 1 : 0]
-      }
-
-      imgData[posDst++] = pxColor.r
-      imgData[posDst++] = pxColor.g
-      imgData[posDst++] = pxColor.b
-      imgData[posDst] = pxColor.a
-    }
-  }
-}
+function hex2rgba(r){if("number"==typeof r&&(r=r.toString()),"string"!=typeof r)throw new Error("Color should be defined as hex string");var t=r.slice().replace("#","").split("");if(t.length<3||5===t.length||t.length>8)throw new Error("Invalid hex color: "+r);3!==t.length&&4!==t.length||(t=Array.prototype.concat.apply([],t.map((function(r){return[r,r]})))),6===t.length&&t.push("F","F");var e=parseInt(t.join(""),16);return{r:e>>24&255,g:e>>16&255,b:e>>8&255,a:255&e,hex:"#"+t.slice(0,6).join("")}}exports.getOptions=function(r){r||(r={}),r.color||(r.color={});var t=void 0===r.margin||null===r.margin||r.margin<0?4:r.margin,e=r.width&&r.width>=21?r.width:void 0,o=r.scale||4;return{width:e,scale:e?4:o,margin:t,color:{dark:hex2rgba(r.color.dark||"#000000ff"),light:hex2rgba(r.color.light||"#ffffffff")},type:r.type,rendererOpts:r.rendererOpts||{}}},exports.getScale=function(r,t){return t.width&&t.width>=r+2*t.margin?t.width/(r+2*t.margin):t.scale},exports.getImageWidth=function(r,t){var e=exports.getScale(r,t);return Math.floor((r+2*t.margin)*e)},exports.qrToImageData=function(r,t,e){for(var o=t.modules.size,a=t.modules.data,n=exports.getScale(o,e),i=Math.floor((o+2*e.margin)*n),l=e.margin*n,g=[e.color.light,e.color.dark],h=0;h<i;h++)for(var f=0;f<i;f++){var c=4*(h*i+f),s=e.color.light;if(h>=l&&f>=l&&h<i-l&&f<i-l)s=g[a[Math.floor((h-l)/n)*o+Math.floor((f-l)/n)]?1:0];r[c++]=s.r,r[c++]=s.g,r[c++]=s.b,r[c]=s.a}};
\ No newline at end of file
index 036e72d..ba506ab 100644 (file)
@@ -1,137 +1 @@
-var canPromise = require('./can-promise')
-var QRCode = require('./core/qrcode')
-var PngRenderer = require('./renderer/png')
-var Utf8Renderer = require('./renderer/utf8')
-var TerminalRenderer = require('./renderer/terminal')
-var SvgRenderer = require('./renderer/svg')
-
-function checkParams (text, opts, cb) {
-  if (typeof text === 'undefined') {
-    throw new Error('String required as first argument')
-  }
-
-  if (typeof cb === 'undefined') {
-    cb = opts
-    opts = {}
-  }
-
-  if (typeof cb !== 'function') {
-    if (!canPromise()) {
-      throw new Error('Callback required as last argument')
-    } else {
-      opts = cb || {}
-      cb = null
-    }
-  }
-
-  return {
-    opts: opts,
-    cb: cb
-  }
-}
-
-function getTypeFromFilename (path) {
-  return path.slice((path.lastIndexOf('.') - 1 >>> 0) + 2).toLowerCase()
-}
-
-function getRendererFromType (type) {
-  switch (type) {
-    case 'svg':
-      return SvgRenderer
-
-    case 'txt':
-    case 'utf8':
-      return Utf8Renderer
-
-    case 'png':
-    case 'image/png':
-    default:
-      return PngRenderer
-  }
-}
-
-function getStringRendererFromType (type) {
-  switch (type) {
-    case 'svg':
-      return SvgRenderer
-
-    case 'terminal':
-      return TerminalRenderer
-
-    case 'utf8':
-    default:
-      return Utf8Renderer
-  }
-}
-
-function render (renderFunc, text, params) {
-  if (!params.cb) {
-    return new Promise(function (resolve, reject) {
-      try {
-        var data = QRCode.create(text, params.opts)
-        return renderFunc(data, params.opts, function (err, data) {
-          return err ? reject(err) : resolve(data)
-        })
-      } catch (e) {
-        reject(e)
-      }
-    })
-  }
-
-  try {
-    var data = QRCode.create(text, params.opts)
-    return renderFunc(data, params.opts, params.cb)
-  } catch (e) {
-    params.cb(e)
-  }
-}
-
-exports.create = QRCode.create
-
-exports.toCanvas = require('./browser').toCanvas
-
-exports.toString = function toString (text, opts, cb) {
-  var params = checkParams(text, opts, cb)
-  var renderer = getStringRendererFromType(params.opts.type)
-  return render(renderer.render, text, params)
-}
-
-exports.toDataURL = function toDataURL (text, opts, cb) {
-  var params = checkParams(text, opts, cb)
-  var renderer = getRendererFromType(params.opts.type)
-  return render(renderer.renderToDataURL, text, params)
-}
-
-exports.toBuffer = function toBuffer (text, opts, cb) {
-  var params = checkParams(text, opts, cb)
-  var renderer = getRendererFromType(params.opts.type)
-  return render(renderer.renderToBuffer, text, params)
-}
-
-exports.toFile = function toFile (path, text, opts, cb) {
-  if (typeof path !== 'string' || !(typeof text === 'string' || typeof text === 'object')) {
-    throw new Error('Invalid argument')
-  }
-
-  if ((arguments.length < 3) && !canPromise()) {
-    throw new Error('Too few arguments provided')
-  }
-
-  var params = checkParams(text, opts, cb)
-  var type = params.opts.type || getTypeFromFilename(path)
-  var renderer = getRendererFromType(type)
-  var renderToFile = renderer.renderToFile.bind(null, path)
-
-  return render(renderToFile, text, params)
-}
-
-exports.toFileStream = function toFileStream (stream, text, opts) {
-  if (arguments.length < 2) {
-    throw new Error('Too few arguments provided')
-  }
-
-  var params = checkParams(text, opts, stream.emit.bind(stream, 'error'))
-  var renderer = getRendererFromType('png') // Only png support for now
-  var renderToFileStream = renderer.renderToFileStream.bind(null, stream)
-  render(renderToFileStream, text, params)
-}
+var canPromise=require("./can-promise"),QRCode=require("./core/qrcode"),PngRenderer=require("./renderer/png"),Utf8Renderer=require("./renderer/utf8"),TerminalRenderer=require("./renderer/terminal"),SvgRenderer=require("./renderer/svg");function checkParams(e,r,n){if(void 0===e)throw new Error("String required as first argument");if(void 0===n&&(n=r,r={}),"function"!=typeof n){if(!canPromise())throw new Error("Callback required as last argument");r=n||{},n=null}return{opts:r,cb:n}}function getTypeFromFilename(e){return e.slice(2+(e.lastIndexOf(".")-1>>>0)).toLowerCase()}function getRendererFromType(e){switch(e){case"svg":return SvgRenderer;case"txt":case"utf8":return Utf8Renderer;case"png":case"image/png":default:return PngRenderer}}function getStringRendererFromType(e){switch(e){case"svg":return SvgRenderer;case"terminal":return TerminalRenderer;case"utf8":default:return Utf8Renderer}}function render(e,r,n){if(!n.cb)return new Promise((function(t,o){try{var a=QRCode.create(r,n.opts);return e(a,n.opts,(function(e,r){return e?o(e):t(r)}))}catch(e){o(e)}}));try{var t=QRCode.create(r,n.opts);return e(t,n.opts,n.cb)}catch(e){n.cb(e)}}exports.create=QRCode.create,exports.toCanvas=require("./browser").toCanvas,exports.toString=function(e,r,n){var t=checkParams(e,r,n);return render(getStringRendererFromType(t.opts.type).render,e,t)},exports.toDataURL=function(e,r,n){var t=checkParams(e,r,n);return render(getRendererFromType(t.opts.type).renderToDataURL,e,t)},exports.toBuffer=function(e,r,n){var t=checkParams(e,r,n);return render(getRendererFromType(t.opts.type).renderToBuffer,e,t)},exports.toFile=function(e,r,n,t){if("string"!=typeof e||"string"!=typeof r&&"object"!=typeof r)throw new Error("Invalid argument");if(arguments.length<3&&!canPromise())throw new Error("Too few arguments provided");var o=checkParams(r,n,t),a=o.opts.type||getTypeFromFilename(e),i=getRendererFromType(a),c=i.renderToFile.bind(null,e);return render(c,r,o)},exports.toFileStream=function(e,r,n){if(arguments.length<2)throw new Error("Too few arguments provided");var t=checkParams(r,n,e.emit.bind(e,"error")),o=getRendererFromType("png"),a=o.renderToFileStream.bind(null,e);render(a,r,t)};
\ No newline at end of file
index 76bd7e0..05bc49a 100644 (file)
@@ -1,2 +1 @@
-module.exports.alloc = require('buffer-alloc')
-module.exports.from = require('buffer-from')
+module.exports.alloc=require("buffer-alloc"),module.exports.from=require("buffer-from");
\ No newline at end of file
index 36f4b50..ad52775 100644 (file)
@@ -1,520 +1 @@
-/**
- * Implementation of a subset of node.js Buffer methods for the browser.
- * Based on https://github.com/feross/buffer
- */
-
-/* eslint-disable no-proto */
-
-'use strict'
-
-var isArray = require('isarray')
-
-function typedArraySupport () {
-  // Can typed array instances 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
-  }
-}
-
-Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
-
-var K_MAX_LENGTH = Buffer.TYPED_ARRAY_SUPPORT
-    ? 0x7fffffff
-    : 0x3fffffff
-
-function Buffer (arg, offset, length) {
-  if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
-    return new Buffer(arg, offset, length)
-  }
-
-  if (typeof arg === 'number') {
-    return allocUnsafe(this, arg)
-  }
-
-  return from(this, arg, offset, length)
-}
-
-if (Buffer.TYPED_ARRAY_SUPPORT) {
-  Buffer.prototype.__proto__ = Uint8Array.prototype
-  Buffer.__proto__ = Uint8Array
-
-  // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
-  if (typeof Symbol !== 'undefined' && Symbol.species &&
-      Buffer[Symbol.species] === Buffer) {
-    Object.defineProperty(Buffer, Symbol.species, {
-      value: null,
-      configurable: true,
-      enumerable: false,
-      writable: false
-    })
-  }
-}
-
-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 isnan (val) {
-  return val !== val // eslint-disable-line no-self-compare
-}
-
-function createBuffer (that, length) {
-  var buf
-  if (Buffer.TYPED_ARRAY_SUPPORT) {
-    buf = new Uint8Array(length)
-    buf.__proto__ = Buffer.prototype
-  } else {
-    // Fallback: Return an object instance of the Buffer class
-    buf = that
-    if (buf === null) {
-      buf = new Buffer(length)
-    }
-    buf.length = length
-  }
-
-  return buf
-}
-
-function allocUnsafe (that, size) {
-  var buf = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
-
-  if (!Buffer.TYPED_ARRAY_SUPPORT) {
-    for (var i = 0; i < size; ++i) {
-      buf[i] = 0
-    }
-  }
-
-  return buf
-}
-
-function fromString (that, string) {
-  var length = byteLength(string) | 0
-  var buf = createBuffer(that, length)
-
-  var actual = buf.write(string)
-
-  if (actual !== length) {
-    // Writing a hex string, for example, that contains invalid characters will
-    // cause everything after the first invalid character to be ignored. (e.g.
-    // 'abxxcd' will be treated as 'ab')
-    buf = buf.slice(0, actual)
-  }
-
-  return buf
-}
-
-function fromArrayLike (that, array) {
-  var length = array.length < 0 ? 0 : checked(array.length) | 0
-  var buf = createBuffer(that, length)
-  for (var i = 0; i < length; i += 1) {
-    buf[i] = array[i] & 255
-  }
-  return buf
-}
-
-function fromArrayBuffer (that, array, byteOffset, length) {
-  if (byteOffset < 0 || array.byteLength < byteOffset) {
-    throw new RangeError('\'offset\' is out of bounds')
-  }
-
-  if (array.byteLength < byteOffset + (length || 0)) {
-    throw new RangeError('\'length\' is out of bounds')
-  }
-
-  var buf
-  if (byteOffset === undefined && length === undefined) {
-    buf = new Uint8Array(array)
-  } else if (length === undefined) {
-    buf = new Uint8Array(array, byteOffset)
-  } else {
-    buf = new Uint8Array(array, byteOffset, length)
-  }
-
-  if (Buffer.TYPED_ARRAY_SUPPORT) {
-    // Return an augmented `Uint8Array` instance, for best performance
-    buf.__proto__ = Buffer.prototype
-  } else {
-    // Fallback: Return an object instance of the Buffer class
-    buf = fromArrayLike(that, buf)
-  }
-
-  return buf
-}
-
-function fromObject (that, obj) {
-  if (Buffer.isBuffer(obj)) {
-    var len = checked(obj.length) | 0
-    var buf = createBuffer(that, len)
-
-    if (buf.length === 0) {
-      return buf
-    }
-
-    obj.copy(buf, 0, 0, len)
-    return buf
-  }
-
-  if (obj) {
-    if ((typeof ArrayBuffer !== 'undefined' &&
-        obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
-      if (typeof obj.length !== 'number' || isnan(obj.length)) {
-        return createBuffer(that, 0)
-      }
-      return fromArrayLike(that, obj)
-    }
-
-    if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
-      return fromArrayLike(that, obj.data)
-    }
-  }
-
-  throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
-}
-
-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 byteLength (string) {
-  if (Buffer.isBuffer(string)) {
-    return string.length
-  }
-  if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
-      (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
-    return string.byteLength
-  }
-  if (typeof string !== 'string') {
-    string = '' + string
-  }
-
-  var len = string.length
-  if (len === 0) return 0
-
-  return utf8ToBytes(string).length
-}
-
-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 utf8Write (buf, string, offset, length) {
-  return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
-}
-
-function from (that, value, offset, length) {
-  if (typeof value === 'number') {
-    throw new TypeError('"value" argument must not be a number')
-  }
-
-  if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
-    return fromArrayBuffer(that, value, offset, length)
-  }
-
-  if (typeof value === 'string') {
-    return fromString(that, value, offset)
-  }
-
-  return fromObject(that, value)
-}
-
-Buffer.prototype.write = function write (string, offset, length) {
-  // Buffer#write(string)
-  if (offset === undefined) {
-    length = this.length
-    offset = 0
-  // Buffer#write(string, encoding)
-  } else if (length === undefined && typeof offset === 'string') {
-    length = this.length
-    offset = 0
-  // Buffer#write(string, offset[, length])
-  } else if (isFinite(offset)) {
-    offset = offset | 0
-    if (isFinite(length)) {
-      length = length | 0
-    } else {
-      length = undefined
-    }
-  }
-
-  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')
-  }
-
-  return utf8Write(this, string, offset, length)
-}
-
-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
-  if (Buffer.TYPED_ARRAY_SUPPORT) {
-    newBuf = this.subarray(start, end)
-    // Return an augmented `Uint8Array` instance
-    newBuf.__proto__ = Buffer.prototype
-  } else {
-    var sliceLen = end - start
-    newBuf = new Buffer(sliceLen, undefined)
-    for (var i = 0; i < sliceLen; ++i) {
-      newBuf[i] = this[i + start]
-    }
-  }
-
-  return newBuf
-}
-
-Buffer.prototype.copy = function copy (target, targetStart, start, end) {
-  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('sourceStart out of bounds')
-  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
-  var i
-
-  if (this === target && start < targetStart && targetStart < end) {
-    // descending copy from end
-    for (i = len - 1; i >= 0; --i) {
-      target[i + targetStart] = this[i + start]
-    }
-  } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
-    // ascending copy from start
-    for (i = 0; i < len; ++i) {
-      target[i + targetStart] = this[i + start]
-    }
-  } else {
-    Uint8Array.prototype.set.call(
-      target,
-      this.subarray(start, start + len),
-      targetStart
-    )
-  }
-
-  return len
-}
-
-Buffer.prototype.fill = function fill (val, start, end) {
-  // Handle string cases:
-  if (typeof val === 'string') {
-    if (typeof start === 'string') {
-      start = 0
-      end = this.length
-    } else if (typeof end === 'string') {
-      end = this.length
-    }
-    if (val.length === 1) {
-      var code = val.charCodeAt(0)
-      if (code < 256) {
-        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
-      : new Buffer(val)
-    var len = bytes.length
-    for (i = 0; i < end - start; ++i) {
-      this[i + start] = bytes[i % len]
-    }
-  }
-
-  return this
-}
-
-Buffer.concat = function concat (list, length) {
-  if (!isArray(list)) {
-    throw new TypeError('"list" argument must be an Array of Buffers')
-  }
-
-  if (list.length === 0) {
-    return createBuffer(null, 0)
-  }
-
-  var i
-  if (length === undefined) {
-    length = 0
-    for (i = 0; i < list.length; ++i) {
-      length += list[i].length
-    }
-  }
-
-  var buffer = allocUnsafe(null, length)
-  var pos = 0
-  for (i = 0; i < list.length; ++i) {
-    var buf = list[i]
-    if (!Buffer.isBuffer(buf)) {
-      throw new TypeError('"list" argument must be an Array of Buffers')
-    }
-    buf.copy(buffer, pos)
-    pos += buf.length
-  }
-  return buffer
-}
-
-Buffer.byteLength = byteLength
-
-Buffer.prototype._isBuffer = true
-Buffer.isBuffer = function isBuffer (b) {
-  return !!(b != null && b._isBuffer)
-}
-
-module.exports.alloc = function (size) {
-  var buffer = new Buffer(size)
-  buffer.fill(0)
-  return buffer
-}
-
-module.exports.from = function (data) {
-  return new Buffer(data)
-}
+"use strict";var isArray=require("isarray");function typedArraySupport(){try{var r=new Uint8Array(1);return r.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===r.foo()}catch(r){return!1}}Buffer.TYPED_ARRAY_SUPPORT=typedArraySupport();var K_MAX_LENGTH=Buffer.TYPED_ARRAY_SUPPORT?2147483647:1073741823;function Buffer(r,e,t){return Buffer.TYPED_ARRAY_SUPPORT||this instanceof Buffer?"number"==typeof r?allocUnsafe(this,r):from(this,r,e,t):new Buffer(r,e,t)}function checked(r){if(r>=K_MAX_LENGTH)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+K_MAX_LENGTH.toString(16)+" bytes");return 0|r}function isnan(r){return r!=r}function createBuffer(r,e){var t;return Buffer.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e)).__proto__=Buffer.prototype:(null===(t=r)&&(t=new Buffer(e)),t.length=e),t}function allocUnsafe(r,e){var t=createBuffer(r,e<0?0:0|checked(e));if(!Buffer.TYPED_ARRAY_SUPPORT)for(var f=0;f<e;++f)t[f]=0;return t}function fromString(r,e){var t=0|byteLength(e),f=createBuffer(r,t),n=f.write(e);return n!==t&&(f=f.slice(0,n)),f}function fromArrayLike(r,e){for(var t=e.length<0?0:0|checked(e.length),f=createBuffer(r,t),n=0;n<t;n+=1)f[n]=255&e[n];return f}function fromArrayBuffer(r,e,t,f){if(t<0||e.byteLength<t)throw new RangeError("'offset' is out of bounds");if(e.byteLength<t+(f||0))throw new RangeError("'length' is out of bounds");var n;return n=void 0===t&&void 0===f?new Uint8Array(e):void 0===f?new Uint8Array(e,t):new Uint8Array(e,t,f),Buffer.TYPED_ARRAY_SUPPORT?n.__proto__=Buffer.prototype:n=fromArrayLike(r,n),n}function fromObject(r,e){if(Buffer.isBuffer(e)){var t=0|checked(e.length),f=createBuffer(r,t);return 0===f.length||e.copy(f,0,0,t),f}if(e){if("undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return"number"!=typeof e.length||isnan(e.length)?createBuffer(r,0):fromArrayLike(r,e);if("Buffer"===e.type&&Array.isArray(e.data))return fromArrayLike(r,e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function utf8ToBytes(r,e){var t;e=e||1/0;for(var f=r.length,n=null,o=[],u=0;u<f;++u){if((t=r.charCodeAt(u))>55295&&t<57344){if(!n){if(t>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(u+1===f){(e-=3)>-1&&o.push(239,191,189);continue}n=t;continue}if(t<56320){(e-=3)>-1&&o.push(239,191,189),n=t;continue}t=65536+(n-55296<<10|t-56320)}else n&&(e-=3)>-1&&o.push(239,191,189);if(n=null,t<128){if((e-=1)<0)break;o.push(t)}else if(t<2048){if((e-=2)<0)break;o.push(t>>6|192,63&t|128)}else if(t<65536){if((e-=3)<0)break;o.push(t>>12|224,t>>6&63|128,63&t|128)}else{if(!(t<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(t>>18|240,t>>12&63|128,t>>6&63|128,63&t|128)}}return o}function byteLength(r){return Buffer.isBuffer(r)?r.length:"undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(r)||r instanceof ArrayBuffer)?r.byteLength:("string"!=typeof r&&(r=""+r),0===r.length?0:utf8ToBytes(r).length)}function blitBuffer(r,e,t,f){for(var n=0;n<f&&!(n+t>=e.length||n>=r.length);++n)e[n+t]=r[n];return n}function utf8Write(r,e,t,f){return blitBuffer(utf8ToBytes(e,r.length-t),r,t,f)}function from(r,e,t,f){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer?fromArrayBuffer(r,e,t,f):"string"==typeof e?fromString(r,e,t):fromObject(r,e)}Buffer.TYPED_ARRAY_SUPPORT&&(Buffer.prototype.__proto__=Uint8Array.prototype,Buffer.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Buffer[Symbol.species]===Buffer&&Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:!0,enumerable:!1,writable:!1})),Buffer.prototype.write=function(r,e,t){void 0===e||void 0===t&&"string"==typeof e?(t=this.length,e=0):isFinite(e)&&(e|=0,isFinite(t)?t|=0:t=void 0);var f=this.length-e;if((void 0===t||t>f)&&(t=f),r.length>0&&(t<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");return utf8Write(this,r,e,t)},Buffer.prototype.slice=function(r,e){var t,f=this.length;if((r=~~r)<0?(r+=f)<0&&(r=0):r>f&&(r=f),(e=void 0===e?f:~~e)<0?(e+=f)<0&&(e=0):e>f&&(e=f),e<r&&(e=r),Buffer.TYPED_ARRAY_SUPPORT)(t=this.subarray(r,e)).__proto__=Buffer.prototype;else{var n=e-r;t=new Buffer(n,void 0);for(var o=0;o<n;++o)t[o]=this[o+r]}return t},Buffer.prototype.copy=function(r,e,t,f){if(t||(t=0),f||0===f||(f=this.length),e>=r.length&&(e=r.length),e||(e=0),f>0&&f<t&&(f=t),f===t)return 0;if(0===r.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(t<0||t>=this.length)throw new RangeError("sourceStart out of bounds");if(f<0)throw new RangeError("sourceEnd out of bounds");f>this.length&&(f=this.length),r.length-e<f-t&&(f=r.length-e+t);var n,o=f-t;if(this===r&&t<e&&e<f)for(n=o-1;n>=0;--n)r[n+e]=this[n+t];else if(o<1e3||!Buffer.TYPED_ARRAY_SUPPORT)for(n=0;n<o;++n)r[n+e]=this[n+t];else Uint8Array.prototype.set.call(r,this.subarray(t,t+o),e);return o},Buffer.prototype.fill=function(r,e,t){if("string"==typeof r){if("string"==typeof e?(e=0,t=this.length):"string"==typeof t&&(t=this.length),1===r.length){var f=r.charCodeAt(0);f<256&&(r=f)}}else"number"==typeof r&&(r&=255);if(e<0||this.length<e||this.length<t)throw new RangeError("Out of range index");if(t<=e)return this;var n;if(e>>>=0,t=void 0===t?this.length:t>>>0,r||(r=0),"number"==typeof r)for(n=e;n<t;++n)this[n]=r;else{var o=Buffer.isBuffer(r)?r:new Buffer(r),u=o.length;for(n=0;n<t-e;++n)this[n+e]=o[n%u]}return this},Buffer.concat=function(r,e){if(!isArray(r))throw new TypeError('"list" argument must be an Array of Buffers');if(0===r.length)return createBuffer(null,0);var t;if(void 0===e)for(e=0,t=0;t<r.length;++t)e+=r[t].length;var f=allocUnsafe(null,e),n=0;for(t=0;t<r.length;++t){var o=r[t];if(!Buffer.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(f,n),n+=o.length}return f},Buffer.byteLength=byteLength,Buffer.prototype._isBuffer=!0,Buffer.isBuffer=function(r){return!(null==r||!r._isBuffer)},module.exports.alloc=function(r){var e=new Buffer(r);return e.fill(0),e},module.exports.from=function(r){return new Buffer(r)};
\ No newline at end of file
index 17f4e60..fb7c88d 100644 (file)
@@ -1,782 +1 @@
-(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Qs = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
-'use strict';
-
-var replace = String.prototype.replace;
-var percentTwenties = /%20/g;
-
-module.exports = {
-    'default': 'RFC3986',
-    formatters: {
-        RFC1738: function (value) {
-            return replace.call(value, percentTwenties, '+');
-        },
-        RFC3986: function (value) {
-            return value;
-        }
-    },
-    RFC1738: 'RFC1738',
-    RFC3986: 'RFC3986'
-};
-
-},{}],2:[function(require,module,exports){
-'use strict';
-
-var stringify = require('./stringify');
-var parse = require('./parse');
-var formats = require('./formats');
-
-module.exports = {
-    formats: formats,
-    parse: parse,
-    stringify: stringify
-};
-
-},{"./formats":1,"./parse":3,"./stringify":4}],3:[function(require,module,exports){
-'use strict';
-
-var utils = require('./utils');
-
-var has = Object.prototype.hasOwnProperty;
-
-var defaults = {
-    allowDots: false,
-    allowPrototypes: false,
-    arrayLimit: 20,
-    charset: 'utf-8',
-    charsetSentinel: false,
-    comma: false,
-    decoder: utils.decode,
-    delimiter: '&',
-    depth: 5,
-    ignoreQueryPrefix: false,
-    interpretNumericEntities: false,
-    parameterLimit: 1000,
-    parseArrays: true,
-    plainObjects: false,
-    strictNullHandling: false
-};
-
-var interpretNumericEntities = function (str) {
-    return str.replace(/&#(\d+);/g, function ($0, numberStr) {
-        return String.fromCharCode(parseInt(numberStr, 10));
-    });
-};
-
-// This is what browsers will submit when the ✓ character occurs in an
-// application/x-www-form-urlencoded body and the encoding of the page containing
-// the form is iso-8859-1, or when the submitted form has an accept-charset
-// attribute of iso-8859-1. Presumably also with other charsets that do not contain
-// the ✓ character, such as us-ascii.
-var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('&#10003;')
-
-// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded.
-var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓')
-
-var parseValues = function parseQueryStringValues(str, options) {
-    var obj = {};
-    var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str;
-    var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;
-    var parts = cleanStr.split(options.delimiter, limit);
-    var skipIndex = -1; // Keep track of where the utf8 sentinel was found
-    var i;
-
-    var charset = options.charset;
-    if (options.charsetSentinel) {
-        for (i = 0; i < parts.length; ++i) {
-            if (parts[i].indexOf('utf8=') === 0) {
-                if (parts[i] === charsetSentinel) {
-                    charset = 'utf-8';
-                } else if (parts[i] === isoSentinel) {
-                    charset = 'iso-8859-1';
-                }
-                skipIndex = i;
-                i = parts.length; // The eslint settings do not allow break;
-            }
-        }
-    }
-
-    for (i = 0; i < parts.length; ++i) {
-        if (i === skipIndex) {
-            continue;
-        }
-        var part = parts[i];
-
-        var bracketEqualsPos = part.indexOf(']=');
-        var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;
-
-        var key, val;
-        if (pos === -1) {
-            key = options.decoder(part, defaults.decoder, charset);
-            val = options.strictNullHandling ? null : '';
-        } else {
-            key = options.decoder(part.slice(0, pos), defaults.decoder, charset);
-            val = options.decoder(part.slice(pos + 1), defaults.decoder, charset);
-        }
-
-        if (val && options.interpretNumericEntities && charset === 'iso-8859-1') {
-            val = interpretNumericEntities(val);
-        }
-
-        if (val && options.comma && val.indexOf(',') > -1) {
-            val = val.split(',');
-        }
-
-        if (has.call(obj, key)) {
-            obj[key] = utils.combine(obj[key], val);
-        } else {
-            obj[key] = val;
-        }
-    }
-
-    return obj;
-};
-
-var parseObject = function (chain, val, options) {
-    var leaf = val;
-
-    for (var i = chain.length - 1; i >= 0; --i) {
-        var obj;
-        var root = chain[i];
-
-        if (root === '[]' && options.parseArrays) {
-            obj = [].concat(leaf);
-        } else {
-            obj = options.plainObjects ? Object.create(null) : {};
-            var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
-            var index = parseInt(cleanRoot, 10);
-            if (!options.parseArrays && cleanRoot === '') {
-                obj = { 0: leaf };
-            } else if (
-                !isNaN(index)
-                && root !== cleanRoot
-                && String(index) === cleanRoot
-                && index >= 0
-                && (options.parseArrays && index <= options.arrayLimit)
-            ) {
-                obj = [];
-                obj[index] = leaf;
-            } else {
-                obj[cleanRoot] = leaf;
-            }
-        }
-
-        leaf = obj;
-    }
-
-    return leaf;
-};
-
-var parseKeys = function parseQueryStringKeys(givenKey, val, options) {
-    if (!givenKey) {
-        return;
-    }
-
-    // Transform dot notation to bracket notation
-    var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey;
-
-    // The regex chunks
-
-    var brackets = /(\[[^[\]]*])/;
-    var child = /(\[[^[\]]*])/g;
-
-    // Get the parent
-
-    var segment = brackets.exec(key);
-    var parent = segment ? key.slice(0, segment.index) : key;
-
-    // Stash the parent if it exists
-
-    var keys = [];
-    if (parent) {
-        // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties
-        if (!options.plainObjects && has.call(Object.prototype, parent)) {
-            if (!options.allowPrototypes) {
-                return;
-            }
-        }
-
-        keys.push(parent);
-    }
-
-    // Loop through children appending to the array until we hit depth
-
-    var i = 0;
-    while ((segment = child.exec(key)) !== null && i < options.depth) {
-        i += 1;
-        if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
-            if (!options.allowPrototypes) {
-                return;
-            }
-        }
-        keys.push(segment[1]);
-    }
-
-    // If there's a remainder, just add whatever is left
-
-    if (segment) {
-        keys.push('[' + key.slice(segment.index) + ']');
-    }
-
-    return parseObject(keys, val, options);
-};
-
-var normalizeParseOptions = function normalizeParseOptions(opts) {
-    if (!opts) {
-        return defaults;
-    }
-
-    if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') {
-        throw new TypeError('Decoder has to be a function.');
-    }
-
-    if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
-        throw new Error('The charset option must be either utf-8, iso-8859-1, or undefined');
-    }
-    var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset;
-
-    return {
-        allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,
-        allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes,
-        arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit,
-        charset: charset,
-        charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
-        comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma,
-        decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder,
-        delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter,
-        depth: typeof opts.depth === 'number' ? opts.depth : defaults.depth,
-        ignoreQueryPrefix: opts.ignoreQueryPrefix === true,
-        interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities,
-        parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit,
-        parseArrays: opts.parseArrays !== false,
-        plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects,
-        strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling
-    };
-};
-
-module.exports = function (str, opts) {
-    var options = normalizeParseOptions(opts);
-
-    if (str === '' || str === null || typeof str === 'undefined') {
-        return options.plainObjects ? Object.create(null) : {};
-    }
-
-    var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
-    var obj = options.plainObjects ? Object.create(null) : {};
-
-    // Iterate over the keys and setup the new object
-
-    var keys = Object.keys(tempObj);
-    for (var i = 0; i < keys.length; ++i) {
-        var key = keys[i];
-        var newObj = parseKeys(key, tempObj[key], options);
-        obj = utils.merge(obj, newObj, options);
-    }
-
-    return utils.compact(obj);
-};
-
-},{"./utils":5}],4:[function(require,module,exports){
-'use strict';
-
-var utils = require('./utils');
-var formats = require('./formats');
-var has = Object.prototype.hasOwnProperty;
-
-var arrayPrefixGenerators = {
-    brackets: function brackets(prefix) { // eslint-disable-line func-name-matching
-        return prefix + '[]';
-    },
-    comma: 'comma',
-    indices: function indices(prefix, key) { // eslint-disable-line func-name-matching
-        return prefix + '[' + key + ']';
-    },
-    repeat: function repeat(prefix) { // eslint-disable-line func-name-matching
-        return prefix;
-    }
-};
-
-var isArray = Array.isArray;
-var push = Array.prototype.push;
-var pushToArray = function (arr, valueOrArray) {
-    push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]);
-};
-
-var toISO = Date.prototype.toISOString;
-
-var defaults = {
-    addQueryPrefix: false,
-    allowDots: false,
-    charset: 'utf-8',
-    charsetSentinel: false,
-    delimiter: '&',
-    encode: true,
-    encoder: utils.encode,
-    encodeValuesOnly: false,
-    formatter: formats.formatters[formats['default']],
-    // deprecated
-    indices: false,
-    serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching
-        return toISO.call(date);
-    },
-    skipNulls: false,
-    strictNullHandling: false
-};
-
-var stringify = function stringify( // eslint-disable-line func-name-matching
-    object,
-    prefix,
-    generateArrayPrefix,
-    strictNullHandling,
-    skipNulls,
-    encoder,
-    filter,
-    sort,
-    allowDots,
-    serializeDate,
-    formatter,
-    encodeValuesOnly,
-    charset
-) {
-    var obj = object;
-    if (typeof filter === 'function') {
-        obj = filter(prefix, obj);
-    } else if (obj instanceof Date) {
-        obj = serializeDate(obj);
-    } else if (generateArrayPrefix === 'comma' && isArray(obj)) {
-        obj = obj.join(',');
-    }
-
-    if (obj === null) {
-        if (strictNullHandling) {
-            return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset) : prefix;
-        }
-
-        obj = '';
-    }
-
-    if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) {
-        if (encoder) {
-            var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset);
-            return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset))];
-        }
-        return [formatter(prefix) + '=' + formatter(String(obj))];
-    }
-
-    var values = [];
-
-    if (typeof obj === 'undefined') {
-        return values;
-    }
-
-    var objKeys;
-    if (isArray(filter)) {
-        objKeys = filter;
-    } else {
-        var keys = Object.keys(obj);
-        objKeys = sort ? keys.sort(sort) : keys;
-    }
-
-    for (var i = 0; i < objKeys.length; ++i) {
-        var key = objKeys[i];
-
-        if (skipNulls && obj[key] === null) {
-            continue;
-        }
-
-        if (isArray(obj)) {
-            pushToArray(values, stringify(
-                obj[key],
-                typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix,
-                generateArrayPrefix,
-                strictNullHandling,
-                skipNulls,
-                encoder,
-                filter,
-                sort,
-                allowDots,
-                serializeDate,
-                formatter,
-                encodeValuesOnly,
-                charset
-            ));
-        } else {
-            pushToArray(values, stringify(
-                obj[key],
-                prefix + (allowDots ? '.' + key : '[' + key + ']'),
-                generateArrayPrefix,
-                strictNullHandling,
-                skipNulls,
-                encoder,
-                filter,
-                sort,
-                allowDots,
-                serializeDate,
-                formatter,
-                encodeValuesOnly,
-                charset
-            ));
-        }
-    }
-
-    return values;
-};
-
-var normalizeStringifyOptions = function normalizeStringifyOptions(opts) {
-    if (!opts) {
-        return defaults;
-    }
-
-    if (opts.encoder !== null && opts.encoder !== undefined && typeof opts.encoder !== 'function') {
-        throw new TypeError('Encoder has to be a function.');
-    }
-
-    var charset = opts.charset || defaults.charset;
-    if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
-        throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
-    }
-
-    var format = formats['default'];
-    if (typeof opts.format !== 'undefined') {
-        if (!has.call(formats.formatters, opts.format)) {
-            throw new TypeError('Unknown format option provided.');
-        }
-        format = opts.format;
-    }
-    var formatter = formats.formatters[format];
-
-    var filter = defaults.filter;
-    if (typeof opts.filter === 'function' || isArray(opts.filter)) {
-        filter = opts.filter;
-    }
-
-    return {
-        addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix,
-        allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,
-        charset: charset,
-        charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
-        delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter,
-        encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode,
-        encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder,
-        encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly,
-        filter: filter,
-        formatter: formatter,
-        serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate,
-        skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls,
-        sort: typeof opts.sort === 'function' ? opts.sort : null,
-        strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling
-    };
-};
-
-module.exports = function (object, opts) {
-    var obj = object;
-    var options = normalizeStringifyOptions(opts);
-
-    var objKeys;
-    var filter;
-
-    if (typeof options.filter === 'function') {
-        filter = options.filter;
-        obj = filter('', obj);
-    } else if (isArray(options.filter)) {
-        filter = options.filter;
-        objKeys = filter;
-    }
-
-    var keys = [];
-
-    if (typeof obj !== 'object' || obj === null) {
-        return '';
-    }
-
-    var arrayFormat;
-    if (opts && opts.arrayFormat in arrayPrefixGenerators) {
-        arrayFormat = opts.arrayFormat;
-    } else if (opts && 'indices' in opts) {
-        arrayFormat = opts.indices ? 'indices' : 'repeat';
-    } else {
-        arrayFormat = 'indices';
-    }
-
-    var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
-
-    if (!objKeys) {
-        objKeys = Object.keys(obj);
-    }
-
-    if (options.sort) {
-        objKeys.sort(options.sort);
-    }
-
-    for (var i = 0; i < objKeys.length; ++i) {
-        var key = objKeys[i];
-
-        if (options.skipNulls && obj[key] === null) {
-            continue;
-        }
-        pushToArray(keys, stringify(
-            obj[key],
-            key,
-            generateArrayPrefix,
-            options.strictNullHandling,
-            options.skipNulls,
-            options.encode ? options.encoder : null,
-            options.filter,
-            options.sort,
-            options.allowDots,
-            options.serializeDate,
-            options.formatter,
-            options.encodeValuesOnly,
-            options.charset
-        ));
-    }
-
-    var joined = keys.join(options.delimiter);
-    var prefix = options.addQueryPrefix === true ? '?' : '';
-
-    if (options.charsetSentinel) {
-        if (options.charset === 'iso-8859-1') {
-            // encodeURIComponent('&#10003;'), the "numeric entity" representation of a checkmark
-            prefix += 'utf8=%26%2310003%3B&';
-        } else {
-            // encodeURIComponent('✓')
-            prefix += 'utf8=%E2%9C%93&';
-        }
-    }
-
-    return joined.length > 0 ? prefix + joined : '';
-};
-
-},{"./formats":1,"./utils":5}],5:[function(require,module,exports){
-'use strict';
-
-var has = Object.prototype.hasOwnProperty;
-var isArray = Array.isArray;
-
-var hexTable = (function () {
-    var array = [];
-    for (var i = 0; i < 256; ++i) {
-        array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
-    }
-
-    return array;
-}());
-
-var compactQueue = function compactQueue(queue) {
-    while (queue.length > 1) {
-        var item = queue.pop();
-        var obj = item.obj[item.prop];
-
-        if (isArray(obj)) {
-            var compacted = [];
-
-            for (var j = 0; j < obj.length; ++j) {
-                if (typeof obj[j] !== 'undefined') {
-                    compacted.push(obj[j]);
-                }
-            }
-
-            item.obj[item.prop] = compacted;
-        }
-    }
-};
-
-var arrayToObject = function arrayToObject(source, options) {
-    var obj = options && options.plainObjects ? Object.create(null) : {};
-    for (var i = 0; i < source.length; ++i) {
-        if (typeof source[i] !== 'undefined') {
-            obj[i] = source[i];
-        }
-    }
-
-    return obj;
-};
-
-var merge = function merge(target, source, options) {
-    if (!source) {
-        return target;
-    }
-
-    if (typeof source !== 'object') {
-        if (isArray(target)) {
-            target.push(source);
-        } else if (target && typeof target === 'object') {
-            if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) {
-                target[source] = true;
-            }
-        } else {
-            return [target, source];
-        }
-
-        return target;
-    }
-
-    if (!target || typeof target !== 'object') {
-        return [target].concat(source);
-    }
-
-    var mergeTarget = target;
-    if (isArray(target) && !isArray(source)) {
-        mergeTarget = arrayToObject(target, options);
-    }
-
-    if (isArray(target) && isArray(source)) {
-        source.forEach(function (item, i) {
-            if (has.call(target, i)) {
-                var targetItem = target[i];
-                if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') {
-                    target[i] = merge(targetItem, item, options);
-                } else {
-                    target.push(item);
-                }
-            } else {
-                target[i] = item;
-            }
-        });
-        return target;
-    }
-
-    return Object.keys(source).reduce(function (acc, key) {
-        var value = source[key];
-
-        if (has.call(acc, key)) {
-            acc[key] = merge(acc[key], value, options);
-        } else {
-            acc[key] = value;
-        }
-        return acc;
-    }, mergeTarget);
-};
-
-var assign = function assignSingleSource(target, source) {
-    return Object.keys(source).reduce(function (acc, key) {
-        acc[key] = source[key];
-        return acc;
-    }, target);
-};
-
-var decode = function (str, decoder, charset) {
-    var strWithoutPlus = str.replace(/\+/g, ' ');
-    if (charset === 'iso-8859-1') {
-        // unescape never throws, no try...catch needed:
-        return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);
-    }
-    // utf-8
-    try {
-        return decodeURIComponent(strWithoutPlus);
-    } catch (e) {
-        return strWithoutPlus;
-    }
-};
-
-var encode = function encode(str, defaultEncoder, charset) {
-    // This code was originally written by Brian White (mscdex) for the io.js core querystring library.
-    // It has been adapted here for stricter adherence to RFC 3986
-    if (str.length === 0) {
-        return str;
-    }
-
-    var string = typeof str === 'string' ? str : String(str);
-
-    if (charset === 'iso-8859-1') {
-        return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) {
-            return '%26%23' + parseInt($0.slice(2), 16) + '%3B';
-        });
-    }
-
-    var out = '';
-    for (var i = 0; i < string.length; ++i) {
-        var c = string.charCodeAt(i);
-
-        if (
-            c === 0x2D // -
-            || c === 0x2E // .
-            || c === 0x5F // _
-            || c === 0x7E // ~
-            || (c >= 0x30 && c <= 0x39) // 0-9
-            || (c >= 0x41 && c <= 0x5A) // a-z
-            || (c >= 0x61 && c <= 0x7A) // A-Z
-        ) {
-            out += string.charAt(i);
-            continue;
-        }
-
-        if (c < 0x80) {
-            out = out + hexTable[c];
-            continue;
-        }
-
-        if (c < 0x800) {
-            out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
-            continue;
-        }
-
-        if (c < 0xD800 || c >= 0xE000) {
-            out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
-            continue;
-        }
-
-        i += 1;
-        c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
-        out += hexTable[0xF0 | (c >> 18)]
-            + hexTable[0x80 | ((c >> 12) & 0x3F)]
-            + hexTable[0x80 | ((c >> 6) & 0x3F)]
-            + hexTable[0x80 | (c & 0x3F)];
-    }
-
-    return out;
-};
-
-var compact = function compact(value) {
-    var queue = [{ obj: { o: value }, prop: 'o' }];
-    var refs = [];
-
-    for (var i = 0; i < queue.length; ++i) {
-        var item = queue[i];
-        var obj = item.obj[item.prop];
-
-        var keys = Object.keys(obj);
-        for (var j = 0; j < keys.length; ++j) {
-            var key = keys[j];
-            var val = obj[key];
-            if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {
-                queue.push({ obj: obj, prop: key });
-                refs.push(val);
-            }
-        }
-    }
-
-    compactQueue(queue);
-
-    return value;
-};
-
-var isRegExp = function isRegExp(obj) {
-    return Object.prototype.toString.call(obj) === '[object RegExp]';
-};
-
-var isBuffer = function isBuffer(obj) {
-    if (!obj || typeof obj !== 'object') {
-        return false;
-    }
-
-    return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
-};
-
-var combine = function combine(a, b) {
-    return [].concat(a, b);
-};
-
-module.exports = {
-    arrayToObject: arrayToObject,
-    assign: assign,
-    combine: combine,
-    compact: compact,
-    decode: decode,
-    encode: encode,
-    isBuffer: isBuffer,
-    isRegExp: isRegExp,
-    merge: merge
-};
-
-},{}]},{},[2])(2)
-});
+!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Qs=e()}}((function(){return function e(t,r,o){function n(a,l){if(!r[a]){if(!t[a]){var c="function"==typeof require&&require;if(!l&&c)return c(a,!0);if(i)return i(a,!0);var s=new Error("Cannot find module '"+a+"'");throw s.code="MODULE_NOT_FOUND",s}var f=r[a]={exports:{}};t[a][0].call(f.exports,(function(e){return n(t[a][1][e]||e)}),f,f.exports,e,t,r,o)}return r[a].exports}for(var i="function"==typeof require&&require,a=0;a<o.length;a++)n(o[a]);return n}({1:[function(e,t,r){"use strict";var o=String.prototype.replace,n=/%20/g;t.exports={default:"RFC3986",formatters:{RFC1738:function(e){return o.call(e,n,"+")},RFC3986:function(e){return e}},RFC1738:"RFC1738",RFC3986:"RFC3986"}},{}],2:[function(e,t,r){"use strict";var o=e("./stringify"),n=e("./parse"),i=e("./formats");t.exports={formats:i,parse:n,stringify:o}},{"./formats":1,"./parse":3,"./stringify":4}],3:[function(e,t,r){"use strict";var o=e("./utils"),n=Object.prototype.hasOwnProperty,i={allowDots:!1,allowPrototypes:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:o.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},a=function(e){return e.replace(/&#(\d+);/g,(function(e,t){return String.fromCharCode(parseInt(t,10))}))},l=function(e,t,r){if(e){var o=r.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,i=/(\[[^[\]]*])/g,a=/(\[[^[\]]*])/.exec(o),l=a?o.slice(0,a.index):o,c=[];if(l){if(!r.plainObjects&&n.call(Object.prototype,l)&&!r.allowPrototypes)return;c.push(l)}for(var s=0;null!==(a=i.exec(o))&&s<r.depth;){if(s+=1,!r.plainObjects&&n.call(Object.prototype,a[1].slice(1,-1))&&!r.allowPrototypes)return;c.push(a[1])}return a&&c.push("["+o.slice(a.index)+"]"),function(e,t,r){for(var o=t,n=e.length-1;n>=0;--n){var i,a=e[n];if("[]"===a&&r.parseArrays)i=[].concat(o);else{i=r.plainObjects?Object.create(null):{};var l="["===a.charAt(0)&&"]"===a.charAt(a.length-1)?a.slice(1,-1):a,c=parseInt(l,10);r.parseArrays||""!==l?!isNaN(c)&&a!==l&&String(c)===l&&c>=0&&r.parseArrays&&c<=r.arrayLimit?(i=[])[c]=o:i[l]=o:i={0:o}}o=i}return o}(c,t,r)}};t.exports=function(e,t){var r=function(e){if(!e)return i;if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new Error("The charset option must be either utf-8, iso-8859-1, or undefined");var t=void 0===e.charset?i.charset:e.charset;return{allowDots:void 0===e.allowDots?i.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:i.allowPrototypes,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:i.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:i.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:i.comma,decoder:"function"==typeof e.decoder?e.decoder:i.decoder,delimiter:"string"==typeof e.delimiter||o.isRegExp(e.delimiter)?e.delimiter:i.delimiter,depth:"number"==typeof e.depth?e.depth:i.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:i.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:i.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:i.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:i.strictNullHandling}}(t);if(""===e||null==e)return r.plainObjects?Object.create(null):{};for(var c="string"==typeof e?function(e,t){var r,l={},c=t.ignoreQueryPrefix?e.replace(/^\?/,""):e,s=t.parameterLimit===1/0?void 0:t.parameterLimit,f=c.split(t.delimiter,s),u=-1,p=t.charset;if(t.charsetSentinel)for(r=0;r<f.length;++r)0===f[r].indexOf("utf8=")&&("utf8=%E2%9C%93"===f[r]?p="utf-8":"utf8=%26%2310003%3B"===f[r]&&(p="iso-8859-1"),u=r,r=f.length);for(r=0;r<f.length;++r)if(r!==u){var d,y,m=f[r],h=m.indexOf("]="),b=-1===h?m.indexOf("="):h+1;-1===b?(d=t.decoder(m,i.decoder,p),y=t.strictNullHandling?null:""):(d=t.decoder(m.slice(0,b),i.decoder,p),y=t.decoder(m.slice(b+1),i.decoder,p)),y&&t.interpretNumericEntities&&"iso-8859-1"===p&&(y=a(y)),y&&t.comma&&y.indexOf(",")>-1&&(y=y.split(",")),n.call(l,d)?l[d]=o.combine(l[d],y):l[d]=y}return l}(e,r):e,s=r.plainObjects?Object.create(null):{},f=Object.keys(c),u=0;u<f.length;++u){var p=f[u],d=l(p,c[p],r);s=o.merge(s,d,r)}return o.compact(s)}},{"./utils":5}],4:[function(e,t,r){"use strict";var o=e("./utils"),n=e("./formats"),i=Object.prototype.hasOwnProperty,a={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},l=Array.isArray,c=Array.prototype.push,s=function(e,t){c.apply(e,l(t)?t:[t])},f=Date.prototype.toISOString,u={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:o.encode,encodeValuesOnly:!1,formatter:n.formatters[n.default],indices:!1,serializeDate:function(e){return f.call(e)},skipNulls:!1,strictNullHandling:!1},p=function e(t,r,n,i,a,c,f,p,d,y,m,h,b){var g=t;if("function"==typeof f?g=f(r,g):g instanceof Date?g=y(g):"comma"===n&&l(g)&&(g=g.join(",")),null===g){if(i)return c&&!h?c(r,u.encoder,b):r;g=""}if("string"==typeof g||"number"==typeof g||"boolean"==typeof g||o.isBuffer(g))return c?[m(h?r:c(r,u.encoder,b))+"="+m(c(g,u.encoder,b))]:[m(r)+"="+m(String(g))];var v,O=[];if(void 0===g)return O;if(l(f))v=f;else{var j=Object.keys(g);v=p?j.sort(p):j}for(var w=0;w<v.length;++w){var x=v[w];a&&null===g[x]||(l(g)?s(O,e(g[x],"function"==typeof n?n(r,x):r,n,i,a,c,f,p,d,y,m,h,b)):s(O,e(g[x],r+(d?"."+x:"["+x+"]"),n,i,a,c,f,p,d,y,m,h,b)))}return O};t.exports=function(e,t){var r,o=e,c=function(e){if(!e)return u;if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");var t=e.charset||u.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var r=n.default;if(void 0!==e.format){if(!i.call(n.formatters,e.format))throw new TypeError("Unknown format option provided.");r=e.format}var o=n.formatters[r],a=u.filter;return("function"==typeof e.filter||l(e.filter))&&(a=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:u.addQueryPrefix,allowDots:void 0===e.allowDots?u.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:u.charsetSentinel,delimiter:void 0===e.delimiter?u.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:u.encode,encoder:"function"==typeof e.encoder?e.encoder:u.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:u.encodeValuesOnly,filter:a,formatter:o,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:u.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:u.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:u.strictNullHandling}}(t);"function"==typeof c.filter?o=(0,c.filter)("",o):l(c.filter)&&(r=c.filter);var f,d=[];if("object"!=typeof o||null===o)return"";f=t&&t.arrayFormat in a?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var y=a[f];r||(r=Object.keys(o)),c.sort&&r.sort(c.sort);for(var m=0;m<r.length;++m){var h=r[m];c.skipNulls&&null===o[h]||s(d,p(o[h],h,y,c.strictNullHandling,c.skipNulls,c.encode?c.encoder:null,c.filter,c.sort,c.allowDots,c.serializeDate,c.formatter,c.encodeValuesOnly,c.charset))}var b=d.join(c.delimiter),g=!0===c.addQueryPrefix?"?":"";return c.charsetSentinel&&("iso-8859-1"===c.charset?g+="utf8=%26%2310003%3B&":g+="utf8=%E2%9C%93&"),b.length>0?g+b:""}},{"./formats":1,"./utils":5}],5:[function(e,t,r){"use strict";var o=Object.prototype.hasOwnProperty,n=Array.isArray,i=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),a=function(e,t){for(var r=t&&t.plainObjects?Object.create(null):{},o=0;o<e.length;++o)void 0!==e[o]&&(r[o]=e[o]);return r};t.exports={arrayToObject:a,assign:function(e,t){return Object.keys(t).reduce((function(e,r){return e[r]=t[r],e}),e)},combine:function(e,t){return[].concat(e,t)},compact:function(e){for(var t=[{obj:{o:e},prop:"o"}],r=[],o=0;o<t.length;++o)for(var i=t[o],a=i.obj[i.prop],l=Object.keys(a),c=0;c<l.length;++c){var s=l[c],f=a[s];"object"==typeof f&&null!==f&&-1===r.indexOf(f)&&(t.push({obj:a,prop:s}),r.push(f))}return function(e){for(;e.length>1;){var t=e.pop(),r=t.obj[t.prop];if(n(r)){for(var o=[],i=0;i<r.length;++i)void 0!==r[i]&&o.push(r[i]);t.obj[t.prop]=o}}}(t),e},decode:function(e,t,r){var o=e.replace(/\+/g," ");if("iso-8859-1"===r)return o.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(o)}catch(e){return o}},encode:function(e,t,r){if(0===e.length)return e;var o="string"==typeof e?e:String(e);if("iso-8859-1"===r)return escape(o).replace(/%u[0-9a-f]{4}/gi,(function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"}));for(var n="",a=0;a<o.length;++a){var l=o.charCodeAt(a);45===l||46===l||95===l||126===l||l>=48&&l<=57||l>=65&&l<=90||l>=97&&l<=122?n+=o.charAt(a):l<128?n+=i[l]:l<2048?n+=i[192|l>>6]+i[128|63&l]:l<55296||l>=57344?n+=i[224|l>>12]+i[128|l>>6&63]+i[128|63&l]:(a+=1,l=65536+((1023&l)<<10|1023&o.charCodeAt(a)),n+=i[240|l>>18]+i[128|l>>12&63]+i[128|l>>6&63]+i[128|63&l])}return n},isBuffer:function(e){return!(!e||"object"!=typeof e)&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))},isRegExp:function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},merge:function e(t,r,i){if(!r)return t;if("object"!=typeof r){if(n(t))t.push(r);else{if(!t||"object"!=typeof t)return[t,r];(i&&(i.plainObjects||i.allowPrototypes)||!o.call(Object.prototype,r))&&(t[r]=!0)}return t}if(!t||"object"!=typeof t)return[t].concat(r);var l=t;return n(t)&&!n(r)&&(l=a(t,i)),n(t)&&n(r)?(r.forEach((function(r,n){if(o.call(t,n)){var a=t[n];a&&"object"==typeof a&&r&&"object"==typeof r?t[n]=e(a,r,i):t.push(r)}else t[n]=r})),t):Object.keys(r).reduce((function(t,n){var a=r[n];return o.call(t,n)?t[n]=e(t[n],a,i):t[n]=a,t}),l)}}},{}]},{},[2])(2)}));
\ No newline at end of file
index df45997..125892c 100644 (file)
@@ -1,18 +1 @@
-'use strict';
-
-var replace = String.prototype.replace;
-var percentTwenties = /%20/g;
-
-module.exports = {
-    'default': 'RFC3986',
-    formatters: {
-        RFC1738: function (value) {
-            return replace.call(value, percentTwenties, '+');
-        },
-        RFC3986: function (value) {
-            return value;
-        }
-    },
-    RFC1738: 'RFC1738',
-    RFC3986: 'RFC3986'
-};
+"use strict";var replace=String.prototype.replace,percentTwenties=/%20/g;module.exports={default:"RFC3986",formatters:{RFC1738:function(e){return replace.call(e,percentTwenties,"+")},RFC3986:function(e){return e}},RFC1738:"RFC1738",RFC3986:"RFC3986"};
\ No newline at end of file
index 0d6a97d..41dfdc1 100644 (file)
@@ -1,11 +1 @@
-'use strict';
-
-var stringify = require('./stringify');
-var parse = require('./parse');
-var formats = require('./formats');
-
-module.exports = {
-    formats: formats,
-    parse: parse,
-    stringify: stringify
-};
+"use strict";var stringify=require("./stringify"),parse=require("./parse"),formats=require("./formats");module.exports={formats:formats,parse:parse,stringify:stringify};
\ No newline at end of file
index d81628b..048f257 100644 (file)
@@ -1,242 +1 @@
-'use strict';
-
-var utils = require('./utils');
-
-var has = Object.prototype.hasOwnProperty;
-
-var defaults = {
-    allowDots: false,
-    allowPrototypes: false,
-    arrayLimit: 20,
-    charset: 'utf-8',
-    charsetSentinel: false,
-    comma: false,
-    decoder: utils.decode,
-    delimiter: '&',
-    depth: 5,
-    ignoreQueryPrefix: false,
-    interpretNumericEntities: false,
-    parameterLimit: 1000,
-    parseArrays: true,
-    plainObjects: false,
-    strictNullHandling: false
-};
-
-var interpretNumericEntities = function (str) {
-    return str.replace(/&#(\d+);/g, function ($0, numberStr) {
-        return String.fromCharCode(parseInt(numberStr, 10));
-    });
-};
-
-// This is what browsers will submit when the ✓ character occurs in an
-// application/x-www-form-urlencoded body and the encoding of the page containing
-// the form is iso-8859-1, or when the submitted form has an accept-charset
-// attribute of iso-8859-1. Presumably also with other charsets that do not contain
-// the ✓ character, such as us-ascii.
-var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('&#10003;')
-
-// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded.
-var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓')
-
-var parseValues = function parseQueryStringValues(str, options) {
-    var obj = {};
-    var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str;
-    var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;
-    var parts = cleanStr.split(options.delimiter, limit);
-    var skipIndex = -1; // Keep track of where the utf8 sentinel was found
-    var i;
-
-    var charset = options.charset;
-    if (options.charsetSentinel) {
-        for (i = 0; i < parts.length; ++i) {
-            if (parts[i].indexOf('utf8=') === 0) {
-                if (parts[i] === charsetSentinel) {
-                    charset = 'utf-8';
-                } else if (parts[i] === isoSentinel) {
-                    charset = 'iso-8859-1';
-                }
-                skipIndex = i;
-                i = parts.length; // The eslint settings do not allow break;
-            }
-        }
-    }
-
-    for (i = 0; i < parts.length; ++i) {
-        if (i === skipIndex) {
-            continue;
-        }
-        var part = parts[i];
-
-        var bracketEqualsPos = part.indexOf(']=');
-        var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;
-
-        var key, val;
-        if (pos === -1) {
-            key = options.decoder(part, defaults.decoder, charset);
-            val = options.strictNullHandling ? null : '';
-        } else {
-            key = options.decoder(part.slice(0, pos), defaults.decoder, charset);
-            val = options.decoder(part.slice(pos + 1), defaults.decoder, charset);
-        }
-
-        if (val && options.interpretNumericEntities && charset === 'iso-8859-1') {
-            val = interpretNumericEntities(val);
-        }
-
-        if (val && options.comma && val.indexOf(',') > -1) {
-            val = val.split(',');
-        }
-
-        if (has.call(obj, key)) {
-            obj[key] = utils.combine(obj[key], val);
-        } else {
-            obj[key] = val;
-        }
-    }
-
-    return obj;
-};
-
-var parseObject = function (chain, val, options) {
-    var leaf = val;
-
-    for (var i = chain.length - 1; i >= 0; --i) {
-        var obj;
-        var root = chain[i];
-
-        if (root === '[]' && options.parseArrays) {
-            obj = [].concat(leaf);
-        } else {
-            obj = options.plainObjects ? Object.create(null) : {};
-            var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
-            var index = parseInt(cleanRoot, 10);
-            if (!options.parseArrays && cleanRoot === '') {
-                obj = { 0: leaf };
-            } else if (
-                !isNaN(index)
-                && root !== cleanRoot
-                && String(index) === cleanRoot
-                && index >= 0
-                && (options.parseArrays && index <= options.arrayLimit)
-            ) {
-                obj = [];
-                obj[index] = leaf;
-            } else {
-                obj[cleanRoot] = leaf;
-            }
-        }
-
-        leaf = obj;
-    }
-
-    return leaf;
-};
-
-var parseKeys = function parseQueryStringKeys(givenKey, val, options) {
-    if (!givenKey) {
-        return;
-    }
-
-    // Transform dot notation to bracket notation
-    var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey;
-
-    // The regex chunks
-
-    var brackets = /(\[[^[\]]*])/;
-    var child = /(\[[^[\]]*])/g;
-
-    // Get the parent
-
-    var segment = brackets.exec(key);
-    var parent = segment ? key.slice(0, segment.index) : key;
-
-    // Stash the parent if it exists
-
-    var keys = [];
-    if (parent) {
-        // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties
-        if (!options.plainObjects && has.call(Object.prototype, parent)) {
-            if (!options.allowPrototypes) {
-                return;
-            }
-        }
-
-        keys.push(parent);
-    }
-
-    // Loop through children appending to the array until we hit depth
-
-    var i = 0;
-    while ((segment = child.exec(key)) !== null && i < options.depth) {
-        i += 1;
-        if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
-            if (!options.allowPrototypes) {
-                return;
-            }
-        }
-        keys.push(segment[1]);
-    }
-
-    // If there's a remainder, just add whatever is left
-
-    if (segment) {
-        keys.push('[' + key.slice(segment.index) + ']');
-    }
-
-    return parseObject(keys, val, options);
-};
-
-var normalizeParseOptions = function normalizeParseOptions(opts) {
-    if (!opts) {
-        return defaults;
-    }
-
-    if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') {
-        throw new TypeError('Decoder has to be a function.');
-    }
-
-    if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
-        throw new Error('The charset option must be either utf-8, iso-8859-1, or undefined');
-    }
-    var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset;
-
-    return {
-        allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,
-        allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes,
-        arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit,
-        charset: charset,
-        charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
-        comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma,
-        decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder,
-        delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter,
-        depth: typeof opts.depth === 'number' ? opts.depth : defaults.depth,
-        ignoreQueryPrefix: opts.ignoreQueryPrefix === true,
-        interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities,
-        parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit,
-        parseArrays: opts.parseArrays !== false,
-        plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects,
-        strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling
-    };
-};
-
-module.exports = function (str, opts) {
-    var options = normalizeParseOptions(opts);
-
-    if (str === '' || str === null || typeof str === 'undefined') {
-        return options.plainObjects ? Object.create(null) : {};
-    }
-
-    var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
-    var obj = options.plainObjects ? Object.create(null) : {};
-
-    // Iterate over the keys and setup the new object
-
-    var keys = Object.keys(tempObj);
-    for (var i = 0; i < keys.length; ++i) {
-        var key = keys[i];
-        var newObj = parseKeys(key, tempObj[key], options);
-        obj = utils.merge(obj, newObj, options);
-    }
-
-    return utils.compact(obj);
-};
+"use strict";var utils=require("./utils"),has=Object.prototype.hasOwnProperty,defaults={allowDots:!1,allowPrototypes:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:utils.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},interpretNumericEntities=function(e){return e.replace(/&#(\d+);/g,(function(e,t){return String.fromCharCode(parseInt(t,10))}))},isoSentinel="utf8=%26%2310003%3B",charsetSentinel="utf8=%E2%9C%93",parseValues=function(e,t){var r,i={},a=t.ignoreQueryPrefix?e.replace(/^\?/,""):e,l=t.parameterLimit===1/0?void 0:t.parameterLimit,s=a.split(t.delimiter,l),n=-1,o=t.charset;if(t.charsetSentinel)for(r=0;r<s.length;++r)0===s[r].indexOf("utf8=")&&(s[r]===charsetSentinel?o="utf-8":s[r]===isoSentinel&&(o="iso-8859-1"),n=r,r=s.length);for(r=0;r<s.length;++r)if(r!==n){var c,u,p=s[r],d=p.indexOf("]="),f=-1===d?p.indexOf("="):d+1;-1===f?(c=t.decoder(p,defaults.decoder,o),u=t.strictNullHandling?null:""):(c=t.decoder(p.slice(0,f),defaults.decoder,o),u=t.decoder(p.slice(f+1),defaults.decoder,o)),u&&t.interpretNumericEntities&&"iso-8859-1"===o&&(u=interpretNumericEntities(u)),u&&t.comma&&u.indexOf(",")>-1&&(u=u.split(",")),has.call(i,c)?i[c]=utils.combine(i[c],u):i[c]=u}return i},parseObject=function(e,t,r){for(var i=t,a=e.length-1;a>=0;--a){var l,s=e[a];if("[]"===s&&r.parseArrays)l=[].concat(i);else{l=r.plainObjects?Object.create(null):{};var n="["===s.charAt(0)&&"]"===s.charAt(s.length-1)?s.slice(1,-1):s,o=parseInt(n,10);r.parseArrays||""!==n?!isNaN(o)&&s!==n&&String(o)===n&&o>=0&&r.parseArrays&&o<=r.arrayLimit?(l=[])[o]=i:l[n]=i:l={0:i}}i=l}return i},parseKeys=function(e,t,r){if(e){var i=r.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,a=/(\[[^[\]]*])/g,l=/(\[[^[\]]*])/.exec(i),s=l?i.slice(0,l.index):i,n=[];if(s){if(!r.plainObjects&&has.call(Object.prototype,s)&&!r.allowPrototypes)return;n.push(s)}for(var o=0;null!==(l=a.exec(i))&&o<r.depth;){if(o+=1,!r.plainObjects&&has.call(Object.prototype,l[1].slice(1,-1))&&!r.allowPrototypes)return;n.push(l[1])}return l&&n.push("["+i.slice(l.index)+"]"),parseObject(n,t,r)}},normalizeParseOptions=function(e){if(!e)return defaults;if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new Error("The charset option must be either utf-8, iso-8859-1, or undefined");var t=void 0===e.charset?defaults.charset:e.charset;return{allowDots:void 0===e.allowDots?defaults.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:defaults.allowPrototypes,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:defaults.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:defaults.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:defaults.comma,decoder:"function"==typeof e.decoder?e.decoder:defaults.decoder,delimiter:"string"==typeof e.delimiter||utils.isRegExp(e.delimiter)?e.delimiter:defaults.delimiter,depth:"number"==typeof e.depth?e.depth:defaults.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:defaults.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:defaults.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:defaults.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:defaults.strictNullHandling}};module.exports=function(e,t){var r=normalizeParseOptions(t);if(""===e||null==e)return r.plainObjects?Object.create(null):{};for(var i="string"==typeof e?parseValues(e,r):e,a=r.plainObjects?Object.create(null):{},l=Object.keys(i),s=0;s<l.length;++s){var n=l[s],o=parseKeys(n,i[n],r);a=utils.merge(a,o,r)}return utils.compact(a)};
\ No newline at end of file
index 7455049..e596dd1 100644 (file)
@@ -1,269 +1 @@
-'use strict';
-
-var utils = require('./utils');
-var formats = require('./formats');
-var has = Object.prototype.hasOwnProperty;
-
-var arrayPrefixGenerators = {
-    brackets: function brackets(prefix) { // eslint-disable-line func-name-matching
-        return prefix + '[]';
-    },
-    comma: 'comma',
-    indices: function indices(prefix, key) { // eslint-disable-line func-name-matching
-        return prefix + '[' + key + ']';
-    },
-    repeat: function repeat(prefix) { // eslint-disable-line func-name-matching
-        return prefix;
-    }
-};
-
-var isArray = Array.isArray;
-var push = Array.prototype.push;
-var pushToArray = function (arr, valueOrArray) {
-    push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]);
-};
-
-var toISO = Date.prototype.toISOString;
-
-var defaults = {
-    addQueryPrefix: false,
-    allowDots: false,
-    charset: 'utf-8',
-    charsetSentinel: false,
-    delimiter: '&',
-    encode: true,
-    encoder: utils.encode,
-    encodeValuesOnly: false,
-    formatter: formats.formatters[formats['default']],
-    // deprecated
-    indices: false,
-    serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching
-        return toISO.call(date);
-    },
-    skipNulls: false,
-    strictNullHandling: false
-};
-
-var stringify = function stringify( // eslint-disable-line func-name-matching
-    object,
-    prefix,
-    generateArrayPrefix,
-    strictNullHandling,
-    skipNulls,
-    encoder,
-    filter,
-    sort,
-    allowDots,
-    serializeDate,
-    formatter,
-    encodeValuesOnly,
-    charset
-) {
-    var obj = object;
-    if (typeof filter === 'function') {
-        obj = filter(prefix, obj);
-    } else if (obj instanceof Date) {
-        obj = serializeDate(obj);
-    } else if (generateArrayPrefix === 'comma' && isArray(obj)) {
-        obj = obj.join(',');
-    }
-
-    if (obj === null) {
-        if (strictNullHandling) {
-            return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset) : prefix;
-        }
-
-        obj = '';
-    }
-
-    if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) {
-        if (encoder) {
-            var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset);
-            return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset))];
-        }
-        return [formatter(prefix) + '=' + formatter(String(obj))];
-    }
-
-    var values = [];
-
-    if (typeof obj === 'undefined') {
-        return values;
-    }
-
-    var objKeys;
-    if (isArray(filter)) {
-        objKeys = filter;
-    } else {
-        var keys = Object.keys(obj);
-        objKeys = sort ? keys.sort(sort) : keys;
-    }
-
-    for (var i = 0; i < objKeys.length; ++i) {
-        var key = objKeys[i];
-
-        if (skipNulls && obj[key] === null) {
-            continue;
-        }
-
-        if (isArray(obj)) {
-            pushToArray(values, stringify(
-                obj[key],
-                typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix,
-                generateArrayPrefix,
-                strictNullHandling,
-                skipNulls,
-                encoder,
-                filter,
-                sort,
-                allowDots,
-                serializeDate,
-                formatter,
-                encodeValuesOnly,
-                charset
-            ));
-        } else {
-            pushToArray(values, stringify(
-                obj[key],
-                prefix + (allowDots ? '.' + key : '[' + key + ']'),
-                generateArrayPrefix,
-                strictNullHandling,
-                skipNulls,
-                encoder,
-                filter,
-                sort,
-                allowDots,
-                serializeDate,
-                formatter,
-                encodeValuesOnly,
-                charset
-            ));
-        }
-    }
-
-    return values;
-};
-
-var normalizeStringifyOptions = function normalizeStringifyOptions(opts) {
-    if (!opts) {
-        return defaults;
-    }
-
-    if (opts.encoder !== null && opts.encoder !== undefined && typeof opts.encoder !== 'function') {
-        throw new TypeError('Encoder has to be a function.');
-    }
-
-    var charset = opts.charset || defaults.charset;
-    if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
-        throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
-    }
-
-    var format = formats['default'];
-    if (typeof opts.format !== 'undefined') {
-        if (!has.call(formats.formatters, opts.format)) {
-            throw new TypeError('Unknown format option provided.');
-        }
-        format = opts.format;
-    }
-    var formatter = formats.formatters[format];
-
-    var filter = defaults.filter;
-    if (typeof opts.filter === 'function' || isArray(opts.filter)) {
-        filter = opts.filter;
-    }
-
-    return {
-        addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix,
-        allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,
-        charset: charset,
-        charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
-        delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter,
-        encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode,
-        encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder,
-        encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly,
-        filter: filter,
-        formatter: formatter,
-        serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate,
-        skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls,
-        sort: typeof opts.sort === 'function' ? opts.sort : null,
-        strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling
-    };
-};
-
-module.exports = function (object, opts) {
-    var obj = object;
-    var options = normalizeStringifyOptions(opts);
-
-    var objKeys;
-    var filter;
-
-    if (typeof options.filter === 'function') {
-        filter = options.filter;
-        obj = filter('', obj);
-    } else if (isArray(options.filter)) {
-        filter = options.filter;
-        objKeys = filter;
-    }
-
-    var keys = [];
-
-    if (typeof obj !== 'object' || obj === null) {
-        return '';
-    }
-
-    var arrayFormat;
-    if (opts && opts.arrayFormat in arrayPrefixGenerators) {
-        arrayFormat = opts.arrayFormat;
-    } else if (opts && 'indices' in opts) {
-        arrayFormat = opts.indices ? 'indices' : 'repeat';
-    } else {
-        arrayFormat = 'indices';
-    }
-
-    var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
-
-    if (!objKeys) {
-        objKeys = Object.keys(obj);
-    }
-
-    if (options.sort) {
-        objKeys.sort(options.sort);
-    }
-
-    for (var i = 0; i < objKeys.length; ++i) {
-        var key = objKeys[i];
-
-        if (options.skipNulls && obj[key] === null) {
-            continue;
-        }
-        pushToArray(keys, stringify(
-            obj[key],
-            key,
-            generateArrayPrefix,
-            options.strictNullHandling,
-            options.skipNulls,
-            options.encode ? options.encoder : null,
-            options.filter,
-            options.sort,
-            options.allowDots,
-            options.serializeDate,
-            options.formatter,
-            options.encodeValuesOnly,
-            options.charset
-        ));
-    }
-
-    var joined = keys.join(options.delimiter);
-    var prefix = options.addQueryPrefix === true ? '?' : '';
-
-    if (options.charsetSentinel) {
-        if (options.charset === 'iso-8859-1') {
-            // encodeURIComponent('&#10003;'), the "numeric entity" representation of a checkmark
-            prefix += 'utf8=%26%2310003%3B&';
-        } else {
-            // encodeURIComponent('✓')
-            prefix += 'utf8=%E2%9C%93&';
-        }
-    }
-
-    return joined.length > 0 ? prefix + joined : '';
-};
+"use strict";var utils=require("./utils"),formats=require("./formats"),has=Object.prototype.hasOwnProperty,arrayPrefixGenerators={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,r){return e+"["+r+"]"},repeat:function(e){return e}},isArray=Array.isArray,push=Array.prototype.push,pushToArray=function(e,r){push.apply(e,isArray(r)?r:[r])},toISO=Date.prototype.toISOString,defaults={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:utils.encode,encodeValuesOnly:!1,formatter:formats.formatters[formats.default],indices:!1,serializeDate:function(e){return toISO.call(e)},skipNulls:!1,strictNullHandling:!1},stringify=function e(r,t,o,a,i,n,l,s,f,u,d,c,y){var p=r;if("function"==typeof l?p=l(t,p):p instanceof Date?p=u(p):"comma"===o&&isArray(p)&&(p=p.join(",")),null===p){if(a)return n&&!c?n(t,defaults.encoder,y):t;p=""}if("string"==typeof p||"number"==typeof p||"boolean"==typeof p||utils.isBuffer(p))return n?[d(c?t:n(t,defaults.encoder,y))+"="+d(n(p,defaults.encoder,y))]:[d(t)+"="+d(String(p))];var m,h=[];if(void 0===p)return h;if(isArray(l))m=l;else{var v=Object.keys(p);m=s?v.sort(s):v}for(var g=0;g<m.length;++g){var b=m[g];i&&null===p[b]||(isArray(p)?pushToArray(h,e(p[b],"function"==typeof o?o(t,b):t,o,a,i,n,l,s,f,u,d,c,y)):pushToArray(h,e(p[b],t+(f?"."+b:"["+b+"]"),o,a,i,n,l,s,f,u,d,c,y)))}return h},normalizeStringifyOptions=function(e){if(!e)return defaults;if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");var r=e.charset||defaults.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var t=formats.default;if(void 0!==e.format){if(!has.call(formats.formatters,e.format))throw new TypeError("Unknown format option provided.");t=e.format}var o=formats.formatters[t],a=defaults.filter;return("function"==typeof e.filter||isArray(e.filter))&&(a=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:defaults.addQueryPrefix,allowDots:void 0===e.allowDots?defaults.allowDots:!!e.allowDots,charset:r,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:defaults.charsetSentinel,delimiter:void 0===e.delimiter?defaults.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:defaults.encode,encoder:"function"==typeof e.encoder?e.encoder:defaults.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:defaults.encodeValuesOnly,filter:a,formatter:o,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:defaults.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:defaults.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:defaults.strictNullHandling}};module.exports=function(e,r){var t,o=e,a=normalizeStringifyOptions(r);"function"==typeof a.filter?o=(0,a.filter)("",o):isArray(a.filter)&&(t=a.filter);var i,n=[];if("object"!=typeof o||null===o)return"";i=r&&r.arrayFormat in arrayPrefixGenerators?r.arrayFormat:r&&"indices"in r?r.indices?"indices":"repeat":"indices";var l=arrayPrefixGenerators[i];t||(t=Object.keys(o)),a.sort&&t.sort(a.sort);for(var s=0;s<t.length;++s){var f=t[s];a.skipNulls&&null===o[f]||pushToArray(n,stringify(o[f],f,l,a.strictNullHandling,a.skipNulls,a.encode?a.encoder:null,a.filter,a.sort,a.allowDots,a.serializeDate,a.formatter,a.encodeValuesOnly,a.charset))}var u=n.join(a.delimiter),d=!0===a.addQueryPrefix?"?":"";return a.charsetSentinel&&("iso-8859-1"===a.charset?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""};
\ No newline at end of file
index 1b219cd..854d0d4 100644 (file)
@@ -1,230 +1 @@
-'use strict';
-
-var has = Object.prototype.hasOwnProperty;
-var isArray = Array.isArray;
-
-var hexTable = (function () {
-    var array = [];
-    for (var i = 0; i < 256; ++i) {
-        array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
-    }
-
-    return array;
-}());
-
-var compactQueue = function compactQueue(queue) {
-    while (queue.length > 1) {
-        var item = queue.pop();
-        var obj = item.obj[item.prop];
-
-        if (isArray(obj)) {
-            var compacted = [];
-
-            for (var j = 0; j < obj.length; ++j) {
-                if (typeof obj[j] !== 'undefined') {
-                    compacted.push(obj[j]);
-                }
-            }
-
-            item.obj[item.prop] = compacted;
-        }
-    }
-};
-
-var arrayToObject = function arrayToObject(source, options) {
-    var obj = options && options.plainObjects ? Object.create(null) : {};
-    for (var i = 0; i < source.length; ++i) {
-        if (typeof source[i] !== 'undefined') {
-            obj[i] = source[i];
-        }
-    }
-
-    return obj;
-};
-
-var merge = function merge(target, source, options) {
-    if (!source) {
-        return target;
-    }
-
-    if (typeof source !== 'object') {
-        if (isArray(target)) {
-            target.push(source);
-        } else if (target && typeof target === 'object') {
-            if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) {
-                target[source] = true;
-            }
-        } else {
-            return [target, source];
-        }
-
-        return target;
-    }
-
-    if (!target || typeof target !== 'object') {
-        return [target].concat(source);
-    }
-
-    var mergeTarget = target;
-    if (isArray(target) && !isArray(source)) {
-        mergeTarget = arrayToObject(target, options);
-    }
-
-    if (isArray(target) && isArray(source)) {
-        source.forEach(function (item, i) {
-            if (has.call(target, i)) {
-                var targetItem = target[i];
-                if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') {
-                    target[i] = merge(targetItem, item, options);
-                } else {
-                    target.push(item);
-                }
-            } else {
-                target[i] = item;
-            }
-        });
-        return target;
-    }
-
-    return Object.keys(source).reduce(function (acc, key) {
-        var value = source[key];
-
-        if (has.call(acc, key)) {
-            acc[key] = merge(acc[key], value, options);
-        } else {
-            acc[key] = value;
-        }
-        return acc;
-    }, mergeTarget);
-};
-
-var assign = function assignSingleSource(target, source) {
-    return Object.keys(source).reduce(function (acc, key) {
-        acc[key] = source[key];
-        return acc;
-    }, target);
-};
-
-var decode = function (str, decoder, charset) {
-    var strWithoutPlus = str.replace(/\+/g, ' ');
-    if (charset === 'iso-8859-1') {
-        // unescape never throws, no try...catch needed:
-        return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);
-    }
-    // utf-8
-    try {
-        return decodeURIComponent(strWithoutPlus);
-    } catch (e) {
-        return strWithoutPlus;
-    }
-};
-
-var encode = function encode(str, defaultEncoder, charset) {
-    // This code was originally written by Brian White (mscdex) for the io.js core querystring library.
-    // It has been adapted here for stricter adherence to RFC 3986
-    if (str.length === 0) {
-        return str;
-    }
-
-    var string = typeof str === 'string' ? str : String(str);
-
-    if (charset === 'iso-8859-1') {
-        return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) {
-            return '%26%23' + parseInt($0.slice(2), 16) + '%3B';
-        });
-    }
-
-    var out = '';
-    for (var i = 0; i < string.length; ++i) {
-        var c = string.charCodeAt(i);
-
-        if (
-            c === 0x2D // -
-            || c === 0x2E // .
-            || c === 0x5F // _
-            || c === 0x7E // ~
-            || (c >= 0x30 && c <= 0x39) // 0-9
-            || (c >= 0x41 && c <= 0x5A) // a-z
-            || (c >= 0x61 && c <= 0x7A) // A-Z
-        ) {
-            out += string.charAt(i);
-            continue;
-        }
-
-        if (c < 0x80) {
-            out = out + hexTable[c];
-            continue;
-        }
-
-        if (c < 0x800) {
-            out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
-            continue;
-        }
-
-        if (c < 0xD800 || c >= 0xE000) {
-            out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
-            continue;
-        }
-
-        i += 1;
-        c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
-        out += hexTable[0xF0 | (c >> 18)]
-            + hexTable[0x80 | ((c >> 12) & 0x3F)]
-            + hexTable[0x80 | ((c >> 6) & 0x3F)]
-            + hexTable[0x80 | (c & 0x3F)];
-    }
-
-    return out;
-};
-
-var compact = function compact(value) {
-    var queue = [{ obj: { o: value }, prop: 'o' }];
-    var refs = [];
-
-    for (var i = 0; i < queue.length; ++i) {
-        var item = queue[i];
-        var obj = item.obj[item.prop];
-
-        var keys = Object.keys(obj);
-        for (var j = 0; j < keys.length; ++j) {
-            var key = keys[j];
-            var val = obj[key];
-            if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {
-                queue.push({ obj: obj, prop: key });
-                refs.push(val);
-            }
-        }
-    }
-
-    compactQueue(queue);
-
-    return value;
-};
-
-var isRegExp = function isRegExp(obj) {
-    return Object.prototype.toString.call(obj) === '[object RegExp]';
-};
-
-var isBuffer = function isBuffer(obj) {
-    if (!obj || typeof obj !== 'object') {
-        return false;
-    }
-
-    return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
-};
-
-var combine = function combine(a, b) {
-    return [].concat(a, b);
-};
-
-module.exports = {
-    arrayToObject: arrayToObject,
-    assign: assign,
-    combine: combine,
-    compact: compact,
-    decode: decode,
-    encode: encode,
-    isBuffer: isBuffer,
-    isRegExp: isRegExp,
-    merge: merge
-};
+"use strict";var has=Object.prototype.hasOwnProperty,isArray=Array.isArray,hexTable=function(){for(var e=[],r=0;r<256;++r)e.push("%"+((r<16?"0":"")+r.toString(16)).toUpperCase());return e}(),compactQueue=function(e){for(;e.length>1;){var r=e.pop(),t=r.obj[r.prop];if(isArray(t)){for(var o=[],c=0;c<t.length;++c)void 0!==t[c]&&o.push(t[c]);r.obj[r.prop]=o}}},arrayToObject=function(e,r){for(var t=r&&r.plainObjects?Object.create(null):{},o=0;o<e.length;++o)void 0!==e[o]&&(t[o]=e[o]);return t},merge=function e(r,t,o){if(!t)return r;if("object"!=typeof t){if(isArray(r))r.push(t);else{if(!r||"object"!=typeof r)return[r,t];(o&&(o.plainObjects||o.allowPrototypes)||!has.call(Object.prototype,t))&&(r[t]=!0)}return r}if(!r||"object"!=typeof r)return[r].concat(t);var c=r;return isArray(r)&&!isArray(t)&&(c=arrayToObject(r,o)),isArray(r)&&isArray(t)?(t.forEach((function(t,c){if(has.call(r,c)){var n=r[c];n&&"object"==typeof n&&t&&"object"==typeof t?r[c]=e(n,t,o):r.push(t)}else r[c]=t})),r):Object.keys(t).reduce((function(r,c){var n=t[c];return has.call(r,c)?r[c]=e(r[c],n,o):r[c]=n,r}),c)},assign=function(e,r){return Object.keys(r).reduce((function(e,t){return e[t]=r[t],e}),e)},decode=function(e,r,t){var o=e.replace(/\+/g," ");if("iso-8859-1"===t)return o.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(o)}catch(e){return o}},encode=function(e,r,t){if(0===e.length)return e;var o="string"==typeof e?e:String(e);if("iso-8859-1"===t)return escape(o).replace(/%u[0-9a-f]{4}/gi,(function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"}));for(var c="",n=0;n<o.length;++n){var a=o.charCodeAt(n);45===a||46===a||95===a||126===a||a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122?c+=o.charAt(n):a<128?c+=hexTable[a]:a<2048?c+=hexTable[192|a>>6]+hexTable[128|63&a]:a<55296||a>=57344?c+=hexTable[224|a>>12]+hexTable[128|a>>6&63]+hexTable[128|63&a]:(n+=1,a=65536+((1023&a)<<10|1023&o.charCodeAt(n)),c+=hexTable[240|a>>18]+hexTable[128|a>>12&63]+hexTable[128|a>>6&63]+hexTable[128|63&a])}return c},compact=function(e){for(var r=[{obj:{o:e},prop:"o"}],t=[],o=0;o<r.length;++o)for(var c=r[o],n=c.obj[c.prop],a=Object.keys(n),i=0;i<a.length;++i){var u=a[i],p=n[u];"object"==typeof p&&null!==p&&-1===t.indexOf(p)&&(r.push({obj:n,prop:u}),t.push(p))}return compactQueue(r),e},isRegExp=function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},isBuffer=function(e){return!(!e||"object"!=typeof e)&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))},combine=function(e,r){return[].concat(e,r)};module.exports={arrayToObject:arrayToObject,assign:assign,combine:combine,compact:compact,decode:decode,encode:encode,isBuffer:isBuffer,isRegExp:isRegExp,merge:merge};
\ No newline at end of file
index 5e6bc8f..0714bdb 100644 (file)
@@ -1,7 +1 @@
-'use strict';
-
-require('./parse');
-
-require('./stringify');
-
-require('./utils');
+"use strict";require("./parse"),require("./stringify"),require("./utils");
\ No newline at end of file
index 8967789..645efa7 100644 (file)
@@ -1,676 +1 @@
-'use strict';
-
-var test = require('tape');
-var qs = require('../');
-var utils = require('../lib/utils');
-var iconv = require('iconv-lite');
-var SaferBuffer = require('safer-buffer').Buffer;
-
-test('parse()', function (t) {
-    t.test('parses a simple string', function (st) {
-        st.deepEqual(qs.parse('0=foo'), { 0: 'foo' });
-        st.deepEqual(qs.parse('foo=c++'), { foo: 'c  ' });
-        st.deepEqual(qs.parse('a[>=]=23'), { a: { '>=': '23' } });
-        st.deepEqual(qs.parse('a[<=>]==23'), { a: { '<=>': '=23' } });
-        st.deepEqual(qs.parse('a[==]=23'), { a: { '==': '23' } });
-        st.deepEqual(qs.parse('foo', { strictNullHandling: true }), { foo: null });
-        st.deepEqual(qs.parse('foo'), { foo: '' });
-        st.deepEqual(qs.parse('foo='), { foo: '' });
-        st.deepEqual(qs.parse('foo=bar'), { foo: 'bar' });
-        st.deepEqual(qs.parse(' foo = bar = baz '), { ' foo ': ' bar = baz ' });
-        st.deepEqual(qs.parse('foo=bar=baz'), { foo: 'bar=baz' });
-        st.deepEqual(qs.parse('foo=bar&bar=baz'), { foo: 'bar', bar: 'baz' });
-        st.deepEqual(qs.parse('foo2=bar2&baz2='), { foo2: 'bar2', baz2: '' });
-        st.deepEqual(qs.parse('foo=bar&baz', { strictNullHandling: true }), { foo: 'bar', baz: null });
-        st.deepEqual(qs.parse('foo=bar&baz'), { foo: 'bar', baz: '' });
-        st.deepEqual(qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World'), {
-            cht: 'p3',
-            chd: 't:60,40',
-            chs: '250x100',
-            chl: 'Hello|World'
-        });
-        st.end();
-    });
-
-    t.test('allows enabling dot notation', function (st) {
-        st.deepEqual(qs.parse('a.b=c'), { 'a.b': 'c' });
-        st.deepEqual(qs.parse('a.b=c', { allowDots: true }), { a: { b: 'c' } });
-        st.end();
-    });
-
-    t.deepEqual(qs.parse('a[b]=c'), { a: { b: 'c' } }, 'parses a single nested string');
-    t.deepEqual(qs.parse('a[b][c]=d'), { a: { b: { c: 'd' } } }, 'parses a double nested string');
-    t.deepEqual(
-        qs.parse('a[b][c][d][e][f][g][h]=i'),
-        { a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } },
-        'defaults to a depth of 5'
-    );
-
-    t.test('only parses one level when depth = 1', function (st) {
-        st.deepEqual(qs.parse('a[b][c]=d', { depth: 1 }), { a: { b: { '[c]': 'd' } } });
-        st.deepEqual(qs.parse('a[b][c][d]=e', { depth: 1 }), { a: { b: { '[c][d]': 'e' } } });
-        st.end();
-    });
-
-    t.deepEqual(qs.parse('a=b&a=c'), { a: ['b', 'c'] }, 'parses a simple array');
-
-    t.test('parses an explicit array', function (st) {
-        st.deepEqual(qs.parse('a[]=b'), { a: ['b'] });
-        st.deepEqual(qs.parse('a[]=b&a[]=c'), { a: ['b', 'c'] });
-        st.deepEqual(qs.parse('a[]=b&a[]=c&a[]=d'), { a: ['b', 'c', 'd'] });
-        st.end();
-    });
-
-    t.test('parses a mix of simple and explicit arrays', function (st) {
-        st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] });
-        st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] });
-        st.deepEqual(qs.parse('a[0]=b&a=c'), { a: ['b', 'c'] });
-        st.deepEqual(qs.parse('a=b&a[0]=c'), { a: ['b', 'c'] });
-
-        st.deepEqual(qs.parse('a[1]=b&a=c', { arrayLimit: 20 }), { a: ['b', 'c'] });
-        st.deepEqual(qs.parse('a[]=b&a=c', { arrayLimit: 0 }), { a: ['b', 'c'] });
-        st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] });
-
-        st.deepEqual(qs.parse('a=b&a[1]=c', { arrayLimit: 20 }), { a: ['b', 'c'] });
-        st.deepEqual(qs.parse('a=b&a[]=c', { arrayLimit: 0 }), { a: ['b', 'c'] });
-        st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] });
-
-        st.end();
-    });
-
-    t.test('parses a nested array', function (st) {
-        st.deepEqual(qs.parse('a[b][]=c&a[b][]=d'), { a: { b: ['c', 'd'] } });
-        st.deepEqual(qs.parse('a[>=]=25'), { a: { '>=': '25' } });
-        st.end();
-    });
-
-    t.test('allows to specify array indices', function (st) {
-        st.deepEqual(qs.parse('a[1]=c&a[0]=b&a[2]=d'), { a: ['b', 'c', 'd'] });
-        st.deepEqual(qs.parse('a[1]=c&a[0]=b'), { a: ['b', 'c'] });
-        st.deepEqual(qs.parse('a[1]=c', { arrayLimit: 20 }), { a: ['c'] });
-        st.deepEqual(qs.parse('a[1]=c', { arrayLimit: 0 }), { a: { 1: 'c' } });
-        st.deepEqual(qs.parse('a[1]=c'), { a: ['c'] });
-        st.end();
-    });
-
-    t.test('limits specific array indices to arrayLimit', function (st) {
-        st.deepEqual(qs.parse('a[20]=a', { arrayLimit: 20 }), { a: ['a'] });
-        st.deepEqual(qs.parse('a[21]=a', { arrayLimit: 20 }), { a: { 21: 'a' } });
-        st.end();
-    });
-
-    t.deepEqual(qs.parse('a[12b]=c'), { a: { '12b': 'c' } }, 'supports keys that begin with a number');
-
-    t.test('supports encoded = signs', function (st) {
-        st.deepEqual(qs.parse('he%3Dllo=th%3Dere'), { 'he=llo': 'th=ere' });
-        st.end();
-    });
-
-    t.test('is ok with url encoded strings', function (st) {
-        st.deepEqual(qs.parse('a[b%20c]=d'), { a: { 'b c': 'd' } });
-        st.deepEqual(qs.parse('a[b]=c%20d'), { a: { b: 'c d' } });
-        st.end();
-    });
-
-    t.test('allows brackets in the value', function (st) {
-        st.deepEqual(qs.parse('pets=["tobi"]'), { pets: '["tobi"]' });
-        st.deepEqual(qs.parse('operators=[">=", "<="]'), { operators: '[">=", "<="]' });
-        st.end();
-    });
-
-    t.test('allows empty values', function (st) {
-        st.deepEqual(qs.parse(''), {});
-        st.deepEqual(qs.parse(null), {});
-        st.deepEqual(qs.parse(undefined), {});
-        st.end();
-    });
-
-    t.test('transforms arrays to objects', function (st) {
-        st.deepEqual(qs.parse('foo[0]=bar&foo[bad]=baz'), { foo: { 0: 'bar', bad: 'baz' } });
-        st.deepEqual(qs.parse('foo[bad]=baz&foo[0]=bar'), { foo: { bad: 'baz', 0: 'bar' } });
-        st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar'), { foo: { bad: 'baz', 0: 'bar' } });
-        st.deepEqual(qs.parse('foo[]=bar&foo[bad]=baz'), { foo: { 0: 'bar', bad: 'baz' } });
-        st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo'), { foo: { bad: 'baz', 0: 'bar', 1: 'foo' } });
-        st.deepEqual(qs.parse('foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb'), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] });
-
-        st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: false }), { a: { 0: 'b', t: 'u' } });
-        st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: true }), { a: { 0: 'b', t: 'u', hasOwnProperty: 'c' } });
-        st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: false }), { a: { 0: 'b', x: 'y' } });
-        st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: true }), { a: { 0: 'b', hasOwnProperty: 'c', x: 'y' } });
-        st.end();
-    });
-
-    t.test('transforms arrays to objects (dot notation)', function (st) {
-        st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: 'baz' } });
-        st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad.boo=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: { boo: 'baz' } } });
-        st.deepEqual(qs.parse('foo[0][0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [[{ baz: 'bar' }]], fool: { bad: 'baz' } });
-        st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15'], bar: '2' }] });
-        st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].baz[1]=16&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15', '16'], bar: '2' }] });
-        st.deepEqual(qs.parse('foo.bad=baz&foo[0]=bar', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar' } });
-        st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar' } });
-        st.deepEqual(qs.parse('foo[]=bar&foo.bad=baz', { allowDots: true }), { foo: { 0: 'bar', bad: 'baz' } });
-        st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar&foo[]=foo', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar', 1: 'foo' } });
-        st.deepEqual(qs.parse('foo[0].a=a&foo[0].b=b&foo[1].a=aa&foo[1].b=bb', { allowDots: true }), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] });
-        st.end();
-    });
-
-    t.test('correctly prunes undefined values when converting an array to an object', function (st) {
-        st.deepEqual(qs.parse('a[2]=b&a[99999999]=c'), { a: { 2: 'b', 99999999: 'c' } });
-        st.end();
-    });
-
-    t.test('supports malformed uri characters', function (st) {
-        st.deepEqual(qs.parse('{%:%}', { strictNullHandling: true }), { '{%:%}': null });
-        st.deepEqual(qs.parse('{%:%}='), { '{%:%}': '' });
-        st.deepEqual(qs.parse('foo=%:%}'), { foo: '%:%}' });
-        st.end();
-    });
-
-    t.test('doesn\'t produce empty keys', function (st) {
-        st.deepEqual(qs.parse('_r=1&'), { _r: '1' });
-        st.end();
-    });
-
-    t.test('cannot access Object prototype', function (st) {
-        qs.parse('constructor[prototype][bad]=bad');
-        qs.parse('bad[constructor][prototype][bad]=bad');
-        st.equal(typeof Object.prototype.bad, 'undefined');
-        st.end();
-    });
-
-    t.test('parses arrays of objects', function (st) {
-        st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] });
-        st.deepEqual(qs.parse('a[0][b]=c'), { a: [{ b: 'c' }] });
-        st.end();
-    });
-
-    t.test('allows for empty strings in arrays', function (st) {
-        st.deepEqual(qs.parse('a[]=b&a[]=&a[]=c'), { a: ['b', '', 'c'] });
-
-        st.deepEqual(
-            qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', { strictNullHandling: true, arrayLimit: 20 }),
-            { a: ['b', null, 'c', ''] },
-            'with arrayLimit 20 + array indices: null then empty string works'
-        );
-        st.deepEqual(
-            qs.parse('a[]=b&a[]&a[]=c&a[]=', { strictNullHandling: true, arrayLimit: 0 }),
-            { a: ['b', null, 'c', ''] },
-            'with arrayLimit 0 + array brackets: null then empty string works'
-        );
-
-        st.deepEqual(
-            qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', { strictNullHandling: true, arrayLimit: 20 }),
-            { a: ['b', '', 'c', null] },
-            'with arrayLimit 20 + array indices: empty string then null works'
-        );
-        st.deepEqual(
-            qs.parse('a[]=b&a[]=&a[]=c&a[]', { strictNullHandling: true, arrayLimit: 0 }),
-            { a: ['b', '', 'c', null] },
-            'with arrayLimit 0 + array brackets: empty string then null works'
-        );
-
-        st.deepEqual(
-            qs.parse('a[]=&a[]=b&a[]=c'),
-            { a: ['', 'b', 'c'] },
-            'array brackets: empty strings work'
-        );
-        st.end();
-    });
-
-    t.test('compacts sparse arrays', function (st) {
-        st.deepEqual(qs.parse('a[10]=1&a[2]=2', { arrayLimit: 20 }), { a: ['2', '1'] });
-        st.deepEqual(qs.parse('a[1][b][2][c]=1', { arrayLimit: 20 }), { a: [{ b: [{ c: '1' }] }] });
-        st.deepEqual(qs.parse('a[1][2][3][c]=1', { arrayLimit: 20 }), { a: [[[{ c: '1' }]]] });
-        st.deepEqual(qs.parse('a[1][2][3][c][1]=1', { arrayLimit: 20 }), { a: [[[{ c: ['1'] }]]] });
-        st.end();
-    });
-
-    t.test('parses semi-parsed strings', function (st) {
-        st.deepEqual(qs.parse({ 'a[b]': 'c' }), { a: { b: 'c' } });
-        st.deepEqual(qs.parse({ 'a[b]': 'c', 'a[d]': 'e' }), { a: { b: 'c', d: 'e' } });
-        st.end();
-    });
-
-    t.test('parses buffers correctly', function (st) {
-        var b = SaferBuffer.from('test');
-        st.deepEqual(qs.parse({ a: b }), { a: b });
-        st.end();
-    });
-
-    t.test('parses jquery-param strings', function (st) {
-        // readable = 'filter[0][]=int1&filter[0][]==&filter[0][]=77&filter[]=and&filter[2][]=int2&filter[2][]==&filter[2][]=8'
-        var encoded = 'filter%5B0%5D%5B%5D=int1&filter%5B0%5D%5B%5D=%3D&filter%5B0%5D%5B%5D=77&filter%5B%5D=and&filter%5B2%5D%5B%5D=int2&filter%5B2%5D%5B%5D=%3D&filter%5B2%5D%5B%5D=8';
-        var expected = { filter: [['int1', '=', '77'], 'and', ['int2', '=', '8']] };
-        st.deepEqual(qs.parse(encoded), expected);
-        st.end();
-    });
-
-    t.test('continues parsing when no parent is found', function (st) {
-        st.deepEqual(qs.parse('[]=&a=b'), { 0: '', a: 'b' });
-        st.deepEqual(qs.parse('[]&a=b', { strictNullHandling: true }), { 0: null, a: 'b' });
-        st.deepEqual(qs.parse('[foo]=bar'), { foo: 'bar' });
-        st.end();
-    });
-
-    t.test('does not error when parsing a very long array', function (st) {
-        var str = 'a[]=a';
-        while (Buffer.byteLength(str) < 128 * 1024) {
-            str = str + '&' + str;
-        }
-
-        st.doesNotThrow(function () {
-            qs.parse(str);
-        });
-
-        st.end();
-    });
-
-    t.test('should not throw when a native prototype has an enumerable property', function (st) {
-        Object.prototype.crash = '';
-        Array.prototype.crash = '';
-        st.doesNotThrow(qs.parse.bind(null, 'a=b'));
-        st.deepEqual(qs.parse('a=b'), { a: 'b' });
-        st.doesNotThrow(qs.parse.bind(null, 'a[][b]=c'));
-        st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] });
-        delete Object.prototype.crash;
-        delete Array.prototype.crash;
-        st.end();
-    });
-
-    t.test('parses a string with an alternative string delimiter', function (st) {
-        st.deepEqual(qs.parse('a=b;c=d', { delimiter: ';' }), { a: 'b', c: 'd' });
-        st.end();
-    });
-
-    t.test('parses a string with an alternative RegExp delimiter', function (st) {
-        st.deepEqual(qs.parse('a=b; c=d', { delimiter: /[;,] */ }), { a: 'b', c: 'd' });
-        st.end();
-    });
-
-    t.test('does not use non-splittable objects as delimiters', function (st) {
-        st.deepEqual(qs.parse('a=b&c=d', { delimiter: true }), { a: 'b', c: 'd' });
-        st.end();
-    });
-
-    t.test('allows overriding parameter limit', function (st) {
-        st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: 1 }), { a: 'b' });
-        st.end();
-    });
-
-    t.test('allows setting the parameter limit to Infinity', function (st) {
-        st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: Infinity }), { a: 'b', c: 'd' });
-        st.end();
-    });
-
-    t.test('allows overriding array limit', function (st) {
-        st.deepEqual(qs.parse('a[0]=b', { arrayLimit: -1 }), { a: { 0: 'b' } });
-        st.deepEqual(qs.parse('a[-1]=b', { arrayLimit: -1 }), { a: { '-1': 'b' } });
-        st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayLimit: 0 }), { a: { 0: 'b', 1: 'c' } });
-        st.end();
-    });
-
-    t.test('allows disabling array parsing', function (st) {
-        var indices = qs.parse('a[0]=b&a[1]=c', { parseArrays: false });
-        st.deepEqual(indices, { a: { 0: 'b', 1: 'c' } });
-        st.equal(Array.isArray(indices.a), false, 'parseArrays:false, indices case is not an array');
-
-        var emptyBrackets = qs.parse('a[]=b', { parseArrays: false });
-        st.deepEqual(emptyBrackets, { a: { 0: 'b' } });
-        st.equal(Array.isArray(emptyBrackets.a), false, 'parseArrays:false, empty brackets case is not an array');
-
-        st.end();
-    });
-
-    t.test('allows for query string prefix', function (st) {
-        st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' });
-        st.deepEqual(qs.parse('foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' });
-        st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: false }), { '?foo': 'bar' });
-        st.end();
-    });
-
-    t.test('parses an object', function (st) {
-        var input = {
-            'user[name]': { 'pop[bob]': 3 },
-            'user[email]': null
-        };
-
-        var expected = {
-            user: {
-                name: { 'pop[bob]': 3 },
-                email: null
-            }
-        };
-
-        var result = qs.parse(input);
-
-        st.deepEqual(result, expected);
-        st.end();
-    });
-
-    t.test('parses string with comma as array divider', function (st) {
-        st.deepEqual(qs.parse('foo=bar,tee', { comma: true }), { foo: ['bar', 'tee'] });
-        st.deepEqual(qs.parse('foo[bar]=coffee,tee', { comma: true }), { foo: { bar: ['coffee', 'tee'] } });
-        st.deepEqual(qs.parse('foo=', { comma: true }), { foo: '' });
-        st.deepEqual(qs.parse('foo', { comma: true }), { foo: '' });
-        st.deepEqual(qs.parse('foo', { comma: true, strictNullHandling: true }), { foo: null });
-        st.end();
-    });
-
-    t.test('parses an object in dot notation', function (st) {
-        var input = {
-            'user.name': { 'pop[bob]': 3 },
-            'user.email.': null
-        };
-
-        var expected = {
-            user: {
-                name: { 'pop[bob]': 3 },
-                email: null
-            }
-        };
-
-        var result = qs.parse(input, { allowDots: true });
-
-        st.deepEqual(result, expected);
-        st.end();
-    });
-
-    t.test('parses an object and not child values', function (st) {
-        var input = {
-            'user[name]': { 'pop[bob]': { test: 3 } },
-            'user[email]': null
-        };
-
-        var expected = {
-            user: {
-                name: { 'pop[bob]': { test: 3 } },
-                email: null
-            }
-        };
-
-        var result = qs.parse(input);
-
-        st.deepEqual(result, expected);
-        st.end();
-    });
-
-    t.test('does not blow up when Buffer global is missing', function (st) {
-        var tempBuffer = global.Buffer;
-        delete global.Buffer;
-        var result = qs.parse('a=b&c=d');
-        global.Buffer = tempBuffer;
-        st.deepEqual(result, { a: 'b', c: 'd' });
-        st.end();
-    });
-
-    t.test('does not crash when parsing circular references', function (st) {
-        var a = {};
-        a.b = a;
-
-        var parsed;
-
-        st.doesNotThrow(function () {
-            parsed = qs.parse({ 'foo[bar]': 'baz', 'foo[baz]': a });
-        });
-
-        st.equal('foo' in parsed, true, 'parsed has "foo" property');
-        st.equal('bar' in parsed.foo, true);
-        st.equal('baz' in parsed.foo, true);
-        st.equal(parsed.foo.bar, 'baz');
-        st.deepEqual(parsed.foo.baz, a);
-        st.end();
-    });
-
-    t.test('does not crash when parsing deep objects', function (st) {
-        var parsed;
-        var str = 'foo';
-
-        for (var i = 0; i < 5000; i++) {
-            str += '[p]';
-        }
-
-        str += '=bar';
-
-        st.doesNotThrow(function () {
-            parsed = qs.parse(str, { depth: 5000 });
-        });
-
-        st.equal('foo' in parsed, true, 'parsed has "foo" property');
-
-        var depth = 0;
-        var ref = parsed.foo;
-        while ((ref = ref.p)) {
-            depth += 1;
-        }
-
-        st.equal(depth, 5000, 'parsed is 5000 properties deep');
-
-        st.end();
-    });
-
-    t.test('parses null objects correctly', { skip: !Object.create }, function (st) {
-        var a = Object.create(null);
-        a.b = 'c';
-
-        st.deepEqual(qs.parse(a), { b: 'c' });
-        var result = qs.parse({ a: a });
-        st.equal('a' in result, true, 'result has "a" property');
-        st.deepEqual(result.a, a);
-        st.end();
-    });
-
-    t.test('parses dates correctly', function (st) {
-        var now = new Date();
-        st.deepEqual(qs.parse({ a: now }), { a: now });
-        st.end();
-    });
-
-    t.test('parses regular expressions correctly', function (st) {
-        var re = /^test$/;
-        st.deepEqual(qs.parse({ a: re }), { a: re });
-        st.end();
-    });
-
-    t.test('does not allow overwriting prototype properties', function (st) {
-        st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: false }), {});
-        st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: false }), {});
-
-        st.deepEqual(
-            qs.parse('toString', { allowPrototypes: false }),
-            {},
-            'bare "toString" results in {}'
-        );
-
-        st.end();
-    });
-
-    t.test('can allow overwriting prototype properties', function (st) {
-        st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }), { a: { hasOwnProperty: 'b' } });
-        st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: true }), { hasOwnProperty: 'b' });
-
-        st.deepEqual(
-            qs.parse('toString', { allowPrototypes: true }),
-            { toString: '' },
-            'bare "toString" results in { toString: "" }'
-        );
-
-        st.end();
-    });
-
-    t.test('params starting with a closing bracket', function (st) {
-        st.deepEqual(qs.parse(']=toString'), { ']': 'toString' });
-        st.deepEqual(qs.parse(']]=toString'), { ']]': 'toString' });
-        st.deepEqual(qs.parse(']hello]=toString'), { ']hello]': 'toString' });
-        st.end();
-    });
-
-    t.test('params starting with a starting bracket', function (st) {
-        st.deepEqual(qs.parse('[=toString'), { '[': 'toString' });
-        st.deepEqual(qs.parse('[[=toString'), { '[[': 'toString' });
-        st.deepEqual(qs.parse('[hello[=toString'), { '[hello[': 'toString' });
-        st.end();
-    });
-
-    t.test('add keys to objects', function (st) {
-        st.deepEqual(
-            qs.parse('a[b]=c&a=d'),
-            { a: { b: 'c', d: true } },
-            'can add keys to objects'
-        );
-
-        st.deepEqual(
-            qs.parse('a[b]=c&a=toString'),
-            { a: { b: 'c' } },
-            'can not overwrite prototype'
-        );
-
-        st.deepEqual(
-            qs.parse('a[b]=c&a=toString', { allowPrototypes: true }),
-            { a: { b: 'c', toString: true } },
-            'can overwrite prototype with allowPrototypes true'
-        );
-
-        st.deepEqual(
-            qs.parse('a[b]=c&a=toString', { plainObjects: true }),
-            { a: { b: 'c', toString: true } },
-            'can overwrite prototype with plainObjects true'
-        );
-
-        st.end();
-    });
-
-    t.test('can return null objects', { skip: !Object.create }, function (st) {
-        var expected = Object.create(null);
-        expected.a = Object.create(null);
-        expected.a.b = 'c';
-        expected.a.hasOwnProperty = 'd';
-        st.deepEqual(qs.parse('a[b]=c&a[hasOwnProperty]=d', { plainObjects: true }), expected);
-        st.deepEqual(qs.parse(null, { plainObjects: true }), Object.create(null));
-        var expectedArray = Object.create(null);
-        expectedArray.a = Object.create(null);
-        expectedArray.a[0] = 'b';
-        expectedArray.a.c = 'd';
-        st.deepEqual(qs.parse('a[]=b&a[c]=d', { plainObjects: true }), expectedArray);
-        st.end();
-    });
-
-    t.test('can parse with custom encoding', function (st) {
-        st.deepEqual(qs.parse('%8c%a7=%91%e5%8d%e3%95%7b', {
-            decoder: function (str) {
-                var reg = /%([0-9A-F]{2})/ig;
-                var result = [];
-                var parts = reg.exec(str);
-                while (parts) {
-                    result.push(parseInt(parts[1], 16));
-                    parts = reg.exec(str);
-                }
-                return String(iconv.decode(SaferBuffer.from(result), 'shift_jis'));
-            }
-        }), { 県: '大阪府' });
-        st.end();
-    });
-
-    t.test('receives the default decoder as a second argument', function (st) {
-        st.plan(1);
-        qs.parse('a', {
-            decoder: function (str, defaultDecoder) {
-                st.equal(defaultDecoder, utils.decode);
-            }
-        });
-        st.end();
-    });
-
-    t.test('throws error with wrong decoder', function (st) {
-        st['throws'](function () {
-            qs.parse({}, { decoder: 'string' });
-        }, new TypeError('Decoder has to be a function.'));
-        st.end();
-    });
-
-    t.test('does not mutate the options argument', function (st) {
-        var options = {};
-        qs.parse('a[b]=true', options);
-        st.deepEqual(options, {});
-        st.end();
-    });
-
-    t.test('throws if an invalid charset is specified', function (st) {
-        st['throws'](function () {
-            qs.parse('a=b', { charset: 'foobar' });
-        }, new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'));
-        st.end();
-    });
-
-    t.test('parses an iso-8859-1 string if asked to', function (st) {
-        st.deepEqual(qs.parse('%A2=%BD', { charset: 'iso-8859-1' }), { '¢': '½' });
-        st.end();
-    });
-
-    var urlEncodedCheckmarkInUtf8 = '%E2%9C%93';
-    var urlEncodedOSlashInUtf8 = '%C3%B8';
-    var urlEncodedNumCheckmark = '%26%2310003%3B';
-    var urlEncodedNumSmiley = '%26%239786%3B';
-
-    t.test('prefers an utf-8 charset specified by the utf8 sentinel to a default charset of iso-8859-1', function (st) {
-        st.deepEqual(qs.parse('utf8=' + urlEncodedCheckmarkInUtf8 + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'iso-8859-1' }), { ø: 'ø' });
-        st.end();
-    });
-
-    t.test('prefers an iso-8859-1 charset specified by the utf8 sentinel to a default charset of utf-8', function (st) {
-        st.deepEqual(qs.parse('utf8=' + urlEncodedNumCheckmark + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'utf-8' }), { 'ø': 'ø' });
-        st.end();
-    });
-
-    t.test('does not require the utf8 sentinel to be defined before the parameters whose decoding it affects', function (st) {
-        st.deepEqual(qs.parse('a=' + urlEncodedOSlashInUtf8 + '&utf8=' + urlEncodedNumCheckmark, { charsetSentinel: true, charset: 'utf-8' }), { a: 'ø' });
-        st.end();
-    });
-
-    t.test('should ignore an utf8 sentinel with an unknown value', function (st) {
-        st.deepEqual(qs.parse('utf8=foo&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'utf-8' }), { ø: 'ø' });
-        st.end();
-    });
-
-    t.test('uses the utf8 sentinel to switch to utf-8 when no default charset is given', function (st) {
-        st.deepEqual(qs.parse('utf8=' + urlEncodedCheckmarkInUtf8 + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true }), { ø: 'ø' });
-        st.end();
-    });
-
-    t.test('uses the utf8 sentinel to switch to iso-8859-1 when no default charset is given', function (st) {
-        st.deepEqual(qs.parse('utf8=' + urlEncodedNumCheckmark + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true }), { 'ø': 'ø' });
-        st.end();
-    });
-
-    t.test('interprets numeric entities in iso-8859-1 when `interpretNumericEntities`', function (st) {
-        st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'iso-8859-1', interpretNumericEntities: true }), { foo: '☺' });
-        st.end();
-    });
-
-    t.test('handles a custom decoder returning `null`, in the `iso-8859-1` charset, when `interpretNumericEntities`', function (st) {
-        st.deepEqual(qs.parse('foo=&bar=' + urlEncodedNumSmiley, {
-            charset: 'iso-8859-1',
-            decoder: function (str, defaultDecoder, charset) {
-                return str ? defaultDecoder(str, defaultDecoder, charset) : null;
-            },
-            interpretNumericEntities: true
-        }), { foo: null, bar: '☺' });
-        st.end();
-    });
-
-    t.test('does not interpret numeric entities in iso-8859-1 when `interpretNumericEntities` is absent', function (st) {
-        st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'iso-8859-1' }), { foo: '&#9786;' });
-        st.end();
-    });
-
-    t.test('does not interpret numeric entities when the charset is utf-8, even when `interpretNumericEntities`', function (st) {
-        st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'utf-8', interpretNumericEntities: true }), { foo: '&#9786;' });
-        st.end();
-    });
-
-    t.test('does not interpret %uXXXX syntax in iso-8859-1 mode', function (st) {
-        st.deepEqual(qs.parse('%u263A=%u263A', { charset: 'iso-8859-1' }), { '%u263A': '%u263A' });
-        st.end();
-    });
-
-    t.end();
-});
+"use strict";var test=require("tape"),qs=require("../"),utils=require("../lib/utils"),iconv=require("iconv-lite"),SaferBuffer=require("safer-buffer").Buffer;test("parse()",(function(e){e.test("parses a simple string",(function(e){e.deepEqual(qs.parse("0=foo"),{0:"foo"}),e.deepEqual(qs.parse("foo=c++"),{foo:"c  "}),e.deepEqual(qs.parse("a[>=]=23"),{a:{">=":"23"}}),e.deepEqual(qs.parse("a[<=>]==23"),{a:{"<=>":"=23"}}),e.deepEqual(qs.parse("a[==]=23"),{a:{"==":"23"}}),e.deepEqual(qs.parse("foo",{strictNullHandling:!0}),{foo:null}),e.deepEqual(qs.parse("foo"),{foo:""}),e.deepEqual(qs.parse("foo="),{foo:""}),e.deepEqual(qs.parse("foo=bar"),{foo:"bar"}),e.deepEqual(qs.parse(" foo = bar = baz "),{" foo ":" bar = baz "}),e.deepEqual(qs.parse("foo=bar=baz"),{foo:"bar=baz"}),e.deepEqual(qs.parse("foo=bar&bar=baz"),{foo:"bar",bar:"baz"}),e.deepEqual(qs.parse("foo2=bar2&baz2="),{foo2:"bar2",baz2:""}),e.deepEqual(qs.parse("foo=bar&baz",{strictNullHandling:!0}),{foo:"bar",baz:null}),e.deepEqual(qs.parse("foo=bar&baz"),{foo:"bar",baz:""}),e.deepEqual(qs.parse("cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World"),{cht:"p3",chd:"t:60,40",chs:"250x100",chl:"Hello|World"}),e.end()})),e.test("allows enabling dot notation",(function(e){e.deepEqual(qs.parse("a.b=c"),{"a.b":"c"}),e.deepEqual(qs.parse("a.b=c",{allowDots:!0}),{a:{b:"c"}}),e.end()})),e.deepEqual(qs.parse("a[b]=c"),{a:{b:"c"}},"parses a single nested string"),e.deepEqual(qs.parse("a[b][c]=d"),{a:{b:{c:"d"}}},"parses a double nested string"),e.deepEqual(qs.parse("a[b][c][d][e][f][g][h]=i"),{a:{b:{c:{d:{e:{f:{"[g][h]":"i"}}}}}}},"defaults to a depth of 5"),e.test("only parses one level when depth = 1",(function(e){e.deepEqual(qs.parse("a[b][c]=d",{depth:1}),{a:{b:{"[c]":"d"}}}),e.deepEqual(qs.parse("a[b][c][d]=e",{depth:1}),{a:{b:{"[c][d]":"e"}}}),e.end()})),e.deepEqual(qs.parse("a=b&a=c"),{a:["b","c"]},"parses a simple array"),e.test("parses an explicit array",(function(e){e.deepEqual(qs.parse("a[]=b"),{a:["b"]}),e.deepEqual(qs.parse("a[]=b&a[]=c"),{a:["b","c"]}),e.deepEqual(qs.parse("a[]=b&a[]=c&a[]=d"),{a:["b","c","d"]}),e.end()})),e.test("parses a mix of simple and explicit arrays",(function(e){e.deepEqual(qs.parse("a=b&a[]=c"),{a:["b","c"]}),e.deepEqual(qs.parse("a[]=b&a=c"),{a:["b","c"]}),e.deepEqual(qs.parse("a[0]=b&a=c"),{a:["b","c"]}),e.deepEqual(qs.parse("a=b&a[0]=c"),{a:["b","c"]}),e.deepEqual(qs.parse("a[1]=b&a=c",{arrayLimit:20}),{a:["b","c"]}),e.deepEqual(qs.parse("a[]=b&a=c",{arrayLimit:0}),{a:["b","c"]}),e.deepEqual(qs.parse("a[]=b&a=c"),{a:["b","c"]}),e.deepEqual(qs.parse("a=b&a[1]=c",{arrayLimit:20}),{a:["b","c"]}),e.deepEqual(qs.parse("a=b&a[]=c",{arrayLimit:0}),{a:["b","c"]}),e.deepEqual(qs.parse("a=b&a[]=c"),{a:["b","c"]}),e.end()})),e.test("parses a nested array",(function(e){e.deepEqual(qs.parse("a[b][]=c&a[b][]=d"),{a:{b:["c","d"]}}),e.deepEqual(qs.parse("a[>=]=25"),{a:{">=":"25"}}),e.end()})),e.test("allows to specify array indices",(function(e){e.deepEqual(qs.parse("a[1]=c&a[0]=b&a[2]=d"),{a:["b","c","d"]}),e.deepEqual(qs.parse("a[1]=c&a[0]=b"),{a:["b","c"]}),e.deepEqual(qs.parse("a[1]=c",{arrayLimit:20}),{a:["c"]}),e.deepEqual(qs.parse("a[1]=c",{arrayLimit:0}),{a:{1:"c"}}),e.deepEqual(qs.parse("a[1]=c"),{a:["c"]}),e.end()})),e.test("limits specific array indices to arrayLimit",(function(e){e.deepEqual(qs.parse("a[20]=a",{arrayLimit:20}),{a:["a"]}),e.deepEqual(qs.parse("a[21]=a",{arrayLimit:20}),{a:{21:"a"}}),e.end()})),e.deepEqual(qs.parse("a[12b]=c"),{a:{"12b":"c"}},"supports keys that begin with a number"),e.test("supports encoded = signs",(function(e){e.deepEqual(qs.parse("he%3Dllo=th%3Dere"),{"he=llo":"th=ere"}),e.end()})),e.test("is ok with url encoded strings",(function(e){e.deepEqual(qs.parse("a[b%20c]=d"),{a:{"b c":"d"}}),e.deepEqual(qs.parse("a[b]=c%20d"),{a:{b:"c d"}}),e.end()})),e.test("allows brackets in the value",(function(e){e.deepEqual(qs.parse('pets=["tobi"]'),{pets:'["tobi"]'}),e.deepEqual(qs.parse('operators=[">=", "<="]'),{operators:'[">=", "<="]'}),e.end()})),e.test("allows empty values",(function(e){e.deepEqual(qs.parse(""),{}),e.deepEqual(qs.parse(null),{}),e.deepEqual(qs.parse(void 0),{}),e.end()})),e.test("transforms arrays to objects",(function(e){e.deepEqual(qs.parse("foo[0]=bar&foo[bad]=baz"),{foo:{0:"bar",bad:"baz"}}),e.deepEqual(qs.parse("foo[bad]=baz&foo[0]=bar"),{foo:{bad:"baz",0:"bar"}}),e.deepEqual(qs.parse("foo[bad]=baz&foo[]=bar"),{foo:{bad:"baz",0:"bar"}}),e.deepEqual(qs.parse("foo[]=bar&foo[bad]=baz"),{foo:{0:"bar",bad:"baz"}}),e.deepEqual(qs.parse("foo[bad]=baz&foo[]=bar&foo[]=foo"),{foo:{bad:"baz",0:"bar",1:"foo"}}),e.deepEqual(qs.parse("foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb"),{foo:[{a:"a",b:"b"},{a:"aa",b:"bb"}]}),e.deepEqual(qs.parse("a[]=b&a[t]=u&a[hasOwnProperty]=c",{allowPrototypes:!1}),{a:{0:"b",t:"u"}}),e.deepEqual(qs.parse("a[]=b&a[t]=u&a[hasOwnProperty]=c",{allowPrototypes:!0}),{a:{0:"b",t:"u",hasOwnProperty:"c"}}),e.deepEqual(qs.parse("a[]=b&a[hasOwnProperty]=c&a[x]=y",{allowPrototypes:!1}),{a:{0:"b",x:"y"}}),e.deepEqual(qs.parse("a[]=b&a[hasOwnProperty]=c&a[x]=y",{allowPrototypes:!0}),{a:{0:"b",hasOwnProperty:"c",x:"y"}}),e.end()})),e.test("transforms arrays to objects (dot notation)",(function(e){e.deepEqual(qs.parse("foo[0].baz=bar&fool.bad=baz",{allowDots:!0}),{foo:[{baz:"bar"}],fool:{bad:"baz"}}),e.deepEqual(qs.parse("foo[0].baz=bar&fool.bad.boo=baz",{allowDots:!0}),{foo:[{baz:"bar"}],fool:{bad:{boo:"baz"}}}),e.deepEqual(qs.parse("foo[0][0].baz=bar&fool.bad=baz",{allowDots:!0}),{foo:[[{baz:"bar"}]],fool:{bad:"baz"}}),e.deepEqual(qs.parse("foo[0].baz[0]=15&foo[0].bar=2",{allowDots:!0}),{foo:[{baz:["15"],bar:"2"}]}),e.deepEqual(qs.parse("foo[0].baz[0]=15&foo[0].baz[1]=16&foo[0].bar=2",{allowDots:!0}),{foo:[{baz:["15","16"],bar:"2"}]}),e.deepEqual(qs.parse("foo.bad=baz&foo[0]=bar",{allowDots:!0}),{foo:{bad:"baz",0:"bar"}}),e.deepEqual(qs.parse("foo.bad=baz&foo[]=bar",{allowDots:!0}),{foo:{bad:"baz",0:"bar"}}),e.deepEqual(qs.parse("foo[]=bar&foo.bad=baz",{allowDots:!0}),{foo:{0:"bar",bad:"baz"}}),e.deepEqual(qs.parse("foo.bad=baz&foo[]=bar&foo[]=foo",{allowDots:!0}),{foo:{bad:"baz",0:"bar",1:"foo"}}),e.deepEqual(qs.parse("foo[0].a=a&foo[0].b=b&foo[1].a=aa&foo[1].b=bb",{allowDots:!0}),{foo:[{a:"a",b:"b"},{a:"aa",b:"bb"}]}),e.end()})),e.test("correctly prunes undefined values when converting an array to an object",(function(e){e.deepEqual(qs.parse("a[2]=b&a[99999999]=c"),{a:{2:"b",99999999:"c"}}),e.end()})),e.test("supports malformed uri characters",(function(e){e.deepEqual(qs.parse("{%:%}",{strictNullHandling:!0}),{"{%:%}":null}),e.deepEqual(qs.parse("{%:%}="),{"{%:%}":""}),e.deepEqual(qs.parse("foo=%:%}"),{foo:"%:%}"}),e.end()})),e.test("doesn't produce empty keys",(function(e){e.deepEqual(qs.parse("_r=1&"),{_r:"1"}),e.end()})),e.test("cannot access Object prototype",(function(e){qs.parse("constructor[prototype][bad]=bad"),qs.parse("bad[constructor][prototype][bad]=bad"),e.equal(typeof Object.prototype.bad,"undefined"),e.end()})),e.test("parses arrays of objects",(function(e){e.deepEqual(qs.parse("a[][b]=c"),{a:[{b:"c"}]}),e.deepEqual(qs.parse("a[0][b]=c"),{a:[{b:"c"}]}),e.end()})),e.test("allows for empty strings in arrays",(function(e){e.deepEqual(qs.parse("a[]=b&a[]=&a[]=c"),{a:["b","","c"]}),e.deepEqual(qs.parse("a[0]=b&a[1]&a[2]=c&a[19]=",{strictNullHandling:!0,arrayLimit:20}),{a:["b",null,"c",""]},"with arrayLimit 20 + array indices: null then empty string works"),e.deepEqual(qs.parse("a[]=b&a[]&a[]=c&a[]=",{strictNullHandling:!0,arrayLimit:0}),{a:["b",null,"c",""]},"with arrayLimit 0 + array brackets: null then empty string works"),e.deepEqual(qs.parse("a[0]=b&a[1]=&a[2]=c&a[19]",{strictNullHandling:!0,arrayLimit:20}),{a:["b","","c",null]},"with arrayLimit 20 + array indices: empty string then null works"),e.deepEqual(qs.parse("a[]=b&a[]=&a[]=c&a[]",{strictNullHandling:!0,arrayLimit:0}),{a:["b","","c",null]},"with arrayLimit 0 + array brackets: empty string then null works"),e.deepEqual(qs.parse("a[]=&a[]=b&a[]=c"),{a:["","b","c"]},"array brackets: empty strings work"),e.end()})),e.test("compacts sparse arrays",(function(e){e.deepEqual(qs.parse("a[10]=1&a[2]=2",{arrayLimit:20}),{a:["2","1"]}),e.deepEqual(qs.parse("a[1][b][2][c]=1",{arrayLimit:20}),{a:[{b:[{c:"1"}]}]}),e.deepEqual(qs.parse("a[1][2][3][c]=1",{arrayLimit:20}),{a:[[[{c:"1"}]]]}),e.deepEqual(qs.parse("a[1][2][3][c][1]=1",{arrayLimit:20}),{a:[[[{c:["1"]}]]]}),e.end()})),e.test("parses semi-parsed strings",(function(e){e.deepEqual(qs.parse({"a[b]":"c"}),{a:{b:"c"}}),e.deepEqual(qs.parse({"a[b]":"c","a[d]":"e"}),{a:{b:"c",d:"e"}}),e.end()})),e.test("parses buffers correctly",(function(e){var a=SaferBuffer.from("test");e.deepEqual(qs.parse({a:a}),{a:a}),e.end()})),e.test("parses jquery-param strings",(function(e){e.deepEqual(qs.parse("filter%5B0%5D%5B%5D=int1&filter%5B0%5D%5B%5D=%3D&filter%5B0%5D%5B%5D=77&filter%5B%5D=and&filter%5B2%5D%5B%5D=int2&filter%5B2%5D%5B%5D=%3D&filter%5B2%5D%5B%5D=8"),{filter:[["int1","=","77"],"and",["int2","=","8"]]}),e.end()})),e.test("continues parsing when no parent is found",(function(e){e.deepEqual(qs.parse("[]=&a=b"),{0:"",a:"b"}),e.deepEqual(qs.parse("[]&a=b",{strictNullHandling:!0}),{0:null,a:"b"}),e.deepEqual(qs.parse("[foo]=bar"),{foo:"bar"}),e.end()})),e.test("does not error when parsing a very long array",(function(e){for(var a="a[]=a";Buffer.byteLength(a)<131072;)a=a+"&"+a;e.doesNotThrow((function(){qs.parse(a)})),e.end()})),e.test("should not throw when a native prototype has an enumerable property",(function(e){Object.prototype.crash="",Array.prototype.crash="",e.doesNotThrow(qs.parse.bind(null,"a=b")),e.deepEqual(qs.parse("a=b"),{a:"b"}),e.doesNotThrow(qs.parse.bind(null,"a[][b]=c")),e.deepEqual(qs.parse("a[][b]=c"),{a:[{b:"c"}]}),delete Object.prototype.crash,delete Array.prototype.crash,e.end()})),e.test("parses a string with an alternative string delimiter",(function(e){e.deepEqual(qs.parse("a=b;c=d",{delimiter:";"}),{a:"b",c:"d"}),e.end()})),e.test("parses a string with an alternative RegExp delimiter",(function(e){e.deepEqual(qs.parse("a=b; c=d",{delimiter:/[;,] */}),{a:"b",c:"d"}),e.end()})),e.test("does not use non-splittable objects as delimiters",(function(e){e.deepEqual(qs.parse("a=b&c=d",{delimiter:!0}),{a:"b",c:"d"}),e.end()})),e.test("allows overriding parameter limit",(function(e){e.deepEqual(qs.parse("a=b&c=d",{parameterLimit:1}),{a:"b"}),e.end()})),e.test("allows setting the parameter limit to Infinity",(function(e){e.deepEqual(qs.parse("a=b&c=d",{parameterLimit:1/0}),{a:"b",c:"d"}),e.end()})),e.test("allows overriding array limit",(function(e){e.deepEqual(qs.parse("a[0]=b",{arrayLimit:-1}),{a:{0:"b"}}),e.deepEqual(qs.parse("a[-1]=b",{arrayLimit:-1}),{a:{"-1":"b"}}),e.deepEqual(qs.parse("a[0]=b&a[1]=c",{arrayLimit:0}),{a:{0:"b",1:"c"}}),e.end()})),e.test("allows disabling array parsing",(function(e){var a=qs.parse("a[0]=b&a[1]=c",{parseArrays:!1});e.deepEqual(a,{a:{0:"b",1:"c"}}),e.equal(Array.isArray(a.a),!1,"parseArrays:false, indices case is not an array");var s=qs.parse("a[]=b",{parseArrays:!1});e.deepEqual(s,{a:{0:"b"}}),e.equal(Array.isArray(s.a),!1,"parseArrays:false, empty brackets case is not an array"),e.end()})),e.test("allows for query string prefix",(function(e){e.deepEqual(qs.parse("?foo=bar",{ignoreQueryPrefix:!0}),{foo:"bar"}),e.deepEqual(qs.parse("foo=bar",{ignoreQueryPrefix:!0}),{foo:"bar"}),e.deepEqual(qs.parse("?foo=bar",{ignoreQueryPrefix:!1}),{"?foo":"bar"}),e.end()})),e.test("parses an object",(function(e){var a=qs.parse({"user[name]":{"pop[bob]":3},"user[email]":null});e.deepEqual(a,{user:{name:{"pop[bob]":3},email:null}}),e.end()})),e.test("parses string with comma as array divider",(function(e){e.deepEqual(qs.parse("foo=bar,tee",{comma:!0}),{foo:["bar","tee"]}),e.deepEqual(qs.parse("foo[bar]=coffee,tee",{comma:!0}),{foo:{bar:["coffee","tee"]}}),e.deepEqual(qs.parse("foo=",{comma:!0}),{foo:""}),e.deepEqual(qs.parse("foo",{comma:!0}),{foo:""}),e.deepEqual(qs.parse("foo",{comma:!0,strictNullHandling:!0}),{foo:null}),e.end()})),e.test("parses an object in dot notation",(function(e){var a=qs.parse({"user.name":{"pop[bob]":3},"user.email.":null},{allowDots:!0});e.deepEqual(a,{user:{name:{"pop[bob]":3},email:null}}),e.end()})),e.test("parses an object and not child values",(function(e){var a=qs.parse({"user[name]":{"pop[bob]":{test:3}},"user[email]":null});e.deepEqual(a,{user:{name:{"pop[bob]":{test:3}},email:null}}),e.end()})),e.test("does not blow up when Buffer global is missing",(function(e){var a=global.Buffer;delete global.Buffer;var s=qs.parse("a=b&c=d");global.Buffer=a,e.deepEqual(s,{a:"b",c:"d"}),e.end()})),e.test("does not crash when parsing circular references",(function(e){var a,s={};s.b=s,e.doesNotThrow((function(){a=qs.parse({"foo[bar]":"baz","foo[baz]":s})})),e.equal("foo"in a,!0,'parsed has "foo" property'),e.equal("bar"in a.foo,!0),e.equal("baz"in a.foo,!0),e.equal(a.foo.bar,"baz"),e.deepEqual(a.foo.baz,s),e.end()})),e.test("does not crash when parsing deep objects",(function(e){for(var a,s="foo",r=0;r<5e3;r++)s+="[p]";s+="=bar",e.doesNotThrow((function(){a=qs.parse(s,{depth:5e3})})),e.equal("foo"in a,!0,'parsed has "foo" property');for(var t=0,o=a.foo;o=o.p;)t+=1;e.equal(t,5e3,"parsed is 5000 properties deep"),e.end()})),e.test("parses null objects correctly",{skip:!Object.create},(function(e){var a=Object.create(null);a.b="c",e.deepEqual(qs.parse(a),{b:"c"});var s=qs.parse({a:a});e.equal("a"in s,!0,'result has "a" property'),e.deepEqual(s.a,a),e.end()})),e.test("parses dates correctly",(function(e){var a=new Date;e.deepEqual(qs.parse({a:a}),{a:a}),e.end()})),e.test("parses regular expressions correctly",(function(e){var a=/^test$/;e.deepEqual(qs.parse({a:a}),{a:a}),e.end()})),e.test("does not allow overwriting prototype properties",(function(e){e.deepEqual(qs.parse("a[hasOwnProperty]=b",{allowPrototypes:!1}),{}),e.deepEqual(qs.parse("hasOwnProperty=b",{allowPrototypes:!1}),{}),e.deepEqual(qs.parse("toString",{allowPrototypes:!1}),{},'bare "toString" results in {}'),e.end()})),e.test("can allow overwriting prototype properties",(function(e){e.deepEqual(qs.parse("a[hasOwnProperty]=b",{allowPrototypes:!0}),{a:{hasOwnProperty:"b"}}),e.deepEqual(qs.parse("hasOwnProperty=b",{allowPrototypes:!0}),{hasOwnProperty:"b"}),e.deepEqual(qs.parse("toString",{allowPrototypes:!0}),{toString:""},'bare "toString" results in { toString: "" }'),e.end()})),e.test("params starting with a closing bracket",(function(e){e.deepEqual(qs.parse("]=toString"),{"]":"toString"}),e.deepEqual(qs.parse("]]=toString"),{"]]":"toString"}),e.deepEqual(qs.parse("]hello]=toString"),{"]hello]":"toString"}),e.end()})),e.test("params starting with a starting bracket",(function(e){e.deepEqual(qs.parse("[=toString"),{"[":"toString"}),e.deepEqual(qs.parse("[[=toString"),{"[[":"toString"}),e.deepEqual(qs.parse("[hello[=toString"),{"[hello[":"toString"}),e.end()})),e.test("add keys to objects",(function(e){e.deepEqual(qs.parse("a[b]=c&a=d"),{a:{b:"c",d:!0}},"can add keys to objects"),e.deepEqual(qs.parse("a[b]=c&a=toString"),{a:{b:"c"}},"can not overwrite prototype"),e.deepEqual(qs.parse("a[b]=c&a=toString",{allowPrototypes:!0}),{a:{b:"c",toString:!0}},"can overwrite prototype with allowPrototypes true"),e.deepEqual(qs.parse("a[b]=c&a=toString",{plainObjects:!0}),{a:{b:"c",toString:!0}},"can overwrite prototype with plainObjects true"),e.end()})),e.test("can return null objects",{skip:!Object.create},(function(e){var a=Object.create(null);a.a=Object.create(null),a.a.b="c",a.a.hasOwnProperty="d",e.deepEqual(qs.parse("a[b]=c&a[hasOwnProperty]=d",{plainObjects:!0}),a),e.deepEqual(qs.parse(null,{plainObjects:!0}),Object.create(null));var s=Object.create(null);s.a=Object.create(null),s.a[0]="b",s.a.c="d",e.deepEqual(qs.parse("a[]=b&a[c]=d",{plainObjects:!0}),s),e.end()})),e.test("can parse with custom encoding",(function(e){e.deepEqual(qs.parse("%8c%a7=%91%e5%8d%e3%95%7b",{decoder:function(e){for(var a=/%([0-9A-F]{2})/gi,s=[],r=a.exec(e);r;)s.push(parseInt(r[1],16)),r=a.exec(e);return String(iconv.decode(SaferBuffer.from(s),"shift_jis"))}}),{"県":"大阪府"}),e.end()})),e.test("receives the default decoder as a second argument",(function(e){e.plan(1),qs.parse("a",{decoder:function(a,s){e.equal(s,utils.decode)}}),e.end()})),e.test("throws error with wrong decoder",(function(e){e.throws((function(){qs.parse({},{decoder:"string"})}),new TypeError("Decoder has to be a function.")),e.end()})),e.test("does not mutate the options argument",(function(e){var a={};qs.parse("a[b]=true",a),e.deepEqual(a,{}),e.end()})),e.test("throws if an invalid charset is specified",(function(e){e.throws((function(){qs.parse("a=b",{charset:"foobar"})}),new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined")),e.end()})),e.test("parses an iso-8859-1 string if asked to",(function(e){e.deepEqual(qs.parse("%A2=%BD",{charset:"iso-8859-1"}),{"¢":"½"}),e.end()}));e.test("prefers an utf-8 charset specified by the utf8 sentinel to a default charset of iso-8859-1",(function(e){e.deepEqual(qs.parse("utf8=%E2%9C%93&%C3%B8=%C3%B8",{charsetSentinel:!0,charset:"iso-8859-1"}),{"ø":"ø"}),e.end()})),e.test("prefers an iso-8859-1 charset specified by the utf8 sentinel to a default charset of utf-8",(function(e){e.deepEqual(qs.parse("utf8=%26%2310003%3B&%C3%B8=%C3%B8",{charsetSentinel:!0,charset:"utf-8"}),{"ø":"ø"}),e.end()})),e.test("does not require the utf8 sentinel to be defined before the parameters whose decoding it affects",(function(e){e.deepEqual(qs.parse("a=%C3%B8&utf8=%26%2310003%3B",{charsetSentinel:!0,charset:"utf-8"}),{a:"ø"}),e.end()})),e.test("should ignore an utf8 sentinel with an unknown value",(function(e){e.deepEqual(qs.parse("utf8=foo&%C3%B8=%C3%B8",{charsetSentinel:!0,charset:"utf-8"}),{"ø":"ø"}),e.end()})),e.test("uses the utf8 sentinel to switch to utf-8 when no default charset is given",(function(e){e.deepEqual(qs.parse("utf8=%E2%9C%93&%C3%B8=%C3%B8",{charsetSentinel:!0}),{"ø":"ø"}),e.end()})),e.test("uses the utf8 sentinel to switch to iso-8859-1 when no default charset is given",(function(e){e.deepEqual(qs.parse("utf8=%26%2310003%3B&%C3%B8=%C3%B8",{charsetSentinel:!0}),{"ø":"ø"}),e.end()})),e.test("interprets numeric entities in iso-8859-1 when `interpretNumericEntities`",(function(e){e.deepEqual(qs.parse("foo=%26%239786%3B",{charset:"iso-8859-1",interpretNumericEntities:!0}),{foo:"☺"}),e.end()})),e.test("handles a custom decoder returning `null`, in the `iso-8859-1` charset, when `interpretNumericEntities`",(function(e){e.deepEqual(qs.parse("foo=&bar=%26%239786%3B",{charset:"iso-8859-1",decoder:function(e,a,s){return e?a(e,a,s):null},interpretNumericEntities:!0}),{foo:null,bar:"☺"}),e.end()})),e.test("does not interpret numeric entities in iso-8859-1 when `interpretNumericEntities` is absent",(function(e){e.deepEqual(qs.parse("foo=%26%239786%3B",{charset:"iso-8859-1"}),{foo:"&#9786;"}),e.end()})),e.test("does not interpret numeric entities when the charset is utf-8, even when `interpretNumericEntities`",(function(e){e.deepEqual(qs.parse("foo=%26%239786%3B",{charset:"utf-8",interpretNumericEntities:!0}),{foo:"&#9786;"}),e.end()})),e.test("does not interpret %uXXXX syntax in iso-8859-1 mode",(function(e){e.deepEqual(qs.parse("%u263A=%u263A",{charset:"iso-8859-1"}),{"%u263A":"%u263A"}),e.end()})),e.end()}));
\ No newline at end of file
index 53041c2..ca75482 100644 (file)
@@ -1,679 +1 @@
-'use strict';
-
-var test = require('tape');
-var qs = require('../');
-var utils = require('../lib/utils');
-var iconv = require('iconv-lite');
-var SaferBuffer = require('safer-buffer').Buffer;
-
-test('stringify()', function (t) {
-    t.test('stringifies a querystring object', function (st) {
-        st.equal(qs.stringify({ a: 'b' }), 'a=b');
-        st.equal(qs.stringify({ a: 1 }), 'a=1');
-        st.equal(qs.stringify({ a: 1, b: 2 }), 'a=1&b=2');
-        st.equal(qs.stringify({ a: 'A_Z' }), 'a=A_Z');
-        st.equal(qs.stringify({ a: '€' }), 'a=%E2%82%AC');
-        st.equal(qs.stringify({ a: '' }), 'a=%EE%80%80');
-        st.equal(qs.stringify({ a: 'א' }), 'a=%D7%90');
-        st.equal(qs.stringify({ a: '𐐷' }), 'a=%F0%90%90%B7');
-        st.end();
-    });
-
-    t.test('stringifies falsy values', function (st) {
-        st.equal(qs.stringify(undefined), '');
-        st.equal(qs.stringify(null), '');
-        st.equal(qs.stringify(null, { strictNullHandling: true }), '');
-        st.equal(qs.stringify(false), '');
-        st.equal(qs.stringify(0), '');
-        st.end();
-    });
-
-    t.test('adds query prefix', function (st) {
-        st.equal(qs.stringify({ a: 'b' }, { addQueryPrefix: true }), '?a=b');
-        st.end();
-    });
-
-    t.test('with query prefix, outputs blank string given an empty object', function (st) {
-        st.equal(qs.stringify({}, { addQueryPrefix: true }), '');
-        st.end();
-    });
-
-    t.test('stringifies nested falsy values', function (st) {
-        st.equal(qs.stringify({ a: { b: { c: null } } }), 'a%5Bb%5D%5Bc%5D=');
-        st.equal(qs.stringify({ a: { b: { c: null } } }, { strictNullHandling: true }), 'a%5Bb%5D%5Bc%5D');
-        st.equal(qs.stringify({ a: { b: { c: false } } }), 'a%5Bb%5D%5Bc%5D=false');
-        st.end();
-    });
-
-    t.test('stringifies a nested object', function (st) {
-        st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c');
-        st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }), 'a%5Bb%5D%5Bc%5D%5Bd%5D=e');
-        st.end();
-    });
-
-    t.test('stringifies a nested object with dots notation', function (st) {
-        st.equal(qs.stringify({ a: { b: 'c' } }, { allowDots: true }), 'a.b=c');
-        st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }, { allowDots: true }), 'a.b.c.d=e');
-        st.end();
-    });
-
-    t.test('stringifies an array value', function (st) {
-        st.equal(
-            qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'indices' }),
-            'a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d',
-            'indices => indices'
-        );
-        st.equal(
-            qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'brackets' }),
-            'a%5B%5D=b&a%5B%5D=c&a%5B%5D=d',
-            'brackets => brackets'
-        );
-        st.equal(
-            qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'comma' }),
-            'a=b%2Cc%2Cd',
-            'comma => comma'
-        );
-        st.equal(
-            qs.stringify({ a: ['b', 'c', 'd'] }),
-            'a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d',
-            'default => indices'
-        );
-        st.end();
-    });
-
-    t.test('omits nulls when asked', function (st) {
-        st.equal(qs.stringify({ a: 'b', c: null }, { skipNulls: true }), 'a=b');
-        st.end();
-    });
-
-    t.test('omits nested nulls when asked', function (st) {
-        st.equal(qs.stringify({ a: { b: 'c', d: null } }, { skipNulls: true }), 'a%5Bb%5D=c');
-        st.end();
-    });
-
-    t.test('omits array indices when asked', function (st) {
-        st.equal(qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }), 'a=b&a=c&a=d');
-        st.end();
-    });
-
-    t.test('stringifies a nested array value', function (st) {
-        st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { arrayFormat: 'indices' }), 'a%5Bb%5D%5B0%5D=c&a%5Bb%5D%5B1%5D=d');
-        st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { arrayFormat: 'brackets' }), 'a%5Bb%5D%5B%5D=c&a%5Bb%5D%5B%5D=d');
-        st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { arrayFormat: 'comma' }), 'a%5Bb%5D=c%2Cd'); // a[b]=c,d
-        st.equal(qs.stringify({ a: { b: ['c', 'd'] } }), 'a%5Bb%5D%5B0%5D=c&a%5Bb%5D%5B1%5D=d');
-        st.end();
-    });
-
-    t.test('stringifies a nested array value with dots notation', function (st) {
-        st.equal(
-            qs.stringify(
-                { a: { b: ['c', 'd'] } },
-                { allowDots: true, encode: false, arrayFormat: 'indices' }
-            ),
-            'a.b[0]=c&a.b[1]=d',
-            'indices: stringifies with dots + indices'
-        );
-        st.equal(
-            qs.stringify(
-                { a: { b: ['c', 'd'] } },
-                { allowDots: true, encode: false, arrayFormat: 'brackets' }
-            ),
-            'a.b[]=c&a.b[]=d',
-            'brackets: stringifies with dots + brackets'
-        );
-        st.equal(
-            qs.stringify(
-                { a: { b: ['c', 'd'] } },
-                { allowDots: true, encode: false, arrayFormat: 'comma' }
-            ),
-            'a.b=c,d',
-            'comma: stringifies with dots + comma'
-        );
-        st.equal(
-            qs.stringify(
-                { a: { b: ['c', 'd'] } },
-                { allowDots: true, encode: false }
-            ),
-            'a.b[0]=c&a.b[1]=d',
-            'default: stringifies with dots + indices'
-        );
-        st.end();
-    });
-
-    t.test('stringifies an object inside an array', function (st) {
-        st.equal(
-            qs.stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'indices' }),
-            'a%5B0%5D%5Bb%5D=c', // a[0][b]=c
-            'indices => brackets'
-        );
-        st.equal(
-            qs.stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'brackets' }),
-            'a%5B%5D%5Bb%5D=c', // a[][b]=c
-            'brackets => brackets'
-        );
-        st.equal(
-            qs.stringify({ a: [{ b: 'c' }] }),
-            'a%5B0%5D%5Bb%5D=c',
-            'default => indices'
-        );
-
-        st.equal(
-            qs.stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'indices' }),
-            'a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1',
-            'indices => indices'
-        );
-
-        st.equal(
-            qs.stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'brackets' }),
-            'a%5B%5D%5Bb%5D%5Bc%5D%5B%5D=1',
-            'brackets => brackets'
-        );
-
-        st.equal(
-            qs.stringify({ a: [{ b: { c: [1] } }] }),
-            'a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1',
-            'default => indices'
-        );
-
-        st.end();
-    });
-
-    t.test('stringifies an array with mixed objects and primitives', function (st) {
-        st.equal(
-            qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encode: false, arrayFormat: 'indices' }),
-            'a[0][b]=1&a[1]=2&a[2]=3',
-            'indices => indices'
-        );
-        st.equal(
-            qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encode: false, arrayFormat: 'brackets' }),
-            'a[][b]=1&a[]=2&a[]=3',
-            'brackets => brackets'
-        );
-        st.equal(
-            qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encode: false }),
-            'a[0][b]=1&a[1]=2&a[2]=3',
-            'default => indices'
-        );
-
-        st.end();
-    });
-
-    t.test('stringifies an object inside an array with dots notation', function (st) {
-        st.equal(
-            qs.stringify(
-                { a: [{ b: 'c' }] },
-                { allowDots: true, encode: false, arrayFormat: 'indices' }
-            ),
-            'a[0].b=c',
-            'indices => indices'
-        );
-        st.equal(
-            qs.stringify(
-                { a: [{ b: 'c' }] },
-                { allowDots: true, encode: false, arrayFormat: 'brackets' }
-            ),
-            'a[].b=c',
-            'brackets => brackets'
-        );
-        st.equal(
-            qs.stringify(
-                { a: [{ b: 'c' }] },
-                { allowDots: true, encode: false }
-            ),
-            'a[0].b=c',
-            'default => indices'
-        );
-
-        st.equal(
-            qs.stringify(
-                { a: [{ b: { c: [1] } }] },
-                { allowDots: true, encode: false, arrayFormat: 'indices' }
-            ),
-            'a[0].b.c[0]=1',
-            'indices => indices'
-        );
-        st.equal(
-            qs.stringify(
-                { a: [{ b: { c: [1] } }] },
-                { allowDots: true, encode: false, arrayFormat: 'brackets' }
-            ),
-            'a[].b.c[]=1',
-            'brackets => brackets'
-        );
-        st.equal(
-            qs.stringify(
-                { a: [{ b: { c: [1] } }] },
-                { allowDots: true, encode: false }
-            ),
-            'a[0].b.c[0]=1',
-            'default => indices'
-        );
-
-        st.end();
-    });
-
-    t.test('does not omit object keys when indices = false', function (st) {
-        st.equal(qs.stringify({ a: [{ b: 'c' }] }, { indices: false }), 'a%5Bb%5D=c');
-        st.end();
-    });
-
-    t.test('uses indices notation for arrays when indices=true', function (st) {
-        st.equal(qs.stringify({ a: ['b', 'c'] }, { indices: true }), 'a%5B0%5D=b&a%5B1%5D=c');
-        st.end();
-    });
-
-    t.test('uses indices notation for arrays when no arrayFormat is specified', function (st) {
-        st.equal(qs.stringify({ a: ['b', 'c'] }), 'a%5B0%5D=b&a%5B1%5D=c');
-        st.end();
-    });
-
-    t.test('uses indices notation for arrays when no arrayFormat=indices', function (st) {
-        st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }), 'a%5B0%5D=b&a%5B1%5D=c');
-        st.end();
-    });
-
-    t.test('uses repeat notation for arrays when no arrayFormat=repeat', function (st) {
-        st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }), 'a=b&a=c');
-        st.end();
-    });
-
-    t.test('uses brackets notation for arrays when no arrayFormat=brackets', function (st) {
-        st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }), 'a%5B%5D=b&a%5B%5D=c');
-        st.end();
-    });
-
-    t.test('stringifies a complicated object', function (st) {
-        st.equal(qs.stringify({ a: { b: 'c', d: 'e' } }), 'a%5Bb%5D=c&a%5Bd%5D=e');
-        st.end();
-    });
-
-    t.test('stringifies an empty value', function (st) {
-        st.equal(qs.stringify({ a: '' }), 'a=');
-        st.equal(qs.stringify({ a: null }, { strictNullHandling: true }), 'a');
-
-        st.equal(qs.stringify({ a: '', b: '' }), 'a=&b=');
-        st.equal(qs.stringify({ a: null, b: '' }, { strictNullHandling: true }), 'a&b=');
-
-        st.equal(qs.stringify({ a: { b: '' } }), 'a%5Bb%5D=');
-        st.equal(qs.stringify({ a: { b: null } }, { strictNullHandling: true }), 'a%5Bb%5D');
-        st.equal(qs.stringify({ a: { b: null } }, { strictNullHandling: false }), 'a%5Bb%5D=');
-
-        st.end();
-    });
-
-    t.test('stringifies a null object', { skip: !Object.create }, function (st) {
-        var obj = Object.create(null);
-        obj.a = 'b';
-        st.equal(qs.stringify(obj), 'a=b');
-        st.end();
-    });
-
-    t.test('returns an empty string for invalid input', function (st) {
-        st.equal(qs.stringify(undefined), '');
-        st.equal(qs.stringify(false), '');
-        st.equal(qs.stringify(null), '');
-        st.equal(qs.stringify(''), '');
-        st.end();
-    });
-
-    t.test('stringifies an object with a null object as a child', { skip: !Object.create }, function (st) {
-        var obj = { a: Object.create(null) };
-
-        obj.a.b = 'c';
-        st.equal(qs.stringify(obj), 'a%5Bb%5D=c');
-        st.end();
-    });
-
-    t.test('drops keys with a value of undefined', function (st) {
-        st.equal(qs.stringify({ a: undefined }), '');
-
-        st.equal(qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: true }), 'a%5Bc%5D');
-        st.equal(qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: false }), 'a%5Bc%5D=');
-        st.equal(qs.stringify({ a: { b: undefined, c: '' } }), 'a%5Bc%5D=');
-        st.end();
-    });
-
-    t.test('url encodes values', function (st) {
-        st.equal(qs.stringify({ a: 'b c' }), 'a=b%20c');
-        st.end();
-    });
-
-    t.test('stringifies a date', function (st) {
-        var now = new Date();
-        var str = 'a=' + encodeURIComponent(now.toISOString());
-        st.equal(qs.stringify({ a: now }), str);
-        st.end();
-    });
-
-    t.test('stringifies the weird object from qs', function (st) {
-        st.equal(qs.stringify({ 'my weird field': '~q1!2"\'w$5&7/z8)?' }), 'my%20weird%20field=~q1%212%22%27w%245%267%2Fz8%29%3F');
-        st.end();
-    });
-
-    t.test('skips properties that are part of the object prototype', function (st) {
-        Object.prototype.crash = 'test';
-        st.equal(qs.stringify({ a: 'b' }), 'a=b');
-        st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c');
-        delete Object.prototype.crash;
-        st.end();
-    });
-
-    t.test('stringifies boolean values', function (st) {
-        st.equal(qs.stringify({ a: true }), 'a=true');
-        st.equal(qs.stringify({ a: { b: true } }), 'a%5Bb%5D=true');
-        st.equal(qs.stringify({ b: false }), 'b=false');
-        st.equal(qs.stringify({ b: { c: false } }), 'b%5Bc%5D=false');
-        st.end();
-    });
-
-    t.test('stringifies buffer values', function (st) {
-        st.equal(qs.stringify({ a: SaferBuffer.from('test') }), 'a=test');
-        st.equal(qs.stringify({ a: { b: SaferBuffer.from('test') } }), 'a%5Bb%5D=test');
-        st.end();
-    });
-
-    t.test('stringifies an object using an alternative delimiter', function (st) {
-        st.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d');
-        st.end();
-    });
-
-    t.test('doesn\'t blow up when Buffer global is missing', function (st) {
-        var tempBuffer = global.Buffer;
-        delete global.Buffer;
-        var result = qs.stringify({ a: 'b', c: 'd' });
-        global.Buffer = tempBuffer;
-        st.equal(result, 'a=b&c=d');
-        st.end();
-    });
-
-    t.test('selects properties when filter=array', function (st) {
-        st.equal(qs.stringify({ a: 'b' }, { filter: ['a'] }), 'a=b');
-        st.equal(qs.stringify({ a: 1 }, { filter: [] }), '');
-
-        st.equal(
-            qs.stringify(
-                { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' },
-                { filter: ['a', 'b', 0, 2], arrayFormat: 'indices' }
-            ),
-            'a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3',
-            'indices => indices'
-        );
-        st.equal(
-            qs.stringify(
-                { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' },
-                { filter: ['a', 'b', 0, 2], arrayFormat: 'brackets' }
-            ),
-            'a%5Bb%5D%5B%5D=1&a%5Bb%5D%5B%5D=3',
-            'brackets => brackets'
-        );
-        st.equal(
-            qs.stringify(
-                { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' },
-                { filter: ['a', 'b', 0, 2] }
-            ),
-            'a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3',
-            'default => indices'
-        );
-
-        st.end();
-    });
-
-    t.test('supports custom representations when filter=function', function (st) {
-        var calls = 0;
-        var obj = { a: 'b', c: 'd', e: { f: new Date(1257894000000) } };
-        var filterFunc = function (prefix, value) {
-            calls += 1;
-            if (calls === 1) {
-                st.equal(prefix, '', 'prefix is empty');
-                st.equal(value, obj);
-            } else if (prefix === 'c') {
-                return void 0;
-            } else if (value instanceof Date) {
-                st.equal(prefix, 'e[f]');
-                return value.getTime();
-            }
-            return value;
-        };
-
-        st.equal(qs.stringify(obj, { filter: filterFunc }), 'a=b&e%5Bf%5D=1257894000000');
-        st.equal(calls, 5);
-        st.end();
-    });
-
-    t.test('can disable uri encoding', function (st) {
-        st.equal(qs.stringify({ a: 'b' }, { encode: false }), 'a=b');
-        st.equal(qs.stringify({ a: { b: 'c' } }, { encode: false }), 'a[b]=c');
-        st.equal(qs.stringify({ a: 'b', c: null }, { strictNullHandling: true, encode: false }), 'a=b&c');
-        st.end();
-    });
-
-    t.test('can sort the keys', function (st) {
-        var sort = function (a, b) {
-            return a.localeCompare(b);
-        };
-        st.equal(qs.stringify({ a: 'c', z: 'y', b: 'f' }, { sort: sort }), 'a=c&b=f&z=y');
-        st.equal(qs.stringify({ a: 'c', z: { j: 'a', i: 'b' }, b: 'f' }, { sort: sort }), 'a=c&b=f&z%5Bi%5D=b&z%5Bj%5D=a');
-        st.end();
-    });
-
-    t.test('can sort the keys at depth 3 or more too', function (st) {
-        var sort = function (a, b) {
-            return a.localeCompare(b);
-        };
-        st.equal(
-            qs.stringify(
-                { a: 'a', z: { zj: { zjb: 'zjb', zja: 'zja' }, zi: { zib: 'zib', zia: 'zia' } }, b: 'b' },
-                { sort: sort, encode: false }
-            ),
-            'a=a&b=b&z[zi][zia]=zia&z[zi][zib]=zib&z[zj][zja]=zja&z[zj][zjb]=zjb'
-        );
-        st.equal(
-            qs.stringify(
-                { a: 'a', z: { zj: { zjb: 'zjb', zja: 'zja' }, zi: { zib: 'zib', zia: 'zia' } }, b: 'b' },
-                { sort: null, encode: false }
-            ),
-            'a=a&z[zj][zjb]=zjb&z[zj][zja]=zja&z[zi][zib]=zib&z[zi][zia]=zia&b=b'
-        );
-        st.end();
-    });
-
-    t.test('can stringify with custom encoding', function (st) {
-        st.equal(qs.stringify({ 県: '大阪府', '': '' }, {
-            encoder: function (str) {
-                if (str.length === 0) {
-                    return '';
-                }
-                var buf = iconv.encode(str, 'shiftjis');
-                var result = [];
-                for (var i = 0; i < buf.length; ++i) {
-                    result.push(buf.readUInt8(i).toString(16));
-                }
-                return '%' + result.join('%');
-            }
-        }), '%8c%a7=%91%e5%8d%e3%95%7b&=');
-        st.end();
-    });
-
-    t.test('receives the default encoder as a second argument', function (st) {
-        st.plan(2);
-        qs.stringify({ a: 1 }, {
-            encoder: function (str, defaultEncoder) {
-                st.equal(defaultEncoder, utils.encode);
-            }
-        });
-        st.end();
-    });
-
-    t.test('throws error with wrong encoder', function (st) {
-        st['throws'](function () {
-            qs.stringify({}, { encoder: 'string' });
-        }, new TypeError('Encoder has to be a function.'));
-        st.end();
-    });
-
-    t.test('can use custom encoder for a buffer object', { skip: typeof Buffer === 'undefined' }, function (st) {
-        st.equal(qs.stringify({ a: SaferBuffer.from([1]) }, {
-            encoder: function (buffer) {
-                if (typeof buffer === 'string') {
-                    return buffer;
-                }
-                return String.fromCharCode(buffer.readUInt8(0) + 97);
-            }
-        }), 'a=b');
-        st.end();
-    });
-
-    t.test('serializeDate option', function (st) {
-        var date = new Date();
-        st.equal(
-            qs.stringify({ a: date }),
-            'a=' + date.toISOString().replace(/:/g, '%3A'),
-            'default is toISOString'
-        );
-
-        var mutatedDate = new Date();
-        mutatedDate.toISOString = function () {
-            throw new SyntaxError();
-        };
-        st['throws'](function () {
-            mutatedDate.toISOString();
-        }, SyntaxError);
-        st.equal(
-            qs.stringify({ a: mutatedDate }),
-            'a=' + Date.prototype.toISOString.call(mutatedDate).replace(/:/g, '%3A'),
-            'toISOString works even when method is not locally present'
-        );
-
-        var specificDate = new Date(6);
-        st.equal(
-            qs.stringify(
-                { a: specificDate },
-                { serializeDate: function (d) { return d.getTime() * 7; } }
-            ),
-            'a=42',
-            'custom serializeDate function called'
-        );
-
-        st.end();
-    });
-
-    t.test('RFC 1738 spaces serialization', function (st) {
-        st.equal(qs.stringify({ a: 'b c' }, { format: qs.formats.RFC1738 }), 'a=b+c');
-        st.equal(qs.stringify({ 'a b': 'c d' }, { format: qs.formats.RFC1738 }), 'a+b=c+d');
-        st.end();
-    });
-
-    t.test('RFC 3986 spaces serialization', function (st) {
-        st.equal(qs.stringify({ a: 'b c' }, { format: qs.formats.RFC3986 }), 'a=b%20c');
-        st.equal(qs.stringify({ 'a b': 'c d' }, { format: qs.formats.RFC3986 }), 'a%20b=c%20d');
-        st.end();
-    });
-
-    t.test('Backward compatibility to RFC 3986', function (st) {
-        st.equal(qs.stringify({ a: 'b c' }), 'a=b%20c');
-        st.end();
-    });
-
-    t.test('Edge cases and unknown formats', function (st) {
-        ['UFO1234', false, 1234, null, {}, []].forEach(
-            function (format) {
-                st['throws'](
-                    function () {
-                        qs.stringify({ a: 'b c' }, { format: format });
-                    },
-                    new TypeError('Unknown format option provided.')
-                );
-            }
-        );
-        st.end();
-    });
-
-    t.test('encodeValuesOnly', function (st) {
-        st.equal(
-            qs.stringify(
-                { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] },
-                { encodeValuesOnly: true }
-            ),
-            'a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h'
-        );
-        st.equal(
-            qs.stringify(
-                { a: 'b', c: ['d', 'e'], f: [['g'], ['h']] }
-            ),
-            'a=b&c%5B0%5D=d&c%5B1%5D=e&f%5B0%5D%5B0%5D=g&f%5B1%5D%5B0%5D=h'
-        );
-        st.end();
-    });
-
-    t.test('encodeValuesOnly - strictNullHandling', function (st) {
-        st.equal(
-            qs.stringify(
-                { a: { b: null } },
-                { encodeValuesOnly: true, strictNullHandling: true }
-            ),
-            'a[b]'
-        );
-        st.end();
-    });
-
-    t.test('throws if an invalid charset is specified', function (st) {
-        st['throws'](function () {
-            qs.stringify({ a: 'b' }, { charset: 'foobar' });
-        }, new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'));
-        st.end();
-    });
-
-    t.test('respects a charset of iso-8859-1', function (st) {
-        st.equal(qs.stringify({ æ: 'æ' }, { charset: 'iso-8859-1' }), '%E6=%E6');
-        st.end();
-    });
-
-    t.test('encodes unrepresentable chars as numeric entities in iso-8859-1 mode', function (st) {
-        st.equal(qs.stringify({ a: '☺' }, { charset: 'iso-8859-1' }), 'a=%26%239786%3B');
-        st.end();
-    });
-
-    t.test('respects an explicit charset of utf-8 (the default)', function (st) {
-        st.equal(qs.stringify({ a: 'æ' }, { charset: 'utf-8' }), 'a=%C3%A6');
-        st.end();
-    });
-
-    t.test('adds the right sentinel when instructed to and the charset is utf-8', function (st) {
-        st.equal(qs.stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'utf-8' }), 'utf8=%E2%9C%93&a=%C3%A6');
-        st.end();
-    });
-
-    t.test('adds the right sentinel when instructed to and the charset is iso-8859-1', function (st) {
-        st.equal(qs.stringify({ a: 'æ' }, { charsetSentinel: true, charset: 'iso-8859-1' }), 'utf8=%26%2310003%3B&a=%E6');
-        st.end();
-    });
-
-    t.test('does not mutate the options argument', function (st) {
-        var options = {};
-        qs.stringify({}, options);
-        st.deepEqual(options, {});
-        st.end();
-    });
-
-    t.test('strictNullHandling works with custom filter', function (st) {
-        var filter = function (prefix, value) {
-            return value;
-        };
-
-        var options = { strictNullHandling: true, filter: filter };
-        st.equal(qs.stringify({ key: null }, options), 'key');
-        st.end();
-    });
-
-    t.test('strictNullHandling works with null serializeDate', function (st) {
-        var serializeDate = function () {
-            return null;
-        };
-        var options = { strictNullHandling: true, serializeDate: serializeDate };
-        var date = new Date();
-        st.equal(qs.stringify({ key: date }, options), 'key');
-        st.end();
-    });
-
-    t.end();
-});
+"use strict";var test=require("tape"),qs=require("../"),utils=require("../lib/utils"),iconv=require("iconv-lite"),SaferBuffer=require("safer-buffer").Buffer;test("stringify()",(function(e){e.test("stringifies a querystring object",(function(e){e.equal(qs.stringify({a:"b"}),"a=b"),e.equal(qs.stringify({a:1}),"a=1"),e.equal(qs.stringify({a:1,b:2}),"a=1&b=2"),e.equal(qs.stringify({a:"A_Z"}),"a=A_Z"),e.equal(qs.stringify({a:"€"}),"a=%E2%82%AC"),e.equal(qs.stringify({a:""}),"a=%EE%80%80"),e.equal(qs.stringify({a:"א"}),"a=%D7%90"),e.equal(qs.stringify({a:"𐐷"}),"a=%F0%90%90%B7"),e.end()})),e.test("stringifies falsy values",(function(e){e.equal(qs.stringify(void 0),""),e.equal(qs.stringify(null),""),e.equal(qs.stringify(null,{strictNullHandling:!0}),""),e.equal(qs.stringify(!1),""),e.equal(qs.stringify(0),""),e.end()})),e.test("adds query prefix",(function(e){e.equal(qs.stringify({a:"b"},{addQueryPrefix:!0}),"?a=b"),e.end()})),e.test("with query prefix, outputs blank string given an empty object",(function(e){e.equal(qs.stringify({},{addQueryPrefix:!0}),""),e.end()})),e.test("stringifies nested falsy values",(function(e){e.equal(qs.stringify({a:{b:{c:null}}}),"a%5Bb%5D%5Bc%5D="),e.equal(qs.stringify({a:{b:{c:null}}},{strictNullHandling:!0}),"a%5Bb%5D%5Bc%5D"),e.equal(qs.stringify({a:{b:{c:!1}}}),"a%5Bb%5D%5Bc%5D=false"),e.end()})),e.test("stringifies a nested object",(function(e){e.equal(qs.stringify({a:{b:"c"}}),"a%5Bb%5D=c"),e.equal(qs.stringify({a:{b:{c:{d:"e"}}}}),"a%5Bb%5D%5Bc%5D%5Bd%5D=e"),e.end()})),e.test("stringifies a nested object with dots notation",(function(e){e.equal(qs.stringify({a:{b:"c"}},{allowDots:!0}),"a.b=c"),e.equal(qs.stringify({a:{b:{c:{d:"e"}}}},{allowDots:!0}),"a.b.c.d=e"),e.end()})),e.test("stringifies an array value",(function(e){e.equal(qs.stringify({a:["b","c","d"]},{arrayFormat:"indices"}),"a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d","indices => indices"),e.equal(qs.stringify({a:["b","c","d"]},{arrayFormat:"brackets"}),"a%5B%5D=b&a%5B%5D=c&a%5B%5D=d","brackets => brackets"),e.equal(qs.stringify({a:["b","c","d"]},{arrayFormat:"comma"}),"a=b%2Cc%2Cd","comma => comma"),e.equal(qs.stringify({a:["b","c","d"]}),"a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d","default => indices"),e.end()})),e.test("omits nulls when asked",(function(e){e.equal(qs.stringify({a:"b",c:null},{skipNulls:!0}),"a=b"),e.end()})),e.test("omits nested nulls when asked",(function(e){e.equal(qs.stringify({a:{b:"c",d:null}},{skipNulls:!0}),"a%5Bb%5D=c"),e.end()})),e.test("omits array indices when asked",(function(e){e.equal(qs.stringify({a:["b","c","d"]},{indices:!1}),"a=b&a=c&a=d"),e.end()})),e.test("stringifies a nested array value",(function(e){e.equal(qs.stringify({a:{b:["c","d"]}},{arrayFormat:"indices"}),"a%5Bb%5D%5B0%5D=c&a%5Bb%5D%5B1%5D=d"),e.equal(qs.stringify({a:{b:["c","d"]}},{arrayFormat:"brackets"}),"a%5Bb%5D%5B%5D=c&a%5Bb%5D%5B%5D=d"),e.equal(qs.stringify({a:{b:["c","d"]}},{arrayFormat:"comma"}),"a%5Bb%5D=c%2Cd"),e.equal(qs.stringify({a:{b:["c","d"]}}),"a%5Bb%5D%5B0%5D=c&a%5Bb%5D%5B1%5D=d"),e.end()})),e.test("stringifies a nested array value with dots notation",(function(e){e.equal(qs.stringify({a:{b:["c","d"]}},{allowDots:!0,encode:!1,arrayFormat:"indices"}),"a.b[0]=c&a.b[1]=d","indices: stringifies with dots + indices"),e.equal(qs.stringify({a:{b:["c","d"]}},{allowDots:!0,encode:!1,arrayFormat:"brackets"}),"a.b[]=c&a.b[]=d","brackets: stringifies with dots + brackets"),e.equal(qs.stringify({a:{b:["c","d"]}},{allowDots:!0,encode:!1,arrayFormat:"comma"}),"a.b=c,d","comma: stringifies with dots + comma"),e.equal(qs.stringify({a:{b:["c","d"]}},{allowDots:!0,encode:!1}),"a.b[0]=c&a.b[1]=d","default: stringifies with dots + indices"),e.end()})),e.test("stringifies an object inside an array",(function(e){e.equal(qs.stringify({a:[{b:"c"}]},{arrayFormat:"indices"}),"a%5B0%5D%5Bb%5D=c","indices => brackets"),e.equal(qs.stringify({a:[{b:"c"}]},{arrayFormat:"brackets"}),"a%5B%5D%5Bb%5D=c","brackets => brackets"),e.equal(qs.stringify({a:[{b:"c"}]}),"a%5B0%5D%5Bb%5D=c","default => indices"),e.equal(qs.stringify({a:[{b:{c:[1]}}]},{arrayFormat:"indices"}),"a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1","indices => indices"),e.equal(qs.stringify({a:[{b:{c:[1]}}]},{arrayFormat:"brackets"}),"a%5B%5D%5Bb%5D%5Bc%5D%5B%5D=1","brackets => brackets"),e.equal(qs.stringify({a:[{b:{c:[1]}}]}),"a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1","default => indices"),e.end()})),e.test("stringifies an array with mixed objects and primitives",(function(e){e.equal(qs.stringify({a:[{b:1},2,3]},{encode:!1,arrayFormat:"indices"}),"a[0][b]=1&a[1]=2&a[2]=3","indices => indices"),e.equal(qs.stringify({a:[{b:1},2,3]},{encode:!1,arrayFormat:"brackets"}),"a[][b]=1&a[]=2&a[]=3","brackets => brackets"),e.equal(qs.stringify({a:[{b:1},2,3]},{encode:!1}),"a[0][b]=1&a[1]=2&a[2]=3","default => indices"),e.end()})),e.test("stringifies an object inside an array with dots notation",(function(e){e.equal(qs.stringify({a:[{b:"c"}]},{allowDots:!0,encode:!1,arrayFormat:"indices"}),"a[0].b=c","indices => indices"),e.equal(qs.stringify({a:[{b:"c"}]},{allowDots:!0,encode:!1,arrayFormat:"brackets"}),"a[].b=c","brackets => brackets"),e.equal(qs.stringify({a:[{b:"c"}]},{allowDots:!0,encode:!1}),"a[0].b=c","default => indices"),e.equal(qs.stringify({a:[{b:{c:[1]}}]},{allowDots:!0,encode:!1,arrayFormat:"indices"}),"a[0].b.c[0]=1","indices => indices"),e.equal(qs.stringify({a:[{b:{c:[1]}}]},{allowDots:!0,encode:!1,arrayFormat:"brackets"}),"a[].b.c[]=1","brackets => brackets"),e.equal(qs.stringify({a:[{b:{c:[1]}}]},{allowDots:!0,encode:!1}),"a[0].b.c[0]=1","default => indices"),e.end()})),e.test("does not omit object keys when indices = false",(function(e){e.equal(qs.stringify({a:[{b:"c"}]},{indices:!1}),"a%5Bb%5D=c"),e.end()})),e.test("uses indices notation for arrays when indices=true",(function(e){e.equal(qs.stringify({a:["b","c"]},{indices:!0}),"a%5B0%5D=b&a%5B1%5D=c"),e.end()})),e.test("uses indices notation for arrays when no arrayFormat is specified",(function(e){e.equal(qs.stringify({a:["b","c"]}),"a%5B0%5D=b&a%5B1%5D=c"),e.end()})),e.test("uses indices notation for arrays when no arrayFormat=indices",(function(e){e.equal(qs.stringify({a:["b","c"]},{arrayFormat:"indices"}),"a%5B0%5D=b&a%5B1%5D=c"),e.end()})),e.test("uses repeat notation for arrays when no arrayFormat=repeat",(function(e){e.equal(qs.stringify({a:["b","c"]},{arrayFormat:"repeat"}),"a=b&a=c"),e.end()})),e.test("uses brackets notation for arrays when no arrayFormat=brackets",(function(e){e.equal(qs.stringify({a:["b","c"]},{arrayFormat:"brackets"}),"a%5B%5D=b&a%5B%5D=c"),e.end()})),e.test("stringifies a complicated object",(function(e){e.equal(qs.stringify({a:{b:"c",d:"e"}}),"a%5Bb%5D=c&a%5Bd%5D=e"),e.end()})),e.test("stringifies an empty value",(function(e){e.equal(qs.stringify({a:""}),"a="),e.equal(qs.stringify({a:null},{strictNullHandling:!0}),"a"),e.equal(qs.stringify({a:"",b:""}),"a=&b="),e.equal(qs.stringify({a:null,b:""},{strictNullHandling:!0}),"a&b="),e.equal(qs.stringify({a:{b:""}}),"a%5Bb%5D="),e.equal(qs.stringify({a:{b:null}},{strictNullHandling:!0}),"a%5Bb%5D"),e.equal(qs.stringify({a:{b:null}},{strictNullHandling:!1}),"a%5Bb%5D="),e.end()})),e.test("stringifies a null object",{skip:!Object.create},(function(e){var a=Object.create(null);a.a="b",e.equal(qs.stringify(a),"a=b"),e.end()})),e.test("returns an empty string for invalid input",(function(e){e.equal(qs.stringify(void 0),""),e.equal(qs.stringify(!1),""),e.equal(qs.stringify(null),""),e.equal(qs.stringify(""),""),e.end()})),e.test("stringifies an object with a null object as a child",{skip:!Object.create},(function(e){var a={a:Object.create(null)};a.a.b="c",e.equal(qs.stringify(a),"a%5Bb%5D=c"),e.end()})),e.test("drops keys with a value of undefined",(function(e){e.equal(qs.stringify({a:void 0}),""),e.equal(qs.stringify({a:{b:void 0,c:null}},{strictNullHandling:!0}),"a%5Bc%5D"),e.equal(qs.stringify({a:{b:void 0,c:null}},{strictNullHandling:!1}),"a%5Bc%5D="),e.equal(qs.stringify({a:{b:void 0,c:""}}),"a%5Bc%5D="),e.end()})),e.test("url encodes values",(function(e){e.equal(qs.stringify({a:"b c"}),"a=b%20c"),e.end()})),e.test("stringifies a date",(function(e){var a=new Date,t="a="+encodeURIComponent(a.toISOString());e.equal(qs.stringify({a:a}),t),e.end()})),e.test("stringifies the weird object from qs",(function(e){e.equal(qs.stringify({"my weird field":"~q1!2\"'w$5&7/z8)?"}),"my%20weird%20field=~q1%212%22%27w%245%267%2Fz8%29%3F"),e.end()})),e.test("skips properties that are part of the object prototype",(function(e){Object.prototype.crash="test",e.equal(qs.stringify({a:"b"}),"a=b"),e.equal(qs.stringify({a:{b:"c"}}),"a%5Bb%5D=c"),delete Object.prototype.crash,e.end()})),e.test("stringifies boolean values",(function(e){e.equal(qs.stringify({a:!0}),"a=true"),e.equal(qs.stringify({a:{b:!0}}),"a%5Bb%5D=true"),e.equal(qs.stringify({b:!1}),"b=false"),e.equal(qs.stringify({b:{c:!1}}),"b%5Bc%5D=false"),e.end()})),e.test("stringifies buffer values",(function(e){e.equal(qs.stringify({a:SaferBuffer.from("test")}),"a=test"),e.equal(qs.stringify({a:{b:SaferBuffer.from("test")}}),"a%5Bb%5D=test"),e.end()})),e.test("stringifies an object using an alternative delimiter",(function(e){e.equal(qs.stringify({a:"b",c:"d"},{delimiter:";"}),"a=b;c=d"),e.end()})),e.test("doesn't blow up when Buffer global is missing",(function(e){var a=global.Buffer;delete global.Buffer;var t=qs.stringify({a:"b",c:"d"});global.Buffer=a,e.equal(t,"a=b&c=d"),e.end()})),e.test("selects properties when filter=array",(function(e){e.equal(qs.stringify({a:"b"},{filter:["a"]}),"a=b"),e.equal(qs.stringify({a:1},{filter:[]}),""),e.equal(qs.stringify({a:{b:[1,2,3,4],c:"d"},c:"f"},{filter:["a","b",0,2],arrayFormat:"indices"}),"a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3","indices => indices"),e.equal(qs.stringify({a:{b:[1,2,3,4],c:"d"},c:"f"},{filter:["a","b",0,2],arrayFormat:"brackets"}),"a%5Bb%5D%5B%5D=1&a%5Bb%5D%5B%5D=3","brackets => brackets"),e.equal(qs.stringify({a:{b:[1,2,3,4],c:"d"},c:"f"},{filter:["a","b",0,2]}),"a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3","default => indices"),e.end()})),e.test("supports custom representations when filter=function",(function(e){var a=0,t={a:"b",c:"d",e:{f:new Date(1257894e6)}};e.equal(qs.stringify(t,{filter:function(i,n){if(1===(a+=1))e.equal(i,"","prefix is empty"),e.equal(n,t);else{if("c"===i)return;if(n instanceof Date)return e.equal(i,"e[f]"),n.getTime()}return n}}),"a=b&e%5Bf%5D=1257894000000"),e.equal(a,5),e.end()})),e.test("can disable uri encoding",(function(e){e.equal(qs.stringify({a:"b"},{encode:!1}),"a=b"),e.equal(qs.stringify({a:{b:"c"}},{encode:!1}),"a[b]=c"),e.equal(qs.stringify({a:"b",c:null},{strictNullHandling:!0,encode:!1}),"a=b&c"),e.end()})),e.test("can sort the keys",(function(e){var a=function(e,a){return e.localeCompare(a)};e.equal(qs.stringify({a:"c",z:"y",b:"f"},{sort:a}),"a=c&b=f&z=y"),e.equal(qs.stringify({a:"c",z:{j:"a",i:"b"},b:"f"},{sort:a}),"a=c&b=f&z%5Bi%5D=b&z%5Bj%5D=a"),e.end()})),e.test("can sort the keys at depth 3 or more too",(function(e){e.equal(qs.stringify({a:"a",z:{zj:{zjb:"zjb",zja:"zja"},zi:{zib:"zib",zia:"zia"}},b:"b"},{sort:function(e,a){return e.localeCompare(a)},encode:!1}),"a=a&b=b&z[zi][zia]=zia&z[zi][zib]=zib&z[zj][zja]=zja&z[zj][zjb]=zjb"),e.equal(qs.stringify({a:"a",z:{zj:{zjb:"zjb",zja:"zja"},zi:{zib:"zib",zia:"zia"}},b:"b"},{sort:null,encode:!1}),"a=a&z[zj][zjb]=zjb&z[zj][zja]=zja&z[zi][zib]=zib&z[zi][zia]=zia&b=b"),e.end()})),e.test("can stringify with custom encoding",(function(e){e.equal(qs.stringify({"県":"大阪府","":""},{encoder:function(e){if(0===e.length)return"";for(var a=iconv.encode(e,"shiftjis"),t=[],i=0;i<a.length;++i)t.push(a.readUInt8(i).toString(16));return"%"+t.join("%")}}),"%8c%a7=%91%e5%8d%e3%95%7b&="),e.end()})),e.test("receives the default encoder as a second argument",(function(e){e.plan(2),qs.stringify({a:1},{encoder:function(a,t){e.equal(t,utils.encode)}}),e.end()})),e.test("throws error with wrong encoder",(function(e){e.throws((function(){qs.stringify({},{encoder:"string"})}),new TypeError("Encoder has to be a function.")),e.end()})),e.test("can use custom encoder for a buffer object",{skip:"undefined"==typeof Buffer},(function(e){e.equal(qs.stringify({a:SaferBuffer.from([1])},{encoder:function(e){return"string"==typeof e?e:String.fromCharCode(e.readUInt8(0)+97)}}),"a=b"),e.end()})),e.test("serializeDate option",(function(e){var a=new Date;e.equal(qs.stringify({a:a}),"a="+a.toISOString().replace(/:/g,"%3A"),"default is toISOString");var t=new Date;t.toISOString=function(){throw new SyntaxError},e.throws((function(){t.toISOString()}),SyntaxError),e.equal(qs.stringify({a:t}),"a="+Date.prototype.toISOString.call(t).replace(/:/g,"%3A"),"toISOString works even when method is not locally present");var i=new Date(6);e.equal(qs.stringify({a:i},{serializeDate:function(e){return 7*e.getTime()}}),"a=42","custom serializeDate function called"),e.end()})),e.test("RFC 1738 spaces serialization",(function(e){e.equal(qs.stringify({a:"b c"},{format:qs.formats.RFC1738}),"a=b+c"),e.equal(qs.stringify({"a b":"c d"},{format:qs.formats.RFC1738}),"a+b=c+d"),e.end()})),e.test("RFC 3986 spaces serialization",(function(e){e.equal(qs.stringify({a:"b c"},{format:qs.formats.RFC3986}),"a=b%20c"),e.equal(qs.stringify({"a b":"c d"},{format:qs.formats.RFC3986}),"a%20b=c%20d"),e.end()})),e.test("Backward compatibility to RFC 3986",(function(e){e.equal(qs.stringify({a:"b c"}),"a=b%20c"),e.end()})),e.test("Edge cases and unknown formats",(function(e){["UFO1234",!1,1234,null,{},[]].forEach((function(a){e.throws((function(){qs.stringify({a:"b c"},{format:a})}),new TypeError("Unknown format option provided."))})),e.end()})),e.test("encodeValuesOnly",(function(e){e.equal(qs.stringify({a:"b",c:["d","e=f"],f:[["g"],["h"]]},{encodeValuesOnly:!0}),"a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h"),e.equal(qs.stringify({a:"b",c:["d","e"],f:[["g"],["h"]]}),"a=b&c%5B0%5D=d&c%5B1%5D=e&f%5B0%5D%5B0%5D=g&f%5B1%5D%5B0%5D=h"),e.end()})),e.test("encodeValuesOnly - strictNullHandling",(function(e){e.equal(qs.stringify({a:{b:null}},{encodeValuesOnly:!0,strictNullHandling:!0}),"a[b]"),e.end()})),e.test("throws if an invalid charset is specified",(function(e){e.throws((function(){qs.stringify({a:"b"},{charset:"foobar"})}),new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined")),e.end()})),e.test("respects a charset of iso-8859-1",(function(e){e.equal(qs.stringify({"æ":"æ"},{charset:"iso-8859-1"}),"%E6=%E6"),e.end()})),e.test("encodes unrepresentable chars as numeric entities in iso-8859-1 mode",(function(e){e.equal(qs.stringify({a:"☺"},{charset:"iso-8859-1"}),"a=%26%239786%3B"),e.end()})),e.test("respects an explicit charset of utf-8 (the default)",(function(e){e.equal(qs.stringify({a:"æ"},{charset:"utf-8"}),"a=%C3%A6"),e.end()})),e.test("adds the right sentinel when instructed to and the charset is utf-8",(function(e){e.equal(qs.stringify({a:"æ"},{charsetSentinel:!0,charset:"utf-8"}),"utf8=%E2%9C%93&a=%C3%A6"),e.end()})),e.test("adds the right sentinel when instructed to and the charset is iso-8859-1",(function(e){e.equal(qs.stringify({a:"æ"},{charsetSentinel:!0,charset:"iso-8859-1"}),"utf8=%26%2310003%3B&a=%E6"),e.end()})),e.test("does not mutate the options argument",(function(e){var a={};qs.stringify({},a),e.deepEqual(a,{}),e.end()})),e.test("strictNullHandling works with custom filter",(function(e){var a={strictNullHandling:!0,filter:function(e,a){return a}};e.equal(qs.stringify({key:null},a),"key"),e.end()})),e.test("strictNullHandling works with null serializeDate",(function(e){var a={strictNullHandling:!0,serializeDate:function(){return null}},t=new Date;e.equal(qs.stringify({key:t},a),"key"),e.end()})),e.end()}));
\ No newline at end of file
index da31ce5..2ab50e5 100644 (file)
@@ -1,136 +1 @@
-'use strict';
-
-var test = require('tape');
-var inspect = require('object-inspect');
-var SaferBuffer = require('safer-buffer').Buffer;
-var forEach = require('for-each');
-var utils = require('../lib/utils');
-
-test('merge()', function (t) {
-    t.deepEqual(utils.merge(null, true), [null, true], 'merges true into null');
-
-    t.deepEqual(utils.merge(null, [42]), [null, 42], 'merges null into an array');
-
-    t.deepEqual(utils.merge({ a: 'b' }, { a: 'c' }), { a: ['b', 'c'] }, 'merges two objects with the same key');
-
-    var oneMerged = utils.merge({ foo: 'bar' }, { foo: { first: '123' } });
-    t.deepEqual(oneMerged, { foo: ['bar', { first: '123' }] }, 'merges a standalone and an object into an array');
-
-    var twoMerged = utils.merge({ foo: ['bar', { first: '123' }] }, { foo: { second: '456' } });
-    t.deepEqual(twoMerged, { foo: { 0: 'bar', 1: { first: '123' }, second: '456' } }, 'merges a standalone and two objects into an array');
-
-    var sandwiched = utils.merge({ foo: ['bar', { first: '123', second: '456' }] }, { foo: 'baz' });
-    t.deepEqual(sandwiched, { foo: ['bar', { first: '123', second: '456' }, 'baz'] }, 'merges an object sandwiched by two standalones into an array');
-
-    var nestedArrays = utils.merge({ foo: ['baz'] }, { foo: ['bar', 'xyzzy'] });
-    t.deepEqual(nestedArrays, { foo: ['baz', 'bar', 'xyzzy'] });
-
-    var noOptionsNonObjectSource = utils.merge({ foo: 'baz' }, 'bar');
-    t.deepEqual(noOptionsNonObjectSource, { foo: 'baz', bar: true });
-
-    t.test(
-        'avoids invoking array setters unnecessarily',
-        { skip: typeof Object.defineProperty !== 'function' },
-        function (st) {
-            var setCount = 0;
-            var getCount = 0;
-            var observed = [];
-            Object.defineProperty(observed, 0, {
-                get: function () {
-                    getCount += 1;
-                    return { bar: 'baz' };
-                },
-                set: function () { setCount += 1; }
-            });
-            utils.merge(observed, [null]);
-            st.equal(setCount, 0);
-            st.equal(getCount, 1);
-            observed[0] = observed[0]; // eslint-disable-line no-self-assign
-            st.equal(setCount, 1);
-            st.equal(getCount, 2);
-            st.end();
-        }
-    );
-
-    t.end();
-});
-
-test('assign()', function (t) {
-    var target = { a: 1, b: 2 };
-    var source = { b: 3, c: 4 };
-    var result = utils.assign(target, source);
-
-    t.equal(result, target, 'returns the target');
-    t.deepEqual(target, { a: 1, b: 3, c: 4 }, 'target and source are merged');
-    t.deepEqual(source, { b: 3, c: 4 }, 'source is untouched');
-
-    t.end();
-});
-
-test('combine()', function (t) {
-    t.test('both arrays', function (st) {
-        var a = [1];
-        var b = [2];
-        var combined = utils.combine(a, b);
-
-        st.deepEqual(a, [1], 'a is not mutated');
-        st.deepEqual(b, [2], 'b is not mutated');
-        st.notEqual(a, combined, 'a !== combined');
-        st.notEqual(b, combined, 'b !== combined');
-        st.deepEqual(combined, [1, 2], 'combined is a + b');
-
-        st.end();
-    });
-
-    t.test('one array, one non-array', function (st) {
-        var aN = 1;
-        var a = [aN];
-        var bN = 2;
-        var b = [bN];
-
-        var combinedAnB = utils.combine(aN, b);
-        st.deepEqual(b, [bN], 'b is not mutated');
-        st.notEqual(aN, combinedAnB, 'aN + b !== aN');
-        st.notEqual(a, combinedAnB, 'aN + b !== a');
-        st.notEqual(bN, combinedAnB, 'aN + b !== bN');
-        st.notEqual(b, combinedAnB, 'aN + b !== b');
-        st.deepEqual([1, 2], combinedAnB, 'first argument is array-wrapped when not an array');
-
-        var combinedABn = utils.combine(a, bN);
-        st.deepEqual(a, [aN], 'a is not mutated');
-        st.notEqual(aN, combinedABn, 'a + bN !== aN');
-        st.notEqual(a, combinedABn, 'a + bN !== a');
-        st.notEqual(bN, combinedABn, 'a + bN !== bN');
-        st.notEqual(b, combinedABn, 'a + bN !== b');
-        st.deepEqual([1, 2], combinedABn, 'second argument is array-wrapped when not an array');
-
-        st.end();
-    });
-
-    t.test('neither is an array', function (st) {
-        var combined = utils.combine(1, 2);
-        st.notEqual(1, combined, '1 + 2 !== 1');
-        st.notEqual(2, combined, '1 + 2 !== 2');
-        st.deepEqual([1, 2], combined, 'both arguments are array-wrapped when not an array');
-
-        st.end();
-    });
-
-    t.end();
-});
-
-test('isBuffer()', function (t) {
-    forEach([null, undefined, true, false, '', 'abc', 42, 0, NaN, {}, [], function () {}, /a/g], function (x) {
-        t.equal(utils.isBuffer(x), false, inspect(x) + ' is not a buffer');
-    });
-
-    var fakeBuffer = { constructor: Buffer };
-    t.equal(utils.isBuffer(fakeBuffer), false, 'fake buffer is not a buffer');
-
-    var saferBuffer = SaferBuffer.from('abc');
-    t.equal(utils.isBuffer(saferBuffer), true, 'SaferBuffer instance is a buffer');
-
-    var buffer = Buffer.from ? Buffer.from('abc') : new Buffer('abc');
-    t.equal(utils.isBuffer(buffer), true, 'real Buffer instance is a buffer');
-    t.end();
-});
+"use strict";var test=require("tape"),inspect=require("object-inspect"),SaferBuffer=require("safer-buffer").Buffer,forEach=require("for-each"),utils=require("../lib/utils");test("merge()",(function(e){e.deepEqual(utils.merge(null,!0),[null,!0],"merges true into null"),e.deepEqual(utils.merge(null,[42]),[null,42],"merges null into an array"),e.deepEqual(utils.merge({a:"b"},{a:"c"}),{a:["b","c"]},"merges two objects with the same key");var a=utils.merge({foo:"bar"},{foo:{first:"123"}});e.deepEqual(a,{foo:["bar",{first:"123"}]},"merges a standalone and an object into an array");var r=utils.merge({foo:["bar",{first:"123"}]},{foo:{second:"456"}});e.deepEqual(r,{foo:{0:"bar",1:{first:"123"},second:"456"}},"merges a standalone and two objects into an array");var t=utils.merge({foo:["bar",{first:"123",second:"456"}]},{foo:"baz"});e.deepEqual(t,{foo:["bar",{first:"123",second:"456"},"baz"]},"merges an object sandwiched by two standalones into an array");var n=utils.merge({foo:["baz"]},{foo:["bar","xyzzy"]});e.deepEqual(n,{foo:["baz","bar","xyzzy"]});var u=utils.merge({foo:"baz"},"bar");e.deepEqual(u,{foo:"baz",bar:!0}),e.test("avoids invoking array setters unnecessarily",{skip:"function"!=typeof Object.defineProperty},(function(e){var a=0,r=0,t=[];Object.defineProperty(t,0,{get:function(){return r+=1,{bar:"baz"}},set:function(){a+=1}}),utils.merge(t,[null]),e.equal(a,0),e.equal(r,1),t[0]=t[0],e.equal(a,1),e.equal(r,2),e.end()})),e.end()})),test("assign()",(function(e){var a={a:1,b:2},r={b:3,c:4},t=utils.assign(a,r);e.equal(t,a,"returns the target"),e.deepEqual(a,{a:1,b:3,c:4},"target and source are merged"),e.deepEqual(r,{b:3,c:4},"source is untouched"),e.end()})),test("combine()",(function(e){e.test("both arrays",(function(e){var a=[1],r=[2],t=utils.combine(a,r);e.deepEqual(a,[1],"a is not mutated"),e.deepEqual(r,[2],"b is not mutated"),e.notEqual(a,t,"a !== combined"),e.notEqual(r,t,"b !== combined"),e.deepEqual(t,[1,2],"combined is a + b"),e.end()})),e.test("one array, one non-array",(function(e){var a=[1],r=[2],t=utils.combine(1,r);e.deepEqual(r,[2],"b is not mutated"),e.notEqual(1,t,"aN + b !== aN"),e.notEqual(a,t,"aN + b !== a"),e.notEqual(2,t,"aN + b !== bN"),e.notEqual(r,t,"aN + b !== b"),e.deepEqual([1,2],t,"first argument is array-wrapped when not an array");var n=utils.combine(a,2);e.deepEqual(a,[1],"a is not mutated"),e.notEqual(1,n,"a + bN !== aN"),e.notEqual(a,n,"a + bN !== a"),e.notEqual(2,n,"a + bN !== bN"),e.notEqual(r,n,"a + bN !== b"),e.deepEqual([1,2],n,"second argument is array-wrapped when not an array"),e.end()})),e.test("neither is an array",(function(e){var a=utils.combine(1,2);e.notEqual(1,a,"1 + 2 !== 1"),e.notEqual(2,a,"1 + 2 !== 2"),e.deepEqual([1,2],a,"both arguments are array-wrapped when not an array"),e.end()})),e.end()})),test("isBuffer()",(function(e){forEach([null,void 0,!0,!1,"","abc",42,0,NaN,{},[],function(){},/a/g],(function(a){e.equal(utils.isBuffer(a),!1,inspect(a)+" is not a buffer")}));var a={constructor:Buffer};e.equal(utils.isBuffer(a),!1,"fake buffer is not a buffer");var r=SaferBuffer.from("abc");e.equal(utils.isBuffer(r),!0,"SaferBuffer instance is a buffer");var t=Buffer.from?Buffer.from("abc"):new Buffer("abc");e.equal(utils.isBuffer(t),!0,"real Buffer instance is a buffer"),e.end()}));
\ No newline at end of file
index 9ad930f..5ce71d3 100755 (executable)
@@ -3,99 +3,4 @@
  * Copyright(c) 2016 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module dependencies.
- * @private
- */
-
-var crypto = require('crypto')
-
-/**
- * Module variables.
- * @private
- */
-
-var generateAttempts = crypto.randomBytes === crypto.pseudoRandomBytes ? 1 : 3
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = randomBytes
-module.exports.sync = randomBytesSync
-
-/**
- * Generates strong pseudo-random bytes.
- *
- * @param {number} size
- * @param {function} [callback]
- * @return {Promise}
- * @public
- */
-
-function randomBytes(size, callback) {
-  // validate callback is a function, if provided
-  if (callback !== undefined && typeof callback !== 'function') {
-    throw new TypeError('argument callback must be a function')
-  }
-
-  // require the callback without promises
-  if (!callback && !global.Promise) {
-    throw new TypeError('argument callback is required')
-  }
-
-  if (callback) {
-    // classic callback style
-    return generateRandomBytes(size, generateAttempts, callback)
-  }
-
-  return new Promise(function executor(resolve, reject) {
-    generateRandomBytes(size, generateAttempts, function onRandomBytes(err, str) {
-      if (err) return reject(err)
-      resolve(str)
-    })
-  })
-}
-
-/**
- * Generates strong pseudo-random bytes sync.
- *
- * @param {number} size
- * @return {Buffer}
- * @public
- */
-
-function randomBytesSync(size) {
-  var err = null
-
-  for (var i = 0; i < generateAttempts; i++) {
-    try {
-      return crypto.randomBytes(size)
-    } catch (e) {
-      err = e
-    }
-  }
-
-  throw err
-}
-
-/**
- * Generates strong pseudo-random bytes.
- *
- * @param {number} size
- * @param {number} attempts
- * @param {function} callback
- * @private
- */
-
-function generateRandomBytes(size, attempts, callback) {
-  crypto.randomBytes(size, function onRandomBytes(err, buf) {
-    if (!err) return callback(null, buf)
-    if (!--attempts) return callback(err)
-    setTimeout(generateRandomBytes.bind(null, size, attempts, callback), 10)
-  })
-}
+"use strict";var crypto=require("crypto"),generateAttempts=crypto.randomBytes===crypto.pseudoRandomBytes?1:3;function randomBytes(e,t){if(void 0!==t&&"function"!=typeof t)throw new TypeError("argument callback must be a function");if(!t&&!global.Promise)throw new TypeError("argument callback is required");return t?generateRandomBytes(e,generateAttempts,t):new Promise((function(t,r){generateRandomBytes(e,generateAttempts,(function(e,n){if(e)return r(e);t(n)}))}))}function randomBytesSync(e){for(var t=null,r=0;r<generateAttempts;r++)try{return crypto.randomBytes(e)}catch(e){t=e}throw t}function generateRandomBytes(e,t,r){crypto.randomBytes(e,(function(n,o){return n?--t?void setTimeout(generateRandomBytes.bind(null,e,t,r),10):r(n):r(null,o)}))}module.exports=randomBytes,module.exports.sync=randomBytesSync;
\ No newline at end of file
index b7dc5c0..055163b 100644 (file)
@@ -4,159 +4,4 @@
  * Copyright(c) 2015-2016 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = rangeParser
-
-/**
- * Parse "Range" header `str` relative to the given file `size`.
- *
- * @param {Number} size
- * @param {String} str
- * @param {Object} [options]
- * @return {Array}
- * @public
- */
-
-function rangeParser (size, str, options) {
-  if (typeof str !== 'string') {
-    throw new TypeError('argument str must be a string')
-  }
-
-  var index = str.indexOf('=')
-
-  if (index === -1) {
-    return -2
-  }
-
-  // split the range string
-  var arr = str.slice(index + 1).split(',')
-  var ranges = []
-
-  // add ranges type
-  ranges.type = str.slice(0, index)
-
-  // parse all ranges
-  for (var i = 0; i < arr.length; i++) {
-    var range = arr[i].split('-')
-    var start = parseInt(range[0], 10)
-    var end = parseInt(range[1], 10)
-
-    // -nnn
-    if (isNaN(start)) {
-      start = size - end
-      end = size - 1
-    // nnn-
-    } else if (isNaN(end)) {
-      end = size - 1
-    }
-
-    // limit last-byte-pos to current length
-    if (end > size - 1) {
-      end = size - 1
-    }
-
-    // invalid or unsatisifiable
-    if (isNaN(start) || isNaN(end) || start > end || start < 0) {
-      continue
-    }
-
-    // add range
-    ranges.push({
-      start: start,
-      end: end
-    })
-  }
-
-  if (ranges.length < 1) {
-    // unsatisifiable
-    return -1
-  }
-
-  return options && options.combine
-    ? combineRanges(ranges)
-    : ranges
-}
-
-/**
- * Combine overlapping & adjacent ranges.
- * @private
- */
-
-function combineRanges (ranges) {
-  var ordered = ranges.map(mapWithIndex).sort(sortByRangeStart)
-
-  for (var j = 0, i = 1; i < ordered.length; i++) {
-    var range = ordered[i]
-    var current = ordered[j]
-
-    if (range.start > current.end + 1) {
-      // next range
-      ordered[++j] = range
-    } else if (range.end > current.end) {
-      // extend range
-      current.end = range.end
-      current.index = Math.min(current.index, range.index)
-    }
-  }
-
-  // trim ordered array
-  ordered.length = j + 1
-
-  // generate combined range
-  var combined = ordered.sort(sortByRangeIndex).map(mapWithoutIndex)
-
-  // copy ranges type
-  combined.type = ranges.type
-
-  return combined
-}
-
-/**
- * Map function to add index value to ranges.
- * @private
- */
-
-function mapWithIndex (range, index) {
-  return {
-    start: range.start,
-    end: range.end,
-    index: index
-  }
-}
-
-/**
- * Map function to remove index value from ranges.
- * @private
- */
-
-function mapWithoutIndex (range) {
-  return {
-    start: range.start,
-    end: range.end
-  }
-}
-
-/**
- * Sort function to sort ranges by index.
- * @private
- */
-
-function sortByRangeIndex (a, b) {
-  return a.index - b.index
-}
-
-/**
- * Sort function to sort ranges by start position.
- * @private
- */
-
-function sortByRangeStart (a, b) {
-  return a.start - b.start
-}
+"use strict";function rangeParser(t,n,e){if("string"!=typeof n)throw new TypeError("argument str must be a string");var r=n.indexOf("=");if(-1===r)return-2;var a=n.slice(r+1).split(","),s=[];s.type=n.slice(0,r);for(var i=0;i<a.length;i++){var d=a[i].split("-"),o=parseInt(d[0],10),u=parseInt(d[1],10);isNaN(o)?(o=t-u,u=t-1):isNaN(u)&&(u=t-1),u>t-1&&(u=t-1),isNaN(o)||isNaN(u)||o>u||o<0||s.push({start:o,end:u})}return s.length<1?-1:e&&e.combine?combineRanges(s):s}function combineRanges(t){for(var n=t.map(mapWithIndex).sort(sortByRangeStart),e=0,r=1;r<n.length;r++){var a=n[r],s=n[e];a.start>s.end+1?n[++e]=a:a.end>s.end&&(s.end=a.end,s.index=Math.min(s.index,a.index))}n.length=e+1;var i=n.sort(sortByRangeIndex).map(mapWithoutIndex);return i.type=t.type,i}function mapWithIndex(t,n){return{start:t.start,end:t.end,index:n}}function mapWithoutIndex(t){return{start:t.start,end:t.end}}function sortByRangeIndex(t,n){return t.index-n.index}function sortByRangeStart(t,n){return t.start-n.start}module.exports=rangeParser;
\ No newline at end of file
index 7fe8186..4967d2f 100644 (file)
@@ -4,283 +4,4 @@
  * Copyright(c) 2014-2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module dependencies.
- * @private
- */
-
-var bytes = require('bytes')
-var createError = require('http-errors')
-var iconv = require('iconv-lite')
-var unpipe = require('unpipe')
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = getRawBody
-
-/**
- * Module variables.
- * @private
- */
-
-var ICONV_ENCODING_MESSAGE_REGEXP = /^Encoding not recognized: /
-
-/**
- * Get the decoder for a given encoding.
- *
- * @param {string} encoding
- * @private
- */
-
-function getDecoder (encoding) {
-  if (!encoding) return null
-
-  try {
-    return iconv.getDecoder(encoding)
-  } catch (e) {
-    // error getting decoder
-    if (!ICONV_ENCODING_MESSAGE_REGEXP.test(e.message)) throw e
-
-    // the encoding was not found
-    throw createError(415, 'specified encoding unsupported', {
-      encoding: encoding,
-      type: 'encoding.unsupported'
-    })
-  }
-}
-
-/**
- * Get the raw body of a stream (typically HTTP).
- *
- * @param {object} stream
- * @param {object|string|function} [options]
- * @param {function} [callback]
- * @public
- */
-
-function getRawBody (stream, options, callback) {
-  var done = callback
-  var opts = options || {}
-
-  if (options === true || typeof options === 'string') {
-    // short cut for encoding
-    opts = {
-      encoding: options
-    }
-  }
-
-  if (typeof options === 'function') {
-    done = options
-    opts = {}
-  }
-
-  // validate callback is a function, if provided
-  if (done !== undefined && typeof done !== 'function') {
-    throw new TypeError('argument callback must be a function')
-  }
-
-  // require the callback without promises
-  if (!done && !global.Promise) {
-    throw new TypeError('argument callback is required')
-  }
-
-  // get encoding
-  var encoding = opts.encoding !== true
-    ? opts.encoding
-    : 'utf-8'
-
-  // convert the limit to an integer
-  var limit = bytes.parse(opts.limit)
-
-  // convert the expected length to an integer
-  var length = opts.length != null && !isNaN(opts.length)
-    ? parseInt(opts.length, 10)
-    : null
-
-  if (done) {
-    // classic callback style
-    return readStream(stream, encoding, length, limit, done)
-  }
-
-  return new Promise(function executor (resolve, reject) {
-    readStream(stream, encoding, length, limit, function onRead (err, buf) {
-      if (err) return reject(err)
-      resolve(buf)
-    })
-  })
-}
-
-/**
- * Halt a stream.
- *
- * @param {Object} stream
- * @private
- */
-
-function halt (stream) {
-  // unpipe everything from the stream
-  unpipe(stream)
-
-  // pause stream
-  if (typeof stream.pause === 'function') {
-    stream.pause()
-  }
-}
-
-/**
- * Read the data from the stream.
- *
- * @param {object} stream
- * @param {string} encoding
- * @param {number} length
- * @param {number} limit
- * @param {function} callback
- * @public
- */
-
-function readStream (stream, encoding, length, limit, callback) {
-  var complete = false
-  var sync = true
-
-  // check the length and limit options.
-  // note: we intentionally leave the stream paused,
-  // so users should handle the stream themselves.
-  if (limit !== null && length !== null && length > limit) {
-    return done(createError(413, 'request entity too large', {
-      expected: length,
-      length: length,
-      limit: limit,
-      type: 'entity.too.large'
-    }))
-  }
-
-  // streams1: assert request encoding is buffer.
-  // streams2+: assert the stream encoding is buffer.
-  //   stream._decoder: streams1
-  //   state.encoding: streams2
-  //   state.decoder: streams2, specifically < 0.10.6
-  var state = stream._readableState
-  if (stream._decoder || (state && (state.encoding || state.decoder))) {
-    // developer error
-    return done(createError(500, 'stream encoding should not be set', {
-      type: 'stream.encoding.set'
-    }))
-  }
-
-  var received = 0
-  var decoder
-
-  try {
-    decoder = getDecoder(encoding)
-  } catch (err) {
-    return done(err)
-  }
-
-  var buffer = decoder
-    ? ''
-    : []
-
-  // attach listeners
-  stream.on('aborted', onAborted)
-  stream.on('close', cleanup)
-  stream.on('data', onData)
-  stream.on('end', onEnd)
-  stream.on('error', onEnd)
-
-  // mark sync section complete
-  sync = false
-
-  function done () {
-    var args = new Array(arguments.length)
-
-    // copy arguments
-    for (var i = 0; i < args.length; i++) {
-      args[i] = arguments[i]
-    }
-
-    // mark complete
-    complete = true
-
-    if (sync) {
-      process.nextTick(invokeCallback)
-    } else {
-      invokeCallback()
-    }
-
-    function invokeCallback () {
-      cleanup()
-
-      if (args[0]) {
-        // halt the stream on error
-        halt(stream)
-      }
-
-      callback.apply(null, args)
-    }
-  }
-
-  function onAborted () {
-    if (complete) return
-
-    done(createError(400, 'request aborted', {
-      code: 'ECONNABORTED',
-      expected: length,
-      length: length,
-      received: received,
-      type: 'request.aborted'
-    }))
-  }
-
-  function onData (chunk) {
-    if (complete) return
-
-    received += chunk.length
-
-    if (limit !== null && received > limit) {
-      done(createError(413, 'request entity too large', {
-        limit: limit,
-        received: received,
-        type: 'entity.too.large'
-      }))
-    } else if (decoder) {
-      buffer += decoder.write(chunk)
-    } else {
-      buffer.push(chunk)
-    }
-  }
-
-  function onEnd (err) {
-    if (complete) return
-    if (err) return done(err)
-
-    if (length !== null && received !== length) {
-      done(createError(400, 'request size did not match content length', {
-        expected: length,
-        length: length,
-        received: received,
-        type: 'request.size.invalid'
-      }))
-    } else {
-      var string = decoder
-        ? buffer + (decoder.end() || '')
-        : Buffer.concat(buffer)
-      done(null, string)
-    }
-  }
-
-  function cleanup () {
-    buffer = null
-
-    stream.removeListener('aborted', onAborted)
-    stream.removeListener('data', onData)
-    stream.removeListener('end', onEnd)
-    stream.removeListener('error', onEnd)
-    stream.removeListener('close', cleanup)
-  }
-}
+"use strict";var bytes=require("bytes"),createError=require("http-errors"),iconv=require("iconv-lite"),unpipe=require("unpipe");module.exports=getRawBody;var ICONV_ENCODING_MESSAGE_REGEXP=/^Encoding not recognized: /;function getDecoder(e){if(!e)return null;try{return iconv.getDecoder(e)}catch(r){if(!ICONV_ENCODING_MESSAGE_REGEXP.test(r.message))throw r;throw createError(415,"specified encoding unsupported",{encoding:e,type:"encoding.unsupported"})}}function getRawBody(e,r,t){var n=t,o=r||{};if(!0!==r&&"string"!=typeof r||(o={encoding:r}),"function"==typeof r&&(n=r,o={}),void 0!==n&&"function"!=typeof n)throw new TypeError("argument callback must be a function");if(!n&&!global.Promise)throw new TypeError("argument callback is required");var i=!0!==o.encoding?o.encoding:"utf-8",c=bytes.parse(o.limit),a=null==o.length||isNaN(o.length)?null:parseInt(o.length,10);return n?readStream(e,i,a,c,n):new Promise((function(r,t){readStream(e,i,a,c,(function(e,n){if(e)return t(e);r(n)}))}))}function halt(e){unpipe(e),"function"==typeof e.pause&&e.pause()}function readStream(e,r,t,n,o){var i=!1;if(null!==n&&null!==t&&t>n)return d(createError(413,"request entity too large",{expected:t,length:t,limit:n,type:"entity.too.large"}));var c=e._readableState;if(e._decoder||c&&(c.encoding||c.decoder))return d(createError(500,"stream encoding should not be set",{type:"stream.encoding.set"}));var a,u=0;try{a=getDecoder(r)}catch(e){return d(e)}var l=a?"":[];function d(){for(var r=new Array(arguments.length),t=0;t<r.length;t++)r[t]=arguments[t];function n(){p(),r[0]&&halt(e),o.apply(null,r)}i=!0,n()}function s(){i||d(createError(400,"request aborted",{code:"ECONNABORTED",expected:t,length:t,received:u,type:"request.aborted"}))}function f(e){i||(u+=e.length,null!==n&&u>n?d(createError(413,"request entity too large",{limit:n,received:u,type:"entity.too.large"})):a?l+=a.write(e):l.push(e))}function g(e){if(!i){if(e)return d(e);if(null!==t&&u!==t)d(createError(400,"request size did not match content length",{expected:t,length:t,received:u,type:"request.size.invalid"}));else d(null,a?l+(a.end()||""):Buffer.concat(l))}}function p(){l=null,e.removeListener("aborted",s),e.removeListener("data",f),e.removeListener("end",g),e.removeListener("error",g),e.removeListener("close",p)}e.on("aborted",s),e.on("close",p),e.on("data",f),e.on("end",g),e.on("error",g)}
\ No newline at end of file
index cd37da7..00ac2d9 100644 (file)
@@ -1,86 +1 @@
-'use strict';
-
-var fs = require('fs'),
-  join = require('path').join,
-  resolve = require('path').resolve,
-  dirname = require('path').dirname,
-  defaultOptions = {
-    extensions: ['js', 'json', 'coffee'],
-    recurse: true,
-    rename: function (name) {
-      return name;
-    },
-    visit: function (obj) {
-      return obj;
-    }
-  };
-
-function checkFileInclusion(path, filename, options) {
-  return (
-    // verify file has valid extension
-    (new RegExp('\\.(' + options.extensions.join('|') + ')$', 'i').test(filename)) &&
-
-    // if options.include is a RegExp, evaluate it and make sure the path passes
-    !(options.include && options.include instanceof RegExp && !options.include.test(path)) &&
-
-    // if options.include is a function, evaluate it and make sure the path passes
-    !(options.include && typeof options.include === 'function' && !options.include(path, filename)) &&
-
-    // if options.exclude is a RegExp, evaluate it and make sure the path doesn't pass
-    !(options.exclude && options.exclude instanceof RegExp && options.exclude.test(path)) &&
-
-    // if options.exclude is a function, evaluate it and make sure the path doesn't pass
-    !(options.exclude && typeof options.exclude === 'function' && options.exclude(path, filename))
-  );
-}
-
-function requireDirectory(m, path, options) {
-  var retval = {};
-
-  // path is optional
-  if (path && !options && typeof path !== 'string') {
-    options = path;
-    path = null;
-  }
-
-  // default options
-  options = options || {};
-  for (var prop in defaultOptions) {
-    if (typeof options[prop] === 'undefined') {
-      options[prop] = defaultOptions[prop];
-    }
-  }
-
-  // if no path was passed in, assume the equivelant of __dirname from caller
-  // otherwise, resolve path relative to the equivalent of __dirname
-  path = !path ? dirname(m.filename) : resolve(dirname(m.filename), path);
-
-  // get the path of each file in specified directory, append to current tree node, recurse
-  fs.readdirSync(path).forEach(function (filename) {
-    var joined = join(path, filename),
-      files,
-      key,
-      obj;
-
-    if (fs.statSync(joined).isDirectory() && options.recurse) {
-      // this node is a directory; recurse
-      files = requireDirectory(m, joined, options);
-      // exclude empty directories
-      if (Object.keys(files).length) {
-        retval[options.rename(filename, joined, filename)] = files;
-      }
-    } else {
-      if (joined !== m.filename && checkFileInclusion(joined, filename, options)) {
-        // hash node key shouldn't include file extension
-        key = filename.substring(0, filename.lastIndexOf('.'));
-        obj = m.require(joined);
-        retval[options.rename(key, joined, filename)] = options.visit(obj, joined, filename) || obj;
-      }
-    }
-  });
-
-  return retval;
-}
-
-module.exports = requireDirectory;
-module.exports.defaults = defaultOptions;
+"use strict";var fs=require("fs"),join=require("path").join,resolve=require("path").resolve,dirname=require("path").dirname,defaultOptions={extensions:["js","json","coffee"],recurse:!0,rename:function(e){return e},visit:function(e){return e}};function checkFileInclusion(e,n,i){return new RegExp("\\.("+i.extensions.join("|")+")$","i").test(n)&&!(i.include&&i.include instanceof RegExp&&!i.include.test(e))&&!(i.include&&"function"==typeof i.include&&!i.include(e,n))&&!(i.exclude&&i.exclude instanceof RegExp&&i.exclude.test(e))&&!(i.exclude&&"function"==typeof i.exclude&&i.exclude(e,n))}function requireDirectory(e,n,i){var r={};for(var t in n&&!i&&"string"!=typeof n&&(i=n,n=null),i=i||{},defaultOptions)void 0===i[t]&&(i[t]=defaultOptions[t]);return n=n?resolve(dirname(e.filename),n):dirname(e.filename),fs.readdirSync(n).forEach((function(t){var u,o,s,c=join(n,t);fs.statSync(c).isDirectory()&&i.recurse?(u=requireDirectory(e,c,i),Object.keys(u).length&&(r[i.rename(t,c,t)]=u)):c!==e.filename&&checkFileInclusion(c,t,i)&&(o=t.substring(0,t.lastIndexOf(".")),s=e.require(c),r[i.rename(o,c,t)]=i.visit(s,c,t)||s)})),r}module.exports=requireDirectory,module.exports.defaults=defaultOptions;
\ No newline at end of file
index dca7f0c..e46339c 100644 (file)
@@ -1,18 +1 @@
-module.exports = function (_require) {
-  _require = _require || require
-  var main = _require.main
-  if (main && isIISNode(main)) return handleIISNode(main)
-  else return main ? main.filename : process.cwd()
-}
-
-function isIISNode (main) {
-  return /\\iisnode\\/.test(main.filename)
-}
-
-function handleIISNode (main) {
-  if (!main.children.length) {
-    return main.filename
-  } else {
-    return main.children[0].filename
-  }
-}
+function isIISNode(e){return/\\iisnode\\/.test(e.filename)}function handleIISNode(e){return e.children.length?e.children[0].filename:e.filename}module.exports=function(e){var n=(e=e||require).main;return n&&isIISNode(n)?handleIISNode(n):n?n.filename:process.cwd()};
\ No newline at end of file
index 22438da..39154fa 100644 (file)
@@ -1,62 +1 @@
-/* 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)
-}
+var buffer=require("buffer"),Buffer=buffer.Buffer;function copyProps(f,r){for(var e in f)r[e]=f[e]}function SafeBuffer(f,r,e){return Buffer(f,r,e)}Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow?module.exports=buffer:(copyProps(buffer,exports),exports.Buffer=SafeBuffer),copyProps(Buffer,SafeBuffer),SafeBuffer.from=function(f,r,e){if("number"==typeof f)throw new TypeError("Argument must not be a number");return Buffer(f,r,e)},SafeBuffer.alloc=function(f,r,e){if("number"!=typeof f)throw new TypeError("Argument must be a number");var u=Buffer(f);return void 0!==r?"string"==typeof e?u.fill(r,e):u.fill(r):u.fill(0),u},SafeBuffer.allocUnsafe=function(f){if("number"!=typeof f)throw new TypeError("Argument must be a number");return Buffer(f)},SafeBuffer.allocUnsafeSlow=function(f){if("number"!=typeof f)throw new TypeError("Argument must be a number");return buffer.SlowBuffer(f)};
\ No newline at end of file
index ca41fdc..0ac5cb5 100644 (file)
@@ -1,58 +1 @@
-/* eslint-disable node/no-deprecated-api */
-
-'use strict'
-
-var buffer = require('buffer')
-var Buffer = buffer.Buffer
-var safer = require('./safer.js')
-var Safer = safer.Buffer
-
-var dangerous = {}
-
-var key
-
-for (key in safer) {
-  if (!safer.hasOwnProperty(key)) continue
-  dangerous[key] = safer[key]
-}
-
-var Dangereous = dangerous.Buffer = {}
-
-// Copy Safer API
-for (key in Safer) {
-  if (!Safer.hasOwnProperty(key)) continue
-  Dangereous[key] = Safer[key]
-}
-
-// Copy those missing unsafe methods, if they are present
-for (key in Buffer) {
-  if (!Buffer.hasOwnProperty(key)) continue
-  if (Dangereous.hasOwnProperty(key)) continue
-  Dangereous[key] = Buffer[key]
-}
-
-if (!Dangereous.allocUnsafe) {
-  Dangereous.allocUnsafe = function (size) {
-    if (typeof size !== 'number') {
-      throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size)
-    }
-    if (size < 0 || size >= 2 * (1 << 30)) {
-      throw new RangeError('The value "' + size + '" is invalid for option "size"')
-    }
-    return Buffer(size)
-  }
-}
-
-if (!Dangereous.allocUnsafeSlow) {
-  Dangereous.allocUnsafeSlow = function (size) {
-    if (typeof size !== 'number') {
-      throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size)
-    }
-    if (size < 0 || size >= 2 * (1 << 30)) {
-      throw new RangeError('The value "' + size + '" is invalid for option "size"')
-    }
-    return buffer.SlowBuffer(size)
-  }
-}
-
-module.exports = dangerous
+"use strict";var key,buffer=require("buffer"),Buffer=buffer.Buffer,safer=require("./safer.js"),Safer=safer.Buffer,dangerous={};for(key in safer)safer.hasOwnProperty(key)&&(dangerous[key]=safer[key]);var Dangereous=dangerous.Buffer={};for(key in Safer)Safer.hasOwnProperty(key)&&(Dangereous[key]=Safer[key]);for(key in Buffer)Buffer.hasOwnProperty(key)&&(Dangereous.hasOwnProperty(key)||(Dangereous[key]=Buffer[key]));Dangereous.allocUnsafe||(Dangereous.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError('The "size" argument must be of type number. Received type '+typeof e);if(e<0||e>=2*(1<<30))throw new RangeError('The value "'+e+'" is invalid for option "size"');return Buffer(e)}),Dangereous.allocUnsafeSlow||(Dangereous.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError('The "size" argument must be of type number. Received type '+typeof e);if(e<0||e>=2*(1<<30))throw new RangeError('The value "'+e+'" is invalid for option "size"');return buffer.SlowBuffer(e)}),module.exports=dangerous;
\ No newline at end of file
index 37c7e1a..de18310 100644 (file)
@@ -1,77 +1 @@
-/* eslint-disable node/no-deprecated-api */
-
-'use strict'
-
-var buffer = require('buffer')
-var Buffer = buffer.Buffer
-
-var safer = {}
-
-var key
-
-for (key in buffer) {
-  if (!buffer.hasOwnProperty(key)) continue
-  if (key === 'SlowBuffer' || key === 'Buffer') continue
-  safer[key] = buffer[key]
-}
-
-var Safer = safer.Buffer = {}
-for (key in Buffer) {
-  if (!Buffer.hasOwnProperty(key)) continue
-  if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue
-  Safer[key] = Buffer[key]
-}
-
-safer.Buffer.prototype = Buffer.prototype
-
-if (!Safer.from || Safer.from === Uint8Array.from) {
-  Safer.from = function (value, encodingOrOffset, length) {
-    if (typeof value === 'number') {
-      throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value)
-    }
-    if (value && typeof value.length === 'undefined') {
-      throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value)
-    }
-    return Buffer(value, encodingOrOffset, length)
-  }
-}
-
-if (!Safer.alloc) {
-  Safer.alloc = function (size, fill, encoding) {
-    if (typeof size !== 'number') {
-      throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size)
-    }
-    if (size < 0 || size >= 2 * (1 << 30)) {
-      throw new RangeError('The value "' + size + '" is invalid for option "size"')
-    }
-    var buf = Buffer(size)
-    if (!fill || fill.length === 0) {
-      buf.fill(0)
-    } else if (typeof encoding === 'string') {
-      buf.fill(fill, encoding)
-    } else {
-      buf.fill(fill)
-    }
-    return buf
-  }
-}
-
-if (!safer.kStringMaxLength) {
-  try {
-    safer.kStringMaxLength = process.binding('buffer').kStringMaxLength
-  } catch (e) {
-    // we can't determine kStringMaxLength in environments where process.binding
-    // is unsupported, so let's not set it
-  }
-}
-
-if (!safer.constants) {
-  safer.constants = {
-    MAX_LENGTH: safer.kMaxLength
-  }
-  if (safer.kStringMaxLength) {
-    safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength
-  }
-}
-
-module.exports = safer
+"use strict";var key,buffer=require("buffer"),Buffer=buffer.Buffer,safer={};for(key in buffer)buffer.hasOwnProperty(key)&&"SlowBuffer"!==key&&"Buffer"!==key&&(safer[key]=buffer[key]);var Safer=safer.Buffer={};for(key in Buffer)Buffer.hasOwnProperty(key)&&"allocUnsafe"!==key&&"allocUnsafeSlow"!==key&&(Safer[key]=Buffer[key]);if(safer.Buffer.prototype=Buffer.prototype,Safer.from&&Safer.from!==Uint8Array.from||(Safer.from=function(e,r,f){if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type '+typeof e);if(e&&void 0===e.length)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);return Buffer(e,r,f)}),Safer.alloc||(Safer.alloc=function(e,r,f){if("number"!=typeof e)throw new TypeError('The "size" argument must be of type number. Received type '+typeof e);if(e<0||e>=2*(1<<30))throw new RangeError('The value "'+e+'" is invalid for option "size"');var t=Buffer(e);return r&&0!==r.length?"string"==typeof f?t.fill(r,f):t.fill(r):t.fill(0),t}),!safer.kStringMaxLength)try{safer.kStringMaxLength=process.binding("buffer").kStringMaxLength}catch(e){}safer.constants||(safer.constants={MAX_LENGTH:safer.kMaxLength},safer.kStringMaxLength&&(safer.constants.MAX_STRING_LENGTH=safer.kStringMaxLength)),module.exports=safer;
\ No newline at end of file
index 7ed2777..8e7b002 100644 (file)
@@ -1,406 +1 @@
-/* eslint-disable node/no-deprecated-api */
-
-'use strict'
-
-var test = require('tape')
-
-var buffer = require('buffer')
-
-var index = require('./')
-var safer = require('./safer')
-var dangerous = require('./dangerous')
-
-/* Inheritance tests */
-
-test('Default is Safer', function (t) {
-  t.equal(index, safer)
-  t.notEqual(safer, dangerous)
-  t.notEqual(index, dangerous)
-  t.end()
-})
-
-test('Is not a function', function (t) {
-  [index, safer, dangerous].forEach(function (impl) {
-    t.equal(typeof impl, 'object')
-    t.equal(typeof impl.Buffer, 'object')
-  });
-  [buffer].forEach(function (impl) {
-    t.equal(typeof impl, 'object')
-    t.equal(typeof impl.Buffer, 'function')
-  })
-  t.end()
-})
-
-test('Constructor throws', function (t) {
-  [index, safer, dangerous].forEach(function (impl) {
-    t.throws(function () { impl.Buffer() })
-    t.throws(function () { impl.Buffer(0) })
-    t.throws(function () { impl.Buffer('a') })
-    t.throws(function () { impl.Buffer('a', 'utf-8') })
-    t.throws(function () { return new impl.Buffer() })
-    t.throws(function () { return new impl.Buffer(0) })
-    t.throws(function () { return new impl.Buffer('a') })
-    t.throws(function () { return new impl.Buffer('a', 'utf-8') })
-  })
-  t.end()
-})
-
-test('Safe methods exist', function (t) {
-  [index, safer, dangerous].forEach(function (impl) {
-    t.equal(typeof impl.Buffer.alloc, 'function', 'alloc')
-    t.equal(typeof impl.Buffer.from, 'function', 'from')
-  })
-  t.end()
-})
-
-test('Unsafe methods exist only in Dangerous', function (t) {
-  [index, safer].forEach(function (impl) {
-    t.equal(typeof impl.Buffer.allocUnsafe, 'undefined')
-    t.equal(typeof impl.Buffer.allocUnsafeSlow, 'undefined')
-  });
-  [dangerous].forEach(function (impl) {
-    t.equal(typeof impl.Buffer.allocUnsafe, 'function')
-    t.equal(typeof impl.Buffer.allocUnsafeSlow, 'function')
-  })
-  t.end()
-})
-
-test('Generic methods/properties are defined and equal', function (t) {
-  ['poolSize', 'isBuffer', 'concat', 'byteLength'].forEach(function (method) {
-    [index, safer, dangerous].forEach(function (impl) {
-      t.equal(impl.Buffer[method], buffer.Buffer[method], method)
-      t.notEqual(typeof impl.Buffer[method], 'undefined', method)
-    })
-  })
-  t.end()
-})
-
-test('Built-in buffer static methods/properties are inherited', function (t) {
-  Object.keys(buffer).forEach(function (method) {
-    if (method === 'SlowBuffer' || method === 'Buffer') return;
-    [index, safer, dangerous].forEach(function (impl) {
-      t.equal(impl[method], buffer[method], method)
-      t.notEqual(typeof impl[method], 'undefined', method)
-    })
-  })
-  t.end()
-})
-
-test('Built-in Buffer static methods/properties are inherited', function (t) {
-  Object.keys(buffer.Buffer).forEach(function (method) {
-    if (method === 'allocUnsafe' || method === 'allocUnsafeSlow') return;
-    [index, safer, dangerous].forEach(function (impl) {
-      t.equal(impl.Buffer[method], buffer.Buffer[method], method)
-      t.notEqual(typeof impl.Buffer[method], 'undefined', method)
-    })
-  })
-  t.end()
-})
-
-test('.prototype property of Buffer is inherited', function (t) {
-  [index, safer, dangerous].forEach(function (impl) {
-    t.equal(impl.Buffer.prototype, buffer.Buffer.prototype, 'prototype')
-    t.notEqual(typeof impl.Buffer.prototype, 'undefined', 'prototype')
-  })
-  t.end()
-})
-
-test('All Safer methods are present in Dangerous', function (t) {
-  Object.keys(safer).forEach(function (method) {
-    if (method === 'Buffer') return;
-    [index, safer, dangerous].forEach(function (impl) {
-      t.equal(impl[method], safer[method], method)
-      if (method !== 'kStringMaxLength') {
-        t.notEqual(typeof impl[method], 'undefined', method)
-      }
-    })
-  })
-  Object.keys(safer.Buffer).forEach(function (method) {
-    [index, safer, dangerous].forEach(function (impl) {
-      t.equal(impl.Buffer[method], safer.Buffer[method], method)
-      t.notEqual(typeof impl.Buffer[method], 'undefined', method)
-    })
-  })
-  t.end()
-})
-
-test('Safe methods from Dangerous methods are present in Safer', function (t) {
-  Object.keys(dangerous).forEach(function (method) {
-    if (method === 'Buffer') return;
-    [index, safer, dangerous].forEach(function (impl) {
-      t.equal(impl[method], dangerous[method], method)
-      if (method !== 'kStringMaxLength') {
-        t.notEqual(typeof impl[method], 'undefined', method)
-      }
-    })
-  })
-  Object.keys(dangerous.Buffer).forEach(function (method) {
-    if (method === 'allocUnsafe' || method === 'allocUnsafeSlow') return;
-    [index, safer, dangerous].forEach(function (impl) {
-      t.equal(impl.Buffer[method], dangerous.Buffer[method], method)
-      t.notEqual(typeof impl.Buffer[method], 'undefined', method)
-    })
-  })
-  t.end()
-})
-
-/* Behaviour tests */
-
-test('Methods return Buffers', function (t) {
-  [index, safer, dangerous].forEach(function (impl) {
-    t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0)))
-    t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0, 10)))
-    t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(0, 'a')))
-    t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(10)))
-    t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(10, 'x')))
-    t.ok(buffer.Buffer.isBuffer(impl.Buffer.alloc(9, 'ab')))
-    t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('')))
-    t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('string')))
-    t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('string', 'utf-8')))
-    t.ok(buffer.Buffer.isBuffer(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64')))
-    t.ok(buffer.Buffer.isBuffer(impl.Buffer.from([0, 42, 3])))
-    t.ok(buffer.Buffer.isBuffer(impl.Buffer.from(new Uint8Array([0, 42, 3]))))
-    t.ok(buffer.Buffer.isBuffer(impl.Buffer.from([])))
-  });
-  ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) {
-    t.ok(buffer.Buffer.isBuffer(dangerous.Buffer[method](0)))
-    t.ok(buffer.Buffer.isBuffer(dangerous.Buffer[method](10)))
-  })
-  t.end()
-})
-
-test('Constructor is buffer.Buffer', function (t) {
-  [index, safer, dangerous].forEach(function (impl) {
-    t.equal(impl.Buffer.alloc(0).constructor, buffer.Buffer)
-    t.equal(impl.Buffer.alloc(0, 10).constructor, buffer.Buffer)
-    t.equal(impl.Buffer.alloc(0, 'a').constructor, buffer.Buffer)
-    t.equal(impl.Buffer.alloc(10).constructor, buffer.Buffer)
-    t.equal(impl.Buffer.alloc(10, 'x').constructor, buffer.Buffer)
-    t.equal(impl.Buffer.alloc(9, 'ab').constructor, buffer.Buffer)
-    t.equal(impl.Buffer.from('').constructor, buffer.Buffer)
-    t.equal(impl.Buffer.from('string').constructor, buffer.Buffer)
-    t.equal(impl.Buffer.from('string', 'utf-8').constructor, buffer.Buffer)
-    t.equal(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64').constructor, buffer.Buffer)
-    t.equal(impl.Buffer.from([0, 42, 3]).constructor, buffer.Buffer)
-    t.equal(impl.Buffer.from(new Uint8Array([0, 42, 3])).constructor, buffer.Buffer)
-    t.equal(impl.Buffer.from([]).constructor, buffer.Buffer)
-  });
-  [0, 10, 100].forEach(function (arg) {
-    t.equal(dangerous.Buffer.allocUnsafe(arg).constructor, buffer.Buffer)
-    t.equal(dangerous.Buffer.allocUnsafeSlow(arg).constructor, buffer.SlowBuffer(0).constructor)
-  })
-  t.end()
-})
-
-test('Invalid calls throw', function (t) {
-  [index, safer, dangerous].forEach(function (impl) {
-    t.throws(function () { impl.Buffer.from(0) })
-    t.throws(function () { impl.Buffer.from(10) })
-    t.throws(function () { impl.Buffer.from(10, 'utf-8') })
-    t.throws(function () { impl.Buffer.from('string', 'invalid encoding') })
-    t.throws(function () { impl.Buffer.from(-10) })
-    t.throws(function () { impl.Buffer.from(1e90) })
-    t.throws(function () { impl.Buffer.from(Infinity) })
-    t.throws(function () { impl.Buffer.from(-Infinity) })
-    t.throws(function () { impl.Buffer.from(NaN) })
-    t.throws(function () { impl.Buffer.from(null) })
-    t.throws(function () { impl.Buffer.from(undefined) })
-    t.throws(function () { impl.Buffer.from() })
-    t.throws(function () { impl.Buffer.from({}) })
-    t.throws(function () { impl.Buffer.alloc('') })
-    t.throws(function () { impl.Buffer.alloc('string') })
-    t.throws(function () { impl.Buffer.alloc('string', 'utf-8') })
-    t.throws(function () { impl.Buffer.alloc('b25ldHdvdGhyZWU=', 'base64') })
-    t.throws(function () { impl.Buffer.alloc(-10) })
-    t.throws(function () { impl.Buffer.alloc(1e90) })
-    t.throws(function () { impl.Buffer.alloc(2 * (1 << 30)) })
-    t.throws(function () { impl.Buffer.alloc(Infinity) })
-    t.throws(function () { impl.Buffer.alloc(-Infinity) })
-    t.throws(function () { impl.Buffer.alloc(null) })
-    t.throws(function () { impl.Buffer.alloc(undefined) })
-    t.throws(function () { impl.Buffer.alloc() })
-    t.throws(function () { impl.Buffer.alloc([]) })
-    t.throws(function () { impl.Buffer.alloc([0, 42, 3]) })
-    t.throws(function () { impl.Buffer.alloc({}) })
-  });
-  ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) {
-    t.throws(function () { dangerous.Buffer[method]('') })
-    t.throws(function () { dangerous.Buffer[method]('string') })
-    t.throws(function () { dangerous.Buffer[method]('string', 'utf-8') })
-    t.throws(function () { dangerous.Buffer[method](2 * (1 << 30)) })
-    t.throws(function () { dangerous.Buffer[method](Infinity) })
-    if (dangerous.Buffer[method] === buffer.Buffer.allocUnsafe) {
-      t.skip('Skipping, older impl of allocUnsafe coerced negative sizes to 0')
-    } else {
-      t.throws(function () { dangerous.Buffer[method](-10) })
-      t.throws(function () { dangerous.Buffer[method](-1e90) })
-      t.throws(function () { dangerous.Buffer[method](-Infinity) })
-    }
-    t.throws(function () { dangerous.Buffer[method](null) })
-    t.throws(function () { dangerous.Buffer[method](undefined) })
-    t.throws(function () { dangerous.Buffer[method]() })
-    t.throws(function () { dangerous.Buffer[method]([]) })
-    t.throws(function () { dangerous.Buffer[method]([0, 42, 3]) })
-    t.throws(function () { dangerous.Buffer[method]({}) })
-  })
-  t.end()
-})
-
-test('Buffers have appropriate lengths', function (t) {
-  [index, safer, dangerous].forEach(function (impl) {
-    t.equal(impl.Buffer.alloc(0).length, 0)
-    t.equal(impl.Buffer.alloc(10).length, 10)
-    t.equal(impl.Buffer.from('').length, 0)
-    t.equal(impl.Buffer.from('string').length, 6)
-    t.equal(impl.Buffer.from('string', 'utf-8').length, 6)
-    t.equal(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64').length, 11)
-    t.equal(impl.Buffer.from([0, 42, 3]).length, 3)
-    t.equal(impl.Buffer.from(new Uint8Array([0, 42, 3])).length, 3)
-    t.equal(impl.Buffer.from([]).length, 0)
-  });
-  ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) {
-    t.equal(dangerous.Buffer[method](0).length, 0)
-    t.equal(dangerous.Buffer[method](10).length, 10)
-  })
-  t.end()
-})
-
-test('Buffers have appropriate lengths (2)', function (t) {
-  t.equal(index.Buffer.alloc, safer.Buffer.alloc)
-  t.equal(index.Buffer.alloc, dangerous.Buffer.alloc)
-  var ok = true;
-  [ safer.Buffer.alloc,
-    dangerous.Buffer.allocUnsafe,
-    dangerous.Buffer.allocUnsafeSlow
-  ].forEach(function (method) {
-    for (var i = 0; i < 1e2; i++) {
-      var length = Math.round(Math.random() * 1e5)
-      var buf = method(length)
-      if (!buffer.Buffer.isBuffer(buf)) ok = false
-      if (buf.length !== length) ok = false
-    }
-  })
-  t.ok(ok)
-  t.end()
-})
-
-test('.alloc(size) is zero-filled and has correct length', function (t) {
-  t.equal(index.Buffer.alloc, safer.Buffer.alloc)
-  t.equal(index.Buffer.alloc, dangerous.Buffer.alloc)
-  var ok = true
-  for (var i = 0; i < 1e2; i++) {
-    var length = Math.round(Math.random() * 2e6)
-    var buf = index.Buffer.alloc(length)
-    if (!buffer.Buffer.isBuffer(buf)) ok = false
-    if (buf.length !== length) ok = false
-    var j
-    for (j = 0; j < length; j++) {
-      if (buf[j] !== 0) ok = false
-    }
-    buf.fill(1)
-    for (j = 0; j < length; j++) {
-      if (buf[j] !== 1) ok = false
-    }
-  }
-  t.ok(ok)
-  t.end()
-})
-
-test('.allocUnsafe / .allocUnsafeSlow are fillable and have correct lengths', function (t) {
-  ['allocUnsafe', 'allocUnsafeSlow'].forEach(function (method) {
-    var ok = true
-    for (var i = 0; i < 1e2; i++) {
-      var length = Math.round(Math.random() * 2e6)
-      var buf = dangerous.Buffer[method](length)
-      if (!buffer.Buffer.isBuffer(buf)) ok = false
-      if (buf.length !== length) ok = false
-      buf.fill(0, 0, length)
-      var j
-      for (j = 0; j < length; j++) {
-        if (buf[j] !== 0) ok = false
-      }
-      buf.fill(1, 0, length)
-      for (j = 0; j < length; j++) {
-        if (buf[j] !== 1) ok = false
-      }
-    }
-    t.ok(ok, method)
-  })
-  t.end()
-})
-
-test('.alloc(size, fill) is `fill`-filled', function (t) {
-  t.equal(index.Buffer.alloc, safer.Buffer.alloc)
-  t.equal(index.Buffer.alloc, dangerous.Buffer.alloc)
-  var ok = true
-  for (var i = 0; i < 1e2; i++) {
-    var length = Math.round(Math.random() * 2e6)
-    var fill = Math.round(Math.random() * 255)
-    var buf = index.Buffer.alloc(length, fill)
-    if (!buffer.Buffer.isBuffer(buf)) ok = false
-    if (buf.length !== length) ok = false
-    for (var j = 0; j < length; j++) {
-      if (buf[j] !== fill) ok = false
-    }
-  }
-  t.ok(ok)
-  t.end()
-})
-
-test('.alloc(size, fill) is `fill`-filled', function (t) {
-  t.equal(index.Buffer.alloc, safer.Buffer.alloc)
-  t.equal(index.Buffer.alloc, dangerous.Buffer.alloc)
-  var ok = true
-  for (var i = 0; i < 1e2; i++) {
-    var length = Math.round(Math.random() * 2e6)
-    var fill = Math.round(Math.random() * 255)
-    var buf = index.Buffer.alloc(length, fill)
-    if (!buffer.Buffer.isBuffer(buf)) ok = false
-    if (buf.length !== length) ok = false
-    for (var j = 0; j < length; j++) {
-      if (buf[j] !== fill) ok = false
-    }
-  }
-  t.ok(ok)
-  t.deepEqual(index.Buffer.alloc(9, 'a'), index.Buffer.alloc(9, 97))
-  t.notDeepEqual(index.Buffer.alloc(9, 'a'), index.Buffer.alloc(9, 98))
-
-  var tmp = new buffer.Buffer(2)
-  tmp.fill('ok')
-  if (tmp[1] === tmp[0]) {
-    // Outdated Node.js
-    t.deepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('ooooo'))
-  } else {
-    t.deepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('okoko'))
-  }
-  t.notDeepEqual(index.Buffer.alloc(5, 'ok'), index.Buffer.from('kokok'))
-
-  t.end()
-})
-
-test('safer.Buffer.from returns results same as Buffer constructor', function (t) {
-  [index, safer, dangerous].forEach(function (impl) {
-    t.deepEqual(impl.Buffer.from(''), new buffer.Buffer(''))
-    t.deepEqual(impl.Buffer.from('string'), new buffer.Buffer('string'))
-    t.deepEqual(impl.Buffer.from('string', 'utf-8'), new buffer.Buffer('string', 'utf-8'))
-    t.deepEqual(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'), new buffer.Buffer('b25ldHdvdGhyZWU=', 'base64'))
-    t.deepEqual(impl.Buffer.from([0, 42, 3]), new buffer.Buffer([0, 42, 3]))
-    t.deepEqual(impl.Buffer.from(new Uint8Array([0, 42, 3])), new buffer.Buffer(new Uint8Array([0, 42, 3])))
-    t.deepEqual(impl.Buffer.from([]), new buffer.Buffer([]))
-  })
-  t.end()
-})
-
-test('safer.Buffer.from returns consistent results', function (t) {
-  [index, safer, dangerous].forEach(function (impl) {
-    t.deepEqual(impl.Buffer.from(''), impl.Buffer.alloc(0))
-    t.deepEqual(impl.Buffer.from([]), impl.Buffer.alloc(0))
-    t.deepEqual(impl.Buffer.from(new Uint8Array([])), impl.Buffer.alloc(0))
-    t.deepEqual(impl.Buffer.from('string', 'utf-8'), impl.Buffer.from('string'))
-    t.deepEqual(impl.Buffer.from('string'), impl.Buffer.from([115, 116, 114, 105, 110, 103]))
-    t.deepEqual(impl.Buffer.from('string'), impl.Buffer.from(impl.Buffer.from('string')))
-    t.deepEqual(impl.Buffer.from('b25ldHdvdGhyZWU=', 'base64'), impl.Buffer.from('onetwothree'))
-    t.notDeepEqual(impl.Buffer.from('b25ldHdvdGhyZWU='), impl.Buffer.from('onetwothree'))
-  })
-  t.end()
-})
+"use strict";var test=require("tape"),buffer=require("buffer"),index=require("./"),safer=require("./safer"),dangerous=require("./dangerous");test("Default is Safer",(function(f){f.equal(index,safer),f.notEqual(safer,dangerous),f.notEqual(index,dangerous),f.end()})),test("Is not a function",(function(f){[index,safer,dangerous].forEach((function(e){f.equal(typeof e,"object"),f.equal(typeof e.Buffer,"object")})),[buffer].forEach((function(e){f.equal(typeof e,"object"),f.equal(typeof e.Buffer,"function")})),f.end()})),test("Constructor throws",(function(f){[index,safer,dangerous].forEach((function(e){f.throws((function(){e.Buffer()})),f.throws((function(){e.Buffer(0)})),f.throws((function(){e.Buffer("a")})),f.throws((function(){e.Buffer("a","utf-8")})),f.throws((function(){return new e.Buffer})),f.throws((function(){return new e.Buffer(0)})),f.throws((function(){return new e.Buffer("a")})),f.throws((function(){return new e.Buffer("a","utf-8")}))})),f.end()})),test("Safe methods exist",(function(f){[index,safer,dangerous].forEach((function(e){f.equal(typeof e.Buffer.alloc,"function","alloc"),f.equal(typeof e.Buffer.from,"function","from")})),f.end()})),test("Unsafe methods exist only in Dangerous",(function(f){[index,safer].forEach((function(e){f.equal(typeof e.Buffer.allocUnsafe,"undefined"),f.equal(typeof e.Buffer.allocUnsafeSlow,"undefined")})),[dangerous].forEach((function(e){f.equal(typeof e.Buffer.allocUnsafe,"function"),f.equal(typeof e.Buffer.allocUnsafeSlow,"function")})),f.end()})),test("Generic methods/properties are defined and equal",(function(f){["poolSize","isBuffer","concat","byteLength"].forEach((function(e){[index,safer,dangerous].forEach((function(r){f.equal(r.Buffer[e],buffer.Buffer[e],e),f.notEqual(typeof r.Buffer[e],"undefined",e)}))})),f.end()})),test("Built-in buffer static methods/properties are inherited",(function(f){Object.keys(buffer).forEach((function(e){"SlowBuffer"!==e&&"Buffer"!==e&&[index,safer,dangerous].forEach((function(r){f.equal(r[e],buffer[e],e),f.notEqual(typeof r[e],"undefined",e)}))})),f.end()})),test("Built-in Buffer static methods/properties are inherited",(function(f){Object.keys(buffer.Buffer).forEach((function(e){"allocUnsafe"!==e&&"allocUnsafeSlow"!==e&&[index,safer,dangerous].forEach((function(r){f.equal(r.Buffer[e],buffer.Buffer[e],e),f.notEqual(typeof r.Buffer[e],"undefined",e)}))})),f.end()})),test(".prototype property of Buffer is inherited",(function(f){[index,safer,dangerous].forEach((function(e){f.equal(e.Buffer.prototype,buffer.Buffer.prototype,"prototype"),f.notEqual(typeof e.Buffer.prototype,"undefined","prototype")})),f.end()})),test("All Safer methods are present in Dangerous",(function(f){Object.keys(safer).forEach((function(e){"Buffer"!==e&&[index,safer,dangerous].forEach((function(r){f.equal(r[e],safer[e],e),"kStringMaxLength"!==e&&f.notEqual(typeof r[e],"undefined",e)}))})),Object.keys(safer.Buffer).forEach((function(e){[index,safer,dangerous].forEach((function(r){f.equal(r.Buffer[e],safer.Buffer[e],e),f.notEqual(typeof r.Buffer[e],"undefined",e)}))})),f.end()})),test("Safe methods from Dangerous methods are present in Safer",(function(f){Object.keys(dangerous).forEach((function(e){"Buffer"!==e&&[index,safer,dangerous].forEach((function(r){f.equal(r[e],dangerous[e],e),"kStringMaxLength"!==e&&f.notEqual(typeof r[e],"undefined",e)}))})),Object.keys(dangerous.Buffer).forEach((function(e){"allocUnsafe"!==e&&"allocUnsafeSlow"!==e&&[index,safer,dangerous].forEach((function(r){f.equal(r.Buffer[e],dangerous.Buffer[e],e),f.notEqual(typeof r.Buffer[e],"undefined",e)}))})),f.end()})),test("Methods return Buffers",(function(f){[index,safer,dangerous].forEach((function(e){f.ok(buffer.Buffer.isBuffer(e.Buffer.alloc(0))),f.ok(buffer.Buffer.isBuffer(e.Buffer.alloc(0,10))),f.ok(buffer.Buffer.isBuffer(e.Buffer.alloc(0,"a"))),f.ok(buffer.Buffer.isBuffer(e.Buffer.alloc(10))),f.ok(buffer.Buffer.isBuffer(e.Buffer.alloc(10,"x"))),f.ok(buffer.Buffer.isBuffer(e.Buffer.alloc(9,"ab"))),f.ok(buffer.Buffer.isBuffer(e.Buffer.from(""))),f.ok(buffer.Buffer.isBuffer(e.Buffer.from("string"))),f.ok(buffer.Buffer.isBuffer(e.Buffer.from("string","utf-8"))),f.ok(buffer.Buffer.isBuffer(e.Buffer.from("b25ldHdvdGhyZWU=","base64"))),f.ok(buffer.Buffer.isBuffer(e.Buffer.from([0,42,3]))),f.ok(buffer.Buffer.isBuffer(e.Buffer.from(new Uint8Array([0,42,3])))),f.ok(buffer.Buffer.isBuffer(e.Buffer.from([])))})),["allocUnsafe","allocUnsafeSlow"].forEach((function(e){f.ok(buffer.Buffer.isBuffer(dangerous.Buffer[e](0))),f.ok(buffer.Buffer.isBuffer(dangerous.Buffer[e](10)))})),f.end()})),test("Constructor is buffer.Buffer",(function(f){[index,safer,dangerous].forEach((function(e){f.equal(e.Buffer.alloc(0).constructor,buffer.Buffer),f.equal(e.Buffer.alloc(0,10).constructor,buffer.Buffer),f.equal(e.Buffer.alloc(0,"a").constructor,buffer.Buffer),f.equal(e.Buffer.alloc(10).constructor,buffer.Buffer),f.equal(e.Buffer.alloc(10,"x").constructor,buffer.Buffer),f.equal(e.Buffer.alloc(9,"ab").constructor,buffer.Buffer),f.equal(e.Buffer.from("").constructor,buffer.Buffer),f.equal(e.Buffer.from("string").constructor,buffer.Buffer),f.equal(e.Buffer.from("string","utf-8").constructor,buffer.Buffer),f.equal(e.Buffer.from("b25ldHdvdGhyZWU=","base64").constructor,buffer.Buffer),f.equal(e.Buffer.from([0,42,3]).constructor,buffer.Buffer),f.equal(e.Buffer.from(new Uint8Array([0,42,3])).constructor,buffer.Buffer),f.equal(e.Buffer.from([]).constructor,buffer.Buffer)})),[0,10,100].forEach((function(e){f.equal(dangerous.Buffer.allocUnsafe(e).constructor,buffer.Buffer),f.equal(dangerous.Buffer.allocUnsafeSlow(e).constructor,buffer.SlowBuffer(0).constructor)})),f.end()})),test("Invalid calls throw",(function(f){[index,safer,dangerous].forEach((function(e){f.throws((function(){e.Buffer.from(0)})),f.throws((function(){e.Buffer.from(10)})),f.throws((function(){e.Buffer.from(10,"utf-8")})),f.throws((function(){e.Buffer.from("string","invalid encoding")})),f.throws((function(){e.Buffer.from(-10)})),f.throws((function(){e.Buffer.from(1e90)})),f.throws((function(){e.Buffer.from(1/0)})),f.throws((function(){e.Buffer.from(-1/0)})),f.throws((function(){e.Buffer.from(NaN)})),f.throws((function(){e.Buffer.from(null)})),f.throws((function(){e.Buffer.from(void 0)})),f.throws((function(){e.Buffer.from()})),f.throws((function(){e.Buffer.from({})})),f.throws((function(){e.Buffer.alloc("")})),f.throws((function(){e.Buffer.alloc("string")})),f.throws((function(){e.Buffer.alloc("string","utf-8")})),f.throws((function(){e.Buffer.alloc("b25ldHdvdGhyZWU=","base64")})),f.throws((function(){e.Buffer.alloc(-10)})),f.throws((function(){e.Buffer.alloc(1e90)})),f.throws((function(){e.Buffer.alloc(2*(1<<30))})),f.throws((function(){e.Buffer.alloc(1/0)})),f.throws((function(){e.Buffer.alloc(-1/0)})),f.throws((function(){e.Buffer.alloc(null)})),f.throws((function(){e.Buffer.alloc(void 0)})),f.throws((function(){e.Buffer.alloc()})),f.throws((function(){e.Buffer.alloc([])})),f.throws((function(){e.Buffer.alloc([0,42,3])})),f.throws((function(){e.Buffer.alloc({})}))})),["allocUnsafe","allocUnsafeSlow"].forEach((function(e){f.throws((function(){dangerous.Buffer[e]("")})),f.throws((function(){dangerous.Buffer[e]("string")})),f.throws((function(){dangerous.Buffer[e]("string","utf-8")})),f.throws((function(){dangerous.Buffer[e](2*(1<<30))})),f.throws((function(){dangerous.Buffer[e](1/0)})),dangerous.Buffer[e]===buffer.Buffer.allocUnsafe?f.skip("Skipping, older impl of allocUnsafe coerced negative sizes to 0"):(f.throws((function(){dangerous.Buffer[e](-10)})),f.throws((function(){dangerous.Buffer[e](-1e90)})),f.throws((function(){dangerous.Buffer[e](-1/0)}))),f.throws((function(){dangerous.Buffer[e](null)})),f.throws((function(){dangerous.Buffer[e](void 0)})),f.throws((function(){dangerous.Buffer[e]()})),f.throws((function(){dangerous.Buffer[e]([])})),f.throws((function(){dangerous.Buffer[e]([0,42,3])})),f.throws((function(){dangerous.Buffer[e]({})}))})),f.end()})),test("Buffers have appropriate lengths",(function(f){[index,safer,dangerous].forEach((function(e){f.equal(e.Buffer.alloc(0).length,0),f.equal(e.Buffer.alloc(10).length,10),f.equal(e.Buffer.from("").length,0),f.equal(e.Buffer.from("string").length,6),f.equal(e.Buffer.from("string","utf-8").length,6),f.equal(e.Buffer.from("b25ldHdvdGhyZWU=","base64").length,11),f.equal(e.Buffer.from([0,42,3]).length,3),f.equal(e.Buffer.from(new Uint8Array([0,42,3])).length,3),f.equal(e.Buffer.from([]).length,0)})),["allocUnsafe","allocUnsafeSlow"].forEach((function(e){f.equal(dangerous.Buffer[e](0).length,0),f.equal(dangerous.Buffer[e](10).length,10)})),f.end()})),test("Buffers have appropriate lengths (2)",(function(f){f.equal(index.Buffer.alloc,safer.Buffer.alloc),f.equal(index.Buffer.alloc,dangerous.Buffer.alloc);var e=!0;[safer.Buffer.alloc,dangerous.Buffer.allocUnsafe,dangerous.Buffer.allocUnsafeSlow].forEach((function(f){for(var r=0;r<100;r++){var u=Math.round(1e5*Math.random()),o=f(u);buffer.Buffer.isBuffer(o)||(e=!1),o.length!==u&&(e=!1)}})),f.ok(e),f.end()})),test(".alloc(size) is zero-filled and has correct length",(function(f){f.equal(index.Buffer.alloc,safer.Buffer.alloc),f.equal(index.Buffer.alloc,dangerous.Buffer.alloc);for(var e=!0,r=0;r<100;r++){var u,o=Math.round(2e6*Math.random()),n=index.Buffer.alloc(o);for(buffer.Buffer.isBuffer(n)||(e=!1),n.length!==o&&(e=!1),u=0;u<o;u++)0!==n[u]&&(e=!1);for(n.fill(1),u=0;u<o;u++)1!==n[u]&&(e=!1)}f.ok(e),f.end()})),test(".allocUnsafe / .allocUnsafeSlow are fillable and have correct lengths",(function(f){["allocUnsafe","allocUnsafeSlow"].forEach((function(e){for(var r=!0,u=0;u<100;u++){var o,n=Math.round(2e6*Math.random()),t=dangerous.Buffer[e](n);for(buffer.Buffer.isBuffer(t)||(r=!1),t.length!==n&&(r=!1),t.fill(0,0,n),o=0;o<n;o++)0!==t[o]&&(r=!1);for(t.fill(1,0,n),o=0;o<n;o++)1!==t[o]&&(r=!1)}f.ok(r,e)})),f.end()})),test(".alloc(size, fill) is `fill`-filled",(function(f){f.equal(index.Buffer.alloc,safer.Buffer.alloc),f.equal(index.Buffer.alloc,dangerous.Buffer.alloc);for(var e=!0,r=0;r<100;r++){var u=Math.round(2e6*Math.random()),o=Math.round(255*Math.random()),n=index.Buffer.alloc(u,o);buffer.Buffer.isBuffer(n)||(e=!1),n.length!==u&&(e=!1);for(var t=0;t<u;t++)n[t]!==o&&(e=!1)}f.ok(e),f.end()})),test(".alloc(size, fill) is `fill`-filled",(function(f){f.equal(index.Buffer.alloc,safer.Buffer.alloc),f.equal(index.Buffer.alloc,dangerous.Buffer.alloc);for(var e=!0,r=0;r<100;r++){var u=Math.round(2e6*Math.random()),o=Math.round(255*Math.random()),n=index.Buffer.alloc(u,o);buffer.Buffer.isBuffer(n)||(e=!1),n.length!==u&&(e=!1);for(var t=0;t<u;t++)n[t]!==o&&(e=!1)}f.ok(e),f.deepEqual(index.Buffer.alloc(9,"a"),index.Buffer.alloc(9,97)),f.notDeepEqual(index.Buffer.alloc(9,"a"),index.Buffer.alloc(9,98));var a=new buffer.Buffer(2);a.fill("ok"),a[1]===a[0]?f.deepEqual(index.Buffer.alloc(5,"ok"),index.Buffer.from("ooooo")):f.deepEqual(index.Buffer.alloc(5,"ok"),index.Buffer.from("okoko")),f.notDeepEqual(index.Buffer.alloc(5,"ok"),index.Buffer.from("kokok")),f.end()})),test("safer.Buffer.from returns results same as Buffer constructor",(function(f){[index,safer,dangerous].forEach((function(e){f.deepEqual(e.Buffer.from(""),new buffer.Buffer("")),f.deepEqual(e.Buffer.from("string"),new buffer.Buffer("string")),f.deepEqual(e.Buffer.from("string","utf-8"),new buffer.Buffer("string","utf-8")),f.deepEqual(e.Buffer.from("b25ldHdvdGhyZWU=","base64"),new buffer.Buffer("b25ldHdvdGhyZWU=","base64")),f.deepEqual(e.Buffer.from([0,42,3]),new buffer.Buffer([0,42,3])),f.deepEqual(e.Buffer.from(new Uint8Array([0,42,3])),new buffer.Buffer(new Uint8Array([0,42,3]))),f.deepEqual(e.Buffer.from([]),new buffer.Buffer([]))})),f.end()})),test("safer.Buffer.from returns consistent results",(function(f){[index,safer,dangerous].forEach((function(e){f.deepEqual(e.Buffer.from(""),e.Buffer.alloc(0)),f.deepEqual(e.Buffer.from([]),e.Buffer.alloc(0)),f.deepEqual(e.Buffer.from(new Uint8Array([])),e.Buffer.alloc(0)),f.deepEqual(e.Buffer.from("string","utf-8"),e.Buffer.from("string")),f.deepEqual(e.Buffer.from("string"),e.Buffer.from([115,116,114,105,110,103])),f.deepEqual(e.Buffer.from("string"),e.Buffer.from(e.Buffer.from("string"))),f.deepEqual(e.Buffer.from("b25ldHdvdGhyZWU=","base64"),e.Buffer.from("onetwothree")),f.notDeepEqual(e.Buffer.from("b25ldHdvdGhyZWU="),e.Buffer.from("onetwothree"))})),f.end()}));
\ No newline at end of file
index fca2112..f0ff1a7 100644 (file)
  * Copyright(c) 2014-2016 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module dependencies.
- * @private
- */
-
-var createError = require('http-errors')
-var debug = require('debug')('send')
-var deprecate = require('depd')('send')
-var destroy = require('destroy')
-var encodeUrl = require('encodeurl')
-var escapeHtml = require('escape-html')
-var etag = require('etag')
-var fresh = require('fresh')
-var fs = require('fs')
-var mime = require('mime')
-var ms = require('ms')
-var onFinished = require('on-finished')
-var parseRange = require('range-parser')
-var path = require('path')
-var statuses = require('statuses')
-var Stream = require('stream')
-var util = require('util')
-
-/**
- * Path function references.
- * @private
- */
-
-var extname = path.extname
-var join = path.join
-var normalize = path.normalize
-var resolve = path.resolve
-var sep = path.sep
-
-/**
- * Regular expression for identifying a bytes Range header.
- * @private
- */
-
-var BYTES_RANGE_REGEXP = /^ *bytes=/
-
-/**
- * Maximum value allowed for the max age.
- * @private
- */
-
-var MAX_MAXAGE = 60 * 60 * 24 * 365 * 1000 // 1 year
-
-/**
- * Regular expression to match a path with a directory up component.
- * @private
- */
-
-var UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = send
-module.exports.mime = mime
-
-/**
- * Return a `SendStream` for `req` and `path`.
- *
- * @param {object} req
- * @param {string} path
- * @param {object} [options]
- * @return {SendStream}
- * @public
- */
-
-function send (req, path, options) {
-  return new SendStream(req, path, options)
-}
-
-/**
- * Initialize a `SendStream` with the given `path`.
- *
- * @param {Request} req
- * @param {String} path
- * @param {object} [options]
- * @private
- */
-
-function SendStream (req, path, options) {
-  Stream.call(this)
-
-  var opts = options || {}
-
-  this.options = opts
-  this.path = path
-  this.req = req
-
-  this._acceptRanges = opts.acceptRanges !== undefined
-    ? Boolean(opts.acceptRanges)
-    : true
-
-  this._cacheControl = opts.cacheControl !== undefined
-    ? Boolean(opts.cacheControl)
-    : true
-
-  this._etag = opts.etag !== undefined
-    ? Boolean(opts.etag)
-    : true
-
-  this._dotfiles = opts.dotfiles !== undefined
-    ? opts.dotfiles
-    : 'ignore'
-
-  if (this._dotfiles !== 'ignore' && this._dotfiles !== 'allow' && this._dotfiles !== 'deny') {
-    throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"')
-  }
-
-  this._hidden = Boolean(opts.hidden)
-
-  if (opts.hidden !== undefined) {
-    deprecate('hidden: use dotfiles: \'' + (this._hidden ? 'allow' : 'ignore') + '\' instead')
-  }
-
-  // legacy support
-  if (opts.dotfiles === undefined) {
-    this._dotfiles = undefined
-  }
-
-  this._extensions = opts.extensions !== undefined
-    ? normalizeList(opts.extensions, 'extensions option')
-    : []
-
-  this._immutable = opts.immutable !== undefined
-    ? Boolean(opts.immutable)
-    : false
-
-  this._index = opts.index !== undefined
-    ? normalizeList(opts.index, 'index option')
-    : ['index.html']
-
-  this._lastModified = opts.lastModified !== undefined
-    ? Boolean(opts.lastModified)
-    : true
-
-  this._maxage = opts.maxAge || opts.maxage
-  this._maxage = typeof this._maxage === 'string'
-    ? ms(this._maxage)
-    : Number(this._maxage)
-  this._maxage = !isNaN(this._maxage)
-    ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE)
-    : 0
-
-  this._root = opts.root
-    ? resolve(opts.root)
-    : null
-
-  if (!this._root && opts.from) {
-    this.from(opts.from)
-  }
-}
-
-/**
- * Inherits from `Stream`.
- */
-
-util.inherits(SendStream, Stream)
-
-/**
- * Enable or disable etag generation.
- *
- * @param {Boolean} val
- * @return {SendStream}
- * @api public
- */
-
-SendStream.prototype.etag = deprecate.function(function etag (val) {
-  this._etag = Boolean(val)
-  debug('etag %s', this._etag)
-  return this
-}, 'send.etag: pass etag as option')
-
-/**
- * Enable or disable "hidden" (dot) files.
- *
- * @param {Boolean} path
- * @return {SendStream}
- * @api public
- */
-
-SendStream.prototype.hidden = deprecate.function(function hidden (val) {
-  this._hidden = Boolean(val)
-  this._dotfiles = undefined
-  debug('hidden %s', this._hidden)
-  return this
-}, 'send.hidden: use dotfiles option')
-
-/**
- * Set index `paths`, set to a falsy
- * value to disable index support.
- *
- * @param {String|Boolean|Array} paths
- * @return {SendStream}
- * @api public
- */
-
-SendStream.prototype.index = deprecate.function(function index (paths) {
-  var index = !paths ? [] : normalizeList(paths, 'paths argument')
-  debug('index %o', paths)
-  this._index = index
-  return this
-}, 'send.index: pass index as option')
-
-/**
- * Set root `path`.
- *
- * @param {String} path
- * @return {SendStream}
- * @api public
- */
-
-SendStream.prototype.root = function root (path) {
-  this._root = resolve(String(path))
-  debug('root %s', this._root)
-  return this
-}
-
-SendStream.prototype.from = deprecate.function(SendStream.prototype.root,
-  'send.from: pass root as option')
-
-SendStream.prototype.root = deprecate.function(SendStream.prototype.root,
-  'send.root: pass root as option')
-
-/**
- * Set max-age to `maxAge`.
- *
- * @param {Number} maxAge
- * @return {SendStream}
- * @api public
- */
-
-SendStream.prototype.maxage = deprecate.function(function maxage (maxAge) {
-  this._maxage = typeof maxAge === 'string'
-    ? ms(maxAge)
-    : Number(maxAge)
-  this._maxage = !isNaN(this._maxage)
-    ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE)
-    : 0
-  debug('max-age %d', this._maxage)
-  return this
-}, 'send.maxage: pass maxAge as option')
-
-/**
- * Emit error with `status`.
- *
- * @param {number} status
- * @param {Error} [err]
- * @private
- */
-
-SendStream.prototype.error = function error (status, err) {
-  // emit if listeners instead of responding
-  if (hasListeners(this, 'error')) {
-    return this.emit('error', createError(status, err, {
-      expose: false
-    }))
-  }
-
-  var res = this.res
-  var msg = statuses[status] || String(status)
-  var doc = createHtmlDocument('Error', escapeHtml(msg))
-
-  // clear existing headers
-  clearHeaders(res)
-
-  // add error headers
-  if (err && err.headers) {
-    setHeaders(res, err.headers)
-  }
-
-  // send basic response
-  res.statusCode = status
-  res.setHeader('Content-Type', 'text/html; charset=UTF-8')
-  res.setHeader('Content-Length', Buffer.byteLength(doc))
-  res.setHeader('Content-Security-Policy', "default-src 'none'")
-  res.setHeader('X-Content-Type-Options', 'nosniff')
-  res.end(doc)
-}
-
-/**
- * Check if the pathname ends with "/".
- *
- * @return {boolean}
- * @private
- */
-
-SendStream.prototype.hasTrailingSlash = function hasTrailingSlash () {
-  return this.path[this.path.length - 1] === '/'
-}
-
-/**
- * Check if this is a conditional GET request.
- *
- * @return {Boolean}
- * @api private
- */
-
-SendStream.prototype.isConditionalGET = function isConditionalGET () {
-  return this.req.headers['if-match'] ||
-    this.req.headers['if-unmodified-since'] ||
-    this.req.headers['if-none-match'] ||
-    this.req.headers['if-modified-since']
-}
-
-/**
- * Check if the request preconditions failed.
- *
- * @return {boolean}
- * @private
- */
-
-SendStream.prototype.isPreconditionFailure = function isPreconditionFailure () {
-  var req = this.req
-  var res = this.res
-
-  // if-match
-  var match = req.headers['if-match']
-  if (match) {
-    var etag = res.getHeader('ETag')
-    return !etag || (match !== '*' && parseTokenList(match).every(function (match) {
-      return match !== etag && match !== 'W/' + etag && 'W/' + match !== etag
-    }))
-  }
-
-  // if-unmodified-since
-  var unmodifiedSince = parseHttpDate(req.headers['if-unmodified-since'])
-  if (!isNaN(unmodifiedSince)) {
-    var lastModified = parseHttpDate(res.getHeader('Last-Modified'))
-    return isNaN(lastModified) || lastModified > unmodifiedSince
-  }
-
-  return false
-}
-
-/**
- * Strip content-* header fields.
- *
- * @private
- */
-
-SendStream.prototype.removeContentHeaderFields = function removeContentHeaderFields () {
-  var res = this.res
-  var headers = getHeaderNames(res)
-
-  for (var i = 0; i < headers.length; i++) {
-    var header = headers[i]
-    if (header.substr(0, 8) === 'content-' && header !== 'content-location') {
-      res.removeHeader(header)
-    }
-  }
-}
-
-/**
- * Respond with 304 not modified.
- *
- * @api private
- */
-
-SendStream.prototype.notModified = function notModified () {
-  var res = this.res
-  debug('not modified')
-  this.removeContentHeaderFields()
-  res.statusCode = 304
-  res.end()
-}
-
-/**
- * Raise error that headers already sent.
- *
- * @api private
- */
-
-SendStream.prototype.headersAlreadySent = function headersAlreadySent () {
-  var err = new Error('Can\'t set headers after they are sent.')
-  debug('headers already sent')
-  this.error(500, err)
-}
-
-/**
- * Check if the request is cacheable, aka
- * responded with 2xx or 304 (see RFC 2616 section 14.2{5,6}).
- *
- * @return {Boolean}
- * @api private
- */
-
-SendStream.prototype.isCachable = function isCachable () {
-  var statusCode = this.res.statusCode
-  return (statusCode >= 200 && statusCode < 300) ||
-    statusCode === 304
-}
-
-/**
- * Handle stat() error.
- *
- * @param {Error} error
- * @private
- */
-
-SendStream.prototype.onStatError = function onStatError (error) {
-  switch (error.code) {
-    case 'ENAMETOOLONG':
-    case 'ENOENT':
-    case 'ENOTDIR':
-      this.error(404, error)
-      break
-    default:
-      this.error(500, error)
-      break
-  }
-}
-
-/**
- * Check if the cache is fresh.
- *
- * @return {Boolean}
- * @api private
- */
-
-SendStream.prototype.isFresh = function isFresh () {
-  return fresh(this.req.headers, {
-    'etag': this.res.getHeader('ETag'),
-    'last-modified': this.res.getHeader('Last-Modified')
-  })
-}
-
-/**
- * Check if the range is fresh.
- *
- * @return {Boolean}
- * @api private
- */
-
-SendStream.prototype.isRangeFresh = function isRangeFresh () {
-  var ifRange = this.req.headers['if-range']
-
-  if (!ifRange) {
-    return true
-  }
-
-  // if-range as etag
-  if (ifRange.indexOf('"') !== -1) {
-    var etag = this.res.getHeader('ETag')
-    return Boolean(etag && ifRange.indexOf(etag) !== -1)
-  }
-
-  // if-range as modified date
-  var lastModified = this.res.getHeader('Last-Modified')
-  return parseHttpDate(lastModified) <= parseHttpDate(ifRange)
-}
-
-/**
- * Redirect to path.
- *
- * @param {string} path
- * @private
- */
-
-SendStream.prototype.redirect = function redirect (path) {
-  var res = this.res
-
-  if (hasListeners(this, 'directory')) {
-    this.emit('directory', res, path)
-    return
-  }
-
-  if (this.hasTrailingSlash()) {
-    this.error(403)
-    return
-  }
-
-  var loc = encodeUrl(collapseLeadingSlashes(this.path + '/'))
-  var doc = createHtmlDocument('Redirecting', 'Redirecting to <a href="' + escapeHtml(loc) + '">' +
-    escapeHtml(loc) + '</a>')
-
-  // redirect
-  res.statusCode = 301
-  res.setHeader('Content-Type', 'text/html; charset=UTF-8')
-  res.setHeader('Content-Length', Buffer.byteLength(doc))
-  res.setHeader('Content-Security-Policy', "default-src 'none'")
-  res.setHeader('X-Content-Type-Options', 'nosniff')
-  res.setHeader('Location', loc)
-  res.end(doc)
-}
-
-/**
- * Pipe to `res.
- *
- * @param {Stream} res
- * @return {Stream} res
- * @api public
- */
-
-SendStream.prototype.pipe = function pipe (res) {
-  // root path
-  var root = this._root
-
-  // references
-  this.res = res
-
-  // decode the path
-  var path = decode(this.path)
-  if (path === -1) {
-    this.error(400)
-    return res
-  }
-
-  // null byte(s)
-  if (~path.indexOf('\0')) {
-    this.error(400)
-    return res
-  }
-
-  var parts
-  if (root !== null) {
-    // normalize
-    if (path) {
-      path = normalize('.' + sep + path)
-    }
-
-    // malicious path
-    if (UP_PATH_REGEXP.test(path)) {
-      debug('malicious path "%s"', path)
-      this.error(403)
-      return res
-    }
-
-    // explode path parts
-    parts = path.split(sep)
-
-    // join / normalize from optional root dir
-    path = normalize(join(root, path))
-  } else {
-    // ".." is malicious without "root"
-    if (UP_PATH_REGEXP.test(path)) {
-      debug('malicious path "%s"', path)
-      this.error(403)
-      return res
-    }
-
-    // explode path parts
-    parts = normalize(path).split(sep)
-
-    // resolve the path
-    path = resolve(path)
-  }
-
-  // dotfile handling
-  if (containsDotFile(parts)) {
-    var access = this._dotfiles
-
-    // legacy support
-    if (access === undefined) {
-      access = parts[parts.length - 1][0] === '.'
-        ? (this._hidden ? 'allow' : 'ignore')
-        : 'allow'
-    }
-
-    debug('%s dotfile "%s"', access, path)
-    switch (access) {
-      case 'allow':
-        break
-      case 'deny':
-        this.error(403)
-        return res
-      case 'ignore':
-      default:
-        this.error(404)
-        return res
-    }
-  }
-
-  // index file support
-  if (this._index.length && this.hasTrailingSlash()) {
-    this.sendIndex(path)
-    return res
-  }
-
-  this.sendFile(path)
-  return res
-}
-
-/**
- * Transfer `path`.
- *
- * @param {String} path
- * @api public
- */
-
-SendStream.prototype.send = function send (path, stat) {
-  var len = stat.size
-  var options = this.options
-  var opts = {}
-  var res = this.res
-  var req = this.req
-  var ranges = req.headers.range
-  var offset = options.start || 0
-
-  if (headersSent(res)) {
-    // impossible to send now
-    this.headersAlreadySent()
-    return
-  }
-
-  debug('pipe "%s"', path)
-
-  // set header fields
-  this.setHeader(path, stat)
-
-  // set content-type
-  this.type(path)
-
-  // conditional GET support
-  if (this.isConditionalGET()) {
-    if (this.isPreconditionFailure()) {
-      this.error(412)
-      return
-    }
-
-    if (this.isCachable() && this.isFresh()) {
-      this.notModified()
-      return
-    }
-  }
-
-  // adjust len to start/end options
-  len = Math.max(0, len - offset)
-  if (options.end !== undefined) {
-    var bytes = options.end - offset + 1
-    if (len > bytes) len = bytes
-  }
-
-  // Range support
-  if (this._acceptRanges && BYTES_RANGE_REGEXP.test(ranges)) {
-    // parse
-    ranges = parseRange(len, ranges, {
-      combine: true
-    })
-
-    // If-Range support
-    if (!this.isRangeFresh()) {
-      debug('range stale')
-      ranges = -2
-    }
-
-    // unsatisfiable
-    if (ranges === -1) {
-      debug('range unsatisfiable')
-
-      // Content-Range
-      res.setHeader('Content-Range', contentRange('bytes', len))
-
-      // 416 Requested Range Not Satisfiable
-      return this.error(416, {
-        headers: { 'Content-Range': res.getHeader('Content-Range') }
-      })
-    }
-
-    // valid (syntactically invalid/multiple ranges are treated as a regular response)
-    if (ranges !== -2 && ranges.length === 1) {
-      debug('range %j', ranges)
-
-      // Content-Range
-      res.statusCode = 206
-      res.setHeader('Content-Range', contentRange('bytes', len, ranges[0]))
-
-      // adjust for requested range
-      offset += ranges[0].start
-      len = ranges[0].end - ranges[0].start + 1
-    }
-  }
-
-  // clone options
-  for (var prop in options) {
-    opts[prop] = options[prop]
-  }
-
-  // set read options
-  opts.start = offset
-  opts.end = Math.max(offset, offset + len - 1)
-
-  // content-length
-  res.setHeader('Content-Length', len)
-
-  // HEAD support
-  if (req.method === 'HEAD') {
-    res.end()
-    return
-  }
-
-  this.stream(path, opts)
-}
-
-/**
- * Transfer file for `path`.
- *
- * @param {String} path
- * @api private
- */
-SendStream.prototype.sendFile = function sendFile (path) {
-  var i = 0
-  var self = this
-
-  debug('stat "%s"', path)
-  fs.stat(path, function onstat (err, stat) {
-    if (err && err.code === 'ENOENT' && !extname(path) && path[path.length - 1] !== sep) {
-      // not found, check extensions
-      return next(err)
-    }
-    if (err) return self.onStatError(err)
-    if (stat.isDirectory()) return self.redirect(path)
-    self.emit('file', path, stat)
-    self.send(path, stat)
-  })
-
-  function next (err) {
-    if (self._extensions.length <= i) {
-      return err
-        ? self.onStatError(err)
-        : self.error(404)
-    }
-
-    var p = path + '.' + self._extensions[i++]
-
-    debug('stat "%s"', p)
-    fs.stat(p, function (err, stat) {
-      if (err) return next(err)
-      if (stat.isDirectory()) return next()
-      self.emit('file', p, stat)
-      self.send(p, stat)
-    })
-  }
-}
-
-/**
- * Transfer index for `path`.
- *
- * @param {String} path
- * @api private
- */
-SendStream.prototype.sendIndex = function sendIndex (path) {
-  var i = -1
-  var self = this
-
-  function next (err) {
-    if (++i >= self._index.length) {
-      if (err) return self.onStatError(err)
-      return self.error(404)
-    }
-
-    var p = join(path, self._index[i])
-
-    debug('stat "%s"', p)
-    fs.stat(p, function (err, stat) {
-      if (err) return next(err)
-      if (stat.isDirectory()) return next()
-      self.emit('file', p, stat)
-      self.send(p, stat)
-    })
-  }
-
-  next()
-}
-
-/**
- * Stream `path` to the response.
- *
- * @param {String} path
- * @param {Object} options
- * @api private
- */
-
-SendStream.prototype.stream = function stream (path, options) {
-  // TODO: this is all lame, refactor meeee
-  var finished = false
-  var self = this
-  var res = this.res
-
-  // pipe
-  var stream = fs.createReadStream(path, options)
-  this.emit('stream', stream)
-  stream.pipe(res)
-
-  // response finished, done with the fd
-  onFinished(res, function onfinished () {
-    finished = true
-    destroy(stream)
-  })
-
-  // error handling code-smell
-  stream.on('error', function onerror (err) {
-    // request already finished
-    if (finished) return
-
-    // clean up stream
-    finished = true
-    destroy(stream)
-
-    // error
-    self.onStatError(err)
-  })
-
-  // end
-  stream.on('end', function onend () {
-    self.emit('end')
-  })
-}
-
-/**
- * Set content-type based on `path`
- * if it hasn't been explicitly set.
- *
- * @param {String} path
- * @api private
- */
-
-SendStream.prototype.type = function type (path) {
-  var res = this.res
-
-  if (res.getHeader('Content-Type')) return
-
-  var type = mime.lookup(path)
-
-  if (!type) {
-    debug('no content-type')
-    return
-  }
-
-  var charset = mime.charsets.lookup(type)
-
-  debug('content-type %s', type)
-  res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : ''))
-}
-
-/**
- * Set response header fields, most
- * fields may be pre-defined.
- *
- * @param {String} path
- * @param {Object} stat
- * @api private
- */
-
-SendStream.prototype.setHeader = function setHeader (path, stat) {
-  var res = this.res
-
-  this.emit('headers', res, path, stat)
-
-  if (this._acceptRanges && !res.getHeader('Accept-Ranges')) {
-    debug('accept ranges')
-    res.setHeader('Accept-Ranges', 'bytes')
-  }
-
-  if (this._cacheControl && !res.getHeader('Cache-Control')) {
-    var cacheControl = 'public, max-age=' + Math.floor(this._maxage / 1000)
-
-    if (this._immutable) {
-      cacheControl += ', immutable'
-    }
-
-    debug('cache-control %s', cacheControl)
-    res.setHeader('Cache-Control', cacheControl)
-  }
-
-  if (this._lastModified && !res.getHeader('Last-Modified')) {
-    var modified = stat.mtime.toUTCString()
-    debug('modified %s', modified)
-    res.setHeader('Last-Modified', modified)
-  }
-
-  if (this._etag && !res.getHeader('ETag')) {
-    var val = etag(stat)
-    debug('etag %s', val)
-    res.setHeader('ETag', val)
-  }
-}
-
-/**
- * Clear all headers from a response.
- *
- * @param {object} res
- * @private
- */
-
-function clearHeaders (res) {
-  var headers = getHeaderNames(res)
-
-  for (var i = 0; i < headers.length; i++) {
-    res.removeHeader(headers[i])
-  }
-}
-
-/**
- * Collapse all leading slashes into a single slash
- *
- * @param {string} str
- * @private
- */
-function collapseLeadingSlashes (str) {
-  for (var i = 0; i < str.length; i++) {
-    if (str[i] !== '/') {
-      break
-    }
-  }
-
-  return i > 1
-    ? '/' + str.substr(i)
-    : str
-}
-
-/**
- * Determine if path parts contain a dotfile.
- *
- * @api private
- */
-
-function containsDotFile (parts) {
-  for (var i = 0; i < parts.length; i++) {
-    var part = parts[i]
-    if (part.length > 1 && part[0] === '.') {
-      return true
-    }
-  }
-
-  return false
-}
-
-/**
- * Create a Content-Range header.
- *
- * @param {string} type
- * @param {number} size
- * @param {array} [range]
- */
-
-function contentRange (type, size, range) {
-  return type + ' ' + (range ? range.start + '-' + range.end : '*') + '/' + size
-}
-
-/**
- * Create a minimal HTML document.
- *
- * @param {string} title
- * @param {string} body
- * @private
- */
-
-function createHtmlDocument (title, body) {
-  return '<!DOCTYPE html>\n' +
-    '<html lang="en">\n' +
-    '<head>\n' +
-    '<meta charset="utf-8">\n' +
-    '<title>' + title + '</title>\n' +
-    '</head>\n' +
-    '<body>\n' +
-    '<pre>' + body + '</pre>\n' +
-    '</body>\n' +
-    '</html>\n'
-}
-
-/**
- * decodeURIComponent.
- *
- * Allows V8 to only deoptimize this fn instead of all
- * of send().
- *
- * @param {String} path
- * @api private
- */
-
-function decode (path) {
-  try {
-    return decodeURIComponent(path)
-  } catch (err) {
-    return -1
-  }
-}
-
-/**
- * Get the header names on a respnse.
- *
- * @param {object} res
- * @returns {array[string]}
- * @private
- */
-
-function getHeaderNames (res) {
-  return typeof res.getHeaderNames !== 'function'
-    ? Object.keys(res._headers || {})
-    : res.getHeaderNames()
-}
-
-/**
- * Determine if emitter has listeners of a given type.
- *
- * The way to do this check is done three different ways in Node.js >= 0.8
- * so this consolidates them into a minimal set using instance methods.
- *
- * @param {EventEmitter} emitter
- * @param {string} type
- * @returns {boolean}
- * @private
- */
-
-function hasListeners (emitter, type) {
-  var count = typeof emitter.listenerCount !== 'function'
-    ? emitter.listeners(type).length
-    : emitter.listenerCount(type)
-
-  return count > 0
-}
-
-/**
- * Determine if the response headers have been sent.
- *
- * @param {object} res
- * @returns {boolean}
- * @private
- */
-
-function headersSent (res) {
-  return typeof res.headersSent !== 'boolean'
-    ? Boolean(res._header)
-    : res.headersSent
-}
-
-/**
- * Normalize the index option into an array.
- *
- * @param {boolean|string|array} val
- * @param {string} name
- * @private
- */
-
-function normalizeList (val, name) {
-  var list = [].concat(val || [])
-
-  for (var i = 0; i < list.length; i++) {
-    if (typeof list[i] !== 'string') {
-      throw new TypeError(name + ' must be array of strings or false')
-    }
-  }
-
-  return list
-}
-
-/**
- * Parse an HTTP Date into a number.
- *
- * @param {string} date
- * @private
- */
-
-function parseHttpDate (date) {
-  var timestamp = date && Date.parse(date)
-
-  return typeof timestamp === 'number'
-    ? timestamp
-    : NaN
-}
-
-/**
- * Parse a HTTP token list.
- *
- * @param {string} str
- * @private
- */
-
-function parseTokenList (str) {
-  var end = 0
-  var list = []
-  var start = 0
-
-  // gather tokens
-  for (var i = 0, len = str.length; i < len; i++) {
-    switch (str.charCodeAt(i)) {
-      case 0x20: /*   */
-        if (start === end) {
-          start = end = i + 1
-        }
-        break
-      case 0x2c: /* , */
-        list.push(str.substring(start, end))
-        start = end = i + 1
-        break
-      default:
-        end = i + 1
-        break
-    }
-  }
-
-  // final token
-  list.push(str.substring(start, end))
-
-  return list
-}
-
-/**
- * Set an object of headers on a response.
- *
- * @param {object} res
- * @param {object} headers
- * @private
- */
-
-function setHeaders (res, headers) {
-  var keys = Object.keys(headers)
-
-  for (var i = 0; i < keys.length; i++) {
-    var key = keys[i]
-    res.setHeader(key, headers[key])
-  }
-}
+"use strict";var createError=require("http-errors"),debug=require("debug")("send"),deprecate=require("depd")("send"),destroy=require("destroy"),encodeUrl=require("encodeurl"),escapeHtml=require("escape-html"),etag=require("etag"),fresh=require("fresh"),fs=require("fs"),mime=require("mime"),ms=require("ms"),onFinished=require("on-finished"),parseRange=require("range-parser"),path=require("path"),statuses=require("statuses"),Stream=require("stream"),util=require("util"),extname=path.extname,join=path.join,normalize=path.normalize,resolve=path.resolve,sep=path.sep,BYTES_RANGE_REGEXP=/^ *bytes=/,MAX_MAXAGE=31536e6,UP_PATH_REGEXP=/(?:^|[\\/])\.\.(?:[\\/]|$)/;function send(e,t,r){return new SendStream(e,t,r)}function SendStream(e,t,r){Stream.call(this);var n=r||{};if(this.options=n,this.path=t,this.req=e,this._acceptRanges=void 0===n.acceptRanges||Boolean(n.acceptRanges),this._cacheControl=void 0===n.cacheControl||Boolean(n.cacheControl),this._etag=void 0===n.etag||Boolean(n.etag),this._dotfiles=void 0!==n.dotfiles?n.dotfiles:"ignore","ignore"!==this._dotfiles&&"allow"!==this._dotfiles&&"deny"!==this._dotfiles)throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"');this._hidden=Boolean(n.hidden),void 0!==n.hidden&&deprecate("hidden: use dotfiles: '"+(this._hidden?"allow":"ignore")+"' instead"),void 0===n.dotfiles&&(this._dotfiles=void 0),this._extensions=void 0!==n.extensions?normalizeList(n.extensions,"extensions option"):[],this._immutable=void 0!==n.immutable&&Boolean(n.immutable),this._index=void 0!==n.index?normalizeList(n.index,"index option"):["index.html"],this._lastModified=void 0===n.lastModified||Boolean(n.lastModified),this._maxage=n.maxAge||n.maxage,this._maxage="string"==typeof this._maxage?ms(this._maxage):Number(this._maxage),this._maxage=isNaN(this._maxage)?0:Math.min(Math.max(0,this._maxage),MAX_MAXAGE),this._root=n.root?resolve(n.root):null,!this._root&&n.from&&this.from(n.from)}function clearHeaders(e){for(var t=getHeaderNames(e),r=0;r<t.length;r++)e.removeHeader(t[r])}function collapseLeadingSlashes(e){for(var t=0;t<e.length&&"/"===e[t];t++);return t>1?"/"+e.substr(t):e}function containsDotFile(e){for(var t=0;t<e.length;t++){var r=e[t];if(r.length>1&&"."===r[0])return!0}return!1}function contentRange(e,t,r){return e+" "+(r?r.start+"-"+r.end:"*")+"/"+t}function createHtmlDocument(e,t){return'<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<title>'+e+"</title>\n</head>\n<body>\n<pre>"+t+"</pre>\n</body>\n</html>\n"}function decode(e){try{return decodeURIComponent(e)}catch(e){return-1}}function getHeaderNames(e){return"function"!=typeof e.getHeaderNames?Object.keys(e._headers||{}):e.getHeaderNames()}function hasListeners(e,t){return("function"!=typeof e.listenerCount?e.listeners(t).length:e.listenerCount(t))>0}function headersSent(e){return"boolean"!=typeof e.headersSent?Boolean(e._header):e.headersSent}function normalizeList(e,t){for(var r=[].concat(e||[]),n=0;n<r.length;n++)if("string"!=typeof r[n])throw new TypeError(t+" must be array of strings or false");return r}function parseHttpDate(e){var t=e&&Date.parse(e);return"number"==typeof t?t:NaN}function parseTokenList(e){for(var t=0,r=[],n=0,i=0,s=e.length;i<s;i++)switch(e.charCodeAt(i)){case 32:n===t&&(n=t=i+1);break;case 44:r.push(e.substring(n,t)),n=t=i+1;break;default:t=i+1}return r.push(e.substring(n,t)),r}function setHeaders(e,t){for(var r=Object.keys(t),n=0;n<r.length;n++){var i=r[n];e.setHeader(i,t[i])}}module.exports=send,module.exports.mime=mime,util.inherits(SendStream,Stream),SendStream.prototype.etag=deprecate.function((function(e){return this._etag=Boolean(e),debug("etag %s",this._etag),this}),"send.etag: pass etag as option"),SendStream.prototype.hidden=deprecate.function((function(e){return this._hidden=Boolean(e),this._dotfiles=void 0,debug("hidden %s",this._hidden),this}),"send.hidden: use dotfiles option"),SendStream.prototype.index=deprecate.function((function(e){var t=e?normalizeList(e,"paths argument"):[];return debug("index %o",e),this._index=t,this}),"send.index: pass index as option"),SendStream.prototype.root=function(e){return this._root=resolve(String(e)),debug("root %s",this._root),this},SendStream.prototype.from=deprecate.function(SendStream.prototype.root,"send.from: pass root as option"),SendStream.prototype.root=deprecate.function(SendStream.prototype.root,"send.root: pass root as option"),SendStream.prototype.maxage=deprecate.function((function(e){return this._maxage="string"==typeof e?ms(e):Number(e),this._maxage=isNaN(this._maxage)?0:Math.min(Math.max(0,this._maxage),MAX_MAXAGE),debug("max-age %d",this._maxage),this}),"send.maxage: pass maxAge as option"),SendStream.prototype.error=function(e,t){if(hasListeners(this,"error"))return this.emit("error",createError(e,t,{expose:!1}));var r=this.res,n=statuses[e]||String(e),i=createHtmlDocument("Error",escapeHtml(n));clearHeaders(r),t&&t.headers&&setHeaders(r,t.headers),r.statusCode=e,r.setHeader("Content-Type","text/html; charset=UTF-8"),r.setHeader("Content-Length",Buffer.byteLength(i)),r.setHeader("Content-Security-Policy","default-src 'none'"),r.setHeader("X-Content-Type-Options","nosniff"),r.end(i)},SendStream.prototype.hasTrailingSlash=function(){return"/"===this.path[this.path.length-1]},SendStream.prototype.isConditionalGET=function(){return this.req.headers["if-match"]||this.req.headers["if-unmodified-since"]||this.req.headers["if-none-match"]||this.req.headers["if-modified-since"]},SendStream.prototype.isPreconditionFailure=function(){var e=this.req,t=this.res,r=e.headers["if-match"];if(r){var n=t.getHeader("ETag");return!n||"*"!==r&&parseTokenList(r).every((function(e){return e!==n&&e!=="W/"+n&&"W/"+e!==n}))}var i=parseHttpDate(e.headers["if-unmodified-since"]);if(!isNaN(i)){var s=parseHttpDate(t.getHeader("Last-Modified"));return isNaN(s)||s>i}return!1},SendStream.prototype.removeContentHeaderFields=function(){for(var e=this.res,t=getHeaderNames(e),r=0;r<t.length;r++){var n=t[r];"content-"===n.substr(0,8)&&"content-location"!==n&&e.removeHeader(n)}},SendStream.prototype.notModified=function(){var e=this.res;debug("not modified"),this.removeContentHeaderFields(),e.statusCode=304,e.end()},SendStream.prototype.headersAlreadySent=function(){var e=new Error("Can't set headers after they are sent.");debug("headers already sent"),this.error(500,e)},SendStream.prototype.isCachable=function(){var e=this.res.statusCode;return e>=200&&e<300||304===e},SendStream.prototype.onStatError=function(e){switch(e.code){case"ENAMETOOLONG":case"ENOENT":case"ENOTDIR":this.error(404,e);break;default:this.error(500,e)}},SendStream.prototype.isFresh=function(){return fresh(this.req.headers,{etag:this.res.getHeader("ETag"),"last-modified":this.res.getHeader("Last-Modified")})},SendStream.prototype.isRangeFresh=function(){var e=this.req.headers["if-range"];if(!e)return!0;if(-1!==e.indexOf('"')){var t=this.res.getHeader("ETag");return Boolean(t&&-1!==e.indexOf(t))}return parseHttpDate(this.res.getHeader("Last-Modified"))<=parseHttpDate(e)},SendStream.prototype.redirect=function(e){var t=this.res;if(hasListeners(this,"directory"))this.emit("directory",t,e);else if(this.hasTrailingSlash())this.error(403);else{var r=encodeUrl(collapseLeadingSlashes(this.path+"/")),n=createHtmlDocument("Redirecting",'Redirecting to <a href="'+escapeHtml(r)+'">'+escapeHtml(r)+"</a>");t.statusCode=301,t.setHeader("Content-Type","text/html; charset=UTF-8"),t.setHeader("Content-Length",Buffer.byteLength(n)),t.setHeader("Content-Security-Policy","default-src 'none'"),t.setHeader("X-Content-Type-Options","nosniff"),t.setHeader("Location",r),t.end(n)}},SendStream.prototype.pipe=function(e){var t=this._root;this.res=e;var r,n=decode(this.path);if(-1===n)return this.error(400),e;if(~n.indexOf("\0"))return this.error(400),e;if(null!==t){if(n&&(n=normalize("."+sep+n)),UP_PATH_REGEXP.test(n))return debug('malicious path "%s"',n),this.error(403),e;r=n.split(sep),n=normalize(join(t,n))}else{if(UP_PATH_REGEXP.test(n))return debug('malicious path "%s"',n),this.error(403),e;r=normalize(n).split(sep),n=resolve(n)}if(containsDotFile(r)){var i=this._dotfiles;switch(void 0===i&&(i="."===r[r.length-1][0]?this._hidden?"allow":"ignore":"allow"),debug('%s dotfile "%s"',i,n),i){case"allow":break;case"deny":return this.error(403),e;case"ignore":default:return this.error(404),e}}return this._index.length&&this.hasTrailingSlash()?(this.sendIndex(n),e):(this.sendFile(n),e)},SendStream.prototype.send=function(e,t){var r=t.size,n=this.options,i={},s=this.res,a=this.req,o=a.headers.range,d=n.start||0;if(headersSent(s))this.headersAlreadySent();else{if(debug('pipe "%s"',e),this.setHeader(e,t),this.type(e),this.isConditionalGET()){if(this.isPreconditionFailure())return void this.error(412);if(this.isCachable()&&this.isFresh())return void this.notModified()}if(r=Math.max(0,r-d),void 0!==n.end){var h=n.end-d+1;r>h&&(r=h)}if(this._acceptRanges&&BYTES_RANGE_REGEXP.test(o)){if(o=parseRange(r,o,{combine:!0}),this.isRangeFresh()||(debug("range stale"),o=-2),-1===o)return debug("range unsatisfiable"),s.setHeader("Content-Range",contentRange("bytes",r)),this.error(416,{headers:{"Content-Range":s.getHeader("Content-Range")}});-2!==o&&1===o.length&&(debug("range %j",o),s.statusCode=206,s.setHeader("Content-Range",contentRange("bytes",r,o[0])),d+=o[0].start,r=o[0].end-o[0].start+1)}for(var u in n)i[u]=n[u];i.start=d,i.end=Math.max(d,d+r-1),s.setHeader("Content-Length",r),"HEAD"!==a.method?this.stream(e,i):s.end()}},SendStream.prototype.sendFile=function(e){var t=0,r=this;function n(i){if(r._extensions.length<=t)return i?r.onStatError(i):r.error(404);var s=e+"."+r._extensions[t++];debug('stat "%s"',s),fs.stat(s,(function(e,t){return e?n(e):t.isDirectory()?n():(r.emit("file",s,t),void r.send(s,t))}))}debug('stat "%s"',e),fs.stat(e,(function(t,i){return t&&"ENOENT"===t.code&&!extname(e)&&e[e.length-1]!==sep?n(t):t?r.onStatError(t):i.isDirectory()?r.redirect(e):(r.emit("file",e,i),void r.send(e,i))}))},SendStream.prototype.sendIndex=function(e){var t=-1,r=this;!function n(i){if(++t>=r._index.length)return i?r.onStatError(i):r.error(404);var s=join(e,r._index[t]);debug('stat "%s"',s),fs.stat(s,(function(e,t){return e?n(e):t.isDirectory()?n():(r.emit("file",s,t),void r.send(s,t))}))}()},SendStream.prototype.stream=function(e,t){var r=!1,n=this,i=this.res,s=fs.createReadStream(e,t);this.emit("stream",s),s.pipe(i),onFinished(i,(function(){r=!0,destroy(s)})),s.on("error",(function(e){r||(r=!0,destroy(s),n.onStatError(e))})),s.on("end",(function(){n.emit("end")}))},SendStream.prototype.type=function(e){var t=this.res;if(!t.getHeader("Content-Type")){var r=mime.lookup(e);if(r){var n=mime.charsets.lookup(r);debug("content-type %s",r),t.setHeader("Content-Type",r+(n?"; charset="+n:""))}else debug("no content-type")}},SendStream.prototype.setHeader=function(e,t){var r=this.res;if(this.emit("headers",r,e,t),this._acceptRanges&&!r.getHeader("Accept-Ranges")&&(debug("accept ranges"),r.setHeader("Accept-Ranges","bytes")),this._cacheControl&&!r.getHeader("Cache-Control")){var n="public, max-age="+Math.floor(this._maxage/1e3);this._immutable&&(n+=", immutable"),debug("cache-control %s",n),r.setHeader("Cache-Control",n)}if(this._lastModified&&!r.getHeader("Last-Modified")){var i=t.mtime.toUTCString();debug("modified %s",i),r.setHeader("Last-Modified",i)}if(this._etag&&!r.getHeader("ETag")){var s=etag(t);debug("etag %s",s),r.setHeader("ETag",s)}};
\ No newline at end of file
index b7d3984..213041d 100644 (file)
@@ -5,206 +5,4 @@
  * Copyright(c) 2014-2016 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module dependencies.
- * @private
- */
-
-var encodeUrl = require('encodeurl')
-var escapeHtml = require('escape-html')
-var parseUrl = require('parseurl')
-var resolve = require('path').resolve
-var send = require('send')
-var url = require('url')
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = serveStatic
-module.exports.mime = send.mime
-
-/**
- * @param {string} root
- * @param {object} [options]
- * @return {function}
- * @public
- */
-
-function serveStatic (root, options) {
-  if (!root) {
-    throw new TypeError('root path required')
-  }
-
-  if (typeof root !== 'string') {
-    throw new TypeError('root path must be a string')
-  }
-
-  // copy options object
-  var opts = Object.create(options || null)
-
-  // fall-though
-  var fallthrough = opts.fallthrough !== false
-
-  // default redirect
-  var redirect = opts.redirect !== false
-
-  // headers listener
-  var setHeaders = opts.setHeaders
-
-  if (setHeaders && typeof setHeaders !== 'function') {
-    throw new TypeError('option setHeaders must be function')
-  }
-
-  // setup options for send
-  opts.maxage = opts.maxage || opts.maxAge || 0
-  opts.root = resolve(root)
-
-  // construct directory listener
-  var onDirectory = redirect
-    ? createRedirectDirectoryListener()
-    : createNotFoundDirectoryListener()
-
-  return function serveStatic (req, res, next) {
-    if (req.method !== 'GET' && req.method !== 'HEAD') {
-      if (fallthrough) {
-        return next()
-      }
-
-      // method not allowed
-      res.statusCode = 405
-      res.setHeader('Allow', 'GET, HEAD')
-      res.setHeader('Content-Length', '0')
-      res.end()
-      return
-    }
-
-    var forwardError = !fallthrough
-    var originalUrl = parseUrl.original(req)
-    var path = parseUrl(req).pathname
-
-    // make sure redirect occurs at mount
-    if (path === '/' && originalUrl.pathname.substr(-1) !== '/') {
-      path = ''
-    }
-
-    // create send stream
-    var stream = send(req, path, opts)
-
-    // add directory handler
-    stream.on('directory', onDirectory)
-
-    // add headers listener
-    if (setHeaders) {
-      stream.on('headers', setHeaders)
-    }
-
-    // add file listener for fallthrough
-    if (fallthrough) {
-      stream.on('file', function onFile () {
-        // once file is determined, always forward error
-        forwardError = true
-      })
-    }
-
-    // forward errors
-    stream.on('error', function error (err) {
-      if (forwardError || !(err.statusCode < 500)) {
-        next(err)
-        return
-      }
-
-      next()
-    })
-
-    // pipe
-    stream.pipe(res)
-  }
-}
-
-/**
- * Collapse all leading slashes into a single slash
- * @private
- */
-function collapseLeadingSlashes (str) {
-  for (var i = 0; i < str.length; i++) {
-    if (str.charCodeAt(i) !== 0x2f /* / */) {
-      break
-    }
-  }
-
-  return i > 1
-    ? '/' + str.substr(i)
-    : str
-}
-
-/**
- * Create a minimal HTML document.
- *
- * @param {string} title
- * @param {string} body
- * @private
- */
-
-function createHtmlDocument (title, body) {
-  return '<!DOCTYPE html>\n' +
-    '<html lang="en">\n' +
-    '<head>\n' +
-    '<meta charset="utf-8">\n' +
-    '<title>' + title + '</title>\n' +
-    '</head>\n' +
-    '<body>\n' +
-    '<pre>' + body + '</pre>\n' +
-    '</body>\n' +
-    '</html>\n'
-}
-
-/**
- * Create a directory listener that just 404s.
- * @private
- */
-
-function createNotFoundDirectoryListener () {
-  return function notFound () {
-    this.error(404)
-  }
-}
-
-/**
- * Create a directory listener that performs a redirect.
- * @private
- */
-
-function createRedirectDirectoryListener () {
-  return function redirect (res) {
-    if (this.hasTrailingSlash()) {
-      this.error(404)
-      return
-    }
-
-    // get original URL
-    var originalUrl = parseUrl.original(this.req)
-
-    // append trailing slash
-    originalUrl.path = null
-    originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + '/')
-
-    // reformat the URL
-    var loc = encodeUrl(url.format(originalUrl))
-    var doc = createHtmlDocument('Redirecting', 'Redirecting to <a href="' + escapeHtml(loc) + '">' +
-      escapeHtml(loc) + '</a>')
-
-    // send redirect response
-    res.statusCode = 301
-    res.setHeader('Content-Type', 'text/html; charset=UTF-8')
-    res.setHeader('Content-Length', Buffer.byteLength(doc))
-    res.setHeader('Content-Security-Policy', "default-src 'none'")
-    res.setHeader('X-Content-Type-Options', 'nosniff')
-    res.setHeader('Location', loc)
-    res.end(doc)
-  }
-}
+"use strict";var encodeUrl=require("encodeurl"),escapeHtml=require("escape-html"),parseUrl=require("parseurl"),resolve=require("path").resolve,send=require("send"),url=require("url");function serveStatic(e,r){if(!e)throw new TypeError("root path required");if("string"!=typeof e)throw new TypeError("root path must be a string");var t=Object.create(r||null),n=!1!==t.fallthrough,o=!1!==t.redirect,a=t.setHeaders;if(a&&"function"!=typeof a)throw new TypeError("option setHeaders must be function");t.maxage=t.maxage||t.maxAge||0,t.root=resolve(e);var i=o?createRedirectDirectoryListener():createNotFoundDirectoryListener();return function(e,r,o){if("GET"!==e.method&&"HEAD"!==e.method)return n?o():(r.statusCode=405,r.setHeader("Allow","GET, HEAD"),r.setHeader("Content-Length","0"),void r.end());var s=!n,l=parseUrl.original(e),c=parseUrl(e).pathname;"/"===c&&"/"!==l.pathname.substr(-1)&&(c="");var u=send(e,c,t);u.on("directory",i),a&&u.on("headers",a),n&&u.on("file",(function(){s=!0})),u.on("error",(function(e){!s&&e.statusCode<500?o():o(e)})),u.pipe(r)}}function collapseLeadingSlashes(e){for(var r=0;r<e.length&&47===e.charCodeAt(r);r++);return r>1?"/"+e.substr(r):e}function createHtmlDocument(e,r){return'<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<title>'+e+"</title>\n</head>\n<body>\n<pre>"+r+"</pre>\n</body>\n</html>\n"}function createNotFoundDirectoryListener(){return function(){this.error(404)}}function createRedirectDirectoryListener(){return function(e){if(this.hasTrailingSlash())this.error(404);else{var r=parseUrl.original(this.req);r.path=null,r.pathname=collapseLeadingSlashes(r.pathname+"/");var t=encodeUrl(url.format(r)),n=createHtmlDocument("Redirecting",'Redirecting to <a href="'+escapeHtml(t)+'">'+escapeHtml(t)+"</a>");e.statusCode=301,e.setHeader("Content-Type","text/html; charset=UTF-8"),e.setHeader("Content-Length",Buffer.byteLength(n)),e.setHeader("Content-Security-Policy","default-src 'none'"),e.setHeader("X-Content-Type-Options","nosniff"),e.setHeader("Location",t),e.end(n)}}}module.exports=serveStatic,module.exports.mime=send.mime;
\ No newline at end of file
index 6f78774..416a4b9 100644 (file)
@@ -1,7 +1 @@
-module.exports = function (blocking) {
-  [process.stdout, process.stderr].forEach(function (stream) {
-    if (stream._handle && stream.isTTY && typeof stream._handle.setBlocking === 'function') {
-      stream._handle.setBlocking(blocking)
-    }
-  })
-}
+module.exports=function(o){[process.stdout,process.stderr].forEach((function(e){e._handle&&e.isTTY&&"function"==typeof e._handle.setBlocking&&e._handle.setBlocking(o)}))};
\ No newline at end of file
index 81fd5d7..15ac76e 100644 (file)
@@ -1,17 +1 @@
-'use strict'
-/* eslint no-proto: 0 */
-module.exports = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties)
-
-function setProtoOf (obj, proto) {
-  obj.__proto__ = proto
-  return obj
-}
-
-function mixinProperties (obj, proto) {
-  for (var prop in proto) {
-    if (!obj.hasOwnProperty(prop)) {
-      obj[prop] = proto[prop]
-    }
-  }
-  return obj
-}
+"use strict";function setProtoOf(r,t){return r.__proto__=t,r}function mixinProperties(r,t){for(var o in t)r.hasOwnProperty(o)||(r[o]=t[o]);return r}module.exports=Object.setPrototypeOf||({__proto__:[]}instanceof Array?setProtoOf:mixinProperties);
\ No newline at end of file
index afeb4dd..f4a9476 100644 (file)
@@ -1,24 +1 @@
-'use strict'
-/* eslint-env mocha */
-/* eslint no-proto: 0 */
-var assert = require('assert')
-var setPrototypeOf = require('..')
-
-describe('setProtoOf(obj, proto)', function () {
-  it('should merge objects', function () {
-    var obj = { a: 1, b: 2 }
-    var proto = { b: 3, c: 4 }
-    var mergeObj = setPrototypeOf(obj, proto)
-
-    if (Object.getPrototypeOf) {
-      assert.strictEqual(Object.getPrototypeOf(obj), proto)
-    } else if ({ __proto__: [] } instanceof Array) {
-      assert.strictEqual(obj.__proto__, proto)
-    } else {
-      assert.strictEqual(obj.a, 1)
-      assert.strictEqual(obj.b, 2)
-      assert.strictEqual(obj.c, 4)
-    }
-    assert.strictEqual(mergeObj, obj)
-  })
-})
+"use strict";var assert=require("assert"),setPrototypeOf=require("..");describe("setProtoOf(obj, proto)",(function(){it("should merge objects",(function(){var t={a:1,b:2},r={b:3,c:4},s=setPrototypeOf(t,r);Object.getPrototypeOf?assert.strictEqual(Object.getPrototypeOf(t),r):{__proto__:[]}instanceof Array?assert.strictEqual(t.__proto__,r):(assert.strictEqual(t.a,1),assert.strictEqual(t.b,2),assert.strictEqual(t.c,4)),assert.strictEqual(s,t)}))}));
\ No newline at end of file
index f21dcbd..ec8320f 100644 (file)
@@ -1,263 +1 @@
-
-/**
- * Module dependencies.
- */
-
-var Emitter = require('events').EventEmitter;
-
-/**
- * Module exports.
- */
-
-module.exports = Adapter;
-
-/**
- * Memory adapter constructor.
- *
- * @param {Namespace} nsp
- * @api public
- */
-
-function Adapter(nsp){
-  this.nsp = nsp;
-  this.rooms = {};
-  this.sids = {};
-  this.encoder = nsp.server.encoder;
-}
-
-/**
- * Inherits from `EventEmitter`.
- */
-
-Adapter.prototype.__proto__ = Emitter.prototype;
-
-/**
- * Adds a socket to a room.
- *
- * @param {String} socket id
- * @param {String} room name
- * @param {Function} callback
- * @api public
- */
-
-Adapter.prototype.add = function(id, room, fn){
-  return this.addAll(id, [ room ], fn);
-};
-
-/**
- * Adds a socket to a list of room.
- *
- * @param {String} socket id
- * @param {String} rooms
- * @param {Function} callback
- * @api public
- */
-
-Adapter.prototype.addAll = function(id, rooms, fn){
-  for (var i = 0; i < rooms.length; i++) {
-    var room = rooms[i];
-    this.sids[id] = this.sids[id] || {};
-    this.sids[id][room] = true;
-    this.rooms[room] = this.rooms[room] || Room();
-    this.rooms[room].add(id);
-  }
-  if (fn) process.nextTick(fn.bind(null, null));
-};
-
-/**
- * Removes a socket from a room.
- *
- * @param {String} socket id
- * @param {String} room name
- * @param {Function} callback
- * @api public
- */
-
-Adapter.prototype.del = function(id, room, fn){
-  if (this.sids[id]) delete this.sids[id][room];
-
-  if (this.rooms.hasOwnProperty(room)) {
-    this.rooms[room].del(id);
-    if (this.rooms[room].length === 0) delete this.rooms[room];
-  }
-
-  if (fn) process.nextTick(fn.bind(null, null));
-};
-
-/**
- * Removes a socket from all rooms it's joined.
- *
- * @param {String} socket id
- * @param {Function} callback
- * @api public
- */
-
-Adapter.prototype.delAll = function(id, fn){
-  var rooms = this.sids[id];
-  if (rooms) {
-    for (var room in rooms) {
-      if (this.rooms.hasOwnProperty(room)) {
-        this.rooms[room].del(id);
-        if (this.rooms[room].length === 0) delete this.rooms[room];
-      }
-    }
-  }
-  delete this.sids[id];
-
-  if (fn) process.nextTick(fn.bind(null, null));
-};
-
-/**
- * Broadcasts a packet.
- *
- * Options:
- *  - `flags` {Object} flags for this packet
- *  - `except` {Array} sids that should be excluded
- *  - `rooms` {Array} list of rooms to broadcast to
- *
- * @param {Object} packet object
- * @api public
- */
-
-Adapter.prototype.broadcast = function(packet, opts){
-  var rooms = opts.rooms || [];
-  var except = opts.except || [];
-  var flags = opts.flags || {};
-  var packetOpts = {
-    preEncoded: true,
-    volatile: flags.volatile,
-    compress: flags.compress
-  };
-  var ids = {};
-  var self = this;
-  var socket;
-
-  packet.nsp = this.nsp.name;
-  this.encoder.encode(packet, function(encodedPackets) {
-    if (rooms.length) {
-      for (var i = 0; i < rooms.length; i++) {
-        var room = self.rooms[rooms[i]];
-        if (!room) continue;
-        var sockets = room.sockets;
-        for (var id in sockets) {
-          if (sockets.hasOwnProperty(id)) {
-            if (ids[id] || ~except.indexOf(id)) continue;
-            socket = self.nsp.connected[id];
-            if (socket) {
-              socket.packet(encodedPackets, packetOpts);
-              ids[id] = true;
-            }
-          }
-        }
-      }
-    } else {
-      for (var id in self.sids) {
-        if (self.sids.hasOwnProperty(id)) {
-          if (~except.indexOf(id)) continue;
-          socket = self.nsp.connected[id];
-          if (socket) socket.packet(encodedPackets, packetOpts);
-        }
-      }
-    }
-  });
-};
-
-/**
- * Gets a list of clients by sid.
- *
- * @param {Array} explicit set of rooms to check.
- * @param {Function} callback
- * @api public
- */
-
-Adapter.prototype.clients = function(rooms, fn){
-  if ('function' == typeof rooms){
-    fn = rooms;
-    rooms = null;
-  }
-
-  rooms = rooms || [];
-
-  var ids = {};
-  var sids = [];
-  var socket;
-
-  if (rooms.length) {
-    for (var i = 0; i < rooms.length; i++) {
-      var room = this.rooms[rooms[i]];
-      if (!room) continue;
-      var sockets = room.sockets;
-      for (var id in sockets) {
-        if (sockets.hasOwnProperty(id)) {
-          if (ids[id]) continue;
-          socket = this.nsp.connected[id];
-          if (socket) {
-            sids.push(id);
-            ids[id] = true;
-          }
-        }
-      }
-    }
-  } else {
-    for (var id in this.sids) {
-      if (this.sids.hasOwnProperty(id)) {
-        socket = this.nsp.connected[id];
-        if (socket) sids.push(id);
-      }
-    }
-  }
-
-  if (fn) process.nextTick(fn.bind(null, null, sids));
-};
-
-/**
- * Gets the list of rooms a given client has joined.
- *
- * @param {String} socket id
- * @param {Function} callback
- * @api public
- */
-Adapter.prototype.clientRooms = function(id, fn){
-  var rooms = this.sids[id];
-  if (fn) process.nextTick(fn.bind(null, null, rooms ? Object.keys(rooms) : null));
-};
-
-/**
-* Room constructor.
-*
-* @api private
-*/
-
-function Room(){
-  if (!(this instanceof Room)) return new Room();
-  this.sockets = {};
-  this.length = 0;
-}
-
-/**
- * Adds a socket to a room.
- *
- * @param {String} socket id
- * @api private
- */
-
-Room.prototype.add = function(id){
-  if (!this.sockets.hasOwnProperty(id)) {
-    this.sockets[id] = true;
-    this.length++;
-  }
-};
-
-/**
- * Removes a socket from a room.
- *
- * @param {String} socket id
- * @api private
- */
-
-Room.prototype.del = function(id){
-  if (this.sockets.hasOwnProperty(id)) {
-    delete this.sockets[id];
-    this.length--;
-  }
-};
+var Emitter=require("events").EventEmitter;function Adapter(t){this.nsp=t,this.rooms={},this.sids={},this.encoder=t.server.encoder}function Room(){if(!(this instanceof Room))return new Room;this.sockets={},this.length=0}module.exports=Adapter,Adapter.prototype.__proto__=Emitter.prototype,Adapter.prototype.add=function(t,s,e){return this.addAll(t,[s],e)},Adapter.prototype.addAll=function(t,s,e){for(var o=0;o<s.length;o++){var n=s[o];this.sids[t]=this.sids[t]||{},this.sids[t][n]=!0,this.rooms[n]=this.rooms[n]||Room(),this.rooms[n].add(t)}e&&process.nextTick(e.bind(null,null))},Adapter.prototype.del=function(t,s,e){this.sids[t]&&delete this.sids[t][s],this.rooms.hasOwnProperty(s)&&(this.rooms[s].del(t),0===this.rooms[s].length&&delete this.rooms[s]),e&&process.nextTick(e.bind(null,null))},Adapter.prototype.delAll=function(t,s){var e=this.sids[t];if(e)for(var o in e)this.rooms.hasOwnProperty(o)&&(this.rooms[o].del(t),0===this.rooms[o].length&&delete this.rooms[o]);delete this.sids[t],s&&process.nextTick(s.bind(null,null))},Adapter.prototype.broadcast=function(t,s){var e,o=s.rooms||[],n=s.except||[],i=s.flags||{},r={preEncoded:!0,volatile:i.volatile,compress:i.compress},p={},d=this;t.nsp=this.nsp.name,this.encoder.encode(t,(function(t){if(o.length)for(var s=0;s<o.length;s++){var i=d.rooms[o[s]];if(i){var h=i.sockets;for(var l in h)if(h.hasOwnProperty(l)){if(p[l]||~n.indexOf(l))continue;(e=d.nsp.connected[l])&&(e.packet(t,r),p[l]=!0)}}}else for(var l in d.sids)if(d.sids.hasOwnProperty(l)){if(~n.indexOf(l))continue;(e=d.nsp.connected[l])&&e.packet(t,r)}}))},Adapter.prototype.clients=function(t,s){"function"==typeof t&&(s=t,t=null);var e={},o=[];if((t=t||[]).length)for(var n=0;n<t.length;n++){var i=this.rooms[t[n]];if(i){var r=i.sockets;for(var p in r)if(r.hasOwnProperty(p)){if(e[p])continue;this.nsp.connected[p]&&(o.push(p),e[p]=!0)}}}else for(var p in this.sids)this.sids.hasOwnProperty(p)&&this.nsp.connected[p]&&o.push(p);s&&process.nextTick(s.bind(null,null,o))},Adapter.prototype.clientRooms=function(t,s){var e=this.sids[t];s&&process.nextTick(s.bind(null,null,e?Object.keys(e):null))},Room.prototype.add=function(t){this.sockets.hasOwnProperty(t)||(this.sockets[t]=!0,this.length++)},Room.prototype.del=function(t){this.sockets.hasOwnProperty(t)&&(delete this.sockets[t],this.length--)};
\ No newline at end of file
index 3e2347d..32649b3 100644 (file)
@@ -1,141 +1 @@
-/*global Blob,File*/
-
-/**
- * Module requirements
- */
-
-var isArray = require('isarray');
-var isBuf = require('./is-buffer');
-var toString = Object.prototype.toString;
-var withNativeBlob = typeof Blob === 'function' || (typeof Blob !== 'undefined' && toString.call(Blob) === '[object BlobConstructor]');
-var withNativeFile = typeof File === 'function' || (typeof File !== 'undefined' && toString.call(File) === '[object FileConstructor]');
-
-/**
- * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
- * Anything with blobs or files should be fed through removeBlobs before coming
- * here.
- *
- * @param {Object} packet - socket.io event packet
- * @return {Object} with deconstructed packet and list of buffers
- * @api public
- */
-
-exports.deconstructPacket = function(packet) {
-  var buffers = [];
-  var packetData = packet.data;
-  var pack = packet;
-  pack.data = _deconstructPacket(packetData, buffers);
-  pack.attachments = buffers.length; // number of binary 'attachments'
-  return {packet: pack, buffers: buffers};
-};
-
-function _deconstructPacket(data, buffers) {
-  if (!data) return data;
-
-  if (isBuf(data)) {
-    var placeholder = { _placeholder: true, num: buffers.length };
-    buffers.push(data);
-    return placeholder;
-  } else if (isArray(data)) {
-    var newData = new Array(data.length);
-    for (var i = 0; i < data.length; i++) {
-      newData[i] = _deconstructPacket(data[i], buffers);
-    }
-    return newData;
-  } else if (typeof data === 'object' && !(data instanceof Date)) {
-    var newData = {};
-    for (var key in data) {
-      newData[key] = _deconstructPacket(data[key], buffers);
-    }
-    return newData;
-  }
-  return data;
-}
-
-/**
- * Reconstructs a binary packet from its placeholder packet and buffers
- *
- * @param {Object} packet - event packet with placeholders
- * @param {Array} buffers - binary buffers to put in placeholder positions
- * @return {Object} reconstructed packet
- * @api public
- */
-
-exports.reconstructPacket = function(packet, buffers) {
-  packet.data = _reconstructPacket(packet.data, buffers);
-  packet.attachments = undefined; // no longer useful
-  return packet;
-};
-
-function _reconstructPacket(data, buffers) {
-  if (!data) return data;
-
-  if (data && data._placeholder) {
-    return buffers[data.num]; // appropriate buffer (should be natural order anyway)
-  } else if (isArray(data)) {
-    for (var i = 0; i < data.length; i++) {
-      data[i] = _reconstructPacket(data[i], buffers);
-    }
-  } else if (typeof data === 'object') {
-    for (var key in data) {
-      data[key] = _reconstructPacket(data[key], buffers);
-    }
-  }
-
-  return data;
-}
-
-/**
- * Asynchronously removes Blobs or Files from data via
- * FileReader's readAsArrayBuffer method. Used before encoding
- * data as msgpack. Calls callback with the blobless data.
- *
- * @param {Object} data
- * @param {Function} callback
- * @api private
- */
-
-exports.removeBlobs = function(data, callback) {
-  function _removeBlobs(obj, curKey, containingObject) {
-    if (!obj) return obj;
-
-    // convert any blob
-    if ((withNativeBlob && obj instanceof Blob) ||
-        (withNativeFile && obj instanceof File)) {
-      pendingBlobs++;
-
-      // async filereader
-      var fileReader = new FileReader();
-      fileReader.onload = function() { // this.result == arraybuffer
-        if (containingObject) {
-          containingObject[curKey] = this.result;
-        }
-        else {
-          bloblessData = this.result;
-        }
-
-        // if nothing pending its callback time
-        if(! --pendingBlobs) {
-          callback(bloblessData);
-        }
-      };
-
-      fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
-    } else if (isArray(obj)) { // handle array
-      for (var i = 0; i < obj.length; i++) {
-        _removeBlobs(obj[i], i, obj);
-      }
-    } else if (typeof obj === 'object' && !isBuf(obj)) { // and object
-      for (var key in obj) {
-        _removeBlobs(obj[key], key, obj);
-      }
-    }
-  }
-
-  var pendingBlobs = 0;
-  var bloblessData = data;
-  _removeBlobs(bloblessData);
-  if (!pendingBlobs) {
-    callback(bloblessData);
-  }
-};
+var isArray=require("isarray"),isBuf=require("./is-buffer"),toString=Object.prototype.toString,withNativeBlob="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===toString.call(Blob),withNativeFile="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===toString.call(File);function _deconstructPacket(t,e){if(!t)return t;if(isBuf(t)){var r={_placeholder:!0,num:e.length};return e.push(t),r}if(isArray(t)){for(var n=new Array(t.length),o=0;o<t.length;o++)n[o]=_deconstructPacket(t[o],e);return n}if("object"==typeof t&&!(t instanceof Date)){n={};for(var i in t)n[i]=_deconstructPacket(t[i],e);return n}return t}function _reconstructPacket(t,e){if(!t)return t;if(t&&t._placeholder)return e[t.num];if(isArray(t))for(var r=0;r<t.length;r++)t[r]=_reconstructPacket(t[r],e);else if("object"==typeof t)for(var n in t)t[n]=_reconstructPacket(t[n],e);return t}exports.deconstructPacket=function(t){var e=[],r=t.data,n=t;return n.data=_deconstructPacket(r,e),n.attachments=e.length,{packet:n,buffers:e}},exports.reconstructPacket=function(t,e){return t.data=_reconstructPacket(t.data,e),t.attachments=void 0,t},exports.removeBlobs=function(t,e){var r=0,n=t;!function t(o,i,a){if(!o)return o;if(withNativeBlob&&o instanceof Blob||withNativeFile&&o instanceof File){r++;var c=new FileReader;c.onload=function(){a?a[i]=this.result:n=this.result,--r||e(n)},c.readAsArrayBuffer(o)}else if(isArray(o))for(var f=0;f<o.length;f++)t(o[f],f,o);else if("object"==typeof o&&!isBuf(o))for(var u in o)t(o[u],u,o)}(n),r||e(n)};
\ No newline at end of file
index ff613cc..6e33d26 100644 (file)
@@ -1,412 +1 @@
-
-/**
- * Module dependencies.
- */
-
-var debug = require('debug')('socket.io-parser');
-var Emitter = require('component-emitter');
-var binary = require('./binary');
-var isArray = require('isarray');
-var isBuf = require('./is-buffer');
-
-/**
- * Protocol version.
- *
- * @api public
- */
-
-exports.protocol = 4;
-
-/**
- * Packet types.
- *
- * @api public
- */
-
-exports.types = [
-  'CONNECT',
-  'DISCONNECT',
-  'EVENT',
-  'ACK',
-  'ERROR',
-  'BINARY_EVENT',
-  'BINARY_ACK'
-];
-
-/**
- * Packet type `connect`.
- *
- * @api public
- */
-
-exports.CONNECT = 0;
-
-/**
- * Packet type `disconnect`.
- *
- * @api public
- */
-
-exports.DISCONNECT = 1;
-
-/**
- * Packet type `event`.
- *
- * @api public
- */
-
-exports.EVENT = 2;
-
-/**
- * Packet type `ack`.
- *
- * @api public
- */
-
-exports.ACK = 3;
-
-/**
- * Packet type `error`.
- *
- * @api public
- */
-
-exports.ERROR = 4;
-
-/**
- * Packet type 'binary event'
- *
- * @api public
- */
-
-exports.BINARY_EVENT = 5;
-
-/**
- * Packet type `binary ack`. For acks with binary arguments.
- *
- * @api public
- */
-
-exports.BINARY_ACK = 6;
-
-/**
- * Encoder constructor.
- *
- * @api public
- */
-
-exports.Encoder = Encoder;
-
-/**
- * Decoder constructor.
- *
- * @api public
- */
-
-exports.Decoder = Decoder;
-
-/**
- * A socket.io Encoder instance
- *
- * @api public
- */
-
-function Encoder() {}
-
-var ERROR_PACKET = exports.ERROR + '"encode error"';
-
-/**
- * Encode a packet as a single string if non-binary, or as a
- * buffer sequence, depending on packet type.
- *
- * @param {Object} obj - packet object
- * @param {Function} callback - function to handle encodings (likely engine.write)
- * @return Calls callback with Array of encodings
- * @api public
- */
-
-Encoder.prototype.encode = function(obj, callback){
-  debug('encoding packet %j', obj);
-
-  if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) {
-    encodeAsBinary(obj, callback);
-  } else {
-    var encoding = encodeAsString(obj);
-    callback([encoding]);
-  }
-};
-
-/**
- * Encode packet as string.
- *
- * @param {Object} packet
- * @return {String} encoded
- * @api private
- */
-
-function encodeAsString(obj) {
-
-  // first is type
-  var str = '' + obj.type;
-
-  // attachments if we have them
-  if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) {
-    str += obj.attachments + '-';
-  }
-
-  // if we have a namespace other than `/`
-  // we append it followed by a comma `,`
-  if (obj.nsp && '/' !== obj.nsp) {
-    str += obj.nsp + ',';
-  }
-
-  // immediately followed by the id
-  if (null != obj.id) {
-    str += obj.id;
-  }
-
-  // json data
-  if (null != obj.data) {
-    var payload = tryStringify(obj.data);
-    if (payload !== false) {
-      str += payload;
-    } else {
-      return ERROR_PACKET;
-    }
-  }
-
-  debug('encoded %j as %s', obj, str);
-  return str;
-}
-
-function tryStringify(str) {
-  try {
-    return JSON.stringify(str);
-  } catch(e){
-    return false;
-  }
-}
-
-/**
- * Encode packet as 'buffer sequence' by removing blobs, and
- * deconstructing packet into object with placeholders and
- * a list of buffers.
- *
- * @param {Object} packet
- * @return {Buffer} encoded
- * @api private
- */
-
-function encodeAsBinary(obj, callback) {
-
-  function writeEncoding(bloblessData) {
-    var deconstruction = binary.deconstructPacket(bloblessData);
-    var pack = encodeAsString(deconstruction.packet);
-    var buffers = deconstruction.buffers;
-
-    buffers.unshift(pack); // add packet info to beginning of data list
-    callback(buffers); // write all the buffers
-  }
-
-  binary.removeBlobs(obj, writeEncoding);
-}
-
-/**
- * A socket.io Decoder instance
- *
- * @return {Object} decoder
- * @api public
- */
-
-function Decoder() {
-  this.reconstructor = null;
-}
-
-/**
- * Mix in `Emitter` with Decoder.
- */
-
-Emitter(Decoder.prototype);
-
-/**
- * Decodes an encoded packet string into packet JSON.
- *
- * @param {String} obj - encoded packet
- * @return {Object} packet
- * @api public
- */
-
-Decoder.prototype.add = function(obj) {
-  var packet;
-  if (typeof obj === 'string') {
-    packet = decodeString(obj);
-    if (exports.BINARY_EVENT === packet.type || exports.BINARY_ACK === packet.type) { // binary packet's json
-      this.reconstructor = new BinaryReconstructor(packet);
-
-      // no attachments, labeled binary but no binary data to follow
-      if (this.reconstructor.reconPack.attachments === 0) {
-        this.emit('decoded', packet);
-      }
-    } else { // non-binary full packet
-      this.emit('decoded', packet);
-    }
-  } else if (isBuf(obj) || obj.base64) { // raw binary data
-    if (!this.reconstructor) {
-      throw new Error('got binary data when not reconstructing a packet');
-    } else {
-      packet = this.reconstructor.takeBinaryData(obj);
-      if (packet) { // received final buffer
-        this.reconstructor = null;
-        this.emit('decoded', packet);
-      }
-    }
-  } else {
-    throw new Error('Unknown type: ' + obj);
-  }
-};
-
-/**
- * Decode a packet String (JSON data)
- *
- * @param {String} str
- * @return {Object} packet
- * @api private
- */
-
-function decodeString(str) {
-  var i = 0;
-  // look up type
-  var p = {
-    type: Number(str.charAt(0))
-  };
-
-  if (null == exports.types[p.type]) {
-    return error('unknown packet type ' + p.type);
-  }
-
-  // look up attachments if type binary
-  if (exports.BINARY_EVENT === p.type || exports.BINARY_ACK === p.type) {
-    var start = i + 1;
-    while (str.charAt(++i) !== '-' && i != str.length) {}
-    var buf = str.substring(start, i);
-    if (buf != Number(buf) || str.charAt(i) !== '-') {
-      throw new Error('Illegal attachments');
-    }
-    p.attachments = Number(buf);
-  }
-
-  // look up namespace (if any)
-  if ('/' === str.charAt(i + 1)) {
-    var start = i + 1;
-    while (++i) {
-      var c = str.charAt(i);
-      if (',' === c) break;
-      if (i === str.length) break;
-    }
-    p.nsp = str.substring(start, i);
-  } else {
-    p.nsp = '/';
-  }
-
-  // look up id
-  var next = str.charAt(i + 1);
-  if ('' !== next && Number(next) == next) {
-    var start = i + 1;
-    while (++i) {
-      var c = str.charAt(i);
-      if (null == c || Number(c) != c) {
-        --i;
-        break;
-      }
-      if (i === str.length) break;
-    }
-    p.id = Number(str.substring(start, i + 1));
-  }
-
-  // look up json data
-  if (str.charAt(++i)) {
-    var payload = tryParse(str.substr(i));
-    var isPayloadValid = payload !== false && (p.type === exports.ERROR || isArray(payload));
-    if (isPayloadValid) {
-      p.data = payload;
-    } else {
-      return error('invalid payload');
-    }
-  }
-
-  debug('decoded %s as %j', str, p);
-  return p;
-}
-
-function tryParse(str) {
-  try {
-    return JSON.parse(str);
-  } catch(e){
-    return false;
-  }
-}
-
-/**
- * Deallocates a parser's resources
- *
- * @api public
- */
-
-Decoder.prototype.destroy = function() {
-  if (this.reconstructor) {
-    this.reconstructor.finishedReconstruction();
-  }
-};
-
-/**
- * A manager of a binary event's 'buffer sequence'. Should
- * be constructed whenever a packet of type BINARY_EVENT is
- * decoded.
- *
- * @param {Object} packet
- * @return {BinaryReconstructor} initialized reconstructor
- * @api private
- */
-
-function BinaryReconstructor(packet) {
-  this.reconPack = packet;
-  this.buffers = [];
-}
-
-/**
- * Method to be called when binary data received from connection
- * after a BINARY_EVENT packet.
- *
- * @param {Buffer | ArrayBuffer} binData - the raw binary data received
- * @return {null | Object} returns null if more binary data is expected or
- *   a reconstructed packet object if all buffers have been received.
- * @api private
- */
-
-BinaryReconstructor.prototype.takeBinaryData = function(binData) {
-  this.buffers.push(binData);
-  if (this.buffers.length === this.reconPack.attachments) { // done with buffer list
-    var packet = binary.reconstructPacket(this.reconPack, this.buffers);
-    this.finishedReconstruction();
-    return packet;
-  }
-  return null;
-};
-
-/**
- * Cleans up binary packet reconstruction variables.
- *
- * @api private
- */
-
-BinaryReconstructor.prototype.finishedReconstruction = function() {
-  this.reconPack = null;
-  this.buffers = [];
-};
-
-function error(msg) {
-  return {
-    type: exports.ERROR,
-    data: 'parser error: ' + msg
-  };
-}
+var debug=require("debug")("socket.io-parser"),Emitter=require("component-emitter"),binary=require("./binary"),isArray=require("isarray"),isBuf=require("./is-buffer");function Encoder(){}exports.protocol=4,exports.types=["CONNECT","DISCONNECT","EVENT","ACK","ERROR","BINARY_EVENT","BINARY_ACK"],exports.CONNECT=0,exports.DISCONNECT=1,exports.EVENT=2,exports.ACK=3,exports.ERROR=4,exports.BINARY_EVENT=5,exports.BINARY_ACK=6,exports.Encoder=Encoder,exports.Decoder=Decoder;var ERROR_PACKET=exports.ERROR+'"encode error"';function encodeAsString(r){var t=""+r.type;if(exports.BINARY_EVENT!==r.type&&exports.BINARY_ACK!==r.type||(t+=r.attachments+"-"),r.nsp&&"/"!==r.nsp&&(t+=r.nsp+","),null!=r.id&&(t+=r.id),null!=r.data){var e=tryStringify(r.data);if(!1===e)return ERROR_PACKET;t+=e}return debug("encoded %j as %s",r,t),t}function tryStringify(r){try{return JSON.stringify(r)}catch(r){return!1}}function encodeAsBinary(r,t){binary.removeBlobs(r,(function(r){var e=binary.deconstructPacket(r),n=encodeAsString(e.packet),o=e.buffers;o.unshift(n),t(o)}))}function Decoder(){this.reconstructor=null}function decodeString(r){var t=0,e={type:Number(r.charAt(0))};if(null==exports.types[e.type])return error("unknown packet type "+e.type);if(exports.BINARY_EVENT===e.type||exports.BINARY_ACK===e.type){for(var n=t+1;"-"!==r.charAt(++t)&&t!=r.length;);var o=r.substring(n,t);if(o!=Number(o)||"-"!==r.charAt(t))throw new Error("Illegal attachments");e.attachments=Number(o)}if("/"===r.charAt(t+1)){for(n=t+1;++t;){if(","===(i=r.charAt(t)))break;if(t===r.length)break}e.nsp=r.substring(n,t)}else e.nsp="/";var s=r.charAt(t+1);if(""!==s&&Number(s)==s){for(n=t+1;++t;){var i;if(null==(i=r.charAt(t))||Number(i)!=i){--t;break}if(t===r.length)break}e.id=Number(r.substring(n,t+1))}if(r.charAt(++t)){var c=tryParse(r.substr(t));if(!(!1!==c&&(e.type===exports.ERROR||isArray(c))))return error("invalid payload");e.data=c}return debug("decoded %s as %j",r,e),e}function tryParse(r){try{return JSON.parse(r)}catch(r){return!1}}function BinaryReconstructor(r){this.reconPack=r,this.buffers=[]}function error(r){return{type:exports.ERROR,data:"parser error: "+r}}Encoder.prototype.encode=function(r,t){(debug("encoding packet %j",r),exports.BINARY_EVENT===r.type||exports.BINARY_ACK===r.type)?encodeAsBinary(r,t):t([encodeAsString(r)])},Emitter(Decoder.prototype),Decoder.prototype.add=function(r){var t;if("string"==typeof r)t=decodeString(r),exports.BINARY_EVENT===t.type||exports.BINARY_ACK===t.type?(this.reconstructor=new BinaryReconstructor(t),0===this.reconstructor.reconPack.attachments&&this.emit("decoded",t)):this.emit("decoded",t);else{if(!isBuf(r)&&!r.base64)throw new Error("Unknown type: "+r);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");(t=this.reconstructor.takeBinaryData(r))&&(this.reconstructor=null,this.emit("decoded",t))}},Decoder.prototype.destroy=function(){this.reconstructor&&this.reconstructor.finishedReconstruction()},BinaryReconstructor.prototype.takeBinaryData=function(r){if(this.buffers.push(r),this.buffers.length===this.reconPack.attachments){var t=binary.reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null},BinaryReconstructor.prototype.finishedReconstruction=function(){this.reconPack=null,this.buffers=[]};
\ No newline at end of file
index c833865..64090b6 100644 (file)
@@ -1,20 +1 @@
-
-module.exports = isBuf;
-
-var withNativeBuffer = typeof Buffer === 'function' && typeof Buffer.isBuffer === 'function';
-var withNativeArrayBuffer = typeof ArrayBuffer === 'function';
-
-var isView = function (obj) {
-  return typeof ArrayBuffer.isView === 'function' ? ArrayBuffer.isView(obj) : (obj.buffer instanceof ArrayBuffer);
-};
-
-/**
- * Returns true if obj is a buffer or an arraybuffer.
- *
- * @api private
- */
-
-function isBuf(obj) {
-  return (withNativeBuffer && Buffer.isBuffer(obj)) ||
-          (withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj)));
-}
+module.exports=isBuf;var withNativeBuffer="function"==typeof Buffer&&"function"==typeof Buffer.isBuffer,withNativeArrayBuffer="function"==typeof ArrayBuffer,isView=function(f){return"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(f):f.buffer instanceof ArrayBuffer};function isBuf(f){return withNativeBuffer&&Buffer.isBuffer(f)||withNativeArrayBuffer&&(f instanceof ArrayBuffer||isView(f))}
\ No newline at end of file
index 32d179f..7990ff6 100644 (file)
@@ -1,273 +1 @@
-
-/**
- * Module dependencies.
- */
-
-var parser = require('socket.io-parser');
-var debug = require('debug')('socket.io:client');
-var url = require('url');
-
-/**
- * Module exports.
- */
-
-module.exports = Client;
-
-/**
- * Client constructor.
- *
- * @param {Server} server instance
- * @param {Socket} conn
- * @api private
- */
-
-function Client(server, conn){
-  this.server = server;
-  this.conn = conn;
-  this.encoder = server.encoder;
-  this.decoder = new server.parser.Decoder();
-  this.id = conn.id;
-  this.request = conn.request;
-  this.setup();
-  this.sockets = {};
-  this.nsps = {};
-  this.connectBuffer = [];
-}
-
-/**
- * Sets up event listeners.
- *
- * @api private
- */
-
-Client.prototype.setup = function(){
-  this.onclose = this.onclose.bind(this);
-  this.ondata = this.ondata.bind(this);
-  this.onerror = this.onerror.bind(this);
-  this.ondecoded = this.ondecoded.bind(this);
-
-  this.decoder.on('decoded', this.ondecoded);
-  this.conn.on('data', this.ondata);
-  this.conn.on('error', this.onerror);
-  this.conn.on('close', this.onclose);
-};
-
-/**
- * Connects a client to a namespace.
- *
- * @param {String} name namespace
- * @param {Object} query the query parameters
- * @api private
- */
-
-Client.prototype.connect = function(name, query){
-  if (this.server.nsps[name]) {
-    debug('connecting to namespace %s', name);
-    return this.doConnect(name, query);
-  }
-
-  this.server.checkNamespace(name, query, (dynamicNsp) => {
-    if (dynamicNsp) {
-      debug('dynamic namespace %s was created', dynamicNsp.name);
-      this.doConnect(name, query);
-    } else {
-      debug('creation of namespace %s was denied', name);
-      this.packet({ type: parser.ERROR, nsp: name, data: 'Invalid namespace' });
-    }
-  });
-};
-
-/**
- * Connects a client to a namespace.
- *
- * @param {String} name namespace
- * @param {String} query the query parameters
- * @api private
- */
-
-Client.prototype.doConnect = function(name, query){
-  var nsp = this.server.of(name);
-
-  if ('/' != name && !this.nsps['/']) {
-    this.connectBuffer.push(name);
-    return;
-  }
-
-  var self = this;
-  var socket = nsp.add(this, query, function(){
-    self.sockets[socket.id] = socket;
-    self.nsps[nsp.name] = socket;
-
-    if ('/' == nsp.name && self.connectBuffer.length > 0) {
-      self.connectBuffer.forEach(self.connect, self);
-      self.connectBuffer = [];
-    }
-  });
-};
-
-/**
- * Disconnects from all namespaces and closes transport.
- *
- * @api private
- */
-
-Client.prototype.disconnect = function(){
-  for (var id in this.sockets) {
-    if (this.sockets.hasOwnProperty(id)) {
-      this.sockets[id].disconnect();
-    }
-  }
-  this.sockets = {};
-  this.close();
-};
-
-/**
- * Removes a socket. Called by each `Socket`.
- *
- * @api private
- */
-
-Client.prototype.remove = function(socket){
-  if (this.sockets.hasOwnProperty(socket.id)) {
-    var nsp = this.sockets[socket.id].nsp.name;
-    delete this.sockets[socket.id];
-    delete this.nsps[nsp];
-  } else {
-    debug('ignoring remove for %s', socket.id);
-  }
-};
-
-/**
- * Closes the underlying connection.
- *
- * @api private
- */
-
-Client.prototype.close = function(){
-  if ('open' == this.conn.readyState) {
-    debug('forcing transport close');
-    this.conn.close();
-    this.onclose('forced server close');
-  }
-};
-
-/**
- * Writes a packet to the transport.
- *
- * @param {Object} packet object
- * @param {Object} opts
- * @api private
- */
-
-Client.prototype.packet = function(packet, opts){
-  opts = opts || {};
-  var self = this;
-
-  // this writes to the actual connection
-  function writeToEngine(encodedPackets) {
-    if (opts.volatile && !self.conn.transport.writable) return;
-    for (var i = 0; i < encodedPackets.length; i++) {
-      self.conn.write(encodedPackets[i], { compress: opts.compress });
-    }
-  }
-
-  if ('open' == this.conn.readyState) {
-    debug('writing packet %j', packet);
-    if (!opts.preEncoded) { // not broadcasting, need to encode
-      this.encoder.encode(packet, writeToEngine); // encode, then write results to engine
-    } else { // a broadcast pre-encodes a packet
-      writeToEngine(packet);
-    }
-  } else {
-    debug('ignoring packet write %j', packet);
-  }
-};
-
-/**
- * Called with incoming transport data.
- *
- * @api private
- */
-
-Client.prototype.ondata = function(data){
-  // try/catch is needed for protocol violations (GH-1880)
-  try {
-    this.decoder.add(data);
-  } catch(e) {
-    this.onerror(e);
-  }
-};
-
-/**
- * Called when parser fully decodes a packet.
- *
- * @api private
- */
-
-Client.prototype.ondecoded = function(packet) {
-  if (parser.CONNECT == packet.type) {
-    this.connect(url.parse(packet.nsp).pathname, url.parse(packet.nsp, true).query);
-  } else {
-    var socket = this.nsps[packet.nsp];
-    if (socket) {
-      process.nextTick(function() {
-        socket.onpacket(packet);
-      });
-    } else {
-      debug('no socket for namespace %s', packet.nsp);
-    }
-  }
-};
-
-/**
- * Handles an error.
- *
- * @param {Object} err object
- * @api private
- */
-
-Client.prototype.onerror = function(err){
-  for (var id in this.sockets) {
-    if (this.sockets.hasOwnProperty(id)) {
-      this.sockets[id].onerror(err);
-    }
-  }
-  this.conn.close();
-};
-
-/**
- * Called upon transport close.
- *
- * @param {String} reason
- * @api private
- */
-
-Client.prototype.onclose = function(reason){
-  debug('client close with reason %s', reason);
-
-  // ignore a potential subsequent `close` event
-  this.destroy();
-
-  // `nsps` and `sockets` are cleaned up seamlessly
-  for (var id in this.sockets) {
-    if (this.sockets.hasOwnProperty(id)) {
-      this.sockets[id].onclose(reason);
-    }
-  }
-  this.sockets = {};
-
-  this.decoder.destroy(); // clean up decoder
-};
-
-/**
- * Cleans up event listeners.
- *
- * @api private
- */
-
-Client.prototype.destroy = function(){
-  this.conn.removeListener('data', this.ondata);
-  this.conn.removeListener('error', this.onerror);
-  this.conn.removeListener('close', this.onclose);
-  this.decoder.removeListener('decoded', this.ondecoded);
-};
+var parser=require("socket.io-parser"),debug=require("debug")("socket.io:client"),url=require("url");function Client(e,t){this.server=e,this.conn=t,this.encoder=e.encoder,this.decoder=new e.parser.Decoder,this.id=t.id,this.request=t.request,this.setup(),this.sockets={},this.nsps={},this.connectBuffer=[]}module.exports=Client,Client.prototype.setup=function(){this.onclose=this.onclose.bind(this),this.ondata=this.ondata.bind(this),this.onerror=this.onerror.bind(this),this.ondecoded=this.ondecoded.bind(this),this.decoder.on("decoded",this.ondecoded),this.conn.on("data",this.ondata),this.conn.on("error",this.onerror),this.conn.on("close",this.onclose)},Client.prototype.connect=function(e,t){if(this.server.nsps[e])return debug("connecting to namespace %s",e),this.doConnect(e,t);this.server.checkNamespace(e,t,(o=>{o?(debug("dynamic namespace %s was created",o.name),this.doConnect(e,t)):(debug("creation of namespace %s was denied",e),this.packet({type:parser.ERROR,nsp:e,data:"Invalid namespace"}))}))},Client.prototype.doConnect=function(e,t){var o=this.server.of(e);if("/"==e||this.nsps["/"])var s=this,n=o.add(this,t,(function(){s.sockets[n.id]=n,s.nsps[o.name]=n,"/"==o.name&&s.connectBuffer.length>0&&(s.connectBuffer.forEach(s.connect,s),s.connectBuffer=[])}));else this.connectBuffer.push(e)},Client.prototype.disconnect=function(){for(var e in this.sockets)this.sockets.hasOwnProperty(e)&&this.sockets[e].disconnect();this.sockets={},this.close()},Client.prototype.remove=function(e){if(this.sockets.hasOwnProperty(e.id)){var t=this.sockets[e.id].nsp.name;delete this.sockets[e.id],delete this.nsps[t]}else debug("ignoring remove for %s",e.id)},Client.prototype.close=function(){"open"==this.conn.readyState&&(debug("forcing transport close"),this.conn.close(),this.onclose("forced server close"))},Client.prototype.packet=function(e,t){t=t||{};var o=this;function s(e){if(!t.volatile||o.conn.transport.writable)for(var s=0;s<e.length;s++)o.conn.write(e[s],{compress:t.compress})}"open"==this.conn.readyState?(debug("writing packet %j",e),t.preEncoded?s(e):this.encoder.encode(e,s)):debug("ignoring packet write %j",e)},Client.prototype.ondata=function(e){try{this.decoder.add(e)}catch(e){this.onerror(e)}},Client.prototype.ondecoded=function(e){if(parser.CONNECT==e.type)this.connect(url.parse(e.nsp).pathname,url.parse(e.nsp,!0).query);else{var t=this.nsps[e.nsp];t?process.nextTick((function(){t.onpacket(e)})):debug("no socket for namespace %s",e.nsp)}},Client.prototype.onerror=function(e){for(var t in this.sockets)this.sockets.hasOwnProperty(t)&&this.sockets[t].onerror(e);this.conn.close()},Client.prototype.onclose=function(e){for(var t in debug("client close with reason %s",e),this.destroy(),this.sockets)this.sockets.hasOwnProperty(t)&&this.sockets[t].onclose(e);this.sockets={},this.decoder.destroy()},Client.prototype.destroy=function(){this.conn.removeListener("data",this.ondata),this.conn.removeListener("error",this.onerror),this.conn.removeListener("close",this.onclose),this.decoder.removeListener("decoded",this.ondecoded)};
\ No newline at end of file
index 5287e4e..a432754 100644 (file)
@@ -1,523 +1 @@
-'use strict';
-
-/**
- * Module dependencies.
- */
-
-var http = require('http');
-var read = require('fs').readFileSync;
-var path = require('path');
-var exists = require('fs').existsSync;
-var engine = require('engine.io');
-var clientVersion = require('socket.io-client/package.json').version;
-var Client = require('./client');
-var Emitter = require('events').EventEmitter;
-var Namespace = require('./namespace');
-var ParentNamespace = require('./parent-namespace');
-var Adapter = require('socket.io-adapter');
-var parser = require('socket.io-parser');
-var debug = require('debug')('socket.io:server');
-var url = require('url');
-
-/**
- * Module exports.
- */
-
-module.exports = Server;
-
-/**
- * Socket.IO client source.
- */
-
-var clientSource = undefined;
-var clientSourceMap = undefined;
-
-/**
- * Server constructor.
- *
- * @param {http.Server|Number|Object} srv http server, port or options
- * @param {Object} [opts]
- * @api public
- */
-
-function Server(srv, opts){
-  if (!(this instanceof Server)) return new Server(srv, opts);
-  if ('object' == typeof srv && srv instanceof Object && !srv.listen) {
-    opts = srv;
-    srv = null;
-  }
-  opts = opts || {};
-  this.nsps = {};
-  this.parentNsps = new Map();
-  this.path(opts.path || '/socket.io');
-  this.serveClient(false !== opts.serveClient);
-  this.parser = opts.parser || parser;
-  this.encoder = new this.parser.Encoder();
-  this.adapter(opts.adapter || Adapter);
-  this.origins(opts.origins || '*:*');
-  this.sockets = this.of('/');
-  if (srv) this.attach(srv, opts);
-}
-
-/**
- * Server request verification function, that checks for allowed origins
- *
- * @param {http.IncomingMessage} req request
- * @param {Function} fn callback to be called with the result: `fn(err, success)`
- */
-
-Server.prototype.checkRequest = function(req, fn) {
-  var origin = req.headers.origin || req.headers.referer;
-
-  // file:// URLs produce a null Origin which can't be authorized via echo-back
-  if ('null' == origin || null == origin) origin = '*';
-
-  if (!!origin && typeof(this._origins) == 'function') return this._origins(origin, fn);
-  if (this._origins.indexOf('*:*') !== -1) return fn(null, true);
-  if (origin) {
-    try {
-      var parts = url.parse(origin);
-      var defaultPort = 'https:' == parts.protocol ? 443 : 80;
-      parts.port = parts.port != null
-        ? parts.port
-        : defaultPort;
-      var ok =
-        ~this._origins.indexOf(parts.protocol + '//' + parts.hostname + ':' + parts.port) ||
-        ~this._origins.indexOf(parts.hostname + ':' + parts.port) ||
-        ~this._origins.indexOf(parts.hostname + ':*') ||
-        ~this._origins.indexOf('*:' + parts.port);
-      debug('origin %s is %svalid', origin, !!ok ? '' : 'not ');
-      return fn(null, !!ok);
-    } catch (ex) {
-    }
-  }
-  fn(null, false);
-};
-
-/**
- * Sets/gets whether client code is being served.
- *
- * @param {Boolean} v whether to serve client code
- * @return {Server|Boolean} self when setting or value when getting
- * @api public
- */
-
-Server.prototype.serveClient = function(v){
-  if (!arguments.length) return this._serveClient;
-  this._serveClient = v;
-  var resolvePath = function(file){
-    var filepath = path.resolve(__dirname, './../../', file);
-    if (exists(filepath)) {
-      return filepath;
-    }
-    return require.resolve(file);
-  };
-  if (v && !clientSource) {
-    clientSource = read(resolvePath( 'socket.io-client/dist/socket.io.js'), 'utf-8');
-    try {
-      clientSourceMap = read(resolvePath( 'socket.io-client/dist/socket.io.js.map'), 'utf-8');
-    } catch(err) {
-      debug('could not load sourcemap file');
-    }
-  }
-  return this;
-};
-
-/**
- * Old settings for backwards compatibility
- */
-
-var oldSettings = {
-  "transports": "transports",
-  "heartbeat timeout": "pingTimeout",
-  "heartbeat interval": "pingInterval",
-  "destroy buffer size": "maxHttpBufferSize"
-};
-
-/**
- * Backwards compatibility.
- *
- * @api public
- */
-
-Server.prototype.set = function(key, val){
-  if ('authorization' == key && val) {
-    this.use(function(socket, next) {
-      val(socket.request, function(err, authorized) {
-        if (err) return next(new Error(err));
-        if (!authorized) return next(new Error('Not authorized'));
-        next();
-      });
-    });
-  } else if ('origins' == key && val) {
-    this.origins(val);
-  } else if ('resource' == key) {
-    this.path(val);
-  } else if (oldSettings[key] && this.eio[oldSettings[key]]) {
-    this.eio[oldSettings[key]] = val;
-  } else {
-    console.error('Option %s is not valid. Please refer to the README.', key);
-  }
-
-  return this;
-};
-
-/**
- * Executes the middleware for an incoming namespace not already created on the server.
- *
- * @param {String} name name of incoming namespace
- * @param {Object} query the query parameters
- * @param {Function} fn callback
- * @api private
- */
-
-Server.prototype.checkNamespace = function(name, query, fn){
-  if (this.parentNsps.size === 0) return fn(false);
-
-  const keysIterator = this.parentNsps.keys();
-
-  const run = () => {
-    let nextFn = keysIterator.next();
-    if (nextFn.done) {
-      return fn(false);
-    }
-    nextFn.value(name, query, (err, allow) => {
-      if (err || !allow) {
-        run();
-      } else {
-        fn(this.parentNsps.get(nextFn.value).createChild(name));
-      }
-    });
-  };
-
-  run();
-};
-
-/**
- * Sets the client serving path.
- *
- * @param {String} v pathname
- * @return {Server|String} self when setting or value when getting
- * @api public
- */
-
-Server.prototype.path = function(v){
-  if (!arguments.length) return this._path;
-  this._path = v.replace(/\/$/, '');
-  return this;
-};
-
-/**
- * Sets the adapter for rooms.
- *
- * @param {Adapter} v pathname
- * @return {Server|Adapter} self when setting or value when getting
- * @api public
- */
-
-Server.prototype.adapter = function(v){
-  if (!arguments.length) return this._adapter;
-  this._adapter = v;
-  for (var i in this.nsps) {
-    if (this.nsps.hasOwnProperty(i)) {
-      this.nsps[i].initAdapter();
-    }
-  }
-  return this;
-};
-
-/**
- * Sets the allowed origins for requests.
- *
- * @param {String|String[]} v origins
- * @return {Server|Adapter} self when setting or value when getting
- * @api public
- */
-
-Server.prototype.origins = function(v){
-  if (!arguments.length) return this._origins;
-
-  this._origins = v;
-  return this;
-};
-
-/**
- * Attaches socket.io to a server or port.
- *
- * @param {http.Server|Number} server or port
- * @param {Object} options passed to engine.io
- * @return {Server} self
- * @api public
- */
-
-Server.prototype.listen =
-Server.prototype.attach = function(srv, opts){
-  if ('function' == typeof srv) {
-    var msg = 'You are trying to attach socket.io to an express ' +
-    'request handler function. Please pass a http.Server instance.';
-    throw new Error(msg);
-  }
-
-  // handle a port as a string
-  if (Number(srv) == srv) {
-    srv = Number(srv);
-  }
-
-  if ('number' == typeof srv) {
-    debug('creating http server and binding to %d', srv);
-    var port = srv;
-    srv = http.Server(function(req, res){
-      res.writeHead(404);
-      res.end();
-    });
-    srv.listen(port);
-
-  }
-
-  // set engine.io path to `/socket.io`
-  opts = opts || {};
-  opts.path = opts.path || this.path();
-  // set origins verification
-  opts.allowRequest = opts.allowRequest || this.checkRequest.bind(this);
-
-  if (this.sockets.fns.length > 0) {
-    this.initEngine(srv, opts);
-    return this;
-  }
-
-  var self = this;
-  var connectPacket = { type: parser.CONNECT, nsp: '/' };
-  this.encoder.encode(connectPacket, function (encodedPacket){
-    // the CONNECT packet will be merged with Engine.IO handshake,
-    // to reduce the number of round trips
-    opts.initialPacket = encodedPacket;
-
-    self.initEngine(srv, opts);
-  });
-  return this;
-};
-
-/**
- * Initialize engine
- *
- * @param {Object} options passed to engine.io
- * @api private
- */
-
-Server.prototype.initEngine = function(srv, opts){
-  // initialize engine
-  debug('creating engine.io instance with opts %j', opts);
-  this.eio = engine.attach(srv, opts);
-
-  // attach static file serving
-  if (this._serveClient) this.attachServe(srv);
-
-  // Export http server
-  this.httpServer = srv;
-
-  // bind to engine events
-  this.bind(this.eio);
-};
-
-/**
- * Attaches the static file serving.
- *
- * @param {Function|http.Server} srv http server
- * @api private
- */
-
-Server.prototype.attachServe = function(srv){
-  debug('attaching client serving req handler');
-  var url = this._path + '/socket.io.js';
-  var urlMap = this._path + '/socket.io.js.map';
-  var evs = srv.listeners('request').slice(0);
-  var self = this;
-  srv.removeAllListeners('request');
-  srv.on('request', function(req, res) {
-    if (0 === req.url.indexOf(urlMap)) {
-      self.serveMap(req, res);
-    } else if (0 === req.url.indexOf(url)) {
-      self.serve(req, res);
-    } else {
-      for (var i = 0; i < evs.length; i++) {
-        evs[i].call(srv, req, res);
-      }
-    }
-  });
-};
-
-/**
- * Handles a request serving `/socket.io.js`
- *
- * @param {http.Request} req
- * @param {http.Response} res
- * @api private
- */
-
-Server.prototype.serve = function(req, res){
-  // Per the standard, ETags must be quoted:
-  // https://tools.ietf.org/html/rfc7232#section-2.3
-  var expectedEtag = '"' + clientVersion + '"';
-
-  var etag = req.headers['if-none-match'];
-  if (etag) {
-    if (expectedEtag == etag) {
-      debug('serve client 304');
-      res.writeHead(304);
-      res.end();
-      return;
-    }
-  }
-
-  debug('serve client source');
-  res.setHeader("Cache-Control", "public, max-age=0");
-  res.setHeader('Content-Type', 'application/javascript');
-  res.setHeader('ETag', expectedEtag);
-  res.writeHead(200);
-  res.end(clientSource);
-};
-
-/**
- * Handles a request serving `/socket.io.js.map`
- *
- * @param {http.Request} req
- * @param {http.Response} res
- * @api private
- */
-
-Server.prototype.serveMap = function(req, res){
-  // Per the standard, ETags must be quoted:
-  // https://tools.ietf.org/html/rfc7232#section-2.3
-  var expectedEtag = '"' + clientVersion + '"';
-
-  var etag = req.headers['if-none-match'];
-  if (etag) {
-    if (expectedEtag == etag) {
-      debug('serve client 304');
-      res.writeHead(304);
-      res.end();
-      return;
-    }
-  }
-
-  debug('serve client sourcemap');
-  res.setHeader('Content-Type', 'application/json');
-  res.setHeader('ETag', expectedEtag);
-  res.writeHead(200);
-  res.end(clientSourceMap);
-};
-
-/**
- * Binds socket.io to an engine.io instance.
- *
- * @param {engine.Server} engine engine.io (or compatible) server
- * @return {Server} self
- * @api public
- */
-
-Server.prototype.bind = function(engine){
-  this.engine = engine;
-  this.engine.on('connection', this.onconnection.bind(this));
-  return this;
-};
-
-/**
- * Called with each incoming transport connection.
- *
- * @param {engine.Socket} conn
- * @return {Server} self
- * @api public
- */
-
-Server.prototype.onconnection = function(conn){
-  debug('incoming connection with id %s', conn.id);
-  var client = new Client(this, conn);
-  client.connect('/');
-  return this;
-};
-
-/**
- * Looks up a namespace.
- *
- * @param {String|RegExp|Function} name nsp name
- * @param {Function} [fn] optional, nsp `connection` ev handler
- * @api public
- */
-
-Server.prototype.of = function(name, fn){
-  if (typeof name === 'function' || name instanceof RegExp) {
-    const parentNsp = new ParentNamespace(this);
-    debug('initializing parent namespace %s', parentNsp.name);
-    if (typeof name === 'function') {
-      this.parentNsps.set(name, parentNsp);
-    } else {
-      this.parentNsps.set((nsp, conn, next) => next(null, name.test(nsp)), parentNsp);
-    }
-    if (fn) parentNsp.on('connect', fn);
-    return parentNsp;
-  }
-
-  if (String(name)[0] !== '/') name = '/' + name;
-
-  var nsp = this.nsps[name];
-  if (!nsp) {
-    debug('initializing namespace %s', name);
-    nsp = new Namespace(this, name);
-    this.nsps[name] = nsp;
-  }
-  if (fn) nsp.on('connect', fn);
-  return nsp;
-};
-
-/**
- * Closes server connection
- *
- * @param {Function} [fn] optional, called as `fn([err])` on error OR all conns closed
- * @api public
- */
-
-Server.prototype.close = function(fn){
-  for (var id in this.nsps['/'].sockets) {
-    if (this.nsps['/'].sockets.hasOwnProperty(id)) {
-      this.nsps['/'].sockets[id].onclose();
-    }
-  }
-
-  this.engine.close();
-
-  if (this.httpServer) {
-    this.httpServer.close(fn);
-  } else {
-    fn && fn();
-  }
-};
-
-/**
- * Expose main namespace (/).
- */
-
-var emitterMethods = Object.keys(Emitter.prototype).filter(function(key){
-  return typeof Emitter.prototype[key] === 'function';
-});
-
-emitterMethods.concat(['to', 'in', 'use', 'send', 'write', 'clients', 'compress', 'binary']).forEach(function(fn){
-  Server.prototype[fn] = function(){
-    return this.sockets[fn].apply(this.sockets, arguments);
-  };
-});
-
-Namespace.flags.forEach(function(flag){
-  Object.defineProperty(Server.prototype, flag, {
-    get: function() {
-      this.sockets.flags = this.sockets.flags || {};
-      this.sockets.flags[flag] = true;
-      return this;
-    }
-  });
-});
-
-/**
- * BC with `io.listen`
- */
-
-Server.listen = Server;
+"use strict";var http=require("http"),read=require("fs").readFileSync,path=require("path"),exists=require("fs").existsSync,engine=require("engine.io"),clientVersion=require("socket.io-client/package.json").version,Client=require("./client"),Emitter=require("events").EventEmitter,Namespace=require("./namespace"),ParentNamespace=require("./parent-namespace"),Adapter=require("socket.io-adapter"),parser=require("socket.io-parser"),debug=require("debug")("socket.io:server"),url=require("url");module.exports=Server;var clientSource=void 0,clientSourceMap=void 0;function Server(e,t){if(!(this instanceof Server))return new Server(e,t);"object"==typeof e&&e instanceof Object&&!e.listen&&(t=e,e=null),t=t||{},this.nsps={},this.parentNsps=new Map,this.path(t.path||"/socket.io"),this.serveClient(!1!==t.serveClient),this.parser=t.parser||parser,this.encoder=new this.parser.Encoder,this.adapter(t.adapter||Adapter),this.origins(t.origins||"*:*"),this.sockets=this.of("/"),e&&this.attach(e,t)}Server.prototype.checkRequest=function(e,t){var r=e.headers.origin||e.headers.referer;if("null"!=r&&null!=r||(r="*"),r&&"function"==typeof this._origins)return this._origins(r,t);if(-1!==this._origins.indexOf("*:*"))return t(null,!0);if(r)try{var i=url.parse(r),n="https:"==i.protocol?443:80;i.port=null!=i.port?i.port:n;var s=~this._origins.indexOf(i.protocol+"//"+i.hostname+":"+i.port)||~this._origins.indexOf(i.hostname+":"+i.port)||~this._origins.indexOf(i.hostname+":*")||~this._origins.indexOf("*:"+i.port);return debug("origin %s is %svalid",r,s?"":"not "),t(null,!!s)}catch(e){}t(null,!1)},Server.prototype.serveClient=function(e){if(!arguments.length)return this._serveClient;this._serveClient=e;var t=function(e){var t=path.resolve(__dirname,"./../../",e);return exists(t)?t:require.resolve(e)};if(e&&!clientSource){clientSource=read(t("socket.io-client/dist/socket.io.js"),"utf-8");try{clientSourceMap=read(t("socket.io-client/dist/socket.io.js.map"),"utf-8")}catch(e){debug("could not load sourcemap file")}}return this};var oldSettings={transports:"transports","heartbeat timeout":"pingTimeout","heartbeat interval":"pingInterval","destroy buffer size":"maxHttpBufferSize"};Server.prototype.set=function(e,t){return"authorization"==e&&t?this.use((function(e,r){t(e.request,(function(e,t){return e?r(new Error(e)):t?void r():r(new Error("Not authorized"))}))})):"origins"==e&&t?this.origins(t):"resource"==e?this.path(t):oldSettings[e]&&this.eio[oldSettings[e]]?this.eio[oldSettings[e]]=t:console.error("Option %s is not valid. Please refer to the README.",e),this},Server.prototype.checkNamespace=function(e,t,r){if(0===this.parentNsps.size)return r(!1);const i=this.parentNsps.keys(),n=()=>{let s=i.next();if(s.done)return r(!1);s.value(e,t,((t,i)=>{t||!i?n():r(this.parentNsps.get(s.value).createChild(e))}))};n()},Server.prototype.path=function(e){return arguments.length?(this._path=e.replace(/\/$/,""),this):this._path},Server.prototype.adapter=function(e){if(!arguments.length)return this._adapter;for(var t in this._adapter=e,this.nsps)this.nsps.hasOwnProperty(t)&&this.nsps[t].initAdapter();return this},Server.prototype.origins=function(e){return arguments.length?(this._origins=e,this):this._origins},Server.prototype.listen=Server.prototype.attach=function(e,t){if("function"==typeof e){throw new Error("You are trying to attach socket.io to an express request handler function. Please pass a http.Server instance.")}if(Number(e)==e&&(e=Number(e)),"number"==typeof e){debug("creating http server and binding to %d",e);var r=e;(e=http.Server((function(e,t){t.writeHead(404),t.end()}))).listen(r)}if((t=t||{}).path=t.path||this.path(),t.allowRequest=t.allowRequest||this.checkRequest.bind(this),this.sockets.fns.length>0)return this.initEngine(e,t),this;var i=this,n={type:parser.CONNECT,nsp:"/"};return this.encoder.encode(n,(function(r){t.initialPacket=r,i.initEngine(e,t)})),this},Server.prototype.initEngine=function(e,t){debug("creating engine.io instance with opts %j",t),this.eio=engine.attach(e,t),this._serveClient&&this.attachServe(e),this.httpServer=e,this.bind(this.eio)},Server.prototype.attachServe=function(e){debug("attaching client serving req handler");var t=this._path+"/socket.io.js",r=this._path+"/socket.io.js.map",i=e.listeners("request").slice(0),n=this;e.removeAllListeners("request"),e.on("request",(function(s,o){if(0===s.url.indexOf(r))n.serveMap(s,o);else if(0===s.url.indexOf(t))n.serve(s,o);else for(var a=0;a<i.length;a++)i[a].call(e,s,o)}))},Server.prototype.serve=function(e,t){var r='"'+clientVersion+'"',i=e.headers["if-none-match"];if(i&&r==i)return debug("serve client 304"),t.writeHead(304),void t.end();debug("serve client source"),t.setHeader("Cache-Control","public, max-age=0"),t.setHeader("Content-Type","application/javascript"),t.setHeader("ETag",r),t.writeHead(200),t.end(clientSource)},Server.prototype.serveMap=function(e,t){var r='"'+clientVersion+'"',i=e.headers["if-none-match"];if(i&&r==i)return debug("serve client 304"),t.writeHead(304),void t.end();debug("serve client sourcemap"),t.setHeader("Content-Type","application/json"),t.setHeader("ETag",r),t.writeHead(200),t.end(clientSourceMap)},Server.prototype.bind=function(e){return this.engine=e,this.engine.on("connection",this.onconnection.bind(this)),this},Server.prototype.onconnection=function(e){return debug("incoming connection with id %s",e.id),new Client(this,e).connect("/"),this},Server.prototype.of=function(e,t){if("function"==typeof e||e instanceof RegExp){const r=new ParentNamespace(this);return debug("initializing parent namespace %s",r.name),"function"==typeof e?this.parentNsps.set(e,r):this.parentNsps.set(((t,r,i)=>i(null,e.test(t))),r),t&&r.on("connect",t),r}"/"!==String(e)[0]&&(e="/"+e);var r=this.nsps[e];return r||(debug("initializing namespace %s",e),r=new Namespace(this,e),this.nsps[e]=r),t&&r.on("connect",t),r},Server.prototype.close=function(e){for(var t in this.nsps["/"].sockets)this.nsps["/"].sockets.hasOwnProperty(t)&&this.nsps["/"].sockets[t].onclose();this.engine.close(),this.httpServer?this.httpServer.close(e):e&&e()};var emitterMethods=Object.keys(Emitter.prototype).filter((function(e){return"function"==typeof Emitter.prototype[e]}));emitterMethods.concat(["to","in","use","send","write","clients","compress","binary"]).forEach((function(e){Server.prototype[e]=function(){return this.sockets[e].apply(this.sockets,arguments)}})),Namespace.flags.forEach((function(e){Object.defineProperty(Server.prototype,e,{get:function(){return this.sockets.flags=this.sockets.flags||{},this.sockets.flags[e]=!0,this}})})),Server.listen=Server;
\ No newline at end of file
index bca8a3e..cc3a65d 100644 (file)
@@ -1,299 +1 @@
-
-/**
- * Module dependencies.
- */
-
-var Socket = require('./socket');
-var Emitter = require('events').EventEmitter;
-var parser = require('socket.io-parser');
-var hasBin = require('has-binary2');
-var debug = require('debug')('socket.io:namespace');
-
-/**
- * Module exports.
- */
-
-module.exports = exports = Namespace;
-
-/**
- * Blacklisted events.
- */
-
-exports.events = [
-  'connect',    // for symmetry with client
-  'connection',
-  'newListener'
-];
-
-/**
- * Flags.
- */
-
-exports.flags = [
-  'json',
-  'volatile',
-  'local'
-];
-
-/**
- * `EventEmitter#emit` reference.
- */
-
-var emit = Emitter.prototype.emit;
-
-/**
- * Namespace constructor.
- *
- * @param {Server} server instance
- * @param {Socket} name
- * @api private
- */
-
-function Namespace(server, name){
-  this.name = name;
-  this.server = server;
-  this.sockets = {};
-  this.connected = {};
-  this.fns = [];
-  this.ids = 0;
-  this.rooms = [];
-  this.flags = {};
-  this.initAdapter();
-}
-
-/**
- * Inherits from `EventEmitter`.
- */
-
-Namespace.prototype.__proto__ = Emitter.prototype;
-
-/**
- * Apply flags from `Socket`.
- */
-
-exports.flags.forEach(function(flag){
-  Object.defineProperty(Namespace.prototype, flag, {
-    get: function() {
-      this.flags[flag] = true;
-      return this;
-    }
-  });
-});
-
-/**
- * Initializes the `Adapter` for this nsp.
- * Run upon changing adapter by `Server#adapter`
- * in addition to the constructor.
- *
- * @api private
- */
-
-Namespace.prototype.initAdapter = function(){
-  this.adapter = new (this.server.adapter())(this);
-};
-
-/**
- * Sets up namespace middleware.
- *
- * @return {Namespace} self
- * @api public
- */
-
-Namespace.prototype.use = function(fn){
-  if (this.server.eio && this.name === '/') {
-    debug('removing initial packet');
-    delete this.server.eio.initialPacket;
-  }
-  this.fns.push(fn);
-  return this;
-};
-
-/**
- * Executes the middleware for an incoming client.
- *
- * @param {Socket} socket that will get added
- * @param {Function} fn last fn call in the middleware
- * @api private
- */
-
-Namespace.prototype.run = function(socket, fn){
-  var fns = this.fns.slice(0);
-  if (!fns.length) return fn(null);
-
-  function run(i){
-    fns[i](socket, function(err){
-      // upon error, short-circuit
-      if (err) return fn(err);
-
-      // if no middleware left, summon callback
-      if (!fns[i + 1]) return fn(null);
-
-      // go on to next
-      run(i + 1);
-    });
-  }
-
-  run(0);
-};
-
-/**
- * Targets a room when emitting.
- *
- * @param {String} name
- * @return {Namespace} self
- * @api public
- */
-
-Namespace.prototype.to =
-Namespace.prototype.in = function(name){
-  if (!~this.rooms.indexOf(name)) this.rooms.push(name);
-  return this;
-};
-
-/**
- * Adds a new client.
- *
- * @return {Socket}
- * @api private
- */
-
-Namespace.prototype.add = function(client, query, fn){
-  debug('adding socket to nsp %s', this.name);
-  var socket = new Socket(this, client, query);
-  var self = this;
-  this.run(socket, function(err){
-    process.nextTick(function(){
-      if ('open' == client.conn.readyState) {
-        if (err) return socket.error(err.data || err.message);
-
-        // track socket
-        self.sockets[socket.id] = socket;
-
-        // it's paramount that the internal `onconnect` logic
-        // fires before user-set events to prevent state order
-        // violations (such as a disconnection before the connection
-        // logic is complete)
-        socket.onconnect();
-        if (fn) fn();
-
-        // fire user-set events
-        self.emit('connect', socket);
-        self.emit('connection', socket);
-      } else {
-        debug('next called after client was closed - ignoring socket');
-      }
-    });
-  });
-  return socket;
-};
-
-/**
- * Removes a client. Called by each `Socket`.
- *
- * @api private
- */
-
-Namespace.prototype.remove = function(socket){
-  if (this.sockets.hasOwnProperty(socket.id)) {
-    delete this.sockets[socket.id];
-  } else {
-    debug('ignoring remove for %s', socket.id);
-  }
-};
-
-/**
- * Emits to all clients.
- *
- * @return {Namespace} self
- * @api public
- */
-
-Namespace.prototype.emit = function(ev){
-  if (~exports.events.indexOf(ev)) {
-    emit.apply(this, arguments);
-    return this;
-  }
-  // set up packet object
-  var args = Array.prototype.slice.call(arguments);
-  var packet = {
-    type: (this.flags.binary !== undefined ? this.flags.binary : hasBin(args)) ? parser.BINARY_EVENT : parser.EVENT,
-    data: args
-  };
-
-  if ('function' == typeof args[args.length - 1]) {
-    throw new Error('Callbacks are not supported when broadcasting');
-  }
-
-  var rooms = this.rooms.slice(0);
-  var flags = Object.assign({}, this.flags);
-
-  // reset flags
-  this.rooms = [];
-  this.flags = {};
-
-  this.adapter.broadcast(packet, {
-    rooms: rooms,
-    flags: flags
-  });
-
-  return this;
-};
-
-/**
- * Sends a `message` event to all clients.
- *
- * @return {Namespace} self
- * @api public
- */
-
-Namespace.prototype.send =
-Namespace.prototype.write = function(){
-  var args = Array.prototype.slice.call(arguments);
-  args.unshift('message');
-  this.emit.apply(this, args);
-  return this;
-};
-
-/**
- * Gets a list of clients.
- *
- * @return {Namespace} self
- * @api public
- */
-
-Namespace.prototype.clients = function(fn){
-  if(!this.adapter){
-    throw new Error('No adapter for this namespace, are you trying to get the list of clients of a dynamic namespace?')
-  }
-  this.adapter.clients(this.rooms, fn);
-  // reset rooms for scenario:
-  // .in('room').clients() (GH-1978)
-  this.rooms = [];
-  return this;
-};
-
-/**
- * Sets the compress flag.
- *
- * @param {Boolean} compress if `true`, compresses the sending data
- * @return {Socket} self
- * @api public
- */
-
-Namespace.prototype.compress = function(compress){
-  this.flags.compress = compress;
-  return this;
-};
-
-/**
- * Sets the binary flag
- *
- * @param {Boolean} Encode as if it has binary data if `true`, Encode as if it doesnt have binary data if `false`
- * @return {Socket} self
- * @api public
- */
-
- Namespace.prototype.binary = function (binary) {
-   this.flags.binary = binary;
-   return this;
- };
+var Socket=require("./socket"),Emitter=require("events").EventEmitter,parser=require("socket.io-parser"),hasBin=require("has-binary2"),debug=require("debug")("socket.io:namespace");module.exports=exports=Namespace,exports.events=["connect","connection","newListener"],exports.flags=["json","volatile","local"];var emit=Emitter.prototype.emit;function Namespace(e,t){this.name=t,this.server=e,this.sockets={},this.connected={},this.fns=[],this.ids=0,this.rooms=[],this.flags={},this.initAdapter()}Namespace.prototype.__proto__=Emitter.prototype,exports.flags.forEach((function(e){Object.defineProperty(Namespace.prototype,e,{get:function(){return this.flags[e]=!0,this}})})),Namespace.prototype.initAdapter=function(){this.adapter=new(this.server.adapter())(this)},Namespace.prototype.use=function(e){return this.server.eio&&"/"===this.name&&(debug("removing initial packet"),delete this.server.eio.initialPacket),this.fns.push(e),this},Namespace.prototype.run=function(e,t){var s=this.fns.slice(0);if(!s.length)return t(null);!function r(i){s[i](e,(function(e){return e?t(e):s[i+1]?void r(i+1):t(null)}))}(0)},Namespace.prototype.to=Namespace.prototype.in=function(e){return~this.rooms.indexOf(e)||this.rooms.push(e),this},Namespace.prototype.add=function(e,t,s){debug("adding socket to nsp %s",this.name);var r=new Socket(this,e,t),i=this;return this.run(r,(function(t){process.nextTick((function(){if("open"==e.conn.readyState){if(t)return r.error(t.data||t.message);i.sockets[r.id]=r,r.onconnect(),s&&s(),i.emit("connect",r),i.emit("connection",r)}else debug("next called after client was closed - ignoring socket")}))})),r},Namespace.prototype.remove=function(e){this.sockets.hasOwnProperty(e.id)?delete this.sockets[e.id]:debug("ignoring remove for %s",e.id)},Namespace.prototype.emit=function(e){if(~exports.events.indexOf(e))return emit.apply(this,arguments),this;var t=Array.prototype.slice.call(arguments),s={type:(void 0!==this.flags.binary?this.flags.binary:hasBin(t))?parser.BINARY_EVENT:parser.EVENT,data:t};if("function"==typeof t[t.length-1])throw new Error("Callbacks are not supported when broadcasting");var r=this.rooms.slice(0),i=Object.assign({},this.flags);return this.rooms=[],this.flags={},this.adapter.broadcast(s,{rooms:r,flags:i}),this},Namespace.prototype.send=Namespace.prototype.write=function(){var e=Array.prototype.slice.call(arguments);return e.unshift("message"),this.emit.apply(this,e),this},Namespace.prototype.clients=function(e){if(!this.adapter)throw new Error("No adapter for this namespace, are you trying to get the list of clients of a dynamic namespace?");return this.adapter.clients(this.rooms,e),this.rooms=[],this},Namespace.prototype.compress=function(e){return this.flags.compress=e,this},Namespace.prototype.binary=function(e){return this.flags.binary=e,this};
\ No newline at end of file
index 5a2b4fa..ca50299 100644 (file)
@@ -1,39 +1 @@
-'use strict';
-
-const Namespace = require('./namespace');
-
-let count = 0;
-
-class ParentNamespace extends Namespace {
-
-  constructor(server) {
-    super(server, '/_' + (count++));
-    this.children = new Set();
-  }
-
-  initAdapter() {}
-
-  emit() {
-    const args = Array.prototype.slice.call(arguments);
-
-    this.children.forEach(nsp => {
-      nsp.rooms = this.rooms;
-      nsp.flags = this.flags;
-      nsp.emit.apply(nsp, args);
-    });
-    this.rooms = [];
-    this.flags = {};
-  }
-
-  createChild(name) {
-    const namespace = new Namespace(this.server, name);
-    namespace.fns = this.fns.slice(0);
-    this.listeners('connect').forEach(listener => namespace.on('connect', listener));
-    this.listeners('connection').forEach(listener => namespace.on('connection', listener));
-    this.children.add(namespace);
-    this.server.nsps[name] = namespace;
-    return namespace;
-  }
-}
-
-module.exports = ParentNamespace;
+"use strict";const Namespace=require("./namespace");let count=0;class ParentNamespace extends Namespace{constructor(e){super(e,"/_"+count++),this.children=new Set}initAdapter(){}emit(){const e=Array.prototype.slice.call(arguments);this.children.forEach((s=>{s.rooms=this.rooms,s.flags=this.flags,s.emit.apply(s,e)})),this.rooms=[],this.flags={}}createChild(e){const s=new Namespace(this.server,e);return s.fns=this.fns.slice(0),this.listeners("connect").forEach((e=>s.on("connect",e))),this.listeners("connection").forEach((e=>s.on("connection",e))),this.children.add(s),this.server.nsps[e]=s,s}}module.exports=ParentNamespace;
\ No newline at end of file
index 4e97eb5..084779c 100644 (file)
@@ -1,572 +1 @@
-
-/**
- * Module dependencies.
- */
-
-var Emitter = require('events').EventEmitter;
-var parser = require('socket.io-parser');
-var hasBin = require('has-binary2');
-var url = require('url');
-var debug = require('debug')('socket.io:socket');
-
-/**
- * Module exports.
- */
-
-module.exports = exports = Socket;
-
-/**
- * Blacklisted events.
- *
- * @api public
- */
-
-exports.events = [
-  'error',
-  'connect',
-  'disconnect',
-  'disconnecting',
-  'newListener',
-  'removeListener'
-];
-
-/**
- * Flags.
- *
- * @api private
- */
-
-var flags = [
-  'json',
-  'volatile',
-  'broadcast',
-  'local'
-];
-
-/**
- * `EventEmitter#emit` reference.
- */
-
-var emit = Emitter.prototype.emit;
-
-/**
- * Interface to a `Client` for a given `Namespace`.
- *
- * @param {Namespace} nsp
- * @param {Client} client
- * @api public
- */
-
-function Socket(nsp, client, query){
-  this.nsp = nsp;
-  this.server = nsp.server;
-  this.adapter = this.nsp.adapter;
-  this.id = nsp.name !== '/' ? nsp.name + '#' + client.id : client.id;
-  this.client = client;
-  this.conn = client.conn;
-  this.rooms = {};
-  this.acks = {};
-  this.connected = true;
-  this.disconnected = false;
-  this.handshake = this.buildHandshake(query);
-  this.fns = [];
-  this.flags = {};
-  this._rooms = [];
-}
-
-/**
- * Inherits from `EventEmitter`.
- */
-
-Socket.prototype.__proto__ = Emitter.prototype;
-
-/**
- * Apply flags from `Socket`.
- */
-
-flags.forEach(function(flag){
-  Object.defineProperty(Socket.prototype, flag, {
-    get: function() {
-      this.flags[flag] = true;
-      return this;
-    }
-  });
-});
-
-/**
- * `request` engine.io shortcut.
- *
- * @api public
- */
-
-Object.defineProperty(Socket.prototype, 'request', {
-  get: function() {
-    return this.conn.request;
-  }
-});
-
-/**
- * Builds the `handshake` BC object
- *
- * @api private
- */
-
-Socket.prototype.buildHandshake = function(query){
-  var self = this;
-  function buildQuery(){
-    var requestQuery = url.parse(self.request.url, true).query;
-    //if socket-specific query exist, replace query strings in requestQuery
-    return Object.assign({}, requestQuery, query);
-  }
-  return {
-    headers: this.request.headers,
-    time: (new Date) + '',
-    address: this.conn.remoteAddress,
-    xdomain: !!this.request.headers.origin,
-    secure: !!this.request.connection.encrypted,
-    issued: +(new Date),
-    url: this.request.url,
-    query: buildQuery()
-  };
-};
-
-/**
- * Emits to this client.
- *
- * @return {Socket} self
- * @api public
- */
-
-Socket.prototype.emit = function(ev){
-  if (~exports.events.indexOf(ev)) {
-    emit.apply(this, arguments);
-    return this;
-  }
-
-  var args = Array.prototype.slice.call(arguments);
-  var packet = {
-    type: (this.flags.binary !== undefined ? this.flags.binary : hasBin(args)) ? parser.BINARY_EVENT : parser.EVENT,
-    data: args
-  };
-
-  // access last argument to see if it's an ACK callback
-  if (typeof args[args.length - 1] === 'function') {
-    if (this._rooms.length || this.flags.broadcast) {
-      throw new Error('Callbacks are not supported when broadcasting');
-    }
-
-    debug('emitting packet with ack id %d', this.nsp.ids);
-    this.acks[this.nsp.ids] = args.pop();
-    packet.id = this.nsp.ids++;
-  }
-
-  var rooms = this._rooms.slice(0);
-  var flags = Object.assign({}, this.flags);
-
-  // reset flags
-  this._rooms = [];
-  this.flags = {};
-
-  if (rooms.length || flags.broadcast) {
-    this.adapter.broadcast(packet, {
-      except: [this.id],
-      rooms: rooms,
-      flags: flags
-    });
-  } else {
-    // dispatch packet
-    this.packet(packet, flags);
-  }
-  return this;
-};
-
-/**
- * Targets a room when broadcasting.
- *
- * @param {String} name
- * @return {Socket} self
- * @api public
- */
-
-Socket.prototype.to =
-Socket.prototype.in = function(name){
-  if (!~this._rooms.indexOf(name)) this._rooms.push(name);
-  return this;
-};
-
-/**
- * Sends a `message` event.
- *
- * @return {Socket} self
- * @api public
- */
-
-Socket.prototype.send =
-Socket.prototype.write = function(){
-  var args = Array.prototype.slice.call(arguments);
-  args.unshift('message');
-  this.emit.apply(this, args);
-  return this;
-};
-
-/**
- * Writes a packet.
- *
- * @param {Object} packet object
- * @param {Object} opts options
- * @api private
- */
-
-Socket.prototype.packet = function(packet, opts){
-  packet.nsp = this.nsp.name;
-  opts = opts || {};
-  opts.compress = false !== opts.compress;
-  this.client.packet(packet, opts);
-};
-
-/**
- * Joins a room.
- *
- * @param {String|Array} room or array of rooms
- * @param {Function} fn optional, callback
- * @return {Socket} self
- * @api private
- */
-
-Socket.prototype.join = function(rooms, fn){
-  debug('joining room %s', rooms);
-  var self = this;
-  if (!Array.isArray(rooms)) {
-    rooms = [rooms];
-  }
-  rooms = rooms.filter(function (room) {
-    return !self.rooms.hasOwnProperty(room);
-  });
-  if (!rooms.length) {
-    fn && fn(null);
-    return this;
-  }
-  this.adapter.addAll(this.id, rooms, function(err){
-    if (err) return fn && fn(err);
-    debug('joined room %s', rooms);
-    rooms.forEach(function (room) {
-      self.rooms[room] = room;
-    });
-    fn && fn(null);
-  });
-  return this;
-};
-
-/**
- * Leaves a room.
- *
- * @param {String} room
- * @param {Function} fn optional, callback
- * @return {Socket} self
- * @api private
- */
-
-Socket.prototype.leave = function(room, fn){
-  debug('leave room %s', room);
-  var self = this;
-  this.adapter.del(this.id, room, function(err){
-    if (err) return fn && fn(err);
-    debug('left room %s', room);
-    delete self.rooms[room];
-    fn && fn(null);
-  });
-  return this;
-};
-
-/**
- * Leave all rooms.
- *
- * @api private
- */
-
-Socket.prototype.leaveAll = function(){
-  this.adapter.delAll(this.id);
-  this.rooms = {};
-};
-
-/**
- * Called by `Namespace` upon successful
- * middleware execution (ie: authorization).
- * Socket is added to namespace array before
- * call to join, so adapters can access it.
- *
- * @api private
- */
-
-Socket.prototype.onconnect = function(){
-  debug('socket connected - writing packet');
-  this.nsp.connected[this.id] = this;
-  this.join(this.id);
-  var skip = this.nsp.name === '/' && this.nsp.fns.length === 0;
-  if (skip) {
-    debug('packet already sent in initial handshake');
-  } else {
-    this.packet({ type: parser.CONNECT });
-  }
-};
-
-/**
- * Called with each packet. Called by `Client`.
- *
- * @param {Object} packet
- * @api private
- */
-
-Socket.prototype.onpacket = function(packet){
-  debug('got packet %j', packet);
-  switch (packet.type) {
-    case parser.EVENT:
-      this.onevent(packet);
-      break;
-
-    case parser.BINARY_EVENT:
-      this.onevent(packet);
-      break;
-
-    case parser.ACK:
-      this.onack(packet);
-      break;
-
-    case parser.BINARY_ACK:
-      this.onack(packet);
-      break;
-
-    case parser.DISCONNECT:
-      this.ondisconnect();
-      break;
-
-    case parser.ERROR:
-      this.onerror(new Error(packet.data));
-  }
-};
-
-/**
- * Called upon event packet.
- *
- * @param {Object} packet object
- * @api private
- */
-
-Socket.prototype.onevent = function(packet){
-  var args = packet.data || [];
-  debug('emitting event %j', args);
-
-  if (null != packet.id) {
-    debug('attaching ack callback to event');
-    args.push(this.ack(packet.id));
-  }
-
-  this.dispatch(args);
-};
-
-/**
- * Produces an ack callback to emit with an event.
- *
- * @param {Number} id packet id
- * @api private
- */
-
-Socket.prototype.ack = function(id){
-  var self = this;
-  var sent = false;
-  return function(){
-    // prevent double callbacks
-    if (sent) return;
-    var args = Array.prototype.slice.call(arguments);
-    debug('sending ack %j', args);
-
-    self.packet({
-      id: id,
-      type: hasBin(args) ? parser.BINARY_ACK : parser.ACK,
-      data: args
-    });
-
-    sent = true;
-  };
-};
-
-/**
- * Called upon ack packet.
- *
- * @api private
- */
-
-Socket.prototype.onack = function(packet){
-  var ack = this.acks[packet.id];
-  if ('function' == typeof ack) {
-    debug('calling ack %s with %j', packet.id, packet.data);
-    ack.apply(this, packet.data);
-    delete this.acks[packet.id];
-  } else {
-    debug('bad ack %s', packet.id);
-  }
-};
-
-/**
- * Called upon client disconnect packet.
- *
- * @api private
- */
-
-Socket.prototype.ondisconnect = function(){
-  debug('got disconnect packet');
-  this.onclose('client namespace disconnect');
-};
-
-/**
- * Handles a client error.
- *
- * @api private
- */
-
-Socket.prototype.onerror = function(err){
-  if (this.listeners('error').length) {
-    this.emit('error', err);
-  } else {
-    console.error('Missing error handler on `socket`.');
-    console.error(err.stack);
-  }
-};
-
-/**
- * Called upon closing. Called by `Client`.
- *
- * @param {String} reason
- * @throw {Error} optional error object
- * @api private
- */
-
-Socket.prototype.onclose = function(reason){
-  if (!this.connected) return this;
-  debug('closing socket - reason %s', reason);
-  this.emit('disconnecting', reason);
-  this.leaveAll();
-  this.nsp.remove(this);
-  this.client.remove(this);
-  this.connected = false;
-  this.disconnected = true;
-  delete this.nsp.connected[this.id];
-  this.emit('disconnect', reason);
-};
-
-/**
- * Produces an `error` packet.
- *
- * @param {Object} err error object
- * @api private
- */
-
-Socket.prototype.error = function(err){
-  this.packet({ type: parser.ERROR, data: err });
-};
-
-/**
- * Disconnects this client.
- *
- * @param {Boolean} close if `true`, closes the underlying connection
- * @return {Socket} self
- * @api public
- */
-
-Socket.prototype.disconnect = function(close){
-  if (!this.connected) return this;
-  if (close) {
-    this.client.disconnect();
-  } else {
-    this.packet({ type: parser.DISCONNECT });
-    this.onclose('server namespace disconnect');
-  }
-  return this;
-};
-
-/**
- * Sets the compress flag.
- *
- * @param {Boolean} compress if `true`, compresses the sending data
- * @return {Socket} self
- * @api public
- */
-
-Socket.prototype.compress = function(compress){
-  this.flags.compress = compress;
-  return this;
-};
-
-/**
- * Sets the binary flag
- *
- * @param {Boolean} Encode as if it has binary data if `true`, Encode as if it doesnt have binary data if `false`
- * @return {Socket} self
- * @api public
- */
-
- Socket.prototype.binary = function (binary) {
-   this.flags.binary = binary;
-   return this;
- };
-
-/**
- * Dispatch incoming event to socket listeners.
- *
- * @param {Array} event that will get emitted
- * @api private
- */
-
-Socket.prototype.dispatch = function(event){
-  debug('dispatching an event %j', event);
-  var self = this;
-  function dispatchSocket(err) {
-    process.nextTick(function(){
-      if (err) {
-        return self.error(err.data || err.message);
-      }
-      emit.apply(self, event);
-    });
-  }
-  this.run(event, dispatchSocket);
-};
-
-/**
- * Sets up socket middleware.
- *
- * @param {Function} middleware function (event, next)
- * @return {Socket} self
- * @api public
- */
-
-Socket.prototype.use = function(fn){
-  this.fns.push(fn);
-  return this;
-};
-
-/**
- * Executes the middleware for an incoming event.
- *
- * @param {Array} event that will get emitted
- * @param {Function} last fn call in the middleware
- * @api private
- */
-Socket.prototype.run = function(event, fn){
-  var fns = this.fns.slice(0);
-  if (!fns.length) return fn(null);
-
-  function run(i){
-    fns[i](event, function(err){
-      // upon error, short-circuit
-      if (err) return fn(err);
-
-      // if no middleware left, summon callback
-      if (!fns[i + 1]) return fn(null);
-
-      // go on to next
-      run(i + 1);
-    });
-  }
-
-  run(0);
-};
+var Emitter=require("events").EventEmitter,parser=require("socket.io-parser"),hasBin=require("has-binary2"),url=require("url"),debug=require("debug")("socket.io:socket");module.exports=exports=Socket,exports.events=["error","connect","disconnect","disconnecting","newListener","removeListener"];var flags=["json","volatile","broadcast","local"],emit=Emitter.prototype.emit;function Socket(t,e,s){this.nsp=t,this.server=t.server,this.adapter=this.nsp.adapter,this.id="/"!==t.name?t.name+"#"+e.id:e.id,this.client=e,this.conn=e.conn,this.rooms={},this.acks={},this.connected=!0,this.disconnected=!1,this.handshake=this.buildHandshake(s),this.fns=[],this.flags={},this._rooms=[]}Socket.prototype.__proto__=Emitter.prototype,flags.forEach((function(t){Object.defineProperty(Socket.prototype,t,{get:function(){return this.flags[t]=!0,this}})})),Object.defineProperty(Socket.prototype,"request",{get:function(){return this.conn.request}}),Socket.prototype.buildHandshake=function(t){var e,s=this;return{headers:this.request.headers,time:new Date+"",address:this.conn.remoteAddress,xdomain:!!this.request.headers.origin,secure:!!this.request.connection.encrypted,issued:+new Date,url:this.request.url,query:(e=url.parse(s.request.url,!0).query,Object.assign({},e,t))}},Socket.prototype.emit=function(t){if(~exports.events.indexOf(t))return emit.apply(this,arguments),this;var e=Array.prototype.slice.call(arguments),s={type:(void 0!==this.flags.binary?this.flags.binary:hasBin(e))?parser.BINARY_EVENT:parser.EVENT,data:e};if("function"==typeof e[e.length-1]){if(this._rooms.length||this.flags.broadcast)throw new Error("Callbacks are not supported when broadcasting");debug("emitting packet with ack id %d",this.nsp.ids),this.acks[this.nsp.ids]=e.pop(),s.id=this.nsp.ids++}var i=this._rooms.slice(0),o=Object.assign({},this.flags);return this._rooms=[],this.flags={},i.length||o.broadcast?this.adapter.broadcast(s,{except:[this.id],rooms:i,flags:o}):this.packet(s,o),this},Socket.prototype.to=Socket.prototype.in=function(t){return~this._rooms.indexOf(t)||this._rooms.push(t),this},Socket.prototype.send=Socket.prototype.write=function(){var t=Array.prototype.slice.call(arguments);return t.unshift("message"),this.emit.apply(this,t),this},Socket.prototype.packet=function(t,e){t.nsp=this.nsp.name,(e=e||{}).compress=!1!==e.compress,this.client.packet(t,e)},Socket.prototype.join=function(t,e){debug("joining room %s",t);var s=this;return Array.isArray(t)||(t=[t]),(t=t.filter((function(t){return!s.rooms.hasOwnProperty(t)}))).length?(this.adapter.addAll(this.id,t,(function(i){if(i)return e&&e(i);debug("joined room %s",t),t.forEach((function(t){s.rooms[t]=t})),e&&e(null)})),this):(e&&e(null),this)},Socket.prototype.leave=function(t,e){debug("leave room %s",t);var s=this;return this.adapter.del(this.id,t,(function(i){if(i)return e&&e(i);debug("left room %s",t),delete s.rooms[t],e&&e(null)})),this},Socket.prototype.leaveAll=function(){this.adapter.delAll(this.id),this.rooms={}},Socket.prototype.onconnect=function(){debug("socket connected - writing packet"),this.nsp.connected[this.id]=this,this.join(this.id),"/"===this.nsp.name&&0===this.nsp.fns.length?debug("packet already sent in initial handshake"):this.packet({type:parser.CONNECT})},Socket.prototype.onpacket=function(t){switch(debug("got packet %j",t),t.type){case parser.EVENT:case parser.BINARY_EVENT:this.onevent(t);break;case parser.ACK:case parser.BINARY_ACK:this.onack(t);break;case parser.DISCONNECT:this.ondisconnect();break;case parser.ERROR:this.onerror(new Error(t.data))}},Socket.prototype.onevent=function(t){var e=t.data||[];debug("emitting event %j",e),null!=t.id&&(debug("attaching ack callback to event"),e.push(this.ack(t.id))),this.dispatch(e)},Socket.prototype.ack=function(t){var e=this,s=!1;return function(){if(!s){var i=Array.prototype.slice.call(arguments);debug("sending ack %j",i),e.packet({id:t,type:hasBin(i)?parser.BINARY_ACK:parser.ACK,data:i}),s=!0}}},Socket.prototype.onack=function(t){var e=this.acks[t.id];"function"==typeof e?(debug("calling ack %s with %j",t.id,t.data),e.apply(this,t.data),delete this.acks[t.id]):debug("bad ack %s",t.id)},Socket.prototype.ondisconnect=function(){debug("got disconnect packet"),this.onclose("client namespace disconnect")},Socket.prototype.onerror=function(t){this.listeners("error").length?this.emit("error",t):(console.error("Missing error handler on `socket`."),console.error(t.stack))},Socket.prototype.onclose=function(t){if(!this.connected)return this;debug("closing socket - reason %s",t),this.emit("disconnecting",t),this.leaveAll(),this.nsp.remove(this),this.client.remove(this),this.connected=!1,this.disconnected=!0,delete this.nsp.connected[this.id],this.emit("disconnect",t)},Socket.prototype.error=function(t){this.packet({type:parser.ERROR,data:t})},Socket.prototype.disconnect=function(t){return this.connected?(t?this.client.disconnect():(this.packet({type:parser.DISCONNECT}),this.onclose("server namespace disconnect")),this):this},Socket.prototype.compress=function(t){return this.flags.compress=t,this},Socket.prototype.binary=function(t){return this.flags.binary=t,this},Socket.prototype.dispatch=function(t){debug("dispatching an event %j",t);var e=this;this.run(t,(function(s){process.nextTick((function(){if(s)return e.error(s.data||s.message);emit.apply(e,t)}))}))},Socket.prototype.use=function(t){return this.fns.push(t),this},Socket.prototype.run=function(t,e){var s=this.fns.slice(0);if(!s.length)return e(null);!function i(o){s[o](t,(function(t){return t?e(t):s[o+1]?void i(o+1):e(null)}))}(0)};
\ No newline at end of file
index 1d158c9..235f8d0 100644 (file)
  * (c) 2014-2021 Guillermo Rauch
  * Released under the MIT License.
  */
-(function webpackUniversalModuleDefinition(root, factory) {
-       if(typeof exports === 'object' && typeof module === 'object')
-               module.exports = factory();
-       else if(typeof define === 'function' && define.amd)
-               define([], factory);
-       else if(typeof exports === 'object')
-               exports["io"] = factory();
-       else
-               root["io"] = factory();
-})(this, function() {
-return /******/ (function(modules) { // webpackBootstrap
-/******/       // The module cache
-/******/       var installedModules = {};
-/******/
-/******/       // The require function
-/******/       function __webpack_require__(moduleId) {
-/******/
-/******/               // Check if module is in cache
-/******/               if(installedModules[moduleId])
-/******/                       return installedModules[moduleId].exports;
-/******/
-/******/               // Create a new module (and put it into the cache)
-/******/               var module = installedModules[moduleId] = {
-/******/                       exports: {},
-/******/                       id: moduleId,
-/******/                       loaded: false
-/******/               };
-/******/
-/******/               // Execute the module function
-/******/               modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
-/******/
-/******/               // Flag the module as loaded
-/******/               module.loaded = true;
-/******/
-/******/               // Return the exports of the module
-/******/               return module.exports;
-/******/       }
-/******/
-/******/
-/******/       // expose the modules object (__webpack_modules__)
-/******/       __webpack_require__.m = modules;
-/******/
-/******/       // expose the module cache
-/******/       __webpack_require__.c = installedModules;
-/******/
-/******/       // __webpack_public_path__
-/******/       __webpack_require__.p = "";
-/******/
-/******/       // Load entry module and return exports
-/******/       return __webpack_require__(0);
-/******/ })
-/************************************************************************/
-/******/ ([
-/* 0 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       
-       /**
-        * Module dependencies.
-        */
-       
-       var url = __webpack_require__(1);
-       var parser = __webpack_require__(7);
-       var Manager = __webpack_require__(12);
-       var debug = __webpack_require__(3)('socket.io-client');
-       
-       /**
-        * Module exports.
-        */
-       
-       module.exports = exports = lookup;
-       
-       /**
-        * Managers cache.
-        */
-       
-       var cache = exports.managers = {};
-       
-       /**
-        * Looks up an existing `Manager` for multiplexing.
-        * If the user summons:
-        *
-        *   `io('http://localhost/a');`
-        *   `io('http://localhost/b');`
-        *
-        * We reuse the existing instance based on same scheme/port/host,
-        * and we initialize sockets for each namespace.
-        *
-        * @api public
-        */
-       
-       function lookup (uri, opts) {
-         if (typeof uri === 'object') {
-           opts = uri;
-           uri = undefined;
-         }
-       
-         opts = opts || {};
-       
-         var parsed = url(uri);
-         var source = parsed.source;
-         var id = parsed.id;
-         var path = parsed.path;
-         var sameNamespace = cache[id] && path in cache[id].nsps;
-         var newConnection = opts.forceNew || opts['force new connection'] ||
-                             false === opts.multiplex || sameNamespace;
-       
-         var io;
-       
-         if (newConnection) {
-           debug('ignoring socket cache for %s', source);
-           io = Manager(source, opts);
-         } else {
-           if (!cache[id]) {
-             debug('new io instance for %s', source);
-             cache[id] = Manager(source, opts);
-           }
-           io = cache[id];
-         }
-         if (parsed.query && !opts.query) {
-           opts.query = parsed.query;
-         }
-         return io.socket(parsed.path, opts);
-       }
-       
-       /**
-        * Protocol version.
-        *
-        * @api public
-        */
-       
-       exports.protocol = parser.protocol;
-       
-       /**
-        * `connect`.
-        *
-        * @param {String} uri
-        * @api public
-        */
-       
-       exports.connect = lookup;
-       
-       /**
-        * Expose constructors for standalone build.
-        *
-        * @api public
-        */
-       
-       exports.Manager = __webpack_require__(12);
-       exports.Socket = __webpack_require__(37);
-
-
-/***/ }),
-/* 1 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       
-       /**
-        * Module dependencies.
-        */
-       
-       var parseuri = __webpack_require__(2);
-       var debug = __webpack_require__(3)('socket.io-client:url');
-       
-       /**
-        * Module exports.
-        */
-       
-       module.exports = url;
-       
-       /**
-        * URL parser.
-        *
-        * @param {String} url
-        * @param {Object} An object meant to mimic window.location.
-        *                 Defaults to window.location.
-        * @api public
-        */
-       
-       function url (uri, loc) {
-         var obj = uri;
-       
-         // default to window.location
-         loc = loc || (typeof location !== 'undefined' && location);
-         if (null == uri) uri = loc.protocol + '//' + loc.host;
-       
-         // relative path support
-         if ('string' === typeof uri) {
-           if ('/' === uri.charAt(0)) {
-             if ('/' === uri.charAt(1)) {
-               uri = loc.protocol + uri;
-             } else {
-               uri = loc.host + uri;
-             }
-           }
-       
-           if (!/^(https?|wss?):\/\//.test(uri)) {
-             debug('protocol-less url %s', uri);
-             if ('undefined' !== typeof loc) {
-               uri = loc.protocol + '//' + uri;
-             } else {
-               uri = 'https://' + uri;
-             }
-           }
-       
-           // parse
-           debug('parse %s', uri);
-           obj = parseuri(uri);
-         }
-       
-         // make sure we treat `localhost:80` and `localhost` equally
-         if (!obj.port) {
-           if (/^(http|ws)$/.test(obj.protocol)) {
-             obj.port = '80';
-           } else if (/^(http|ws)s$/.test(obj.protocol)) {
-             obj.port = '443';
-           }
-         }
-       
-         obj.path = obj.path || '/';
-       
-         var ipv6 = obj.host.indexOf(':') !== -1;
-         var host = ipv6 ? '[' + obj.host + ']' : obj.host;
-       
-         // define unique id
-         obj.id = obj.protocol + '://' + host + ':' + obj.port;
-         // define href
-         obj.href = obj.protocol + '://' + host + (loc && loc.port === obj.port ? '' : (':' + obj.port));
-       
-         return obj;
-       }
-
-
-/***/ }),
-/* 2 */
-/***/ (function(module, exports) {
-
-       /**
-        * Parses an URI
-        *
-        * @author Steven Levithan <stevenlevithan.com> (MIT license)
-        * @api private
-        */
-       
-       var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
-       
-       var parts = [
-           'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
-       ];
-       
-       module.exports = function parseuri(str) {
-           var src = str,
-               b = str.indexOf('['),
-               e = str.indexOf(']');
-       
-           if (b != -1 && e != -1) {
-               str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
-           }
-       
-           var m = re.exec(str || ''),
-               uri = {},
-               i = 14;
-       
-           while (i--) {
-               uri[parts[i]] = m[i] || '';
-           }
-       
-           if (b != -1 && e != -1) {
-               uri.source = src;
-               uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
-               uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
-               uri.ipv6uri = true;
-           }
-       
-           uri.pathNames = pathNames(uri, uri['path']);
-           uri.queryKey = queryKey(uri, uri['query']);
-       
-           return uri;
-       };
-       
-       function pathNames(obj, path) {
-           var regx = /\/{2,9}/g,
-               names = path.replace(regx, "/").split("/");
-       
-           if (path.substr(0, 1) == '/' || path.length === 0) {
-               names.splice(0, 1);
-           }
-           if (path.substr(path.length - 1, 1) == '/') {
-               names.splice(names.length - 1, 1);
-           }
-       
-           return names;
-       }
-       
-       function queryKey(uri, query) {
-           var data = {};
-       
-           query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
-               if ($1) {
-                   data[$1] = $2;
-               }
-           });
-       
-           return data;
-       }
-
-
-/***/ }),
-/* 3 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       /* WEBPACK VAR INJECTION */(function(process) {'use strict';
-       
-       var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
-       
-       /**
-        * This is the web browser implementation of `debug()`.
-        *
-        * Expose `debug()` as the module.
-        */
-       
-       exports = module.exports = __webpack_require__(5);
-       exports.log = log;
-       exports.formatArgs = formatArgs;
-       exports.save = save;
-       exports.load = load;
-       exports.useColors = useColors;
-       exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage();
-       
-       /**
-        * Colors.
-        */
-       
-       exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
-       
-       /**
-        * Currently only WebKit-based Web Inspectors, Firefox >= v31,
-        * and the Firebug extension (any Firefox version) are known
-        * to support "%c" CSS customizations.
-        *
-        * TODO: add a `localStorage` variable to explicitly enable/disable colors
-        */
-       
-       function useColors() {
-         // NB: In an Electron preload script, document will be defined but not fully
-         // initialized. Since we know we're in Chrome, we'll just detect this case
-         // explicitly
-         if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
-           return true;
-         }
-       
-         // Internet Explorer and Edge do not support colors.
-         if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
-           return false;
-         }
-       
-         // is webkit? http://stackoverflow.com/a/16459606/376773
-         // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
-         return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance ||
-         // is firebug? http://stackoverflow.com/a/398120/376773
-         typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) ||
-         // is firefox >= v31?
-         // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
-         typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 ||
-         // double check webkit in userAgent just in case we are in a worker
-         typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
-       }
-       
-       /**
-        * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
-        */
-       
-       exports.formatters.j = function (v) {
-         try {
-           return JSON.stringify(v);
-         } catch (err) {
-           return '[UnexpectedJSONParseError]: ' + err.message;
-         }
-       };
-       
-       /**
-        * Colorize log arguments if enabled.
-        *
-        * @api public
-        */
-       
-       function formatArgs(args) {
-         var useColors = this.useColors;
-       
-         args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff);
-       
-         if (!useColors) return;
-       
-         var c = 'color: ' + this.color;
-         args.splice(1, 0, c, 'color: inherit');
-       
-         // the final "%c" is somewhat tricky, because there could be other
-         // arguments passed either before or after the %c, so we need to
-         // figure out the correct index to insert the CSS into
-         var index = 0;
-         var lastC = 0;
-         args[0].replace(/%[a-zA-Z%]/g, function (match) {
-           if ('%%' === match) return;
-           index++;
-           if ('%c' === match) {
-             // we only are interested in the *last* %c
-             // (the user may have provided their own)
-             lastC = index;
-           }
-         });
-       
-         args.splice(lastC, 0, c);
-       }
-       
-       /**
-        * Invokes `console.log()` when available.
-        * No-op when `console.log` is not a "function".
-        *
-        * @api public
-        */
-       
-       function log() {
-         // this hackery is required for IE8/9, where
-         // the `console.log` function doesn't have 'apply'
-         return 'object' === (typeof console === 'undefined' ? 'undefined' : _typeof(console)) && console.log && Function.prototype.apply.call(console.log, console, arguments);
-       }
-       
-       /**
-        * Save `namespaces`.
-        *
-        * @param {String} namespaces
-        * @api private
-        */
-       
-       function save(namespaces) {
-         try {
-           if (null == namespaces) {
-             exports.storage.removeItem('debug');
-           } else {
-             exports.storage.debug = namespaces;
-           }
-         } catch (e) {}
-       }
-       
-       /**
-        * Load `namespaces`.
-        *
-        * @return {String} returns the previously persisted debug modes
-        * @api private
-        */
-       
-       function load() {
-         var r;
-         try {
-           r = exports.storage.debug;
-         } catch (e) {}
-       
-         // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
-         if (!r && typeof process !== 'undefined' && 'env' in process) {
-           r = process.env.DEBUG;
-         }
-       
-         return r;
-       }
-       
-       /**
-        * Enable namespaces listed in `localStorage.debug` initially.
-        */
-       
-       exports.enable(load());
-       
-       /**
-        * Localstorage attempts to return the localstorage.
-        *
-        * This is necessary because safari throws
-        * when a user disables cookies/localstorage
-        * and you attempt to access it.
-        *
-        * @return {LocalStorage}
-        * @api private
-        */
-       
-       function localstorage() {
-         try {
-           return window.localStorage;
-         } catch (e) {}
-       }
-       /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(4)))
-
-/***/ }),
-/* 4 */
-/***/ (function(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; };
-
-
-/***/ }),
-/* 5 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       'use strict';
-       
-       /**
-        * This is the common logic for both the Node.js and web browser
-        * implementations of `debug()`.
-        *
-        * Expose `debug()` as the module.
-        */
-       
-       exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
-       exports.coerce = coerce;
-       exports.disable = disable;
-       exports.enable = enable;
-       exports.enabled = enabled;
-       exports.humanize = __webpack_require__(6);
-       
-       /**
-        * Active `debug` instances.
-        */
-       exports.instances = [];
-       
-       /**
-        * The currently active debug mode names, and names to skip.
-        */
-       
-       exports.names = [];
-       exports.skips = [];
-       
-       /**
-        * Map of special "%n" handling functions, for the debug "format" argument.
-        *
-        * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
-        */
-       
-       exports.formatters = {};
-       
-       /**
-        * Select a color.
-        * @param {String} namespace
-        * @return {Number}
-        * @api private
-        */
-       
-       function selectColor(namespace) {
-         var hash = 0,
-             i;
-       
-         for (i in namespace) {
-           hash = (hash << 5) - hash + namespace.charCodeAt(i);
-           hash |= 0; // Convert to 32bit integer
-         }
-       
-         return exports.colors[Math.abs(hash) % exports.colors.length];
-       }
-       
-       /**
-        * Create a debugger with the given `namespace`.
-        *
-        * @param {String} namespace
-        * @return {Function}
-        * @api public
-        */
-       
-       function createDebug(namespace) {
-       
-         var prevTime;
-       
-         function debug() {
-           // disabled?
-           if (!debug.enabled) return;
-       
-           var self = debug;
-       
-           // set `diff` timestamp
-           var curr = +new Date();
-           var ms = curr - (prevTime || curr);
-           self.diff = ms;
-           self.prev = prevTime;
-           self.curr = curr;
-           prevTime = curr;
-       
-           // turn the `arguments` into a proper Array
-           var args = new Array(arguments.length);
-           for (var i = 0; i < args.length; i++) {
-             args[i] = arguments[i];
-           }
-       
-           args[0] = exports.coerce(args[0]);
-       
-           if ('string' !== typeof args[0]) {
-             // anything else let's inspect with %O
-             args.unshift('%O');
-           }
-       
-           // apply any `formatters` transformations
-           var index = 0;
-           args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
-             // if we encounter an escaped % then don't increase the array index
-             if (match === '%%') return match;
-             index++;
-             var formatter = exports.formatters[format];
-             if ('function' === typeof formatter) {
-               var val = args[index];
-               match = formatter.call(self, val);
-       
-               // now we need to remove `args[index]` since it's inlined in the `format`
-               args.splice(index, 1);
-               index--;
-             }
-             return match;
-           });
-       
-           // apply env-specific formatting (colors, etc.)
-           exports.formatArgs.call(self, args);
-       
-           var logFn = debug.log || exports.log || console.log.bind(console);
-           logFn.apply(self, args);
-         }
-       
-         debug.namespace = namespace;
-         debug.enabled = exports.enabled(namespace);
-         debug.useColors = exports.useColors();
-         debug.color = selectColor(namespace);
-         debug.destroy = destroy;
-       
-         // env-specific initialization logic for debug instances
-         if ('function' === typeof exports.init) {
-           exports.init(debug);
-         }
-       
-         exports.instances.push(debug);
-       
-         return debug;
-       }
-       
-       function destroy() {
-         var index = exports.instances.indexOf(this);
-         if (index !== -1) {
-           exports.instances.splice(index, 1);
-           return true;
-         } else {
-           return false;
-         }
-       }
-       
-       /**
-        * Enables a debug mode by namespaces. This can include modes
-        * separated by a colon and wildcards.
-        *
-        * @param {String} namespaces
-        * @api public
-        */
-       
-       function enable(namespaces) {
-         exports.save(namespaces);
-       
-         exports.names = [];
-         exports.skips = [];
-       
-         var i;
-         var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
-         var len = split.length;
-       
-         for (i = 0; i < len; i++) {
-           if (!split[i]) continue; // ignore empty strings
-           namespaces = split[i].replace(/\*/g, '.*?');
-           if (namespaces[0] === '-') {
-             exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
-           } else {
-             exports.names.push(new RegExp('^' + namespaces + '$'));
-           }
-         }
-       
-         for (i = 0; i < exports.instances.length; i++) {
-           var instance = exports.instances[i];
-           instance.enabled = exports.enabled(instance.namespace);
-         }
-       }
-       
-       /**
-        * Disable debug output.
-        *
-        * @api public
-        */
-       
-       function disable() {
-         exports.enable('');
-       }
-       
-       /**
-        * Returns true if the given mode name is enabled, false otherwise.
-        *
-        * @param {String} name
-        * @return {Boolean}
-        * @api public
-        */
-       
-       function enabled(name) {
-         if (name[name.length - 1] === '*') {
-           return true;
-         }
-         var i, len;
-         for (i = 0, len = exports.skips.length; i < len; i++) {
-           if (exports.skips[i].test(name)) {
-             return false;
-           }
-         }
-         for (i = 0, len = exports.names.length; i < len; i++) {
-           if (exports.names[i].test(name)) {
-             return true;
-           }
-         }
-         return false;
-       }
-       
-       /**
-        * Coerce `val`.
-        *
-        * @param {Mixed} val
-        * @return {Mixed}
-        * @api private
-        */
-       
-       function coerce(val) {
-         if (val instanceof Error) return val.stack || val.message;
-         return val;
-       }
-
-/***/ }),
-/* 6 */
-/***/ (function(module, exports) {
-
-       /**
-        * Helpers.
-        */
-       
-       var s = 1000;
-       var m = s * 60;
-       var h = m * 60;
-       var d = h * 24;
-       var y = d * 365.25;
-       
-       /**
-        * Parse or format the given `val`.
-        *
-        * Options:
-        *
-        *  - `long` verbose formatting [false]
-        *
-        * @param {String|Number} val
-        * @param {Object} [options]
-        * @throws {Error} throw an error if val is not a non-empty string or a number
-        * @return {String|Number}
-        * @api public
-        */
-       
-       module.exports = function(val, options) {
-         options = options || {};
-         var type = typeof val;
-         if (type === 'string' && val.length > 0) {
-           return parse(val);
-         } else if (type === 'number' && isNaN(val) === false) {
-           return options.long ? fmtLong(val) : fmtShort(val);
-         }
-         throw new Error(
-           'val is not a non-empty string or a valid number. val=' +
-             JSON.stringify(val)
-         );
-       };
-       
-       /**
-        * Parse the given `str` and return milliseconds.
-        *
-        * @param {String} str
-        * @return {Number}
-        * @api private
-        */
-       
-       function parse(str) {
-         str = String(str);
-         if (str.length > 100) {
-           return;
-         }
-         var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
-           str
-         );
-         if (!match) {
-           return;
-         }
-         var n = parseFloat(match[1]);
-         var type = (match[2] || 'ms').toLowerCase();
-         switch (type) {
-           case 'years':
-           case 'year':
-           case 'yrs':
-           case 'yr':
-           case 'y':
-             return n * y;
-           case 'days':
-           case 'day':
-           case 'd':
-             return n * d;
-           case 'hours':
-           case 'hour':
-           case 'hrs':
-           case 'hr':
-           case 'h':
-             return n * h;
-           case 'minutes':
-           case 'minute':
-           case 'mins':
-           case 'min':
-           case 'm':
-             return n * m;
-           case 'seconds':
-           case 'second':
-           case 'secs':
-           case 'sec':
-           case 's':
-             return n * s;
-           case 'milliseconds':
-           case 'millisecond':
-           case 'msecs':
-           case 'msec':
-           case 'ms':
-             return n;
-           default:
-             return undefined;
-         }
-       }
-       
-       /**
-        * Short format for `ms`.
-        *
-        * @param {Number} ms
-        * @return {String}
-        * @api private
-        */
-       
-       function fmtShort(ms) {
-         if (ms >= d) {
-           return Math.round(ms / d) + 'd';
-         }
-         if (ms >= h) {
-           return Math.round(ms / h) + 'h';
-         }
-         if (ms >= m) {
-           return Math.round(ms / m) + 'm';
-         }
-         if (ms >= s) {
-           return Math.round(ms / s) + 's';
-         }
-         return ms + 'ms';
-       }
-       
-       /**
-        * Long format for `ms`.
-        *
-        * @param {Number} ms
-        * @return {String}
-        * @api private
-        */
-       
-       function fmtLong(ms) {
-         return plural(ms, d, 'day') ||
-           plural(ms, h, 'hour') ||
-           plural(ms, m, 'minute') ||
-           plural(ms, s, 'second') ||
-           ms + ' ms';
-       }
-       
-       /**
-        * Pluralization helper.
-        */
-       
-       function plural(ms, n, name) {
-         if (ms < n) {
-           return;
-         }
-         if (ms < n * 1.5) {
-           return Math.floor(ms / n) + ' ' + name;
-         }
-         return Math.ceil(ms / n) + ' ' + name + 's';
-       }
-
-
-/***/ }),
-/* 7 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       
-       /**
-        * Module dependencies.
-        */
-       
-       var debug = __webpack_require__(3)('socket.io-parser');
-       var Emitter = __webpack_require__(8);
-       var binary = __webpack_require__(9);
-       var isArray = __webpack_require__(10);
-       var isBuf = __webpack_require__(11);
-       
-       /**
-        * Protocol version.
-        *
-        * @api public
-        */
-       
-       exports.protocol = 4;
-       
-       /**
-        * Packet types.
-        *
-        * @api public
-        */
-       
-       exports.types = [
-         'CONNECT',
-         'DISCONNECT',
-         'EVENT',
-         'ACK',
-         'ERROR',
-         'BINARY_EVENT',
-         'BINARY_ACK'
-       ];
-       
-       /**
-        * Packet type `connect`.
-        *
-        * @api public
-        */
-       
-       exports.CONNECT = 0;
-       
-       /**
-        * Packet type `disconnect`.
-        *
-        * @api public
-        */
-       
-       exports.DISCONNECT = 1;
-       
-       /**
-        * Packet type `event`.
-        *
-        * @api public
-        */
-       
-       exports.EVENT = 2;
-       
-       /**
-        * Packet type `ack`.
-        *
-        * @api public
-        */
-       
-       exports.ACK = 3;
-       
-       /**
-        * Packet type `error`.
-        *
-        * @api public
-        */
-       
-       exports.ERROR = 4;
-       
-       /**
-        * Packet type 'binary event'
-        *
-        * @api public
-        */
-       
-       exports.BINARY_EVENT = 5;
-       
-       /**
-        * Packet type `binary ack`. For acks with binary arguments.
-        *
-        * @api public
-        */
-       
-       exports.BINARY_ACK = 6;
-       
-       /**
-        * Encoder constructor.
-        *
-        * @api public
-        */
-       
-       exports.Encoder = Encoder;
-       
-       /**
-        * Decoder constructor.
-        *
-        * @api public
-        */
-       
-       exports.Decoder = Decoder;
-       
-       /**
-        * A socket.io Encoder instance
-        *
-        * @api public
-        */
-       
-       function Encoder() {}
-       
-       var ERROR_PACKET = exports.ERROR + '"encode error"';
-       
-       /**
-        * Encode a packet as a single string if non-binary, or as a
-        * buffer sequence, depending on packet type.
-        *
-        * @param {Object} obj - packet object
-        * @param {Function} callback - function to handle encodings (likely engine.write)
-        * @return Calls callback with Array of encodings
-        * @api public
-        */
-       
-       Encoder.prototype.encode = function(obj, callback){
-         debug('encoding packet %j', obj);
-       
-         if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) {
-           encodeAsBinary(obj, callback);
-         } else {
-           var encoding = encodeAsString(obj);
-           callback([encoding]);
-         }
-       };
-       
-       /**
-        * Encode packet as string.
-        *
-        * @param {Object} packet
-        * @return {String} encoded
-        * @api private
-        */
-       
-       function encodeAsString(obj) {
-       
-         // first is type
-         var str = '' + obj.type;
-       
-         // attachments if we have them
-         if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) {
-           str += obj.attachments + '-';
-         }
-       
-         // if we have a namespace other than `/`
-         // we append it followed by a comma `,`
-         if (obj.nsp && '/' !== obj.nsp) {
-           str += obj.nsp + ',';
-         }
-       
-         // immediately followed by the id
-         if (null != obj.id) {
-           str += obj.id;
-         }
-       
-         // json data
-         if (null != obj.data) {
-           var payload = tryStringify(obj.data);
-           if (payload !== false) {
-             str += payload;
-           } else {
-             return ERROR_PACKET;
-           }
-         }
-       
-         debug('encoded %j as %s', obj, str);
-         return str;
-       }
-       
-       function tryStringify(str) {
-         try {
-           return JSON.stringify(str);
-         } catch(e){
-           return false;
-         }
-       }
-       
-       /**
-        * Encode packet as 'buffer sequence' by removing blobs, and
-        * deconstructing packet into object with placeholders and
-        * a list of buffers.
-        *
-        * @param {Object} packet
-        * @return {Buffer} encoded
-        * @api private
-        */
-       
-       function encodeAsBinary(obj, callback) {
-       
-         function writeEncoding(bloblessData) {
-           var deconstruction = binary.deconstructPacket(bloblessData);
-           var pack = encodeAsString(deconstruction.packet);
-           var buffers = deconstruction.buffers;
-       
-           buffers.unshift(pack); // add packet info to beginning of data list
-           callback(buffers); // write all the buffers
-         }
-       
-         binary.removeBlobs(obj, writeEncoding);
-       }
-       
-       /**
-        * A socket.io Decoder instance
-        *
-        * @return {Object} decoder
-        * @api public
-        */
-       
-       function Decoder() {
-         this.reconstructor = null;
-       }
-       
-       /**
-        * Mix in `Emitter` with Decoder.
-        */
-       
-       Emitter(Decoder.prototype);
-       
-       /**
-        * Decodes an encoded packet string into packet JSON.
-        *
-        * @param {String} obj - encoded packet
-        * @return {Object} packet
-        * @api public
-        */
-       
-       Decoder.prototype.add = function(obj) {
-         var packet;
-         if (typeof obj === 'string') {
-           packet = decodeString(obj);
-           if (exports.BINARY_EVENT === packet.type || exports.BINARY_ACK === packet.type) { // binary packet's json
-             this.reconstructor = new BinaryReconstructor(packet);
-       
-             // no attachments, labeled binary but no binary data to follow
-             if (this.reconstructor.reconPack.attachments === 0) {
-               this.emit('decoded', packet);
-             }
-           } else { // non-binary full packet
-             this.emit('decoded', packet);
-           }
-         } else if (isBuf(obj) || obj.base64) { // raw binary data
-           if (!this.reconstructor) {
-             throw new Error('got binary data when not reconstructing a packet');
-           } else {
-             packet = this.reconstructor.takeBinaryData(obj);
-             if (packet) { // received final buffer
-               this.reconstructor = null;
-               this.emit('decoded', packet);
-             }
-           }
-         } else {
-           throw new Error('Unknown type: ' + obj);
-         }
-       };
-       
-       /**
-        * Decode a packet String (JSON data)
-        *
-        * @param {String} str
-        * @return {Object} packet
-        * @api private
-        */
-       
-       function decodeString(str) {
-         var i = 0;
-         // look up type
-         var p = {
-           type: Number(str.charAt(0))
-         };
-       
-         if (null == exports.types[p.type]) {
-           return error('unknown packet type ' + p.type);
-         }
-       
-         // look up attachments if type binary
-         if (exports.BINARY_EVENT === p.type || exports.BINARY_ACK === p.type) {
-           var buf = '';
-           while (str.charAt(++i) !== '-') {
-             buf += str.charAt(i);
-             if (i == str.length) break;
-           }
-           if (buf != Number(buf) || str.charAt(i) !== '-') {
-             throw new Error('Illegal attachments');
-           }
-           p.attachments = Number(buf);
-         }
-       
-         // look up namespace (if any)
-         if ('/' === str.charAt(i + 1)) {
-           p.nsp = '';
-           while (++i) {
-             var c = str.charAt(i);
-             if (',' === c) break;
-             p.nsp += c;
-             if (i === str.length) break;
-           }
-         } else {
-           p.nsp = '/';
-         }
-       
-         // look up id
-         var next = str.charAt(i + 1);
-         if ('' !== next && Number(next) == next) {
-           p.id = '';
-           while (++i) {
-             var c = str.charAt(i);
-             if (null == c || Number(c) != c) {
-               --i;
-               break;
-             }
-             p.id += str.charAt(i);
-             if (i === str.length) break;
-           }
-           p.id = Number(p.id);
-         }
-       
-         // look up json data
-         if (str.charAt(++i)) {
-           var payload = tryParse(str.substr(i));
-           var isPayloadValid = payload !== false && (p.type === exports.ERROR || isArray(payload));
-           if (isPayloadValid) {
-             p.data = payload;
-           } else {
-             return error('invalid payload');
-           }
-         }
-       
-         debug('decoded %s as %j', str, p);
-         return p;
-       }
-       
-       function tryParse(str) {
-         try {
-           return JSON.parse(str);
-         } catch(e){
-           return false;
-         }
-       }
-       
-       /**
-        * Deallocates a parser's resources
-        *
-        * @api public
-        */
-       
-       Decoder.prototype.destroy = function() {
-         if (this.reconstructor) {
-           this.reconstructor.finishedReconstruction();
-         }
-       };
-       
-       /**
-        * A manager of a binary event's 'buffer sequence'. Should
-        * be constructed whenever a packet of type BINARY_EVENT is
-        * decoded.
-        *
-        * @param {Object} packet
-        * @return {BinaryReconstructor} initialized reconstructor
-        * @api private
-        */
-       
-       function BinaryReconstructor(packet) {
-         this.reconPack = packet;
-         this.buffers = [];
-       }
-       
-       /**
-        * Method to be called when binary data received from connection
-        * after a BINARY_EVENT packet.
-        *
-        * @param {Buffer | ArrayBuffer} binData - the raw binary data received
-        * @return {null | Object} returns null if more binary data is expected or
-        *   a reconstructed packet object if all buffers have been received.
-        * @api private
-        */
-       
-       BinaryReconstructor.prototype.takeBinaryData = function(binData) {
-         this.buffers.push(binData);
-         if (this.buffers.length === this.reconPack.attachments) { // done with buffer list
-           var packet = binary.reconstructPacket(this.reconPack, this.buffers);
-           this.finishedReconstruction();
-           return packet;
-         }
-         return null;
-       };
-       
-       /**
-        * Cleans up binary packet reconstruction variables.
-        *
-        * @api private
-        */
-       
-       BinaryReconstructor.prototype.finishedReconstruction = function() {
-         this.reconPack = null;
-         this.buffers = [];
-       };
-       
-       function error(msg) {
-         return {
-           type: exports.ERROR,
-           data: 'parser error: ' + msg
-         };
-       }
-
-
-/***/ }),
-/* 8 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       
-       /**
-        * Expose `Emitter`.
-        */
-       
-       if (true) {
-         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;
-       };
-
-
-/***/ }),
-/* 9 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       /*global Blob,File*/
-       
-       /**
-        * Module requirements
-        */
-       
-       var isArray = __webpack_require__(10);
-       var isBuf = __webpack_require__(11);
-       var toString = Object.prototype.toString;
-       var withNativeBlob = typeof Blob === 'function' || (typeof Blob !== 'undefined' && toString.call(Blob) === '[object BlobConstructor]');
-       var withNativeFile = typeof File === 'function' || (typeof File !== 'undefined' && toString.call(File) === '[object FileConstructor]');
-       
-       /**
-        * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
-        * Anything with blobs or files should be fed through removeBlobs before coming
-        * here.
-        *
-        * @param {Object} packet - socket.io event packet
-        * @return {Object} with deconstructed packet and list of buffers
-        * @api public
-        */
-       
-       exports.deconstructPacket = function(packet) {
-         var buffers = [];
-         var packetData = packet.data;
-         var pack = packet;
-         pack.data = _deconstructPacket(packetData, buffers);
-         pack.attachments = buffers.length; // number of binary 'attachments'
-         return {packet: pack, buffers: buffers};
-       };
-       
-       function _deconstructPacket(data, buffers) {
-         if (!data) return data;
-       
-         if (isBuf(data)) {
-           var placeholder = { _placeholder: true, num: buffers.length };
-           buffers.push(data);
-           return placeholder;
-         } else if (isArray(data)) {
-           var newData = new Array(data.length);
-           for (var i = 0; i < data.length; i++) {
-             newData[i] = _deconstructPacket(data[i], buffers);
-           }
-           return newData;
-         } else if (typeof data === 'object' && !(data instanceof Date)) {
-           var newData = {};
-           for (var key in data) {
-             newData[key] = _deconstructPacket(data[key], buffers);
-           }
-           return newData;
-         }
-         return data;
-       }
-       
-       /**
-        * Reconstructs a binary packet from its placeholder packet and buffers
-        *
-        * @param {Object} packet - event packet with placeholders
-        * @param {Array} buffers - binary buffers to put in placeholder positions
-        * @return {Object} reconstructed packet
-        * @api public
-        */
-       
-       exports.reconstructPacket = function(packet, buffers) {
-         packet.data = _reconstructPacket(packet.data, buffers);
-         packet.attachments = undefined; // no longer useful
-         return packet;
-       };
-       
-       function _reconstructPacket(data, buffers) {
-         if (!data) return data;
-       
-         if (data && data._placeholder) {
-           return buffers[data.num]; // appropriate buffer (should be natural order anyway)
-         } else if (isArray(data)) {
-           for (var i = 0; i < data.length; i++) {
-             data[i] = _reconstructPacket(data[i], buffers);
-           }
-         } else if (typeof data === 'object') {
-           for (var key in data) {
-             data[key] = _reconstructPacket(data[key], buffers);
-           }
-         }
-       
-         return data;
-       }
-       
-       /**
-        * Asynchronously removes Blobs or Files from data via
-        * FileReader's readAsArrayBuffer method. Used before encoding
-        * data as msgpack. Calls callback with the blobless data.
-        *
-        * @param {Object} data
-        * @param {Function} callback
-        * @api private
-        */
-       
-       exports.removeBlobs = function(data, callback) {
-         function _removeBlobs(obj, curKey, containingObject) {
-           if (!obj) return obj;
-       
-           // convert any blob
-           if ((withNativeBlob && obj instanceof Blob) ||
-               (withNativeFile && obj instanceof File)) {
-             pendingBlobs++;
-       
-             // async filereader
-             var fileReader = new FileReader();
-             fileReader.onload = function() { // this.result == arraybuffer
-               if (containingObject) {
-                 containingObject[curKey] = this.result;
-               }
-               else {
-                 bloblessData = this.result;
-               }
-       
-               // if nothing pending its callback time
-               if(! --pendingBlobs) {
-                 callback(bloblessData);
-               }
-             };
-       
-             fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
-           } else if (isArray(obj)) { // handle array
-             for (var i = 0; i < obj.length; i++) {
-               _removeBlobs(obj[i], i, obj);
-             }
-           } else if (typeof obj === 'object' && !isBuf(obj)) { // and object
-             for (var key in obj) {
-               _removeBlobs(obj[key], key, obj);
-             }
-           }
-         }
-       
-         var pendingBlobs = 0;
-         var bloblessData = data;
-         _removeBlobs(bloblessData);
-         if (!pendingBlobs) {
-           callback(bloblessData);
-         }
-       };
-
-
-/***/ }),
-/* 10 */
-/***/ (function(module, exports) {
-
-       var toString = {}.toString;
-       
-       module.exports = Array.isArray || function (arr) {
-         return toString.call(arr) == '[object Array]';
-       };
-
-
-/***/ }),
-/* 11 */
-/***/ (function(module, exports) {
-
-       
-       module.exports = isBuf;
-       
-       var withNativeBuffer = typeof Buffer === 'function' && typeof Buffer.isBuffer === 'function';
-       var withNativeArrayBuffer = typeof ArrayBuffer === 'function';
-       
-       var isView = function (obj) {
-         return typeof ArrayBuffer.isView === 'function' ? ArrayBuffer.isView(obj) : (obj.buffer instanceof ArrayBuffer);
-       };
-       
-       /**
-        * Returns true if obj is a buffer or an arraybuffer.
-        *
-        * @api private
-        */
-       
-       function isBuf(obj) {
-         return (withNativeBuffer && Buffer.isBuffer(obj)) ||
-                 (withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj)));
-       }
-
-
-/***/ }),
-/* 12 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       
-       /**
-        * Module dependencies.
-        */
-       
-       var eio = __webpack_require__(13);
-       var Socket = __webpack_require__(37);
-       var Emitter = __webpack_require__(8);
-       var parser = __webpack_require__(7);
-       var on = __webpack_require__(39);
-       var bind = __webpack_require__(40);
-       var debug = __webpack_require__(3)('socket.io-client:manager');
-       var indexOf = __webpack_require__(36);
-       var Backoff = __webpack_require__(41);
-       
-       /**
-        * IE6+ hasOwnProperty
-        */
-       
-       var has = Object.prototype.hasOwnProperty;
-       
-       /**
-        * Module exports
-        */
-       
-       module.exports = Manager;
-       
-       /**
-        * `Manager` constructor.
-        *
-        * @param {String} engine instance or engine uri/opts
-        * @param {Object} options
-        * @api public
-        */
-       
-       function Manager (uri, opts) {
-         if (!(this instanceof Manager)) return new Manager(uri, opts);
-         if (uri && ('object' === typeof uri)) {
-           opts = uri;
-           uri = undefined;
-         }
-         opts = opts || {};
-       
-         opts.path = opts.path || '/socket.io';
-         this.nsps = {};
-         this.subs = [];
-         this.opts = opts;
-         this.reconnection(opts.reconnection !== false);
-         this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
-         this.reconnectionDelay(opts.reconnectionDelay || 1000);
-         this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
-         this.randomizationFactor(opts.randomizationFactor || 0.5);
-         this.backoff = new Backoff({
-           min: this.reconnectionDelay(),
-           max: this.reconnectionDelayMax(),
-           jitter: this.randomizationFactor()
-         });
-         this.timeout(null == opts.timeout ? 20000 : opts.timeout);
-         this.readyState = 'closed';
-         this.uri = uri;
-         this.connecting = [];
-         this.lastPing = null;
-         this.encoding = false;
-         this.packetBuffer = [];
-         var _parser = opts.parser || parser;
-         this.encoder = new _parser.Encoder();
-         this.decoder = new _parser.Decoder();
-         this.autoConnect = opts.autoConnect !== false;
-         if (this.autoConnect) this.open();
-       }
-       
-       /**
-        * Propagate given event to sockets and emit on `this`
-        *
-        * @api private
-        */
-       
-       Manager.prototype.emitAll = function () {
-         this.emit.apply(this, arguments);
-         for (var nsp in this.nsps) {
-           if (has.call(this.nsps, nsp)) {
-             this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
-           }
-         }
-       };
-       
-       /**
-        * Update `socket.id` of all sockets
-        *
-        * @api private
-        */
-       
-       Manager.prototype.updateSocketIds = function () {
-         for (var nsp in this.nsps) {
-           if (has.call(this.nsps, nsp)) {
-             this.nsps[nsp].id = this.generateId(nsp);
-           }
-         }
-       };
-       
-       /**
-        * generate `socket.id` for the given `nsp`
-        *
-        * @param {String} nsp
-        * @return {String}
-        * @api private
-        */
-       
-       Manager.prototype.generateId = function (nsp) {
-         return (nsp === '/' ? '' : (nsp + '#')) + this.engine.id;
-       };
-       
-       /**
-        * Mix in `Emitter`.
-        */
-       
-       Emitter(Manager.prototype);
-       
-       /**
-        * Sets the `reconnection` config.
-        *
-        * @param {Boolean} true/false if it should automatically reconnect
-        * @return {Manager} self or value
-        * @api public
-        */
-       
-       Manager.prototype.reconnection = function (v) {
-         if (!arguments.length) return this._reconnection;
-         this._reconnection = !!v;
-         return this;
-       };
-       
-       /**
-        * Sets the reconnection attempts config.
-        *
-        * @param {Number} max reconnection attempts before giving up
-        * @return {Manager} self or value
-        * @api public
-        */
-       
-       Manager.prototype.reconnectionAttempts = function (v) {
-         if (!arguments.length) return this._reconnectionAttempts;
-         this._reconnectionAttempts = v;
-         return this;
-       };
-       
-       /**
-        * Sets the delay between reconnections.
-        *
-        * @param {Number} delay
-        * @return {Manager} self or value
-        * @api public
-        */
-       
-       Manager.prototype.reconnectionDelay = function (v) {
-         if (!arguments.length) return this._reconnectionDelay;
-         this._reconnectionDelay = v;
-         this.backoff && this.backoff.setMin(v);
-         return this;
-       };
-       
-       Manager.prototype.randomizationFactor = function (v) {
-         if (!arguments.length) return this._randomizationFactor;
-         this._randomizationFactor = v;
-         this.backoff && this.backoff.setJitter(v);
-         return this;
-       };
-       
-       /**
-        * Sets the maximum delay between reconnections.
-        *
-        * @param {Number} delay
-        * @return {Manager} self or value
-        * @api public
-        */
-       
-       Manager.prototype.reconnectionDelayMax = function (v) {
-         if (!arguments.length) return this._reconnectionDelayMax;
-         this._reconnectionDelayMax = v;
-         this.backoff && this.backoff.setMax(v);
-         return this;
-       };
-       
-       /**
-        * Sets the connection timeout. `false` to disable
-        *
-        * @return {Manager} self or value
-        * @api public
-        */
-       
-       Manager.prototype.timeout = function (v) {
-         if (!arguments.length) return this._timeout;
-         this._timeout = v;
-         return this;
-       };
-       
-       /**
-        * Starts trying to reconnect if reconnection is enabled and we have not
-        * started reconnecting yet
-        *
-        * @api private
-        */
-       
-       Manager.prototype.maybeReconnectOnOpen = function () {
-         // Only try to reconnect if it's the first time we're connecting
-         if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
-           // keeps reconnection from firing twice for the same reconnection loop
-           this.reconnect();
-         }
-       };
-       
-       /**
-        * Sets the current transport `socket`.
-        *
-        * @param {Function} optional, callback
-        * @return {Manager} self
-        * @api public
-        */
-       
-       Manager.prototype.open =
-       Manager.prototype.connect = function (fn, opts) {
-         debug('readyState %s', this.readyState);
-         if (~this.readyState.indexOf('open')) return this;
-       
-         debug('opening %s', this.uri);
-         this.engine = eio(this.uri, this.opts);
-         var socket = this.engine;
-         var self = this;
-         this.readyState = 'opening';
-         this.skipReconnect = false;
-       
-         // emit `open`
-         var openSub = on(socket, 'open', function () {
-           self.onopen();
-           fn && fn();
-         });
-       
-         // emit `connect_error`
-         var errorSub = on(socket, 'error', function (data) {
-           debug('connect_error');
-           self.cleanup();
-           self.readyState = 'closed';
-           self.emitAll('connect_error', data);
-           if (fn) {
-             var err = new Error('Connection error');
-             err.data = data;
-             fn(err);
-           } else {
-             // Only do this if there is no fn to handle the error
-             self.maybeReconnectOnOpen();
-           }
-         });
-       
-         // emit `connect_timeout`
-         if (false !== this._timeout) {
-           var timeout = this._timeout;
-           debug('connect attempt will timeout after %d', timeout);
-       
-           if (timeout === 0) {
-             openSub.destroy(); // prevents a race condition with the 'open' event
-           }
-       
-           // set timer
-           var timer = setTimeout(function () {
-             debug('connect attempt timed out after %d', timeout);
-             openSub.destroy();
-             socket.close();
-             socket.emit('error', 'timeout');
-             self.emitAll('connect_timeout', timeout);
-           }, timeout);
-       
-           this.subs.push({
-             destroy: function () {
-               clearTimeout(timer);
-             }
-           });
-         }
-       
-         this.subs.push(openSub);
-         this.subs.push(errorSub);
-       
-         return this;
-       };
-       
-       /**
-        * Called upon transport open.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.onopen = function () {
-         debug('open');
-       
-         // clear old subs
-         this.cleanup();
-       
-         // mark as open
-         this.readyState = 'open';
-         this.emit('open');
-       
-         // add new subs
-         var socket = this.engine;
-         this.subs.push(on(socket, 'data', bind(this, 'ondata')));
-         this.subs.push(on(socket, 'ping', bind(this, 'onping')));
-         this.subs.push(on(socket, 'pong', bind(this, 'onpong')));
-         this.subs.push(on(socket, 'error', bind(this, 'onerror')));
-         this.subs.push(on(socket, 'close', bind(this, 'onclose')));
-         this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
-       };
-       
-       /**
-        * Called upon a ping.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.onping = function () {
-         this.lastPing = new Date();
-         this.emitAll('ping');
-       };
-       
-       /**
-        * Called upon a packet.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.onpong = function () {
-         this.emitAll('pong', new Date() - this.lastPing);
-       };
-       
-       /**
-        * Called with data.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.ondata = function (data) {
-         this.decoder.add(data);
-       };
-       
-       /**
-        * Called when parser fully decodes a packet.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.ondecoded = function (packet) {
-         this.emit('packet', packet);
-       };
-       
-       /**
-        * Called upon socket error.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.onerror = function (err) {
-         debug('error', err);
-         this.emitAll('error', err);
-       };
-       
-       /**
-        * Creates a new socket for the given `nsp`.
-        *
-        * @return {Socket}
-        * @api public
-        */
-       
-       Manager.prototype.socket = function (nsp, opts) {
-         var socket = this.nsps[nsp];
-         if (!socket) {
-           socket = new Socket(this, nsp, opts);
-           this.nsps[nsp] = socket;
-           var self = this;
-           socket.on('connecting', onConnecting);
-           socket.on('connect', function () {
-             socket.id = self.generateId(nsp);
-           });
-       
-           if (this.autoConnect) {
-             // manually call here since connecting event is fired before listening
-             onConnecting();
-           }
-         }
-       
-         function onConnecting () {
-           if (!~indexOf(self.connecting, socket)) {
-             self.connecting.push(socket);
-           }
-         }
-       
-         return socket;
-       };
-       
-       /**
-        * Called upon a socket close.
-        *
-        * @param {Socket} socket
-        */
-       
-       Manager.prototype.destroy = function (socket) {
-         var index = indexOf(this.connecting, socket);
-         if (~index) this.connecting.splice(index, 1);
-         if (this.connecting.length) return;
-       
-         this.close();
-       };
-       
-       /**
-        * Writes a packet.
-        *
-        * @param {Object} packet
-        * @api private
-        */
-       
-       Manager.prototype.packet = function (packet) {
-         debug('writing packet %j', packet);
-         var self = this;
-         if (packet.query && packet.type === 0) packet.nsp += '?' + packet.query;
-       
-         if (!self.encoding) {
-           // encode, then write to engine with result
-           self.encoding = true;
-           this.encoder.encode(packet, function (encodedPackets) {
-             for (var i = 0; i < encodedPackets.length; i++) {
-               self.engine.write(encodedPackets[i], packet.options);
-             }
-             self.encoding = false;
-             self.processPacketQueue();
-           });
-         } else { // add packet to the queue
-           self.packetBuffer.push(packet);
-         }
-       };
-       
-       /**
-        * If packet buffer is non-empty, begins encoding the
-        * next packet in line.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.processPacketQueue = function () {
-         if (this.packetBuffer.length > 0 && !this.encoding) {
-           var pack = this.packetBuffer.shift();
-           this.packet(pack);
-         }
-       };
-       
-       /**
-        * Clean up transport subscriptions and packet buffer.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.cleanup = function () {
-         debug('cleanup');
-       
-         var subsLength = this.subs.length;
-         for (var i = 0; i < subsLength; i++) {
-           var sub = this.subs.shift();
-           sub.destroy();
-         }
-       
-         this.packetBuffer = [];
-         this.encoding = false;
-         this.lastPing = null;
-       
-         this.decoder.destroy();
-       };
-       
-       /**
-        * Close the current socket.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.close =
-       Manager.prototype.disconnect = function () {
-         debug('disconnect');
-         this.skipReconnect = true;
-         this.reconnecting = false;
-         if ('opening' === this.readyState) {
-           // `onclose` will not fire because
-           // an open event never happened
-           this.cleanup();
-         }
-         this.backoff.reset();
-         this.readyState = 'closed';
-         if (this.engine) this.engine.close();
-       };
-       
-       /**
-        * Called upon engine close.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.onclose = function (reason) {
-         debug('onclose');
-       
-         this.cleanup();
-         this.backoff.reset();
-         this.readyState = 'closed';
-         this.emit('close', reason);
-       
-         if (this._reconnection && !this.skipReconnect) {
-           this.reconnect();
-         }
-       };
-       
-       /**
-        * Attempt a reconnection.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.reconnect = function () {
-         if (this.reconnecting || this.skipReconnect) return this;
-       
-         var self = this;
-       
-         if (this.backoff.attempts >= this._reconnectionAttempts) {
-           debug('reconnect failed');
-           this.backoff.reset();
-           this.emitAll('reconnect_failed');
-           this.reconnecting = false;
-         } else {
-           var delay = this.backoff.duration();
-           debug('will wait %dms before reconnect attempt', delay);
-       
-           this.reconnecting = true;
-           var timer = setTimeout(function () {
-             if (self.skipReconnect) return;
-       
-             debug('attempting reconnect');
-             self.emitAll('reconnect_attempt', self.backoff.attempts);
-             self.emitAll('reconnecting', self.backoff.attempts);
-       
-             // check again for the case socket closed in above events
-             if (self.skipReconnect) return;
-       
-             self.open(function (err) {
-               if (err) {
-                 debug('reconnect attempt error');
-                 self.reconnecting = false;
-                 self.reconnect();
-                 self.emitAll('reconnect_error', err.data);
-               } else {
-                 debug('reconnect success');
-                 self.onreconnect();
-               }
-             });
-           }, delay);
-       
-           this.subs.push({
-             destroy: function () {
-               clearTimeout(timer);
-             }
-           });
-         }
-       };
-       
-       /**
-        * Called upon successful reconnect.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.onreconnect = function () {
-         var attempt = this.backoff.attempts;
-         this.reconnecting = false;
-         this.backoff.reset();
-         this.updateSocketIds();
-         this.emitAll('reconnect', attempt);
-       };
-
-
-/***/ }),
-/* 13 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       
-       module.exports = __webpack_require__(14);
-       
-       /**
-        * Exports parser
-        *
-        * @api public
-        *
-        */
-       module.exports.parser = __webpack_require__(22);
-
-
-/***/ }),
-/* 14 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       /**
-        * Module dependencies.
-        */
-       
-       var transports = __webpack_require__(15);
-       var Emitter = __webpack_require__(8);
-       var debug = __webpack_require__(3)('engine.io-client:socket');
-       var index = __webpack_require__(36);
-       var parser = __webpack_require__(22);
-       var parseuri = __webpack_require__(2);
-       var parseqs = __webpack_require__(30);
-       
-       /**
-        * Module exports.
-        */
-       
-       module.exports = Socket;
-       
-       /**
-        * Socket constructor.
-        *
-        * @param {String|Object} uri or options
-        * @param {Object} options
-        * @api public
-        */
-       
-       function Socket (uri, opts) {
-         if (!(this instanceof Socket)) return new Socket(uri, opts);
-       
-         opts = opts || {};
-       
-         if (uri && 'object' === typeof uri) {
-           opts = uri;
-           uri = null;
-         }
-       
-         if (uri) {
-           uri = parseuri(uri);
-           opts.hostname = uri.host;
-           opts.secure = uri.protocol === 'https' || uri.protocol === 'wss';
-           opts.port = uri.port;
-           if (uri.query) opts.query = uri.query;
-         } else if (opts.host) {
-           opts.hostname = parseuri(opts.host).host;
-         }
-       
-         this.secure = null != opts.secure ? opts.secure
-           : (typeof location !== 'undefined' && 'https:' === location.protocol);
-       
-         if (opts.hostname && !opts.port) {
-           // if no port is specified manually, use the protocol default
-           opts.port = this.secure ? '443' : '80';
-         }
-       
-         this.agent = opts.agent || false;
-         this.hostname = opts.hostname ||
-           (typeof location !== 'undefined' ? location.hostname : 'localhost');
-         this.port = opts.port || (typeof location !== 'undefined' && location.port
-             ? location.port
-             : (this.secure ? 443 : 80));
-         this.query = opts.query || {};
-         if ('string' === typeof this.query) this.query = parseqs.decode(this.query);
-         this.upgrade = false !== opts.upgrade;
-         this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
-         this.forceJSONP = !!opts.forceJSONP;
-         this.jsonp = false !== opts.jsonp;
-         this.forceBase64 = !!opts.forceBase64;
-         this.enablesXDR = !!opts.enablesXDR;
-         this.withCredentials = false !== opts.withCredentials;
-         this.timestampParam = opts.timestampParam || 't';
-         this.timestampRequests = opts.timestampRequests;
-         this.transports = opts.transports || ['polling', 'websocket'];
-         this.transportOptions = opts.transportOptions || {};
-         this.readyState = '';
-         this.writeBuffer = [];
-         this.prevBufferLen = 0;
-         this.policyPort = opts.policyPort || 843;
-         this.rememberUpgrade = opts.rememberUpgrade || false;
-         this.binaryType = null;
-         this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
-         this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false;
-       
-         if (true === this.perMessageDeflate) this.perMessageDeflate = {};
-         if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) {
-           this.perMessageDeflate.threshold = 1024;
-         }
-       
-         // SSL options for Node.js client
-         this.pfx = opts.pfx || null;
-         this.key = opts.key || null;
-         this.passphrase = opts.passphrase || null;
-         this.cert = opts.cert || null;
-         this.ca = opts.ca || null;
-         this.ciphers = opts.ciphers || null;
-         this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? true : opts.rejectUnauthorized;
-         this.forceNode = !!opts.forceNode;
-       
-         // detect ReactNative environment
-         this.isReactNative = (typeof navigator !== 'undefined' && typeof navigator.product === 'string' && navigator.product.toLowerCase() === 'reactnative');
-       
-         // other options for Node.js or ReactNative client
-         if (typeof self === 'undefined' || this.isReactNative) {
-           if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) {
-             this.extraHeaders = opts.extraHeaders;
-           }
-       
-           if (opts.localAddress) {
-             this.localAddress = opts.localAddress;
-           }
-         }
-       
-         // set on handshake
-         this.id = null;
-         this.upgrades = null;
-         this.pingInterval = null;
-         this.pingTimeout = null;
-       
-         // set on heartbeat
-         this.pingIntervalTimer = null;
-         this.pingTimeoutTimer = null;
-       
-         this.open();
-       }
-       
-       Socket.priorWebsocketSuccess = false;
-       
-       /**
-        * Mix in `Emitter`.
-        */
-       
-       Emitter(Socket.prototype);
-       
-       /**
-        * Protocol version.
-        *
-        * @api public
-        */
-       
-       Socket.protocol = parser.protocol; // this is an int
-       
-       /**
-        * Expose deps for legacy compatibility
-        * and standalone browser access.
-        */
-       
-       Socket.Socket = Socket;
-       Socket.Transport = __webpack_require__(21);
-       Socket.transports = __webpack_require__(15);
-       Socket.parser = __webpack_require__(22);
-       
-       /**
-        * Creates transport of the given type.
-        *
-        * @param {String} transport name
-        * @return {Transport}
-        * @api private
-        */
-       
-       Socket.prototype.createTransport = function (name) {
-         debug('creating transport "%s"', name);
-         var query = clone(this.query);
-       
-         // append engine.io protocol identifier
-         query.EIO = parser.protocol;
-       
-         // transport name
-         query.transport = name;
-       
-         // per-transport options
-         var options = this.transportOptions[name] || {};
-       
-         // session id if we already have one
-         if (this.id) query.sid = this.id;
-       
-         var transport = new transports[name]({
-           query: query,
-           socket: this,
-           agent: options.agent || this.agent,
-           hostname: options.hostname || this.hostname,
-           port: options.port || this.port,
-           secure: options.secure || this.secure,
-           path: options.path || this.path,
-           forceJSONP: options.forceJSONP || this.forceJSONP,
-           jsonp: options.jsonp || this.jsonp,
-           forceBase64: options.forceBase64 || this.forceBase64,
-           enablesXDR: options.enablesXDR || this.enablesXDR,
-           withCredentials: options.withCredentials || this.withCredentials,
-           timestampRequests: options.timestampRequests || this.timestampRequests,
-           timestampParam: options.timestampParam || this.timestampParam,
-           policyPort: options.policyPort || this.policyPort,
-           pfx: options.pfx || this.pfx,
-           key: options.key || this.key,
-           passphrase: options.passphrase || this.passphrase,
-           cert: options.cert || this.cert,
-           ca: options.ca || this.ca,
-           ciphers: options.ciphers || this.ciphers,
-           rejectUnauthorized: options.rejectUnauthorized || this.rejectUnauthorized,
-           perMessageDeflate: options.perMessageDeflate || this.perMessageDeflate,
-           extraHeaders: options.extraHeaders || this.extraHeaders,
-           forceNode: options.forceNode || this.forceNode,
-           localAddress: options.localAddress || this.localAddress,
-           requestTimeout: options.requestTimeout || this.requestTimeout,
-           protocols: options.protocols || void (0),
-           isReactNative: this.isReactNative
-         });
-       
-         return transport;
-       };
-       
-       function clone (obj) {
-         var o = {};
-         for (var i in obj) {
-           if (obj.hasOwnProperty(i)) {
-             o[i] = obj[i];
-           }
-         }
-         return o;
-       }
-       
-       /**
-        * Initializes transport to use and starts probe.
-        *
-        * @api private
-        */
-       Socket.prototype.open = function () {
-         var transport;
-         if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) {
-           transport = 'websocket';
-         } else if (0 === this.transports.length) {
-           // Emit error on next tick so it can be listened to
-           var self = this;
-           setTimeout(function () {
-             self.emit('error', 'No transports available');
-           }, 0);
-           return;
-         } else {
-           transport = this.transports[0];
-         }
-         this.readyState = 'opening';
-       
-         // Retry with the next transport if the transport is disabled (jsonp: false)
-         try {
-           transport = this.createTransport(transport);
-         } catch (e) {
-           this.transports.shift();
-           this.open();
-           return;
-         }
-       
-         transport.open();
-         this.setTransport(transport);
-       };
-       
-       /**
-        * Sets the current transport. Disables the existing one (if any).
-        *
-        * @api private
-        */
-       
-       Socket.prototype.setTransport = function (transport) {
-         debug('setting transport %s', transport.name);
-         var self = this;
-       
-         if (this.transport) {
-           debug('clearing existing transport %s', this.transport.name);
-           this.transport.removeAllListeners();
-         }
-       
-         // set up transport
-         this.transport = transport;
-       
-         // set up transport listeners
-         transport
-         .on('drain', function () {
-           self.onDrain();
-         })
-         .on('packet', function (packet) {
-           self.onPacket(packet);
-         })
-         .on('error', function (e) {
-           self.onError(e);
-         })
-         .on('close', function () {
-           self.onClose('transport close');
-         });
-       };
-       
-       /**
-        * Probes a transport.
-        *
-        * @param {String} transport name
-        * @api private
-        */
-       
-       Socket.prototype.probe = function (name) {
-         debug('probing transport "%s"', name);
-         var transport = this.createTransport(name, { probe: 1 });
-         var failed = false;
-         var self = this;
-       
-         Socket.priorWebsocketSuccess = false;
-       
-         function onTransportOpen () {
-           if (self.onlyBinaryUpgrades) {
-             var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
-             failed = failed || upgradeLosesBinary;
-           }
-           if (failed) return;
-       
-           debug('probe transport "%s" opened', name);
-           transport.send([{ type: 'ping', data: 'probe' }]);
-           transport.once('packet', function (msg) {
-             if (failed) return;
-             if ('pong' === msg.type && 'probe' === msg.data) {
-               debug('probe transport "%s" pong', name);
-               self.upgrading = true;
-               self.emit('upgrading', transport);
-               if (!transport) return;
-               Socket.priorWebsocketSuccess = 'websocket' === transport.name;
-       
-               debug('pausing current transport "%s"', self.transport.name);
-               self.transport.pause(function () {
-                 if (failed) return;
-                 if ('closed' === self.readyState) return;
-                 debug('changing transport and sending upgrade packet');
-       
-                 cleanup();
-       
-                 self.setTransport(transport);
-                 transport.send([{ type: 'upgrade' }]);
-                 self.emit('upgrade', transport);
-                 transport = null;
-                 self.upgrading = false;
-                 self.flush();
-               });
-             } else {
-               debug('probe transport "%s" failed', name);
-               var err = new Error('probe error');
-               err.transport = transport.name;
-               self.emit('upgradeError', err);
-             }
-           });
-         }
-       
-         function freezeTransport () {
-           if (failed) return;
-       
-           // Any callback called by transport should be ignored since now
-           failed = true;
-       
-           cleanup();
-       
-           transport.close();
-           transport = null;
-         }
-       
-         // Handle any error that happens while probing
-         function onerror (err) {
-           var error = new Error('probe error: ' + err);
-           error.transport = transport.name;
-       
-           freezeTransport();
-       
-           debug('probe transport "%s" failed because of error: %s', name, err);
-       
-           self.emit('upgradeError', error);
-         }
-       
-         function onTransportClose () {
-           onerror('transport closed');
-         }
-       
-         // When the socket is closed while we're probing
-         function onclose () {
-           onerror('socket closed');
-         }
-       
-         // When the socket is upgraded while we're probing
-         function onupgrade (to) {
-           if (transport && to.name !== transport.name) {
-             debug('"%s" works - aborting "%s"', to.name, transport.name);
-             freezeTransport();
-           }
-         }
-       
-         // Remove all listeners on the transport and on self
-         function cleanup () {
-           transport.removeListener('open', onTransportOpen);
-           transport.removeListener('error', onerror);
-           transport.removeListener('close', onTransportClose);
-           self.removeListener('close', onclose);
-           self.removeListener('upgrading', onupgrade);
-         }
-       
-         transport.once('open', onTransportOpen);
-         transport.once('error', onerror);
-         transport.once('close', onTransportClose);
-       
-         this.once('close', onclose);
-         this.once('upgrading', onupgrade);
-       
-         transport.open();
-       };
-       
-       /**
-        * Called when connection is deemed open.
-        *
-        * @api public
-        */
-       
-       Socket.prototype.onOpen = function () {
-         debug('socket open');
-         this.readyState = 'open';
-         Socket.priorWebsocketSuccess = 'websocket' === this.transport.name;
-         this.emit('open');
-         this.flush();
-       
-         // we check for `readyState` in case an `open`
-         // listener already closed the socket
-         if ('open' === this.readyState && this.upgrade && this.transport.pause) {
-           debug('starting upgrade probes');
-           for (var i = 0, l = this.upgrades.length; i < l; i++) {
-             this.probe(this.upgrades[i]);
-           }
-         }
-       };
-       
-       /**
-        * Handles a packet.
-        *
-        * @api private
-        */
-       
-       Socket.prototype.onPacket = function (packet) {
-         if ('opening' === this.readyState || 'open' === this.readyState ||
-             'closing' === this.readyState) {
-           debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
-       
-           this.emit('packet', packet);
-       
-           // Socket is live - any packet counts
-           this.emit('heartbeat');
-       
-           switch (packet.type) {
-             case 'open':
-               this.onHandshake(JSON.parse(packet.data));
-               break;
-       
-             case 'pong':
-               this.setPing();
-               this.emit('pong');
-               break;
-       
-             case 'error':
-               var err = new Error('server error');
-               err.code = packet.data;
-               this.onError(err);
-               break;
-       
-             case 'message':
-               this.emit('data', packet.data);
-               this.emit('message', packet.data);
-               break;
-           }
-         } else {
-           debug('packet received with socket readyState "%s"', this.readyState);
-         }
-       };
-       
-       /**
-        * Called upon handshake completion.
-        *
-        * @param {Object} handshake obj
-        * @api private
-        */
-       
-       Socket.prototype.onHandshake = function (data) {
-         this.emit('handshake', data);
-         this.id = data.sid;
-         this.transport.query.sid = data.sid;
-         this.upgrades = this.filterUpgrades(data.upgrades);
-         this.pingInterval = data.pingInterval;
-         this.pingTimeout = data.pingTimeout;
-         this.onOpen();
-         // In case open handler closes socket
-         if ('closed' === this.readyState) return;
-         this.setPing();
-       
-         // Prolong liveness of socket on heartbeat
-         this.removeListener('heartbeat', this.onHeartbeat);
-         this.on('heartbeat', this.onHeartbeat);
-       };
-       
-       /**
-        * Resets ping timeout.
-        *
-        * @api private
-        */
-       
-       Socket.prototype.onHeartbeat = function (timeout) {
-         clearTimeout(this.pingTimeoutTimer);
-         var self = this;
-         self.pingTimeoutTimer = setTimeout(function () {
-           if ('closed' === self.readyState) return;
-           self.onClose('ping timeout');
-         }, timeout || (self.pingInterval + self.pingTimeout));
-       };
-       
-       /**
-        * Pings server every `this.pingInterval` and expects response
-        * within `this.pingTimeout` or closes connection.
-        *
-        * @api private
-        */
-       
-       Socket.prototype.setPing = function () {
-         var self = this;
-         clearTimeout(self.pingIntervalTimer);
-         self.pingIntervalTimer = setTimeout(function () {
-           debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
-           self.ping();
-           self.onHeartbeat(self.pingTimeout);
-         }, self.pingInterval);
-       };
-       
-       /**
-       * Sends a ping packet.
-       *
-       * @api private
-       */
-       
-       Socket.prototype.ping = function () {
-         var self = this;
-         this.sendPacket('ping', function () {
-           self.emit('ping');
-         });
-       };
-       
-       /**
-        * Called on `drain` event
-        *
-        * @api private
-        */
-       
-       Socket.prototype.onDrain = function () {
-         this.writeBuffer.splice(0, this.prevBufferLen);
-       
-         // setting prevBufferLen = 0 is very important
-         // for example, when upgrading, upgrade packet is sent over,
-         // and a nonzero prevBufferLen could cause problems on `drain`
-         this.prevBufferLen = 0;
-       
-         if (0 === this.writeBuffer.length) {
-           this.emit('drain');
-         } else {
-           this.flush();
-         }
-       };
-       
-       /**
-        * Flush write buffers.
-        *
-        * @api private
-        */
-       
-       Socket.prototype.flush = function () {
-         if ('closed' !== this.readyState && this.transport.writable &&
-           !this.upgrading && this.writeBuffer.length) {
-           debug('flushing %d packets in socket', this.writeBuffer.length);
-           this.transport.send(this.writeBuffer);
-           // keep track of current length of writeBuffer
-           // splice writeBuffer and callbackBuffer on `drain`
-           this.prevBufferLen = this.writeBuffer.length;
-           this.emit('flush');
-         }
-       };
-       
-       /**
-        * Sends a message.
-        *
-        * @param {String} message.
-        * @param {Function} callback function.
-        * @param {Object} options.
-        * @return {Socket} for chaining.
-        * @api public
-        */
-       
-       Socket.prototype.write =
-       Socket.prototype.send = function (msg, options, fn) {
-         this.sendPacket('message', msg, options, fn);
-         return this;
-       };
-       
-       /**
-        * Sends a packet.
-        *
-        * @param {String} packet type.
-        * @param {String} data.
-        * @param {Object} options.
-        * @param {Function} callback function.
-        * @api private
-        */
-       
-       Socket.prototype.sendPacket = function (type, data, options, fn) {
-         if ('function' === typeof data) {
-           fn = data;
-           data = undefined;
-         }
-       
-         if ('function' === typeof options) {
-           fn = options;
-           options = null;
-         }
-       
-         if ('closing' === this.readyState || 'closed' === this.readyState) {
-           return;
-         }
-       
-         options = options || {};
-         options.compress = false !== options.compress;
-       
-         var packet = {
-           type: type,
-           data: data,
-           options: options
-         };
-         this.emit('packetCreate', packet);
-         this.writeBuffer.push(packet);
-         if (fn) this.once('flush', fn);
-         this.flush();
-       };
-       
-       /**
-        * Closes the connection.
-        *
-        * @api private
-        */
-       
-       Socket.prototype.close = function () {
-         if ('opening' === this.readyState || 'open' === this.readyState) {
-           this.readyState = 'closing';
-       
-           var self = this;
-       
-           if (this.writeBuffer.length) {
-             this.once('drain', function () {
-               if (this.upgrading) {
-                 waitForUpgrade();
-               } else {
-                 close();
-               }
-             });
-           } else if (this.upgrading) {
-             waitForUpgrade();
-           } else {
-             close();
-           }
-         }
-       
-         function close () {
-           self.onClose('forced close');
-           debug('socket closing - telling transport to close');
-           self.transport.close();
-         }
-       
-         function cleanupAndClose () {
-           self.removeListener('upgrade', cleanupAndClose);
-           self.removeListener('upgradeError', cleanupAndClose);
-           close();
-         }
-       
-         function waitForUpgrade () {
-           // wait for upgrade to finish since we can't send packets while pausing a transport
-           self.once('upgrade', cleanupAndClose);
-           self.once('upgradeError', cleanupAndClose);
-         }
-       
-         return this;
-       };
-       
-       /**
-        * Called upon transport error
-        *
-        * @api private
-        */
-       
-       Socket.prototype.onError = function (err) {
-         debug('socket error %j', err);
-         Socket.priorWebsocketSuccess = false;
-         this.emit('error', err);
-         this.onClose('transport error', err);
-       };
-       
-       /**
-        * Called upon transport close.
-        *
-        * @api private
-        */
-       
-       Socket.prototype.onClose = function (reason, desc) {
-         if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) {
-           debug('socket close with reason: "%s"', reason);
-           var self = this;
-       
-           // clear timers
-           clearTimeout(this.pingIntervalTimer);
-           clearTimeout(this.pingTimeoutTimer);
-       
-           // stop event from firing again for transport
-           this.transport.removeAllListeners('close');
-       
-           // ensure transport won't stay open
-           this.transport.close();
-       
-           // ignore further transport communication
-           this.transport.removeAllListeners();
-       
-           // set ready state
-           this.readyState = 'closed';
-       
-           // clear session id
-           this.id = null;
-       
-           // emit close event
-           this.emit('close', reason, desc);
-       
-           // clean buffers after, so users can still
-           // grab the buffers on `close` event
-           self.writeBuffer = [];
-           self.prevBufferLen = 0;
-         }
-       };
-       
-       /**
-        * Filters upgrades, returning only those matching client transports.
-        *
-        * @param {Array} server upgrades
-        * @api private
-        *
-        */
-       
-       Socket.prototype.filterUpgrades = function (upgrades) {
-         var filteredUpgrades = [];
-         for (var i = 0, j = upgrades.length; i < j; i++) {
-           if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
-         }
-         return filteredUpgrades;
-       };
-
-
-/***/ }),
-/* 15 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       /**
-        * Module dependencies
-        */
-       
-       var XMLHttpRequest = __webpack_require__(16);
-       var XHR = __webpack_require__(19);
-       var JSONP = __webpack_require__(33);
-       var websocket = __webpack_require__(34);
-       
-       /**
-        * Export transports.
-        */
-       
-       exports.polling = polling;
-       exports.websocket = websocket;
-       
-       /**
-        * Polling transport polymorphic constructor.
-        * Decides on xhr vs jsonp based on feature detection.
-        *
-        * @api private
-        */
-       
-       function polling (opts) {
-         var xhr;
-         var xd = false;
-         var xs = false;
-         var jsonp = false !== opts.jsonp;
-       
-         if (typeof location !== 'undefined') {
-           var isSSL = 'https:' === location.protocol;
-           var port = location.port;
-       
-           // some user agents have empty `location.port`
-           if (!port) {
-             port = isSSL ? 443 : 80;
-           }
-       
-           xd = opts.hostname !== location.hostname || port !== opts.port;
-           xs = opts.secure !== isSSL;
-         }
-       
-         opts.xdomain = xd;
-         opts.xscheme = xs;
-         xhr = new XMLHttpRequest(opts);
-       
-         if ('open' in xhr && !opts.forceJSONP) {
-           return new XHR(opts);
-         } else {
-           if (!jsonp) throw new Error('JSONP disabled');
-           return new JSONP(opts);
-         }
-       }
-
-
-/***/ }),
-/* 16 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       // browser shim for xmlhttprequest module
-       
-       var hasCORS = __webpack_require__(17);
-       var globalThis = __webpack_require__(18);
-       
-       module.exports = function (opts) {
-         var xdomain = opts.xdomain;
-       
-         // scheme must be same when usign XDomainRequest
-         // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
-         var xscheme = opts.xscheme;
-       
-         // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
-         // https://github.com/Automattic/engine.io-client/pull/217
-         var enablesXDR = opts.enablesXDR;
-       
-         // XMLHttpRequest can be disabled on IE
-         try {
-           if ('undefined' !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
-             return new XMLHttpRequest();
-           }
-         } catch (e) { }
-       
-         // Use XDomainRequest for IE8 if enablesXDR is true
-         // because loading bar keeps flashing when using jsonp-polling
-         // https://github.com/yujiosaka/socke.io-ie8-loading-example
-         try {
-           if ('undefined' !== typeof XDomainRequest && !xscheme && enablesXDR) {
-             return new XDomainRequest();
-           }
-         } catch (e) { }
-       
-         if (!xdomain) {
-           try {
-             return new globalThis[['Active'].concat('Object').join('X')]('Microsoft.XMLHTTP');
-           } catch (e) { }
-         }
-       };
-
-
-/***/ }),
-/* 17 */
-/***/ (function(module, exports) {
-
-       
-       /**
-        * Module exports.
-        *
-        * Logic borrowed from Modernizr:
-        *
-        *   - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
-        */
-       
-       try {
-         module.exports = typeof XMLHttpRequest !== 'undefined' &&
-           'withCredentials' in new XMLHttpRequest();
-       } catch (err) {
-         // if XMLHttp support is disabled in IE then it will throw
-         // when trying to create
-         module.exports = false;
-       }
-
-
-/***/ }),
-/* 18 */
-/***/ (function(module, exports) {
-
-       module.exports = (function () {
-         if (typeof self !== 'undefined') {
-           return self;
-         } else if (typeof window !== 'undefined') {
-           return window;
-         } else {
-           return Function('return this')(); // eslint-disable-line no-new-func
-         }
-       })();
-
-
-/***/ }),
-/* 19 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       /* global attachEvent */
-       
-       /**
-        * Module requirements.
-        */
-       
-       var XMLHttpRequest = __webpack_require__(16);
-       var Polling = __webpack_require__(20);
-       var Emitter = __webpack_require__(8);
-       var inherit = __webpack_require__(31);
-       var debug = __webpack_require__(3)('engine.io-client:polling-xhr');
-       var globalThis = __webpack_require__(18);
-       
-       /**
-        * Module exports.
-        */
-       
-       module.exports = XHR;
-       module.exports.Request = Request;
-       
-       /**
-        * Empty function
-        */
-       
-       function empty () {}
-       
-       /**
-        * XHR Polling constructor.
-        *
-        * @param {Object} opts
-        * @api public
-        */
-       
-       function XHR (opts) {
-         Polling.call(this, opts);
-         this.requestTimeout = opts.requestTimeout;
-         this.extraHeaders = opts.extraHeaders;
-       
-         if (typeof location !== 'undefined') {
-           var isSSL = 'https:' === location.protocol;
-           var port = location.port;
-       
-           // some user agents have empty `location.port`
-           if (!port) {
-             port = isSSL ? 443 : 80;
-           }
-       
-           this.xd = (typeof location !== 'undefined' && opts.hostname !== location.hostname) ||
-             port !== opts.port;
-           this.xs = opts.secure !== isSSL;
-         }
-       }
-       
-       /**
-        * Inherits from Polling.
-        */
-       
-       inherit(XHR, Polling);
-       
-       /**
-        * XHR supports binary
-        */
-       
-       XHR.prototype.supportsBinary = true;
-       
-       /**
-        * Creates a request.
-        *
-        * @param {String} method
-        * @api private
-        */
-       
-       XHR.prototype.request = function (opts) {
-         opts = opts || {};
-         opts.uri = this.uri();
-         opts.xd = this.xd;
-         opts.xs = this.xs;
-         opts.agent = this.agent || false;
-         opts.supportsBinary = this.supportsBinary;
-         opts.enablesXDR = this.enablesXDR;
-         opts.withCredentials = this.withCredentials;
-       
-         // SSL options for Node.js client
-         opts.pfx = this.pfx;
-         opts.key = this.key;
-         opts.passphrase = this.passphrase;
-         opts.cert = this.cert;
-         opts.ca = this.ca;
-         opts.ciphers = this.ciphers;
-         opts.rejectUnauthorized = this.rejectUnauthorized;
-         opts.requestTimeout = this.requestTimeout;
-       
-         // other options for Node.js client
-         opts.extraHeaders = this.extraHeaders;
-       
-         return new Request(opts);
-       };
-       
-       /**
-        * Sends data.
-        *
-        * @param {String} data to send.
-        * @param {Function} called upon flush.
-        * @api private
-        */
-       
-       XHR.prototype.doWrite = function (data, fn) {
-         var isBinary = typeof data !== 'string' && data !== undefined;
-         var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
-         var self = this;
-         req.on('success', fn);
-         req.on('error', function (err) {
-           self.onError('xhr post error', err);
-         });
-         this.sendXhr = req;
-       };
-       
-       /**
-        * Starts a poll cycle.
-        *
-        * @api private
-        */
-       
-       XHR.prototype.doPoll = function () {
-         debug('xhr poll');
-         var req = this.request();
-         var self = this;
-         req.on('data', function (data) {
-           self.onData(data);
-         });
-         req.on('error', function (err) {
-           self.onError('xhr poll error', err);
-         });
-         this.pollXhr = req;
-       };
-       
-       /**
-        * Request constructor
-        *
-        * @param {Object} options
-        * @api public
-        */
-       
-       function Request (opts) {
-         this.method = opts.method || 'GET';
-         this.uri = opts.uri;
-         this.xd = !!opts.xd;
-         this.xs = !!opts.xs;
-         this.async = false !== opts.async;
-         this.data = undefined !== opts.data ? opts.data : null;
-         this.agent = opts.agent;
-         this.isBinary = opts.isBinary;
-         this.supportsBinary = opts.supportsBinary;
-         this.enablesXDR = opts.enablesXDR;
-         this.withCredentials = opts.withCredentials;
-         this.requestTimeout = opts.requestTimeout;
-       
-         // SSL options for Node.js client
-         this.pfx = opts.pfx;
-         this.key = opts.key;
-         this.passphrase = opts.passphrase;
-         this.cert = opts.cert;
-         this.ca = opts.ca;
-         this.ciphers = opts.ciphers;
-         this.rejectUnauthorized = opts.rejectUnauthorized;
-       
-         // other options for Node.js client
-         this.extraHeaders = opts.extraHeaders;
-       
-         this.create();
-       }
-       
-       /**
-        * Mix in `Emitter`.
-        */
-       
-       Emitter(Request.prototype);
-       
-       /**
-        * Creates the XHR object and sends the request.
-        *
-        * @api private
-        */
-       
-       Request.prototype.create = function () {
-         var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
-       
-         // SSL options for Node.js client
-         opts.pfx = this.pfx;
-         opts.key = this.key;
-         opts.passphrase = this.passphrase;
-         opts.cert = this.cert;
-         opts.ca = this.ca;
-         opts.ciphers = this.ciphers;
-         opts.rejectUnauthorized = this.rejectUnauthorized;
-       
-         var xhr = this.xhr = new XMLHttpRequest(opts);
-         var self = this;
-       
-         try {
-           debug('xhr open %s: %s', this.method, this.uri);
-           xhr.open(this.method, this.uri, this.async);
-           try {
-             if (this.extraHeaders) {
-               xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
-               for (var i in this.extraHeaders) {
-                 if (this.extraHeaders.hasOwnProperty(i)) {
-                   xhr.setRequestHeader(i, this.extraHeaders[i]);
-                 }
-               }
-             }
-           } catch (e) {}
-       
-           if ('POST' === this.method) {
-             try {
-               if (this.isBinary) {
-                 xhr.setRequestHeader('Content-type', 'application/octet-stream');
-               } else {
-                 xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
-               }
-             } catch (e) {}
-           }
-       
-           try {
-             xhr.setRequestHeader('Accept', '*/*');
-           } catch (e) {}
-       
-           // ie6 check
-           if ('withCredentials' in xhr) {
-             xhr.withCredentials = this.withCredentials;
-           }
-       
-           if (this.requestTimeout) {
-             xhr.timeout = this.requestTimeout;
-           }
-       
-           if (this.hasXDR()) {
-             xhr.onload = function () {
-               self.onLoad();
-             };
-             xhr.onerror = function () {
-               self.onError(xhr.responseText);
-             };
-           } else {
-             xhr.onreadystatechange = function () {
-               if (xhr.readyState === 2) {
-                 try {
-                   var contentType = xhr.getResponseHeader('Content-Type');
-                   if (self.supportsBinary && contentType === 'application/octet-stream' || contentType === 'application/octet-stream; charset=UTF-8') {
-                     xhr.responseType = 'arraybuffer';
-                   }
-                 } catch (e) {}
-               }
-               if (4 !== xhr.readyState) return;
-               if (200 === xhr.status || 1223 === xhr.status) {
-                 self.onLoad();
-               } else {
-                 // make sure the `error` event handler that's user-set
-                 // does not throw in the same tick and gets caught here
-                 setTimeout(function () {
-                   self.onError(typeof xhr.status === 'number' ? xhr.status : 0);
-                 }, 0);
-               }
-             };
-           }
-       
-           debug('xhr data %s', this.data);
-           xhr.send(this.data);
-         } catch (e) {
-           // Need to defer since .create() is called directly fhrom the constructor
-           // and thus the 'error' event can only be only bound *after* this exception
-           // occurs.  Therefore, also, we cannot throw here at all.
-           setTimeout(function () {
-             self.onError(e);
-           }, 0);
-           return;
-         }
-       
-         if (typeof document !== 'undefined') {
-           this.index = Request.requestsCount++;
-           Request.requests[this.index] = this;
-         }
-       };
-       
-       /**
-        * Called upon successful response.
-        *
-        * @api private
-        */
-       
-       Request.prototype.onSuccess = function () {
-         this.emit('success');
-         this.cleanup();
-       };
-       
-       /**
-        * Called if we have data.
-        *
-        * @api private
-        */
-       
-       Request.prototype.onData = function (data) {
-         this.emit('data', data);
-         this.onSuccess();
-       };
-       
-       /**
-        * Called upon error.
-        *
-        * @api private
-        */
-       
-       Request.prototype.onError = function (err) {
-         this.emit('error', err);
-         this.cleanup(true);
-       };
-       
-       /**
-        * Cleans up house.
-        *
-        * @api private
-        */
-       
-       Request.prototype.cleanup = function (fromError) {
-         if ('undefined' === typeof this.xhr || null === this.xhr) {
-           return;
-         }
-         // xmlhttprequest
-         if (this.hasXDR()) {
-           this.xhr.onload = this.xhr.onerror = empty;
-         } else {
-           this.xhr.onreadystatechange = empty;
-         }
-       
-         if (fromError) {
-           try {
-             this.xhr.abort();
-           } catch (e) {}
-         }
-       
-         if (typeof document !== 'undefined') {
-           delete Request.requests[this.index];
-         }
-       
-         this.xhr = null;
-       };
-       
-       /**
-        * Called upon load.
-        *
-        * @api private
-        */
-       
-       Request.prototype.onLoad = function () {
-         var data;
-         try {
-           var contentType;
-           try {
-             contentType = this.xhr.getResponseHeader('Content-Type');
-           } catch (e) {}
-           if (contentType === 'application/octet-stream' || contentType === 'application/octet-stream; charset=UTF-8') {
-             data = this.xhr.response || this.xhr.responseText;
-           } else {
-             data = this.xhr.responseText;
-           }
-         } catch (e) {
-           this.onError(e);
-         }
-         if (null != data) {
-           this.onData(data);
-         }
-       };
-       
-       /**
-        * Check if it has XDomainRequest.
-        *
-        * @api private
-        */
-       
-       Request.prototype.hasXDR = function () {
-         return typeof XDomainRequest !== 'undefined' && !this.xs && this.enablesXDR;
-       };
-       
-       /**
-        * Aborts the request.
-        *
-        * @api public
-        */
-       
-       Request.prototype.abort = function () {
-         this.cleanup();
-       };
-       
-       /**
-        * Aborts pending requests when unloading the window. This is needed to prevent
-        * memory leaks (e.g. when using IE) and to ensure that no spurious error is
-        * emitted.
-        */
-       
-       Request.requestsCount = 0;
-       Request.requests = {};
-       
-       if (typeof document !== 'undefined') {
-         if (typeof attachEvent === 'function') {
-           attachEvent('onunload', unloadHandler);
-         } else if (typeof addEventListener === 'function') {
-           var terminationEvent = 'onpagehide' in globalThis ? 'pagehide' : 'unload';
-           addEventListener(terminationEvent, unloadHandler, false);
-         }
-       }
-       
-       function unloadHandler () {
-         for (var i in Request.requests) {
-           if (Request.requests.hasOwnProperty(i)) {
-             Request.requests[i].abort();
-           }
-         }
-       }
-
-
-/***/ }),
-/* 20 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       /**
-        * Module dependencies.
-        */
-       
-       var Transport = __webpack_require__(21);
-       var parseqs = __webpack_require__(30);
-       var parser = __webpack_require__(22);
-       var inherit = __webpack_require__(31);
-       var yeast = __webpack_require__(32);
-       var debug = __webpack_require__(3)('engine.io-client:polling');
-       
-       /**
-        * Module exports.
-        */
-       
-       module.exports = Polling;
-       
-       /**
-        * Is XHR2 supported?
-        */
-       
-       var hasXHR2 = (function () {
-         var XMLHttpRequest = __webpack_require__(16);
-         var xhr = new XMLHttpRequest({ xdomain: false });
-         return null != xhr.responseType;
-       })();
-       
-       /**
-        * Polling interface.
-        *
-        * @param {Object} opts
-        * @api private
-        */
-       
-       function Polling (opts) {
-         var forceBase64 = (opts && opts.forceBase64);
-         if (!hasXHR2 || forceBase64) {
-           this.supportsBinary = false;
-         }
-         Transport.call(this, opts);
-       }
-       
-       /**
-        * Inherits from Transport.
-        */
-       
-       inherit(Polling, Transport);
-       
-       /**
-        * Transport name.
-        */
-       
-       Polling.prototype.name = 'polling';
-       
-       /**
-        * Opens the socket (triggers polling). We write a PING message to determine
-        * when the transport is open.
-        *
-        * @api private
-        */
-       
-       Polling.prototype.doOpen = function () {
-         this.poll();
-       };
-       
-       /**
-        * Pauses polling.
-        *
-        * @param {Function} callback upon buffers are flushed and transport is paused
-        * @api private
-        */
-       
-       Polling.prototype.pause = function (onPause) {
-         var self = this;
-       
-         this.readyState = 'pausing';
-       
-         function pause () {
-           debug('paused');
-           self.readyState = 'paused';
-           onPause();
-         }
-       
-         if (this.polling || !this.writable) {
-           var total = 0;
-       
-           if (this.polling) {
-             debug('we are currently polling - waiting to pause');
-             total++;
-             this.once('pollComplete', function () {
-               debug('pre-pause polling complete');
-               --total || pause();
-             });
-           }
-       
-           if (!this.writable) {
-             debug('we are currently writing - waiting to pause');
-             total++;
-             this.once('drain', function () {
-               debug('pre-pause writing complete');
-               --total || pause();
-             });
-           }
-         } else {
-           pause();
-         }
-       };
-       
-       /**
-        * Starts polling cycle.
-        *
-        * @api public
-        */
-       
-       Polling.prototype.poll = function () {
-         debug('polling');
-         this.polling = true;
-         this.doPoll();
-         this.emit('poll');
-       };
-       
-       /**
-        * Overloads onData to detect payloads.
-        *
-        * @api private
-        */
-       
-       Polling.prototype.onData = function (data) {
-         var self = this;
-         debug('polling got data %s', data);
-         var callback = function (packet, index, total) {
-           // if its the first message we consider the transport open
-           if ('opening' === self.readyState && packet.type === 'open') {
-             self.onOpen();
-           }
-       
-           // if its a close packet, we close the ongoing requests
-           if ('close' === packet.type) {
-             self.onClose();
-             return false;
-           }
-       
-           // otherwise bypass onData and handle the message
-           self.onPacket(packet);
-         };
-       
-         // decode payload
-         parser.decodePayload(data, this.socket.binaryType, callback);
-       
-         // if an event did not trigger closing
-         if ('closed' !== this.readyState) {
-           // if we got data we're not polling
-           this.polling = false;
-           this.emit('pollComplete');
-       
-           if ('open' === this.readyState) {
-             this.poll();
-           } else {
-             debug('ignoring poll - transport state "%s"', this.readyState);
-           }
-         }
-       };
-       
-       /**
-        * For polling, send a close packet.
-        *
-        * @api private
-        */
-       
-       Polling.prototype.doClose = function () {
-         var self = this;
-       
-         function close () {
-           debug('writing close packet');
-           self.write([{ type: 'close' }]);
-         }
-       
-         if ('open' === this.readyState) {
-           debug('transport open - closing');
-           close();
-         } else {
-           // in case we're trying to close while
-           // handshaking is in progress (GH-164)
-           debug('transport not open - deferring close');
-           this.once('open', close);
-         }
-       };
-       
-       /**
-        * Writes a packets payload.
-        *
-        * @param {Array} data packets
-        * @param {Function} drain callback
-        * @api private
-        */
-       
-       Polling.prototype.write = function (packets) {
-         var self = this;
-         this.writable = false;
-         var callbackfn = function () {
-           self.writable = true;
-           self.emit('drain');
-         };
-       
-         parser.encodePayload(packets, this.supportsBinary, function (data) {
-           self.doWrite(data, callbackfn);
-         });
-       };
-       
-       /**
-        * Generates uri for connection.
-        *
-        * @api private
-        */
-       
-       Polling.prototype.uri = function () {
-         var query = this.query || {};
-         var schema = this.secure ? 'https' : 'http';
-         var port = '';
-       
-         // cache busting is forced
-         if (false !== this.timestampRequests) {
-           query[this.timestampParam] = yeast();
-         }
-       
-         if (!this.supportsBinary && !query.sid) {
-           query.b64 = 1;
-         }
-       
-         query = parseqs.encode(query);
-       
-         // avoid port if default for schema
-         if (this.port && (('https' === schema && Number(this.port) !== 443) ||
-            ('http' === schema && Number(this.port) !== 80))) {
-           port = ':' + this.port;
-         }
-       
-         // prepend ? to query
-         if (query.length) {
-           query = '?' + query;
-         }
-       
-         var ipv6 = this.hostname.indexOf(':') !== -1;
-         return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
-       };
-
-
-/***/ }),
-/* 21 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       /**
-        * Module dependencies.
-        */
-       
-       var parser = __webpack_require__(22);
-       var Emitter = __webpack_require__(8);
-       
-       /**
-        * Module exports.
-        */
-       
-       module.exports = Transport;
-       
-       /**
-        * Transport abstract constructor.
-        *
-        * @param {Object} options.
-        * @api private
-        */
-       
-       function Transport (opts) {
-         this.path = opts.path;
-         this.hostname = opts.hostname;
-         this.port = opts.port;
-         this.secure = opts.secure;
-         this.query = opts.query;
-         this.timestampParam = opts.timestampParam;
-         this.timestampRequests = opts.timestampRequests;
-         this.readyState = '';
-         this.agent = opts.agent || false;
-         this.socket = opts.socket;
-         this.enablesXDR = opts.enablesXDR;
-         this.withCredentials = opts.withCredentials;
-       
-         // SSL options for Node.js client
-         this.pfx = opts.pfx;
-         this.key = opts.key;
-         this.passphrase = opts.passphrase;
-         this.cert = opts.cert;
-         this.ca = opts.ca;
-         this.ciphers = opts.ciphers;
-         this.rejectUnauthorized = opts.rejectUnauthorized;
-         this.forceNode = opts.forceNode;
-       
-         // results of ReactNative environment detection
-         this.isReactNative = opts.isReactNative;
-       
-         // other options for Node.js client
-         this.extraHeaders = opts.extraHeaders;
-         this.localAddress = opts.localAddress;
-       }
-       
-       /**
-        * Mix in `Emitter`.
-        */
-       
-       Emitter(Transport.prototype);
-       
-       /**
-        * Emits an error.
-        *
-        * @param {String} str
-        * @return {Transport} for chaining
-        * @api public
-        */
-       
-       Transport.prototype.onError = function (msg, desc) {
-         var err = new Error(msg);
-         err.type = 'TransportError';
-         err.description = desc;
-         this.emit('error', err);
-         return this;
-       };
-       
-       /**
-        * Opens the transport.
-        *
-        * @api public
-        */
-       
-       Transport.prototype.open = function () {
-         if ('closed' === this.readyState || '' === this.readyState) {
-           this.readyState = 'opening';
-           this.doOpen();
-         }
-       
-         return this;
-       };
-       
-       /**
-        * Closes the transport.
-        *
-        * @api private
-        */
-       
-       Transport.prototype.close = function () {
-         if ('opening' === this.readyState || 'open' === this.readyState) {
-           this.doClose();
-           this.onClose();
-         }
-       
-         return this;
-       };
-       
-       /**
-        * Sends multiple packets.
-        *
-        * @param {Array} packets
-        * @api private
-        */
-       
-       Transport.prototype.send = function (packets) {
-         if ('open' === this.readyState) {
-           this.write(packets);
-         } else {
-           throw new Error('Transport not open');
-         }
-       };
-       
-       /**
-        * Called upon open
-        *
-        * @api private
-        */
-       
-       Transport.prototype.onOpen = function () {
-         this.readyState = 'open';
-         this.writable = true;
-         this.emit('open');
-       };
-       
-       /**
-        * Called with data.
-        *
-        * @param {String} data
-        * @api private
-        */
-       
-       Transport.prototype.onData = function (data) {
-         var packet = parser.decodePacket(data, this.socket.binaryType);
-         this.onPacket(packet);
-       };
-       
-       /**
-        * Called with a decoded packet.
-        */
-       
-       Transport.prototype.onPacket = function (packet) {
-         this.emit('packet', packet);
-       };
-       
-       /**
-        * Called upon close.
-        *
-        * @api private
-        */
-       
-       Transport.prototype.onClose = function () {
-         this.readyState = 'closed';
-         this.emit('close');
-       };
-
-
-/***/ }),
-/* 22 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       /**
-        * Module dependencies.
-        */
-       
-       var keys = __webpack_require__(23);
-       var hasBinary = __webpack_require__(24);
-       var sliceBuffer = __webpack_require__(25);
-       var after = __webpack_require__(26);
-       var utf8 = __webpack_require__(27);
-       
-       var base64encoder;
-       if (typeof ArrayBuffer !== 'undefined') {
-         base64encoder = __webpack_require__(28);
-       }
-       
-       /**
-        * Check if we are running an android browser. That requires us to use
-        * ArrayBuffer with polling transports...
-        *
-        * http://ghinda.net/jpeg-blob-ajax-android/
-        */
-       
-       var isAndroid = typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent);
-       
-       /**
-        * Check if we are running in PhantomJS.
-        * Uploading a Blob with PhantomJS does not work correctly, as reported here:
-        * https://github.com/ariya/phantomjs/issues/11395
-        * @type boolean
-        */
-       var isPhantomJS = typeof navigator !== 'undefined' && /PhantomJS/i.test(navigator.userAgent);
-       
-       /**
-        * When true, avoids using Blobs to encode payloads.
-        * @type boolean
-        */
-       var dontSendBlobs = isAndroid || isPhantomJS;
-       
-       /**
-        * Current protocol version.
-        */
-       
-       exports.protocol = 3;
-       
-       /**
-        * Packet types.
-        */
-       
-       var packets = exports.packets = {
-           open:     0    // non-ws
-         , close:    1    // non-ws
-         , ping:     2
-         , pong:     3
-         , message:  4
-         , upgrade:  5
-         , noop:     6
-       };
-       
-       var packetslist = keys(packets);
-       
-       /**
-        * Premade error packet.
-        */
-       
-       var err = { type: 'error', data: 'parser error' };
-       
-       /**
-        * Create a blob api even for blob builder when vendor prefixes exist
-        */
-       
-       var Blob = __webpack_require__(29);
-       
-       /**
-        * Encodes a packet.
-        *
-        *     <packet type id> [ <data> ]
-        *
-        * Example:
-        *
-        *     5hello world
-        *     3
-        *     4
-        *
-        * Binary is encoded in an identical principle
-        *
-        * @api private
-        */
-       
-       exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
-         if (typeof supportsBinary === 'function') {
-           callback = supportsBinary;
-           supportsBinary = false;
-         }
-       
-         if (typeof utf8encode === 'function') {
-           callback = utf8encode;
-           utf8encode = null;
-         }
-       
-         var data = (packet.data === undefined)
-           ? undefined
-           : packet.data.buffer || packet.data;
-       
-         if (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer) {
-           return encodeArrayBuffer(packet, supportsBinary, callback);
-         } else if (typeof Blob !== 'undefined' && data instanceof Blob) {
-           return encodeBlob(packet, supportsBinary, callback);
-         }
-       
-         // might be an object with { base64: true, data: dataAsBase64String }
-         if (data && data.base64) {
-           return encodeBase64Object(packet, callback);
-         }
-       
-         // Sending data as a utf-8 string
-         var encoded = packets[packet.type];
-       
-         // data fragment is optional
-         if (undefined !== packet.data) {
-           encoded += utf8encode ? utf8.encode(String(packet.data), { strict: false }) : String(packet.data);
-         }
-       
-         return callback('' + encoded);
-       
-       };
-       
-       function encodeBase64Object(packet, callback) {
-         // packet data is an object { base64: true, data: dataAsBase64String }
-         var message = 'b' + exports.packets[packet.type] + packet.data.data;
-         return callback(message);
-       }
-       
-       /**
-        * Encode packet helpers for binary types
-        */
-       
-       function encodeArrayBuffer(packet, supportsBinary, callback) {
-         if (!supportsBinary) {
-           return exports.encodeBase64Packet(packet, callback);
-         }
-       
-         var data = packet.data;
-         var contentArray = new Uint8Array(data);
-         var resultBuffer = new Uint8Array(1 + data.byteLength);
-       
-         resultBuffer[0] = packets[packet.type];
-         for (var i = 0; i < contentArray.length; i++) {
-           resultBuffer[i+1] = contentArray[i];
-         }
-       
-         return callback(resultBuffer.buffer);
-       }
-       
-       function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
-         if (!supportsBinary) {
-           return exports.encodeBase64Packet(packet, callback);
-         }
-       
-         var fr = new FileReader();
-         fr.onload = function() {
-           exports.encodePacket({ type: packet.type, data: fr.result }, supportsBinary, true, callback);
-         };
-         return fr.readAsArrayBuffer(packet.data);
-       }
-       
-       function encodeBlob(packet, supportsBinary, callback) {
-         if (!supportsBinary) {
-           return exports.encodeBase64Packet(packet, callback);
-         }
-       
-         if (dontSendBlobs) {
-           return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
-         }
-       
-         var length = new Uint8Array(1);
-         length[0] = packets[packet.type];
-         var blob = new Blob([length.buffer, packet.data]);
-       
-         return callback(blob);
-       }
-       
-       /**
-        * Encodes a packet with binary data in a base64 string
-        *
-        * @param {Object} packet, has `type` and `data`
-        * @return {String} base64 encoded message
-        */
-       
-       exports.encodeBase64Packet = function(packet, callback) {
-         var message = 'b' + exports.packets[packet.type];
-         if (typeof Blob !== 'undefined' && packet.data instanceof Blob) {
-           var fr = new FileReader();
-           fr.onload = function() {
-             var b64 = fr.result.split(',')[1];
-             callback(message + b64);
-           };
-           return fr.readAsDataURL(packet.data);
-         }
-       
-         var b64data;
-         try {
-           b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
-         } catch (e) {
-           // iPhone Safari doesn't let you apply with typed arrays
-           var typed = new Uint8Array(packet.data);
-           var basic = new Array(typed.length);
-           for (var i = 0; i < typed.length; i++) {
-             basic[i] = typed[i];
-           }
-           b64data = String.fromCharCode.apply(null, basic);
-         }
-         message += btoa(b64data);
-         return callback(message);
-       };
-       
-       /**
-        * Decodes a packet. Changes format to Blob if requested.
-        *
-        * @return {Object} with `type` and `data` (if any)
-        * @api private
-        */
-       
-       exports.decodePacket = function (data, binaryType, utf8decode) {
-         if (data === undefined) {
-           return err;
-         }
-         // String data
-         if (typeof data === 'string') {
-           if (data.charAt(0) === 'b') {
-             return exports.decodeBase64Packet(data.substr(1), binaryType);
-           }
-       
-           if (utf8decode) {
-             data = tryDecode(data);
-             if (data === false) {
-               return err;
-             }
-           }
-           var type = data.charAt(0);
-       
-           if (Number(type) != type || !packetslist[type]) {
-             return err;
-           }
-       
-           if (data.length > 1) {
-             return { type: packetslist[type], data: data.substring(1) };
-           } else {
-             return { type: packetslist[type] };
-           }
-         }
-       
-         var asArray = new Uint8Array(data);
-         var type = asArray[0];
-         var rest = sliceBuffer(data, 1);
-         if (Blob && binaryType === 'blob') {
-           rest = new Blob([rest]);
-         }
-         return { type: packetslist[type], data: rest };
-       };
-       
-       function tryDecode(data) {
-         try {
-           data = utf8.decode(data, { strict: false });
-         } catch (e) {
-           return false;
-         }
-         return data;
-       }
-       
-       /**
-        * Decodes a packet encoded in a base64 string
-        *
-        * @param {String} base64 encoded message
-        * @return {Object} with `type` and `data` (if any)
-        */
-       
-       exports.decodeBase64Packet = function(msg, binaryType) {
-         var type = packetslist[msg.charAt(0)];
-         if (!base64encoder) {
-           return { type: type, data: { base64: true, data: msg.substr(1) } };
-         }
-       
-         var data = base64encoder.decode(msg.substr(1));
-       
-         if (binaryType === 'blob' && Blob) {
-           data = new Blob([data]);
-         }
-       
-         return { type: type, data: data };
-       };
-       
-       /**
-        * Encodes multiple messages (payload).
-        *
-        *     <length>:data
-        *
-        * Example:
-        *
-        *     11:hello world2:hi
-        *
-        * If any contents are binary, they will be encoded as base64 strings. Base64
-        * encoded strings are marked with a b before the length specifier
-        *
-        * @param {Array} packets
-        * @api private
-        */
-       
-       exports.encodePayload = function (packets, supportsBinary, callback) {
-         if (typeof supportsBinary === 'function') {
-           callback = supportsBinary;
-           supportsBinary = null;
-         }
-       
-         var isBinary = hasBinary(packets);
-       
-         if (supportsBinary && isBinary) {
-           if (Blob && !dontSendBlobs) {
-             return exports.encodePayloadAsBlob(packets, callback);
-           }
-       
-           return exports.encodePayloadAsArrayBuffer(packets, callback);
-         }
-       
-         if (!packets.length) {
-           return callback('0:');
-         }
-       
-         function setLengthHeader(message) {
-           return message.length + ':' + message;
-         }
-       
-         function encodeOne(packet, doneCallback) {
-           exports.encodePacket(packet, !isBinary ? false : supportsBinary, false, function(message) {
-             doneCallback(null, setLengthHeader(message));
-           });
-         }
-       
-         map(packets, encodeOne, function(err, results) {
-           return callback(results.join(''));
-         });
-       };
-       
-       /**
-        * Async array map using after
-        */
-       
-       function map(ary, each, done) {
-         var result = new Array(ary.length);
-         var next = after(ary.length, done);
-       
-         var eachWithIndex = function(i, el, cb) {
-           each(el, function(error, msg) {
-             result[i] = msg;
-             cb(error, result);
-           });
-         };
-       
-         for (var i = 0; i < ary.length; i++) {
-           eachWithIndex(i, ary[i], next);
-         }
-       }
-       
-       /*
-        * Decodes data when a payload is maybe expected. Possible binary contents are
-        * decoded from their base64 representation
-        *
-        * @param {String} data, callback method
-        * @api public
-        */
-       
-       exports.decodePayload = function (data, binaryType, callback) {
-         if (typeof data !== 'string') {
-           return exports.decodePayloadAsBinary(data, binaryType, callback);
-         }
-       
-         if (typeof binaryType === 'function') {
-           callback = binaryType;
-           binaryType = null;
-         }
-       
-         var packet;
-         if (data === '') {
-           // parser error - ignoring payload
-           return callback(err, 0, 1);
-         }
-       
-         var length = '', n, msg;
-       
-         for (var i = 0, l = data.length; i < l; i++) {
-           var chr = data.charAt(i);
-       
-           if (chr !== ':') {
-             length += chr;
-             continue;
-           }
-       
-           if (length === '' || (length != (n = Number(length)))) {
-             // parser error - ignoring payload
-             return callback(err, 0, 1);
-           }
-       
-           msg = data.substr(i + 1, n);
-       
-           if (length != msg.length) {
-             // parser error - ignoring payload
-             return callback(err, 0, 1);
-           }
-       
-           if (msg.length) {
-             packet = exports.decodePacket(msg, binaryType, false);
-       
-             if (err.type === packet.type && err.data === packet.data) {
-               // parser error in individual packet - ignoring payload
-               return callback(err, 0, 1);
-             }
-       
-             var ret = callback(packet, i + n, l);
-             if (false === ret) return;
-           }
-       
-           // advance cursor
-           i += n;
-           length = '';
-         }
-       
-         if (length !== '') {
-           // parser error - ignoring payload
-           return callback(err, 0, 1);
-         }
-       
-       };
-       
-       /**
-        * Encodes multiple messages (payload) as binary.
-        *
-        * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
-        * 255><data>
-        *
-        * Example:
-        * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
-        *
-        * @param {Array} packets
-        * @return {ArrayBuffer} encoded payload
-        * @api private
-        */
-       
-       exports.encodePayloadAsArrayBuffer = function(packets, callback) {
-         if (!packets.length) {
-           return callback(new ArrayBuffer(0));
-         }
-       
-         function encodeOne(packet, doneCallback) {
-           exports.encodePacket(packet, true, true, function(data) {
-             return doneCallback(null, data);
-           });
-         }
-       
-         map(packets, encodeOne, function(err, encodedPackets) {
-           var totalLength = encodedPackets.reduce(function(acc, p) {
-             var len;
-             if (typeof p === 'string'){
-               len = p.length;
-             } else {
-               len = p.byteLength;
-             }
-             return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
-           }, 0);
-       
-           var resultArray = new Uint8Array(totalLength);
-       
-           var bufferIndex = 0;
-           encodedPackets.forEach(function(p) {
-             var isString = typeof p === 'string';
-             var ab = p;
-             if (isString) {
-               var view = new Uint8Array(p.length);
-               for (var i = 0; i < p.length; i++) {
-                 view[i] = p.charCodeAt(i);
-               }
-               ab = view.buffer;
-             }
-       
-             if (isString) { // not true binary
-               resultArray[bufferIndex++] = 0;
-             } else { // true binary
-               resultArray[bufferIndex++] = 1;
-             }
-       
-             var lenStr = ab.byteLength.toString();
-             for (var i = 0; i < lenStr.length; i++) {
-               resultArray[bufferIndex++] = parseInt(lenStr[i]);
-             }
-             resultArray[bufferIndex++] = 255;
-       
-             var view = new Uint8Array(ab);
-             for (var i = 0; i < view.length; i++) {
-               resultArray[bufferIndex++] = view[i];
-             }
-           });
-       
-           return callback(resultArray.buffer);
-         });
-       };
-       
-       /**
-        * Encode as Blob
-        */
-       
-       exports.encodePayloadAsBlob = function(packets, callback) {
-         function encodeOne(packet, doneCallback) {
-           exports.encodePacket(packet, true, true, function(encoded) {
-             var binaryIdentifier = new Uint8Array(1);
-             binaryIdentifier[0] = 1;
-             if (typeof encoded === 'string') {
-               var view = new Uint8Array(encoded.length);
-               for (var i = 0; i < encoded.length; i++) {
-                 view[i] = encoded.charCodeAt(i);
-               }
-               encoded = view.buffer;
-               binaryIdentifier[0] = 0;
-             }
-       
-             var len = (encoded instanceof ArrayBuffer)
-               ? encoded.byteLength
-               : encoded.size;
-       
-             var lenStr = len.toString();
-             var lengthAry = new Uint8Array(lenStr.length + 1);
-             for (var i = 0; i < lenStr.length; i++) {
-               lengthAry[i] = parseInt(lenStr[i]);
-             }
-             lengthAry[lenStr.length] = 255;
-       
-             if (Blob) {
-               var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
-               doneCallback(null, blob);
-             }
-           });
-         }
-       
-         map(packets, encodeOne, function(err, results) {
-           return callback(new Blob(results));
-         });
-       };
-       
-       /*
-        * Decodes data when a payload is maybe expected. Strings are decoded by
-        * interpreting each byte as a key code for entries marked to start with 0. See
-        * description of encodePayloadAsBinary
-        *
-        * @param {ArrayBuffer} data, callback method
-        * @api public
-        */
-       
-       exports.decodePayloadAsBinary = function (data, binaryType, callback) {
-         if (typeof binaryType === 'function') {
-           callback = binaryType;
-           binaryType = null;
-         }
-       
-         var bufferTail = data;
-         var buffers = [];
-       
-         while (bufferTail.byteLength > 0) {
-           var tailArray = new Uint8Array(bufferTail);
-           var isString = tailArray[0] === 0;
-           var msgLength = '';
-       
-           for (var i = 1; ; i++) {
-             if (tailArray[i] === 255) break;
-       
-             // 310 = char length of Number.MAX_VALUE
-             if (msgLength.length > 310) {
-               return callback(err, 0, 1);
-             }
-       
-             msgLength += tailArray[i];
-           }
-       
-           bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
-           msgLength = parseInt(msgLength);
-       
-           var msg = sliceBuffer(bufferTail, 0, msgLength);
-           if (isString) {
-             try {
-               msg = String.fromCharCode.apply(null, new Uint8Array(msg));
-             } catch (e) {
-               // iPhone Safari doesn't let you apply to typed arrays
-               var typed = new Uint8Array(msg);
-               msg = '';
-               for (var i = 0; i < typed.length; i++) {
-                 msg += String.fromCharCode(typed[i]);
-               }
-             }
-           }
-       
-           buffers.push(msg);
-           bufferTail = sliceBuffer(bufferTail, msgLength);
-         }
-       
-         var total = buffers.length;
-         buffers.forEach(function(buffer, i) {
-           callback(exports.decodePacket(buffer, binaryType, true), i, total);
-         });
-       };
-
-
-/***/ }),
-/* 23 */
-/***/ (function(module, exports) {
-
-       
-       /**
-        * Gets the keys for an object.
-        *
-        * @return {Array} keys
-        * @api private
-        */
-       
-       module.exports = Object.keys || function keys (obj){
-         var arr = [];
-         var has = Object.prototype.hasOwnProperty;
-       
-         for (var i in obj) {
-           if (has.call(obj, i)) {
-             arr.push(i);
-           }
-         }
-         return arr;
-       };
-
-
-/***/ }),
-/* 24 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       /* global Blob File */
-       
-       /*
-        * Module requirements.
-        */
-       
-       var isArray = __webpack_require__(10);
-       
-       var toString = Object.prototype.toString;
-       var withNativeBlob = typeof Blob === 'function' ||
-                               typeof Blob !== 'undefined' && toString.call(Blob) === '[object BlobConstructor]';
-       var withNativeFile = typeof File === 'function' ||
-                               typeof File !== 'undefined' && toString.call(File) === '[object FileConstructor]';
-       
-       /**
-        * Module exports.
-        */
-       
-       module.exports = hasBinary;
-       
-       /**
-        * Checks for binary data.
-        *
-        * Supports Buffer, ArrayBuffer, Blob and File.
-        *
-        * @param {Object} anything
-        * @api public
-        */
-       
-       function hasBinary (obj) {
-         if (!obj || typeof obj !== 'object') {
-           return false;
-         }
-       
-         if (isArray(obj)) {
-           for (var i = 0, l = obj.length; i < l; i++) {
-             if (hasBinary(obj[i])) {
-               return true;
-             }
-           }
-           return false;
-         }
-       
-         if ((typeof Buffer === 'function' && Buffer.isBuffer && Buffer.isBuffer(obj)) ||
-           (typeof ArrayBuffer === 'function' && obj instanceof ArrayBuffer) ||
-           (withNativeBlob && obj instanceof Blob) ||
-           (withNativeFile && obj instanceof File)
-         ) {
-           return true;
-         }
-       
-         // see: https://github.com/Automattic/has-binary/pull/4
-         if (obj.toJSON && typeof obj.toJSON === 'function' && arguments.length === 1) {
-           return hasBinary(obj.toJSON(), true);
-         }
-       
-         for (var key in obj) {
-           if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
-             return true;
-           }
-         }
-       
-         return false;
-       }
-
-
-/***/ }),
-/* 25 */
-/***/ (function(module, exports) {
-
-       /**
-        * An abstraction for slicing an arraybuffer even when
-        * ArrayBuffer.prototype.slice is not supported
-        *
-        * @api public
-        */
-       
-       module.exports = function(arraybuffer, start, end) {
-         var bytes = arraybuffer.byteLength;
-         start = start || 0;
-         end = end || bytes;
-       
-         if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
-       
-         if (start < 0) { start += bytes; }
-         if (end < 0) { end += bytes; }
-         if (end > bytes) { end = bytes; }
-       
-         if (start >= bytes || start >= end || bytes === 0) {
-           return new ArrayBuffer(0);
-         }
-       
-         var abv = new Uint8Array(arraybuffer);
-         var result = new Uint8Array(end - start);
-         for (var i = start, ii = 0; i < end; i++, ii++) {
-           result[ii] = abv[i];
-         }
-         return result.buffer;
-       };
-
-
-/***/ }),
-/* 26 */
-/***/ (function(module, exports) {
-
-       module.exports = after
-       
-       function after(count, callback, err_cb) {
-           var bail = false
-           err_cb = err_cb || noop
-           proxy.count = count
-       
-           return (count === 0) ? callback() : proxy
-       
-           function proxy(err, result) {
-               if (proxy.count <= 0) {
-                   throw new Error('after called too many times')
-               }
-               --proxy.count
-       
-               // after first error, rest are passed to err_cb
-               if (err) {
-                   bail = true
-                   callback(err)
-                   // future error callbacks will go to error handler
-                   callback = err_cb
-               } else if (proxy.count === 0 && !bail) {
-                   callback(null, result)
-               }
-           }
-       }
-       
-       function noop() {}
-
-
-/***/ }),
-/* 27 */
-/***/ (function(module, exports) {
-
-       /*! https://mths.be/utf8js v2.1.2 by @mathias */
-       
-       var stringFromCharCode = String.fromCharCode;
-       
-       // Taken from https://mths.be/punycode
-       function ucs2decode(string) {
-               var output = [];
-               var counter = 0;
-               var length = string.length;
-               var value;
-               var 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;
-       }
-       
-       // Taken from https://mths.be/punycode
-       function ucs2encode(array) {
-               var length = array.length;
-               var index = -1;
-               var value;
-               var output = '';
-               while (++index < length) {
-                       value = array[index];
-                       if (value > 0xFFFF) {
-                               value -= 0x10000;
-                               output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
-                               value = 0xDC00 | value & 0x3FF;
-                       }
-                       output += stringFromCharCode(value);
-               }
-               return output;
-       }
-       
-       function checkScalarValue(codePoint, strict) {
-               if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {
-                       if (strict) {
-                               throw Error(
-                                       'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +
-                                       ' is not a scalar value'
-                               );
-                       }
-                       return false;
-               }
-               return true;
-       }
-       /*--------------------------------------------------------------------------*/
-       
-       function createByte(codePoint, shift) {
-               return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
-       }
-       
-       function encodeCodePoint(codePoint, strict) {
-               if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
-                       return stringFromCharCode(codePoint);
-               }
-               var symbol = '';
-               if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
-                       symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
-               }
-               else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
-                       if (!checkScalarValue(codePoint, strict)) {
-                               codePoint = 0xFFFD;
-                       }
-                       symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
-                       symbol += createByte(codePoint, 6);
-               }
-               else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
-                       symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
-                       symbol += createByte(codePoint, 12);
-                       symbol += createByte(codePoint, 6);
-               }
-               symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
-               return symbol;
-       }
-       
-       function utf8encode(string, opts) {
-               opts = opts || {};
-               var strict = false !== opts.strict;
-       
-               var codePoints = ucs2decode(string);
-               var length = codePoints.length;
-               var index = -1;
-               var codePoint;
-               var byteString = '';
-               while (++index < length) {
-                       codePoint = codePoints[index];
-                       byteString += encodeCodePoint(codePoint, strict);
-               }
-               return byteString;
-       }
-       
-       /*--------------------------------------------------------------------------*/
-       
-       function readContinuationByte() {
-               if (byteIndex >= byteCount) {
-                       throw Error('Invalid byte index');
-               }
-       
-               var continuationByte = byteArray[byteIndex] & 0xFF;
-               byteIndex++;
-       
-               if ((continuationByte & 0xC0) == 0x80) {
-                       return continuationByte & 0x3F;
-               }
-       
-               // If we end up here, it’s not a continuation byte
-               throw Error('Invalid continuation byte');
-       }
-       
-       function decodeSymbol(strict) {
-               var byte1;
-               var byte2;
-               var byte3;
-               var byte4;
-               var codePoint;
-       
-               if (byteIndex > byteCount) {
-                       throw Error('Invalid byte index');
-               }
-       
-               if (byteIndex == byteCount) {
-                       return false;
-               }
-       
-               // Read first byte
-               byte1 = byteArray[byteIndex] & 0xFF;
-               byteIndex++;
-       
-               // 1-byte sequence (no continuation bytes)
-               if ((byte1 & 0x80) == 0) {
-                       return byte1;
-               }
-       
-               // 2-byte sequence
-               if ((byte1 & 0xE0) == 0xC0) {
-                       byte2 = readContinuationByte();
-                       codePoint = ((byte1 & 0x1F) << 6) | byte2;
-                       if (codePoint >= 0x80) {
-                               return codePoint;
-                       } else {
-                               throw Error('Invalid continuation byte');
-                       }
-               }
-       
-               // 3-byte sequence (may include unpaired surrogates)
-               if ((byte1 & 0xF0) == 0xE0) {
-                       byte2 = readContinuationByte();
-                       byte3 = readContinuationByte();
-                       codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
-                       if (codePoint >= 0x0800) {
-                               return checkScalarValue(codePoint, strict) ? codePoint : 0xFFFD;
-                       } else {
-                               throw Error('Invalid continuation byte');
-                       }
-               }
-       
-               // 4-byte sequence
-               if ((byte1 & 0xF8) == 0xF0) {
-                       byte2 = readContinuationByte();
-                       byte3 = readContinuationByte();
-                       byte4 = readContinuationByte();
-                       codePoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0C) |
-                               (byte3 << 0x06) | byte4;
-                       if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
-                               return codePoint;
-                       }
-               }
-       
-               throw Error('Invalid UTF-8 detected');
-       }
-       
-       var byteArray;
-       var byteCount;
-       var byteIndex;
-       function utf8decode(byteString, opts) {
-               opts = opts || {};
-               var strict = false !== opts.strict;
-       
-               byteArray = ucs2decode(byteString);
-               byteCount = byteArray.length;
-               byteIndex = 0;
-               var codePoints = [];
-               var tmp;
-               while ((tmp = decodeSymbol(strict)) !== false) {
-                       codePoints.push(tmp);
-               }
-               return ucs2encode(codePoints);
-       }
-       
-       module.exports = {
-               version: '2.1.2',
-               encode: utf8encode,
-               decode: utf8decode
-       };
-
-
-/***/ }),
-/* 28 */
-/***/ (function(module, exports) {
-
-       /*
-        * base64-arraybuffer
-        * https://github.com/niklasvh/base64-arraybuffer
-        *
-        * Copyright (c) 2012 Niklas von Hertzen
-        * Licensed under the MIT license.
-        */
-       (function(chars){
-         "use strict";
-       
-         exports.encode = function(arraybuffer) {
-           var bytes = new Uint8Array(arraybuffer),
-           i, len = bytes.length, base64 = "";
-       
-           for (i = 0; i < len; i+=3) {
-             base64 += chars[bytes[i] >> 2];
-             base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
-             base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
-             base64 += chars[bytes[i + 2] & 63];
-           }
-       
-           if ((len % 3) === 2) {
-             base64 = base64.substring(0, base64.length - 1) + "=";
-           } else if (len % 3 === 1) {
-             base64 = base64.substring(0, base64.length - 2) + "==";
-           }
-       
-           return base64;
-         };
-       
-         exports.decode =  function(base64) {
-           var bufferLength = base64.length * 0.75,
-           len = base64.length, i, p = 0,
-           encoded1, encoded2, encoded3, encoded4;
-       
-           if (base64[base64.length - 1] === "=") {
-             bufferLength--;
-             if (base64[base64.length - 2] === "=") {
-               bufferLength--;
-             }
-           }
-       
-           var arraybuffer = new ArrayBuffer(bufferLength),
-           bytes = new Uint8Array(arraybuffer);
-       
-           for (i = 0; i < len; i+=4) {
-             encoded1 = chars.indexOf(base64[i]);
-             encoded2 = chars.indexOf(base64[i+1]);
-             encoded3 = chars.indexOf(base64[i+2]);
-             encoded4 = chars.indexOf(base64[i+3]);
-       
-             bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
-             bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
-             bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
-           }
-       
-           return arraybuffer;
-         };
-       })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
-
-
-/***/ }),
-/* 29 */
-/***/ (function(module, exports) {
-
-       /**
-        * Create a blob builder even when vendor prefixes exist
-        */
-       
-       var BlobBuilder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
-         typeof WebKitBlobBuilder !== 'undefined' ? WebKitBlobBuilder :
-         typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
-         typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : 
-         false;
-       
-       /**
-        * Check if Blob constructor is supported
-        */
-       
-       var blobSupported = (function() {
-         try {
-           var a = new Blob(['hi']);
-           return a.size === 2;
-         } catch(e) {
-           return false;
-         }
-       })();
-       
-       /**
-        * Check if Blob constructor supports ArrayBufferViews
-        * Fails in Safari 6, so we need to map to ArrayBuffers there.
-        */
-       
-       var blobSupportsArrayBufferView = blobSupported && (function() {
-         try {
-           var b = new Blob([new Uint8Array([1,2])]);
-           return b.size === 2;
-         } catch(e) {
-           return false;
-         }
-       })();
-       
-       /**
-        * Check if BlobBuilder is supported
-        */
-       
-       var blobBuilderSupported = BlobBuilder
-         && BlobBuilder.prototype.append
-         && BlobBuilder.prototype.getBlob;
-       
-       /**
-        * Helper function that maps ArrayBufferViews to ArrayBuffers
-        * Used by BlobBuilder constructor and old browsers that didn't
-        * support it in the Blob constructor.
-        */
-       
-       function mapArrayBufferViews(ary) {
-         return ary.map(function(chunk) {
-           if (chunk.buffer instanceof ArrayBuffer) {
-             var buf = chunk.buffer;
-       
-             // if this is a subarray, make a copy so we only
-             // include the subarray region from the underlying buffer
-             if (chunk.byteLength !== buf.byteLength) {
-               var copy = new Uint8Array(chunk.byteLength);
-               copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
-               buf = copy.buffer;
-             }
-       
-             return buf;
-           }
-       
-           return chunk;
-         });
-       }
-       
-       function BlobBuilderConstructor(ary, options) {
-         options = options || {};
-       
-         var bb = new BlobBuilder();
-         mapArrayBufferViews(ary).forEach(function(part) {
-           bb.append(part);
-         });
-       
-         return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
-       };
-       
-       function BlobConstructor(ary, options) {
-         return new Blob(mapArrayBufferViews(ary), options || {});
-       };
-       
-       if (typeof Blob !== 'undefined') {
-         BlobBuilderConstructor.prototype = Blob.prototype;
-         BlobConstructor.prototype = Blob.prototype;
-       }
-       
-       module.exports = (function() {
-         if (blobSupported) {
-           return blobSupportsArrayBufferView ? Blob : BlobConstructor;
-         } else if (blobBuilderSupported) {
-           return BlobBuilderConstructor;
-         } else {
-           return undefined;
-         }
-       })();
-
-
-/***/ }),
-/* 30 */
-/***/ (function(module, exports) {
-
-       /**
-        * Compiles a querystring
-        * Returns string representation of the object
-        *
-        * @param {Object}
-        * @api private
-        */
-       
-       exports.encode = function (obj) {
-         var str = '';
-       
-         for (var i in obj) {
-           if (obj.hasOwnProperty(i)) {
-             if (str.length) str += '&';
-             str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
-           }
-         }
-       
-         return str;
-       };
-       
-       /**
-        * Parses a simple querystring into an object
-        *
-        * @param {String} qs
-        * @api private
-        */
-       
-       exports.decode = function(qs){
-         var qry = {};
-         var pairs = qs.split('&');
-         for (var i = 0, l = pairs.length; i < l; i++) {
-           var pair = pairs[i].split('=');
-           qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
-         }
-         return qry;
-       };
-
-
-/***/ }),
-/* 31 */
-/***/ (function(module, exports) {
-
-       
-       module.exports = function(a, b){
-         var fn = function(){};
-         fn.prototype = b.prototype;
-         a.prototype = new fn;
-         a.prototype.constructor = a;
-       };
-
-/***/ }),
-/* 32 */
-/***/ (function(module, exports) {
-
-       'use strict';
-       
-       var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('')
-         , length = 64
-         , map = {}
-         , seed = 0
-         , i = 0
-         , prev;
-       
-       /**
-        * Return a string representing the specified number.
-        *
-        * @param {Number} num The number to convert.
-        * @returns {String} The string representation of the number.
-        * @api public
-        */
-       function encode(num) {
-         var encoded = '';
-       
-         do {
-           encoded = alphabet[num % length] + encoded;
-           num = Math.floor(num / length);
-         } while (num > 0);
-       
-         return encoded;
-       }
-       
-       /**
-        * Return the integer value specified by the given string.
-        *
-        * @param {String} str The string to convert.
-        * @returns {Number} The integer value represented by the string.
-        * @api public
-        */
-       function decode(str) {
-         var decoded = 0;
-       
-         for (i = 0; i < str.length; i++) {
-           decoded = decoded * length + map[str.charAt(i)];
-         }
-       
-         return decoded;
-       }
-       
-       /**
-        * Yeast: A tiny growing id generator.
-        *
-        * @returns {String} A unique id.
-        * @api public
-        */
-       function yeast() {
-         var now = encode(+new Date());
-       
-         if (now !== prev) return seed = 0, prev = now;
-         return now +'.'+ encode(seed++);
-       }
-       
-       //
-       // Map each character to its index.
-       //
-       for (; i < length; i++) map[alphabet[i]] = i;
-       
-       //
-       // Expose the `yeast`, `encode` and `decode` functions.
-       //
-       yeast.encode = encode;
-       yeast.decode = decode;
-       module.exports = yeast;
-
-
-/***/ }),
-/* 33 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       /**
-        * Module requirements.
-        */
-       
-       var Polling = __webpack_require__(20);
-       var inherit = __webpack_require__(31);
-       var globalThis = __webpack_require__(18);
-       
-       /**
-        * Module exports.
-        */
-       
-       module.exports = JSONPPolling;
-       
-       /**
-        * Cached regular expressions.
-        */
-       
-       var rNewline = /\n/g;
-       var rEscapedNewline = /\\n/g;
-       
-       /**
-        * Global JSONP callbacks.
-        */
-       
-       var callbacks;
-       
-       /**
-        * Noop.
-        */
-       
-       function empty () { }
-       
-       /**
-        * JSONP Polling constructor.
-        *
-        * @param {Object} opts.
-        * @api public
-        */
-       
-       function JSONPPolling (opts) {
-         Polling.call(this, opts);
-       
-         this.query = this.query || {};
-       
-         // define global callbacks array if not present
-         // we do this here (lazily) to avoid unneeded global pollution
-         if (!callbacks) {
-           // we need to consider multiple engines in the same page
-           callbacks = globalThis.___eio = (globalThis.___eio || []);
-         }
-       
-         // callback identifier
-         this.index = callbacks.length;
-       
-         // add callback to jsonp global
-         var self = this;
-         callbacks.push(function (msg) {
-           self.onData(msg);
-         });
-       
-         // append to query string
-         this.query.j = this.index;
-       
-         // prevent spurious errors from being emitted when the window is unloaded
-         if (typeof addEventListener === 'function') {
-           addEventListener('beforeunload', function () {
-             if (self.script) self.script.onerror = empty;
-           }, false);
-         }
-       }
-       
-       /**
-        * Inherits from Polling.
-        */
-       
-       inherit(JSONPPolling, Polling);
-       
-       /*
-        * JSONP only supports binary as base64 encoded strings
-        */
-       
-       JSONPPolling.prototype.supportsBinary = false;
-       
-       /**
-        * Closes the socket.
-        *
-        * @api private
-        */
-       
-       JSONPPolling.prototype.doClose = function () {
-         if (this.script) {
-           this.script.parentNode.removeChild(this.script);
-           this.script = null;
-         }
-       
-         if (this.form) {
-           this.form.parentNode.removeChild(this.form);
-           this.form = null;
-           this.iframe = null;
-         }
-       
-         Polling.prototype.doClose.call(this);
-       };
-       
-       /**
-        * Starts a poll cycle.
-        *
-        * @api private
-        */
-       
-       JSONPPolling.prototype.doPoll = function () {
-         var self = this;
-         var script = document.createElement('script');
-       
-         if (this.script) {
-           this.script.parentNode.removeChild(this.script);
-           this.script = null;
-         }
-       
-         script.async = true;
-         script.src = this.uri();
-         script.onerror = function (e) {
-           self.onError('jsonp poll error', e);
-         };
-       
-         var insertAt = document.getElementsByTagName('script')[0];
-         if (insertAt) {
-           insertAt.parentNode.insertBefore(script, insertAt);
-         } else {
-           (document.head || document.body).appendChild(script);
-         }
-         this.script = script;
-       
-         var isUAgecko = 'undefined' !== typeof navigator && /gecko/i.test(navigator.userAgent);
-       
-         if (isUAgecko) {
-           setTimeout(function () {
-             var iframe = document.createElement('iframe');
-             document.body.appendChild(iframe);
-             document.body.removeChild(iframe);
-           }, 100);
-         }
-       };
-       
-       /**
-        * Writes with a hidden iframe.
-        *
-        * @param {String} data to send
-        * @param {Function} called upon flush.
-        * @api private
-        */
-       
-       JSONPPolling.prototype.doWrite = function (data, fn) {
-         var self = this;
-       
-         if (!this.form) {
-           var form = document.createElement('form');
-           var area = document.createElement('textarea');
-           var id = this.iframeId = 'eio_iframe_' + this.index;
-           var iframe;
-       
-           form.className = 'socketio';
-           form.style.position = 'absolute';
-           form.style.top = '-1000px';
-           form.style.left = '-1000px';
-           form.target = id;
-           form.method = 'POST';
-           form.setAttribute('accept-charset', 'utf-8');
-           area.name = 'd';
-           form.appendChild(area);
-           document.body.appendChild(form);
-       
-           this.form = form;
-           this.area = area;
-         }
-       
-         this.form.action = this.uri();
-       
-         function complete () {
-           initIframe();
-           fn();
-         }
-       
-         function initIframe () {
-           if (self.iframe) {
-             try {
-               self.form.removeChild(self.iframe);
-             } catch (e) {
-               self.onError('jsonp polling iframe removal error', e);
-             }
-           }
-       
-           try {
-             // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
-             var html = '<iframe src="javascript:0" name="' + self.iframeId + '">';
-             iframe = document.createElement(html);
-           } catch (e) {
-             iframe = document.createElement('iframe');
-             iframe.name = self.iframeId;
-             iframe.src = 'javascript:0';
-           }
-       
-           iframe.id = self.iframeId;
-       
-           self.form.appendChild(iframe);
-           self.iframe = iframe;
-         }
-       
-         initIframe();
-       
-         // escape \n to prevent it from being converted into \r\n by some UAs
-         // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
-         data = data.replace(rEscapedNewline, '\\\n');
-         this.area.value = data.replace(rNewline, '\\n');
-       
-         try {
-           this.form.submit();
-         } catch (e) {}
-       
-         if (this.iframe.attachEvent) {
-           this.iframe.onreadystatechange = function () {
-             if (self.iframe.readyState === 'complete') {
-               complete();
-             }
-           };
-         } else {
-           this.iframe.onload = complete;
-         }
-       };
-
-
-/***/ }),
-/* 34 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       /**
-        * Module dependencies.
-        */
-       
-       var Transport = __webpack_require__(21);
-       var parser = __webpack_require__(22);
-       var parseqs = __webpack_require__(30);
-       var inherit = __webpack_require__(31);
-       var yeast = __webpack_require__(32);
-       var debug = __webpack_require__(3)('engine.io-client:websocket');
-       
-       var BrowserWebSocket, NodeWebSocket;
-       
-       if (typeof WebSocket !== 'undefined') {
-         BrowserWebSocket = WebSocket;
-       } else if (typeof self !== 'undefined') {
-         BrowserWebSocket = self.WebSocket || self.MozWebSocket;
-       }
-       
-       if (typeof window === 'undefined') {
-         try {
-           NodeWebSocket = __webpack_require__(35);
-         } catch (e) { }
-       }
-       
-       /**
-        * Get either the `WebSocket` or `MozWebSocket` globals
-        * in the browser or try to resolve WebSocket-compatible
-        * interface exposed by `ws` for Node-like environment.
-        */
-       
-       var WebSocketImpl = BrowserWebSocket || NodeWebSocket;
-       
-       /**
-        * Module exports.
-        */
-       
-       module.exports = WS;
-       
-       /**
-        * WebSocket transport constructor.
-        *
-        * @api {Object} connection options
-        * @api public
-        */
-       
-       function WS (opts) {
-         var forceBase64 = (opts && opts.forceBase64);
-         if (forceBase64) {
-           this.supportsBinary = false;
-         }
-         this.perMessageDeflate = opts.perMessageDeflate;
-         this.usingBrowserWebSocket = BrowserWebSocket && !opts.forceNode;
-         this.protocols = opts.protocols;
-         if (!this.usingBrowserWebSocket) {
-           WebSocketImpl = NodeWebSocket;
-         }
-         Transport.call(this, opts);
-       }
-       
-       /**
-        * Inherits from Transport.
-        */
-       
-       inherit(WS, Transport);
-       
-       /**
-        * Transport name.
-        *
-        * @api public
-        */
-       
-       WS.prototype.name = 'websocket';
-       
-       /*
-        * WebSockets support binary
-        */
-       
-       WS.prototype.supportsBinary = true;
-       
-       /**
-        * Opens socket.
-        *
-        * @api private
-        */
-       
-       WS.prototype.doOpen = function () {
-         if (!this.check()) {
-           // let probe timeout
-           return;
-         }
-       
-         var uri = this.uri();
-         var protocols = this.protocols;
-       
-         var opts = {};
-       
-         if (!this.isReactNative) {
-           opts.agent = this.agent;
-           opts.perMessageDeflate = this.perMessageDeflate;
-       
-           // SSL options for Node.js client
-           opts.pfx = this.pfx;
-           opts.key = this.key;
-           opts.passphrase = this.passphrase;
-           opts.cert = this.cert;
-           opts.ca = this.ca;
-           opts.ciphers = this.ciphers;
-           opts.rejectUnauthorized = this.rejectUnauthorized;
-         }
-       
-         if (this.extraHeaders) {
-           opts.headers = this.extraHeaders;
-         }
-         if (this.localAddress) {
-           opts.localAddress = this.localAddress;
-         }
-       
-         try {
-           this.ws =
-             this.usingBrowserWebSocket && !this.isReactNative
-               ? protocols
-                 ? new WebSocketImpl(uri, protocols)
-                 : new WebSocketImpl(uri)
-               : new WebSocketImpl(uri, protocols, opts);
-         } catch (err) {
-           return this.emit('error', err);
-         }
-       
-         if (this.ws.binaryType === undefined) {
-           this.supportsBinary = false;
-         }
-       
-         if (this.ws.supports && this.ws.supports.binary) {
-           this.supportsBinary = true;
-           this.ws.binaryType = 'nodebuffer';
-         } else {
-           this.ws.binaryType = 'arraybuffer';
-         }
-       
-         this.addEventListeners();
-       };
-       
-       /**
-        * Adds event listeners to the socket
-        *
-        * @api private
-        */
-       
-       WS.prototype.addEventListeners = function () {
-         var self = this;
-       
-         this.ws.onopen = function () {
-           self.onOpen();
-         };
-         this.ws.onclose = function () {
-           self.onClose();
-         };
-         this.ws.onmessage = function (ev) {
-           self.onData(ev.data);
-         };
-         this.ws.onerror = function (e) {
-           self.onError('websocket error', e);
-         };
-       };
-       
-       /**
-        * Writes data to socket.
-        *
-        * @param {Array} array of packets.
-        * @api private
-        */
-       
-       WS.prototype.write = function (packets) {
-         var self = this;
-         this.writable = false;
-       
-         // encodePacket efficient as it uses WS framing
-         // no need for encodePayload
-         var total = packets.length;
-         for (var i = 0, l = total; i < l; i++) {
-           (function (packet) {
-             parser.encodePacket(packet, self.supportsBinary, function (data) {
-               if (!self.usingBrowserWebSocket) {
-                 // always create a new object (GH-437)
-                 var opts = {};
-                 if (packet.options) {
-                   opts.compress = packet.options.compress;
-                 }
-       
-                 if (self.perMessageDeflate) {
-                   var len = 'string' === typeof data ? Buffer.byteLength(data) : data.length;
-                   if (len < self.perMessageDeflate.threshold) {
-                     opts.compress = false;
-                   }
-                 }
-               }
-       
-               // Sometimes the websocket has already been closed but the browser didn't
-               // have a chance of informing us about it yet, in that case send will
-               // throw an error
-               try {
-                 if (self.usingBrowserWebSocket) {
-                   // TypeError is thrown when passing the second argument on Safari
-                   self.ws.send(data);
-                 } else {
-                   self.ws.send(data, opts);
-                 }
-               } catch (e) {
-                 debug('websocket closed before onclose event');
-               }
-       
-               --total || done();
-             });
-           })(packets[i]);
-         }
-       
-         function done () {
-           self.emit('flush');
-       
-           // fake drain
-           // defer to next tick to allow Socket to clear writeBuffer
-           setTimeout(function () {
-             self.writable = true;
-             self.emit('drain');
-           }, 0);
-         }
-       };
-       
-       /**
-        * Called upon close
-        *
-        * @api private
-        */
-       
-       WS.prototype.onClose = function () {
-         Transport.prototype.onClose.call(this);
-       };
-       
-       /**
-        * Closes socket.
-        *
-        * @api private
-        */
-       
-       WS.prototype.doClose = function () {
-         if (typeof this.ws !== 'undefined') {
-           this.ws.close();
-         }
-       };
-       
-       /**
-        * Generates uri for connection.
-        *
-        * @api private
-        */
-       
-       WS.prototype.uri = function () {
-         var query = this.query || {};
-         var schema = this.secure ? 'wss' : 'ws';
-         var port = '';
-       
-         // avoid port if default for schema
-         if (this.port && (('wss' === schema && Number(this.port) !== 443) ||
-           ('ws' === schema && Number(this.port) !== 80))) {
-           port = ':' + this.port;
-         }
-       
-         // append timestamp to URI
-         if (this.timestampRequests) {
-           query[this.timestampParam] = yeast();
-         }
-       
-         // communicate binary support capabilities
-         if (!this.supportsBinary) {
-           query.b64 = 1;
-         }
-       
-         query = parseqs.encode(query);
-       
-         // prepend ? to query
-         if (query.length) {
-           query = '?' + query;
-         }
-       
-         var ipv6 = this.hostname.indexOf(':') !== -1;
-         return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
-       };
-       
-       /**
-        * Feature detection for WebSocket.
-        *
-        * @return {Boolean} whether this transport is available.
-        * @api public
-        */
-       
-       WS.prototype.check = function () {
-         return !!WebSocketImpl && !('__initialize' in WebSocketImpl && this.name === WS.prototype.name);
-       };
-
-
-/***/ }),
-/* 35 */
-/***/ (function(module, exports) {
-
-       /* (ignored) */
-
-/***/ }),
-/* 36 */
-/***/ (function(module, exports) {
-
-       
-       var indexOf = [].indexOf;
-       
-       module.exports = function(arr, obj){
-         if (indexOf) return arr.indexOf(obj);
-         for (var i = 0; i < arr.length; ++i) {
-           if (arr[i] === obj) return i;
-         }
-         return -1;
-       };
-
-/***/ }),
-/* 37 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       
-       /**
-        * Module dependencies.
-        */
-       
-       var parser = __webpack_require__(7);
-       var Emitter = __webpack_require__(8);
-       var toArray = __webpack_require__(38);
-       var on = __webpack_require__(39);
-       var bind = __webpack_require__(40);
-       var debug = __webpack_require__(3)('socket.io-client:socket');
-       var parseqs = __webpack_require__(30);
-       var hasBin = __webpack_require__(24);
-       
-       /**
-        * Module exports.
-        */
-       
-       module.exports = exports = Socket;
-       
-       /**
-        * Internal events (blacklisted).
-        * These events can't be emitted by the user.
-        *
-        * @api private
-        */
-       
-       var events = {
-         connect: 1,
-         connect_error: 1,
-         connect_timeout: 1,
-         connecting: 1,
-         disconnect: 1,
-         error: 1,
-         reconnect: 1,
-         reconnect_attempt: 1,
-         reconnect_failed: 1,
-         reconnect_error: 1,
-         reconnecting: 1,
-         ping: 1,
-         pong: 1
-       };
-       
-       /**
-        * Shortcut to `Emitter#emit`.
-        */
-       
-       var emit = Emitter.prototype.emit;
-       
-       /**
-        * `Socket` constructor.
-        *
-        * @api public
-        */
-       
-       function Socket (io, nsp, opts) {
-         this.io = io;
-         this.nsp = nsp;
-         this.json = this; // compat
-         this.ids = 0;
-         this.acks = {};
-         this.receiveBuffer = [];
-         this.sendBuffer = [];
-         this.connected = false;
-         this.disconnected = true;
-         this.flags = {};
-         if (opts && opts.query) {
-           this.query = opts.query;
-         }
-         if (this.io.autoConnect) this.open();
-       }
-       
-       /**
-        * Mix in `Emitter`.
-        */
-       
-       Emitter(Socket.prototype);
-       
-       /**
-        * Subscribe to open, close and packet events
-        *
-        * @api private
-        */
-       
-       Socket.prototype.subEvents = function () {
-         if (this.subs) return;
-       
-         var io = this.io;
-         this.subs = [
-           on(io, 'open', bind(this, 'onopen')),
-           on(io, 'packet', bind(this, 'onpacket')),
-           on(io, 'close', bind(this, 'onclose'))
-         ];
-       };
-       
-       /**
-        * "Opens" the socket.
-        *
-        * @api public
-        */
-       
-       Socket.prototype.open =
-       Socket.prototype.connect = function () {
-         if (this.connected) return this;
-       
-         this.subEvents();
-         if (!this.io.reconnecting) this.io.open(); // ensure open
-         if ('open' === this.io.readyState) this.onopen();
-         this.emit('connecting');
-         return this;
-       };
-       
-       /**
-        * Sends a `message` event.
-        *
-        * @return {Socket} self
-        * @api public
-        */
-       
-       Socket.prototype.send = function () {
-         var args = toArray(arguments);
-         args.unshift('message');
-         this.emit.apply(this, args);
-         return this;
-       };
-       
-       /**
-        * Override `emit`.
-        * If the event is in `events`, it's emitted normally.
-        *
-        * @param {String} event name
-        * @return {Socket} self
-        * @api public
-        */
-       
-       Socket.prototype.emit = function (ev) {
-         if (events.hasOwnProperty(ev)) {
-           emit.apply(this, arguments);
-           return this;
-         }
-       
-         var args = toArray(arguments);
-         var packet = {
-           type: (this.flags.binary !== undefined ? this.flags.binary : hasBin(args)) ? parser.BINARY_EVENT : parser.EVENT,
-           data: args
-         };
-       
-         packet.options = {};
-         packet.options.compress = !this.flags || false !== this.flags.compress;
-       
-         // event ack callback
-         if ('function' === typeof args[args.length - 1]) {
-           debug('emitting packet with ack id %d', this.ids);
-           this.acks[this.ids] = args.pop();
-           packet.id = this.ids++;
-         }
-       
-         if (this.connected) {
-           this.packet(packet);
-         } else {
-           this.sendBuffer.push(packet);
-         }
-       
-         this.flags = {};
-       
-         return this;
-       };
-       
-       /**
-        * Sends a packet.
-        *
-        * @param {Object} packet
-        * @api private
-        */
-       
-       Socket.prototype.packet = function (packet) {
-         packet.nsp = this.nsp;
-         this.io.packet(packet);
-       };
-       
-       /**
-        * Called upon engine `open`.
-        *
-        * @api private
-        */
-       
-       Socket.prototype.onopen = function () {
-         debug('transport is open - connecting');
-       
-         // write connect packet if necessary
-         if ('/' !== this.nsp) {
-           if (this.query) {
-             var query = typeof this.query === 'object' ? parseqs.encode(this.query) : this.query;
-             debug('sending connect packet with query %s', query);
-             this.packet({type: parser.CONNECT, query: query});
-           } else {
-             this.packet({type: parser.CONNECT});
-           }
-         }
-       };
-       
-       /**
-        * Called upon engine `close`.
-        *
-        * @param {String} reason
-        * @api private
-        */
-       
-       Socket.prototype.onclose = function (reason) {
-         debug('close (%s)', reason);
-         this.connected = false;
-         this.disconnected = true;
-         delete this.id;
-         this.emit('disconnect', reason);
-       };
-       
-       /**
-        * Called with socket packet.
-        *
-        * @param {Object} packet
-        * @api private
-        */
-       
-       Socket.prototype.onpacket = function (packet) {
-         var sameNamespace = packet.nsp === this.nsp;
-         var rootNamespaceError = packet.type === parser.ERROR && packet.nsp === '/';
-       
-         if (!sameNamespace && !rootNamespaceError) return;
-       
-         switch (packet.type) {
-           case parser.CONNECT:
-             this.onconnect();
-             break;
-       
-           case parser.EVENT:
-             this.onevent(packet);
-             break;
-       
-           case parser.BINARY_EVENT:
-             this.onevent(packet);
-             break;
-       
-           case parser.ACK:
-             this.onack(packet);
-             break;
-       
-           case parser.BINARY_ACK:
-             this.onack(packet);
-             break;
-       
-           case parser.DISCONNECT:
-             this.ondisconnect();
-             break;
-       
-           case parser.ERROR:
-             this.emit('error', packet.data);
-             break;
-         }
-       };
-       
-       /**
-        * Called upon a server event.
-        *
-        * @param {Object} packet
-        * @api private
-        */
-       
-       Socket.prototype.onevent = function (packet) {
-         var args = packet.data || [];
-         debug('emitting event %j', args);
-       
-         if (null != packet.id) {
-           debug('attaching ack callback to event');
-           args.push(this.ack(packet.id));
-         }
-       
-         if (this.connected) {
-           emit.apply(this, args);
-         } else {
-           this.receiveBuffer.push(args);
-         }
-       };
-       
-       /**
-        * Produces an ack callback to emit with an event.
-        *
-        * @api private
-        */
-       
-       Socket.prototype.ack = function (id) {
-         var self = this;
-         var sent = false;
-         return function () {
-           // prevent double callbacks
-           if (sent) return;
-           sent = true;
-           var args = toArray(arguments);
-           debug('sending ack %j', args);
-       
-           self.packet({
-             type: hasBin(args) ? parser.BINARY_ACK : parser.ACK,
-             id: id,
-             data: args
-           });
-         };
-       };
-       
-       /**
-        * Called upon a server acknowlegement.
-        *
-        * @param {Object} packet
-        * @api private
-        */
-       
-       Socket.prototype.onack = function (packet) {
-         var ack = this.acks[packet.id];
-         if ('function' === typeof ack) {
-           debug('calling ack %s with %j', packet.id, packet.data);
-           ack.apply(this, packet.data);
-           delete this.acks[packet.id];
-         } else {
-           debug('bad ack %s', packet.id);
-         }
-       };
-       
-       /**
-        * Called upon server connect.
-        *
-        * @api private
-        */
-       
-       Socket.prototype.onconnect = function () {
-         this.connected = true;
-         this.disconnected = false;
-         this.emit('connect');
-         this.emitBuffered();
-       };
-       
-       /**
-        * Emit buffered events (received and emitted).
-        *
-        * @api private
-        */
-       
-       Socket.prototype.emitBuffered = function () {
-         var i;
-         for (i = 0; i < this.receiveBuffer.length; i++) {
-           emit.apply(this, this.receiveBuffer[i]);
-         }
-         this.receiveBuffer = [];
-       
-         for (i = 0; i < this.sendBuffer.length; i++) {
-           this.packet(this.sendBuffer[i]);
-         }
-         this.sendBuffer = [];
-       };
-       
-       /**
-        * Called upon server disconnect.
-        *
-        * @api private
-        */
-       
-       Socket.prototype.ondisconnect = function () {
-         debug('server disconnect (%s)', this.nsp);
-         this.destroy();
-         this.onclose('io server disconnect');
-       };
-       
-       /**
-        * Called upon forced client/server side disconnections,
-        * this method ensures the manager stops tracking us and
-        * that reconnections don't get triggered for this.
-        *
-        * @api private.
-        */
-       
-       Socket.prototype.destroy = function () {
-         if (this.subs) {
-           // clean subscriptions to avoid reconnections
-           for (var i = 0; i < this.subs.length; i++) {
-             this.subs[i].destroy();
-           }
-           this.subs = null;
-         }
-       
-         this.io.destroy(this);
-       };
-       
-       /**
-        * Disconnects the socket manually.
-        *
-        * @return {Socket} self
-        * @api public
-        */
-       
-       Socket.prototype.close =
-       Socket.prototype.disconnect = function () {
-         if (this.connected) {
-           debug('performing disconnect (%s)', this.nsp);
-           this.packet({ type: parser.DISCONNECT });
-         }
-       
-         // remove socket from pool
-         this.destroy();
-       
-         if (this.connected) {
-           // fire events
-           this.onclose('io client disconnect');
-         }
-         return this;
-       };
-       
-       /**
-        * Sets the compress flag.
-        *
-        * @param {Boolean} if `true`, compresses the sending data
-        * @return {Socket} self
-        * @api public
-        */
-       
-       Socket.prototype.compress = function (compress) {
-         this.flags.compress = compress;
-         return this;
-       };
-       
-       /**
-        * Sets the binary flag
-        *
-        * @param {Boolean} whether the emitted data contains binary
-        * @return {Socket} self
-        * @api public
-        */
-       
-       Socket.prototype.binary = function (binary) {
-         this.flags.binary = binary;
-         return this;
-       };
-
-
-/***/ }),
-/* 38 */
-/***/ (function(module, exports) {
-
-       module.exports = toArray
-       
-       function toArray(list, index) {
-           var array = []
-       
-           index = index || 0
-       
-           for (var i = index || 0; i < list.length; i++) {
-               array[i - index] = list[i]
-           }
-       
-           return array
-       }
-
-
-/***/ }),
-/* 39 */
-/***/ (function(module, exports) {
-
-       
-       /**
-        * Module exports.
-        */
-       
-       module.exports = on;
-       
-       /**
-        * Helper for subscriptions.
-        *
-        * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
-        * @param {String} event name
-        * @param {Function} callback
-        * @api public
-        */
-       
-       function on (obj, ev, fn) {
-         obj.on(ev, fn);
-         return {
-           destroy: function () {
-             obj.removeListener(ev, fn);
-           }
-         };
-       }
-
-
-/***/ }),
-/* 40 */
-/***/ (function(module, exports) {
-
-       /**
-        * Slice reference.
-        */
-       
-       var slice = [].slice;
-       
-       /**
-        * Bind `obj` to `fn`.
-        *
-        * @param {Object} obj
-        * @param {Function|String} fn or string
-        * @return {Function}
-        * @api public
-        */
-       
-       module.exports = function(obj, fn){
-         if ('string' == typeof fn) fn = obj[fn];
-         if ('function' != typeof fn) throw new Error('bind() requires a function');
-         var args = slice.call(arguments, 2);
-         return function(){
-           return fn.apply(obj, args.concat(slice.call(arguments)));
-         }
-       };
-
-
-/***/ }),
-/* 41 */
-/***/ (function(module, exports) {
-
-       
-       /**
-        * Expose `Backoff`.
-        */
-       
-       module.exports = Backoff;
-       
-       /**
-        * Initialize backoff timer with `opts`.
-        *
-        * - `min` initial timeout in milliseconds [100]
-        * - `max` max timeout [10000]
-        * - `jitter` [0]
-        * - `factor` [2]
-        *
-        * @param {Object} opts
-        * @api public
-        */
-       
-       function Backoff(opts) {
-         opts = opts || {};
-         this.ms = opts.min || 100;
-         this.max = opts.max || 10000;
-         this.factor = opts.factor || 2;
-         this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
-         this.attempts = 0;
-       }
-       
-       /**
-        * Return the backoff duration.
-        *
-        * @return {Number}
-        * @api public
-        */
-       
-       Backoff.prototype.duration = function(){
-         var ms = this.ms * Math.pow(this.factor, this.attempts++);
-         if (this.jitter) {
-           var rand =  Math.random();
-           var deviation = Math.floor(rand * this.jitter * ms);
-           ms = (Math.floor(rand * 10) & 1) == 0  ? ms - deviation : ms + deviation;
-         }
-         return Math.min(ms, this.max) | 0;
-       };
-       
-       /**
-        * Reset the number of attempts.
-        *
-        * @api public
-        */
-       
-       Backoff.prototype.reset = function(){
-         this.attempts = 0;
-       };
-       
-       /**
-        * Set the minimum duration
-        *
-        * @api public
-        */
-       
-       Backoff.prototype.setMin = function(min){
-         this.ms = min;
-       };
-       
-       /**
-        * Set the maximum duration
-        *
-        * @api public
-        */
-       
-       Backoff.prototype.setMax = function(max){
-         this.max = max;
-       };
-       
-       /**
-        * Set the jitter
-        *
-        * @api public
-        */
-       
-       Backoff.prototype.setJitter = function(jitter){
-         this.jitter = jitter;
-       };
-       
-
-
-/***/ })
-/******/ ])
-});
-;
-//# sourceMappingURL=socket.io.dev.js.map
+!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.io=e():t.io=e()}(this,(function(){return function(t){var e={};function n(r){if(e[r])return e[r].exports;var o=e[r]={exports:{},id:r,loaded:!1};return t[r].call(o.exports,o,o.exports,n),o.loaded=!0,o.exports}return n.m=t,n.c=e,n.p="",n(0)}([function(t,e,n){var r=n(1),o=n(7),i=n(12),s=n(3)("socket.io-client");t.exports=e=c;var a=e.managers={};function c(t,e){"object"==typeof t&&(e=t,t=void 0),e=e||{};var n,o=r(t),c=o.source,p=o.id,h=o.path,u=a[p]&&h in a[p].nsps;return e.forceNew||e["force new connection"]||!1===e.multiplex||u?(s("ignoring socket cache for %s",c),n=i(c,e)):(a[p]||(s("new io instance for %s",c),a[p]=i(c,e)),n=a[p]),o.query&&!e.query&&(e.query=o.query),n.socket(o.path,e)}e.protocol=o.protocol,e.connect=c,e.Manager=n(12),e.Socket=n(37)},function(t,e,n){var r=n(2),o=n(3)("socket.io-client:url");t.exports=function(t,e){var n=t;e=e||"undefined"!=typeof location&&location,null==t&&(t=e.protocol+"//"+e.host);"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?e.protocol+t:e.host+t),/^(https?|wss?):\/\//.test(t)||(o("protocol-less url %s",t),t=void 0!==e?e.protocol+"//"+t:"https://"+t),o("parse %s",t),n=r(t));n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443"));n.path=n.path||"/";var i=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port,n.href=n.protocol+"://"+i+(e&&e.port===n.port?"":":"+n.port),n}},function(t,e){var n=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,r=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];t.exports=function(t){var e=t,o=t.indexOf("["),i=t.indexOf("]");-1!=o&&-1!=i&&(t=t.substring(0,o)+t.substring(o,i).replace(/:/g,";")+t.substring(i,t.length));for(var s,a,c=n.exec(t||""),p={},h=14;h--;)p[r[h]]=c[h]||"";return-1!=o&&-1!=i&&(p.source=e,p.host=p.host.substring(1,p.host.length-1).replace(/;/g,":"),p.authority=p.authority.replace("[","").replace("]","").replace(/;/g,":"),p.ipv6uri=!0),p.pathNames=function(t,e){var n=/\/{2,9}/g,r=e.replace(n,"/").split("/");"/"!=e.substr(0,1)&&0!==e.length||r.splice(0,1);"/"==e.substr(e.length-1,1)&&r.splice(r.length-1,1);return r}(0,p.path),p.queryKey=(s=p.query,a={},s.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(t,e,n){e&&(a[e]=n)})),a),p}},function(t,e,n){(function(r){"use strict";var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};function i(){var t;try{t=e.storage.debug}catch(t){}return!t&&void 0!==r&&"env"in r&&(t=r.env.DEBUG),t}(e=t.exports=n(5)).log=function(){return"object"===("undefined"==typeof console?"undefined":o(console))&&console.log&&Function.prototype.apply.call(console.log,console,arguments)},e.formatArgs=function(t){var n=this.useColors;if(t[0]=(n?"%c":"")+this.namespace+(n?" %c":" ")+t[0]+(n?"%c ":" ")+"+"+e.humanize(this.diff),!n)return;var r="color: "+this.color;t.splice(1,0,r,"color: inherit");var o=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(function(t){"%%"!==t&&(o++,"%c"===t&&(i=o))})),t.splice(i,0,r)},e.save=function(t){try{null==t?e.storage.removeItem("debug"):e.storage.debug=t}catch(t){}},e.load=i,e.useColors=function(){if("undefined"!=typeof window&&window.process&&"renderer"===window.process.type)return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},e.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(t){}}(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],e.formatters.j=function(t){try{return JSON.stringify(t)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}},e.enable(i())}).call(e,n(4))},function(t,e){var n,r,o=t.exports={};function i(){throw new Error("setTimeout has not been defined")}function s(){throw new Error("clearTimeout has not been defined")}function a(t){if(n===setTimeout)return setTimeout(t,0);if((n===i||!n)&&setTimeout)return n=setTimeout,setTimeout(t,0);try{return n(t,0)}catch(e){try{return n.call(null,t,0)}catch(e){return n.call(this,t,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:i}catch(t){n=i}try{r="function"==typeof clearTimeout?clearTimeout:s}catch(t){r=s}}();var c,p=[],h=!1,u=-1;function f(){h&&c&&(h=!1,c.length?p=c.concat(p):u=-1,p.length&&l())}function l(){if(!h){var t=a(f);h=!0;for(var e=p.length;e;){for(c=p,p=[];++u<e;)c&&c[u].run();u=-1,e=p.length}c=null,h=!1,function(t){if(r===clearTimeout)return clearTimeout(t);if((r===s||!r)&&clearTimeout)return r=clearTimeout,clearTimeout(t);try{r(t)}catch(e){try{return r.call(null,t)}catch(e){return r.call(this,t)}}}(t)}}function d(t,e){this.fun=t,this.array=e}function y(){}o.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];p.push(new d(t,e)),1!==p.length||h||a(l)},d.prototype.run=function(){this.fun.apply(null,this.array)},o.title="browser",o.browser=!0,o.env={},o.argv=[],o.version="",o.versions={},o.on=y,o.addListener=y,o.once=y,o.off=y,o.removeListener=y,o.removeAllListeners=y,o.emit=y,o.prependListener=y,o.prependOnceListener=y,o.listeners=function(t){return[]},o.binding=function(t){throw new Error("process.binding is not supported")},o.cwd=function(){return"/"},o.chdir=function(t){throw new Error("process.chdir is not supported")},o.umask=function(){return 0}},function(t,e,n){"use strict";function r(t){var n;function r(){if(r.enabled){var t=r,o=+new Date,i=o-(n||o);t.diff=i,t.prev=n,t.curr=o,n=o;for(var s=new Array(arguments.length),a=0;a<s.length;a++)s[a]=arguments[a];s[0]=e.coerce(s[0]),"string"!=typeof s[0]&&s.unshift("%O");var c=0;s[0]=s[0].replace(/%([a-zA-Z%])/g,(function(n,r){if("%%"===n)return n;c++;var o=e.formatters[r];if("function"==typeof o){var i=s[c];n=o.call(t,i),s.splice(c,1),c--}return n})),e.formatArgs.call(t,s);var p=r.log||e.log||console.log.bind(console);p.apply(t,s)}}return r.namespace=t,r.enabled=e.enabled(t),r.useColors=e.useColors(),r.color=function(t){var n,r=0;for(n in t)r=(r<<5)-r+t.charCodeAt(n),r|=0;return e.colors[Math.abs(r)%e.colors.length]}(t),r.destroy=o,"function"==typeof e.init&&e.init(r),e.instances.push(r),r}function o(){var t=e.instances.indexOf(this);return-1!==t&&(e.instances.splice(t,1),!0)}(e=t.exports=r.debug=r.default=r).coerce=function(t){return t instanceof Error?t.stack||t.message:t},e.disable=function(){e.enable("")},e.enable=function(t){var n;e.save(t),e.names=[],e.skips=[];var r=("string"==typeof t?t:"").split(/[\s,]+/),o=r.length;for(n=0;n<o;n++)r[n]&&("-"===(t=r[n].replace(/\*/g,".*?"))[0]?e.skips.push(new RegExp("^"+t.substr(1)+"$")):e.names.push(new RegExp("^"+t+"$")));for(n=0;n<e.instances.length;n++){var i=e.instances[n];i.enabled=e.enabled(i.namespace)}},e.enabled=function(t){if("*"===t[t.length-1])return!0;var n,r;for(n=0,r=e.skips.length;n<r;n++)if(e.skips[n].test(t))return!1;for(n=0,r=e.names.length;n<r;n++)if(e.names[n].test(t))return!0;return!1},e.humanize=n(6),e.instances=[],e.names=[],e.skips=[],e.formatters={}},function(t,e){var n=1e3,r=60*n,o=60*r,i=24*o,s=365.25*i;function a(t,e,n){if(!(t<e))return t<1.5*e?Math.floor(t/e)+" "+n:Math.ceil(t/e)+" "+n+"s"}t.exports=function(t,e){e=e||{};var c,p=typeof t;if("string"===p&&t.length>0)return function(t){if((t=String(t)).length>100)return;var e=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(t);if(!e)return;var a=parseFloat(e[1]);switch((e[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return a*s;case"days":case"day":case"d":return a*i;case"hours":case"hour":case"hrs":case"hr":case"h":return a*o;case"minutes":case"minute":case"mins":case"min":case"m":return a*r;case"seconds":case"second":case"secs":case"sec":case"s":return a*n;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return a;default:return}}(t);if("number"===p&&!1===isNaN(t))return e.long?a(c=t,i,"day")||a(c,o,"hour")||a(c,r,"minute")||a(c,n,"second")||c+" ms":function(t){if(t>=i)return Math.round(t/i)+"d";if(t>=o)return Math.round(t/o)+"h";if(t>=r)return Math.round(t/r)+"m";if(t>=n)return Math.round(t/n)+"s";return t+"ms"}(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))}},function(t,e,n){var r=n(3)("socket.io-parser"),o=n(8),i=n(9),s=n(10),a=n(11);function c(){}e.protocol=4,e.types=["CONNECT","DISCONNECT","EVENT","ACK","ERROR","BINARY_EVENT","BINARY_ACK"],e.CONNECT=0,e.DISCONNECT=1,e.EVENT=2,e.ACK=3,e.ERROR=4,e.BINARY_EVENT=5,e.BINARY_ACK=6,e.Encoder=c,e.Decoder=u;var p=e.ERROR+'"encode error"';function h(t){var n=""+t.type;if(e.BINARY_EVENT!==t.type&&e.BINARY_ACK!==t.type||(n+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(n+=t.nsp+","),null!=t.id&&(n+=t.id),null!=t.data){var o=function(t){try{return JSON.stringify(t)}catch(t){return!1}}(t.data);if(!1===o)return p;n+=o}return r("encoded %j as %s",t,n),n}function u(){this.reconstructor=null}function f(t){this.reconPack=t,this.buffers=[]}function l(t){return{type:e.ERROR,data:"parser error: "+t}}c.prototype.encode=function(t,n){(r("encoding packet %j",t),e.BINARY_EVENT===t.type||e.BINARY_ACK===t.type)?function(t,e){function n(t){var n=i.deconstructPacket(t),r=h(n.packet),o=n.buffers;o.unshift(r),e(o)}i.removeBlobs(t,n)}(t,n):n([h(t)])},o(u.prototype),u.prototype.add=function(t){var n;if("string"==typeof t)n=function(t){var n=0,o={type:Number(t.charAt(0))};if(null==e.types[o.type])return l("unknown packet type "+o.type);if(e.BINARY_EVENT===o.type||e.BINARY_ACK===o.type){for(var i="";"-"!==t.charAt(++n)&&(i+=t.charAt(n),n!=t.length););if(i!=Number(i)||"-"!==t.charAt(n))throw new Error("Illegal attachments");o.attachments=Number(i)}if("/"===t.charAt(n+1))for(o.nsp="";++n;){if(","===(c=t.charAt(n)))break;if(o.nsp+=c,n===t.length)break}else o.nsp="/";var a=t.charAt(n+1);if(""!==a&&Number(a)==a){for(o.id="";++n;){var c;if(null==(c=t.charAt(n))||Number(c)!=c){--n;break}if(o.id+=t.charAt(n),n===t.length)break}o.id=Number(o.id)}if(t.charAt(++n)){var p=function(t){try{return JSON.parse(t)}catch(t){return!1}}(t.substr(n));if(!(!1!==p&&(o.type===e.ERROR||s(p))))return l("invalid payload");o.data=p}return r("decoded %s as %j",t,o),o}(t),e.BINARY_EVENT===n.type||e.BINARY_ACK===n.type?(this.reconstructor=new f(n),0===this.reconstructor.reconPack.attachments&&this.emit("decoded",n)):this.emit("decoded",n);else{if(!a(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");(n=this.reconstructor.takeBinaryData(t))&&(this.reconstructor=null,this.emit("decoded",n))}},u.prototype.destroy=function(){this.reconstructor&&this.reconstructor.finishedReconstruction()},f.prototype.takeBinaryData=function(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){var e=i.reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null},f.prototype.finishedReconstruction=function(){this.reconPack=null,this.buffers=[]}},function(t,e,n){function r(t){if(t)return function(t){for(var e in r.prototype)t[e]=r.prototype[e];return t}(t)}t.exports=r,r.prototype.on=r.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},r.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},r.prototype.off=r.prototype.removeListener=r.prototype.removeAllListeners=r.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n,r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var o=0;o<r.length;o++)if((n=r[o])===e||n.fn===e){r.splice(o,1);break}return 0===r.length&&delete this._callbacks["$"+t],this},r.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),n=this._callbacks["$"+t],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(n){r=0;for(var o=(n=n.slice(0)).length;r<o;++r)n[r].apply(this,e)}return this},r.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},r.prototype.hasListeners=function(t){return!!this.listeners(t).length}},function(t,e,n){var r=n(10),o=n(11),i=Object.prototype.toString,s="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===i.call(Blob),a="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===i.call(File);function c(t,e){if(!t)return t;if(o(t)){var n={_placeholder:!0,num:e.length};return e.push(t),n}if(r(t)){for(var i=new Array(t.length),s=0;s<t.length;s++)i[s]=c(t[s],e);return i}if("object"==typeof t&&!(t instanceof Date)){i={};for(var a in t)i[a]=c(t[a],e);return i}return t}function p(t,e){if(!t)return t;if(t&&t._placeholder)return e[t.num];if(r(t))for(var n=0;n<t.length;n++)t[n]=p(t[n],e);else if("object"==typeof t)for(var o in t)t[o]=p(t[o],e);return t}e.deconstructPacket=function(t){var e=[],n=t.data,r=t;return r.data=c(n,e),r.attachments=e.length,{packet:r,buffers:e}},e.reconstructPacket=function(t,e){return t.data=p(t.data,e),t.attachments=void 0,t},e.removeBlobs=function(t,e){var n=0,i=t;!function t(c,p,h){if(!c)return c;if(s&&c instanceof Blob||a&&c instanceof File){n++;var u=new FileReader;u.onload=function(){h?h[p]=this.result:i=this.result,--n||e(i)},u.readAsArrayBuffer(c)}else if(r(c))for(var f=0;f<c.length;f++)t(c[f],f,c);else if("object"==typeof c&&!o(c))for(var l in c)t(c[l],l,c)}(i),n||e(i)}},function(t,e){var n={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},function(t,e){t.exports=function(t){return n&&Buffer.isBuffer(t)||r&&(t instanceof ArrayBuffer||function(t){return"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer}(t))};var n="function"==typeof Buffer&&"function"==typeof Buffer.isBuffer,r="function"==typeof ArrayBuffer},function(t,e,n){var r=n(13),o=n(37),i=n(8),s=n(7),a=n(39),c=n(40),p=n(3)("socket.io-client:manager"),h=n(36),u=n(41),f=Object.prototype.hasOwnProperty;function l(t,e){if(!(this instanceof l))return new l(t,e);t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.nsps={},this.subs=[],this.opts=e,this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(e.randomizationFactor||.5),this.backoff=new u({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this.readyState="closed",this.uri=t,this.connecting=[],this.lastPing=null,this.encoding=!1,this.packetBuffer=[];var n=e.parser||s;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this.autoConnect=!1!==e.autoConnect,this.autoConnect&&this.open()}t.exports=l,l.prototype.emitAll=function(){for(var t in this.emit.apply(this,arguments),this.nsps)f.call(this.nsps,t)&&this.nsps[t].emit.apply(this.nsps[t],arguments)},l.prototype.updateSocketIds=function(){for(var t in this.nsps)f.call(this.nsps,t)&&(this.nsps[t].id=this.generateId(t))},l.prototype.generateId=function(t){return("/"===t?"":t+"#")+this.engine.id},i(l.prototype),l.prototype.reconnection=function(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection},l.prototype.reconnectionAttempts=function(t){return arguments.length?(this._reconnectionAttempts=t,this):this._reconnectionAttempts},l.prototype.reconnectionDelay=function(t){return arguments.length?(this._reconnectionDelay=t,this.backoff&&this.backoff.setMin(t),this):this._reconnectionDelay},l.prototype.randomizationFactor=function(t){return arguments.length?(this._randomizationFactor=t,this.backoff&&this.backoff.setJitter(t),this):this._randomizationFactor},l.prototype.reconnectionDelayMax=function(t){return arguments.length?(this._reconnectionDelayMax=t,this.backoff&&this.backoff.setMax(t),this):this._reconnectionDelayMax},l.prototype.timeout=function(t){return arguments.length?(this._timeout=t,this):this._timeout},l.prototype.maybeReconnectOnOpen=function(){!this.reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()},l.prototype.open=l.prototype.connect=function(t,e){if(p("readyState %s",this.readyState),~this.readyState.indexOf("open"))return this;p("opening %s",this.uri),this.engine=r(this.uri,this.opts);var n=this.engine,o=this;this.readyState="opening",this.skipReconnect=!1;var i=a(n,"open",(function(){o.onopen(),t&&t()})),s=a(n,"error",(function(e){if(p("connect_error"),o.cleanup(),o.readyState="closed",o.emitAll("connect_error",e),t){var n=new Error("Connection error");n.data=e,t(n)}else o.maybeReconnectOnOpen()}));if(!1!==this._timeout){var c=this._timeout;p("connect attempt will timeout after %d",c),0===c&&i.destroy();var h=setTimeout((function(){p("connect attempt timed out after %d",c),i.destroy(),n.close(),n.emit("error","timeout"),o.emitAll("connect_timeout",c)}),c);this.subs.push({destroy:function(){clearTimeout(h)}})}return this.subs.push(i),this.subs.push(s),this},l.prototype.onopen=function(){p("open"),this.cleanup(),this.readyState="open",this.emit("open");var t=this.engine;this.subs.push(a(t,"data",c(this,"ondata"))),this.subs.push(a(t,"ping",c(this,"onping"))),this.subs.push(a(t,"pong",c(this,"onpong"))),this.subs.push(a(t,"error",c(this,"onerror"))),this.subs.push(a(t,"close",c(this,"onclose"))),this.subs.push(a(this.decoder,"decoded",c(this,"ondecoded")))},l.prototype.onping=function(){this.lastPing=new Date,this.emitAll("ping")},l.prototype.onpong=function(){this.emitAll("pong",new Date-this.lastPing)},l.prototype.ondata=function(t){this.decoder.add(t)},l.prototype.ondecoded=function(t){this.emit("packet",t)},l.prototype.onerror=function(t){p("error",t),this.emitAll("error",t)},l.prototype.socket=function(t,e){var n=this.nsps[t];if(!n){n=new o(this,t,e),this.nsps[t]=n;var r=this;n.on("connecting",i),n.on("connect",(function(){n.id=r.generateId(t)})),this.autoConnect&&i()}function i(){~h(r.connecting,n)||r.connecting.push(n)}return n},l.prototype.destroy=function(t){var e=h(this.connecting,t);~e&&this.connecting.splice(e,1),this.connecting.length||this.close()},l.prototype.packet=function(t){p("writing packet %j",t);var e=this;t.query&&0===t.type&&(t.nsp+="?"+t.query),e.encoding?e.packetBuffer.push(t):(e.encoding=!0,this.encoder.encode(t,(function(n){for(var r=0;r<n.length;r++)e.engine.write(n[r],t.options);e.encoding=!1,e.processPacketQueue()})))},l.prototype.processPacketQueue=function(){if(this.packetBuffer.length>0&&!this.encoding){var t=this.packetBuffer.shift();this.packet(t)}},l.prototype.cleanup=function(){p("cleanup");for(var t=this.subs.length,e=0;e<t;e++){this.subs.shift().destroy()}this.packetBuffer=[],this.encoding=!1,this.lastPing=null,this.decoder.destroy()},l.prototype.close=l.prototype.disconnect=function(){p("disconnect"),this.skipReconnect=!0,this.reconnecting=!1,"opening"===this.readyState&&this.cleanup(),this.backoff.reset(),this.readyState="closed",this.engine&&this.engine.close()},l.prototype.onclose=function(t){p("onclose"),this.cleanup(),this.backoff.reset(),this.readyState="closed",this.emit("close",t),this._reconnection&&!this.skipReconnect&&this.reconnect()},l.prototype.reconnect=function(){if(this.reconnecting||this.skipReconnect)return this;var t=this;if(this.backoff.attempts>=this._reconnectionAttempts)p("reconnect failed"),this.backoff.reset(),this.emitAll("reconnect_failed"),this.reconnecting=!1;else{var e=this.backoff.duration();p("will wait %dms before reconnect attempt",e),this.reconnecting=!0;var n=setTimeout((function(){t.skipReconnect||(p("attempting reconnect"),t.emitAll("reconnect_attempt",t.backoff.attempts),t.emitAll("reconnecting",t.backoff.attempts),t.skipReconnect||t.open((function(e){e?(p("reconnect attempt error"),t.reconnecting=!1,t.reconnect(),t.emitAll("reconnect_error",e.data)):(p("reconnect success"),t.onreconnect())})))}),e);this.subs.push({destroy:function(){clearTimeout(n)}})}},l.prototype.onreconnect=function(){var t=this.backoff.attempts;this.reconnecting=!1,this.backoff.reset(),this.updateSocketIds(),this.emitAll("reconnect",t)}},function(t,e,n){t.exports=n(14),t.exports.parser=n(22)},function(t,e,n){var r=n(15),o=n(8),i=n(3)("engine.io-client:socket"),s=n(36),a=n(22),c=n(2),p=n(30);function h(t,e){if(!(this instanceof h))return new h(t,e);e=e||{},t&&"object"==typeof t&&(e=t,t=null),t?(t=c(t),e.hostname=t.host,e.secure="https"===t.protocol||"wss"===t.protocol,e.port=t.port,t.query&&(e.query=t.query)):e.host&&(e.hostname=c(e.host).host),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.agent=e.agent||!1,this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?443:80),this.query=e.query||{},"string"==typeof this.query&&(this.query=p.decode(this.query)),this.upgrade=!1!==e.upgrade,this.path=(e.path||"/engine.io").replace(/\/$/,"")+"/",this.forceJSONP=!!e.forceJSONP,this.jsonp=!1!==e.jsonp,this.forceBase64=!!e.forceBase64,this.enablesXDR=!!e.enablesXDR,this.withCredentials=!1!==e.withCredentials,this.timestampParam=e.timestampParam||"t",this.timestampRequests=e.timestampRequests,this.transports=e.transports||["polling","websocket"],this.transportOptions=e.transportOptions||{},this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.policyPort=e.policyPort||843,this.rememberUpgrade=e.rememberUpgrade||!1,this.binaryType=null,this.onlyBinaryUpgrades=e.onlyBinaryUpgrades,this.perMessageDeflate=!1!==e.perMessageDeflate&&(e.perMessageDeflate||{}),!0===this.perMessageDeflate&&(this.perMessageDeflate={}),this.perMessageDeflate&&null==this.perMessageDeflate.threshold&&(this.perMessageDeflate.threshold=1024),this.pfx=e.pfx||null,this.key=e.key||null,this.passphrase=e.passphrase||null,this.cert=e.cert||null,this.ca=e.ca||null,this.ciphers=e.ciphers||null,this.rejectUnauthorized=void 0===e.rejectUnauthorized||e.rejectUnauthorized,this.forceNode=!!e.forceNode,this.isReactNative="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),("undefined"==typeof self||this.isReactNative)&&(e.extraHeaders&&Object.keys(e.extraHeaders).length>0&&(this.extraHeaders=e.extraHeaders),e.localAddress&&(this.localAddress=e.localAddress)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingIntervalTimer=null,this.pingTimeoutTimer=null,this.open()}t.exports=h,h.priorWebsocketSuccess=!1,o(h.prototype),h.protocol=a.protocol,h.Socket=h,h.Transport=n(21),h.transports=n(15),h.parser=n(22),h.prototype.createTransport=function(t){i('creating transport "%s"',t);var e=function(t){var e={};for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}(this.query);e.EIO=a.protocol,e.transport=t;var n=this.transportOptions[t]||{};return this.id&&(e.sid=this.id),new r[t]({query:e,socket:this,agent:n.agent||this.agent,hostname:n.hostname||this.hostname,port:n.port||this.port,secure:n.secure||this.secure,path:n.path||this.path,forceJSONP:n.forceJSONP||this.forceJSONP,jsonp:n.jsonp||this.jsonp,forceBase64:n.forceBase64||this.forceBase64,enablesXDR:n.enablesXDR||this.enablesXDR,withCredentials:n.withCredentials||this.withCredentials,timestampRequests:n.timestampRequests||this.timestampRequests,timestampParam:n.timestampParam||this.timestampParam,policyPort:n.policyPort||this.policyPort,pfx:n.pfx||this.pfx,key:n.key||this.key,passphrase:n.passphrase||this.passphrase,cert:n.cert||this.cert,ca:n.ca||this.ca,ciphers:n.ciphers||this.ciphers,rejectUnauthorized:n.rejectUnauthorized||this.rejectUnauthorized,perMessageDeflate:n.perMessageDeflate||this.perMessageDeflate,extraHeaders:n.extraHeaders||this.extraHeaders,forceNode:n.forceNode||this.forceNode,localAddress:n.localAddress||this.localAddress,requestTimeout:n.requestTimeout||this.requestTimeout,protocols:n.protocols||void 0,isReactNative:this.isReactNative})},h.prototype.open=function(){var t;if(this.rememberUpgrade&&h.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length){var e=this;return void setTimeout((function(){e.emit("error","No transports available")}),0)}t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(t){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)},h.prototype.setTransport=function(t){i("setting transport %s",t.name);var e=this;this.transport&&(i("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=t,t.on("drain",(function(){e.onDrain()})).on("packet",(function(t){e.onPacket(t)})).on("error",(function(t){e.onError(t)})).on("close",(function(){e.onClose("transport close")}))},h.prototype.probe=function(t){i('probing transport "%s"',t);var e=this.createTransport(t,{probe:1}),n=!1,r=this;function o(){if(r.onlyBinaryUpgrades){var o=!this.supportsBinary&&r.transport.supportsBinary;n=n||o}n||(i('probe transport "%s" opened',t),e.send([{type:"ping",data:"probe"}]),e.once("packet",(function(o){if(!n)if("pong"===o.type&&"probe"===o.data){if(i('probe transport "%s" pong',t),r.upgrading=!0,r.emit("upgrading",e),!e)return;h.priorWebsocketSuccess="websocket"===e.name,i('pausing current transport "%s"',r.transport.name),r.transport.pause((function(){n||"closed"!==r.readyState&&(i("changing transport and sending upgrade packet"),f(),r.setTransport(e),e.send([{type:"upgrade"}]),r.emit("upgrade",e),e=null,r.upgrading=!1,r.flush())}))}else{i('probe transport "%s" failed',t);var s=new Error("probe error");s.transport=e.name,r.emit("upgradeError",s)}})))}function s(){n||(n=!0,f(),e.close(),e=null)}function a(n){var o=new Error("probe error: "+n);o.transport=e.name,s(),i('probe transport "%s" failed because of error: %s',t,n),r.emit("upgradeError",o)}function c(){a("transport closed")}function p(){a("socket closed")}function u(t){e&&t.name!==e.name&&(i('"%s" works - aborting "%s"',t.name,e.name),s())}function f(){e.removeListener("open",o),e.removeListener("error",a),e.removeListener("close",c),r.removeListener("close",p),r.removeListener("upgrading",u)}h.priorWebsocketSuccess=!1,e.once("open",o),e.once("error",a),e.once("close",c),this.once("close",p),this.once("upgrading",u),e.open()},h.prototype.onOpen=function(){if(i("socket open"),this.readyState="open",h.priorWebsocketSuccess="websocket"===this.transport.name,this.emit("open"),this.flush(),"open"===this.readyState&&this.upgrade&&this.transport.pause){i("starting upgrade probes");for(var t=0,e=this.upgrades.length;t<e;t++)this.probe(this.upgrades[t])}},h.prototype.onPacket=function(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(i('socket receive: type "%s", data "%s"',t.type,t.data),this.emit("packet",t),this.emit("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"pong":this.setPing(),this.emit("pong");break;case"error":var e=new Error("server error");e.code=t.data,this.onError(e);break;case"message":this.emit("data",t.data),this.emit("message",t.data)}else i('packet received with socket readyState "%s"',this.readyState)},h.prototype.onHandshake=function(t){this.emit("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this.upgrades=this.filterUpgrades(t.upgrades),this.pingInterval=t.pingInterval,this.pingTimeout=t.pingTimeout,this.onOpen(),"closed"!==this.readyState&&(this.setPing(),this.removeListener("heartbeat",this.onHeartbeat),this.on("heartbeat",this.onHeartbeat))},h.prototype.onHeartbeat=function(t){clearTimeout(this.pingTimeoutTimer);var e=this;e.pingTimeoutTimer=setTimeout((function(){"closed"!==e.readyState&&e.onClose("ping timeout")}),t||e.pingInterval+e.pingTimeout)},h.prototype.setPing=function(){var t=this;clearTimeout(t.pingIntervalTimer),t.pingIntervalTimer=setTimeout((function(){i("writing ping packet - expecting pong within %sms",t.pingTimeout),t.ping(),t.onHeartbeat(t.pingTimeout)}),t.pingInterval)},h.prototype.ping=function(){var t=this;this.sendPacket("ping",(function(){t.emit("ping")}))},h.prototype.onDrain=function(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emit("drain"):this.flush()},h.prototype.flush=function(){"closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length&&(i("flushing %d packets in socket",this.writeBuffer.length),this.transport.send(this.writeBuffer),this.prevBufferLen=this.writeBuffer.length,this.emit("flush"))},h.prototype.write=h.prototype.send=function(t,e,n){return this.sendPacket("message",t,e,n),this},h.prototype.sendPacket=function(t,e,n,r){if("function"==typeof e&&(r=e,e=void 0),"function"==typeof n&&(r=n,n=null),"closing"!==this.readyState&&"closed"!==this.readyState){(n=n||{}).compress=!1!==n.compress;var o={type:t,data:e,options:n};this.emit("packetCreate",o),this.writeBuffer.push(o),r&&this.once("flush",r),this.flush()}},h.prototype.close=function(){if("opening"===this.readyState||"open"===this.readyState){this.readyState="closing";var t=this;this.writeBuffer.length?this.once("drain",(function(){this.upgrading?r():e()})):this.upgrading?r():e()}function e(){t.onClose("forced close"),i("socket closing - telling transport to close"),t.transport.close()}function n(){t.removeListener("upgrade",n),t.removeListener("upgradeError",n),e()}function r(){t.once("upgrade",n),t.once("upgradeError",n)}return this},h.prototype.onError=function(t){i("socket error %j",t),h.priorWebsocketSuccess=!1,this.emit("error",t),this.onClose("transport error",t)},h.prototype.onClose=function(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){i('socket close with reason: "%s"',t);clearTimeout(this.pingIntervalTimer),clearTimeout(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),this.readyState="closed",this.id=null,this.emit("close",t,e),this.writeBuffer=[],this.prevBufferLen=0}},h.prototype.filterUpgrades=function(t){for(var e=[],n=0,r=t.length;n<r;n++)~s(this.transports,t[n])&&e.push(t[n]);return e}},function(t,e,n){var r=n(16),o=n(19),i=n(33),s=n(34);e.polling=function(t){var e=!1,n=!1,s=!1!==t.jsonp;if("undefined"!=typeof location){var a="https:"===location.protocol,c=location.port;c||(c=a?443:80),e=t.hostname!==location.hostname||c!==t.port,n=t.secure!==a}if(t.xdomain=e,t.xscheme=n,"open"in new r(t)&&!t.forceJSONP)return new o(t);if(!s)throw new Error("JSONP disabled");return new i(t)},e.websocket=s},function(t,e,n){var r=n(17),o=n(18);t.exports=function(t){var e=t.xdomain,n=t.xscheme,i=t.enablesXDR;try{if("undefined"!=typeof XMLHttpRequest&&(!e||r))return new XMLHttpRequest}catch(t){}try{if("undefined"!=typeof XDomainRequest&&!n&&i)return new XDomainRequest}catch(t){}if(!e)try{return new(o[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}},function(t,e){try{t.exports="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){t.exports=!1}},function(t,e){t.exports="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")()},function(t,e,n){var r=n(16),o=n(20),i=n(8),s=n(31),a=n(3)("engine.io-client:polling-xhr"),c=n(18);function p(){}function h(t){if(o.call(this,t),this.requestTimeout=t.requestTimeout,this.extraHeaders=t.extraHeaders,"undefined"!=typeof location){var e="https:"===location.protocol,n=location.port;n||(n=e?443:80),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||n!==t.port,this.xs=t.secure!==e}}function u(t){this.method=t.method||"GET",this.uri=t.uri,this.xd=!!t.xd,this.xs=!!t.xs,this.async=!1!==t.async,this.data=void 0!==t.data?t.data:null,this.agent=t.agent,this.isBinary=t.isBinary,this.supportsBinary=t.supportsBinary,this.enablesXDR=t.enablesXDR,this.withCredentials=t.withCredentials,this.requestTimeout=t.requestTimeout,this.pfx=t.pfx,this.key=t.key,this.passphrase=t.passphrase,this.cert=t.cert,this.ca=t.ca,this.ciphers=t.ciphers,this.rejectUnauthorized=t.rejectUnauthorized,this.extraHeaders=t.extraHeaders,this.create()}if(t.exports=h,t.exports.Request=u,s(h,o),h.prototype.supportsBinary=!0,h.prototype.request=function(t){return(t=t||{}).uri=this.uri(),t.xd=this.xd,t.xs=this.xs,t.agent=this.agent||!1,t.supportsBinary=this.supportsBinary,t.enablesXDR=this.enablesXDR,t.withCredentials=this.withCredentials,t.pfx=this.pfx,t.key=this.key,t.passphrase=this.passphrase,t.cert=this.cert,t.ca=this.ca,t.ciphers=this.ciphers,t.rejectUnauthorized=this.rejectUnauthorized,t.requestTimeout=this.requestTimeout,t.extraHeaders=this.extraHeaders,new u(t)},h.prototype.doWrite=function(t,e){var n="string"!=typeof t&&void 0!==t,r=this.request({method:"POST",data:t,isBinary:n}),o=this;r.on("success",e),r.on("error",(function(t){o.onError("xhr post error",t)})),this.sendXhr=r},h.prototype.doPoll=function(){a("xhr poll");var t=this.request(),e=this;t.on("data",(function(t){e.onData(t)})),t.on("error",(function(t){e.onError("xhr poll error",t)})),this.pollXhr=t},i(u.prototype),u.prototype.create=function(){var t={agent:this.agent,xdomain:this.xd,xscheme:this.xs,enablesXDR:this.enablesXDR};t.pfx=this.pfx,t.key=this.key,t.passphrase=this.passphrase,t.cert=this.cert,t.ca=this.ca,t.ciphers=this.ciphers,t.rejectUnauthorized=this.rejectUnauthorized;var e=this.xhr=new r(t),n=this;try{a("xhr open %s: %s",this.method,this.uri),e.open(this.method,this.uri,this.async);try{if(this.extraHeaders)for(var o in e.setDisableHeaderCheck&&e.setDisableHeaderCheck(!0),this.extraHeaders)this.extraHeaders.hasOwnProperty(o)&&e.setRequestHeader(o,this.extraHeaders[o])}catch(t){}if("POST"===this.method)try{this.isBinary?e.setRequestHeader("Content-type","application/octet-stream"):e.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{e.setRequestHeader("Accept","*/*")}catch(t){}"withCredentials"in e&&(e.withCredentials=this.withCredentials),this.requestTimeout&&(e.timeout=this.requestTimeout),this.hasXDR()?(e.onload=function(){n.onLoad()},e.onerror=function(){n.onError(e.responseText)}):e.onreadystatechange=function(){if(2===e.readyState)try{var t=e.getResponseHeader("Content-Type");(n.supportsBinary&&"application/octet-stream"===t||"application/octet-stream; charset=UTF-8"===t)&&(e.responseType="arraybuffer")}catch(t){}4===e.readyState&&(200===e.status||1223===e.status?n.onLoad():setTimeout((function(){n.onError("number"==typeof e.status?e.status:0)}),0))},a("xhr data %s",this.data),e.send(this.data)}catch(t){return void setTimeout((function(){n.onError(t)}),0)}"undefined"!=typeof document&&(this.index=u.requestsCount++,u.requests[this.index]=this)},u.prototype.onSuccess=function(){this.emit("success"),this.cleanup()},u.prototype.onData=function(t){this.emit("data",t),this.onSuccess()},u.prototype.onError=function(t){this.emit("error",t),this.cleanup(!0)},u.prototype.cleanup=function(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.hasXDR()?this.xhr.onload=this.xhr.onerror=p:this.xhr.onreadystatechange=p,t)try{this.xhr.abort()}catch(t){}"undefined"!=typeof document&&delete u.requests[this.index],this.xhr=null}},u.prototype.onLoad=function(){var t;try{var e;try{e=this.xhr.getResponseHeader("Content-Type")}catch(t){}t=("application/octet-stream"===e||"application/octet-stream; charset=UTF-8"===e)&&this.xhr.response||this.xhr.responseText}catch(t){this.onError(t)}null!=t&&this.onData(t)},u.prototype.hasXDR=function(){return"undefined"!=typeof XDomainRequest&&!this.xs&&this.enablesXDR},u.prototype.abort=function(){this.cleanup()},u.requestsCount=0,u.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",f);else if("function"==typeof addEventListener){addEventListener("onpagehide"in c?"pagehide":"unload",f,!1)}function f(){for(var t in u.requests)u.requests.hasOwnProperty(t)&&u.requests[t].abort()}},function(t,e,n){var r=n(21),o=n(30),i=n(22),s=n(31),a=n(32),c=n(3)("engine.io-client:polling");t.exports=h;var p=null!=new(n(16))({xdomain:!1}).responseType;function h(t){var e=t&&t.forceBase64;p&&!e||(this.supportsBinary=!1),r.call(this,t)}s(h,r),h.prototype.name="polling",h.prototype.doOpen=function(){this.poll()},h.prototype.pause=function(t){var e=this;function n(){c("paused"),e.readyState="paused",t()}if(this.readyState="pausing",this.polling||!this.writable){var r=0;this.polling&&(c("we are currently polling - waiting to pause"),r++,this.once("pollComplete",(function(){c("pre-pause polling complete"),--r||n()}))),this.writable||(c("we are currently writing - waiting to pause"),r++,this.once("drain",(function(){c("pre-pause writing complete"),--r||n()})))}else n()},h.prototype.poll=function(){c("polling"),this.polling=!0,this.doPoll(),this.emit("poll")},h.prototype.onData=function(t){var e=this;c("polling got data %s",t);i.decodePayload(t,this.socket.binaryType,(function(t,n,r){if("opening"===e.readyState&&"open"===t.type&&e.onOpen(),"close"===t.type)return e.onClose(),!1;e.onPacket(t)})),"closed"!==this.readyState&&(this.polling=!1,this.emit("pollComplete"),"open"===this.readyState?this.poll():c('ignoring poll - transport state "%s"',this.readyState))},h.prototype.doClose=function(){var t=this;function e(){c("writing close packet"),t.write([{type:"close"}])}"open"===this.readyState?(c("transport open - closing"),e()):(c("transport not open - deferring close"),this.once("open",e))},h.prototype.write=function(t){var e=this;this.writable=!1;var n=function(){e.writable=!0,e.emit("drain")};i.encodePayload(t,this.supportsBinary,(function(t){e.doWrite(t,n)}))},h.prototype.uri=function(){var t=this.query||{},e=this.secure?"https":"http",n="";return!1!==this.timestampRequests&&(t[this.timestampParam]=a()),this.supportsBinary||t.sid||(t.b64=1),t=o.encode(t),this.port&&("https"===e&&443!==Number(this.port)||"http"===e&&80!==Number(this.port))&&(n=":"+this.port),t.length&&(t="?"+t),e+"://"+(-1!==this.hostname.indexOf(":")?"["+this.hostname+"]":this.hostname)+n+this.path+t}},function(t,e,n){var r=n(22),o=n(8);function i(t){this.path=t.path,this.hostname=t.hostname,this.port=t.port,this.secure=t.secure,this.query=t.query,this.timestampParam=t.timestampParam,this.timestampRequests=t.timestampRequests,this.readyState="",this.agent=t.agent||!1,this.socket=t.socket,this.enablesXDR=t.enablesXDR,this.withCredentials=t.withCredentials,this.pfx=t.pfx,this.key=t.key,this.passphrase=t.passphrase,this.cert=t.cert,this.ca=t.ca,this.ciphers=t.ciphers,this.rejectUnauthorized=t.rejectUnauthorized,this.forceNode=t.forceNode,this.isReactNative=t.isReactNative,this.extraHeaders=t.extraHeaders,this.localAddress=t.localAddress}t.exports=i,o(i.prototype),i.prototype.onError=function(t,e){var n=new Error(t);return n.type="TransportError",n.description=e,this.emit("error",n),this},i.prototype.open=function(){return"closed"!==this.readyState&&""!==this.readyState||(this.readyState="opening",this.doOpen()),this},i.prototype.close=function(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this},i.prototype.send=function(t){if("open"!==this.readyState)throw new Error("Transport not open");this.write(t)},i.prototype.onOpen=function(){this.readyState="open",this.writable=!0,this.emit("open")},i.prototype.onData=function(t){var e=r.decodePacket(t,this.socket.binaryType);this.onPacket(e)},i.prototype.onPacket=function(t){this.emit("packet",t)},i.prototype.onClose=function(){this.readyState="closed",this.emit("close")}},function(t,e,n){var r,o=n(23),i=n(24),s=n(25),a=n(26),c=n(27);"undefined"!=typeof ArrayBuffer&&(r=n(28));var p="undefined"!=typeof navigator&&/Android/i.test(navigator.userAgent),h="undefined"!=typeof navigator&&/PhantomJS/i.test(navigator.userAgent),u=p||h;e.protocol=3;var f=e.packets={open:0,close:1,ping:2,pong:3,message:4,upgrade:5,noop:6},l=o(f),d={type:"error",data:"parser error"},y=n(29);function g(t,e,n){for(var r=new Array(t.length),o=a(t.length,n),i=function(t,n,o){e(n,(function(e,n){r[t]=n,o(e,r)}))},s=0;s<t.length;s++)i(s,t[s],o)}e.encodePacket=function(t,n,r,o){"function"==typeof n&&(o=n,n=!1),"function"==typeof r&&(o=r,r=null);var i=void 0===t.data?void 0:t.data.buffer||t.data;if("undefined"!=typeof ArrayBuffer&&i instanceof ArrayBuffer)return function(t,n,r){if(!n)return e.encodeBase64Packet(t,r);var o=t.data,i=new Uint8Array(o),s=new Uint8Array(1+o.byteLength);s[0]=f[t.type];for(var a=0;a<i.length;a++)s[a+1]=i[a];return r(s.buffer)}(t,n,o);if(void 0!==y&&i instanceof y)return function(t,n,r){if(!n)return e.encodeBase64Packet(t,r);if(u)return function(t,n,r){if(!n)return e.encodeBase64Packet(t,r);var o=new FileReader;return o.onload=function(){e.encodePacket({type:t.type,data:o.result},n,!0,r)},o.readAsArrayBuffer(t.data)}(t,n,r);var o=new Uint8Array(1);o[0]=f[t.type];var i=new y([o.buffer,t.data]);return r(i)}(t,n,o);if(i&&i.base64)return function(t,n){var r="b"+e.packets[t.type]+t.data.data;return n(r)}(t,o);var s=f[t.type];return void 0!==t.data&&(s+=r?c.encode(String(t.data),{strict:!1}):String(t.data)),o(""+s)},e.encodeBase64Packet=function(t,n){var r,o="b"+e.packets[t.type];if(void 0!==y&&t.data instanceof y){var i=new FileReader;return i.onload=function(){var t=i.result.split(",")[1];n(o+t)},i.readAsDataURL(t.data)}try{r=String.fromCharCode.apply(null,new Uint8Array(t.data))}catch(e){for(var s=new Uint8Array(t.data),a=new Array(s.length),c=0;c<s.length;c++)a[c]=s[c];r=String.fromCharCode.apply(null,a)}return o+=btoa(r),n(o)},e.decodePacket=function(t,n,r){if(void 0===t)return d;if("string"==typeof t){if("b"===t.charAt(0))return e.decodeBase64Packet(t.substr(1),n);if(r&&!1===(t=function(t){try{t=c.decode(t,{strict:!1})}catch(t){return!1}return t}(t)))return d;var o=t.charAt(0);return Number(o)==o&&l[o]?t.length>1?{type:l[o],data:t.substring(1)}:{type:l[o]}:d}o=new Uint8Array(t)[0];var i=s(t,1);return y&&"blob"===n&&(i=new y([i])),{type:l[o],data:i}},e.decodeBase64Packet=function(t,e){var n=l[t.charAt(0)];if(!r)return{type:n,data:{base64:!0,data:t.substr(1)}};var o=r.decode(t.substr(1));return"blob"===e&&y&&(o=new y([o])),{type:n,data:o}},e.encodePayload=function(t,n,r){"function"==typeof n&&(r=n,n=null);var o=i(t);if(n&&o)return y&&!u?e.encodePayloadAsBlob(t,r):e.encodePayloadAsArrayBuffer(t,r);if(!t.length)return r("0:");g(t,(function(t,r){e.encodePacket(t,!!o&&n,!1,(function(t){r(null,function(t){return t.length+":"+t}(t))}))}),(function(t,e){return r(e.join(""))}))},e.decodePayload=function(t,n,r){if("string"!=typeof t)return e.decodePayloadAsBinary(t,n,r);var o;if("function"==typeof n&&(r=n,n=null),""===t)return r(d,0,1);for(var i,s,a="",c=0,p=t.length;c<p;c++){var h=t.charAt(c);if(":"===h){if(""===a||a!=(i=Number(a)))return r(d,0,1);if(a!=(s=t.substr(c+1,i)).length)return r(d,0,1);if(s.length){if(o=e.decodePacket(s,n,!1),d.type===o.type&&d.data===o.data)return r(d,0,1);if(!1===r(o,c+i,p))return}c+=i,a=""}else a+=h}return""!==a?r(d,0,1):void 0},e.encodePayloadAsArrayBuffer=function(t,n){if(!t.length)return n(new ArrayBuffer(0));g(t,(function(t,n){e.encodePacket(t,!0,!0,(function(t){return n(null,t)}))}),(function(t,e){var r=e.reduce((function(t,e){var n;return t+(n="string"==typeof e?e.length:e.byteLength).toString().length+n+2}),0),o=new Uint8Array(r),i=0;return e.forEach((function(t){var e="string"==typeof t,n=t;if(e){for(var r=new Uint8Array(t.length),s=0;s<t.length;s++)r[s]=t.charCodeAt(s);n=r.buffer}o[i++]=e?0:1;var a=n.byteLength.toString();for(s=0;s<a.length;s++)o[i++]=parseInt(a[s]);o[i++]=255;for(r=new Uint8Array(n),s=0;s<r.length;s++)o[i++]=r[s]})),n(o.buffer)}))},e.encodePayloadAsBlob=function(t,n){g(t,(function(t,n){e.encodePacket(t,!0,!0,(function(t){var e=new Uint8Array(1);if(e[0]=1,"string"==typeof t){for(var r=new Uint8Array(t.length),o=0;o<t.length;o++)r[o]=t.charCodeAt(o);t=r.buffer,e[0]=0}var i=(t instanceof ArrayBuffer?t.byteLength:t.size).toString(),s=new Uint8Array(i.length+1);for(o=0;o<i.length;o++)s[o]=parseInt(i[o]);if(s[i.length]=255,y){var a=new y([e.buffer,s.buffer,t]);n(null,a)}}))}),(function(t,e){return n(new y(e))}))},e.decodePayloadAsBinary=function(t,n,r){"function"==typeof n&&(r=n,n=null);for(var o=t,i=[];o.byteLength>0;){for(var a=new Uint8Array(o),c=0===a[0],p="",h=1;255!==a[h];h++){if(p.length>310)return r(d,0,1);p+=a[h]}o=s(o,2+p.length),p=parseInt(p);var u=s(o,0,p);if(c)try{u=String.fromCharCode.apply(null,new Uint8Array(u))}catch(t){var f=new Uint8Array(u);u="";for(h=0;h<f.length;h++)u+=String.fromCharCode(f[h])}i.push(u),o=s(o,p)}var l=i.length;i.forEach((function(t,o){r(e.decodePacket(t,n,!0),o,l)}))}},function(t,e){t.exports=Object.keys||function(t){var e=[],n=Object.prototype.hasOwnProperty;for(var r in t)n.call(t,r)&&e.push(r);return e}},function(t,e,n){var r=n(10),o=Object.prototype.toString,i="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===o.call(Blob),s="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===o.call(File);t.exports=function t(e){if(!e||"object"!=typeof e)return!1;if(r(e)){for(var n=0,o=e.length;n<o;n++)if(t(e[n]))return!0;return!1}if("function"==typeof Buffer&&Buffer.isBuffer&&Buffer.isBuffer(e)||"function"==typeof ArrayBuffer&&e instanceof ArrayBuffer||i&&e instanceof Blob||s&&e instanceof File)return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return t(e.toJSON(),!0);for(var a in e)if(Object.prototype.hasOwnProperty.call(e,a)&&t(e[a]))return!0;return!1}},function(t,e){t.exports=function(t,e,n){var r=t.byteLength;if(e=e||0,n=n||r,t.slice)return t.slice(e,n);if(e<0&&(e+=r),n<0&&(n+=r),n>r&&(n=r),e>=r||e>=n||0===r)return new ArrayBuffer(0);for(var o=new Uint8Array(t),i=new Uint8Array(n-e),s=e,a=0;s<n;s++,a++)i[a]=o[s];return i.buffer}},function(t,e){function n(){}t.exports=function(t,e,r){var o=!1;return r=r||n,i.count=t,0===t?e():i;function i(t,n){if(i.count<=0)throw new Error("after called too many times");--i.count,t?(o=!0,e(t),e=r):0!==i.count||o||e(null,n)}}},function(t,e){
+/*! https://mths.be/utf8js v2.1.2 by @mathias */
+var n,r,o,i=String.fromCharCode;function s(t){for(var e,n,r=[],o=0,i=t.length;o<i;)(e=t.charCodeAt(o++))>=55296&&e<=56319&&o<i?56320==(64512&(n=t.charCodeAt(o++)))?r.push(((1023&e)<<10)+(1023&n)+65536):(r.push(e),o--):r.push(e);return r}function a(t,e){if(t>=55296&&t<=57343){if(e)throw Error("Lone surrogate U+"+t.toString(16).toUpperCase()+" is not a scalar value");return!1}return!0}function c(t,e){return i(t>>e&63|128)}function p(t,e){if(0==(4294967168&t))return i(t);var n="";return 0==(4294965248&t)?n=i(t>>6&31|192):0==(4294901760&t)?(a(t,e)||(t=65533),n=i(t>>12&15|224),n+=c(t,6)):0==(4292870144&t)&&(n=i(t>>18&7|240),n+=c(t,12),n+=c(t,6)),n+=i(63&t|128)}function h(){if(o>=r)throw Error("Invalid byte index");var t=255&n[o];if(o++,128==(192&t))return 63&t;throw Error("Invalid continuation byte")}function u(t){var e,i;if(o>r)throw Error("Invalid byte index");if(o==r)return!1;if(e=255&n[o],o++,0==(128&e))return e;if(192==(224&e)){if((i=(31&e)<<6|h())>=128)return i;throw Error("Invalid continuation byte")}if(224==(240&e)){if((i=(15&e)<<12|h()<<6|h())>=2048)return a(i,t)?i:65533;throw Error("Invalid continuation byte")}if(240==(248&e)&&(i=(7&e)<<18|h()<<12|h()<<6|h())>=65536&&i<=1114111)return i;throw Error("Invalid UTF-8 detected")}t.exports={version:"2.1.2",encode:function(t,e){for(var n=!1!==(e=e||{}).strict,r=s(t),o=r.length,i=-1,a="";++i<o;)a+=p(r[i],n);return a},decode:function(t,e){var a=!1!==(e=e||{}).strict;n=s(t),r=n.length,o=0;for(var c,p=[];!1!==(c=u(a));)p.push(c);return function(t){for(var e,n=t.length,r=-1,o="";++r<n;)(e=t[r])>65535&&(o+=i((e-=65536)>>>10&1023|55296),e=56320|1023&e),o+=i(e);return o}(p)}}},function(t,e){!function(t){"use strict";e.encode=function(e){var n,r=new Uint8Array(e),o=r.length,i="";for(n=0;n<o;n+=3)i+=t[r[n]>>2],i+=t[(3&r[n])<<4|r[n+1]>>4],i+=t[(15&r[n+1])<<2|r[n+2]>>6],i+=t[63&r[n+2]];return o%3==2?i=i.substring(0,i.length-1)+"=":o%3==1&&(i=i.substring(0,i.length-2)+"=="),i},e.decode=function(e){var n,r,o,i,s,a=.75*e.length,c=e.length,p=0;"="===e[e.length-1]&&(a--,"="===e[e.length-2]&&a--);var h=new ArrayBuffer(a),u=new Uint8Array(h);for(n=0;n<c;n+=4)r=t.indexOf(e[n]),o=t.indexOf(e[n+1]),i=t.indexOf(e[n+2]),s=t.indexOf(e[n+3]),u[p++]=r<<2|o>>4,u[p++]=(15&o)<<4|i>>2,u[p++]=(3&i)<<6|63&s;return h}}("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")},function(t,e){var n=void 0!==n?n:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder&&MozBlobBuilder,r=function(){try{return 2===new Blob(["hi"]).size}catch(t){return!1}}(),o=r&&function(){try{return 2===new Blob([new Uint8Array([1,2])]).size}catch(t){return!1}}(),i=n&&n.prototype.append&&n.prototype.getBlob;function s(t){return t.map((function(t){if(t.buffer instanceof ArrayBuffer){var e=t.buffer;if(t.byteLength!==e.byteLength){var n=new Uint8Array(t.byteLength);n.set(new Uint8Array(e,t.byteOffset,t.byteLength)),e=n.buffer}return e}return t}))}function a(t,e){e=e||{};var r=new n;return s(t).forEach((function(t){r.append(t)})),e.type?r.getBlob(e.type):r.getBlob()}function c(t,e){return new Blob(s(t),e||{})}"undefined"!=typeof Blob&&(a.prototype=Blob.prototype,c.prototype=Blob.prototype),t.exports=r?o?Blob:c:i?a:void 0},function(t,e){e.encode=function(t){var e="";for(var n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e},e.decode=function(t){for(var e={},n=t.split("&"),r=0,o=n.length;r<o;r++){var i=n[r].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}},function(t,e){t.exports=function(t,e){var n=function(){};n.prototype=e.prototype,t.prototype=new n,t.prototype.constructor=t}},function(t,e){"use strict";var n,r="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),o={},i=0,s=0;function a(t){var e="";do{e=r[t%64]+e,t=Math.floor(t/64)}while(t>0);return e}function c(){var t=a(+new Date);return t!==n?(i=0,n=t):t+"."+a(i++)}for(;s<64;s++)o[r[s]]=s;c.encode=a,c.decode=function(t){var e=0;for(s=0;s<t.length;s++)e=64*e+o[t.charAt(s)];return e},t.exports=c},function(t,e,n){var r=n(20),o=n(31),i=n(18);t.exports=h;var s,a=/\n/g,c=/\\n/g;function p(){}function h(t){r.call(this,t),this.query=this.query||{},s||(s=i.___eio=i.___eio||[]),this.index=s.length;var e=this;s.push((function(t){e.onData(t)})),this.query.j=this.index,"function"==typeof addEventListener&&addEventListener("beforeunload",(function(){e.script&&(e.script.onerror=p)}),!1)}o(h,r),h.prototype.supportsBinary=!1,h.prototype.doClose=function(){this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),this.form&&(this.form.parentNode.removeChild(this.form),this.form=null,this.iframe=null),r.prototype.doClose.call(this)},h.prototype.doPoll=function(){var t=this,e=document.createElement("script");this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),e.async=!0,e.src=this.uri(),e.onerror=function(e){t.onError("jsonp poll error",e)};var n=document.getElementsByTagName("script")[0];n?n.parentNode.insertBefore(e,n):(document.head||document.body).appendChild(e),this.script=e,"undefined"!=typeof navigator&&/gecko/i.test(navigator.userAgent)&&setTimeout((function(){var t=document.createElement("iframe");document.body.appendChild(t),document.body.removeChild(t)}),100)},h.prototype.doWrite=function(t,e){var n=this;if(!this.form){var r,o=document.createElement("form"),i=document.createElement("textarea"),s=this.iframeId="eio_iframe_"+this.index;o.className="socketio",o.style.position="absolute",o.style.top="-1000px",o.style.left="-1000px",o.target=s,o.method="POST",o.setAttribute("accept-charset","utf-8"),i.name="d",o.appendChild(i),document.body.appendChild(o),this.form=o,this.area=i}function p(){h(),e()}function h(){if(n.iframe)try{n.form.removeChild(n.iframe)}catch(t){n.onError("jsonp polling iframe removal error",t)}try{var t='<iframe src="javascript:0" name="'+n.iframeId+'">';r=document.createElement(t)}catch(t){(r=document.createElement("iframe")).name=n.iframeId,r.src="javascript:0"}r.id=n.iframeId,n.form.appendChild(r),n.iframe=r}this.form.action=this.uri(),h(),t=t.replace(c,"\\\n"),this.area.value=t.replace(a,"\\n");try{this.form.submit()}catch(t){}this.iframe.attachEvent?this.iframe.onreadystatechange=function(){"complete"===n.iframe.readyState&&p()}:this.iframe.onload=p}},function(t,e,n){var r,o,i=n(21),s=n(22),a=n(30),c=n(31),p=n(32),h=n(3)("engine.io-client:websocket");if("undefined"!=typeof WebSocket?r=WebSocket:"undefined"!=typeof self&&(r=self.WebSocket||self.MozWebSocket),"undefined"==typeof window)try{o=n(35)}catch(t){}var u=r||o;function f(t){t&&t.forceBase64&&(this.supportsBinary=!1),this.perMessageDeflate=t.perMessageDeflate,this.usingBrowserWebSocket=r&&!t.forceNode,this.protocols=t.protocols,this.usingBrowserWebSocket||(u=o),i.call(this,t)}t.exports=f,c(f,i),f.prototype.name="websocket",f.prototype.supportsBinary=!0,f.prototype.doOpen=function(){if(this.check()){var t=this.uri(),e=this.protocols,n={};this.isReactNative||(n.agent=this.agent,n.perMessageDeflate=this.perMessageDeflate,n.pfx=this.pfx,n.key=this.key,n.passphrase=this.passphrase,n.cert=this.cert,n.ca=this.ca,n.ciphers=this.ciphers,n.rejectUnauthorized=this.rejectUnauthorized),this.extraHeaders&&(n.headers=this.extraHeaders),this.localAddress&&(n.localAddress=this.localAddress);try{this.ws=this.usingBrowserWebSocket&&!this.isReactNative?e?new u(t,e):new u(t):new u(t,e,n)}catch(t){return this.emit("error",t)}void 0===this.ws.binaryType&&(this.supportsBinary=!1),this.ws.supports&&this.ws.supports.binary?(this.supportsBinary=!0,this.ws.binaryType="nodebuffer"):this.ws.binaryType="arraybuffer",this.addEventListeners()}},f.prototype.addEventListeners=function(){var t=this;this.ws.onopen=function(){t.onOpen()},this.ws.onclose=function(){t.onClose()},this.ws.onmessage=function(e){t.onData(e.data)},this.ws.onerror=function(e){t.onError("websocket error",e)}},f.prototype.write=function(t){var e=this;this.writable=!1;for(var n=t.length,r=0,o=n;r<o;r++)!function(t){s.encodePacket(t,e.supportsBinary,(function(r){if(!e.usingBrowserWebSocket){var o={};if(t.options&&(o.compress=t.options.compress),e.perMessageDeflate)("string"==typeof r?Buffer.byteLength(r):r.length)<e.perMessageDeflate.threshold&&(o.compress=!1)}try{e.usingBrowserWebSocket?e.ws.send(r):e.ws.send(r,o)}catch(t){h("websocket closed before onclose event")}--n||i()}))}(t[r]);function i(){e.emit("flush"),setTimeout((function(){e.writable=!0,e.emit("drain")}),0)}},f.prototype.onClose=function(){i.prototype.onClose.call(this)},f.prototype.doClose=function(){void 0!==this.ws&&this.ws.close()},f.prototype.uri=function(){var t=this.query||{},e=this.secure?"wss":"ws",n="";return this.port&&("wss"===e&&443!==Number(this.port)||"ws"===e&&80!==Number(this.port))&&(n=":"+this.port),this.timestampRequests&&(t[this.timestampParam]=p()),this.supportsBinary||(t.b64=1),(t=a.encode(t)).length&&(t="?"+t),e+"://"+(-1!==this.hostname.indexOf(":")?"["+this.hostname+"]":this.hostname)+n+this.path+t},f.prototype.check=function(){return!(!u||"__initialize"in u&&this.name===f.prototype.name)}},function(t,e){},function(t,e){var n=[].indexOf;t.exports=function(t,e){if(n)return t.indexOf(e);for(var r=0;r<t.length;++r)if(t[r]===e)return r;return-1}},function(t,e,n){var r=n(7),o=n(8),i=n(38),s=n(39),a=n(40),c=n(3)("socket.io-client:socket"),p=n(30),h=n(24);t.exports=l;var u={connect:1,connect_error:1,connect_timeout:1,connecting:1,disconnect:1,error:1,reconnect:1,reconnect_attempt:1,reconnect_failed:1,reconnect_error:1,reconnecting:1,ping:1,pong:1},f=o.prototype.emit;function l(t,e,n){this.io=t,this.nsp=e,this.json=this,this.ids=0,this.acks={},this.receiveBuffer=[],this.sendBuffer=[],this.connected=!1,this.disconnected=!0,this.flags={},n&&n.query&&(this.query=n.query),this.io.autoConnect&&this.open()}o(l.prototype),l.prototype.subEvents=function(){if(!this.subs){var t=this.io;this.subs=[s(t,"open",a(this,"onopen")),s(t,"packet",a(this,"onpacket")),s(t,"close",a(this,"onclose"))]}},l.prototype.open=l.prototype.connect=function(){return this.connected||(this.subEvents(),this.io.reconnecting||this.io.open(),"open"===this.io.readyState&&this.onopen(),this.emit("connecting")),this},l.prototype.send=function(){var t=i(arguments);return t.unshift("message"),this.emit.apply(this,t),this},l.prototype.emit=function(t){if(u.hasOwnProperty(t))return f.apply(this,arguments),this;var e=i(arguments),n={type:(void 0!==this.flags.binary?this.flags.binary:h(e))?r.BINARY_EVENT:r.EVENT,data:e,options:{}};return n.options.compress=!this.flags||!1!==this.flags.compress,"function"==typeof e[e.length-1]&&(c("emitting packet with ack id %d",this.ids),this.acks[this.ids]=e.pop(),n.id=this.ids++),this.connected?this.packet(n):this.sendBuffer.push(n),this.flags={},this},l.prototype.packet=function(t){t.nsp=this.nsp,this.io.packet(t)},l.prototype.onopen=function(){if(c("transport is open - connecting"),"/"!==this.nsp)if(this.query){var t="object"==typeof this.query?p.encode(this.query):this.query;c("sending connect packet with query %s",t),this.packet({type:r.CONNECT,query:t})}else this.packet({type:r.CONNECT})},l.prototype.onclose=function(t){c("close (%s)",t),this.connected=!1,this.disconnected=!0,delete this.id,this.emit("disconnect",t)},l.prototype.onpacket=function(t){var e=t.nsp===this.nsp,n=t.type===r.ERROR&&"/"===t.nsp;if(e||n)switch(t.type){case r.CONNECT:this.onconnect();break;case r.EVENT:case r.BINARY_EVENT:this.onevent(t);break;case r.ACK:case r.BINARY_ACK:this.onack(t);break;case r.DISCONNECT:this.ondisconnect();break;case r.ERROR:this.emit("error",t.data)}},l.prototype.onevent=function(t){var e=t.data||[];c("emitting event %j",e),null!=t.id&&(c("attaching ack callback to event"),e.push(this.ack(t.id))),this.connected?f.apply(this,e):this.receiveBuffer.push(e)},l.prototype.ack=function(t){var e=this,n=!1;return function(){if(!n){n=!0;var o=i(arguments);c("sending ack %j",o),e.packet({type:h(o)?r.BINARY_ACK:r.ACK,id:t,data:o})}}},l.prototype.onack=function(t){var e=this.acks[t.id];"function"==typeof e?(c("calling ack %s with %j",t.id,t.data),e.apply(this,t.data),delete this.acks[t.id]):c("bad ack %s",t.id)},l.prototype.onconnect=function(){this.connected=!0,this.disconnected=!1,this.emit("connect"),this.emitBuffered()},l.prototype.emitBuffered=function(){var t;for(t=0;t<this.receiveBuffer.length;t++)f.apply(this,this.receiveBuffer[t]);for(this.receiveBuffer=[],t=0;t<this.sendBuffer.length;t++)this.packet(this.sendBuffer[t]);this.sendBuffer=[]},l.prototype.ondisconnect=function(){c("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")},l.prototype.destroy=function(){if(this.subs){for(var t=0;t<this.subs.length;t++)this.subs[t].destroy();this.subs=null}this.io.destroy(this)},l.prototype.close=l.prototype.disconnect=function(){return this.connected&&(c("performing disconnect (%s)",this.nsp),this.packet({type:r.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this},l.prototype.compress=function(t){return this.flags.compress=t,this},l.prototype.binary=function(t){return this.flags.binary=t,this}},function(t,e){t.exports=function(t,e){for(var n=[],r=(e=e||0)||0;r<t.length;r++)n[r-e]=t[r];return n}},function(t,e){t.exports=function(t,e,n){return t.on(e,n),{destroy:function(){t.removeListener(e,n)}}}},function(t,e){var n=[].slice;t.exports=function(t,e){if("string"==typeof e&&(e=t[e]),"function"!=typeof e)throw new Error("bind() requires a function");var r=n.call(arguments,2);return function(){return e.apply(t,r.concat(n.call(arguments)))}}},function(t,e){function n(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}t.exports=n,n.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=0==(1&Math.floor(10*e))?t-n:t+n}return 0|Math.min(t,this.max)},n.prototype.reset=function(){this.attempts=0},n.prototype.setMin=function(t){this.ms=t},n.prototype.setMax=function(t){this.max=t},n.prototype.setJitter=function(t){this.jitter=t}}])}));
\ No newline at end of file
index 50e33f6..aa62084 100644 (file)
@@ -3,7 +3,5 @@
  * (c) 2014-2021 Guillermo Rauch
  * Released under the MIT License.
  */
-!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.io=e():t.io=e()}(this,function(){return function(t){function e(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return t[r].call(o.exports,o,o.exports,e),o.loaded=!0,o.exports}var n={};return e.m=t,e.c=n,e.p="",e(0)}([function(t,e,n){function r(t,e){"object"==typeof t&&(e=t,t=void 0),e=e||{};var n,r=o(t),i=r.source,p=r.id,u=r.path,h=c[p]&&u in c[p].nsps,f=e.forceNew||e["force new connection"]||!1===e.multiplex||h;return f?(a("ignoring socket cache for %s",i),n=s(i,e)):(c[p]||(a("new io instance for %s",i),c[p]=s(i,e)),n=c[p]),r.query&&!e.query&&(e.query=r.query),n.socket(r.path,e)}var o=n(1),i=n(7),s=n(12),a=n(3)("socket.io-client");t.exports=e=r;var c=e.managers={};e.protocol=i.protocol,e.connect=r,e.Manager=n(12),e.Socket=n(37)},function(t,e,n){function r(t,e){var n=t;e=e||"undefined"!=typeof location&&location,null==t&&(t=e.protocol+"//"+e.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?e.protocol+t:e.host+t),/^(https?|wss?):\/\//.test(t)||(i("protocol-less url %s",t),t="undefined"!=typeof e?e.protocol+"//"+t:"https://"+t),i("parse %s",t),n=o(t)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";var r=n.host.indexOf(":")!==-1,s=r?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+s+":"+n.port,n.href=n.protocol+"://"+s+(e&&e.port===n.port?"":":"+n.port),n}var o=n(2),i=n(3)("socket.io-client:url");t.exports=r},function(t,e){function n(t,e){var n=/\/{2,9}/g,r=e.replace(n,"/").split("/");return"/"!=e.substr(0,1)&&0!==e.length||r.splice(0,1),"/"==e.substr(e.length-1,1)&&r.splice(r.length-1,1),r}function r(t,e){var n={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,r){e&&(n[e]=r)}),n}var o=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,i=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];t.exports=function(t){var e=t,s=t.indexOf("["),a=t.indexOf("]");s!=-1&&a!=-1&&(t=t.substring(0,s)+t.substring(s,a).replace(/:/g,";")+t.substring(a,t.length));for(var c=o.exec(t||""),p={},u=14;u--;)p[i[u]]=c[u]||"";return s!=-1&&a!=-1&&(p.source=e,p.host=p.host.substring(1,p.host.length-1).replace(/;/g,":"),p.authority=p.authority.replace("[","").replace("]","").replace(/;/g,":"),p.ipv6uri=!0),p.pathNames=n(p,p.path),p.queryKey=r(p,p.query),p}},function(t,e,n){(function(r){"use strict";function o(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))}function i(t){var n=this.useColors;if(t[0]=(n?"%c":"")+this.namespace+(n?" %c":" ")+t[0]+(n?"%c ":" ")+"+"+e.humanize(this.diff),n){var r="color: "+this.color;t.splice(1,0,r,"color: inherit");var o=0,i=0;t[0].replace(/%[a-zA-Z%]/g,function(t){"%%"!==t&&(o++,"%c"===t&&(i=o))}),t.splice(i,0,r)}}function s(){return"object"===("undefined"==typeof console?"undefined":u(console))&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function a(t){try{null==t?e.storage.removeItem("debug"):e.storage.debug=t}catch(n){}}function c(){var t;try{t=e.storage.debug}catch(n){}return!t&&"undefined"!=typeof r&&"env"in r&&(t=r.env.DEBUG),t}function p(){try{return window.localStorage}catch(t){}}var u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};e=t.exports=n(5),e.log=s,e.formatArgs=i,e.save=a,e.load=c,e.useColors=o,e.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:p(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],e.formatters.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},e.enable(c())}).call(e,n(4))},function(t,e){function n(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function o(t){if(u===setTimeout)return setTimeout(t,0);if((u===n||!u)&&setTimeout)return u=setTimeout,setTimeout(t,0);try{return u(t,0)}catch(e){try{return u.call(null,t,0)}catch(e){return u.call(this,t,0)}}}function i(t){if(h===clearTimeout)return clearTimeout(t);if((h===r||!h)&&clearTimeout)return h=clearTimeout,clearTimeout(t);try{return h(t)}catch(e){try{return h.call(null,t)}catch(e){return h.call(this,t)}}}function s(){y&&l&&(y=!1,l.length?d=l.concat(d):g=-1,d.length&&a())}function a(){if(!y){var t=o(s);y=!0;for(var e=d.length;e;){for(l=d,d=[];++g<e;)l&&l[g].run();g=-1,e=d.length}l=null,y=!1,i(t)}}function c(t,e){this.fun=t,this.array=e}function p(){}var u,h,f=t.exports={};!function(){try{u="function"==typeof setTimeout?setTimeout:n}catch(t){u=n}try{h="function"==typeof clearTimeout?clearTimeout:r}catch(t){h=r}}();var l,d=[],y=!1,g=-1;f.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];d.push(new c(t,e)),1!==d.length||y||o(a)},c.prototype.run=function(){this.fun.apply(null,this.array)},f.title="browser",f.browser=!0,f.env={},f.argv=[],f.version="",f.versions={},f.on=p,f.addListener=p,f.once=p,f.off=p,f.removeListener=p,f.removeAllListeners=p,f.emit=p,f.prependListener=p,f.prependOnceListener=p,f.listeners=function(t){return[]},f.binding=function(t){throw new Error("process.binding is not supported")},f.cwd=function(){return"/"},f.chdir=function(t){throw new Error("process.chdir is not supported")},f.umask=function(){return 0}},function(t,e,n){"use strict";function r(t){var n,r=0;for(n in t)r=(r<<5)-r+t.charCodeAt(n),r|=0;return e.colors[Math.abs(r)%e.colors.length]}function o(t){function n(){if(n.enabled){var t=n,r=+new Date,i=r-(o||r);t.diff=i,t.prev=o,t.curr=r,o=r;for(var s=new Array(arguments.length),a=0;a<s.length;a++)s[a]=arguments[a];s[0]=e.coerce(s[0]),"string"!=typeof s[0]&&s.unshift("%O");var c=0;s[0]=s[0].replace(/%([a-zA-Z%])/g,function(n,r){if("%%"===n)return n;c++;var o=e.formatters[r];if("function"==typeof o){var i=s[c];n=o.call(t,i),s.splice(c,1),c--}return n}),e.formatArgs.call(t,s);var p=n.log||e.log||console.log.bind(console);p.apply(t,s)}}var o;return n.namespace=t,n.enabled=e.enabled(t),n.useColors=e.useColors(),n.color=r(t),n.destroy=i,"function"==typeof e.init&&e.init(n),e.instances.push(n),n}function i(){var t=e.instances.indexOf(this);return t!==-1&&(e.instances.splice(t,1),!0)}function s(t){e.save(t),e.names=[],e.skips=[];var n,r=("string"==typeof t?t:"").split(/[\s,]+/),o=r.length;for(n=0;n<o;n++)r[n]&&(t=r[n].replace(/\*/g,".*?"),"-"===t[0]?e.skips.push(new RegExp("^"+t.substr(1)+"$")):e.names.push(new RegExp("^"+t+"$")));for(n=0;n<e.instances.length;n++){var i=e.instances[n];i.enabled=e.enabled(i.namespace)}}function a(){e.enable("")}function c(t){if("*"===t[t.length-1])return!0;var n,r;for(n=0,r=e.skips.length;n<r;n++)if(e.skips[n].test(t))return!1;for(n=0,r=e.names.length;n<r;n++)if(e.names[n].test(t))return!0;return!1}function p(t){return t instanceof Error?t.stack||t.message:t}e=t.exports=o.debug=o["default"]=o,e.coerce=p,e.disable=a,e.enable=s,e.enabled=c,e.humanize=n(6),e.instances=[],e.names=[],e.skips=[],e.formatters={}},function(t,e){function n(t){if(t=String(t),!(t.length>100)){var e=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(t);if(e){var n=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return n*u;case"days":case"day":case"d":return n*p;case"hours":case"hour":case"hrs":case"hr":case"h":return n*c;case"minutes":case"minute":case"mins":case"min":case"m":return n*a;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function r(t){return t>=p?Math.round(t/p)+"d":t>=c?Math.round(t/c)+"h":t>=a?Math.round(t/a)+"m":t>=s?Math.round(t/s)+"s":t+"ms"}function o(t){return i(t,p,"day")||i(t,c,"hour")||i(t,a,"minute")||i(t,s,"second")||t+" ms"}function i(t,e,n){if(!(t<e))return t<1.5*e?Math.floor(t/e)+" "+n:Math.ceil(t/e)+" "+n+"s"}var s=1e3,a=60*s,c=60*a,p=24*c,u=365.25*p;t.exports=function(t,e){e=e||{};var i=typeof t;if("string"===i&&t.length>0)return n(t);if("number"===i&&isNaN(t)===!1)return e["long"]?o(t):r(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))}},function(t,e,n){function r(){}function o(t){var n=""+t.type;if(e.BINARY_EVENT!==t.type&&e.BINARY_ACK!==t.type||(n+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(n+=t.nsp+","),null!=t.id&&(n+=t.id),null!=t.data){var r=i(t.data);if(r===!1)return m;n+=r}return f("encoded %j as %s",t,n),n}function i(t){try{return JSON.stringify(t)}catch(e){return!1}}function s(t,e){function n(t){var n=d.deconstructPacket(t),r=o(n.packet),i=n.buffers;i.unshift(r),e(i)}d.removeBlobs(t,n)}function a(){this.reconstructor=null}function c(t){var n=0,r={type:Number(t.charAt(0))};if(null==e.types[r.type])return h("unknown packet type "+r.type);if(e.BINARY_EVENT===r.type||e.BINARY_ACK===r.type){for(var o="";"-"!==t.charAt(++n)&&(o+=t.charAt(n),n!=t.length););if(o!=Number(o)||"-"!==t.charAt(n))throw new Error("Illegal attachments");r.attachments=Number(o)}if("/"===t.charAt(n+1))for(r.nsp="";++n;){var i=t.charAt(n);if(","===i)break;if(r.nsp+=i,n===t.length)break}else r.nsp="/";var s=t.charAt(n+1);if(""!==s&&Number(s)==s){for(r.id="";++n;){var i=t.charAt(n);if(null==i||Number(i)!=i){--n;break}if(r.id+=t.charAt(n),n===t.length)break}r.id=Number(r.id)}if(t.charAt(++n)){var a=p(t.substr(n)),c=a!==!1&&(r.type===e.ERROR||y(a));if(!c)return h("invalid payload");r.data=a}return f("decoded %s as %j",t,r),r}function p(t){try{return JSON.parse(t)}catch(e){return!1}}function u(t){this.reconPack=t,this.buffers=[]}function h(t){return{type:e.ERROR,data:"parser error: "+t}}var f=n(3)("socket.io-parser"),l=n(8),d=n(9),y=n(10),g=n(11);e.protocol=4,e.types=["CONNECT","DISCONNECT","EVENT","ACK","ERROR","BINARY_EVENT","BINARY_ACK"],e.CONNECT=0,e.DISCONNECT=1,e.EVENT=2,e.ACK=3,e.ERROR=4,e.BINARY_EVENT=5,e.BINARY_ACK=6,e.Encoder=r,e.Decoder=a;var m=e.ERROR+'"encode error"';r.prototype.encode=function(t,n){if(f("encoding packet %j",t),e.BINARY_EVENT===t.type||e.BINARY_ACK===t.type)s(t,n);else{var r=o(t);n([r])}},l(a.prototype),a.prototype.add=function(t){var n;if("string"==typeof t)n=c(t),e.BINARY_EVENT===n.type||e.BINARY_ACK===n.type?(this.reconstructor=new u(n),0===this.reconstructor.reconPack.attachments&&this.emit("decoded",n)):this.emit("decoded",n);else{if(!g(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");n=this.reconstructor.takeBinaryData(t),n&&(this.reconstructor=null,this.emit("decoded",n))}},a.prototype.destroy=function(){this.reconstructor&&this.reconstructor.finishedReconstruction()},u.prototype.takeBinaryData=function(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){var e=d.reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null},u.prototype.finishedReconstruction=function(){this.reconPack=null,this.buffers=[]}},function(t,e,n){function r(t){if(t)return o(t)}function o(t){for(var e in r.prototype)t[e]=r.prototype[e];return t}t.exports=r,r.prototype.on=r.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},r.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},r.prototype.off=r.prototype.removeListener=r.prototype.removeAllListeners=r.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n=this._callbacks["$"+t];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var r,o=0;o<n.length;o++)if(r=n[o],r===e||r.fn===e){n.splice(o,1);break}return 0===n.length&&delete this._callbacks["$"+t],this},r.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),n=this._callbacks["$"+t],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(n){n=n.slice(0);for(var r=0,o=n.length;r<o;++r)n[r].apply(this,e)}return this},r.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},r.prototype.hasListeners=function(t){return!!this.listeners(t).length}},function(t,e,n){function r(t,e){if(!t)return t;if(s(t)){var n={_placeholder:!0,num:e.length};return e.push(t),n}if(i(t)){for(var o=new Array(t.length),a=0;a<t.length;a++)o[a]=r(t[a],e);return o}if("object"==typeof t&&!(t instanceof Date)){var o={};for(var c in t)o[c]=r(t[c],e);return o}return t}function o(t,e){if(!t)return t;if(t&&t._placeholder)return e[t.num];if(i(t))for(var n=0;n<t.length;n++)t[n]=o(t[n],e);else if("object"==typeof t)for(var r in t)t[r]=o(t[r],e);return t}var i=n(10),s=n(11),a=Object.prototype.toString,c="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===a.call(Blob),p="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===a.call(File);e.deconstructPacket=function(t){var e=[],n=t.data,o=t;return o.data=r(n,e),o.attachments=e.length,{packet:o,buffers:e}},e.reconstructPacket=function(t,e){return t.data=o(t.data,e),t.attachments=void 0,t},e.removeBlobs=function(t,e){function n(t,a,u){if(!t)return t;if(c&&t instanceof Blob||p&&t instanceof File){r++;var h=new FileReader;h.onload=function(){u?u[a]=this.result:o=this.result,--r||e(o)},h.readAsArrayBuffer(t)}else if(i(t))for(var f=0;f<t.length;f++)n(t[f],f,t);else if("object"==typeof t&&!s(t))for(var l in t)n(t[l],l,t)}var r=0,o=t;n(o),r||e(o)}},function(t,e){var n={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},function(t,e){function n(t){return r&&Buffer.isBuffer(t)||o&&(t instanceof ArrayBuffer||i(t))}t.exports=n;var r="function"==typeof Buffer&&"function"==typeof Buffer.isBuffer,o="function"==typeof ArrayBuffer,i=function(t){return"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer}},function(t,e,n){function r(t,e){if(!(this instanceof r))return new r(t,e);t&&"object"==typeof t&&(e=t,t=void 0),e=e||{},e.path=e.path||"/socket.io",this.nsps={},this.subs=[],this.opts=e,this.reconnection(e.reconnection!==!1),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(e.randomizationFactor||.5),this.backoff=new f({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this.readyState="closed",this.uri=t,this.connecting=[],this.lastPing=null,this.encoding=!1,this.packetBuffer=[];var n=e.parser||a;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this.autoConnect=e.autoConnect!==!1,this.autoConnect&&this.open()}var o=n(13),i=n(37),s=n(8),a=n(7),c=n(39),p=n(40),u=n(3)("socket.io-client:manager"),h=n(36),f=n(41),l=Object.prototype.hasOwnProperty;t.exports=r,r.prototype.emitAll=function(){this.emit.apply(this,arguments);for(var t in this.nsps)l.call(this.nsps,t)&&this.nsps[t].emit.apply(this.nsps[t],arguments)},r.prototype.updateSocketIds=function(){for(var t in this.nsps)l.call(this.nsps,t)&&(this.nsps[t].id=this.generateId(t))},r.prototype.generateId=function(t){return("/"===t?"":t+"#")+this.engine.id},s(r.prototype),r.prototype.reconnection=function(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection},r.prototype.reconnectionAttempts=function(t){return arguments.length?(this._reconnectionAttempts=t,this):this._reconnectionAttempts},r.prototype.reconnectionDelay=function(t){return arguments.length?(this._reconnectionDelay=t,this.backoff&&this.backoff.setMin(t),this):this._reconnectionDelay},r.prototype.randomizationFactor=function(t){return arguments.length?(this._randomizationFactor=t,this.backoff&&this.backoff.setJitter(t),this):this._randomizationFactor},r.prototype.reconnectionDelayMax=function(t){return arguments.length?(this._reconnectionDelayMax=t,this.backoff&&this.backoff.setMax(t),this):this._reconnectionDelayMax},r.prototype.timeout=function(t){return arguments.length?(this._timeout=t,this):this._timeout},r.prototype.maybeReconnectOnOpen=function(){!this.reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()},r.prototype.open=r.prototype.connect=function(t,e){if(u("readyState %s",this.readyState),~this.readyState.indexOf("open"))return this;u("opening %s",this.uri),this.engine=o(this.uri,this.opts);var n=this.engine,r=this;this.readyState="opening",this.skipReconnect=!1;var i=c(n,"open",function(){r.onopen(),t&&t()}),s=c(n,"error",function(e){if(u("connect_error"),r.cleanup(),r.readyState="closed",r.emitAll("connect_error",e),t){var n=new Error("Connection error");n.data=e,t(n)}else r.maybeReconnectOnOpen()});if(!1!==this._timeout){var a=this._timeout;u("connect attempt will timeout after %d",a),0===a&&i.destroy();var p=setTimeout(function(){u("connect attempt timed out after %d",a),i.destroy(),n.close(),n.emit("error","timeout"),r.emitAll("connect_timeout",a)},a);this.subs.push({destroy:function(){clearTimeout(p)}})}return this.subs.push(i),this.subs.push(s),this},r.prototype.onopen=function(){u("open"),this.cleanup(),this.readyState="open",this.emit("open");var t=this.engine;this.subs.push(c(t,"data",p(this,"ondata"))),this.subs.push(c(t,"ping",p(this,"onping"))),this.subs.push(c(t,"pong",p(this,"onpong"))),this.subs.push(c(t,"error",p(this,"onerror"))),this.subs.push(c(t,"close",p(this,"onclose"))),this.subs.push(c(this.decoder,"decoded",p(this,"ondecoded")))},r.prototype.onping=function(){this.lastPing=new Date,this.emitAll("ping")},r.prototype.onpong=function(){this.emitAll("pong",new Date-this.lastPing)},r.prototype.ondata=function(t){this.decoder.add(t)},r.prototype.ondecoded=function(t){this.emit("packet",t)},r.prototype.onerror=function(t){u("error",t),this.emitAll("error",t)},r.prototype.socket=function(t,e){function n(){~h(o.connecting,r)||o.connecting.push(r)}var r=this.nsps[t];if(!r){r=new i(this,t,e),this.nsps[t]=r;var o=this;r.on("connecting",n),r.on("connect",function(){r.id=o.generateId(t)}),this.autoConnect&&n()}return r},r.prototype.destroy=function(t){var e=h(this.connecting,t);~e&&this.connecting.splice(e,1),this.connecting.length||this.close()},r.prototype.packet=function(t){u("writing packet %j",t);var e=this;t.query&&0===t.type&&(t.nsp+="?"+t.query),e.encoding?e.packetBuffer.push(t):(e.encoding=!0,this.encoder.encode(t,function(n){for(var r=0;r<n.length;r++)e.engine.write(n[r],t.options);e.encoding=!1,e.processPacketQueue()}))},r.prototype.processPacketQueue=function(){if(this.packetBuffer.length>0&&!this.encoding){var t=this.packetBuffer.shift();this.packet(t)}},r.prototype.cleanup=function(){u("cleanup");for(var t=this.subs.length,e=0;e<t;e++){var n=this.subs.shift();n.destroy()}this.packetBuffer=[],this.encoding=!1,this.lastPing=null,this.decoder.destroy()},r.prototype.close=r.prototype.disconnect=function(){u("disconnect"),this.skipReconnect=!0,this.reconnecting=!1,"opening"===this.readyState&&this.cleanup(),this.backoff.reset(),this.readyState="closed",this.engine&&this.engine.close()},r.prototype.onclose=function(t){u("onclose"),this.cleanup(),this.backoff.reset(),this.readyState="closed",this.emit("close",t),this._reconnection&&!this.skipReconnect&&this.reconnect()},r.prototype.reconnect=function(){if(this.reconnecting||this.skipReconnect)return this;var t=this;if(this.backoff.attempts>=this._reconnectionAttempts)u("reconnect failed"),this.backoff.reset(),this.emitAll("reconnect_failed"),this.reconnecting=!1;else{var e=this.backoff.duration();u("will wait %dms before reconnect attempt",e),this.reconnecting=!0;var n=setTimeout(function(){t.skipReconnect||(u("attempting reconnect"),t.emitAll("reconnect_attempt",t.backoff.attempts),t.emitAll("reconnecting",t.backoff.attempts),t.skipReconnect||t.open(function(e){e?(u("reconnect attempt error"),t.reconnecting=!1,t.reconnect(),t.emitAll("reconnect_error",e.data)):(u("reconnect success"),t.onreconnect())}))},e);this.subs.push({destroy:function(){clearTimeout(n)}})}},r.prototype.onreconnect=function(){var t=this.backoff.attempts;this.reconnecting=!1,this.backoff.reset(),this.updateSocketIds(),this.emitAll("reconnect",t)}},function(t,e,n){t.exports=n(14),t.exports.parser=n(22)},function(t,e,n){function r(t,e){return this instanceof r?(e=e||{},t&&"object"==typeof t&&(e=t,t=null),t?(t=u(t),e.hostname=t.host,e.secure="https"===t.protocol||"wss"===t.protocol,e.port=t.port,t.query&&(e.query=t.query)):e.host&&(e.hostname=u(e.host).host),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.agent=e.agent||!1,this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?443:80),this.query=e.query||{},"string"==typeof this.query&&(this.query=h.decode(this.query)),this.upgrade=!1!==e.upgrade,this.path=(e.path||"/engine.io").replace(/\/$/,"")+"/",this.forceJSONP=!!e.forceJSONP,this.jsonp=!1!==e.jsonp,this.forceBase64=!!e.forceBase64,this.enablesXDR=!!e.enablesXDR,this.withCredentials=!1!==e.withCredentials,this.timestampParam=e.timestampParam||"t",this.timestampRequests=e.timestampRequests,this.transports=e.transports||["polling","websocket"],this.transportOptions=e.transportOptions||{},this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.policyPort=e.policyPort||843,this.rememberUpgrade=e.rememberUpgrade||!1,this.binaryType=null,this.onlyBinaryUpgrades=e.onlyBinaryUpgrades,this.perMessageDeflate=!1!==e.perMessageDeflate&&(e.perMessageDeflate||{}),!0===this.perMessageDeflate&&(this.perMessageDeflate={}),this.perMessageDeflate&&null==this.perMessageDeflate.threshold&&(this.perMessageDeflate.threshold=1024),this.pfx=e.pfx||null,this.key=e.key||null,this.passphrase=e.passphrase||null,this.cert=e.cert||null,this.ca=e.ca||null,this.ciphers=e.ciphers||null,this.rejectUnauthorized=void 0===e.rejectUnauthorized||e.rejectUnauthorized,this.forceNode=!!e.forceNode,this.isReactNative="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),("undefined"==typeof self||this.isReactNative)&&(e.extraHeaders&&Object.keys(e.extraHeaders).length>0&&(this.extraHeaders=e.extraHeaders),e.localAddress&&(this.localAddress=e.localAddress)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingIntervalTimer=null,this.pingTimeoutTimer=null,void this.open()):new r(t,e)}function o(t){var e={};for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}var i=n(15),s=n(8),a=n(3)("engine.io-client:socket"),c=n(36),p=n(22),u=n(2),h=n(30);t.exports=r,r.priorWebsocketSuccess=!1,s(r.prototype),r.protocol=p.protocol,r.Socket=r,r.Transport=n(21),r.transports=n(15),r.parser=n(22),r.prototype.createTransport=function(t){a('creating transport "%s"',t);var e=o(this.query);e.EIO=p.protocol,e.transport=t;var n=this.transportOptions[t]||{};this.id&&(e.sid=this.id);var r=new i[t]({query:e,socket:this,agent:n.agent||this.agent,hostname:n.hostname||this.hostname,port:n.port||this.port,secure:n.secure||this.secure,path:n.path||this.path,forceJSONP:n.forceJSONP||this.forceJSONP,jsonp:n.jsonp||this.jsonp,forceBase64:n.forceBase64||this.forceBase64,enablesXDR:n.enablesXDR||this.enablesXDR,withCredentials:n.withCredentials||this.withCredentials,timestampRequests:n.timestampRequests||this.timestampRequests,timestampParam:n.timestampParam||this.timestampParam,policyPort:n.policyPort||this.policyPort,pfx:n.pfx||this.pfx,key:n.key||this.key,passphrase:n.passphrase||this.passphrase,cert:n.cert||this.cert,ca:n.ca||this.ca,ciphers:n.ciphers||this.ciphers,rejectUnauthorized:n.rejectUnauthorized||this.rejectUnauthorized,perMessageDeflate:n.perMessageDeflate||this.perMessageDeflate,extraHeaders:n.extraHeaders||this.extraHeaders,forceNode:n.forceNode||this.forceNode,localAddress:n.localAddress||this.localAddress,requestTimeout:n.requestTimeout||this.requestTimeout,protocols:n.protocols||void 0,isReactNative:this.isReactNative});return r},r.prototype.open=function(){var t;if(this.rememberUpgrade&&r.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)t="websocket";else{if(0===this.transports.length){var e=this;return void setTimeout(function(){e.emit("error","No transports available")},0)}t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(n){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)},r.prototype.setTransport=function(t){a("setting transport %s",t.name);var e=this;this.transport&&(a("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=t,t.on("drain",function(){e.onDrain()}).on("packet",function(t){e.onPacket(t)}).on("error",function(t){e.onError(t)}).on("close",function(){e.onClose("transport close")})},r.prototype.probe=function(t){function e(){if(f.onlyBinaryUpgrades){var e=!this.supportsBinary&&f.transport.supportsBinary;h=h||e}h||(a('probe transport "%s" opened',t),u.send([{type:"ping",data:"probe"}]),u.once("packet",function(e){if(!h)if("pong"===e.type&&"probe"===e.data){if(a('probe transport "%s" pong',t),f.upgrading=!0,f.emit("upgrading",u),!u)return;r.priorWebsocketSuccess="websocket"===u.name,a('pausing current transport "%s"',f.transport.name),f.transport.pause(function(){h||"closed"!==f.readyState&&(a("changing transport and sending upgrade packet"),p(),f.setTransport(u),u.send([{type:"upgrade"}]),f.emit("upgrade",u),u=null,f.upgrading=!1,f.flush())})}else{a('probe transport "%s" failed',t);var n=new Error("probe error");n.transport=u.name,f.emit("upgradeError",n)}}))}function n(){h||(h=!0,p(),u.close(),u=null)}function o(e){var r=new Error("probe error: "+e);r.transport=u.name,n(),a('probe transport "%s" failed because of error: %s',t,e),f.emit("upgradeError",r)}function i(){o("transport closed")}function s(){o("socket closed")}function c(t){u&&t.name!==u.name&&(a('"%s" works - aborting "%s"',t.name,u.name),n())}function p(){u.removeListener("open",e),u.removeListener("error",o),u.removeListener("close",i),f.removeListener("close",s),f.removeListener("upgrading",c)}a('probing transport "%s"',t);var u=this.createTransport(t,{probe:1}),h=!1,f=this;r.priorWebsocketSuccess=!1,u.once("open",e),u.once("error",o),u.once("close",i),this.once("close",s),this.once("upgrading",c),u.open()},r.prototype.onOpen=function(){if(a("socket open"),this.readyState="open",r.priorWebsocketSuccess="websocket"===this.transport.name,this.emit("open"),this.flush(),"open"===this.readyState&&this.upgrade&&this.transport.pause){a("starting upgrade probes");for(var t=0,e=this.upgrades.length;t<e;t++)this.probe(this.upgrades[t])}},r.prototype.onPacket=function(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(a('socket receive: type "%s", data "%s"',t.type,t.data),this.emit("packet",t),this.emit("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"pong":this.setPing(),this.emit("pong");break;case"error":var e=new Error("server error");e.code=t.data,this.onError(e);break;case"message":this.emit("data",t.data),this.emit("message",t.data)}else a('packet received with socket readyState "%s"',this.readyState)},r.prototype.onHandshake=function(t){this.emit("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this.upgrades=this.filterUpgrades(t.upgrades),this.pingInterval=t.pingInterval,this.pingTimeout=t.pingTimeout,this.onOpen(),"closed"!==this.readyState&&(this.setPing(),this.removeListener("heartbeat",this.onHeartbeat),this.on("heartbeat",this.onHeartbeat))},r.prototype.onHeartbeat=function(t){clearTimeout(this.pingTimeoutTimer);var e=this;e.pingTimeoutTimer=setTimeout(function(){"closed"!==e.readyState&&e.onClose("ping timeout")},t||e.pingInterval+e.pingTimeout)},r.prototype.setPing=function(){var t=this;clearTimeout(t.pingIntervalTimer),t.pingIntervalTimer=setTimeout(function(){a("writing ping packet - expecting pong within %sms",t.pingTimeout),t.ping(),t.onHeartbeat(t.pingTimeout)},t.pingInterval)},r.prototype.ping=function(){var t=this;this.sendPacket("ping",function(){t.emit("ping")})},r.prototype.onDrain=function(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emit("drain"):this.flush()},r.prototype.flush=function(){"closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length&&(a("flushing %d packets in socket",this.writeBuffer.length),this.transport.send(this.writeBuffer),this.prevBufferLen=this.writeBuffer.length,this.emit("flush"))},r.prototype.write=r.prototype.send=function(t,e,n){return this.sendPacket("message",t,e,n),this},r.prototype.sendPacket=function(t,e,n,r){if("function"==typeof e&&(r=e,e=void 0),"function"==typeof n&&(r=n,n=null),"closing"!==this.readyState&&"closed"!==this.readyState){n=n||{},n.compress=!1!==n.compress;var o={type:t,data:e,options:n};this.emit("packetCreate",o),this.writeBuffer.push(o),r&&this.once("flush",r),this.flush()}},r.prototype.close=function(){function t(){r.onClose("forced close"),a("socket closing - telling transport to close"),r.transport.close()}function e(){r.removeListener("upgrade",e),r.removeListener("upgradeError",e),t()}function n(){r.once("upgrade",e),r.once("upgradeError",e)}if("opening"===this.readyState||"open"===this.readyState){this.readyState="closing";var r=this;this.writeBuffer.length?this.once("drain",function(){this.upgrading?n():t()}):this.upgrading?n():t()}return this},r.prototype.onError=function(t){a("socket error %j",t),r.priorWebsocketSuccess=!1,this.emit("error",t),this.onClose("transport error",t)},r.prototype.onClose=function(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){a('socket close with reason: "%s"',t);var n=this;clearTimeout(this.pingIntervalTimer),clearTimeout(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),
-this.transport.removeAllListeners(),this.readyState="closed",this.id=null,this.emit("close",t,e),n.writeBuffer=[],n.prevBufferLen=0}},r.prototype.filterUpgrades=function(t){for(var e=[],n=0,r=t.length;n<r;n++)~c(this.transports,t[n])&&e.push(t[n]);return e}},function(t,e,n){function r(t){var e,n=!1,r=!1,a=!1!==t.jsonp;if("undefined"!=typeof location){var c="https:"===location.protocol,p=location.port;p||(p=c?443:80),n=t.hostname!==location.hostname||p!==t.port,r=t.secure!==c}if(t.xdomain=n,t.xscheme=r,e=new o(t),"open"in e&&!t.forceJSONP)return new i(t);if(!a)throw new Error("JSONP disabled");return new s(t)}var o=n(16),i=n(19),s=n(33),a=n(34);e.polling=r,e.websocket=a},function(t,e,n){var r=n(17),o=n(18);t.exports=function(t){var e=t.xdomain,n=t.xscheme,i=t.enablesXDR;try{if("undefined"!=typeof XMLHttpRequest&&(!e||r))return new XMLHttpRequest}catch(s){}try{if("undefined"!=typeof XDomainRequest&&!n&&i)return new XDomainRequest}catch(s){}if(!e)try{return new(o[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(s){}}},function(t,e){try{t.exports="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(n){t.exports=!1}},function(t,e){t.exports=function(){return"undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")()}()},function(t,e,n){function r(){}function o(t){if(c.call(this,t),this.requestTimeout=t.requestTimeout,this.extraHeaders=t.extraHeaders,"undefined"!=typeof location){var e="https:"===location.protocol,n=location.port;n||(n=e?443:80),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||n!==t.port,this.xs=t.secure!==e}}function i(t){this.method=t.method||"GET",this.uri=t.uri,this.xd=!!t.xd,this.xs=!!t.xs,this.async=!1!==t.async,this.data=void 0!==t.data?t.data:null,this.agent=t.agent,this.isBinary=t.isBinary,this.supportsBinary=t.supportsBinary,this.enablesXDR=t.enablesXDR,this.withCredentials=t.withCredentials,this.requestTimeout=t.requestTimeout,this.pfx=t.pfx,this.key=t.key,this.passphrase=t.passphrase,this.cert=t.cert,this.ca=t.ca,this.ciphers=t.ciphers,this.rejectUnauthorized=t.rejectUnauthorized,this.extraHeaders=t.extraHeaders,this.create()}function s(){for(var t in i.requests)i.requests.hasOwnProperty(t)&&i.requests[t].abort()}var a=n(16),c=n(20),p=n(8),u=n(31),h=n(3)("engine.io-client:polling-xhr"),f=n(18);if(t.exports=o,t.exports.Request=i,u(o,c),o.prototype.supportsBinary=!0,o.prototype.request=function(t){return t=t||{},t.uri=this.uri(),t.xd=this.xd,t.xs=this.xs,t.agent=this.agent||!1,t.supportsBinary=this.supportsBinary,t.enablesXDR=this.enablesXDR,t.withCredentials=this.withCredentials,t.pfx=this.pfx,t.key=this.key,t.passphrase=this.passphrase,t.cert=this.cert,t.ca=this.ca,t.ciphers=this.ciphers,t.rejectUnauthorized=this.rejectUnauthorized,t.requestTimeout=this.requestTimeout,t.extraHeaders=this.extraHeaders,new i(t)},o.prototype.doWrite=function(t,e){var n="string"!=typeof t&&void 0!==t,r=this.request({method:"POST",data:t,isBinary:n}),o=this;r.on("success",e),r.on("error",function(t){o.onError("xhr post error",t)}),this.sendXhr=r},o.prototype.doPoll=function(){h("xhr poll");var t=this.request(),e=this;t.on("data",function(t){e.onData(t)}),t.on("error",function(t){e.onError("xhr poll error",t)}),this.pollXhr=t},p(i.prototype),i.prototype.create=function(){var t={agent:this.agent,xdomain:this.xd,xscheme:this.xs,enablesXDR:this.enablesXDR};t.pfx=this.pfx,t.key=this.key,t.passphrase=this.passphrase,t.cert=this.cert,t.ca=this.ca,t.ciphers=this.ciphers,t.rejectUnauthorized=this.rejectUnauthorized;var e=this.xhr=new a(t),n=this;try{h("xhr open %s: %s",this.method,this.uri),e.open(this.method,this.uri,this.async);try{if(this.extraHeaders){e.setDisableHeaderCheck&&e.setDisableHeaderCheck(!0);for(var r in this.extraHeaders)this.extraHeaders.hasOwnProperty(r)&&e.setRequestHeader(r,this.extraHeaders[r])}}catch(o){}if("POST"===this.method)try{this.isBinary?e.setRequestHeader("Content-type","application/octet-stream"):e.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(o){}try{e.setRequestHeader("Accept","*/*")}catch(o){}"withCredentials"in e&&(e.withCredentials=this.withCredentials),this.requestTimeout&&(e.timeout=this.requestTimeout),this.hasXDR()?(e.onload=function(){n.onLoad()},e.onerror=function(){n.onError(e.responseText)}):e.onreadystatechange=function(){if(2===e.readyState)try{var t=e.getResponseHeader("Content-Type");(n.supportsBinary&&"application/octet-stream"===t||"application/octet-stream; charset=UTF-8"===t)&&(e.responseType="arraybuffer")}catch(r){}4===e.readyState&&(200===e.status||1223===e.status?n.onLoad():setTimeout(function(){n.onError("number"==typeof e.status?e.status:0)},0))},h("xhr data %s",this.data),e.send(this.data)}catch(o){return void setTimeout(function(){n.onError(o)},0)}"undefined"!=typeof document&&(this.index=i.requestsCount++,i.requests[this.index]=this)},i.prototype.onSuccess=function(){this.emit("success"),this.cleanup()},i.prototype.onData=function(t){this.emit("data",t),this.onSuccess()},i.prototype.onError=function(t){this.emit("error",t),this.cleanup(!0)},i.prototype.cleanup=function(t){if("undefined"!=typeof this.xhr&&null!==this.xhr){if(this.hasXDR()?this.xhr.onload=this.xhr.onerror=r:this.xhr.onreadystatechange=r,t)try{this.xhr.abort()}catch(e){}"undefined"!=typeof document&&delete i.requests[this.index],this.xhr=null}},i.prototype.onLoad=function(){var t;try{var e;try{e=this.xhr.getResponseHeader("Content-Type")}catch(n){}t="application/octet-stream"===e||"application/octet-stream; charset=UTF-8"===e?this.xhr.response||this.xhr.responseText:this.xhr.responseText}catch(n){this.onError(n)}null!=t&&this.onData(t)},i.prototype.hasXDR=function(){return"undefined"!=typeof XDomainRequest&&!this.xs&&this.enablesXDR},i.prototype.abort=function(){this.cleanup()},i.requestsCount=0,i.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",s);else if("function"==typeof addEventListener){var l="onpagehide"in f?"pagehide":"unload";addEventListener(l,s,!1)}},function(t,e,n){function r(t){var e=t&&t.forceBase64;u&&!e||(this.supportsBinary=!1),o.call(this,t)}var o=n(21),i=n(30),s=n(22),a=n(31),c=n(32),p=n(3)("engine.io-client:polling");t.exports=r;var u=function(){var t=n(16),e=new t({xdomain:!1});return null!=e.responseType}();a(r,o),r.prototype.name="polling",r.prototype.doOpen=function(){this.poll()},r.prototype.pause=function(t){function e(){p("paused"),n.readyState="paused",t()}var n=this;if(this.readyState="pausing",this.polling||!this.writable){var r=0;this.polling&&(p("we are currently polling - waiting to pause"),r++,this.once("pollComplete",function(){p("pre-pause polling complete"),--r||e()})),this.writable||(p("we are currently writing - waiting to pause"),r++,this.once("drain",function(){p("pre-pause writing complete"),--r||e()}))}else e()},r.prototype.poll=function(){p("polling"),this.polling=!0,this.doPoll(),this.emit("poll")},r.prototype.onData=function(t){var e=this;p("polling got data %s",t);var n=function(t,n,r){return"opening"===e.readyState&&"open"===t.type&&e.onOpen(),"close"===t.type?(e.onClose(),!1):void e.onPacket(t)};s.decodePayload(t,this.socket.binaryType,n),"closed"!==this.readyState&&(this.polling=!1,this.emit("pollComplete"),"open"===this.readyState?this.poll():p('ignoring poll - transport state "%s"',this.readyState))},r.prototype.doClose=function(){function t(){p("writing close packet"),e.write([{type:"close"}])}var e=this;"open"===this.readyState?(p("transport open - closing"),t()):(p("transport not open - deferring close"),this.once("open",t))},r.prototype.write=function(t){var e=this;this.writable=!1;var n=function(){e.writable=!0,e.emit("drain")};s.encodePayload(t,this.supportsBinary,function(t){e.doWrite(t,n)})},r.prototype.uri=function(){var t=this.query||{},e=this.secure?"https":"http",n="";!1!==this.timestampRequests&&(t[this.timestampParam]=c()),this.supportsBinary||t.sid||(t.b64=1),t=i.encode(t),this.port&&("https"===e&&443!==Number(this.port)||"http"===e&&80!==Number(this.port))&&(n=":"+this.port),t.length&&(t="?"+t);var r=this.hostname.indexOf(":")!==-1;return e+"://"+(r?"["+this.hostname+"]":this.hostname)+n+this.path+t}},function(t,e,n){function r(t){this.path=t.path,this.hostname=t.hostname,this.port=t.port,this.secure=t.secure,this.query=t.query,this.timestampParam=t.timestampParam,this.timestampRequests=t.timestampRequests,this.readyState="",this.agent=t.agent||!1,this.socket=t.socket,this.enablesXDR=t.enablesXDR,this.withCredentials=t.withCredentials,this.pfx=t.pfx,this.key=t.key,this.passphrase=t.passphrase,this.cert=t.cert,this.ca=t.ca,this.ciphers=t.ciphers,this.rejectUnauthorized=t.rejectUnauthorized,this.forceNode=t.forceNode,this.isReactNative=t.isReactNative,this.extraHeaders=t.extraHeaders,this.localAddress=t.localAddress}var o=n(22),i=n(8);t.exports=r,i(r.prototype),r.prototype.onError=function(t,e){var n=new Error(t);return n.type="TransportError",n.description=e,this.emit("error",n),this},r.prototype.open=function(){return"closed"!==this.readyState&&""!==this.readyState||(this.readyState="opening",this.doOpen()),this},r.prototype.close=function(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this},r.prototype.send=function(t){if("open"!==this.readyState)throw new Error("Transport not open");this.write(t)},r.prototype.onOpen=function(){this.readyState="open",this.writable=!0,this.emit("open")},r.prototype.onData=function(t){var e=o.decodePacket(t,this.socket.binaryType);this.onPacket(e)},r.prototype.onPacket=function(t){this.emit("packet",t)},r.prototype.onClose=function(){this.readyState="closed",this.emit("close")}},function(t,e,n){function r(t,n){var r="b"+e.packets[t.type]+t.data.data;return n(r)}function o(t,n,r){if(!n)return e.encodeBase64Packet(t,r);var o=t.data,i=new Uint8Array(o),s=new Uint8Array(1+o.byteLength);s[0]=v[t.type];for(var a=0;a<i.length;a++)s[a+1]=i[a];return r(s.buffer)}function i(t,n,r){if(!n)return e.encodeBase64Packet(t,r);var o=new FileReader;return o.onload=function(){e.encodePacket({type:t.type,data:o.result},n,!0,r)},o.readAsArrayBuffer(t.data)}function s(t,n,r){if(!n)return e.encodeBase64Packet(t,r);if(m)return i(t,n,r);var o=new Uint8Array(1);o[0]=v[t.type];var s=new k([o.buffer,t.data]);return r(s)}function a(t){try{t=d.decode(t,{strict:!1})}catch(e){return!1}return t}function c(t,e,n){for(var r=new Array(t.length),o=l(t.length,n),i=function(t,n,o){e(n,function(e,n){r[t]=n,o(e,r)})},s=0;s<t.length;s++)i(s,t[s],o)}var p,u=n(23),h=n(24),f=n(25),l=n(26),d=n(27);"undefined"!=typeof ArrayBuffer&&(p=n(28));var y="undefined"!=typeof navigator&&/Android/i.test(navigator.userAgent),g="undefined"!=typeof navigator&&/PhantomJS/i.test(navigator.userAgent),m=y||g;e.protocol=3;var v=e.packets={open:0,close:1,ping:2,pong:3,message:4,upgrade:5,noop:6},b=u(v),w={type:"error",data:"parser error"},k=n(29);e.encodePacket=function(t,e,n,i){"function"==typeof e&&(i=e,e=!1),"function"==typeof n&&(i=n,n=null);var a=void 0===t.data?void 0:t.data.buffer||t.data;if("undefined"!=typeof ArrayBuffer&&a instanceof ArrayBuffer)return o(t,e,i);if("undefined"!=typeof k&&a instanceof k)return s(t,e,i);if(a&&a.base64)return r(t,i);var c=v[t.type];return void 0!==t.data&&(c+=n?d.encode(String(t.data),{strict:!1}):String(t.data)),i(""+c)},e.encodeBase64Packet=function(t,n){var r="b"+e.packets[t.type];if("undefined"!=typeof k&&t.data instanceof k){var o=new FileReader;return o.onload=function(){var t=o.result.split(",")[1];n(r+t)},o.readAsDataURL(t.data)}var i;try{i=String.fromCharCode.apply(null,new Uint8Array(t.data))}catch(s){for(var a=new Uint8Array(t.data),c=new Array(a.length),p=0;p<a.length;p++)c[p]=a[p];i=String.fromCharCode.apply(null,c)}return r+=btoa(i),n(r)},e.decodePacket=function(t,n,r){if(void 0===t)return w;if("string"==typeof t){if("b"===t.charAt(0))return e.decodeBase64Packet(t.substr(1),n);if(r&&(t=a(t),t===!1))return w;var o=t.charAt(0);return Number(o)==o&&b[o]?t.length>1?{type:b[o],data:t.substring(1)}:{type:b[o]}:w}var i=new Uint8Array(t),o=i[0],s=f(t,1);return k&&"blob"===n&&(s=new k([s])),{type:b[o],data:s}},e.decodeBase64Packet=function(t,e){var n=b[t.charAt(0)];if(!p)return{type:n,data:{base64:!0,data:t.substr(1)}};var r=p.decode(t.substr(1));return"blob"===e&&k&&(r=new k([r])),{type:n,data:r}},e.encodePayload=function(t,n,r){function o(t){return t.length+":"+t}function i(t,r){e.encodePacket(t,!!s&&n,!1,function(t){r(null,o(t))})}"function"==typeof n&&(r=n,n=null);var s=h(t);return n&&s?k&&!m?e.encodePayloadAsBlob(t,r):e.encodePayloadAsArrayBuffer(t,r):t.length?void c(t,i,function(t,e){return r(e.join(""))}):r("0:")},e.decodePayload=function(t,n,r){if("string"!=typeof t)return e.decodePayloadAsBinary(t,n,r);"function"==typeof n&&(r=n,n=null);var o;if(""===t)return r(w,0,1);for(var i,s,a="",c=0,p=t.length;c<p;c++){var u=t.charAt(c);if(":"===u){if(""===a||a!=(i=Number(a)))return r(w,0,1);if(s=t.substr(c+1,i),a!=s.length)return r(w,0,1);if(s.length){if(o=e.decodePacket(s,n,!1),w.type===o.type&&w.data===o.data)return r(w,0,1);var h=r(o,c+i,p);if(!1===h)return}c+=i,a=""}else a+=u}return""!==a?r(w,0,1):void 0},e.encodePayloadAsArrayBuffer=function(t,n){function r(t,n){e.encodePacket(t,!0,!0,function(t){return n(null,t)})}return t.length?void c(t,r,function(t,e){var r=e.reduce(function(t,e){var n;return n="string"==typeof e?e.length:e.byteLength,t+n.toString().length+n+2},0),o=new Uint8Array(r),i=0;return e.forEach(function(t){var e="string"==typeof t,n=t;if(e){for(var r=new Uint8Array(t.length),s=0;s<t.length;s++)r[s]=t.charCodeAt(s);n=r.buffer}e?o[i++]=0:o[i++]=1;for(var a=n.byteLength.toString(),s=0;s<a.length;s++)o[i++]=parseInt(a[s]);o[i++]=255;for(var r=new Uint8Array(n),s=0;s<r.length;s++)o[i++]=r[s]}),n(o.buffer)}):n(new ArrayBuffer(0))},e.encodePayloadAsBlob=function(t,n){function r(t,n){e.encodePacket(t,!0,!0,function(t){var e=new Uint8Array(1);if(e[0]=1,"string"==typeof t){for(var r=new Uint8Array(t.length),o=0;o<t.length;o++)r[o]=t.charCodeAt(o);t=r.buffer,e[0]=0}for(var i=t instanceof ArrayBuffer?t.byteLength:t.size,s=i.toString(),a=new Uint8Array(s.length+1),o=0;o<s.length;o++)a[o]=parseInt(s[o]);if(a[s.length]=255,k){var c=new k([e.buffer,a.buffer,t]);n(null,c)}})}c(t,r,function(t,e){return n(new k(e))})},e.decodePayloadAsBinary=function(t,n,r){"function"==typeof n&&(r=n,n=null);for(var o=t,i=[];o.byteLength>0;){for(var s=new Uint8Array(o),a=0===s[0],c="",p=1;255!==s[p];p++){if(c.length>310)return r(w,0,1);c+=s[p]}o=f(o,2+c.length),c=parseInt(c);var u=f(o,0,c);if(a)try{u=String.fromCharCode.apply(null,new Uint8Array(u))}catch(h){var l=new Uint8Array(u);u="";for(var p=0;p<l.length;p++)u+=String.fromCharCode(l[p])}i.push(u),o=f(o,c)}var d=i.length;i.forEach(function(t,o){r(e.decodePacket(t,n,!0),o,d)})}},function(t,e){t.exports=Object.keys||function(t){var e=[],n=Object.prototype.hasOwnProperty;for(var r in t)n.call(t,r)&&e.push(r);return e}},function(t,e,n){function r(t){if(!t||"object"!=typeof t)return!1;if(o(t)){for(var e=0,n=t.length;e<n;e++)if(r(t[e]))return!0;return!1}if("function"==typeof Buffer&&Buffer.isBuffer&&Buffer.isBuffer(t)||"function"==typeof ArrayBuffer&&t instanceof ArrayBuffer||s&&t instanceof Blob||a&&t instanceof File)return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return r(t.toJSON(),!0);for(var i in t)if(Object.prototype.hasOwnProperty.call(t,i)&&r(t[i]))return!0;return!1}var o=n(10),i=Object.prototype.toString,s="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===i.call(Blob),a="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===i.call(File);t.exports=r},function(t,e){t.exports=function(t,e,n){var r=t.byteLength;if(e=e||0,n=n||r,t.slice)return t.slice(e,n);if(e<0&&(e+=r),n<0&&(n+=r),n>r&&(n=r),e>=r||e>=n||0===r)return new ArrayBuffer(0);for(var o=new Uint8Array(t),i=new Uint8Array(n-e),s=e,a=0;s<n;s++,a++)i[a]=o[s];return i.buffer}},function(t,e){function n(t,e,n){function o(t,r){if(o.count<=0)throw new Error("after called too many times");--o.count,t?(i=!0,e(t),e=n):0!==o.count||i||e(null,r)}var i=!1;return n=n||r,o.count=t,0===t?e():o}function r(){}t.exports=n},function(t,e){function n(t){for(var e,n,r=[],o=0,i=t.length;o<i;)e=t.charCodeAt(o++),e>=55296&&e<=56319&&o<i?(n=t.charCodeAt(o++),56320==(64512&n)?r.push(((1023&e)<<10)+(1023&n)+65536):(r.push(e),o--)):r.push(e);return r}function r(t){for(var e,n=t.length,r=-1,o="";++r<n;)e=t[r],e>65535&&(e-=65536,o+=d(e>>>10&1023|55296),e=56320|1023&e),o+=d(e);return o}function o(t,e){if(t>=55296&&t<=57343){if(e)throw Error("Lone surrogate U+"+t.toString(16).toUpperCase()+" is not a scalar value");return!1}return!0}function i(t,e){return d(t>>e&63|128)}function s(t,e){if(0==(4294967168&t))return d(t);var n="";return 0==(4294965248&t)?n=d(t>>6&31|192):0==(4294901760&t)?(o(t,e)||(t=65533),n=d(t>>12&15|224),n+=i(t,6)):0==(4292870144&t)&&(n=d(t>>18&7|240),n+=i(t,12),n+=i(t,6)),n+=d(63&t|128)}function a(t,e){e=e||{};for(var r,o=!1!==e.strict,i=n(t),a=i.length,c=-1,p="";++c<a;)r=i[c],p+=s(r,o);return p}function c(){if(l>=f)throw Error("Invalid byte index");var t=255&h[l];if(l++,128==(192&t))return 63&t;throw Error("Invalid continuation byte")}function p(t){var e,n,r,i,s;if(l>f)throw Error("Invalid byte index");if(l==f)return!1;if(e=255&h[l],l++,0==(128&e))return e;if(192==(224&e)){if(n=c(),s=(31&e)<<6|n,s>=128)return s;throw Error("Invalid continuation byte")}if(224==(240&e)){if(n=c(),r=c(),s=(15&e)<<12|n<<6|r,s>=2048)return o(s,t)?s:65533;throw Error("Invalid continuation byte")}if(240==(248&e)&&(n=c(),r=c(),i=c(),s=(7&e)<<18|n<<12|r<<6|i,s>=65536&&s<=1114111))return s;throw Error("Invalid UTF-8 detected")}function u(t,e){e=e||{};var o=!1!==e.strict;h=n(t),f=h.length,l=0;for(var i,s=[];(i=p(o))!==!1;)s.push(i);return r(s)}/*! https://mths.be/utf8js v2.1.2 by @mathias */
-var h,f,l,d=String.fromCharCode;t.exports={version:"2.1.2",encode:a,decode:u}},function(t,e){!function(t){"use strict";e.encode=function(e){var n,r=new Uint8Array(e),o=r.length,i="";for(n=0;n<o;n+=3)i+=t[r[n]>>2],i+=t[(3&r[n])<<4|r[n+1]>>4],i+=t[(15&r[n+1])<<2|r[n+2]>>6],i+=t[63&r[n+2]];return o%3===2?i=i.substring(0,i.length-1)+"=":o%3===1&&(i=i.substring(0,i.length-2)+"=="),i},e.decode=function(e){var n,r,o,i,s,a=.75*e.length,c=e.length,p=0;"="===e[e.length-1]&&(a--,"="===e[e.length-2]&&a--);var u=new ArrayBuffer(a),h=new Uint8Array(u);for(n=0;n<c;n+=4)r=t.indexOf(e[n]),o=t.indexOf(e[n+1]),i=t.indexOf(e[n+2]),s=t.indexOf(e[n+3]),h[p++]=r<<2|o>>4,h[p++]=(15&o)<<4|i>>2,h[p++]=(3&i)<<6|63&s;return u}}("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")},function(t,e){function n(t){return t.map(function(t){if(t.buffer instanceof ArrayBuffer){var e=t.buffer;if(t.byteLength!==e.byteLength){var n=new Uint8Array(t.byteLength);n.set(new Uint8Array(e,t.byteOffset,t.byteLength)),e=n.buffer}return e}return t})}function r(t,e){e=e||{};var r=new i;return n(t).forEach(function(t){r.append(t)}),e.type?r.getBlob(e.type):r.getBlob()}function o(t,e){return new Blob(n(t),e||{})}var i="undefined"!=typeof i?i:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder&&MozBlobBuilder,s=function(){try{var t=new Blob(["hi"]);return 2===t.size}catch(e){return!1}}(),a=s&&function(){try{var t=new Blob([new Uint8Array([1,2])]);return 2===t.size}catch(e){return!1}}(),c=i&&i.prototype.append&&i.prototype.getBlob;"undefined"!=typeof Blob&&(r.prototype=Blob.prototype,o.prototype=Blob.prototype),t.exports=function(){return s?a?Blob:o:c?r:void 0}()},function(t,e){e.encode=function(t){var e="";for(var n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e},e.decode=function(t){for(var e={},n=t.split("&"),r=0,o=n.length;r<o;r++){var i=n[r].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}},function(t,e){t.exports=function(t,e){var n=function(){};n.prototype=e.prototype,t.prototype=new n,t.prototype.constructor=t}},function(t,e){"use strict";function n(t){var e="";do e=s[t%a]+e,t=Math.floor(t/a);while(t>0);return e}function r(t){var e=0;for(u=0;u<t.length;u++)e=e*a+c[t.charAt(u)];return e}function o(){var t=n(+new Date);return t!==i?(p=0,i=t):t+"."+n(p++)}for(var i,s="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),a=64,c={},p=0,u=0;u<a;u++)c[s[u]]=u;o.encode=n,o.decode=r,t.exports=o},function(t,e,n){function r(){}function o(t){i.call(this,t),this.query=this.query||{},c||(c=a.___eio=a.___eio||[]),this.index=c.length;var e=this;c.push(function(t){e.onData(t)}),this.query.j=this.index,"function"==typeof addEventListener&&addEventListener("beforeunload",function(){e.script&&(e.script.onerror=r)},!1)}var i=n(20),s=n(31),a=n(18);t.exports=o;var c,p=/\n/g,u=/\\n/g;s(o,i),o.prototype.supportsBinary=!1,o.prototype.doClose=function(){this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),this.form&&(this.form.parentNode.removeChild(this.form),this.form=null,this.iframe=null),i.prototype.doClose.call(this)},o.prototype.doPoll=function(){var t=this,e=document.createElement("script");this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),e.async=!0,e.src=this.uri(),e.onerror=function(e){t.onError("jsonp poll error",e)};var n=document.getElementsByTagName("script")[0];n?n.parentNode.insertBefore(e,n):(document.head||document.body).appendChild(e),this.script=e;var r="undefined"!=typeof navigator&&/gecko/i.test(navigator.userAgent);r&&setTimeout(function(){var t=document.createElement("iframe");document.body.appendChild(t),document.body.removeChild(t)},100)},o.prototype.doWrite=function(t,e){function n(){r(),e()}function r(){if(o.iframe)try{o.form.removeChild(o.iframe)}catch(t){o.onError("jsonp polling iframe removal error",t)}try{var e='<iframe src="javascript:0" name="'+o.iframeId+'">';i=document.createElement(e)}catch(t){i=document.createElement("iframe"),i.name=o.iframeId,i.src="javascript:0"}i.id=o.iframeId,o.form.appendChild(i),o.iframe=i}var o=this;if(!this.form){var i,s=document.createElement("form"),a=document.createElement("textarea"),c=this.iframeId="eio_iframe_"+this.index;s.className="socketio",s.style.position="absolute",s.style.top="-1000px",s.style.left="-1000px",s.target=c,s.method="POST",s.setAttribute("accept-charset","utf-8"),a.name="d",s.appendChild(a),document.body.appendChild(s),this.form=s,this.area=a}this.form.action=this.uri(),r(),t=t.replace(u,"\\\n"),this.area.value=t.replace(p,"\\n");try{this.form.submit()}catch(h){}this.iframe.attachEvent?this.iframe.onreadystatechange=function(){"complete"===o.iframe.readyState&&n()}:this.iframe.onload=n}},function(t,e,n){function r(t){var e=t&&t.forceBase64;e&&(this.supportsBinary=!1),this.perMessageDeflate=t.perMessageDeflate,this.usingBrowserWebSocket=o&&!t.forceNode,this.protocols=t.protocols,this.usingBrowserWebSocket||(l=i),s.call(this,t)}var o,i,s=n(21),a=n(22),c=n(30),p=n(31),u=n(32),h=n(3)("engine.io-client:websocket");if("undefined"!=typeof WebSocket?o=WebSocket:"undefined"!=typeof self&&(o=self.WebSocket||self.MozWebSocket),"undefined"==typeof window)try{i=n(35)}catch(f){}var l=o||i;t.exports=r,p(r,s),r.prototype.name="websocket",r.prototype.supportsBinary=!0,r.prototype.doOpen=function(){if(this.check()){var t=this.uri(),e=this.protocols,n={};this.isReactNative||(n.agent=this.agent,n.perMessageDeflate=this.perMessageDeflate,n.pfx=this.pfx,n.key=this.key,n.passphrase=this.passphrase,n.cert=this.cert,n.ca=this.ca,n.ciphers=this.ciphers,n.rejectUnauthorized=this.rejectUnauthorized),this.extraHeaders&&(n.headers=this.extraHeaders),this.localAddress&&(n.localAddress=this.localAddress);try{this.ws=this.usingBrowserWebSocket&&!this.isReactNative?e?new l(t,e):new l(t):new l(t,e,n)}catch(r){return this.emit("error",r)}void 0===this.ws.binaryType&&(this.supportsBinary=!1),this.ws.supports&&this.ws.supports.binary?(this.supportsBinary=!0,this.ws.binaryType="nodebuffer"):this.ws.binaryType="arraybuffer",this.addEventListeners()}},r.prototype.addEventListeners=function(){var t=this;this.ws.onopen=function(){t.onOpen()},this.ws.onclose=function(){t.onClose()},this.ws.onmessage=function(e){t.onData(e.data)},this.ws.onerror=function(e){t.onError("websocket error",e)}},r.prototype.write=function(t){function e(){n.emit("flush"),setTimeout(function(){n.writable=!0,n.emit("drain")},0)}var n=this;this.writable=!1;for(var r=t.length,o=0,i=r;o<i;o++)!function(t){a.encodePacket(t,n.supportsBinary,function(o){if(!n.usingBrowserWebSocket){var i={};if(t.options&&(i.compress=t.options.compress),n.perMessageDeflate){var s="string"==typeof o?Buffer.byteLength(o):o.length;s<n.perMessageDeflate.threshold&&(i.compress=!1)}}try{n.usingBrowserWebSocket?n.ws.send(o):n.ws.send(o,i)}catch(a){h("websocket closed before onclose event")}--r||e()})}(t[o])},r.prototype.onClose=function(){s.prototype.onClose.call(this)},r.prototype.doClose=function(){"undefined"!=typeof this.ws&&this.ws.close()},r.prototype.uri=function(){var t=this.query||{},e=this.secure?"wss":"ws",n="";this.port&&("wss"===e&&443!==Number(this.port)||"ws"===e&&80!==Number(this.port))&&(n=":"+this.port),this.timestampRequests&&(t[this.timestampParam]=u()),this.supportsBinary||(t.b64=1),t=c.encode(t),t.length&&(t="?"+t);var r=this.hostname.indexOf(":")!==-1;return e+"://"+(r?"["+this.hostname+"]":this.hostname)+n+this.path+t},r.prototype.check=function(){return!(!l||"__initialize"in l&&this.name===r.prototype.name)}},function(t,e){},function(t,e){var n=[].indexOf;t.exports=function(t,e){if(n)return t.indexOf(e);for(var r=0;r<t.length;++r)if(t[r]===e)return r;return-1}},function(t,e,n){function r(t,e,n){this.io=t,this.nsp=e,this.json=this,this.ids=0,this.acks={},this.receiveBuffer=[],this.sendBuffer=[],this.connected=!1,this.disconnected=!0,this.flags={},n&&n.query&&(this.query=n.query),this.io.autoConnect&&this.open()}var o=n(7),i=n(8),s=n(38),a=n(39),c=n(40),p=n(3)("socket.io-client:socket"),u=n(30),h=n(24);t.exports=e=r;var f={connect:1,connect_error:1,connect_timeout:1,connecting:1,disconnect:1,error:1,reconnect:1,reconnect_attempt:1,reconnect_failed:1,reconnect_error:1,reconnecting:1,ping:1,pong:1},l=i.prototype.emit;i(r.prototype),r.prototype.subEvents=function(){if(!this.subs){var t=this.io;this.subs=[a(t,"open",c(this,"onopen")),a(t,"packet",c(this,"onpacket")),a(t,"close",c(this,"onclose"))]}},r.prototype.open=r.prototype.connect=function(){return this.connected?this:(this.subEvents(),this.io.reconnecting||this.io.open(),"open"===this.io.readyState&&this.onopen(),this.emit("connecting"),this)},r.prototype.send=function(){var t=s(arguments);return t.unshift("message"),this.emit.apply(this,t),this},r.prototype.emit=function(t){if(f.hasOwnProperty(t))return l.apply(this,arguments),this;var e=s(arguments),n={type:(void 0!==this.flags.binary?this.flags.binary:h(e))?o.BINARY_EVENT:o.EVENT,data:e};return n.options={},n.options.compress=!this.flags||!1!==this.flags.compress,"function"==typeof e[e.length-1]&&(p("emitting packet with ack id %d",this.ids),this.acks[this.ids]=e.pop(),n.id=this.ids++),this.connected?this.packet(n):this.sendBuffer.push(n),this.flags={},this},r.prototype.packet=function(t){t.nsp=this.nsp,this.io.packet(t)},r.prototype.onopen=function(){if(p("transport is open - connecting"),"/"!==this.nsp)if(this.query){var t="object"==typeof this.query?u.encode(this.query):this.query;p("sending connect packet with query %s",t),this.packet({type:o.CONNECT,query:t})}else this.packet({type:o.CONNECT})},r.prototype.onclose=function(t){p("close (%s)",t),this.connected=!1,this.disconnected=!0,delete this.id,this.emit("disconnect",t)},r.prototype.onpacket=function(t){var e=t.nsp===this.nsp,n=t.type===o.ERROR&&"/"===t.nsp;if(e||n)switch(t.type){case o.CONNECT:this.onconnect();break;case o.EVENT:this.onevent(t);break;case o.BINARY_EVENT:this.onevent(t);break;case o.ACK:this.onack(t);break;case o.BINARY_ACK:this.onack(t);break;case o.DISCONNECT:this.ondisconnect();break;case o.ERROR:this.emit("error",t.data)}},r.prototype.onevent=function(t){var e=t.data||[];p("emitting event %j",e),null!=t.id&&(p("attaching ack callback to event"),e.push(this.ack(t.id))),this.connected?l.apply(this,e):this.receiveBuffer.push(e)},r.prototype.ack=function(t){var e=this,n=!1;return function(){if(!n){n=!0;var r=s(arguments);p("sending ack %j",r),e.packet({type:h(r)?o.BINARY_ACK:o.ACK,id:t,data:r})}}},r.prototype.onack=function(t){var e=this.acks[t.id];"function"==typeof e?(p("calling ack %s with %j",t.id,t.data),e.apply(this,t.data),delete this.acks[t.id]):p("bad ack %s",t.id)},r.prototype.onconnect=function(){this.connected=!0,this.disconnected=!1,this.emit("connect"),this.emitBuffered()},r.prototype.emitBuffered=function(){var t;for(t=0;t<this.receiveBuffer.length;t++)l.apply(this,this.receiveBuffer[t]);for(this.receiveBuffer=[],t=0;t<this.sendBuffer.length;t++)this.packet(this.sendBuffer[t]);this.sendBuffer=[]},r.prototype.ondisconnect=function(){p("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")},r.prototype.destroy=function(){if(this.subs){for(var t=0;t<this.subs.length;t++)this.subs[t].destroy();this.subs=null}this.io.destroy(this)},r.prototype.close=r.prototype.disconnect=function(){return this.connected&&(p("performing disconnect (%s)",this.nsp),this.packet({type:o.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this},r.prototype.compress=function(t){return this.flags.compress=t,this},r.prototype.binary=function(t){return this.flags.binary=t,this}},function(t,e){function n(t,e){var n=[];e=e||0;for(var r=e||0;r<t.length;r++)n[r-e]=t[r];return n}t.exports=n},function(t,e){function n(t,e,n){return t.on(e,n),{destroy:function(){t.removeListener(e,n)}}}t.exports=n},function(t,e){var n=[].slice;t.exports=function(t,e){if("string"==typeof e&&(e=t[e]),"function"!=typeof e)throw new Error("bind() requires a function");var r=n.call(arguments,2);return function(){return e.apply(t,r.concat(n.call(arguments)))}}},function(t,e){function n(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}t.exports=n,n.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=0==(1&Math.floor(10*e))?t-n:t+n}return 0|Math.min(t,this.max)},n.prototype.reset=function(){this.attempts=0},n.prototype.setMin=function(t){this.ms=t},n.prototype.setMax=function(t){this.max=t},n.prototype.setJitter=function(t){this.jitter=t}}])});
-//# sourceMappingURL=socket.io.js.map
+!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.io=e():t.io=e()}(this,(function(){return function(t){function e(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return t[r].call(o.exports,o,o.exports,e),o.loaded=!0,o.exports}var n={};return e.m=t,e.c=n,e.p="",e(0)}([function(t,e,n){function r(t,e){"object"==typeof t&&(e=t,t=void 0),e=e||{};var n,r=o(t),i=r.source,p=r.id,h=r.path,u=c[p]&&h in c[p].nsps;return e.forceNew||e["force new connection"]||!1===e.multiplex||u?(a("ignoring socket cache for %s",i),n=s(i,e)):(c[p]||(a("new io instance for %s",i),c[p]=s(i,e)),n=c[p]),r.query&&!e.query&&(e.query=r.query),n.socket(r.path,e)}var o=n(1),i=n(7),s=n(12),a=n(3)("socket.io-client");t.exports=e=r;var c=e.managers={};e.protocol=i.protocol,e.connect=r,e.Manager=n(12),e.Socket=n(37)},function(t,e,n){var r=n(2),o=n(3)("socket.io-client:url");t.exports=function(t,e){var n=t;e=e||"undefined"!=typeof location&&location,null==t&&(t=e.protocol+"//"+e.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?e.protocol+t:e.host+t),/^(https?|wss?):\/\//.test(t)||(o("protocol-less url %s",t),t=void 0!==e?e.protocol+"//"+t:"https://"+t),o("parse %s",t),n=r(t)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";var i=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+i+":"+n.port,n.href=n.protocol+"://"+i+(e&&e.port===n.port?"":":"+n.port),n}},function(t,e){var n=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,r=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];t.exports=function(t){var e=t,o=t.indexOf("["),i=t.indexOf("]");-1!=o&&-1!=i&&(t=t.substring(0,o)+t.substring(o,i).replace(/:/g,";")+t.substring(i,t.length));for(var s=n.exec(t||""),a={},c=14;c--;)a[r[c]]=s[c]||"";return-1!=o&&-1!=i&&(a.source=e,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a.pathNames=function(t,e){var n=e.replace(/\/{2,9}/g,"/").split("/");return"/"!=e.substr(0,1)&&0!==e.length||n.splice(0,1),"/"==e.substr(e.length-1,1)&&n.splice(n.length-1,1),n}(0,a.path),a.queryKey=function(t,e){var n={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(t,e,r){e&&(n[e]=r)})),n}(0,a.query),a}},function(t,e,n){(function(r){"use strict";function o(){var t;try{t=e.storage.debug}catch(t){}return!t&&void 0!==r&&"env"in r&&(t=r.env.DEBUG),t}var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};(e=t.exports=n(5)).log=function(){return"object"===("undefined"==typeof console?"undefined":i(console))&&console.log&&Function.prototype.apply.call(console.log,console,arguments)},e.formatArgs=function(t){var n=this.useColors;if(t[0]=(n?"%c":"")+this.namespace+(n?" %c":" ")+t[0]+(n?"%c ":" ")+"+"+e.humanize(this.diff),n){var r="color: "+this.color;t.splice(1,0,r,"color: inherit");var o=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(function(t){"%%"!==t&&(o++,"%c"===t&&(i=o))})),t.splice(i,0,r)}},e.save=function(t){try{null==t?e.storage.removeItem("debug"):e.storage.debug=t}catch(t){}},e.load=o,e.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},e.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(t){}}(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],e.formatters.j=function(t){try{return JSON.stringify(t)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}},e.enable(o())}).call(e,n(4))},function(t,e){function n(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function o(t){if(p===setTimeout)return setTimeout(t,0);if((p===n||!p)&&setTimeout)return p=setTimeout,setTimeout(t,0);try{return p(t,0)}catch(e){try{return p.call(null,t,0)}catch(e){return p.call(this,t,0)}}}function i(){d&&f&&(d=!1,f.length?l=f.concat(l):y=-1,l.length&&s())}function s(){if(!d){var t=o(i);d=!0;for(var e=l.length;e;){for(f=l,l=[];++y<e;)f&&f[y].run();y=-1,e=l.length}f=null,d=!1,function(t){if(h===clearTimeout)return clearTimeout(t);if((h===r||!h)&&clearTimeout)return h=clearTimeout,clearTimeout(t);try{h(t)}catch(e){try{return h.call(null,t)}catch(e){return h.call(this,t)}}}(t)}}function a(t,e){this.fun=t,this.array=e}function c(){}var p,h,u=t.exports={};!function(){try{p="function"==typeof setTimeout?setTimeout:n}catch(t){p=n}try{h="function"==typeof clearTimeout?clearTimeout:r}catch(t){h=r}}();var f,l=[],d=!1,y=-1;u.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];l.push(new a(t,e)),1!==l.length||d||o(s)},a.prototype.run=function(){this.fun.apply(null,this.array)},u.title="browser",u.browser=!0,u.env={},u.argv=[],u.version="",u.versions={},u.on=c,u.addListener=c,u.once=c,u.off=c,u.removeListener=c,u.removeAllListeners=c,u.emit=c,u.prependListener=c,u.prependOnceListener=c,u.listeners=function(t){return[]},u.binding=function(t){throw new Error("process.binding is not supported")},u.cwd=function(){return"/"},u.chdir=function(t){throw new Error("process.chdir is not supported")},u.umask=function(){return 0}},function(t,e,n){"use strict";function r(t){function n(){if(n.enabled){var t=n,o=+new Date,i=o-(r||o);t.diff=i,t.prev=r,t.curr=o,r=o;for(var s=new Array(arguments.length),a=0;a<s.length;a++)s[a]=arguments[a];s[0]=e.coerce(s[0]),"string"!=typeof s[0]&&s.unshift("%O");var c=0;s[0]=s[0].replace(/%([a-zA-Z%])/g,(function(n,r){if("%%"===n)return n;c++;var o=e.formatters[r];if("function"==typeof o){var i=s[c];n=o.call(t,i),s.splice(c,1),c--}return n})),e.formatArgs.call(t,s);var p=n.log||e.log||console.log.bind(console);p.apply(t,s)}}var r;return n.namespace=t,n.enabled=e.enabled(t),n.useColors=e.useColors(),n.color=function(t){var n,r=0;for(n in t)r=(r<<5)-r+t.charCodeAt(n),r|=0;return e.colors[Math.abs(r)%e.colors.length]}(t),n.destroy=o,"function"==typeof e.init&&e.init(n),e.instances.push(n),n}function o(){var t=e.instances.indexOf(this);return-1!==t&&(e.instances.splice(t,1),!0)}(e=t.exports=r.debug=r.default=r).coerce=function(t){return t instanceof Error?t.stack||t.message:t},e.disable=function(){e.enable("")},e.enable=function(t){e.save(t),e.names=[],e.skips=[];var n,r=("string"==typeof t?t:"").split(/[\s,]+/),o=r.length;for(n=0;n<o;n++)r[n]&&("-"===(t=r[n].replace(/\*/g,".*?"))[0]?e.skips.push(new RegExp("^"+t.substr(1)+"$")):e.names.push(new RegExp("^"+t+"$")));for(n=0;n<e.instances.length;n++){var i=e.instances[n];i.enabled=e.enabled(i.namespace)}},e.enabled=function(t){if("*"===t[t.length-1])return!0;var n,r;for(n=0,r=e.skips.length;n<r;n++)if(e.skips[n].test(t))return!1;for(n=0,r=e.names.length;n<r;n++)if(e.names[n].test(t))return!0;return!1},e.humanize=n(6),e.instances=[],e.names=[],e.skips=[],e.formatters={}},function(t,e){function n(t){return r(t,a,"day")||r(t,s,"hour")||r(t,i,"minute")||r(t,o,"second")||t+" ms"}function r(t,e,n){if(!(t<e))return t<1.5*e?Math.floor(t/e)+" "+n:Math.ceil(t/e)+" "+n+"s"}var o=1e3,i=60*o,s=60*i,a=24*s,c=365.25*a;t.exports=function(t,e){e=e||{};var r=typeof t;if("string"===r&&t.length>0)return function(t){if(!((t=String(t)).length>100)){var e=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(t);if(e){var n=parseFloat(e[1]);switch((e[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*c;case"days":case"day":case"d":return n*a;case"hours":case"hour":case"hrs":case"hr":case"h":return n*s;case"minutes":case"minute":case"mins":case"min":case"m":return n*i;case"seconds":case"second":case"secs":case"sec":case"s":return n*o;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}(t);if("number"===r&&!1===isNaN(t))return e.long?n(t):function(t){return t>=a?Math.round(t/a)+"d":t>=s?Math.round(t/s)+"h":t>=i?Math.round(t/i)+"m":t>=o?Math.round(t/o)+"s":t+"ms"}(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))}},function(t,e,n){function r(){}function o(t){var n=""+t.type;if(e.BINARY_EVENT!==t.type&&e.BINARY_ACK!==t.type||(n+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(n+=t.nsp+","),null!=t.id&&(n+=t.id),null!=t.data){var r=function(t){try{return JSON.stringify(t)}catch(t){return!1}}(t.data);if(!1===r)return d;n+=r}return p("encoded %j as %s",t,n),n}function i(){this.reconstructor=null}function s(t){var n=0,r={type:Number(t.charAt(0))};if(null==e.types[r.type])return c("unknown packet type "+r.type);if(e.BINARY_EVENT===r.type||e.BINARY_ACK===r.type){for(var o="";"-"!==t.charAt(++n)&&(o+=t.charAt(n),n!=t.length););if(o!=Number(o)||"-"!==t.charAt(n))throw new Error("Illegal attachments");r.attachments=Number(o)}if("/"===t.charAt(n+1))for(r.nsp="";++n;){if(","===(s=t.charAt(n)))break;if(r.nsp+=s,n===t.length)break}else r.nsp="/";var i=t.charAt(n+1);if(""!==i&&Number(i)==i){for(r.id="";++n;){var s;if(null==(s=t.charAt(n))||Number(s)!=s){--n;break}if(r.id+=t.charAt(n),n===t.length)break}r.id=Number(r.id)}if(t.charAt(++n)){var a=function(t){try{return JSON.parse(t)}catch(t){return!1}}(t.substr(n));if(!(!1!==a&&(r.type===e.ERROR||f(a))))return c("invalid payload");r.data=a}return p("decoded %s as %j",t,r),r}function a(t){this.reconPack=t,this.buffers=[]}function c(t){return{type:e.ERROR,data:"parser error: "+t}}var p=n(3)("socket.io-parser"),h=n(8),u=n(9),f=n(10),l=n(11);e.protocol=4,e.types=["CONNECT","DISCONNECT","EVENT","ACK","ERROR","BINARY_EVENT","BINARY_ACK"],e.CONNECT=0,e.DISCONNECT=1,e.EVENT=2,e.ACK=3,e.ERROR=4,e.BINARY_EVENT=5,e.BINARY_ACK=6,e.Encoder=r,e.Decoder=i;var d=e.ERROR+'"encode error"';r.prototype.encode=function(t,n){(p("encoding packet %j",t),e.BINARY_EVENT===t.type||e.BINARY_ACK===t.type)?function(t,e){u.removeBlobs(t,(function(t){var n=u.deconstructPacket(t),r=o(n.packet),i=n.buffers;i.unshift(r),e(i)}))}(t,n):n([o(t)])},h(i.prototype),i.prototype.add=function(t){var n;if("string"==typeof t)n=s(t),e.BINARY_EVENT===n.type||e.BINARY_ACK===n.type?(this.reconstructor=new a(n),0===this.reconstructor.reconPack.attachments&&this.emit("decoded",n)):this.emit("decoded",n);else{if(!l(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");(n=this.reconstructor.takeBinaryData(t))&&(this.reconstructor=null,this.emit("decoded",n))}},i.prototype.destroy=function(){this.reconstructor&&this.reconstructor.finishedReconstruction()},a.prototype.takeBinaryData=function(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){var e=u.reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null},a.prototype.finishedReconstruction=function(){this.reconPack=null,this.buffers=[]}},function(t,e,n){function r(t){if(t)return function(t){for(var e in r.prototype)t[e]=r.prototype[e];return t}(t)}t.exports=r,r.prototype.on=r.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},r.prototype.once=function(t,e){function n(){this.off(t,n),e.apply(this,arguments)}return n.fn=e,this.on(t,n),this},r.prototype.off=r.prototype.removeListener=r.prototype.removeAllListeners=r.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var n=this._callbacks["$"+t];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var r,o=0;o<n.length;o++)if((r=n[o])===e||r.fn===e){n.splice(o,1);break}return 0===n.length&&delete this._callbacks["$"+t],this},r.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),n=this._callbacks["$"+t],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(n){r=0;for(var o=(n=n.slice(0)).length;r<o;++r)n[r].apply(this,e)}return this},r.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},r.prototype.hasListeners=function(t){return!!this.listeners(t).length}},function(t,e,n){function r(t,e){if(!t)return t;if(s(t)){var n={_placeholder:!0,num:e.length};return e.push(t),n}if(i(t)){for(var o=new Array(t.length),a=0;a<t.length;a++)o[a]=r(t[a],e);return o}if("object"==typeof t&&!(t instanceof Date)){o={};for(var c in t)o[c]=r(t[c],e);return o}return t}function o(t,e){if(!t)return t;if(t&&t._placeholder)return e[t.num];if(i(t))for(var n=0;n<t.length;n++)t[n]=o(t[n],e);else if("object"==typeof t)for(var r in t)t[r]=o(t[r],e);return t}var i=n(10),s=n(11),a=Object.prototype.toString,c="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===a.call(Blob),p="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===a.call(File);e.deconstructPacket=function(t){var e=[],n=t.data,o=t;return o.data=r(n,e),o.attachments=e.length,{packet:o,buffers:e}},e.reconstructPacket=function(t,e){return t.data=o(t.data,e),t.attachments=void 0,t},e.removeBlobs=function(t,e){var n=0,r=t;(function t(o,a,h){if(!o)return o;if(c&&o instanceof Blob||p&&o instanceof File){n++;var u=new FileReader;u.onload=function(){h?h[a]=this.result:r=this.result,--n||e(r)},u.readAsArrayBuffer(o)}else if(i(o))for(var f=0;f<o.length;f++)t(o[f],f,o);else if("object"==typeof o&&!s(o))for(var l in o)t(o[l],l,o)})(r),n||e(r)}},function(t,e){var n={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},function(t,e){t.exports=function(t){return n&&Buffer.isBuffer(t)||r&&(t instanceof ArrayBuffer||o(t))};var n="function"==typeof Buffer&&"function"==typeof Buffer.isBuffer,r="function"==typeof ArrayBuffer,o=function(t){return"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer}},function(t,e,n){function r(t,e){if(!(this instanceof r))return new r(t,e);t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.nsps={},this.subs=[],this.opts=e,this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(e.randomizationFactor||.5),this.backoff=new f({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this.readyState="closed",this.uri=t,this.connecting=[],this.lastPing=null,this.encoding=!1,this.packetBuffer=[];var n=e.parser||a;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this.autoConnect=!1!==e.autoConnect,this.autoConnect&&this.open()}var o=n(13),i=n(37),s=n(8),a=n(7),c=n(39),p=n(40),h=n(3)("socket.io-client:manager"),u=n(36),f=n(41),l=Object.prototype.hasOwnProperty;t.exports=r,r.prototype.emitAll=function(){for(var t in this.emit.apply(this,arguments),this.nsps)l.call(this.nsps,t)&&this.nsps[t].emit.apply(this.nsps[t],arguments)},r.prototype.updateSocketIds=function(){for(var t in this.nsps)l.call(this.nsps,t)&&(this.nsps[t].id=this.generateId(t))},r.prototype.generateId=function(t){return("/"===t?"":t+"#")+this.engine.id},s(r.prototype),r.prototype.reconnection=function(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection},r.prototype.reconnectionAttempts=function(t){return arguments.length?(this._reconnectionAttempts=t,this):this._reconnectionAttempts},r.prototype.reconnectionDelay=function(t){return arguments.length?(this._reconnectionDelay=t,this.backoff&&this.backoff.setMin(t),this):this._reconnectionDelay},r.prototype.randomizationFactor=function(t){return arguments.length?(this._randomizationFactor=t,this.backoff&&this.backoff.setJitter(t),this):this._randomizationFactor},r.prototype.reconnectionDelayMax=function(t){return arguments.length?(this._reconnectionDelayMax=t,this.backoff&&this.backoff.setMax(t),this):this._reconnectionDelayMax},r.prototype.timeout=function(t){return arguments.length?(this._timeout=t,this):this._timeout},r.prototype.maybeReconnectOnOpen=function(){!this.reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()},r.prototype.open=r.prototype.connect=function(t,e){if(h("readyState %s",this.readyState),~this.readyState.indexOf("open"))return this;h("opening %s",this.uri),this.engine=o(this.uri,this.opts);var n=this.engine,r=this;this.readyState="opening",this.skipReconnect=!1;var i=c(n,"open",(function(){r.onopen(),t&&t()})),s=c(n,"error",(function(e){if(h("connect_error"),r.cleanup(),r.readyState="closed",r.emitAll("connect_error",e),t){var n=new Error("Connection error");n.data=e,t(n)}else r.maybeReconnectOnOpen()}));if(!1!==this._timeout){var a=this._timeout;h("connect attempt will timeout after %d",a),0===a&&i.destroy();var p=setTimeout((function(){h("connect attempt timed out after %d",a),i.destroy(),n.close(),n.emit("error","timeout"),r.emitAll("connect_timeout",a)}),a);this.subs.push({destroy:function(){clearTimeout(p)}})}return this.subs.push(i),this.subs.push(s),this},r.prototype.onopen=function(){h("open"),this.cleanup(),this.readyState="open",this.emit("open");var t=this.engine;this.subs.push(c(t,"data",p(this,"ondata"))),this.subs.push(c(t,"ping",p(this,"onping"))),this.subs.push(c(t,"pong",p(this,"onpong"))),this.subs.push(c(t,"error",p(this,"onerror"))),this.subs.push(c(t,"close",p(this,"onclose"))),this.subs.push(c(this.decoder,"decoded",p(this,"ondecoded")))},r.prototype.onping=function(){this.lastPing=new Date,this.emitAll("ping")},r.prototype.onpong=function(){this.emitAll("pong",new Date-this.lastPing)},r.prototype.ondata=function(t){this.decoder.add(t)},r.prototype.ondecoded=function(t){this.emit("packet",t)},r.prototype.onerror=function(t){h("error",t),this.emitAll("error",t)},r.prototype.socket=function(t,e){function n(){~u(o.connecting,r)||o.connecting.push(r)}var r=this.nsps[t];if(!r){r=new i(this,t,e),this.nsps[t]=r;var o=this;r.on("connecting",n),r.on("connect",(function(){r.id=o.generateId(t)})),this.autoConnect&&n()}return r},r.prototype.destroy=function(t){var e=u(this.connecting,t);~e&&this.connecting.splice(e,1),this.connecting.length||this.close()},r.prototype.packet=function(t){h("writing packet %j",t);var e=this;t.query&&0===t.type&&(t.nsp+="?"+t.query),e.encoding?e.packetBuffer.push(t):(e.encoding=!0,this.encoder.encode(t,(function(n){for(var r=0;r<n.length;r++)e.engine.write(n[r],t.options);e.encoding=!1,e.processPacketQueue()})))},r.prototype.processPacketQueue=function(){if(this.packetBuffer.length>0&&!this.encoding){var t=this.packetBuffer.shift();this.packet(t)}},r.prototype.cleanup=function(){h("cleanup");for(var t=this.subs.length,e=0;e<t;e++){this.subs.shift().destroy()}this.packetBuffer=[],this.encoding=!1,this.lastPing=null,this.decoder.destroy()},r.prototype.close=r.prototype.disconnect=function(){h("disconnect"),this.skipReconnect=!0,this.reconnecting=!1,"opening"===this.readyState&&this.cleanup(),this.backoff.reset(),this.readyState="closed",this.engine&&this.engine.close()},r.prototype.onclose=function(t){h("onclose"),this.cleanup(),this.backoff.reset(),this.readyState="closed",this.emit("close",t),this._reconnection&&!this.skipReconnect&&this.reconnect()},r.prototype.reconnect=function(){if(this.reconnecting||this.skipReconnect)return this;var t=this;if(this.backoff.attempts>=this._reconnectionAttempts)h("reconnect failed"),this.backoff.reset(),this.emitAll("reconnect_failed"),this.reconnecting=!1;else{var e=this.backoff.duration();h("will wait %dms before reconnect attempt",e),this.reconnecting=!0;var n=setTimeout((function(){t.skipReconnect||(h("attempting reconnect"),t.emitAll("reconnect_attempt",t.backoff.attempts),t.emitAll("reconnecting",t.backoff.attempts),t.skipReconnect||t.open((function(e){e?(h("reconnect attempt error"),t.reconnecting=!1,t.reconnect(),t.emitAll("reconnect_error",e.data)):(h("reconnect success"),t.onreconnect())})))}),e);this.subs.push({destroy:function(){clearTimeout(n)}})}},r.prototype.onreconnect=function(){var t=this.backoff.attempts;this.reconnecting=!1,this.backoff.reset(),this.updateSocketIds(),this.emitAll("reconnect",t)}},function(t,e,n){t.exports=n(14),t.exports.parser=n(22)},function(t,e,n){function r(t,e){return this instanceof r?(e=e||{},t&&"object"==typeof t&&(e=t,t=null),t?(t=p(t),e.hostname=t.host,e.secure="https"===t.protocol||"wss"===t.protocol,e.port=t.port,t.query&&(e.query=t.query)):e.host&&(e.hostname=p(e.host).host),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.agent=e.agent||!1,this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?443:80),this.query=e.query||{},"string"==typeof this.query&&(this.query=h.decode(this.query)),this.upgrade=!1!==e.upgrade,this.path=(e.path||"/engine.io").replace(/\/$/,"")+"/",this.forceJSONP=!!e.forceJSONP,this.jsonp=!1!==e.jsonp,this.forceBase64=!!e.forceBase64,this.enablesXDR=!!e.enablesXDR,this.withCredentials=!1!==e.withCredentials,this.timestampParam=e.timestampParam||"t",this.timestampRequests=e.timestampRequests,this.transports=e.transports||["polling","websocket"],this.transportOptions=e.transportOptions||{},this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.policyPort=e.policyPort||843,this.rememberUpgrade=e.rememberUpgrade||!1,this.binaryType=null,this.onlyBinaryUpgrades=e.onlyBinaryUpgrades,this.perMessageDeflate=!1!==e.perMessageDeflate&&(e.perMessageDeflate||{}),!0===this.perMessageDeflate&&(this.perMessageDeflate={}),this.perMessageDeflate&&null==this.perMessageDeflate.threshold&&(this.perMessageDeflate.threshold=1024),this.pfx=e.pfx||null,this.key=e.key||null,this.passphrase=e.passphrase||null,this.cert=e.cert||null,this.ca=e.ca||null,this.ciphers=e.ciphers||null,this.rejectUnauthorized=void 0===e.rejectUnauthorized||e.rejectUnauthorized,this.forceNode=!!e.forceNode,this.isReactNative="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),("undefined"==typeof self||this.isReactNative)&&(e.extraHeaders&&Object.keys(e.extraHeaders).length>0&&(this.extraHeaders=e.extraHeaders),e.localAddress&&(this.localAddress=e.localAddress)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingIntervalTimer=null,this.pingTimeoutTimer=null,void this.open()):new r(t,e)}var o=n(15),i=n(8),s=n(3)("engine.io-client:socket"),a=n(36),c=n(22),p=n(2),h=n(30);t.exports=r,r.priorWebsocketSuccess=!1,i(r.prototype),r.protocol=c.protocol,r.Socket=r,r.Transport=n(21),r.transports=n(15),r.parser=n(22),r.prototype.createTransport=function(t){s('creating transport "%s"',t);var e=function(t){var e={};for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}(this.query);e.EIO=c.protocol,e.transport=t;var n=this.transportOptions[t]||{};return this.id&&(e.sid=this.id),new o[t]({query:e,socket:this,agent:n.agent||this.agent,hostname:n.hostname||this.hostname,port:n.port||this.port,secure:n.secure||this.secure,path:n.path||this.path,forceJSONP:n.forceJSONP||this.forceJSONP,jsonp:n.jsonp||this.jsonp,forceBase64:n.forceBase64||this.forceBase64,enablesXDR:n.enablesXDR||this.enablesXDR,withCredentials:n.withCredentials||this.withCredentials,timestampRequests:n.timestampRequests||this.timestampRequests,timestampParam:n.timestampParam||this.timestampParam,policyPort:n.policyPort||this.policyPort,pfx:n.pfx||this.pfx,key:n.key||this.key,passphrase:n.passphrase||this.passphrase,cert:n.cert||this.cert,ca:n.ca||this.ca,ciphers:n.ciphers||this.ciphers,rejectUnauthorized:n.rejectUnauthorized||this.rejectUnauthorized,perMessageDeflate:n.perMessageDeflate||this.perMessageDeflate,extraHeaders:n.extraHeaders||this.extraHeaders,forceNode:n.forceNode||this.forceNode,localAddress:n.localAddress||this.localAddress,requestTimeout:n.requestTimeout||this.requestTimeout,protocols:n.protocols||void 0,isReactNative:this.isReactNative})},r.prototype.open=function(){var t;if(this.rememberUpgrade&&r.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length){var e=this;return void setTimeout((function(){e.emit("error","No transports available")}),0)}t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(t){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)},r.prototype.setTransport=function(t){s("setting transport %s",t.name);var e=this;this.transport&&(s("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=t,t.on("drain",(function(){e.onDrain()})).on("packet",(function(t){e.onPacket(t)})).on("error",(function(t){e.onError(t)})).on("close",(function(){e.onClose("transport close")}))},r.prototype.probe=function(t){function e(){if(f.onlyBinaryUpgrades){var e=!this.supportsBinary&&f.transport.supportsBinary;u=u||e}u||(s('probe transport "%s" opened',t),h.send([{type:"ping",data:"probe"}]),h.once("packet",(function(e){if(!u)if("pong"===e.type&&"probe"===e.data){if(s('probe transport "%s" pong',t),f.upgrading=!0,f.emit("upgrading",h),!h)return;r.priorWebsocketSuccess="websocket"===h.name,s('pausing current transport "%s"',f.transport.name),f.transport.pause((function(){u||"closed"!==f.readyState&&(s("changing transport and sending upgrade packet"),p(),f.setTransport(h),h.send([{type:"upgrade"}]),f.emit("upgrade",h),h=null,f.upgrading=!1,f.flush())}))}else{s('probe transport "%s" failed',t);var n=new Error("probe error");n.transport=h.name,f.emit("upgradeError",n)}})))}function n(){u||(u=!0,p(),h.close(),h=null)}function o(e){var r=new Error("probe error: "+e);r.transport=h.name,n(),s('probe transport "%s" failed because of error: %s',t,e),f.emit("upgradeError",r)}function i(){o("transport closed")}function a(){o("socket closed")}function c(t){h&&t.name!==h.name&&(s('"%s" works - aborting "%s"',t.name,h.name),n())}function p(){h.removeListener("open",e),h.removeListener("error",o),h.removeListener("close",i),f.removeListener("close",a),f.removeListener("upgrading",c)}s('probing transport "%s"',t);var h=this.createTransport(t,{probe:1}),u=!1,f=this;r.priorWebsocketSuccess=!1,h.once("open",e),h.once("error",o),h.once("close",i),this.once("close",a),this.once("upgrading",c),h.open()},r.prototype.onOpen=function(){if(s("socket open"),this.readyState="open",r.priorWebsocketSuccess="websocket"===this.transport.name,this.emit("open"),this.flush(),"open"===this.readyState&&this.upgrade&&this.transport.pause){s("starting upgrade probes");for(var t=0,e=this.upgrades.length;t<e;t++)this.probe(this.upgrades[t])}},r.prototype.onPacket=function(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(s('socket receive: type "%s", data "%s"',t.type,t.data),this.emit("packet",t),this.emit("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"pong":this.setPing(),this.emit("pong");break;case"error":var e=new Error("server error");e.code=t.data,this.onError(e);break;case"message":this.emit("data",t.data),this.emit("message",t.data)}else s('packet received with socket readyState "%s"',this.readyState)},r.prototype.onHandshake=function(t){this.emit("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this.upgrades=this.filterUpgrades(t.upgrades),this.pingInterval=t.pingInterval,this.pingTimeout=t.pingTimeout,this.onOpen(),"closed"!==this.readyState&&(this.setPing(),this.removeListener("heartbeat",this.onHeartbeat),this.on("heartbeat",this.onHeartbeat))},r.prototype.onHeartbeat=function(t){clearTimeout(this.pingTimeoutTimer);var e=this;e.pingTimeoutTimer=setTimeout((function(){"closed"!==e.readyState&&e.onClose("ping timeout")}),t||e.pingInterval+e.pingTimeout)},r.prototype.setPing=function(){var t=this;clearTimeout(t.pingIntervalTimer),t.pingIntervalTimer=setTimeout((function(){s("writing ping packet - expecting pong within %sms",t.pingTimeout),t.ping(),t.onHeartbeat(t.pingTimeout)}),t.pingInterval)},r.prototype.ping=function(){var t=this;this.sendPacket("ping",(function(){t.emit("ping")}))},r.prototype.onDrain=function(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emit("drain"):this.flush()},r.prototype.flush=function(){"closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length&&(s("flushing %d packets in socket",this.writeBuffer.length),this.transport.send(this.writeBuffer),this.prevBufferLen=this.writeBuffer.length,this.emit("flush"))},r.prototype.write=r.prototype.send=function(t,e,n){return this.sendPacket("message",t,e,n),this},r.prototype.sendPacket=function(t,e,n,r){if("function"==typeof e&&(r=e,e=void 0),"function"==typeof n&&(r=n,n=null),"closing"!==this.readyState&&"closed"!==this.readyState){(n=n||{}).compress=!1!==n.compress;var o={type:t,data:e,options:n};this.emit("packetCreate",o),this.writeBuffer.push(o),r&&this.once("flush",r),this.flush()}},r.prototype.close=function(){function t(){r.onClose("forced close"),s("socket closing - telling transport to close"),r.transport.close()}function e(){r.removeListener("upgrade",e),r.removeListener("upgradeError",e),t()}function n(){r.once("upgrade",e),r.once("upgradeError",e)}if("opening"===this.readyState||"open"===this.readyState){this.readyState="closing";var r=this;this.writeBuffer.length?this.once("drain",(function(){this.upgrading?n():t()})):this.upgrading?n():t()}return this},r.prototype.onError=function(t){s("socket error %j",t),r.priorWebsocketSuccess=!1,this.emit("error",t),this.onClose("transport error",t)},r.prototype.onClose=function(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){s('socket close with reason: "%s"',t);clearTimeout(this.pingIntervalTimer),clearTimeout(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),this.readyState="closed",this.id=null,this.emit("close",t,e),this.writeBuffer=[],this.prevBufferLen=0}},r.prototype.filterUpgrades=function(t){for(var e=[],n=0,r=t.length;n<r;n++)~a(this.transports,t[n])&&e.push(t[n]);return e}},function(t,e,n){var r=n(16),o=n(19),i=n(33),s=n(34);e.polling=function(t){var e=!1,n=!1,s=!1!==t.jsonp;if("undefined"!=typeof location){var a="https:"===location.protocol,c=location.port;c||(c=a?443:80),e=t.hostname!==location.hostname||c!==t.port,n=t.secure!==a}if(t.xdomain=e,t.xscheme=n,"open"in new r(t)&&!t.forceJSONP)return new o(t);if(!s)throw new Error("JSONP disabled");return new i(t)},e.websocket=s},function(t,e,n){var r=n(17),o=n(18);t.exports=function(t){var e=t.xdomain,n=t.xscheme,i=t.enablesXDR;try{if("undefined"!=typeof XMLHttpRequest&&(!e||r))return new XMLHttpRequest}catch(t){}try{if("undefined"!=typeof XDomainRequest&&!n&&i)return new XDomainRequest}catch(t){}if(!e)try{return new(o[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}},function(t,e){try{t.exports="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){t.exports=!1}},function(t,e){t.exports="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")()},function(t,e,n){function r(){}function o(t){if(c.call(this,t),this.requestTimeout=t.requestTimeout,this.extraHeaders=t.extraHeaders,"undefined"!=typeof location){var e="https:"===location.protocol,n=location.port;n||(n=e?443:80),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||n!==t.port,this.xs=t.secure!==e}}function i(t){this.method=t.method||"GET",this.uri=t.uri,this.xd=!!t.xd,this.xs=!!t.xs,this.async=!1!==t.async,this.data=void 0!==t.data?t.data:null,this.agent=t.agent,this.isBinary=t.isBinary,this.supportsBinary=t.supportsBinary,this.enablesXDR=t.enablesXDR,this.withCredentials=t.withCredentials,this.requestTimeout=t.requestTimeout,this.pfx=t.pfx,this.key=t.key,this.passphrase=t.passphrase,this.cert=t.cert,this.ca=t.ca,this.ciphers=t.ciphers,this.rejectUnauthorized=t.rejectUnauthorized,this.extraHeaders=t.extraHeaders,this.create()}function s(){for(var t in i.requests)i.requests.hasOwnProperty(t)&&i.requests[t].abort()}var a=n(16),c=n(20),p=n(8),h=n(31),u=n(3)("engine.io-client:polling-xhr"),f=n(18);if(t.exports=o,t.exports.Request=i,h(o,c),o.prototype.supportsBinary=!0,o.prototype.request=function(t){return(t=t||{}).uri=this.uri(),t.xd=this.xd,t.xs=this.xs,t.agent=this.agent||!1,t.supportsBinary=this.supportsBinary,t.enablesXDR=this.enablesXDR,t.withCredentials=this.withCredentials,t.pfx=this.pfx,t.key=this.key,t.passphrase=this.passphrase,t.cert=this.cert,t.ca=this.ca,t.ciphers=this.ciphers,t.rejectUnauthorized=this.rejectUnauthorized,t.requestTimeout=this.requestTimeout,t.extraHeaders=this.extraHeaders,new i(t)},o.prototype.doWrite=function(t,e){var n="string"!=typeof t&&void 0!==t,r=this.request({method:"POST",data:t,isBinary:n}),o=this;r.on("success",e),r.on("error",(function(t){o.onError("xhr post error",t)})),this.sendXhr=r},o.prototype.doPoll=function(){u("xhr poll");var t=this.request(),e=this;t.on("data",(function(t){e.onData(t)})),t.on("error",(function(t){e.onError("xhr poll error",t)})),this.pollXhr=t},p(i.prototype),i.prototype.create=function(){var t={agent:this.agent,xdomain:this.xd,xscheme:this.xs,enablesXDR:this.enablesXDR};t.pfx=this.pfx,t.key=this.key,t.passphrase=this.passphrase,t.cert=this.cert,t.ca=this.ca,t.ciphers=this.ciphers,t.rejectUnauthorized=this.rejectUnauthorized;var e=this.xhr=new a(t),n=this;try{u("xhr open %s: %s",this.method,this.uri),e.open(this.method,this.uri,this.async);try{if(this.extraHeaders)for(var r in e.setDisableHeaderCheck&&e.setDisableHeaderCheck(!0),this.extraHeaders)this.extraHeaders.hasOwnProperty(r)&&e.setRequestHeader(r,this.extraHeaders[r])}catch(t){}if("POST"===this.method)try{this.isBinary?e.setRequestHeader("Content-type","application/octet-stream"):e.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{e.setRequestHeader("Accept","*/*")}catch(t){}"withCredentials"in e&&(e.withCredentials=this.withCredentials),this.requestTimeout&&(e.timeout=this.requestTimeout),this.hasXDR()?(e.onload=function(){n.onLoad()},e.onerror=function(){n.onError(e.responseText)}):e.onreadystatechange=function(){if(2===e.readyState)try{var t=e.getResponseHeader("Content-Type");(n.supportsBinary&&"application/octet-stream"===t||"application/octet-stream; charset=UTF-8"===t)&&(e.responseType="arraybuffer")}catch(t){}4===e.readyState&&(200===e.status||1223===e.status?n.onLoad():setTimeout((function(){n.onError("number"==typeof e.status?e.status:0)}),0))},u("xhr data %s",this.data),e.send(this.data)}catch(t){return void setTimeout((function(){n.onError(t)}),0)}"undefined"!=typeof document&&(this.index=i.requestsCount++,i.requests[this.index]=this)},i.prototype.onSuccess=function(){this.emit("success"),this.cleanup()},i.prototype.onData=function(t){this.emit("data",t),this.onSuccess()},i.prototype.onError=function(t){this.emit("error",t),this.cleanup(!0)},i.prototype.cleanup=function(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.hasXDR()?this.xhr.onload=this.xhr.onerror=r:this.xhr.onreadystatechange=r,t)try{this.xhr.abort()}catch(t){}"undefined"!=typeof document&&delete i.requests[this.index],this.xhr=null}},i.prototype.onLoad=function(){var t;try{var e;try{e=this.xhr.getResponseHeader("Content-Type")}catch(t){}t=("application/octet-stream"===e||"application/octet-stream; charset=UTF-8"===e)&&this.xhr.response||this.xhr.responseText}catch(t){this.onError(t)}null!=t&&this.onData(t)},i.prototype.hasXDR=function(){return"undefined"!=typeof XDomainRequest&&!this.xs&&this.enablesXDR},i.prototype.abort=function(){this.cleanup()},i.requestsCount=0,i.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",s);else if("function"==typeof addEventListener){addEventListener("onpagehide"in f?"pagehide":"unload",s,!1)}},function(t,e,n){function r(t){var e=t&&t.forceBase64;h&&!e||(this.supportsBinary=!1),o.call(this,t)}var o=n(21),i=n(30),s=n(22),a=n(31),c=n(32),p=n(3)("engine.io-client:polling");t.exports=r;var h=null!=new(n(16))({xdomain:!1}).responseType;a(r,o),r.prototype.name="polling",r.prototype.doOpen=function(){this.poll()},r.prototype.pause=function(t){function e(){p("paused"),n.readyState="paused",t()}var n=this;if(this.readyState="pausing",this.polling||!this.writable){var r=0;this.polling&&(p("we are currently polling - waiting to pause"),r++,this.once("pollComplete",(function(){p("pre-pause polling complete"),--r||e()}))),this.writable||(p("we are currently writing - waiting to pause"),r++,this.once("drain",(function(){p("pre-pause writing complete"),--r||e()})))}else e()},r.prototype.poll=function(){p("polling"),this.polling=!0,this.doPoll(),this.emit("poll")},r.prototype.onData=function(t){var e=this;p("polling got data %s",t);s.decodePayload(t,this.socket.binaryType,(function(t,n,r){return"opening"===e.readyState&&"open"===t.type&&e.onOpen(),"close"===t.type?(e.onClose(),!1):void e.onPacket(t)})),"closed"!==this.readyState&&(this.polling=!1,this.emit("pollComplete"),"open"===this.readyState?this.poll():p('ignoring poll - transport state "%s"',this.readyState))},r.prototype.doClose=function(){function t(){p("writing close packet"),e.write([{type:"close"}])}var e=this;"open"===this.readyState?(p("transport open - closing"),t()):(p("transport not open - deferring close"),this.once("open",t))},r.prototype.write=function(t){var e=this;this.writable=!1;var n=function(){e.writable=!0,e.emit("drain")};s.encodePayload(t,this.supportsBinary,(function(t){e.doWrite(t,n)}))},r.prototype.uri=function(){var t=this.query||{},e=this.secure?"https":"http",n="";return!1!==this.timestampRequests&&(t[this.timestampParam]=c()),this.supportsBinary||t.sid||(t.b64=1),t=i.encode(t),this.port&&("https"===e&&443!==Number(this.port)||"http"===e&&80!==Number(this.port))&&(n=":"+this.port),t.length&&(t="?"+t),e+"://"+(-1!==this.hostname.indexOf(":")?"["+this.hostname+"]":this.hostname)+n+this.path+t}},function(t,e,n){function r(t){this.path=t.path,this.hostname=t.hostname,this.port=t.port,this.secure=t.secure,this.query=t.query,this.timestampParam=t.timestampParam,this.timestampRequests=t.timestampRequests,this.readyState="",this.agent=t.agent||!1,this.socket=t.socket,this.enablesXDR=t.enablesXDR,this.withCredentials=t.withCredentials,this.pfx=t.pfx,this.key=t.key,this.passphrase=t.passphrase,this.cert=t.cert,this.ca=t.ca,this.ciphers=t.ciphers,this.rejectUnauthorized=t.rejectUnauthorized,this.forceNode=t.forceNode,this.isReactNative=t.isReactNative,this.extraHeaders=t.extraHeaders,this.localAddress=t.localAddress}var o=n(22),i=n(8);t.exports=r,i(r.prototype),r.prototype.onError=function(t,e){var n=new Error(t);return n.type="TransportError",n.description=e,this.emit("error",n),this},r.prototype.open=function(){return"closed"!==this.readyState&&""!==this.readyState||(this.readyState="opening",this.doOpen()),this},r.prototype.close=function(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this},r.prototype.send=function(t){if("open"!==this.readyState)throw new Error("Transport not open");this.write(t)},r.prototype.onOpen=function(){this.readyState="open",this.writable=!0,this.emit("open")},r.prototype.onData=function(t){var e=o.decodePacket(t,this.socket.binaryType);this.onPacket(e)},r.prototype.onPacket=function(t){this.emit("packet",t)},r.prototype.onClose=function(){this.readyState="closed",this.emit("close")}},function(t,e,n){function r(t,n){return n("b"+e.packets[t.type]+t.data.data)}function o(t,n,r){if(!n)return e.encodeBase64Packet(t,r);var o=t.data,i=new Uint8Array(o),s=new Uint8Array(1+o.byteLength);s[0]=g[t.type];for(var a=0;a<i.length;a++)s[a+1]=i[a];return r(s.buffer)}function i(t,n,r){if(!n)return e.encodeBase64Packet(t,r);if(y)return function(t,n,r){if(!n)return e.encodeBase64Packet(t,r);var o=new FileReader;return o.onload=function(){e.encodePacket({type:t.type,data:o.result},n,!0,r)},o.readAsArrayBuffer(t.data)}(t,n,r);var o=new Uint8Array(1);return o[0]=g[t.type],r(new b([o.buffer,t.data]))}function s(t,e,n){for(var r=new Array(t.length),o=u(t.length,n),i=function(t,n,o){e(n,(function(e,n){r[t]=n,o(e,r)}))},s=0;s<t.length;s++)i(s,t[s],o)}var a,c=n(23),p=n(24),h=n(25),u=n(26),f=n(27);"undefined"!=typeof ArrayBuffer&&(a=n(28));var l="undefined"!=typeof navigator&&/Android/i.test(navigator.userAgent),d="undefined"!=typeof navigator&&/PhantomJS/i.test(navigator.userAgent),y=l||d;e.protocol=3;var g=e.packets={open:0,close:1,ping:2,pong:3,message:4,upgrade:5,noop:6},m=c(g),v={type:"error",data:"parser error"},b=n(29);e.encodePacket=function(t,e,n,s){"function"==typeof e&&(s=e,e=!1),"function"==typeof n&&(s=n,n=null);var a=void 0===t.data?void 0:t.data.buffer||t.data;if("undefined"!=typeof ArrayBuffer&&a instanceof ArrayBuffer)return o(t,e,s);if(void 0!==b&&a instanceof b)return i(t,e,s);if(a&&a.base64)return r(t,s);var c=g[t.type];return void 0!==t.data&&(c+=n?f.encode(String(t.data),{strict:!1}):String(t.data)),s(""+c)},e.encodeBase64Packet=function(t,n){var r,o="b"+e.packets[t.type];if(void 0!==b&&t.data instanceof b){var i=new FileReader;return i.onload=function(){var t=i.result.split(",")[1];n(o+t)},i.readAsDataURL(t.data)}try{r=String.fromCharCode.apply(null,new Uint8Array(t.data))}catch(e){for(var s=new Uint8Array(t.data),a=new Array(s.length),c=0;c<s.length;c++)a[c]=s[c];r=String.fromCharCode.apply(null,a)}return o+=btoa(r),n(o)},e.decodePacket=function(t,n,r){if(void 0===t)return v;if("string"==typeof t){if("b"===t.charAt(0))return e.decodeBase64Packet(t.substr(1),n);if(r&&!1===(t=function(t){try{t=f.decode(t,{strict:!1})}catch(t){return!1}return t}(t)))return v;var o=t.charAt(0);return Number(o)==o&&m[o]?t.length>1?{type:m[o],data:t.substring(1)}:{type:m[o]}:v}o=new Uint8Array(t)[0];var i=h(t,1);return b&&"blob"===n&&(i=new b([i])),{type:m[o],data:i}},e.decodeBase64Packet=function(t,e){var n=m[t.charAt(0)];if(!a)return{type:n,data:{base64:!0,data:t.substr(1)}};var r=a.decode(t.substr(1));return"blob"===e&&b&&(r=new b([r])),{type:n,data:r}},e.encodePayload=function(t,n,r){"function"==typeof n&&(r=n,n=null);var o=p(t);return n&&o?b&&!y?e.encodePayloadAsBlob(t,r):e.encodePayloadAsArrayBuffer(t,r):t.length?void s(t,(function(t,r){e.encodePacket(t,!!o&&n,!1,(function(t){r(null,function(t){return t.length+":"+t}(t))}))}),(function(t,e){return r(e.join(""))})):r("0:")},e.decodePayload=function(t,n,r){if("string"!=typeof t)return e.decodePayloadAsBinary(t,n,r);var o;if("function"==typeof n&&(r=n,n=null),""===t)return r(v,0,1);for(var i,s,a="",c=0,p=t.length;c<p;c++){var h=t.charAt(c);if(":"===h){if(""===a||a!=(i=Number(a)))return r(v,0,1);if(a!=(s=t.substr(c+1,i)).length)return r(v,0,1);if(s.length){if(o=e.decodePacket(s,n,!1),v.type===o.type&&v.data===o.data)return r(v,0,1);if(!1===r(o,c+i,p))return}c+=i,a=""}else a+=h}return""!==a?r(v,0,1):void 0},e.encodePayloadAsArrayBuffer=function(t,n){return t.length?void s(t,(function(t,n){e.encodePacket(t,!0,!0,(function(t){return n(null,t)}))}),(function(t,e){var r=e.reduce((function(t,e){var n;return t+(n="string"==typeof e?e.length:e.byteLength).toString().length+n+2}),0),o=new Uint8Array(r),i=0;return e.forEach((function(t){var e="string"==typeof t,n=t;if(e){for(var r=new Uint8Array(t.length),s=0;s<t.length;s++)r[s]=t.charCodeAt(s);n=r.buffer}o[i++]=e?0:1;var a=n.byteLength.toString();for(s=0;s<a.length;s++)o[i++]=parseInt(a[s]);o[i++]=255;for(r=new Uint8Array(n),s=0;s<r.length;s++)o[i++]=r[s]})),n(o.buffer)})):n(new ArrayBuffer(0))},e.encodePayloadAsBlob=function(t,n){s(t,(function(t,n){e.encodePacket(t,!0,!0,(function(t){var e=new Uint8Array(1);if(e[0]=1,"string"==typeof t){for(var r=new Uint8Array(t.length),o=0;o<t.length;o++)r[o]=t.charCodeAt(o);t=r.buffer,e[0]=0}var i=(t instanceof ArrayBuffer?t.byteLength:t.size).toString(),s=new Uint8Array(i.length+1);for(o=0;o<i.length;o++)s[o]=parseInt(i[o]);if(s[i.length]=255,b){var a=new b([e.buffer,s.buffer,t]);n(null,a)}}))}),(function(t,e){return n(new b(e))}))},e.decodePayloadAsBinary=function(t,n,r){"function"==typeof n&&(r=n,n=null);for(var o=t,i=[];o.byteLength>0;){for(var s=new Uint8Array(o),a=0===s[0],c="",p=1;255!==s[p];p++){if(c.length>310)return r(v,0,1);c+=s[p]}o=h(o,2+c.length),c=parseInt(c);var u=h(o,0,c);if(a)try{u=String.fromCharCode.apply(null,new Uint8Array(u))}catch(t){var f=new Uint8Array(u);u="";for(p=0;p<f.length;p++)u+=String.fromCharCode(f[p])}i.push(u),o=h(o,c)}var l=i.length;i.forEach((function(t,o){r(e.decodePacket(t,n,!0),o,l)}))}},function(t,e){t.exports=Object.keys||function(t){var e=[],n=Object.prototype.hasOwnProperty;for(var r in t)n.call(t,r)&&e.push(r);return e}},function(t,e,n){var r=n(10),o=Object.prototype.toString,i="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===o.call(Blob),s="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===o.call(File);t.exports=function t(e){if(!e||"object"!=typeof e)return!1;if(r(e)){for(var n=0,o=e.length;n<o;n++)if(t(e[n]))return!0;return!1}if("function"==typeof Buffer&&Buffer.isBuffer&&Buffer.isBuffer(e)||"function"==typeof ArrayBuffer&&e instanceof ArrayBuffer||i&&e instanceof Blob||s&&e instanceof File)return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return t(e.toJSON(),!0);for(var a in e)if(Object.prototype.hasOwnProperty.call(e,a)&&t(e[a]))return!0;return!1}},function(t,e){t.exports=function(t,e,n){var r=t.byteLength;if(e=e||0,n=n||r,t.slice)return t.slice(e,n);if(e<0&&(e+=r),n<0&&(n+=r),n>r&&(n=r),e>=r||e>=n||0===r)return new ArrayBuffer(0);for(var o=new Uint8Array(t),i=new Uint8Array(n-e),s=e,a=0;s<n;s++,a++)i[a]=o[s];return i.buffer}},function(t,e){function n(){}t.exports=function(t,e,r){function o(t,n){if(o.count<=0)throw new Error("after called too many times");--o.count,t?(i=!0,e(t),e=r):0!==o.count||i||e(null,n)}var i=!1;return r=r||n,o.count=t,0===t?e():o}},function(t,e){function n(t){for(var e,n,r=[],o=0,i=t.length;o<i;)(e=t.charCodeAt(o++))>=55296&&e<=56319&&o<i?56320==(64512&(n=t.charCodeAt(o++)))?r.push(((1023&e)<<10)+(1023&n)+65536):(r.push(e),o--):r.push(e);return r}function r(t,e){if(t>=55296&&t<=57343){if(e)throw Error("Lone surrogate U+"+t.toString(16).toUpperCase()+" is not a scalar value");return!1}return!0}function o(t,e){return u(t>>e&63|128)}function i(t,e){if(0==(4294967168&t))return u(t);var n="";return 0==(4294965248&t)?n=u(t>>6&31|192):0==(4294901760&t)?(r(t,e)||(t=65533),n=u(t>>12&15|224),n+=o(t,6)):0==(4292870144&t)&&(n=u(t>>18&7|240),n+=o(t,12),n+=o(t,6)),n+u(63&t|128)}function s(){if(h>=p)throw Error("Invalid byte index");var t=255&c[h];if(h++,128==(192&t))return 63&t;throw Error("Invalid continuation byte")}function a(t){var e,n;if(h>p)throw Error("Invalid byte index");if(h==p)return!1;if(e=255&c[h],h++,0==(128&e))return e;if(192==(224&e)){if((n=(31&e)<<6|s())>=128)return n;throw Error("Invalid continuation byte")}if(224==(240&e)){if((n=(15&e)<<12|s()<<6|s())>=2048)return r(n,t)?n:65533;throw Error("Invalid continuation byte")}if(240==(248&e)&&((n=(7&e)<<18|s()<<12|s()<<6|s())>=65536&&n<=1114111))return n;throw Error("Invalid UTF-8 detected")}/*! https://mths.be/utf8js v2.1.2 by @mathias */
+var c,p,h,u=String.fromCharCode;t.exports={version:"2.1.2",encode:function(t,e){for(var r=!1!==(e=e||{}).strict,o=n(t),s=o.length,a=-1,c="";++a<s;)c+=i(o[a],r);return c},decode:function(t,e){var r=!1!==(e=e||{}).strict;c=n(t),p=c.length,h=0;for(var o,i=[];!1!==(o=a(r));)i.push(o);return function(t){for(var e,n=t.length,r=-1,o="";++r<n;)(e=t[r])>65535&&(o+=u((e-=65536)>>>10&1023|55296),e=56320|1023&e),o+=u(e);return o}(i)}}},function(t,e){!function(t){"use strict";e.encode=function(e){var n,r=new Uint8Array(e),o=r.length,i="";for(n=0;n<o;n+=3)i+=t[r[n]>>2],i+=t[(3&r[n])<<4|r[n+1]>>4],i+=t[(15&r[n+1])<<2|r[n+2]>>6],i+=t[63&r[n+2]];return o%3==2?i=i.substring(0,i.length-1)+"=":o%3==1&&(i=i.substring(0,i.length-2)+"=="),i},e.decode=function(e){var n,r,o,i,s,a=.75*e.length,c=e.length,p=0;"="===e[e.length-1]&&(a--,"="===e[e.length-2]&&a--);var h=new ArrayBuffer(a),u=new Uint8Array(h);for(n=0;n<c;n+=4)r=t.indexOf(e[n]),o=t.indexOf(e[n+1]),i=t.indexOf(e[n+2]),s=t.indexOf(e[n+3]),u[p++]=r<<2|o>>4,u[p++]=(15&o)<<4|i>>2,u[p++]=(3&i)<<6|63&s;return h}}("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")},function(t,e){function n(t){return t.map((function(t){if(t.buffer instanceof ArrayBuffer){var e=t.buffer;if(t.byteLength!==e.byteLength){var n=new Uint8Array(t.byteLength);n.set(new Uint8Array(e,t.byteOffset,t.byteLength)),e=n.buffer}return e}return t}))}function r(t,e){e=e||{};var r=new i;return n(t).forEach((function(t){r.append(t)})),e.type?r.getBlob(e.type):r.getBlob()}function o(t,e){return new Blob(n(t),e||{})}var i=void 0!==i?i:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder&&MozBlobBuilder,s=function(){try{return 2===new Blob(["hi"]).size}catch(t){return!1}}(),a=s&&function(){try{return 2===new Blob([new Uint8Array([1,2])]).size}catch(t){return!1}}(),c=i&&i.prototype.append&&i.prototype.getBlob;"undefined"!=typeof Blob&&(r.prototype=Blob.prototype,o.prototype=Blob.prototype),t.exports=s?a?Blob:o:c?r:void 0},function(t,e){e.encode=function(t){var e="";for(var n in t)t.hasOwnProperty(n)&&(e.length&&(e+="&"),e+=encodeURIComponent(n)+"="+encodeURIComponent(t[n]));return e},e.decode=function(t){for(var e={},n=t.split("&"),r=0,o=n.length;r<o;r++){var i=n[r].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}},function(t,e){t.exports=function(t,e){var n=function(){};n.prototype=e.prototype,t.prototype=new n,t.prototype.constructor=t}},function(t,e){"use strict";function n(t){var e="";do{e=i[t%s]+e,t=Math.floor(t/s)}while(t>0);return e}function r(){var t=n(+new Date);return t!==o?(c=0,o=t):t+"."+n(c++)}for(var o,i="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),s=64,a={},c=0,p=0;p<s;p++)a[i[p]]=p;r.encode=n,r.decode=function(t){var e=0;for(p=0;p<t.length;p++)e=e*s+a[t.charAt(p)];return e},t.exports=r},function(t,e,n){function r(){}function o(t){i.call(this,t),this.query=this.query||{},c||(c=a.___eio=a.___eio||[]),this.index=c.length;var e=this;c.push((function(t){e.onData(t)})),this.query.j=this.index,"function"==typeof addEventListener&&addEventListener("beforeunload",(function(){e.script&&(e.script.onerror=r)}),!1)}var i=n(20),s=n(31),a=n(18);t.exports=o;var c,p=/\n/g,h=/\\n/g;s(o,i),o.prototype.supportsBinary=!1,o.prototype.doClose=function(){this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),this.form&&(this.form.parentNode.removeChild(this.form),this.form=null,this.iframe=null),i.prototype.doClose.call(this)},o.prototype.doPoll=function(){var t=this,e=document.createElement("script");this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),e.async=!0,e.src=this.uri(),e.onerror=function(e){t.onError("jsonp poll error",e)};var n=document.getElementsByTagName("script")[0];n?n.parentNode.insertBefore(e,n):(document.head||document.body).appendChild(e),this.script=e,"undefined"!=typeof navigator&&/gecko/i.test(navigator.userAgent)&&setTimeout((function(){var t=document.createElement("iframe");document.body.appendChild(t),document.body.removeChild(t)}),100)},o.prototype.doWrite=function(t,e){function n(){r(),e()}function r(){if(o.iframe)try{o.form.removeChild(o.iframe)}catch(t){o.onError("jsonp polling iframe removal error",t)}try{var t='<iframe src="javascript:0" name="'+o.iframeId+'">';i=document.createElement(t)}catch(t){(i=document.createElement("iframe")).name=o.iframeId,i.src="javascript:0"}i.id=o.iframeId,o.form.appendChild(i),o.iframe=i}var o=this;if(!this.form){var i,s=document.createElement("form"),a=document.createElement("textarea"),c=this.iframeId="eio_iframe_"+this.index;s.className="socketio",s.style.position="absolute",s.style.top="-1000px",s.style.left="-1000px",s.target=c,s.method="POST",s.setAttribute("accept-charset","utf-8"),a.name="d",s.appendChild(a),document.body.appendChild(s),this.form=s,this.area=a}this.form.action=this.uri(),r(),t=t.replace(h,"\\\n"),this.area.value=t.replace(p,"\\n");try{this.form.submit()}catch(t){}this.iframe.attachEvent?this.iframe.onreadystatechange=function(){"complete"===o.iframe.readyState&&n()}:this.iframe.onload=n}},function(t,e,n){function r(t){t&&t.forceBase64&&(this.supportsBinary=!1),this.perMessageDeflate=t.perMessageDeflate,this.usingBrowserWebSocket=o&&!t.forceNode,this.protocols=t.protocols,this.usingBrowserWebSocket||(f=i),s.call(this,t)}var o,i,s=n(21),a=n(22),c=n(30),p=n(31),h=n(32),u=n(3)("engine.io-client:websocket");if("undefined"!=typeof WebSocket?o=WebSocket:"undefined"!=typeof self&&(o=self.WebSocket||self.MozWebSocket),"undefined"==typeof window)try{i=n(35)}catch(t){}var f=o||i;t.exports=r,p(r,s),r.prototype.name="websocket",r.prototype.supportsBinary=!0,r.prototype.doOpen=function(){if(this.check()){var t=this.uri(),e=this.protocols,n={};this.isReactNative||(n.agent=this.agent,n.perMessageDeflate=this.perMessageDeflate,n.pfx=this.pfx,n.key=this.key,n.passphrase=this.passphrase,n.cert=this.cert,n.ca=this.ca,n.ciphers=this.ciphers,n.rejectUnauthorized=this.rejectUnauthorized),this.extraHeaders&&(n.headers=this.extraHeaders),this.localAddress&&(n.localAddress=this.localAddress);try{this.ws=this.usingBrowserWebSocket&&!this.isReactNative?e?new f(t,e):new f(t):new f(t,e,n)}catch(t){return this.emit("error",t)}void 0===this.ws.binaryType&&(this.supportsBinary=!1),this.ws.supports&&this.ws.supports.binary?(this.supportsBinary=!0,this.ws.binaryType="nodebuffer"):this.ws.binaryType="arraybuffer",this.addEventListeners()}},r.prototype.addEventListeners=function(){var t=this;this.ws.onopen=function(){t.onOpen()},this.ws.onclose=function(){t.onClose()},this.ws.onmessage=function(e){t.onData(e.data)},this.ws.onerror=function(e){t.onError("websocket error",e)}},r.prototype.write=function(t){var e=this;this.writable=!1;for(var n=t.length,r=0,o=n;r<o;r++)!function(t){a.encodePacket(t,e.supportsBinary,(function(r){if(!e.usingBrowserWebSocket){var o={};if(t.options&&(o.compress=t.options.compress),e.perMessageDeflate)("string"==typeof r?Buffer.byteLength(r):r.length)<e.perMessageDeflate.threshold&&(o.compress=!1)}try{e.usingBrowserWebSocket?e.ws.send(r):e.ws.send(r,o)}catch(t){u("websocket closed before onclose event")}--n||(e.emit("flush"),setTimeout((function(){e.writable=!0,e.emit("drain")}),0))}))}(t[r])},r.prototype.onClose=function(){s.prototype.onClose.call(this)},r.prototype.doClose=function(){void 0!==this.ws&&this.ws.close()},r.prototype.uri=function(){var t=this.query||{},e=this.secure?"wss":"ws",n="";return this.port&&("wss"===e&&443!==Number(this.port)||"ws"===e&&80!==Number(this.port))&&(n=":"+this.port),this.timestampRequests&&(t[this.timestampParam]=h()),this.supportsBinary||(t.b64=1),(t=c.encode(t)).length&&(t="?"+t),e+"://"+(-1!==this.hostname.indexOf(":")?"["+this.hostname+"]":this.hostname)+n+this.path+t},r.prototype.check=function(){return!(!f||"__initialize"in f&&this.name===r.prototype.name)}},function(t,e){},function(t,e){var n=[].indexOf;t.exports=function(t,e){if(n)return t.indexOf(e);for(var r=0;r<t.length;++r)if(t[r]===e)return r;return-1}},function(t,e,n){function r(t,e,n){this.io=t,this.nsp=e,this.json=this,this.ids=0,this.acks={},this.receiveBuffer=[],this.sendBuffer=[],this.connected=!1,this.disconnected=!0,this.flags={},n&&n.query&&(this.query=n.query),this.io.autoConnect&&this.open()}var o=n(7),i=n(8),s=n(38),a=n(39),c=n(40),p=n(3)("socket.io-client:socket"),h=n(30),u=n(24);t.exports=r;var f={connect:1,connect_error:1,connect_timeout:1,connecting:1,disconnect:1,error:1,reconnect:1,reconnect_attempt:1,reconnect_failed:1,reconnect_error:1,reconnecting:1,ping:1,pong:1},l=i.prototype.emit;i(r.prototype),r.prototype.subEvents=function(){if(!this.subs){var t=this.io;this.subs=[a(t,"open",c(this,"onopen")),a(t,"packet",c(this,"onpacket")),a(t,"close",c(this,"onclose"))]}},r.prototype.open=r.prototype.connect=function(){return this.connected||(this.subEvents(),this.io.reconnecting||this.io.open(),"open"===this.io.readyState&&this.onopen(),this.emit("connecting")),this},r.prototype.send=function(){var t=s(arguments);return t.unshift("message"),this.emit.apply(this,t),this},r.prototype.emit=function(t){if(f.hasOwnProperty(t))return l.apply(this,arguments),this;var e=s(arguments),n={type:(void 0!==this.flags.binary?this.flags.binary:u(e))?o.BINARY_EVENT:o.EVENT,data:e,options:{}};return n.options.compress=!this.flags||!1!==this.flags.compress,"function"==typeof e[e.length-1]&&(p("emitting packet with ack id %d",this.ids),this.acks[this.ids]=e.pop(),n.id=this.ids++),this.connected?this.packet(n):this.sendBuffer.push(n),this.flags={},this},r.prototype.packet=function(t){t.nsp=this.nsp,this.io.packet(t)},r.prototype.onopen=function(){if(p("transport is open - connecting"),"/"!==this.nsp)if(this.query){var t="object"==typeof this.query?h.encode(this.query):this.query;p("sending connect packet with query %s",t),this.packet({type:o.CONNECT,query:t})}else this.packet({type:o.CONNECT})},r.prototype.onclose=function(t){p("close (%s)",t),this.connected=!1,this.disconnected=!0,delete this.id,this.emit("disconnect",t)},r.prototype.onpacket=function(t){var e=t.nsp===this.nsp,n=t.type===o.ERROR&&"/"===t.nsp;if(e||n)switch(t.type){case o.CONNECT:this.onconnect();break;case o.EVENT:case o.BINARY_EVENT:this.onevent(t);break;case o.ACK:case o.BINARY_ACK:this.onack(t);break;case o.DISCONNECT:this.ondisconnect();break;case o.ERROR:this.emit("error",t.data)}},r.prototype.onevent=function(t){var e=t.data||[];p("emitting event %j",e),null!=t.id&&(p("attaching ack callback to event"),e.push(this.ack(t.id))),this.connected?l.apply(this,e):this.receiveBuffer.push(e)},r.prototype.ack=function(t){var e=this,n=!1;return function(){if(!n){n=!0;var r=s(arguments);p("sending ack %j",r),e.packet({type:u(r)?o.BINARY_ACK:o.ACK,id:t,data:r})}}},r.prototype.onack=function(t){var e=this.acks[t.id];"function"==typeof e?(p("calling ack %s with %j",t.id,t.data),e.apply(this,t.data),delete this.acks[t.id]):p("bad ack %s",t.id)},r.prototype.onconnect=function(){this.connected=!0,this.disconnected=!1,this.emit("connect"),this.emitBuffered()},r.prototype.emitBuffered=function(){var t;for(t=0;t<this.receiveBuffer.length;t++)l.apply(this,this.receiveBuffer[t]);for(this.receiveBuffer=[],t=0;t<this.sendBuffer.length;t++)this.packet(this.sendBuffer[t]);this.sendBuffer=[]},r.prototype.ondisconnect=function(){p("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")},r.prototype.destroy=function(){if(this.subs){for(var t=0;t<this.subs.length;t++)this.subs[t].destroy();this.subs=null}this.io.destroy(this)},r.prototype.close=r.prototype.disconnect=function(){return this.connected&&(p("performing disconnect (%s)",this.nsp),this.packet({type:o.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this},r.prototype.compress=function(t){return this.flags.compress=t,this},r.prototype.binary=function(t){return this.flags.binary=t,this}},function(t,e){t.exports=function(t,e){for(var n=[],r=(e=e||0)||0;r<t.length;r++)n[r-e]=t[r];return n}},function(t,e){t.exports=function(t,e,n){return t.on(e,n),{destroy:function(){t.removeListener(e,n)}}}},function(t,e){var n=[].slice;t.exports=function(t,e){if("string"==typeof e&&(e=t[e]),"function"!=typeof e)throw new Error("bind() requires a function");var r=n.call(arguments,2);return function(){return e.apply(t,r.concat(n.call(arguments)))}}},function(t,e){function n(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}t.exports=n,n.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),n=Math.floor(e*this.jitter*t);t=0==(1&Math.floor(10*e))?t-n:t+n}return 0|Math.min(t,this.max)},n.prototype.reset=function(){this.attempts=0},n.prototype.setMin=function(t){this.ms=t},n.prototype.setMax=function(t){this.max=t},n.prototype.setJitter=function(t){this.jitter=t}}])}));
\ No newline at end of file
index 7b39f7c..022241f 100644 (file)
  * (c) 2014-2021 Guillermo Rauch
  * Released under the MIT License.
  */
-(function webpackUniversalModuleDefinition(root, factory) {
-       if(typeof exports === 'object' && typeof module === 'object')
-               module.exports = factory();
-       else if(typeof define === 'function' && define.amd)
-               define([], factory);
-       else if(typeof exports === 'object')
-               exports["io"] = factory();
-       else
-               root["io"] = factory();
-})(this, function() {
-return /******/ (function(modules) { // webpackBootstrap
-/******/       // The module cache
-/******/       var installedModules = {};
-/******/
-/******/       // The require function
-/******/       function __webpack_require__(moduleId) {
-/******/
-/******/               // Check if module is in cache
-/******/               if(installedModules[moduleId])
-/******/                       return installedModules[moduleId].exports;
-/******/
-/******/               // Create a new module (and put it into the cache)
-/******/               var module = installedModules[moduleId] = {
-/******/                       exports: {},
-/******/                       id: moduleId,
-/******/                       loaded: false
-/******/               };
-/******/
-/******/               // Execute the module function
-/******/               modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
-/******/
-/******/               // Flag the module as loaded
-/******/               module.loaded = true;
-/******/
-/******/               // Return the exports of the module
-/******/               return module.exports;
-/******/       }
-/******/
-/******/
-/******/       // expose the modules object (__webpack_modules__)
-/******/       __webpack_require__.m = modules;
-/******/
-/******/       // expose the module cache
-/******/       __webpack_require__.c = installedModules;
-/******/
-/******/       // __webpack_public_path__
-/******/       __webpack_require__.p = "";
-/******/
-/******/       // Load entry module and return exports
-/******/       return __webpack_require__(0);
-/******/ })
-/************************************************************************/
-/******/ ([
-/* 0 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       'use strict';
-       
-       var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
-       
-       /**
-        * Module dependencies.
-        */
-       
-       var url = __webpack_require__(1);
-       var parser = __webpack_require__(4);
-       var Manager = __webpack_require__(9);
-       var debug = __webpack_require__(3)('socket.io-client');
-       
-       /**
-        * Module exports.
-        */
-       
-       module.exports = exports = lookup;
-       
-       /**
-        * Managers cache.
-        */
-       
-       var cache = exports.managers = {};
-       
-       /**
-        * Looks up an existing `Manager` for multiplexing.
-        * If the user summons:
-        *
-        *   `io('http://localhost/a');`
-        *   `io('http://localhost/b');`
-        *
-        * We reuse the existing instance based on same scheme/port/host,
-        * and we initialize sockets for each namespace.
-        *
-        * @api public
-        */
-       
-       function lookup(uri, opts) {
-         if ((typeof uri === 'undefined' ? 'undefined' : _typeof(uri)) === 'object') {
-           opts = uri;
-           uri = undefined;
-         }
-       
-         opts = opts || {};
-       
-         var parsed = url(uri);
-         var source = parsed.source;
-         var id = parsed.id;
-         var path = parsed.path;
-         var sameNamespace = cache[id] && path in cache[id].nsps;
-         var newConnection = opts.forceNew || opts['force new connection'] || false === opts.multiplex || sameNamespace;
-       
-         var io;
-       
-         if (newConnection) {
-       
-           io = Manager(source, opts);
-         } else {
-           if (!cache[id]) {
-       
-             cache[id] = Manager(source, opts);
-           }
-           io = cache[id];
-         }
-         if (parsed.query && !opts.query) {
-           opts.query = parsed.query;
-         }
-         return io.socket(parsed.path, opts);
-       }
-       
-       /**
-        * Protocol version.
-        *
-        * @api public
-        */
-       
-       exports.protocol = parser.protocol;
-       
-       /**
-        * `connect`.
-        *
-        * @param {String} uri
-        * @api public
-        */
-       
-       exports.connect = lookup;
-       
-       /**
-        * Expose constructors for standalone build.
-        *
-        * @api public
-        */
-       
-       exports.Manager = __webpack_require__(9);
-       exports.Socket = __webpack_require__(34);
-
-/***/ }),
-/* 1 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       'use strict';
-       
-       /**
-        * Module dependencies.
-        */
-       
-       var parseuri = __webpack_require__(2);
-       var debug = __webpack_require__(3)('socket.io-client:url');
-       
-       /**
-        * Module exports.
-        */
-       
-       module.exports = url;
-       
-       /**
-        * URL parser.
-        *
-        * @param {String} url
-        * @param {Object} An object meant to mimic window.location.
-        *                 Defaults to window.location.
-        * @api public
-        */
-       
-       function url(uri, loc) {
-         var obj = uri;
-       
-         // default to window.location
-         loc = loc || typeof location !== 'undefined' && location;
-         if (null == uri) uri = loc.protocol + '//' + loc.host;
-       
-         // relative path support
-         if ('string' === typeof uri) {
-           if ('/' === uri.charAt(0)) {
-             if ('/' === uri.charAt(1)) {
-               uri = loc.protocol + uri;
-             } else {
-               uri = loc.host + uri;
-             }
-           }
-       
-           if (!/^(https?|wss?):\/\//.test(uri)) {
-       
-             if ('undefined' !== typeof loc) {
-               uri = loc.protocol + '//' + uri;
-             } else {
-               uri = 'https://' + uri;
-             }
-           }
-       
-           // parse
-       
-           obj = parseuri(uri);
-         }
-       
-         // make sure we treat `localhost:80` and `localhost` equally
-         if (!obj.port) {
-           if (/^(http|ws)$/.test(obj.protocol)) {
-             obj.port = '80';
-           } else if (/^(http|ws)s$/.test(obj.protocol)) {
-             obj.port = '443';
-           }
-         }
-       
-         obj.path = obj.path || '/';
-       
-         var ipv6 = obj.host.indexOf(':') !== -1;
-         var host = ipv6 ? '[' + obj.host + ']' : obj.host;
-       
-         // define unique id
-         obj.id = obj.protocol + '://' + host + ':' + obj.port;
-         // define href
-         obj.href = obj.protocol + '://' + host + (loc && loc.port === obj.port ? '' : ':' + obj.port);
-       
-         return obj;
-       }
-
-/***/ }),
-/* 2 */
-/***/ (function(module, exports) {
-
-       /**
-        * Parses an URI
-        *
-        * @author Steven Levithan <stevenlevithan.com> (MIT license)
-        * @api private
-        */
-       
-       var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
-       
-       var parts = [
-           'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
-       ];
-       
-       module.exports = function parseuri(str) {
-           var src = str,
-               b = str.indexOf('['),
-               e = str.indexOf(']');
-       
-           if (b != -1 && e != -1) {
-               str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
-           }
-       
-           var m = re.exec(str || ''),
-               uri = {},
-               i = 14;
-       
-           while (i--) {
-               uri[parts[i]] = m[i] || '';
-           }
-       
-           if (b != -1 && e != -1) {
-               uri.source = src;
-               uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
-               uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
-               uri.ipv6uri = true;
-           }
-       
-           uri.pathNames = pathNames(uri, uri['path']);
-           uri.queryKey = queryKey(uri, uri['query']);
-       
-           return uri;
-       };
-       
-       function pathNames(obj, path) {
-           var regx = /\/{2,9}/g,
-               names = path.replace(regx, "/").split("/");
-       
-           if (path.substr(0, 1) == '/' || path.length === 0) {
-               names.splice(0, 1);
-           }
-           if (path.substr(path.length - 1, 1) == '/') {
-               names.splice(names.length - 1, 1);
-           }
-       
-           return names;
-       }
-       
-       function queryKey(uri, query) {
-           var data = {};
-       
-           query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) {
-               if ($1) {
-                   data[$1] = $2;
-               }
-           });
-       
-           return data;
-       }
-
-
-/***/ }),
-/* 3 */
-/***/ (function(module, exports) {
-
-       "use strict";
-       
-       module.exports = function () {
-         return function () {};
-       };
-
-/***/ }),
-/* 4 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       
-       /**
-        * Module dependencies.
-        */
-       
-       var debug = __webpack_require__(3)('socket.io-parser');
-       var Emitter = __webpack_require__(5);
-       var binary = __webpack_require__(6);
-       var isArray = __webpack_require__(7);
-       var isBuf = __webpack_require__(8);
-       
-       /**
-        * Protocol version.
-        *
-        * @api public
-        */
-       
-       exports.protocol = 4;
-       
-       /**
-        * Packet types.
-        *
-        * @api public
-        */
-       
-       exports.types = [
-         'CONNECT',
-         'DISCONNECT',
-         'EVENT',
-         'ACK',
-         'ERROR',
-         'BINARY_EVENT',
-         'BINARY_ACK'
-       ];
-       
-       /**
-        * Packet type `connect`.
-        *
-        * @api public
-        */
-       
-       exports.CONNECT = 0;
-       
-       /**
-        * Packet type `disconnect`.
-        *
-        * @api public
-        */
-       
-       exports.DISCONNECT = 1;
-       
-       /**
-        * Packet type `event`.
-        *
-        * @api public
-        */
-       
-       exports.EVENT = 2;
-       
-       /**
-        * Packet type `ack`.
-        *
-        * @api public
-        */
-       
-       exports.ACK = 3;
-       
-       /**
-        * Packet type `error`.
-        *
-        * @api public
-        */
-       
-       exports.ERROR = 4;
-       
-       /**
-        * Packet type 'binary event'
-        *
-        * @api public
-        */
-       
-       exports.BINARY_EVENT = 5;
-       
-       /**
-        * Packet type `binary ack`. For acks with binary arguments.
-        *
-        * @api public
-        */
-       
-       exports.BINARY_ACK = 6;
-       
-       /**
-        * Encoder constructor.
-        *
-        * @api public
-        */
-       
-       exports.Encoder = Encoder;
-       
-       /**
-        * Decoder constructor.
-        *
-        * @api public
-        */
-       
-       exports.Decoder = Decoder;
-       
-       /**
-        * A socket.io Encoder instance
-        *
-        * @api public
-        */
-       
-       function Encoder() {}
-       
-       var ERROR_PACKET = exports.ERROR + '"encode error"';
-       
-       /**
-        * Encode a packet as a single string if non-binary, or as a
-        * buffer sequence, depending on packet type.
-        *
-        * @param {Object} obj - packet object
-        * @param {Function} callback - function to handle encodings (likely engine.write)
-        * @return Calls callback with Array of encodings
-        * @api public
-        */
-       
-       Encoder.prototype.encode = function(obj, callback){
-       
-       
-         if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) {
-           encodeAsBinary(obj, callback);
-         } else {
-           var encoding = encodeAsString(obj);
-           callback([encoding]);
-         }
-       };
-       
-       /**
-        * Encode packet as string.
-        *
-        * @param {Object} packet
-        * @return {String} encoded
-        * @api private
-        */
-       
-       function encodeAsString(obj) {
-       
-         // first is type
-         var str = '' + obj.type;
-       
-         // attachments if we have them
-         if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) {
-           str += obj.attachments + '-';
-         }
-       
-         // if we have a namespace other than `/`
-         // we append it followed by a comma `,`
-         if (obj.nsp && '/' !== obj.nsp) {
-           str += obj.nsp + ',';
-         }
-       
-         // immediately followed by the id
-         if (null != obj.id) {
-           str += obj.id;
-         }
-       
-         // json data
-         if (null != obj.data) {
-           var payload = tryStringify(obj.data);
-           if (payload !== false) {
-             str += payload;
-           } else {
-             return ERROR_PACKET;
-           }
-         }
-       
-       
-         return str;
-       }
-       
-       function tryStringify(str) {
-         try {
-           return JSON.stringify(str);
-         } catch(e){
-           return false;
-         }
-       }
-       
-       /**
-        * Encode packet as 'buffer sequence' by removing blobs, and
-        * deconstructing packet into object with placeholders and
-        * a list of buffers.
-        *
-        * @param {Object} packet
-        * @return {Buffer} encoded
-        * @api private
-        */
-       
-       function encodeAsBinary(obj, callback) {
-       
-         function writeEncoding(bloblessData) {
-           var deconstruction = binary.deconstructPacket(bloblessData);
-           var pack = encodeAsString(deconstruction.packet);
-           var buffers = deconstruction.buffers;
-       
-           buffers.unshift(pack); // add packet info to beginning of data list
-           callback(buffers); // write all the buffers
-         }
-       
-         binary.removeBlobs(obj, writeEncoding);
-       }
-       
-       /**
-        * A socket.io Decoder instance
-        *
-        * @return {Object} decoder
-        * @api public
-        */
-       
-       function Decoder() {
-         this.reconstructor = null;
-       }
-       
-       /**
-        * Mix in `Emitter` with Decoder.
-        */
-       
-       Emitter(Decoder.prototype);
-       
-       /**
-        * Decodes an encoded packet string into packet JSON.
-        *
-        * @param {String} obj - encoded packet
-        * @return {Object} packet
-        * @api public
-        */
-       
-       Decoder.prototype.add = function(obj) {
-         var packet;
-         if (typeof obj === 'string') {
-           packet = decodeString(obj);
-           if (exports.BINARY_EVENT === packet.type || exports.BINARY_ACK === packet.type) { // binary packet's json
-             this.reconstructor = new BinaryReconstructor(packet);
-       
-             // no attachments, labeled binary but no binary data to follow
-             if (this.reconstructor.reconPack.attachments === 0) {
-               this.emit('decoded', packet);
-             }
-           } else { // non-binary full packet
-             this.emit('decoded', packet);
-           }
-         } else if (isBuf(obj) || obj.base64) { // raw binary data
-           if (!this.reconstructor) {
-             throw new Error('got binary data when not reconstructing a packet');
-           } else {
-             packet = this.reconstructor.takeBinaryData(obj);
-             if (packet) { // received final buffer
-               this.reconstructor = null;
-               this.emit('decoded', packet);
-             }
-           }
-         } else {
-           throw new Error('Unknown type: ' + obj);
-         }
-       };
-       
-       /**
-        * Decode a packet String (JSON data)
-        *
-        * @param {String} str
-        * @return {Object} packet
-        * @api private
-        */
-       
-       function decodeString(str) {
-         var i = 0;
-         // look up type
-         var p = {
-           type: Number(str.charAt(0))
-         };
-       
-         if (null == exports.types[p.type]) {
-           return error('unknown packet type ' + p.type);
-         }
-       
-         // look up attachments if type binary
-         if (exports.BINARY_EVENT === p.type || exports.BINARY_ACK === p.type) {
-           var buf = '';
-           while (str.charAt(++i) !== '-') {
-             buf += str.charAt(i);
-             if (i == str.length) break;
-           }
-           if (buf != Number(buf) || str.charAt(i) !== '-') {
-             throw new Error('Illegal attachments');
-           }
-           p.attachments = Number(buf);
-         }
-       
-         // look up namespace (if any)
-         if ('/' === str.charAt(i + 1)) {
-           p.nsp = '';
-           while (++i) {
-             var c = str.charAt(i);
-             if (',' === c) break;
-             p.nsp += c;
-             if (i === str.length) break;
-           }
-         } else {
-           p.nsp = '/';
-         }
-       
-         // look up id
-         var next = str.charAt(i + 1);
-         if ('' !== next && Number(next) == next) {
-           p.id = '';
-           while (++i) {
-             var c = str.charAt(i);
-             if (null == c || Number(c) != c) {
-               --i;
-               break;
-             }
-             p.id += str.charAt(i);
-             if (i === str.length) break;
-           }
-           p.id = Number(p.id);
-         }
-       
-         // look up json data
-         if (str.charAt(++i)) {
-           var payload = tryParse(str.substr(i));
-           var isPayloadValid = payload !== false && (p.type === exports.ERROR || isArray(payload));
-           if (isPayloadValid) {
-             p.data = payload;
-           } else {
-             return error('invalid payload');
-           }
-         }
-       
-       
-         return p;
-       }
-       
-       function tryParse(str) {
-         try {
-           return JSON.parse(str);
-         } catch(e){
-           return false;
-         }
-       }
-       
-       /**
-        * Deallocates a parser's resources
-        *
-        * @api public
-        */
-       
-       Decoder.prototype.destroy = function() {
-         if (this.reconstructor) {
-           this.reconstructor.finishedReconstruction();
-         }
-       };
-       
-       /**
-        * A manager of a binary event's 'buffer sequence'. Should
-        * be constructed whenever a packet of type BINARY_EVENT is
-        * decoded.
-        *
-        * @param {Object} packet
-        * @return {BinaryReconstructor} initialized reconstructor
-        * @api private
-        */
-       
-       function BinaryReconstructor(packet) {
-         this.reconPack = packet;
-         this.buffers = [];
-       }
-       
-       /**
-        * Method to be called when binary data received from connection
-        * after a BINARY_EVENT packet.
-        *
-        * @param {Buffer | ArrayBuffer} binData - the raw binary data received
-        * @return {null | Object} returns null if more binary data is expected or
-        *   a reconstructed packet object if all buffers have been received.
-        * @api private
-        */
-       
-       BinaryReconstructor.prototype.takeBinaryData = function(binData) {
-         this.buffers.push(binData);
-         if (this.buffers.length === this.reconPack.attachments) { // done with buffer list
-           var packet = binary.reconstructPacket(this.reconPack, this.buffers);
-           this.finishedReconstruction();
-           return packet;
-         }
-         return null;
-       };
-       
-       /**
-        * Cleans up binary packet reconstruction variables.
-        *
-        * @api private
-        */
-       
-       BinaryReconstructor.prototype.finishedReconstruction = function() {
-         this.reconPack = null;
-         this.buffers = [];
-       };
-       
-       function error(msg) {
-         return {
-           type: exports.ERROR,
-           data: 'parser error: ' + msg
-         };
-       }
-
-
-/***/ }),
-/* 5 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       
-       /**
-        * Expose `Emitter`.
-        */
-       
-       if (true) {
-         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;
-       };
-
-
-/***/ }),
-/* 6 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       /*global Blob,File*/
-       
-       /**
-        * Module requirements
-        */
-       
-       var isArray = __webpack_require__(7);
-       var isBuf = __webpack_require__(8);
-       var toString = Object.prototype.toString;
-       var withNativeBlob = typeof Blob === 'function' || (typeof Blob !== 'undefined' && toString.call(Blob) === '[object BlobConstructor]');
-       var withNativeFile = typeof File === 'function' || (typeof File !== 'undefined' && toString.call(File) === '[object FileConstructor]');
-       
-       /**
-        * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
-        * Anything with blobs or files should be fed through removeBlobs before coming
-        * here.
-        *
-        * @param {Object} packet - socket.io event packet
-        * @return {Object} with deconstructed packet and list of buffers
-        * @api public
-        */
-       
-       exports.deconstructPacket = function(packet) {
-         var buffers = [];
-         var packetData = packet.data;
-         var pack = packet;
-         pack.data = _deconstructPacket(packetData, buffers);
-         pack.attachments = buffers.length; // number of binary 'attachments'
-         return {packet: pack, buffers: buffers};
-       };
-       
-       function _deconstructPacket(data, buffers) {
-         if (!data) return data;
-       
-         if (isBuf(data)) {
-           var placeholder = { _placeholder: true, num: buffers.length };
-           buffers.push(data);
-           return placeholder;
-         } else if (isArray(data)) {
-           var newData = new Array(data.length);
-           for (var i = 0; i < data.length; i++) {
-             newData[i] = _deconstructPacket(data[i], buffers);
-           }
-           return newData;
-         } else if (typeof data === 'object' && !(data instanceof Date)) {
-           var newData = {};
-           for (var key in data) {
-             newData[key] = _deconstructPacket(data[key], buffers);
-           }
-           return newData;
-         }
-         return data;
-       }
-       
-       /**
-        * Reconstructs a binary packet from its placeholder packet and buffers
-        *
-        * @param {Object} packet - event packet with placeholders
-        * @param {Array} buffers - binary buffers to put in placeholder positions
-        * @return {Object} reconstructed packet
-        * @api public
-        */
-       
-       exports.reconstructPacket = function(packet, buffers) {
-         packet.data = _reconstructPacket(packet.data, buffers);
-         packet.attachments = undefined; // no longer useful
-         return packet;
-       };
-       
-       function _reconstructPacket(data, buffers) {
-         if (!data) return data;
-       
-         if (data && data._placeholder) {
-           return buffers[data.num]; // appropriate buffer (should be natural order anyway)
-         } else if (isArray(data)) {
-           for (var i = 0; i < data.length; i++) {
-             data[i] = _reconstructPacket(data[i], buffers);
-           }
-         } else if (typeof data === 'object') {
-           for (var key in data) {
-             data[key] = _reconstructPacket(data[key], buffers);
-           }
-         }
-       
-         return data;
-       }
-       
-       /**
-        * Asynchronously removes Blobs or Files from data via
-        * FileReader's readAsArrayBuffer method. Used before encoding
-        * data as msgpack. Calls callback with the blobless data.
-        *
-        * @param {Object} data
-        * @param {Function} callback
-        * @api private
-        */
-       
-       exports.removeBlobs = function(data, callback) {
-         function _removeBlobs(obj, curKey, containingObject) {
-           if (!obj) return obj;
-       
-           // convert any blob
-           if ((withNativeBlob && obj instanceof Blob) ||
-               (withNativeFile && obj instanceof File)) {
-             pendingBlobs++;
-       
-             // async filereader
-             var fileReader = new FileReader();
-             fileReader.onload = function() { // this.result == arraybuffer
-               if (containingObject) {
-                 containingObject[curKey] = this.result;
-               }
-               else {
-                 bloblessData = this.result;
-               }
-       
-               // if nothing pending its callback time
-               if(! --pendingBlobs) {
-                 callback(bloblessData);
-               }
-             };
-       
-             fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
-           } else if (isArray(obj)) { // handle array
-             for (var i = 0; i < obj.length; i++) {
-               _removeBlobs(obj[i], i, obj);
-             }
-           } else if (typeof obj === 'object' && !isBuf(obj)) { // and object
-             for (var key in obj) {
-               _removeBlobs(obj[key], key, obj);
-             }
-           }
-         }
-       
-         var pendingBlobs = 0;
-         var bloblessData = data;
-         _removeBlobs(bloblessData);
-         if (!pendingBlobs) {
-           callback(bloblessData);
-         }
-       };
-
-
-/***/ }),
-/* 7 */
-/***/ (function(module, exports) {
-
-       var toString = {}.toString;
-       
-       module.exports = Array.isArray || function (arr) {
-         return toString.call(arr) == '[object Array]';
-       };
-
-
-/***/ }),
-/* 8 */
-/***/ (function(module, exports) {
-
-       
-       module.exports = isBuf;
-       
-       var withNativeBuffer = typeof Buffer === 'function' && typeof Buffer.isBuffer === 'function';
-       var withNativeArrayBuffer = typeof ArrayBuffer === 'function';
-       
-       var isView = function (obj) {
-         return typeof ArrayBuffer.isView === 'function' ? ArrayBuffer.isView(obj) : (obj.buffer instanceof ArrayBuffer);
-       };
-       
-       /**
-        * Returns true if obj is a buffer or an arraybuffer.
-        *
-        * @api private
-        */
-       
-       function isBuf(obj) {
-         return (withNativeBuffer && Buffer.isBuffer(obj)) ||
-                 (withNativeArrayBuffer && (obj instanceof ArrayBuffer || isView(obj)));
-       }
-
-
-/***/ }),
-/* 9 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       'use strict';
-       
-       var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
-       
-       /**
-        * Module dependencies.
-        */
-       
-       var eio = __webpack_require__(10);
-       var Socket = __webpack_require__(34);
-       var Emitter = __webpack_require__(5);
-       var parser = __webpack_require__(4);
-       var on = __webpack_require__(36);
-       var bind = __webpack_require__(37);
-       var debug = __webpack_require__(3)('socket.io-client:manager');
-       var indexOf = __webpack_require__(33);
-       var Backoff = __webpack_require__(38);
-       
-       /**
-        * IE6+ hasOwnProperty
-        */
-       
-       var has = Object.prototype.hasOwnProperty;
-       
-       /**
-        * Module exports
-        */
-       
-       module.exports = Manager;
-       
-       /**
-        * `Manager` constructor.
-        *
-        * @param {String} engine instance or engine uri/opts
-        * @param {Object} options
-        * @api public
-        */
-       
-       function Manager(uri, opts) {
-         if (!(this instanceof Manager)) return new Manager(uri, opts);
-         if (uri && 'object' === (typeof uri === 'undefined' ? 'undefined' : _typeof(uri))) {
-           opts = uri;
-           uri = undefined;
-         }
-         opts = opts || {};
-       
-         opts.path = opts.path || '/socket.io';
-         this.nsps = {};
-         this.subs = [];
-         this.opts = opts;
-         this.reconnection(opts.reconnection !== false);
-         this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
-         this.reconnectionDelay(opts.reconnectionDelay || 1000);
-         this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
-         this.randomizationFactor(opts.randomizationFactor || 0.5);
-         this.backoff = new Backoff({
-           min: this.reconnectionDelay(),
-           max: this.reconnectionDelayMax(),
-           jitter: this.randomizationFactor()
-         });
-         this.timeout(null == opts.timeout ? 20000 : opts.timeout);
-         this.readyState = 'closed';
-         this.uri = uri;
-         this.connecting = [];
-         this.lastPing = null;
-         this.encoding = false;
-         this.packetBuffer = [];
-         var _parser = opts.parser || parser;
-         this.encoder = new _parser.Encoder();
-         this.decoder = new _parser.Decoder();
-         this.autoConnect = opts.autoConnect !== false;
-         if (this.autoConnect) this.open();
-       }
-       
-       /**
-        * Propagate given event to sockets and emit on `this`
-        *
-        * @api private
-        */
-       
-       Manager.prototype.emitAll = function () {
-         this.emit.apply(this, arguments);
-         for (var nsp in this.nsps) {
-           if (has.call(this.nsps, nsp)) {
-             this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
-           }
-         }
-       };
-       
-       /**
-        * Update `socket.id` of all sockets
-        *
-        * @api private
-        */
-       
-       Manager.prototype.updateSocketIds = function () {
-         for (var nsp in this.nsps) {
-           if (has.call(this.nsps, nsp)) {
-             this.nsps[nsp].id = this.generateId(nsp);
-           }
-         }
-       };
-       
-       /**
-        * generate `socket.id` for the given `nsp`
-        *
-        * @param {String} nsp
-        * @return {String}
-        * @api private
-        */
-       
-       Manager.prototype.generateId = function (nsp) {
-         return (nsp === '/' ? '' : nsp + '#') + this.engine.id;
-       };
-       
-       /**
-        * Mix in `Emitter`.
-        */
-       
-       Emitter(Manager.prototype);
-       
-       /**
-        * Sets the `reconnection` config.
-        *
-        * @param {Boolean} true/false if it should automatically reconnect
-        * @return {Manager} self or value
-        * @api public
-        */
-       
-       Manager.prototype.reconnection = function (v) {
-         if (!arguments.length) return this._reconnection;
-         this._reconnection = !!v;
-         return this;
-       };
-       
-       /**
-        * Sets the reconnection attempts config.
-        *
-        * @param {Number} max reconnection attempts before giving up
-        * @return {Manager} self or value
-        * @api public
-        */
-       
-       Manager.prototype.reconnectionAttempts = function (v) {
-         if (!arguments.length) return this._reconnectionAttempts;
-         this._reconnectionAttempts = v;
-         return this;
-       };
-       
-       /**
-        * Sets the delay between reconnections.
-        *
-        * @param {Number} delay
-        * @return {Manager} self or value
-        * @api public
-        */
-       
-       Manager.prototype.reconnectionDelay = function (v) {
-         if (!arguments.length) return this._reconnectionDelay;
-         this._reconnectionDelay = v;
-         this.backoff && this.backoff.setMin(v);
-         return this;
-       };
-       
-       Manager.prototype.randomizationFactor = function (v) {
-         if (!arguments.length) return this._randomizationFactor;
-         this._randomizationFactor = v;
-         this.backoff && this.backoff.setJitter(v);
-         return this;
-       };
-       
-       /**
-        * Sets the maximum delay between reconnections.
-        *
-        * @param {Number} delay
-        * @return {Manager} self or value
-        * @api public
-        */
-       
-       Manager.prototype.reconnectionDelayMax = function (v) {
-         if (!arguments.length) return this._reconnectionDelayMax;
-         this._reconnectionDelayMax = v;
-         this.backoff && this.backoff.setMax(v);
-         return this;
-       };
-       
-       /**
-        * Sets the connection timeout. `false` to disable
-        *
-        * @return {Manager} self or value
-        * @api public
-        */
-       
-       Manager.prototype.timeout = function (v) {
-         if (!arguments.length) return this._timeout;
-         this._timeout = v;
-         return this;
-       };
-       
-       /**
-        * Starts trying to reconnect if reconnection is enabled and we have not
-        * started reconnecting yet
-        *
-        * @api private
-        */
-       
-       Manager.prototype.maybeReconnectOnOpen = function () {
-         // Only try to reconnect if it's the first time we're connecting
-         if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
-           // keeps reconnection from firing twice for the same reconnection loop
-           this.reconnect();
-         }
-       };
-       
-       /**
-        * Sets the current transport `socket`.
-        *
-        * @param {Function} optional, callback
-        * @return {Manager} self
-        * @api public
-        */
-       
-       Manager.prototype.open = Manager.prototype.connect = function (fn, opts) {
-       
-         if (~this.readyState.indexOf('open')) return this;
-       
-         this.engine = eio(this.uri, this.opts);
-         var socket = this.engine;
-         var self = this;
-         this.readyState = 'opening';
-         this.skipReconnect = false;
-       
-         // emit `open`
-         var openSub = on(socket, 'open', function () {
-           self.onopen();
-           fn && fn();
-         });
-       
-         // emit `connect_error`
-         var errorSub = on(socket, 'error', function (data) {
-       
-           self.cleanup();
-           self.readyState = 'closed';
-           self.emitAll('connect_error', data);
-           if (fn) {
-             var err = new Error('Connection error');
-             err.data = data;
-             fn(err);
-           } else {
-             // Only do this if there is no fn to handle the error
-             self.maybeReconnectOnOpen();
-           }
-         });
-       
-         // emit `connect_timeout`
-         if (false !== this._timeout) {
-           var timeout = this._timeout;
-       
-           if (timeout === 0) {
-             openSub.destroy(); // prevents a race condition with the 'open' event
-           }
-       
-           // set timer
-           var timer = setTimeout(function () {
-       
-             openSub.destroy();
-             socket.close();
-             socket.emit('error', 'timeout');
-             self.emitAll('connect_timeout', timeout);
-           }, timeout);
-       
-           this.subs.push({
-             destroy: function destroy() {
-               clearTimeout(timer);
-             }
-           });
-         }
-       
-         this.subs.push(openSub);
-         this.subs.push(errorSub);
-       
-         return this;
-       };
-       
-       /**
-        * Called upon transport open.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.onopen = function () {
-       
-         // clear old subs
-         this.cleanup();
-       
-         // mark as open
-         this.readyState = 'open';
-         this.emit('open');
-       
-         // add new subs
-         var socket = this.engine;
-         this.subs.push(on(socket, 'data', bind(this, 'ondata')));
-         this.subs.push(on(socket, 'ping', bind(this, 'onping')));
-         this.subs.push(on(socket, 'pong', bind(this, 'onpong')));
-         this.subs.push(on(socket, 'error', bind(this, 'onerror')));
-         this.subs.push(on(socket, 'close', bind(this, 'onclose')));
-         this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
-       };
-       
-       /**
-        * Called upon a ping.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.onping = function () {
-         this.lastPing = new Date();
-         this.emitAll('ping');
-       };
-       
-       /**
-        * Called upon a packet.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.onpong = function () {
-         this.emitAll('pong', new Date() - this.lastPing);
-       };
-       
-       /**
-        * Called with data.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.ondata = function (data) {
-         this.decoder.add(data);
-       };
-       
-       /**
-        * Called when parser fully decodes a packet.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.ondecoded = function (packet) {
-         this.emit('packet', packet);
-       };
-       
-       /**
-        * Called upon socket error.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.onerror = function (err) {
-       
-         this.emitAll('error', err);
-       };
-       
-       /**
-        * Creates a new socket for the given `nsp`.
-        *
-        * @return {Socket}
-        * @api public
-        */
-       
-       Manager.prototype.socket = function (nsp, opts) {
-         var socket = this.nsps[nsp];
-         if (!socket) {
-           socket = new Socket(this, nsp, opts);
-           this.nsps[nsp] = socket;
-           var self = this;
-           socket.on('connecting', onConnecting);
-           socket.on('connect', function () {
-             socket.id = self.generateId(nsp);
-           });
-       
-           if (this.autoConnect) {
-             // manually call here since connecting event is fired before listening
-             onConnecting();
-           }
-         }
-       
-         function onConnecting() {
-           if (!~indexOf(self.connecting, socket)) {
-             self.connecting.push(socket);
-           }
-         }
-       
-         return socket;
-       };
-       
-       /**
-        * Called upon a socket close.
-        *
-        * @param {Socket} socket
-        */
-       
-       Manager.prototype.destroy = function (socket) {
-         var index = indexOf(this.connecting, socket);
-         if (~index) this.connecting.splice(index, 1);
-         if (this.connecting.length) return;
-       
-         this.close();
-       };
-       
-       /**
-        * Writes a packet.
-        *
-        * @param {Object} packet
-        * @api private
-        */
-       
-       Manager.prototype.packet = function (packet) {
-       
-         var self = this;
-         if (packet.query && packet.type === 0) packet.nsp += '?' + packet.query;
-       
-         if (!self.encoding) {
-           // encode, then write to engine with result
-           self.encoding = true;
-           this.encoder.encode(packet, function (encodedPackets) {
-             for (var i = 0; i < encodedPackets.length; i++) {
-               self.engine.write(encodedPackets[i], packet.options);
-             }
-             self.encoding = false;
-             self.processPacketQueue();
-           });
-         } else {
-           // add packet to the queue
-           self.packetBuffer.push(packet);
-         }
-       };
-       
-       /**
-        * If packet buffer is non-empty, begins encoding the
-        * next packet in line.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.processPacketQueue = function () {
-         if (this.packetBuffer.length > 0 && !this.encoding) {
-           var pack = this.packetBuffer.shift();
-           this.packet(pack);
-         }
-       };
-       
-       /**
-        * Clean up transport subscriptions and packet buffer.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.cleanup = function () {
-       
-         var subsLength = this.subs.length;
-         for (var i = 0; i < subsLength; i++) {
-           var sub = this.subs.shift();
-           sub.destroy();
-         }
-       
-         this.packetBuffer = [];
-         this.encoding = false;
-         this.lastPing = null;
-       
-         this.decoder.destroy();
-       };
-       
-       /**
-        * Close the current socket.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.close = Manager.prototype.disconnect = function () {
-       
-         this.skipReconnect = true;
-         this.reconnecting = false;
-         if ('opening' === this.readyState) {
-           // `onclose` will not fire because
-           // an open event never happened
-           this.cleanup();
-         }
-         this.backoff.reset();
-         this.readyState = 'closed';
-         if (this.engine) this.engine.close();
-       };
-       
-       /**
-        * Called upon engine close.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.onclose = function (reason) {
-       
-         this.cleanup();
-         this.backoff.reset();
-         this.readyState = 'closed';
-         this.emit('close', reason);
-       
-         if (this._reconnection && !this.skipReconnect) {
-           this.reconnect();
-         }
-       };
-       
-       /**
-        * Attempt a reconnection.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.reconnect = function () {
-         if (this.reconnecting || this.skipReconnect) return this;
-       
-         var self = this;
-       
-         if (this.backoff.attempts >= this._reconnectionAttempts) {
-       
-           this.backoff.reset();
-           this.emitAll('reconnect_failed');
-           this.reconnecting = false;
-         } else {
-           var delay = this.backoff.duration();
-       
-           this.reconnecting = true;
-           var timer = setTimeout(function () {
-             if (self.skipReconnect) return;
-       
-             self.emitAll('reconnect_attempt', self.backoff.attempts);
-             self.emitAll('reconnecting', self.backoff.attempts);
-       
-             // check again for the case socket closed in above events
-             if (self.skipReconnect) return;
-       
-             self.open(function (err) {
-               if (err) {
-       
-                 self.reconnecting = false;
-                 self.reconnect();
-                 self.emitAll('reconnect_error', err.data);
-               } else {
-       
-                 self.onreconnect();
-               }
-             });
-           }, delay);
-       
-           this.subs.push({
-             destroy: function destroy() {
-               clearTimeout(timer);
-             }
-           });
-         }
-       };
-       
-       /**
-        * Called upon successful reconnect.
-        *
-        * @api private
-        */
-       
-       Manager.prototype.onreconnect = function () {
-         var attempt = this.backoff.attempts;
-         this.reconnecting = false;
-         this.backoff.reset();
-         this.updateSocketIds();
-         this.emitAll('reconnect', attempt);
-       };
-
-/***/ }),
-/* 10 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       
-       module.exports = __webpack_require__(11);
-       
-       /**
-        * Exports parser
-        *
-        * @api public
-        *
-        */
-       module.exports.parser = __webpack_require__(19);
-
-
-/***/ }),
-/* 11 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       /**
-        * Module dependencies.
-        */
-       
-       var transports = __webpack_require__(12);
-       var Emitter = __webpack_require__(5);
-       var debug = __webpack_require__(3)('engine.io-client:socket');
-       var index = __webpack_require__(33);
-       var parser = __webpack_require__(19);
-       var parseuri = __webpack_require__(2);
-       var parseqs = __webpack_require__(27);
-       
-       /**
-        * Module exports.
-        */
-       
-       module.exports = Socket;
-       
-       /**
-        * Socket constructor.
-        *
-        * @param {String|Object} uri or options
-        * @param {Object} options
-        * @api public
-        */
-       
-       function Socket (uri, opts) {
-         if (!(this instanceof Socket)) return new Socket(uri, opts);
-       
-         opts = opts || {};
-       
-         if (uri && 'object' === typeof uri) {
-           opts = uri;
-           uri = null;
-         }
-       
-         if (uri) {
-           uri = parseuri(uri);
-           opts.hostname = uri.host;
-           opts.secure = uri.protocol === 'https' || uri.protocol === 'wss';
-           opts.port = uri.port;
-           if (uri.query) opts.query = uri.query;
-         } else if (opts.host) {
-           opts.hostname = parseuri(opts.host).host;
-         }
-       
-         this.secure = null != opts.secure ? opts.secure
-           : (typeof location !== 'undefined' && 'https:' === location.protocol);
-       
-         if (opts.hostname && !opts.port) {
-           // if no port is specified manually, use the protocol default
-           opts.port = this.secure ? '443' : '80';
-         }
-       
-         this.agent = opts.agent || false;
-         this.hostname = opts.hostname ||
-           (typeof location !== 'undefined' ? location.hostname : 'localhost');
-         this.port = opts.port || (typeof location !== 'undefined' && location.port
-             ? location.port
-             : (this.secure ? 443 : 80));
-         this.query = opts.query || {};
-         if ('string' === typeof this.query) this.query = parseqs.decode(this.query);
-         this.upgrade = false !== opts.upgrade;
-         this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
-         this.forceJSONP = !!opts.forceJSONP;
-         this.jsonp = false !== opts.jsonp;
-         this.forceBase64 = !!opts.forceBase64;
-         this.enablesXDR = !!opts.enablesXDR;
-         this.withCredentials = false !== opts.withCredentials;
-         this.timestampParam = opts.timestampParam || 't';
-         this.timestampRequests = opts.timestampRequests;
-         this.transports = opts.transports || ['polling', 'websocket'];
-         this.transportOptions = opts.transportOptions || {};
-         this.readyState = '';
-         this.writeBuffer = [];
-         this.prevBufferLen = 0;
-         this.policyPort = opts.policyPort || 843;
-         this.rememberUpgrade = opts.rememberUpgrade || false;
-         this.binaryType = null;
-         this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
-         this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false;
-       
-         if (true === this.perMessageDeflate) this.perMessageDeflate = {};
-         if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) {
-           this.perMessageDeflate.threshold = 1024;
-         }
-       
-         // SSL options for Node.js client
-         this.pfx = opts.pfx || null;
-         this.key = opts.key || null;
-         this.passphrase = opts.passphrase || null;
-         this.cert = opts.cert || null;
-         this.ca = opts.ca || null;
-         this.ciphers = opts.ciphers || null;
-         this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? true : opts.rejectUnauthorized;
-         this.forceNode = !!opts.forceNode;
-       
-         // detect ReactNative environment
-         this.isReactNative = (typeof navigator !== 'undefined' && typeof navigator.product === 'string' && navigator.product.toLowerCase() === 'reactnative');
-       
-         // other options for Node.js or ReactNative client
-         if (typeof self === 'undefined' || this.isReactNative) {
-           if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) {
-             this.extraHeaders = opts.extraHeaders;
-           }
-       
-           if (opts.localAddress) {
-             this.localAddress = opts.localAddress;
-           }
-         }
-       
-         // set on handshake
-         this.id = null;
-         this.upgrades = null;
-         this.pingInterval = null;
-         this.pingTimeout = null;
-       
-         // set on heartbeat
-         this.pingIntervalTimer = null;
-         this.pingTimeoutTimer = null;
-       
-         this.open();
-       }
-       
-       Socket.priorWebsocketSuccess = false;
-       
-       /**
-        * Mix in `Emitter`.
-        */
-       
-       Emitter(Socket.prototype);
-       
-       /**
-        * Protocol version.
-        *
-        * @api public
-        */
-       
-       Socket.protocol = parser.protocol; // this is an int
-       
-       /**
-        * Expose deps for legacy compatibility
-        * and standalone browser access.
-        */
-       
-       Socket.Socket = Socket;
-       Socket.Transport = __webpack_require__(18);
-       Socket.transports = __webpack_require__(12);
-       Socket.parser = __webpack_require__(19);
-       
-       /**
-        * Creates transport of the given type.
-        *
-        * @param {String} transport name
-        * @return {Transport}
-        * @api private
-        */
-       
-       Socket.prototype.createTransport = function (name) {
-       
-         var query = clone(this.query);
-       
-         // append engine.io protocol identifier
-         query.EIO = parser.protocol;
-       
-         // transport name
-         query.transport = name;
-       
-         // per-transport options
-         var options = this.transportOptions[name] || {};
-       
-         // session id if we already have one
-         if (this.id) query.sid = this.id;
-       
-         var transport = new transports[name]({
-           query: query,
-           socket: this,
-           agent: options.agent || this.agent,
-           hostname: options.hostname || this.hostname,
-           port: options.port || this.port,
-           secure: options.secure || this.secure,
-           path: options.path || this.path,
-           forceJSONP: options.forceJSONP || this.forceJSONP,
-           jsonp: options.jsonp || this.jsonp,
-           forceBase64: options.forceBase64 || this.forceBase64,
-           enablesXDR: options.enablesXDR || this.enablesXDR,
-           withCredentials: options.withCredentials || this.withCredentials,
-           timestampRequests: options.timestampRequests || this.timestampRequests,
-           timestampParam: options.timestampParam || this.timestampParam,
-           policyPort: options.policyPort || this.policyPort,
-           pfx: options.pfx || this.pfx,
-           key: options.key || this.key,
-           passphrase: options.passphrase || this.passphrase,
-           cert: options.cert || this.cert,
-           ca: options.ca || this.ca,
-           ciphers: options.ciphers || this.ciphers,
-           rejectUnauthorized: options.rejectUnauthorized || this.rejectUnauthorized,
-           perMessageDeflate: options.perMessageDeflate || this.perMessageDeflate,
-           extraHeaders: options.extraHeaders || this.extraHeaders,
-           forceNode: options.forceNode || this.forceNode,
-           localAddress: options.localAddress || this.localAddress,
-           requestTimeout: options.requestTimeout || this.requestTimeout,
-           protocols: options.protocols || void (0),
-           isReactNative: this.isReactNative
-         });
-       
-         return transport;
-       };
-       
-       function clone (obj) {
-         var o = {};
-         for (var i in obj) {
-           if (obj.hasOwnProperty(i)) {
-             o[i] = obj[i];
-           }
-         }
-         return o;
-       }
-       
-       /**
-        * Initializes transport to use and starts probe.
-        *
-        * @api private
-        */
-       Socket.prototype.open = function () {
-         var transport;
-         if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') !== -1) {
-           transport = 'websocket';
-         } else if (0 === this.transports.length) {
-           // Emit error on next tick so it can be listened to
-           var self = this;
-           setTimeout(function () {
-             self.emit('error', 'No transports available');
-           }, 0);
-           return;
-         } else {
-           transport = this.transports[0];
-         }
-         this.readyState = 'opening';
-       
-         // Retry with the next transport if the transport is disabled (jsonp: false)
-         try {
-           transport = this.createTransport(transport);
-         } catch (e) {
-           this.transports.shift();
-           this.open();
-           return;
-         }
-       
-         transport.open();
-         this.setTransport(transport);
-       };
-       
-       /**
-        * Sets the current transport. Disables the existing one (if any).
-        *
-        * @api private
-        */
-       
-       Socket.prototype.setTransport = function (transport) {
-       
-         var self = this;
-       
-         if (this.transport) {
-       
-           this.transport.removeAllListeners();
-         }
-       
-         // set up transport
-         this.transport = transport;
-       
-         // set up transport listeners
-         transport
-         .on('drain', function () {
-           self.onDrain();
-         })
-         .on('packet', function (packet) {
-           self.onPacket(packet);
-         })
-         .on('error', function (e) {
-           self.onError(e);
-         })
-         .on('close', function () {
-           self.onClose('transport close');
-         });
-       };
-       
-       /**
-        * Probes a transport.
-        *
-        * @param {String} transport name
-        * @api private
-        */
-       
-       Socket.prototype.probe = function (name) {
-       
-         var transport = this.createTransport(name, { probe: 1 });
-         var failed = false;
-         var self = this;
-       
-         Socket.priorWebsocketSuccess = false;
-       
-         function onTransportOpen () {
-           if (self.onlyBinaryUpgrades) {
-             var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
-             failed = failed || upgradeLosesBinary;
-           }
-           if (failed) return;
-       
-       
-           transport.send([{ type: 'ping', data: 'probe' }]);
-           transport.once('packet', function (msg) {
-             if (failed) return;
-             if ('pong' === msg.type && 'probe' === msg.data) {
-       
-               self.upgrading = true;
-               self.emit('upgrading', transport);
-               if (!transport) return;
-               Socket.priorWebsocketSuccess = 'websocket' === transport.name;
-       
-       
-               self.transport.pause(function () {
-                 if (failed) return;
-                 if ('closed' === self.readyState) return;
-       
-       
-                 cleanup();
-       
-                 self.setTransport(transport);
-                 transport.send([{ type: 'upgrade' }]);
-                 self.emit('upgrade', transport);
-                 transport = null;
-                 self.upgrading = false;
-                 self.flush();
-               });
-             } else {
-       
-               var err = new Error('probe error');
-               err.transport = transport.name;
-               self.emit('upgradeError', err);
-             }
-           });
-         }
-       
-         function freezeTransport () {
-           if (failed) return;
-       
-           // Any callback called by transport should be ignored since now
-           failed = true;
-       
-           cleanup();
-       
-           transport.close();
-           transport = null;
-         }
-       
-         // Handle any error that happens while probing
-         function onerror (err) {
-           var error = new Error('probe error: ' + err);
-           error.transport = transport.name;
-       
-           freezeTransport();
-       
-       
-       
-           self.emit('upgradeError', error);
-         }
-       
-         function onTransportClose () {
-           onerror('transport closed');
-         }
-       
-         // When the socket is closed while we're probing
-         function onclose () {
-           onerror('socket closed');
-         }
-       
-         // When the socket is upgraded while we're probing
-         function onupgrade (to) {
-           if (transport && to.name !== transport.name) {
-       
-             freezeTransport();
-           }
-         }
-       
-         // Remove all listeners on the transport and on self
-         function cleanup () {
-           transport.removeListener('open', onTransportOpen);
-           transport.removeListener('error', onerror);
-           transport.removeListener('close', onTransportClose);
-           self.removeListener('close', onclose);
-           self.removeListener('upgrading', onupgrade);
-         }
-       
-         transport.once('open', onTransportOpen);
-         transport.once('error', onerror);
-         transport.once('close', onTransportClose);
-       
-         this.once('close', onclose);
-         this.once('upgrading', onupgrade);
-       
-         transport.open();
-       };
-       
-       /**
-        * Called when connection is deemed open.
-        *
-        * @api public
-        */
-       
-       Socket.prototype.onOpen = function () {
-       
-         this.readyState = 'open';
-         Socket.priorWebsocketSuccess = 'websocket' === this.transport.name;
-         this.emit('open');
-         this.flush();
-       
-         // we check for `readyState` in case an `open`
-         // listener already closed the socket
-         if ('open' === this.readyState && this.upgrade && this.transport.pause) {
-       
-           for (var i = 0, l = this.upgrades.length; i < l; i++) {
-             this.probe(this.upgrades[i]);
-           }
-         }
-       };
-       
-       /**
-        * Handles a packet.
-        *
-        * @api private
-        */
-       
-       Socket.prototype.onPacket = function (packet) {
-         if ('opening' === this.readyState || 'open' === this.readyState ||
-             'closing' === this.readyState) {
-       
-       
-           this.emit('packet', packet);
-       
-           // Socket is live - any packet counts
-           this.emit('heartbeat');
-       
-           switch (packet.type) {
-             case 'open':
-               this.onHandshake(JSON.parse(packet.data));
-               break;
-       
-             case 'pong':
-               this.setPing();
-               this.emit('pong');
-               break;
-       
-             case 'error':
-               var err = new Error('server error');
-               err.code = packet.data;
-               this.onError(err);
-               break;
-       
-             case 'message':
-               this.emit('data', packet.data);
-               this.emit('message', packet.data);
-               break;
-           }
-         } else {
-       
-         }
-       };
-       
-       /**
-        * Called upon handshake completion.
-        *
-        * @param {Object} handshake obj
-        * @api private
-        */
-       
-       Socket.prototype.onHandshake = function (data) {
-         this.emit('handshake', data);
-         this.id = data.sid;
-         this.transport.query.sid = data.sid;
-         this.upgrades = this.filterUpgrades(data.upgrades);
-         this.pingInterval = data.pingInterval;
-         this.pingTimeout = data.pingTimeout;
-         this.onOpen();
-         // In case open handler closes socket
-         if ('closed' === this.readyState) return;
-         this.setPing();
-       
-         // Prolong liveness of socket on heartbeat
-         this.removeListener('heartbeat', this.onHeartbeat);
-         this.on('heartbeat', this.onHeartbeat);
-       };
-       
-       /**
-        * Resets ping timeout.
-        *
-        * @api private
-        */
-       
-       Socket.prototype.onHeartbeat = function (timeout) {
-         clearTimeout(this.pingTimeoutTimer);
-         var self = this;
-         self.pingTimeoutTimer = setTimeout(function () {
-           if ('closed' === self.readyState) return;
-           self.onClose('ping timeout');
-         }, timeout || (self.pingInterval + self.pingTimeout));
-       };
-       
-       /**
-        * Pings server every `this.pingInterval` and expects response
-        * within `this.pingTimeout` or closes connection.
-        *
-        * @api private
-        */
-       
-       Socket.prototype.setPing = function () {
-         var self = this;
-         clearTimeout(self.pingIntervalTimer);
-         self.pingIntervalTimer = setTimeout(function () {
-       
-           self.ping();
-           self.onHeartbeat(self.pingTimeout);
-         }, self.pingInterval);
-       };
-       
-       /**
-       * Sends a ping packet.
-       *
-       * @api private
-       */
-       
-       Socket.prototype.ping = function () {
-         var self = this;
-         this.sendPacket('ping', function () {
-           self.emit('ping');
-         });
-       };
-       
-       /**
-        * Called on `drain` event
-        *
-        * @api private
-        */
-       
-       Socket.prototype.onDrain = function () {
-         this.writeBuffer.splice(0, this.prevBufferLen);
-       
-         // setting prevBufferLen = 0 is very important
-         // for example, when upgrading, upgrade packet is sent over,
-         // and a nonzero prevBufferLen could cause problems on `drain`
-         this.prevBufferLen = 0;
-       
-         if (0 === this.writeBuffer.length) {
-           this.emit('drain');
-         } else {
-           this.flush();
-         }
-       };
-       
-       /**
-        * Flush write buffers.
-        *
-        * @api private
-        */
-       
-       Socket.prototype.flush = function () {
-         if ('closed' !== this.readyState && this.transport.writable &&
-           !this.upgrading && this.writeBuffer.length) {
-       
-           this.transport.send(this.writeBuffer);
-           // keep track of current length of writeBuffer
-           // splice writeBuffer and callbackBuffer on `drain`
-           this.prevBufferLen = this.writeBuffer.length;
-           this.emit('flush');
-         }
-       };
-       
-       /**
-        * Sends a message.
-        *
-        * @param {String} message.
-        * @param {Function} callback function.
-        * @param {Object} options.
-        * @return {Socket} for chaining.
-        * @api public
-        */
-       
-       Socket.prototype.write =
-       Socket.prototype.send = function (msg, options, fn) {
-         this.sendPacket('message', msg, options, fn);
-         return this;
-       };
-       
-       /**
-        * Sends a packet.
-        *
-        * @param {String} packet type.
-        * @param {String} data.
-        * @param {Object} options.
-        * @param {Function} callback function.
-        * @api private
-        */
-       
-       Socket.prototype.sendPacket = function (type, data, options, fn) {
-         if ('function' === typeof data) {
-           fn = data;
-           data = undefined;
-         }
-       
-         if ('function' === typeof options) {
-           fn = options;
-           options = null;
-         }
-       
-         if ('closing' === this.readyState || 'closed' === this.readyState) {
-           return;
-         }
-       
-         options = options || {};
-         options.compress = false !== options.compress;
-       
-         var packet = {
-           type: type,
-           data: data,
-           options: options
-         };
-         this.emit('packetCreate', packet);
-         this.writeBuffer.push(packet);
-         if (fn) this.once('flush', fn);
-         this.flush();
-       };
-       
-       /**
-        * Closes the connection.
-        *
-        * @api private
-        */
-       
-       Socket.prototype.close = function () {
-         if ('opening' === this.readyState || 'open' === this.readyState) {
-           this.readyState = 'closing';
-       
-           var self = this;
-       
-           if (this.writeBuffer.length) {
-             this.once('drain', function () {
-               if (this.upgrading) {
-                 waitForUpgrade();
-               } else {
-                 close();
-               }
-             });
-           } else if (this.upgrading) {
-             waitForUpgrade();
-           } else {
-             close();
-           }
-         }
-       
-         function close () {
-           self.onClose('forced close');
-       
-           self.transport.close();
-         }
-       
-         function cleanupAndClose () {
-           self.removeListener('upgrade', cleanupAndClose);
-           self.removeListener('upgradeError', cleanupAndClose);
-           close();
-         }
-       
-         function waitForUpgrade () {
-           // wait for upgrade to finish since we can't send packets while pausing a transport
-           self.once('upgrade', cleanupAndClose);
-           self.once('upgradeError', cleanupAndClose);
-         }
-       
-         return this;
-       };
-       
-       /**
-        * Called upon transport error
-        *
-        * @api private
-        */
-       
-       Socket.prototype.onError = function (err) {
-       
-         Socket.priorWebsocketSuccess = false;
-         this.emit('error', err);
-         this.onClose('transport error', err);
-       };
-       
-       /**
-        * Called upon transport close.
-        *
-        * @api private
-        */
-       
-       Socket.prototype.onClose = function (reason, desc) {
-         if ('opening' === this.readyState || 'open' === this.readyState || 'closing' === this.readyState) {
-       
-           var self = this;
-       
-           // clear timers
-           clearTimeout(this.pingIntervalTimer);
-           clearTimeout(this.pingTimeoutTimer);
-       
-           // stop event from firing again for transport
-           this.transport.removeAllListeners('close');
-       
-           // ensure transport won't stay open
-           this.transport.close();
-       
-           // ignore further transport communication
-           this.transport.removeAllListeners();
-       
-           // set ready state
-           this.readyState = 'closed';
-       
-           // clear session id
-           this.id = null;
-       
-           // emit close event
-           this.emit('close', reason, desc);
-       
-           // clean buffers after, so users can still
-           // grab the buffers on `close` event
-           self.writeBuffer = [];
-           self.prevBufferLen = 0;
-         }
-       };
-       
-       /**
-        * Filters upgrades, returning only those matching client transports.
-        *
-        * @param {Array} server upgrades
-        * @api private
-        *
-        */
-       
-       Socket.prototype.filterUpgrades = function (upgrades) {
-         var filteredUpgrades = [];
-         for (var i = 0, j = upgrades.length; i < j; i++) {
-           if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
-         }
-         return filteredUpgrades;
-       };
-
-
-/***/ }),
-/* 12 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       /**
-        * Module dependencies
-        */
-       
-       var XMLHttpRequest = __webpack_require__(13);
-       var XHR = __webpack_require__(16);
-       var JSONP = __webpack_require__(30);
-       var websocket = __webpack_require__(31);
-       
-       /**
-        * Export transports.
-        */
-       
-       exports.polling = polling;
-       exports.websocket = websocket;
-       
-       /**
-        * Polling transport polymorphic constructor.
-        * Decides on xhr vs jsonp based on feature detection.
-        *
-        * @api private
-        */
-       
-       function polling (opts) {
-         var xhr;
-         var xd = false;
-         var xs = false;
-         var jsonp = false !== opts.jsonp;
-       
-         if (typeof location !== 'undefined') {
-           var isSSL = 'https:' === location.protocol;
-           var port = location.port;
-       
-           // some user agents have empty `location.port`
-           if (!port) {
-             port = isSSL ? 443 : 80;
-           }
-       
-           xd = opts.hostname !== location.hostname || port !== opts.port;
-           xs = opts.secure !== isSSL;
-         }
-       
-         opts.xdomain = xd;
-         opts.xscheme = xs;
-         xhr = new XMLHttpRequest(opts);
-       
-         if ('open' in xhr && !opts.forceJSONP) {
-           return new XHR(opts);
-         } else {
-           if (!jsonp) throw new Error('JSONP disabled');
-           return new JSONP(opts);
-         }
-       }
-
-
-/***/ }),
-/* 13 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       // browser shim for xmlhttprequest module
-       
-       var hasCORS = __webpack_require__(14);
-       var globalThis = __webpack_require__(15);
-       
-       module.exports = function (opts) {
-         var xdomain = opts.xdomain;
-       
-         // scheme must be same when usign XDomainRequest
-         // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
-         var xscheme = opts.xscheme;
-       
-         // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
-         // https://github.com/Automattic/engine.io-client/pull/217
-         var enablesXDR = opts.enablesXDR;
-       
-         // XMLHttpRequest can be disabled on IE
-         try {
-           if ('undefined' !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
-             return new XMLHttpRequest();
-           }
-         } catch (e) { }
-       
-         // Use XDomainRequest for IE8 if enablesXDR is true
-         // because loading bar keeps flashing when using jsonp-polling
-         // https://github.com/yujiosaka/socke.io-ie8-loading-example
-         try {
-           if ('undefined' !== typeof XDomainRequest && !xscheme && enablesXDR) {
-             return new XDomainRequest();
-           }
-         } catch (e) { }
-       
-         if (!xdomain) {
-           try {
-             return new globalThis[['Active'].concat('Object').join('X')]('Microsoft.XMLHTTP');
-           } catch (e) { }
-         }
-       };
-
-
-/***/ }),
-/* 14 */
-/***/ (function(module, exports) {
-
-       
-       /**
-        * Module exports.
-        *
-        * Logic borrowed from Modernizr:
-        *
-        *   - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
-        */
-       
-       try {
-         module.exports = typeof XMLHttpRequest !== 'undefined' &&
-           'withCredentials' in new XMLHttpRequest();
-       } catch (err) {
-         // if XMLHttp support is disabled in IE then it will throw
-         // when trying to create
-         module.exports = false;
-       }
-
-
-/***/ }),
-/* 15 */
-/***/ (function(module, exports) {
-
-       module.exports = (function () {
-         if (typeof self !== 'undefined') {
-           return self;
-         } else if (typeof window !== 'undefined') {
-           return window;
-         } else {
-           return Function('return this')(); // eslint-disable-line no-new-func
-         }
-       })();
-
-
-/***/ }),
-/* 16 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       /* global attachEvent */
-       
-       /**
-        * Module requirements.
-        */
-       
-       var XMLHttpRequest = __webpack_require__(13);
-       var Polling = __webpack_require__(17);
-       var Emitter = __webpack_require__(5);
-       var inherit = __webpack_require__(28);
-       var debug = __webpack_require__(3)('engine.io-client:polling-xhr');
-       var globalThis = __webpack_require__(15);
-       
-       /**
-        * Module exports.
-        */
-       
-       module.exports = XHR;
-       module.exports.Request = Request;
-       
-       /**
-        * Empty function
-        */
-       
-       function empty () {}
-       
-       /**
-        * XHR Polling constructor.
-        *
-        * @param {Object} opts
-        * @api public
-        */
-       
-       function XHR (opts) {
-         Polling.call(this, opts);
-         this.requestTimeout = opts.requestTimeout;
-         this.extraHeaders = opts.extraHeaders;
-       
-         if (typeof location !== 'undefined') {
-           var isSSL = 'https:' === location.protocol;
-           var port = location.port;
-       
-           // some user agents have empty `location.port`
-           if (!port) {
-             port = isSSL ? 443 : 80;
-           }
-       
-           this.xd = (typeof location !== 'undefined' && opts.hostname !== location.hostname) ||
-             port !== opts.port;
-           this.xs = opts.secure !== isSSL;
-         }
-       }
-       
-       /**
-        * Inherits from Polling.
-        */
-       
-       inherit(XHR, Polling);
-       
-       /**
-        * XHR supports binary
-        */
-       
-       XHR.prototype.supportsBinary = true;
-       
-       /**
-        * Creates a request.
-        *
-        * @param {String} method
-        * @api private
-        */
-       
-       XHR.prototype.request = function (opts) {
-         opts = opts || {};
-         opts.uri = this.uri();
-         opts.xd = this.xd;
-         opts.xs = this.xs;
-         opts.agent = this.agent || false;
-         opts.supportsBinary = this.supportsBinary;
-         opts.enablesXDR = this.enablesXDR;
-         opts.withCredentials = this.withCredentials;
-       
-         // SSL options for Node.js client
-         opts.pfx = this.pfx;
-         opts.key = this.key;
-         opts.passphrase = this.passphrase;
-         opts.cert = this.cert;
-         opts.ca = this.ca;
-         opts.ciphers = this.ciphers;
-         opts.rejectUnauthorized = this.rejectUnauthorized;
-         opts.requestTimeout = this.requestTimeout;
-       
-         // other options for Node.js client
-         opts.extraHeaders = this.extraHeaders;
-       
-         return new Request(opts);
-       };
-       
-       /**
-        * Sends data.
-        *
-        * @param {String} data to send.
-        * @param {Function} called upon flush.
-        * @api private
-        */
-       
-       XHR.prototype.doWrite = function (data, fn) {
-         var isBinary = typeof data !== 'string' && data !== undefined;
-         var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
-         var self = this;
-         req.on('success', fn);
-         req.on('error', function (err) {
-           self.onError('xhr post error', err);
-         });
-         this.sendXhr = req;
-       };
-       
-       /**
-        * Starts a poll cycle.
-        *
-        * @api private
-        */
-       
-       XHR.prototype.doPoll = function () {
-       
-         var req = this.request();
-         var self = this;
-         req.on('data', function (data) {
-           self.onData(data);
-         });
-         req.on('error', function (err) {
-           self.onError('xhr poll error', err);
-         });
-         this.pollXhr = req;
-       };
-       
-       /**
-        * Request constructor
-        *
-        * @param {Object} options
-        * @api public
-        */
-       
-       function Request (opts) {
-         this.method = opts.method || 'GET';
-         this.uri = opts.uri;
-         this.xd = !!opts.xd;
-         this.xs = !!opts.xs;
-         this.async = false !== opts.async;
-         this.data = undefined !== opts.data ? opts.data : null;
-         this.agent = opts.agent;
-         this.isBinary = opts.isBinary;
-         this.supportsBinary = opts.supportsBinary;
-         this.enablesXDR = opts.enablesXDR;
-         this.withCredentials = opts.withCredentials;
-         this.requestTimeout = opts.requestTimeout;
-       
-         // SSL options for Node.js client
-         this.pfx = opts.pfx;
-         this.key = opts.key;
-         this.passphrase = opts.passphrase;
-         this.cert = opts.cert;
-         this.ca = opts.ca;
-         this.ciphers = opts.ciphers;
-         this.rejectUnauthorized = opts.rejectUnauthorized;
-       
-         // other options for Node.js client
-         this.extraHeaders = opts.extraHeaders;
-       
-         this.create();
-       }
-       
-       /**
-        * Mix in `Emitter`.
-        */
-       
-       Emitter(Request.prototype);
-       
-       /**
-        * Creates the XHR object and sends the request.
-        *
-        * @api private
-        */
-       
-       Request.prototype.create = function () {
-         var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
-       
-         // SSL options for Node.js client
-         opts.pfx = this.pfx;
-         opts.key = this.key;
-         opts.passphrase = this.passphrase;
-         opts.cert = this.cert;
-         opts.ca = this.ca;
-         opts.ciphers = this.ciphers;
-         opts.rejectUnauthorized = this.rejectUnauthorized;
-       
-         var xhr = this.xhr = new XMLHttpRequest(opts);
-         var self = this;
-       
-         try {
-       
-           xhr.open(this.method, this.uri, this.async);
-           try {
-             if (this.extraHeaders) {
-               xhr.setDisableHeaderCheck && xhr.setDisableHeaderCheck(true);
-               for (var i in this.extraHeaders) {
-                 if (this.extraHeaders.hasOwnProperty(i)) {
-                   xhr.setRequestHeader(i, this.extraHeaders[i]);
-                 }
-               }
-             }
-           } catch (e) {}
-       
-           if ('POST' === this.method) {
-             try {
-               if (this.isBinary) {
-                 xhr.setRequestHeader('Content-type', 'application/octet-stream');
-               } else {
-                 xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
-               }
-             } catch (e) {}
-           }
-       
-           try {
-             xhr.setRequestHeader('Accept', '*/*');
-           } catch (e) {}
-       
-           // ie6 check
-           if ('withCredentials' in xhr) {
-             xhr.withCredentials = this.withCredentials;
-           }
-       
-           if (this.requestTimeout) {
-             xhr.timeout = this.requestTimeout;
-           }
-       
-           if (this.hasXDR()) {
-             xhr.onload = function () {
-               self.onLoad();
-             };
-             xhr.onerror = function () {
-               self.onError(xhr.responseText);
-             };
-           } else {
-             xhr.onreadystatechange = function () {
-               if (xhr.readyState === 2) {
-                 try {
-                   var contentType = xhr.getResponseHeader('Content-Type');
-                   if (self.supportsBinary && contentType === 'application/octet-stream' || contentType === 'application/octet-stream; charset=UTF-8') {
-                     xhr.responseType = 'arraybuffer';
-                   }
-                 } catch (e) {}
-               }
-               if (4 !== xhr.readyState) return;
-               if (200 === xhr.status || 1223 === xhr.status) {
-                 self.onLoad();
-               } else {
-                 // make sure the `error` event handler that's user-set
-                 // does not throw in the same tick and gets caught here
-                 setTimeout(function () {
-                   self.onError(typeof xhr.status === 'number' ? xhr.status : 0);
-                 }, 0);
-               }
-             };
-           }
-       
-       
-           xhr.send(this.data);
-         } catch (e) {
-           // Need to defer since .create() is called directly fhrom the constructor
-           // and thus the 'error' event can only be only bound *after* this exception
-           // occurs.  Therefore, also, we cannot throw here at all.
-           setTimeout(function () {
-             self.onError(e);
-           }, 0);
-           return;
-         }
-       
-         if (typeof document !== 'undefined') {
-           this.index = Request.requestsCount++;
-           Request.requests[this.index] = this;
-         }
-       };
-       
-       /**
-        * Called upon successful response.
-        *
-        * @api private
-        */
-       
-       Request.prototype.onSuccess = function () {
-         this.emit('success');
-         this.cleanup();
-       };
-       
-       /**
-        * Called if we have data.
-        *
-        * @api private
-        */
-       
-       Request.prototype.onData = function (data) {
-         this.emit('data', data);
-         this.onSuccess();
-       };
-       
-       /**
-        * Called upon error.
-        *
-        * @api private
-        */
-       
-       Request.prototype.onError = function (err) {
-         this.emit('error', err);
-         this.cleanup(true);
-       };
-       
-       /**
-        * Cleans up house.
-        *
-        * @api private
-        */
-       
-       Request.prototype.cleanup = function (fromError) {
-         if ('undefined' === typeof this.xhr || null === this.xhr) {
-           return;
-         }
-         // xmlhttprequest
-         if (this.hasXDR()) {
-           this.xhr.onload = this.xhr.onerror = empty;
-         } else {
-           this.xhr.onreadystatechange = empty;
-         }
-       
-         if (fromError) {
-           try {
-             this.xhr.abort();
-           } catch (e) {}
-         }
-       
-         if (typeof document !== 'undefined') {
-           delete Request.requests[this.index];
-         }
-       
-         this.xhr = null;
-       };
-       
-       /**
-        * Called upon load.
-        *
-        * @api private
-        */
-       
-       Request.prototype.onLoad = function () {
-         var data;
-         try {
-           var contentType;
-           try {
-             contentType = this.xhr.getResponseHeader('Content-Type');
-           } catch (e) {}
-           if (contentType === 'application/octet-stream' || contentType === 'application/octet-stream; charset=UTF-8') {
-             data = this.xhr.response || this.xhr.responseText;
-           } else {
-             data = this.xhr.responseText;
-           }
-         } catch (e) {
-           this.onError(e);
-         }
-         if (null != data) {
-           this.onData(data);
-         }
-       };
-       
-       /**
-        * Check if it has XDomainRequest.
-        *
-        * @api private
-        */
-       
-       Request.prototype.hasXDR = function () {
-         return typeof XDomainRequest !== 'undefined' && !this.xs && this.enablesXDR;
-       };
-       
-       /**
-        * Aborts the request.
-        *
-        * @api public
-        */
-       
-       Request.prototype.abort = function () {
-         this.cleanup();
-       };
-       
-       /**
-        * Aborts pending requests when unloading the window. This is needed to prevent
-        * memory leaks (e.g. when using IE) and to ensure that no spurious error is
-        * emitted.
-        */
-       
-       Request.requestsCount = 0;
-       Request.requests = {};
-       
-       if (typeof document !== 'undefined') {
-         if (typeof attachEvent === 'function') {
-           attachEvent('onunload', unloadHandler);
-         } else if (typeof addEventListener === 'function') {
-           var terminationEvent = 'onpagehide' in globalThis ? 'pagehide' : 'unload';
-           addEventListener(terminationEvent, unloadHandler, false);
-         }
-       }
-       
-       function unloadHandler () {
-         for (var i in Request.requests) {
-           if (Request.requests.hasOwnProperty(i)) {
-             Request.requests[i].abort();
-           }
-         }
-       }
-
-
-/***/ }),
-/* 17 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       /**
-        * Module dependencies.
-        */
-       
-       var Transport = __webpack_require__(18);
-       var parseqs = __webpack_require__(27);
-       var parser = __webpack_require__(19);
-       var inherit = __webpack_require__(28);
-       var yeast = __webpack_require__(29);
-       var debug = __webpack_require__(3)('engine.io-client:polling');
-       
-       /**
-        * Module exports.
-        */
-       
-       module.exports = Polling;
-       
-       /**
-        * Is XHR2 supported?
-        */
-       
-       var hasXHR2 = (function () {
-         var XMLHttpRequest = __webpack_require__(13);
-         var xhr = new XMLHttpRequest({ xdomain: false });
-         return null != xhr.responseType;
-       })();
-       
-       /**
-        * Polling interface.
-        *
-        * @param {Object} opts
-        * @api private
-        */
-       
-       function Polling (opts) {
-         var forceBase64 = (opts && opts.forceBase64);
-         if (!hasXHR2 || forceBase64) {
-           this.supportsBinary = false;
-         }
-         Transport.call(this, opts);
-       }
-       
-       /**
-        * Inherits from Transport.
-        */
-       
-       inherit(Polling, Transport);
-       
-       /**
-        * Transport name.
-        */
-       
-       Polling.prototype.name = 'polling';
-       
-       /**
-        * Opens the socket (triggers polling). We write a PING message to determine
-        * when the transport is open.
-        *
-        * @api private
-        */
-       
-       Polling.prototype.doOpen = function () {
-         this.poll();
-       };
-       
-       /**
-        * Pauses polling.
-        *
-        * @param {Function} callback upon buffers are flushed and transport is paused
-        * @api private
-        */
-       
-       Polling.prototype.pause = function (onPause) {
-         var self = this;
-       
-         this.readyState = 'pausing';
-       
-         function pause () {
-       
-           self.readyState = 'paused';
-           onPause();
-         }
-       
-         if (this.polling || !this.writable) {
-           var total = 0;
-       
-           if (this.polling) {
-       
-             total++;
-             this.once('pollComplete', function () {
-       
-               --total || pause();
-             });
-           }
-       
-           if (!this.writable) {
-       
-             total++;
-             this.once('drain', function () {
-       
-               --total || pause();
-             });
-           }
-         } else {
-           pause();
-         }
-       };
-       
-       /**
-        * Starts polling cycle.
-        *
-        * @api public
-        */
-       
-       Polling.prototype.poll = function () {
-       
-         this.polling = true;
-         this.doPoll();
-         this.emit('poll');
-       };
-       
-       /**
-        * Overloads onData to detect payloads.
-        *
-        * @api private
-        */
-       
-       Polling.prototype.onData = function (data) {
-         var self = this;
-       
-         var callback = function (packet, index, total) {
-           // if its the first message we consider the transport open
-           if ('opening' === self.readyState && packet.type === 'open') {
-             self.onOpen();
-           }
-       
-           // if its a close packet, we close the ongoing requests
-           if ('close' === packet.type) {
-             self.onClose();
-             return false;
-           }
-       
-           // otherwise bypass onData and handle the message
-           self.onPacket(packet);
-         };
-       
-         // decode payload
-         parser.decodePayload(data, this.socket.binaryType, callback);
-       
-         // if an event did not trigger closing
-         if ('closed' !== this.readyState) {
-           // if we got data we're not polling
-           this.polling = false;
-           this.emit('pollComplete');
-       
-           if ('open' === this.readyState) {
-             this.poll();
-           } else {
-       
-           }
-         }
-       };
-       
-       /**
-        * For polling, send a close packet.
-        *
-        * @api private
-        */
-       
-       Polling.prototype.doClose = function () {
-         var self = this;
-       
-         function close () {
-       
-           self.write([{ type: 'close' }]);
-         }
-       
-         if ('open' === this.readyState) {
-       
-           close();
-         } else {
-           // in case we're trying to close while
-           // handshaking is in progress (GH-164)
-       
-           this.once('open', close);
-         }
-       };
-       
-       /**
-        * Writes a packets payload.
-        *
-        * @param {Array} data packets
-        * @param {Function} drain callback
-        * @api private
-        */
-       
-       Polling.prototype.write = function (packets) {
-         var self = this;
-         this.writable = false;
-         var callbackfn = function () {
-           self.writable = true;
-           self.emit('drain');
-         };
-       
-         parser.encodePayload(packets, this.supportsBinary, function (data) {
-           self.doWrite(data, callbackfn);
-         });
-       };
-       
-       /**
-        * Generates uri for connection.
-        *
-        * @api private
-        */
-       
-       Polling.prototype.uri = function () {
-         var query = this.query || {};
-         var schema = this.secure ? 'https' : 'http';
-         var port = '';
-       
-         // cache busting is forced
-         if (false !== this.timestampRequests) {
-           query[this.timestampParam] = yeast();
-         }
-       
-         if (!this.supportsBinary && !query.sid) {
-           query.b64 = 1;
-         }
-       
-         query = parseqs.encode(query);
-       
-         // avoid port if default for schema
-         if (this.port && (('https' === schema && Number(this.port) !== 443) ||
-            ('http' === schema && Number(this.port) !== 80))) {
-           port = ':' + this.port;
-         }
-       
-         // prepend ? to query
-         if (query.length) {
-           query = '?' + query;
-         }
-       
-         var ipv6 = this.hostname.indexOf(':') !== -1;
-         return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
-       };
-
-
-/***/ }),
-/* 18 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       /**
-        * Module dependencies.
-        */
-       
-       var parser = __webpack_require__(19);
-       var Emitter = __webpack_require__(5);
-       
-       /**
-        * Module exports.
-        */
-       
-       module.exports = Transport;
-       
-       /**
-        * Transport abstract constructor.
-        *
-        * @param {Object} options.
-        * @api private
-        */
-       
-       function Transport (opts) {
-         this.path = opts.path;
-         this.hostname = opts.hostname;
-         this.port = opts.port;
-         this.secure = opts.secure;
-         this.query = opts.query;
-         this.timestampParam = opts.timestampParam;
-         this.timestampRequests = opts.timestampRequests;
-         this.readyState = '';
-         this.agent = opts.agent || false;
-         this.socket = opts.socket;
-         this.enablesXDR = opts.enablesXDR;
-         this.withCredentials = opts.withCredentials;
-       
-         // SSL options for Node.js client
-         this.pfx = opts.pfx;
-         this.key = opts.key;
-         this.passphrase = opts.passphrase;
-         this.cert = opts.cert;
-         this.ca = opts.ca;
-         this.ciphers = opts.ciphers;
-         this.rejectUnauthorized = opts.rejectUnauthorized;
-         this.forceNode = opts.forceNode;
-       
-         // results of ReactNative environment detection
-         this.isReactNative = opts.isReactNative;
-       
-         // other options for Node.js client
-         this.extraHeaders = opts.extraHeaders;
-         this.localAddress = opts.localAddress;
-       }
-       
-       /**
-        * Mix in `Emitter`.
-        */
-       
-       Emitter(Transport.prototype);
-       
-       /**
-        * Emits an error.
-        *
-        * @param {String} str
-        * @return {Transport} for chaining
-        * @api public
-        */
-       
-       Transport.prototype.onError = function (msg, desc) {
-         var err = new Error(msg);
-         err.type = 'TransportError';
-         err.description = desc;
-         this.emit('error', err);
-         return this;
-       };
-       
-       /**
-        * Opens the transport.
-        *
-        * @api public
-        */
-       
-       Transport.prototype.open = function () {
-         if ('closed' === this.readyState || '' === this.readyState) {
-           this.readyState = 'opening';
-           this.doOpen();
-         }
-       
-         return this;
-       };
-       
-       /**
-        * Closes the transport.
-        *
-        * @api private
-        */
-       
-       Transport.prototype.close = function () {
-         if ('opening' === this.readyState || 'open' === this.readyState) {
-           this.doClose();
-           this.onClose();
-         }
-       
-         return this;
-       };
-       
-       /**
-        * Sends multiple packets.
-        *
-        * @param {Array} packets
-        * @api private
-        */
-       
-       Transport.prototype.send = function (packets) {
-         if ('open' === this.readyState) {
-           this.write(packets);
-         } else {
-           throw new Error('Transport not open');
-         }
-       };
-       
-       /**
-        * Called upon open
-        *
-        * @api private
-        */
-       
-       Transport.prototype.onOpen = function () {
-         this.readyState = 'open';
-         this.writable = true;
-         this.emit('open');
-       };
-       
-       /**
-        * Called with data.
-        *
-        * @param {String} data
-        * @api private
-        */
-       
-       Transport.prototype.onData = function (data) {
-         var packet = parser.decodePacket(data, this.socket.binaryType);
-         this.onPacket(packet);
-       };
-       
-       /**
-        * Called with a decoded packet.
-        */
-       
-       Transport.prototype.onPacket = function (packet) {
-         this.emit('packet', packet);
-       };
-       
-       /**
-        * Called upon close.
-        *
-        * @api private
-        */
-       
-       Transport.prototype.onClose = function () {
-         this.readyState = 'closed';
-         this.emit('close');
-       };
-
-
-/***/ }),
-/* 19 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       /**
-        * Module dependencies.
-        */
-       
-       var keys = __webpack_require__(20);
-       var hasBinary = __webpack_require__(21);
-       var sliceBuffer = __webpack_require__(22);
-       var after = __webpack_require__(23);
-       var utf8 = __webpack_require__(24);
-       
-       var base64encoder;
-       if (typeof ArrayBuffer !== 'undefined') {
-         base64encoder = __webpack_require__(25);
-       }
-       
-       /**
-        * Check if we are running an android browser. That requires us to use
-        * ArrayBuffer with polling transports...
-        *
-        * http://ghinda.net/jpeg-blob-ajax-android/
-        */
-       
-       var isAndroid = typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent);
-       
-       /**
-        * Check if we are running in PhantomJS.
-        * Uploading a Blob with PhantomJS does not work correctly, as reported here:
-        * https://github.com/ariya/phantomjs/issues/11395
-        * @type boolean
-        */
-       var isPhantomJS = typeof navigator !== 'undefined' && /PhantomJS/i.test(navigator.userAgent);
-       
-       /**
-        * When true, avoids using Blobs to encode payloads.
-        * @type boolean
-        */
-       var dontSendBlobs = isAndroid || isPhantomJS;
-       
-       /**
-        * Current protocol version.
-        */
-       
-       exports.protocol = 3;
-       
-       /**
-        * Packet types.
-        */
-       
-       var packets = exports.packets = {
-           open:     0    // non-ws
-         , close:    1    // non-ws
-         , ping:     2
-         , pong:     3
-         , message:  4
-         , upgrade:  5
-         , noop:     6
-       };
-       
-       var packetslist = keys(packets);
-       
-       /**
-        * Premade error packet.
-        */
-       
-       var err = { type: 'error', data: 'parser error' };
-       
-       /**
-        * Create a blob api even for blob builder when vendor prefixes exist
-        */
-       
-       var Blob = __webpack_require__(26);
-       
-       /**
-        * Encodes a packet.
-        *
-        *     <packet type id> [ <data> ]
-        *
-        * Example:
-        *
-        *     5hello world
-        *     3
-        *     4
-        *
-        * Binary is encoded in an identical principle
-        *
-        * @api private
-        */
-       
-       exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
-         if (typeof supportsBinary === 'function') {
-           callback = supportsBinary;
-           supportsBinary = false;
-         }
-       
-         if (typeof utf8encode === 'function') {
-           callback = utf8encode;
-           utf8encode = null;
-         }
-       
-         var data = (packet.data === undefined)
-           ? undefined
-           : packet.data.buffer || packet.data;
-       
-         if (typeof ArrayBuffer !== 'undefined' && data instanceof ArrayBuffer) {
-           return encodeArrayBuffer(packet, supportsBinary, callback);
-         } else if (typeof Blob !== 'undefined' && data instanceof Blob) {
-           return encodeBlob(packet, supportsBinary, callback);
-         }
-       
-         // might be an object with { base64: true, data: dataAsBase64String }
-         if (data && data.base64) {
-           return encodeBase64Object(packet, callback);
-         }
-       
-         // Sending data as a utf-8 string
-         var encoded = packets[packet.type];
-       
-         // data fragment is optional
-         if (undefined !== packet.data) {
-           encoded += utf8encode ? utf8.encode(String(packet.data), { strict: false }) : String(packet.data);
-         }
-       
-         return callback('' + encoded);
-       
-       };
-       
-       function encodeBase64Object(packet, callback) {
-         // packet data is an object { base64: true, data: dataAsBase64String }
-         var message = 'b' + exports.packets[packet.type] + packet.data.data;
-         return callback(message);
-       }
-       
-       /**
-        * Encode packet helpers for binary types
-        */
-       
-       function encodeArrayBuffer(packet, supportsBinary, callback) {
-         if (!supportsBinary) {
-           return exports.encodeBase64Packet(packet, callback);
-         }
-       
-         var data = packet.data;
-         var contentArray = new Uint8Array(data);
-         var resultBuffer = new Uint8Array(1 + data.byteLength);
-       
-         resultBuffer[0] = packets[packet.type];
-         for (var i = 0; i < contentArray.length; i++) {
-           resultBuffer[i+1] = contentArray[i];
-         }
-       
-         return callback(resultBuffer.buffer);
-       }
-       
-       function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
-         if (!supportsBinary) {
-           return exports.encodeBase64Packet(packet, callback);
-         }
-       
-         var fr = new FileReader();
-         fr.onload = function() {
-           exports.encodePacket({ type: packet.type, data: fr.result }, supportsBinary, true, callback);
-         };
-         return fr.readAsArrayBuffer(packet.data);
-       }
-       
-       function encodeBlob(packet, supportsBinary, callback) {
-         if (!supportsBinary) {
-           return exports.encodeBase64Packet(packet, callback);
-         }
-       
-         if (dontSendBlobs) {
-           return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
-         }
-       
-         var length = new Uint8Array(1);
-         length[0] = packets[packet.type];
-         var blob = new Blob([length.buffer, packet.data]);
-       
-         return callback(blob);
-       }
-       
-       /**
-        * Encodes a packet with binary data in a base64 string
-        *
-        * @param {Object} packet, has `type` and `data`
-        * @return {String} base64 encoded message
-        */
-       
-       exports.encodeBase64Packet = function(packet, callback) {
-         var message = 'b' + exports.packets[packet.type];
-         if (typeof Blob !== 'undefined' && packet.data instanceof Blob) {
-           var fr = new FileReader();
-           fr.onload = function() {
-             var b64 = fr.result.split(',')[1];
-             callback(message + b64);
-           };
-           return fr.readAsDataURL(packet.data);
-         }
-       
-         var b64data;
-         try {
-           b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
-         } catch (e) {
-           // iPhone Safari doesn't let you apply with typed arrays
-           var typed = new Uint8Array(packet.data);
-           var basic = new Array(typed.length);
-           for (var i = 0; i < typed.length; i++) {
-             basic[i] = typed[i];
-           }
-           b64data = String.fromCharCode.apply(null, basic);
-         }
-         message += btoa(b64data);
-         return callback(message);
-       };
-       
-       /**
-        * Decodes a packet. Changes format to Blob if requested.
-        *
-        * @return {Object} with `type` and `data` (if any)
-        * @api private
-        */
-       
-       exports.decodePacket = function (data, binaryType, utf8decode) {
-         if (data === undefined) {
-           return err;
-         }
-         // String data
-         if (typeof data === 'string') {
-           if (data.charAt(0) === 'b') {
-             return exports.decodeBase64Packet(data.substr(1), binaryType);
-           }
-       
-           if (utf8decode) {
-             data = tryDecode(data);
-             if (data === false) {
-               return err;
-             }
-           }
-           var type = data.charAt(0);
-       
-           if (Number(type) != type || !packetslist[type]) {
-             return err;
-           }
-       
-           if (data.length > 1) {
-             return { type: packetslist[type], data: data.substring(1) };
-           } else {
-             return { type: packetslist[type] };
-           }
-         }
-       
-         var asArray = new Uint8Array(data);
-         var type = asArray[0];
-         var rest = sliceBuffer(data, 1);
-         if (Blob && binaryType === 'blob') {
-           rest = new Blob([rest]);
-         }
-         return { type: packetslist[type], data: rest };
-       };
-       
-       function tryDecode(data) {
-         try {
-           data = utf8.decode(data, { strict: false });
-         } catch (e) {
-           return false;
-         }
-         return data;
-       }
-       
-       /**
-        * Decodes a packet encoded in a base64 string
-        *
-        * @param {String} base64 encoded message
-        * @return {Object} with `type` and `data` (if any)
-        */
-       
-       exports.decodeBase64Packet = function(msg, binaryType) {
-         var type = packetslist[msg.charAt(0)];
-         if (!base64encoder) {
-           return { type: type, data: { base64: true, data: msg.substr(1) } };
-         }
-       
-         var data = base64encoder.decode(msg.substr(1));
-       
-         if (binaryType === 'blob' && Blob) {
-           data = new Blob([data]);
-         }
-       
-         return { type: type, data: data };
-       };
-       
-       /**
-        * Encodes multiple messages (payload).
-        *
-        *     <length>:data
-        *
-        * Example:
-        *
-        *     11:hello world2:hi
-        *
-        * If any contents are binary, they will be encoded as base64 strings. Base64
-        * encoded strings are marked with a b before the length specifier
-        *
-        * @param {Array} packets
-        * @api private
-        */
-       
-       exports.encodePayload = function (packets, supportsBinary, callback) {
-         if (typeof supportsBinary === 'function') {
-           callback = supportsBinary;
-           supportsBinary = null;
-         }
-       
-         var isBinary = hasBinary(packets);
-       
-         if (supportsBinary && isBinary) {
-           if (Blob && !dontSendBlobs) {
-             return exports.encodePayloadAsBlob(packets, callback);
-           }
-       
-           return exports.encodePayloadAsArrayBuffer(packets, callback);
-         }
-       
-         if (!packets.length) {
-           return callback('0:');
-         }
-       
-         function setLengthHeader(message) {
-           return message.length + ':' + message;
-         }
-       
-         function encodeOne(packet, doneCallback) {
-           exports.encodePacket(packet, !isBinary ? false : supportsBinary, false, function(message) {
-             doneCallback(null, setLengthHeader(message));
-           });
-         }
-       
-         map(packets, encodeOne, function(err, results) {
-           return callback(results.join(''));
-         });
-       };
-       
-       /**
-        * Async array map using after
-        */
-       
-       function map(ary, each, done) {
-         var result = new Array(ary.length);
-         var next = after(ary.length, done);
-       
-         var eachWithIndex = function(i, el, cb) {
-           each(el, function(error, msg) {
-             result[i] = msg;
-             cb(error, result);
-           });
-         };
-       
-         for (var i = 0; i < ary.length; i++) {
-           eachWithIndex(i, ary[i], next);
-         }
-       }
-       
-       /*
-        * Decodes data when a payload is maybe expected. Possible binary contents are
-        * decoded from their base64 representation
-        *
-        * @param {String} data, callback method
-        * @api public
-        */
-       
-       exports.decodePayload = function (data, binaryType, callback) {
-         if (typeof data !== 'string') {
-           return exports.decodePayloadAsBinary(data, binaryType, callback);
-         }
-       
-         if (typeof binaryType === 'function') {
-           callback = binaryType;
-           binaryType = null;
-         }
-       
-         var packet;
-         if (data === '') {
-           // parser error - ignoring payload
-           return callback(err, 0, 1);
-         }
-       
-         var length = '', n, msg;
-       
-         for (var i = 0, l = data.length; i < l; i++) {
-           var chr = data.charAt(i);
-       
-           if (chr !== ':') {
-             length += chr;
-             continue;
-           }
-       
-           if (length === '' || (length != (n = Number(length)))) {
-             // parser error - ignoring payload
-             return callback(err, 0, 1);
-           }
-       
-           msg = data.substr(i + 1, n);
-       
-           if (length != msg.length) {
-             // parser error - ignoring payload
-             return callback(err, 0, 1);
-           }
-       
-           if (msg.length) {
-             packet = exports.decodePacket(msg, binaryType, false);
-       
-             if (err.type === packet.type && err.data === packet.data) {
-               // parser error in individual packet - ignoring payload
-               return callback(err, 0, 1);
-             }
-       
-             var ret = callback(packet, i + n, l);
-             if (false === ret) return;
-           }
-       
-           // advance cursor
-           i += n;
-           length = '';
-         }
-       
-         if (length !== '') {
-           // parser error - ignoring payload
-           return callback(err, 0, 1);
-         }
-       
-       };
-       
-       /**
-        * Encodes multiple messages (payload) as binary.
-        *
-        * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
-        * 255><data>
-        *
-        * Example:
-        * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
-        *
-        * @param {Array} packets
-        * @return {ArrayBuffer} encoded payload
-        * @api private
-        */
-       
-       exports.encodePayloadAsArrayBuffer = function(packets, callback) {
-         if (!packets.length) {
-           return callback(new ArrayBuffer(0));
-         }
-       
-         function encodeOne(packet, doneCallback) {
-           exports.encodePacket(packet, true, true, function(data) {
-             return doneCallback(null, data);
-           });
-         }
-       
-         map(packets, encodeOne, function(err, encodedPackets) {
-           var totalLength = encodedPackets.reduce(function(acc, p) {
-             var len;
-             if (typeof p === 'string'){
-               len = p.length;
-             } else {
-               len = p.byteLength;
-             }
-             return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
-           }, 0);
-       
-           var resultArray = new Uint8Array(totalLength);
-       
-           var bufferIndex = 0;
-           encodedPackets.forEach(function(p) {
-             var isString = typeof p === 'string';
-             var ab = p;
-             if (isString) {
-               var view = new Uint8Array(p.length);
-               for (var i = 0; i < p.length; i++) {
-                 view[i] = p.charCodeAt(i);
-               }
-               ab = view.buffer;
-             }
-       
-             if (isString) { // not true binary
-               resultArray[bufferIndex++] = 0;
-             } else { // true binary
-               resultArray[bufferIndex++] = 1;
-             }
-       
-             var lenStr = ab.byteLength.toString();
-             for (var i = 0; i < lenStr.length; i++) {
-               resultArray[bufferIndex++] = parseInt(lenStr[i]);
-             }
-             resultArray[bufferIndex++] = 255;
-       
-             var view = new Uint8Array(ab);
-             for (var i = 0; i < view.length; i++) {
-               resultArray[bufferIndex++] = view[i];
-             }
-           });
-       
-           return callback(resultArray.buffer);
-         });
-       };
-       
-       /**
-        * Encode as Blob
-        */
-       
-       exports.encodePayloadAsBlob = function(packets, callback) {
-         function encodeOne(packet, doneCallback) {
-           exports.encodePacket(packet, true, true, function(encoded) {
-             var binaryIdentifier = new Uint8Array(1);
-             binaryIdentifier[0] = 1;
-             if (typeof encoded === 'string') {
-               var view = new Uint8Array(encoded.length);
-               for (var i = 0; i < encoded.length; i++) {
-                 view[i] = encoded.charCodeAt(i);
-               }
-               encoded = view.buffer;
-               binaryIdentifier[0] = 0;
-             }
-       
-             var len = (encoded instanceof ArrayBuffer)
-               ? encoded.byteLength
-               : encoded.size;
-       
-             var lenStr = len.toString();
-             var lengthAry = new Uint8Array(lenStr.length + 1);
-             for (var i = 0; i < lenStr.length; i++) {
-               lengthAry[i] = parseInt(lenStr[i]);
-             }
-             lengthAry[lenStr.length] = 255;
-       
-             if (Blob) {
-               var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
-               doneCallback(null, blob);
-             }
-           });
-         }
-       
-         map(packets, encodeOne, function(err, results) {
-           return callback(new Blob(results));
-         });
-       };
-       
-       /*
-        * Decodes data when a payload is maybe expected. Strings are decoded by
-        * interpreting each byte as a key code for entries marked to start with 0. See
-        * description of encodePayloadAsBinary
-        *
-        * @param {ArrayBuffer} data, callback method
-        * @api public
-        */
-       
-       exports.decodePayloadAsBinary = function (data, binaryType, callback) {
-         if (typeof binaryType === 'function') {
-           callback = binaryType;
-           binaryType = null;
-         }
-       
-         var bufferTail = data;
-         var buffers = [];
-       
-         while (bufferTail.byteLength > 0) {
-           var tailArray = new Uint8Array(bufferTail);
-           var isString = tailArray[0] === 0;
-           var msgLength = '';
-       
-           for (var i = 1; ; i++) {
-             if (tailArray[i] === 255) break;
-       
-             // 310 = char length of Number.MAX_VALUE
-             if (msgLength.length > 310) {
-               return callback(err, 0, 1);
-             }
-       
-             msgLength += tailArray[i];
-           }
-       
-           bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
-           msgLength = parseInt(msgLength);
-       
-           var msg = sliceBuffer(bufferTail, 0, msgLength);
-           if (isString) {
-             try {
-               msg = String.fromCharCode.apply(null, new Uint8Array(msg));
-             } catch (e) {
-               // iPhone Safari doesn't let you apply to typed arrays
-               var typed = new Uint8Array(msg);
-               msg = '';
-               for (var i = 0; i < typed.length; i++) {
-                 msg += String.fromCharCode(typed[i]);
-               }
-             }
-           }
-       
-           buffers.push(msg);
-           bufferTail = sliceBuffer(bufferTail, msgLength);
-         }
-       
-         var total = buffers.length;
-         buffers.forEach(function(buffer, i) {
-           callback(exports.decodePacket(buffer, binaryType, true), i, total);
-         });
-       };
-
-
-/***/ }),
-/* 20 */
-/***/ (function(module, exports) {
-
-       
-       /**
-        * Gets the keys for an object.
-        *
-        * @return {Array} keys
-        * @api private
-        */
-       
-       module.exports = Object.keys || function keys (obj){
-         var arr = [];
-         var has = Object.prototype.hasOwnProperty;
-       
-         for (var i in obj) {
-           if (has.call(obj, i)) {
-             arr.push(i);
-           }
-         }
-         return arr;
-       };
-
-
-/***/ }),
-/* 21 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       /* global Blob File */
-       
-       /*
-        * Module requirements.
-        */
-       
-       var isArray = __webpack_require__(7);
-       
-       var toString = Object.prototype.toString;
-       var withNativeBlob = typeof Blob === 'function' ||
-                               typeof Blob !== 'undefined' && toString.call(Blob) === '[object BlobConstructor]';
-       var withNativeFile = typeof File === 'function' ||
-                               typeof File !== 'undefined' && toString.call(File) === '[object FileConstructor]';
-       
-       /**
-        * Module exports.
-        */
-       
-       module.exports = hasBinary;
-       
-       /**
-        * Checks for binary data.
-        *
-        * Supports Buffer, ArrayBuffer, Blob and File.
-        *
-        * @param {Object} anything
-        * @api public
-        */
-       
-       function hasBinary (obj) {
-         if (!obj || typeof obj !== 'object') {
-           return false;
-         }
-       
-         if (isArray(obj)) {
-           for (var i = 0, l = obj.length; i < l; i++) {
-             if (hasBinary(obj[i])) {
-               return true;
-             }
-           }
-           return false;
-         }
-       
-         if ((typeof Buffer === 'function' && Buffer.isBuffer && Buffer.isBuffer(obj)) ||
-           (typeof ArrayBuffer === 'function' && obj instanceof ArrayBuffer) ||
-           (withNativeBlob && obj instanceof Blob) ||
-           (withNativeFile && obj instanceof File)
-         ) {
-           return true;
-         }
-       
-         // see: https://github.com/Automattic/has-binary/pull/4
-         if (obj.toJSON && typeof obj.toJSON === 'function' && arguments.length === 1) {
-           return hasBinary(obj.toJSON(), true);
-         }
-       
-         for (var key in obj) {
-           if (Object.prototype.hasOwnProperty.call(obj, key) && hasBinary(obj[key])) {
-             return true;
-           }
-         }
-       
-         return false;
-       }
-
-
-/***/ }),
-/* 22 */
-/***/ (function(module, exports) {
-
-       /**
-        * An abstraction for slicing an arraybuffer even when
-        * ArrayBuffer.prototype.slice is not supported
-        *
-        * @api public
-        */
-       
-       module.exports = function(arraybuffer, start, end) {
-         var bytes = arraybuffer.byteLength;
-         start = start || 0;
-         end = end || bytes;
-       
-         if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
-       
-         if (start < 0) { start += bytes; }
-         if (end < 0) { end += bytes; }
-         if (end > bytes) { end = bytes; }
-       
-         if (start >= bytes || start >= end || bytes === 0) {
-           return new ArrayBuffer(0);
-         }
-       
-         var abv = new Uint8Array(arraybuffer);
-         var result = new Uint8Array(end - start);
-         for (var i = start, ii = 0; i < end; i++, ii++) {
-           result[ii] = abv[i];
-         }
-         return result.buffer;
-       };
-
-
-/***/ }),
-/* 23 */
-/***/ (function(module, exports) {
-
-       module.exports = after
-       
-       function after(count, callback, err_cb) {
-           var bail = false
-           err_cb = err_cb || noop
-           proxy.count = count
-       
-           return (count === 0) ? callback() : proxy
-       
-           function proxy(err, result) {
-               if (proxy.count <= 0) {
-                   throw new Error('after called too many times')
-               }
-               --proxy.count
-       
-               // after first error, rest are passed to err_cb
-               if (err) {
-                   bail = true
-                   callback(err)
-                   // future error callbacks will go to error handler
-                   callback = err_cb
-               } else if (proxy.count === 0 && !bail) {
-                   callback(null, result)
-               }
-           }
-       }
-       
-       function noop() {}
-
-
-/***/ }),
-/* 24 */
-/***/ (function(module, exports) {
-
-       /*! https://mths.be/utf8js v2.1.2 by @mathias */
-       
-       var stringFromCharCode = String.fromCharCode;
-       
-       // Taken from https://mths.be/punycode
-       function ucs2decode(string) {
-               var output = [];
-               var counter = 0;
-               var length = string.length;
-               var value;
-               var 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;
-       }
-       
-       // Taken from https://mths.be/punycode
-       function ucs2encode(array) {
-               var length = array.length;
-               var index = -1;
-               var value;
-               var output = '';
-               while (++index < length) {
-                       value = array[index];
-                       if (value > 0xFFFF) {
-                               value -= 0x10000;
-                               output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
-                               value = 0xDC00 | value & 0x3FF;
-                       }
-                       output += stringFromCharCode(value);
-               }
-               return output;
-       }
-       
-       function checkScalarValue(codePoint, strict) {
-               if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {
-                       if (strict) {
-                               throw Error(
-                                       'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +
-                                       ' is not a scalar value'
-                               );
-                       }
-                       return false;
-               }
-               return true;
-       }
-       /*--------------------------------------------------------------------------*/
-       
-       function createByte(codePoint, shift) {
-               return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
-       }
-       
-       function encodeCodePoint(codePoint, strict) {
-               if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
-                       return stringFromCharCode(codePoint);
-               }
-               var symbol = '';
-               if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
-                       symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
-               }
-               else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
-                       if (!checkScalarValue(codePoint, strict)) {
-                               codePoint = 0xFFFD;
-                       }
-                       symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
-                       symbol += createByte(codePoint, 6);
-               }
-               else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
-                       symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
-                       symbol += createByte(codePoint, 12);
-                       symbol += createByte(codePoint, 6);
-               }
-               symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
-               return symbol;
-       }
-       
-       function utf8encode(string, opts) {
-               opts = opts || {};
-               var strict = false !== opts.strict;
-       
-               var codePoints = ucs2decode(string);
-               var length = codePoints.length;
-               var index = -1;
-               var codePoint;
-               var byteString = '';
-               while (++index < length) {
-                       codePoint = codePoints[index];
-                       byteString += encodeCodePoint(codePoint, strict);
-               }
-               return byteString;
-       }
-       
-       /*--------------------------------------------------------------------------*/
-       
-       function readContinuationByte() {
-               if (byteIndex >= byteCount) {
-                       throw Error('Invalid byte index');
-               }
-       
-               var continuationByte = byteArray[byteIndex] & 0xFF;
-               byteIndex++;
-       
-               if ((continuationByte & 0xC0) == 0x80) {
-                       return continuationByte & 0x3F;
-               }
-       
-               // If we end up here, it’s not a continuation byte
-               throw Error('Invalid continuation byte');
-       }
-       
-       function decodeSymbol(strict) {
-               var byte1;
-               var byte2;
-               var byte3;
-               var byte4;
-               var codePoint;
-       
-               if (byteIndex > byteCount) {
-                       throw Error('Invalid byte index');
-               }
-       
-               if (byteIndex == byteCount) {
-                       return false;
-               }
-       
-               // Read first byte
-               byte1 = byteArray[byteIndex] & 0xFF;
-               byteIndex++;
-       
-               // 1-byte sequence (no continuation bytes)
-               if ((byte1 & 0x80) == 0) {
-                       return byte1;
-               }
-       
-               // 2-byte sequence
-               if ((byte1 & 0xE0) == 0xC0) {
-                       byte2 = readContinuationByte();
-                       codePoint = ((byte1 & 0x1F) << 6) | byte2;
-                       if (codePoint >= 0x80) {
-                               return codePoint;
-                       } else {
-                               throw Error('Invalid continuation byte');
-                       }
-               }
-       
-               // 3-byte sequence (may include unpaired surrogates)
-               if ((byte1 & 0xF0) == 0xE0) {
-                       byte2 = readContinuationByte();
-                       byte3 = readContinuationByte();
-                       codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
-                       if (codePoint >= 0x0800) {
-                               return checkScalarValue(codePoint, strict) ? codePoint : 0xFFFD;
-                       } else {
-                               throw Error('Invalid continuation byte');
-                       }
-               }
-       
-               // 4-byte sequence
-               if ((byte1 & 0xF8) == 0xF0) {
-                       byte2 = readContinuationByte();
-                       byte3 = readContinuationByte();
-                       byte4 = readContinuationByte();
-                       codePoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0C) |
-                               (byte3 << 0x06) | byte4;
-                       if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
-                               return codePoint;
-                       }
-               }
-       
-               throw Error('Invalid UTF-8 detected');
-       }
-       
-       var byteArray;
-       var byteCount;
-       var byteIndex;
-       function utf8decode(byteString, opts) {
-               opts = opts || {};
-               var strict = false !== opts.strict;
-       
-               byteArray = ucs2decode(byteString);
-               byteCount = byteArray.length;
-               byteIndex = 0;
-               var codePoints = [];
-               var tmp;
-               while ((tmp = decodeSymbol(strict)) !== false) {
-                       codePoints.push(tmp);
-               }
-               return ucs2encode(codePoints);
-       }
-       
-       module.exports = {
-               version: '2.1.2',
-               encode: utf8encode,
-               decode: utf8decode
-       };
-
-
-/***/ }),
-/* 25 */
-/***/ (function(module, exports) {
-
-       /*
-        * base64-arraybuffer
-        * https://github.com/niklasvh/base64-arraybuffer
-        *
-        * Copyright (c) 2012 Niklas von Hertzen
-        * Licensed under the MIT license.
-        */
-       (function(chars){
-         "use strict";
-       
-         exports.encode = function(arraybuffer) {
-           var bytes = new Uint8Array(arraybuffer),
-           i, len = bytes.length, base64 = "";
-       
-           for (i = 0; i < len; i+=3) {
-             base64 += chars[bytes[i] >> 2];
-             base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
-             base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
-             base64 += chars[bytes[i + 2] & 63];
-           }
-       
-           if ((len % 3) === 2) {
-             base64 = base64.substring(0, base64.length - 1) + "=";
-           } else if (len % 3 === 1) {
-             base64 = base64.substring(0, base64.length - 2) + "==";
-           }
-       
-           return base64;
-         };
-       
-         exports.decode =  function(base64) {
-           var bufferLength = base64.length * 0.75,
-           len = base64.length, i, p = 0,
-           encoded1, encoded2, encoded3, encoded4;
-       
-           if (base64[base64.length - 1] === "=") {
-             bufferLength--;
-             if (base64[base64.length - 2] === "=") {
-               bufferLength--;
-             }
-           }
-       
-           var arraybuffer = new ArrayBuffer(bufferLength),
-           bytes = new Uint8Array(arraybuffer);
-       
-           for (i = 0; i < len; i+=4) {
-             encoded1 = chars.indexOf(base64[i]);
-             encoded2 = chars.indexOf(base64[i+1]);
-             encoded3 = chars.indexOf(base64[i+2]);
-             encoded4 = chars.indexOf(base64[i+3]);
-       
-             bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
-             bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
-             bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
-           }
-       
-           return arraybuffer;
-         };
-       })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
-
-
-/***/ }),
-/* 26 */
-/***/ (function(module, exports) {
-
-       /**
-        * Create a blob builder even when vendor prefixes exist
-        */
-       
-       var BlobBuilder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
-         typeof WebKitBlobBuilder !== 'undefined' ? WebKitBlobBuilder :
-         typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
-         typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : 
-         false;
-       
-       /**
-        * Check if Blob constructor is supported
-        */
-       
-       var blobSupported = (function() {
-         try {
-           var a = new Blob(['hi']);
-           return a.size === 2;
-         } catch(e) {
-           return false;
-         }
-       })();
-       
-       /**
-        * Check if Blob constructor supports ArrayBufferViews
-        * Fails in Safari 6, so we need to map to ArrayBuffers there.
-        */
-       
-       var blobSupportsArrayBufferView = blobSupported && (function() {
-         try {
-           var b = new Blob([new Uint8Array([1,2])]);
-           return b.size === 2;
-         } catch(e) {
-           return false;
-         }
-       })();
-       
-       /**
-        * Check if BlobBuilder is supported
-        */
-       
-       var blobBuilderSupported = BlobBuilder
-         && BlobBuilder.prototype.append
-         && BlobBuilder.prototype.getBlob;
-       
-       /**
-        * Helper function that maps ArrayBufferViews to ArrayBuffers
-        * Used by BlobBuilder constructor and old browsers that didn't
-        * support it in the Blob constructor.
-        */
-       
-       function mapArrayBufferViews(ary) {
-         return ary.map(function(chunk) {
-           if (chunk.buffer instanceof ArrayBuffer) {
-             var buf = chunk.buffer;
-       
-             // if this is a subarray, make a copy so we only
-             // include the subarray region from the underlying buffer
-             if (chunk.byteLength !== buf.byteLength) {
-               var copy = new Uint8Array(chunk.byteLength);
-               copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
-               buf = copy.buffer;
-             }
-       
-             return buf;
-           }
-       
-           return chunk;
-         });
-       }
-       
-       function BlobBuilderConstructor(ary, options) {
-         options = options || {};
-       
-         var bb = new BlobBuilder();
-         mapArrayBufferViews(ary).forEach(function(part) {
-           bb.append(part);
-         });
-       
-         return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
-       };
-       
-       function BlobConstructor(ary, options) {
-         return new Blob(mapArrayBufferViews(ary), options || {});
-       };
-       
-       if (typeof Blob !== 'undefined') {
-         BlobBuilderConstructor.prototype = Blob.prototype;
-         BlobConstructor.prototype = Blob.prototype;
-       }
-       
-       module.exports = (function() {
-         if (blobSupported) {
-           return blobSupportsArrayBufferView ? Blob : BlobConstructor;
-         } else if (blobBuilderSupported) {
-           return BlobBuilderConstructor;
-         } else {
-           return undefined;
-         }
-       })();
-
-
-/***/ }),
-/* 27 */
-/***/ (function(module, exports) {
-
-       /**
-        * Compiles a querystring
-        * Returns string representation of the object
-        *
-        * @param {Object}
-        * @api private
-        */
-       
-       exports.encode = function (obj) {
-         var str = '';
-       
-         for (var i in obj) {
-           if (obj.hasOwnProperty(i)) {
-             if (str.length) str += '&';
-             str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
-           }
-         }
-       
-         return str;
-       };
-       
-       /**
-        * Parses a simple querystring into an object
-        *
-        * @param {String} qs
-        * @api private
-        */
-       
-       exports.decode = function(qs){
-         var qry = {};
-         var pairs = qs.split('&');
-         for (var i = 0, l = pairs.length; i < l; i++) {
-           var pair = pairs[i].split('=');
-           qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
-         }
-         return qry;
-       };
-
-
-/***/ }),
-/* 28 */
-/***/ (function(module, exports) {
-
-       
-       module.exports = function(a, b){
-         var fn = function(){};
-         fn.prototype = b.prototype;
-         a.prototype = new fn;
-         a.prototype.constructor = a;
-       };
-
-/***/ }),
-/* 29 */
-/***/ (function(module, exports) {
-
-       'use strict';
-       
-       var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('')
-         , length = 64
-         , map = {}
-         , seed = 0
-         , i = 0
-         , prev;
-       
-       /**
-        * Return a string representing the specified number.
-        *
-        * @param {Number} num The number to convert.
-        * @returns {String} The string representation of the number.
-        * @api public
-        */
-       function encode(num) {
-         var encoded = '';
-       
-         do {
-           encoded = alphabet[num % length] + encoded;
-           num = Math.floor(num / length);
-         } while (num > 0);
-       
-         return encoded;
-       }
-       
-       /**
-        * Return the integer value specified by the given string.
-        *
-        * @param {String} str The string to convert.
-        * @returns {Number} The integer value represented by the string.
-        * @api public
-        */
-       function decode(str) {
-         var decoded = 0;
-       
-         for (i = 0; i < str.length; i++) {
-           decoded = decoded * length + map[str.charAt(i)];
-         }
-       
-         return decoded;
-       }
-       
-       /**
-        * Yeast: A tiny growing id generator.
-        *
-        * @returns {String} A unique id.
-        * @api public
-        */
-       function yeast() {
-         var now = encode(+new Date());
-       
-         if (now !== prev) return seed = 0, prev = now;
-         return now +'.'+ encode(seed++);
-       }
-       
-       //
-       // Map each character to its index.
-       //
-       for (; i < length; i++) map[alphabet[i]] = i;
-       
-       //
-       // Expose the `yeast`, `encode` and `decode` functions.
-       //
-       yeast.encode = encode;
-       yeast.decode = decode;
-       module.exports = yeast;
-
-
-/***/ }),
-/* 30 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       /**
-        * Module requirements.
-        */
-       
-       var Polling = __webpack_require__(17);
-       var inherit = __webpack_require__(28);
-       var globalThis = __webpack_require__(15);
-       
-       /**
-        * Module exports.
-        */
-       
-       module.exports = JSONPPolling;
-       
-       /**
-        * Cached regular expressions.
-        */
-       
-       var rNewline = /\n/g;
-       var rEscapedNewline = /\\n/g;
-       
-       /**
-        * Global JSONP callbacks.
-        */
-       
-       var callbacks;
-       
-       /**
-        * Noop.
-        */
-       
-       function empty () { }
-       
-       /**
-        * JSONP Polling constructor.
-        *
-        * @param {Object} opts.
-        * @api public
-        */
-       
-       function JSONPPolling (opts) {
-         Polling.call(this, opts);
-       
-         this.query = this.query || {};
-       
-         // define global callbacks array if not present
-         // we do this here (lazily) to avoid unneeded global pollution
-         if (!callbacks) {
-           // we need to consider multiple engines in the same page
-           callbacks = globalThis.___eio = (globalThis.___eio || []);
-         }
-       
-         // callback identifier
-         this.index = callbacks.length;
-       
-         // add callback to jsonp global
-         var self = this;
-         callbacks.push(function (msg) {
-           self.onData(msg);
-         });
-       
-         // append to query string
-         this.query.j = this.index;
-       
-         // prevent spurious errors from being emitted when the window is unloaded
-         if (typeof addEventListener === 'function') {
-           addEventListener('beforeunload', function () {
-             if (self.script) self.script.onerror = empty;
-           }, false);
-         }
-       }
-       
-       /**
-        * Inherits from Polling.
-        */
-       
-       inherit(JSONPPolling, Polling);
-       
-       /*
-        * JSONP only supports binary as base64 encoded strings
-        */
-       
-       JSONPPolling.prototype.supportsBinary = false;
-       
-       /**
-        * Closes the socket.
-        *
-        * @api private
-        */
-       
-       JSONPPolling.prototype.doClose = function () {
-         if (this.script) {
-           this.script.parentNode.removeChild(this.script);
-           this.script = null;
-         }
-       
-         if (this.form) {
-           this.form.parentNode.removeChild(this.form);
-           this.form = null;
-           this.iframe = null;
-         }
-       
-         Polling.prototype.doClose.call(this);
-       };
-       
-       /**
-        * Starts a poll cycle.
-        *
-        * @api private
-        */
-       
-       JSONPPolling.prototype.doPoll = function () {
-         var self = this;
-         var script = document.createElement('script');
-       
-         if (this.script) {
-           this.script.parentNode.removeChild(this.script);
-           this.script = null;
-         }
-       
-         script.async = true;
-         script.src = this.uri();
-         script.onerror = function (e) {
-           self.onError('jsonp poll error', e);
-         };
-       
-         var insertAt = document.getElementsByTagName('script')[0];
-         if (insertAt) {
-           insertAt.parentNode.insertBefore(script, insertAt);
-         } else {
-           (document.head || document.body).appendChild(script);
-         }
-         this.script = script;
-       
-         var isUAgecko = 'undefined' !== typeof navigator && /gecko/i.test(navigator.userAgent);
-       
-         if (isUAgecko) {
-           setTimeout(function () {
-             var iframe = document.createElement('iframe');
-             document.body.appendChild(iframe);
-             document.body.removeChild(iframe);
-           }, 100);
-         }
-       };
-       
-       /**
-        * Writes with a hidden iframe.
-        *
-        * @param {String} data to send
-        * @param {Function} called upon flush.
-        * @api private
-        */
-       
-       JSONPPolling.prototype.doWrite = function (data, fn) {
-         var self = this;
-       
-         if (!this.form) {
-           var form = document.createElement('form');
-           var area = document.createElement('textarea');
-           var id = this.iframeId = 'eio_iframe_' + this.index;
-           var iframe;
-       
-           form.className = 'socketio';
-           form.style.position = 'absolute';
-           form.style.top = '-1000px';
-           form.style.left = '-1000px';
-           form.target = id;
-           form.method = 'POST';
-           form.setAttribute('accept-charset', 'utf-8');
-           area.name = 'd';
-           form.appendChild(area);
-           document.body.appendChild(form);
-       
-           this.form = form;
-           this.area = area;
-         }
-       
-         this.form.action = this.uri();
-       
-         function complete () {
-           initIframe();
-           fn();
-         }
-       
-         function initIframe () {
-           if (self.iframe) {
-             try {
-               self.form.removeChild(self.iframe);
-             } catch (e) {
-               self.onError('jsonp polling iframe removal error', e);
-             }
-           }
-       
-           try {
-             // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
-             var html = '<iframe src="javascript:0" name="' + self.iframeId + '">';
-             iframe = document.createElement(html);
-           } catch (e) {
-             iframe = document.createElement('iframe');
-             iframe.name = self.iframeId;
-             iframe.src = 'javascript:0';
-           }
-       
-           iframe.id = self.iframeId;
-       
-           self.form.appendChild(iframe);
-           self.iframe = iframe;
-         }
-       
-         initIframe();
-       
-         // escape \n to prevent it from being converted into \r\n by some UAs
-         // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
-         data = data.replace(rEscapedNewline, '\\\n');
-         this.area.value = data.replace(rNewline, '\\n');
-       
-         try {
-           this.form.submit();
-         } catch (e) {}
-       
-         if (this.iframe.attachEvent) {
-           this.iframe.onreadystatechange = function () {
-             if (self.iframe.readyState === 'complete') {
-               complete();
-             }
-           };
-         } else {
-           this.iframe.onload = complete;
-         }
-       };
-
-
-/***/ }),
-/* 31 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       /**
-        * Module dependencies.
-        */
-       
-       var Transport = __webpack_require__(18);
-       var parser = __webpack_require__(19);
-       var parseqs = __webpack_require__(27);
-       var inherit = __webpack_require__(28);
-       var yeast = __webpack_require__(29);
-       var debug = __webpack_require__(3)('engine.io-client:websocket');
-       
-       var BrowserWebSocket, NodeWebSocket;
-       
-       if (typeof WebSocket !== 'undefined') {
-         BrowserWebSocket = WebSocket;
-       } else if (typeof self !== 'undefined') {
-         BrowserWebSocket = self.WebSocket || self.MozWebSocket;
-       }
-       
-       if (typeof window === 'undefined') {
-         try {
-           NodeWebSocket = __webpack_require__(32);
-         } catch (e) { }
-       }
-       
-       /**
-        * Get either the `WebSocket` or `MozWebSocket` globals
-        * in the browser or try to resolve WebSocket-compatible
-        * interface exposed by `ws` for Node-like environment.
-        */
-       
-       var WebSocketImpl = BrowserWebSocket || NodeWebSocket;
-       
-       /**
-        * Module exports.
-        */
-       
-       module.exports = WS;
-       
-       /**
-        * WebSocket transport constructor.
-        *
-        * @api {Object} connection options
-        * @api public
-        */
-       
-       function WS (opts) {
-         var forceBase64 = (opts && opts.forceBase64);
-         if (forceBase64) {
-           this.supportsBinary = false;
-         }
-         this.perMessageDeflate = opts.perMessageDeflate;
-         this.usingBrowserWebSocket = BrowserWebSocket && !opts.forceNode;
-         this.protocols = opts.protocols;
-         if (!this.usingBrowserWebSocket) {
-           WebSocketImpl = NodeWebSocket;
-         }
-         Transport.call(this, opts);
-       }
-       
-       /**
-        * Inherits from Transport.
-        */
-       
-       inherit(WS, Transport);
-       
-       /**
-        * Transport name.
-        *
-        * @api public
-        */
-       
-       WS.prototype.name = 'websocket';
-       
-       /*
-        * WebSockets support binary
-        */
-       
-       WS.prototype.supportsBinary = true;
-       
-       /**
-        * Opens socket.
-        *
-        * @api private
-        */
-       
-       WS.prototype.doOpen = function () {
-         if (!this.check()) {
-           // let probe timeout
-           return;
-         }
-       
-         var uri = this.uri();
-         var protocols = this.protocols;
-       
-         var opts = {};
-       
-         if (!this.isReactNative) {
-           opts.agent = this.agent;
-           opts.perMessageDeflate = this.perMessageDeflate;
-       
-           // SSL options for Node.js client
-           opts.pfx = this.pfx;
-           opts.key = this.key;
-           opts.passphrase = this.passphrase;
-           opts.cert = this.cert;
-           opts.ca = this.ca;
-           opts.ciphers = this.ciphers;
-           opts.rejectUnauthorized = this.rejectUnauthorized;
-         }
-       
-         if (this.extraHeaders) {
-           opts.headers = this.extraHeaders;
-         }
-         if (this.localAddress) {
-           opts.localAddress = this.localAddress;
-         }
-       
-         try {
-           this.ws =
-             this.usingBrowserWebSocket && !this.isReactNative
-               ? protocols
-                 ? new WebSocketImpl(uri, protocols)
-                 : new WebSocketImpl(uri)
-               : new WebSocketImpl(uri, protocols, opts);
-         } catch (err) {
-           return this.emit('error', err);
-         }
-       
-         if (this.ws.binaryType === undefined) {
-           this.supportsBinary = false;
-         }
-       
-         if (this.ws.supports && this.ws.supports.binary) {
-           this.supportsBinary = true;
-           this.ws.binaryType = 'nodebuffer';
-         } else {
-           this.ws.binaryType = 'arraybuffer';
-         }
-       
-         this.addEventListeners();
-       };
-       
-       /**
-        * Adds event listeners to the socket
-        *
-        * @api private
-        */
-       
-       WS.prototype.addEventListeners = function () {
-         var self = this;
-       
-         this.ws.onopen = function () {
-           self.onOpen();
-         };
-         this.ws.onclose = function () {
-           self.onClose();
-         };
-         this.ws.onmessage = function (ev) {
-           self.onData(ev.data);
-         };
-         this.ws.onerror = function (e) {
-           self.onError('websocket error', e);
-         };
-       };
-       
-       /**
-        * Writes data to socket.
-        *
-        * @param {Array} array of packets.
-        * @api private
-        */
-       
-       WS.prototype.write = function (packets) {
-         var self = this;
-         this.writable = false;
-       
-         // encodePacket efficient as it uses WS framing
-         // no need for encodePayload
-         var total = packets.length;
-         for (var i = 0, l = total; i < l; i++) {
-           (function (packet) {
-             parser.encodePacket(packet, self.supportsBinary, function (data) {
-               if (!self.usingBrowserWebSocket) {
-                 // always create a new object (GH-437)
-                 var opts = {};
-                 if (packet.options) {
-                   opts.compress = packet.options.compress;
-                 }
-       
-                 if (self.perMessageDeflate) {
-                   var len = 'string' === typeof data ? Buffer.byteLength(data) : data.length;
-                   if (len < self.perMessageDeflate.threshold) {
-                     opts.compress = false;
-                   }
-                 }
-               }
-       
-               // Sometimes the websocket has already been closed but the browser didn't
-               // have a chance of informing us about it yet, in that case send will
-               // throw an error
-               try {
-                 if (self.usingBrowserWebSocket) {
-                   // TypeError is thrown when passing the second argument on Safari
-                   self.ws.send(data);
-                 } else {
-                   self.ws.send(data, opts);
-                 }
-               } catch (e) {
-       
-               }
-       
-               --total || done();
-             });
-           })(packets[i]);
-         }
-       
-         function done () {
-           self.emit('flush');
-       
-           // fake drain
-           // defer to next tick to allow Socket to clear writeBuffer
-           setTimeout(function () {
-             self.writable = true;
-             self.emit('drain');
-           }, 0);
-         }
-       };
-       
-       /**
-        * Called upon close
-        *
-        * @api private
-        */
-       
-       WS.prototype.onClose = function () {
-         Transport.prototype.onClose.call(this);
-       };
-       
-       /**
-        * Closes socket.
-        *
-        * @api private
-        */
-       
-       WS.prototype.doClose = function () {
-         if (typeof this.ws !== 'undefined') {
-           this.ws.close();
-         }
-       };
-       
-       /**
-        * Generates uri for connection.
-        *
-        * @api private
-        */
-       
-       WS.prototype.uri = function () {
-         var query = this.query || {};
-         var schema = this.secure ? 'wss' : 'ws';
-         var port = '';
-       
-         // avoid port if default for schema
-         if (this.port && (('wss' === schema && Number(this.port) !== 443) ||
-           ('ws' === schema && Number(this.port) !== 80))) {
-           port = ':' + this.port;
-         }
-       
-         // append timestamp to URI
-         if (this.timestampRequests) {
-           query[this.timestampParam] = yeast();
-         }
-       
-         // communicate binary support capabilities
-         if (!this.supportsBinary) {
-           query.b64 = 1;
-         }
-       
-         query = parseqs.encode(query);
-       
-         // prepend ? to query
-         if (query.length) {
-           query = '?' + query;
-         }
-       
-         var ipv6 = this.hostname.indexOf(':') !== -1;
-         return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
-       };
-       
-       /**
-        * Feature detection for WebSocket.
-        *
-        * @return {Boolean} whether this transport is available.
-        * @api public
-        */
-       
-       WS.prototype.check = function () {
-         return !!WebSocketImpl && !('__initialize' in WebSocketImpl && this.name === WS.prototype.name);
-       };
-
-
-/***/ }),
-/* 32 */
-/***/ (function(module, exports) {
-
-       /* (ignored) */
-
-/***/ }),
-/* 33 */
-/***/ (function(module, exports) {
-
-       
-       var indexOf = [].indexOf;
-       
-       module.exports = function(arr, obj){
-         if (indexOf) return arr.indexOf(obj);
-         for (var i = 0; i < arr.length; ++i) {
-           if (arr[i] === obj) return i;
-         }
-         return -1;
-       };
-
-/***/ }),
-/* 34 */
-/***/ (function(module, exports, __webpack_require__) {
-
-       'use strict';
-       
-       var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
-       
-       /**
-        * Module dependencies.
-        */
-       
-       var parser = __webpack_require__(4);
-       var Emitter = __webpack_require__(5);
-       var toArray = __webpack_require__(35);
-       var on = __webpack_require__(36);
-       var bind = __webpack_require__(37);
-       var debug = __webpack_require__(3)('socket.io-client:socket');
-       var parseqs = __webpack_require__(27);
-       var hasBin = __webpack_require__(21);
-       
-       /**
-        * Module exports.
-        */
-       
-       module.exports = exports = Socket;
-       
-       /**
-        * Internal events (blacklisted).
-        * These events can't be emitted by the user.
-        *
-        * @api private
-        */
-       
-       var events = {
-         connect: 1,
-         connect_error: 1,
-         connect_timeout: 1,
-         connecting: 1,
-         disconnect: 1,
-         error: 1,
-         reconnect: 1,
-         reconnect_attempt: 1,
-         reconnect_failed: 1,
-         reconnect_error: 1,
-         reconnecting: 1,
-         ping: 1,
-         pong: 1
-       };
-       
-       /**
-        * Shortcut to `Emitter#emit`.
-        */
-       
-       var emit = Emitter.prototype.emit;
-       
-       /**
-        * `Socket` constructor.
-        *
-        * @api public
-        */
-       
-       function Socket(io, nsp, opts) {
-         this.io = io;
-         this.nsp = nsp;
-         this.json = this; // compat
-         this.ids = 0;
-         this.acks = {};
-         this.receiveBuffer = [];
-         this.sendBuffer = [];
-         this.connected = false;
-         this.disconnected = true;
-         this.flags = {};
-         if (opts && opts.query) {
-           this.query = opts.query;
-         }
-         if (this.io.autoConnect) this.open();
-       }
-       
-       /**
-        * Mix in `Emitter`.
-        */
-       
-       Emitter(Socket.prototype);
-       
-       /**
-        * Subscribe to open, close and packet events
-        *
-        * @api private
-        */
-       
-       Socket.prototype.subEvents = function () {
-         if (this.subs) return;
-       
-         var io = this.io;
-         this.subs = [on(io, 'open', bind(this, 'onopen')), on(io, 'packet', bind(this, 'onpacket')), on(io, 'close', bind(this, 'onclose'))];
-       };
-       
-       /**
-        * "Opens" the socket.
-        *
-        * @api public
-        */
-       
-       Socket.prototype.open = Socket.prototype.connect = function () {
-         if (this.connected) return this;
-       
-         this.subEvents();
-         if (!this.io.reconnecting) this.io.open(); // ensure open
-         if ('open' === this.io.readyState) this.onopen();
-         this.emit('connecting');
-         return this;
-       };
-       
-       /**
-        * Sends a `message` event.
-        *
-        * @return {Socket} self
-        * @api public
-        */
-       
-       Socket.prototype.send = function () {
-         var args = toArray(arguments);
-         args.unshift('message');
-         this.emit.apply(this, args);
-         return this;
-       };
-       
-       /**
-        * Override `emit`.
-        * If the event is in `events`, it's emitted normally.
-        *
-        * @param {String} event name
-        * @return {Socket} self
-        * @api public
-        */
-       
-       Socket.prototype.emit = function (ev) {
-         if (events.hasOwnProperty(ev)) {
-           emit.apply(this, arguments);
-           return this;
-         }
-       
-         var args = toArray(arguments);
-         var packet = {
-           type: (this.flags.binary !== undefined ? this.flags.binary : hasBin(args)) ? parser.BINARY_EVENT : parser.EVENT,
-           data: args
-         };
-       
-         packet.options = {};
-         packet.options.compress = !this.flags || false !== this.flags.compress;
-       
-         // event ack callback
-         if ('function' === typeof args[args.length - 1]) {
-       
-           this.acks[this.ids] = args.pop();
-           packet.id = this.ids++;
-         }
-       
-         if (this.connected) {
-           this.packet(packet);
-         } else {
-           this.sendBuffer.push(packet);
-         }
-       
-         this.flags = {};
-       
-         return this;
-       };
-       
-       /**
-        * Sends a packet.
-        *
-        * @param {Object} packet
-        * @api private
-        */
-       
-       Socket.prototype.packet = function (packet) {
-         packet.nsp = this.nsp;
-         this.io.packet(packet);
-       };
-       
-       /**
-        * Called upon engine `open`.
-        *
-        * @api private
-        */
-       
-       Socket.prototype.onopen = function () {
-       
-         // write connect packet if necessary
-         if ('/' !== this.nsp) {
-           if (this.query) {
-             var query = _typeof(this.query) === 'object' ? parseqs.encode(this.query) : this.query;
-       
-             this.packet({ type: parser.CONNECT, query: query });
-           } else {
-             this.packet({ type: parser.CONNECT });
-           }
-         }
-       };
-       
-       /**
-        * Called upon engine `close`.
-        *
-        * @param {String} reason
-        * @api private
-        */
-       
-       Socket.prototype.onclose = function (reason) {
-       
-         this.connected = false;
-         this.disconnected = true;
-         delete this.id;
-         this.emit('disconnect', reason);
-       };
-       
-       /**
-        * Called with socket packet.
-        *
-        * @param {Object} packet
-        * @api private
-        */
-       
-       Socket.prototype.onpacket = function (packet) {
-         var sameNamespace = packet.nsp === this.nsp;
-         var rootNamespaceError = packet.type === parser.ERROR && packet.nsp === '/';
-       
-         if (!sameNamespace && !rootNamespaceError) return;
-       
-         switch (packet.type) {
-           case parser.CONNECT:
-             this.onconnect();
-             break;
-       
-           case parser.EVENT:
-             this.onevent(packet);
-             break;
-       
-           case parser.BINARY_EVENT:
-             this.onevent(packet);
-             break;
-       
-           case parser.ACK:
-             this.onack(packet);
-             break;
-       
-           case parser.BINARY_ACK:
-             this.onack(packet);
-             break;
-       
-           case parser.DISCONNECT:
-             this.ondisconnect();
-             break;
-       
-           case parser.ERROR:
-             this.emit('error', packet.data);
-             break;
-         }
-       };
-       
-       /**
-        * Called upon a server event.
-        *
-        * @param {Object} packet
-        * @api private
-        */
-       
-       Socket.prototype.onevent = function (packet) {
-         var args = packet.data || [];
-       
-         if (null != packet.id) {
-       
-           args.push(this.ack(packet.id));
-         }
-       
-         if (this.connected) {
-           emit.apply(this, args);
-         } else {
-           this.receiveBuffer.push(args);
-         }
-       };
-       
-       /**
-        * Produces an ack callback to emit with an event.
-        *
-        * @api private
-        */
-       
-       Socket.prototype.ack = function (id) {
-         var self = this;
-         var sent = false;
-         return function () {
-           // prevent double callbacks
-           if (sent) return;
-           sent = true;
-           var args = toArray(arguments);
-       
-           self.packet({
-             type: hasBin(args) ? parser.BINARY_ACK : parser.ACK,
-             id: id,
-             data: args
-           });
-         };
-       };
-       
-       /**
-        * Called upon a server acknowlegement.
-        *
-        * @param {Object} packet
-        * @api private
-        */
-       
-       Socket.prototype.onack = function (packet) {
-         var ack = this.acks[packet.id];
-         if ('function' === typeof ack) {
-       
-           ack.apply(this, packet.data);
-           delete this.acks[packet.id];
-         } else {}
-       };
-       
-       /**
-        * Called upon server connect.
-        *
-        * @api private
-        */
-       
-       Socket.prototype.onconnect = function () {
-         this.connected = true;
-         this.disconnected = false;
-         this.emit('connect');
-         this.emitBuffered();
-       };
-       
-       /**
-        * Emit buffered events (received and emitted).
-        *
-        * @api private
-        */
-       
-       Socket.prototype.emitBuffered = function () {
-         var i;
-         for (i = 0; i < this.receiveBuffer.length; i++) {
-           emit.apply(this, this.receiveBuffer[i]);
-         }
-         this.receiveBuffer = [];
-       
-         for (i = 0; i < this.sendBuffer.length; i++) {
-           this.packet(this.sendBuffer[i]);
-         }
-         this.sendBuffer = [];
-       };
-       
-       /**
-        * Called upon server disconnect.
-        *
-        * @api private
-        */
-       
-       Socket.prototype.ondisconnect = function () {
-       
-         this.destroy();
-         this.onclose('io server disconnect');
-       };
-       
-       /**
-        * Called upon forced client/server side disconnections,
-        * this method ensures the manager stops tracking us and
-        * that reconnections don't get triggered for this.
-        *
-        * @api private.
-        */
-       
-       Socket.prototype.destroy = function () {
-         if (this.subs) {
-           // clean subscriptions to avoid reconnections
-           for (var i = 0; i < this.subs.length; i++) {
-             this.subs[i].destroy();
-           }
-           this.subs = null;
-         }
-       
-         this.io.destroy(this);
-       };
-       
-       /**
-        * Disconnects the socket manually.
-        *
-        * @return {Socket} self
-        * @api public
-        */
-       
-       Socket.prototype.close = Socket.prototype.disconnect = function () {
-         if (this.connected) {
-       
-           this.packet({ type: parser.DISCONNECT });
-         }
-       
-         // remove socket from pool
-         this.destroy();
-       
-         if (this.connected) {
-           // fire events
-           this.onclose('io client disconnect');
-         }
-         return this;
-       };
-       
-       /**
-        * Sets the compress flag.
-        *
-        * @param {Boolean} if `true`, compresses the sending data
-        * @return {Socket} self
-        * @api public
-        */
-       
-       Socket.prototype.compress = function (compress) {
-         this.flags.compress = compress;
-         return this;
-       };
-       
-       /**
-        * Sets the binary flag
-        *
-        * @param {Boolean} whether the emitted data contains binary
-        * @return {Socket} self
-        * @api public
-        */
-       
-       Socket.prototype.binary = function (binary) {
-         this.flags.binary = binary;
-         return this;
-       };
-
-/***/ }),
-/* 35 */
-/***/ (function(module, exports) {
-
-       module.exports = toArray
-       
-       function toArray(list, index) {
-           var array = []
-       
-           index = index || 0
-       
-           for (var i = index || 0; i < list.length; i++) {
-               array[i - index] = list[i]
-           }
-       
-           return array
-       }
-
-
-/***/ }),
-/* 36 */
-/***/ (function(module, exports) {
-
-       "use strict";
-       
-       /**
-        * Module exports.
-        */
-       
-       module.exports = on;
-       
-       /**
-        * Helper for subscriptions.
-        *
-        * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
-        * @param {String} event name
-        * @param {Function} callback
-        * @api public
-        */
-       
-       function on(obj, ev, fn) {
-         obj.on(ev, fn);
-         return {
-           destroy: function destroy() {
-             obj.removeListener(ev, fn);
-           }
-         };
-       }
-
-/***/ }),
-/* 37 */
-/***/ (function(module, exports) {
-
-       /**
-        * Slice reference.
-        */
-       
-       var slice = [].slice;
-       
-       /**
-        * Bind `obj` to `fn`.
-        *
-        * @param {Object} obj
-        * @param {Function|String} fn or string
-        * @return {Function}
-        * @api public
-        */
-       
-       module.exports = function(obj, fn){
-         if ('string' == typeof fn) fn = obj[fn];
-         if ('function' != typeof fn) throw new Error('bind() requires a function');
-         var args = slice.call(arguments, 2);
-         return function(){
-           return fn.apply(obj, args.concat(slice.call(arguments)));
-         }
-       };
-
-
-/***/ }),
-/* 38 */
-/***/ (function(module, exports) {
-
-       
-       /**
-        * Expose `Backoff`.
-        */
-       
-       module.exports = Backoff;
-       
-       /**
-        * Initialize backoff timer with `opts`.
-        *
-        * - `min` initial timeout in milliseconds [100]
-        * - `max` max timeout [10000]
-        * - `jitter` [0]
-        * - `factor` [2]
-        *
-        * @param {Object} opts
-        * @api public
-        */
-       
-       function Backoff(opts) {
-         opts = opts || {};
-         this.ms = opts.min || 100;
-         this.max = opts.max || 10000;
-         this.factor = opts.factor || 2;
-         this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
-         this.attempts = 0;
-       }
-       
-       /**
-        * Return the backoff duration.
-        *
-        * @return {Number}
-        * @api public
-        */
-       
-       Backoff.prototype.duration = function(){
-         var ms = this.ms * Math.pow(this.factor, this.attempts++);
-         if (this.jitter) {
-           var rand =  Math.random();
-           var deviation = Math.floor(rand * this.jitter * ms);
-           ms = (Math.floor(rand * 10) & 1) == 0  ? ms - deviation : ms + deviation;
-         }
-         return Math.min(ms, this.max) | 0;
-       };
-       
-       /**
-        * Reset the number of attempts.
-        *
-        * @api public
-        */
-       
-       Backoff.prototype.reset = function(){
-         this.attempts = 0;
-       };
-       
-       /**
-        * Set the minimum duration
-        *
-        * @api public
-        */
-       
-       Backoff.prototype.setMin = function(min){
-         this.ms = min;
-       };
-       
-       /**
-        * Set the maximum duration
-        *
-        * @api public
-        */
-       
-       Backoff.prototype.setMax = function(max){
-         this.max = max;
-       };
-       
-       /**
-        * Set the jitter
-        *
-        * @api public
-        */
-       
-       Backoff.prototype.setJitter = function(jitter){
-         this.jitter = jitter;
-       };
-       
-
-
-/***/ })
-/******/ ])
-});
-;
-//# sourceMappingURL=socket.io.slim.dev.js.map
+!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.io=e():t.io=e()}(this,(function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={exports:{},id:n,loaded:!1};return t[n].call(o.exports,o,o.exports,r),o.loaded=!0,o.exports}return r.m=t,r.c=e,r.p="",r(0)}([function(t,e,r){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},o=r(1),i=r(4),s=r(9);r(3)("socket.io-client");t.exports=e=c;var a=e.managers={};function c(t,e){"object"===(void 0===t?"undefined":n(t))&&(e=t,t=void 0),e=e||{};var r,i=o(t),c=i.source,p=i.id,h=i.path,u=a[p]&&h in a[p].nsps;return e.forceNew||e["force new connection"]||!1===e.multiplex||u?r=s(c,e):(a[p]||(a[p]=s(c,e)),r=a[p]),i.query&&!e.query&&(e.query=i.query),r.socket(i.path,e)}e.protocol=i.protocol,e.connect=c,e.Manager=r(9),e.Socket=r(34)},function(t,e,r){"use strict";var n=r(2);r(3)("socket.io-client:url");t.exports=function(t,e){var r=t;e=e||"undefined"!=typeof location&&location,null==t&&(t=e.protocol+"//"+e.host);"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?e.protocol+t:e.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==e?e.protocol+"//"+t:"https://"+t),r=n(t));r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443"));r.path=r.path||"/";var o=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+o+":"+r.port,r.href=r.protocol+"://"+o+(e&&e.port===r.port?"":":"+r.port),r}},function(t,e){var r=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,n=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];t.exports=function(t){var e=t,o=t.indexOf("["),i=t.indexOf("]");-1!=o&&-1!=i&&(t=t.substring(0,o)+t.substring(o,i).replace(/:/g,";")+t.substring(i,t.length));for(var s,a,c=r.exec(t||""),p={},h=14;h--;)p[n[h]]=c[h]||"";return-1!=o&&-1!=i&&(p.source=e,p.host=p.host.substring(1,p.host.length-1).replace(/;/g,":"),p.authority=p.authority.replace("[","").replace("]","").replace(/;/g,":"),p.ipv6uri=!0),p.pathNames=function(t,e){var r=/\/{2,9}/g,n=e.replace(r,"/").split("/");"/"!=e.substr(0,1)&&0!==e.length||n.splice(0,1);"/"==e.substr(e.length-1,1)&&n.splice(n.length-1,1);return n}(0,p.path),p.queryKey=(s=p.query,a={},s.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(t,e,r){e&&(a[e]=r)})),a),p}},function(t,e){"use strict";t.exports=function(){return function(){}}},function(t,e,r){r(3)("socket.io-parser");var n=r(5),o=r(6),i=r(7),s=r(8);function a(){}e.protocol=4,e.types=["CONNECT","DISCONNECT","EVENT","ACK","ERROR","BINARY_EVENT","BINARY_ACK"],e.CONNECT=0,e.DISCONNECT=1,e.EVENT=2,e.ACK=3,e.ERROR=4,e.BINARY_EVENT=5,e.BINARY_ACK=6,e.Encoder=a,e.Decoder=h;var c=e.ERROR+'"encode error"';function p(t){var r=""+t.type;if(e.BINARY_EVENT!==t.type&&e.BINARY_ACK!==t.type||(r+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(r+=t.nsp+","),null!=t.id&&(r+=t.id),null!=t.data){var n=function(t){try{return JSON.stringify(t)}catch(t){return!1}}(t.data);if(!1===n)return c;r+=n}return r}function h(){this.reconstructor=null}function u(t){this.reconPack=t,this.buffers=[]}function f(t){return{type:e.ERROR,data:"parser error: "+t}}a.prototype.encode=function(t,r){e.BINARY_EVENT===t.type||e.BINARY_ACK===t.type?function(t,e){function r(t){var r=o.deconstructPacket(t),n=p(r.packet),i=r.buffers;i.unshift(n),e(i)}o.removeBlobs(t,r)}(t,r):r([p(t)])},n(h.prototype),h.prototype.add=function(t){var r;if("string"==typeof t)r=function(t){var r=0,n={type:Number(t.charAt(0))};if(null==e.types[n.type])return f("unknown packet type "+n.type);if(e.BINARY_EVENT===n.type||e.BINARY_ACK===n.type){for(var o="";"-"!==t.charAt(++r)&&(o+=t.charAt(r),r!=t.length););if(o!=Number(o)||"-"!==t.charAt(r))throw new Error("Illegal attachments");n.attachments=Number(o)}if("/"===t.charAt(r+1))for(n.nsp="";++r;){if(","===(a=t.charAt(r)))break;if(n.nsp+=a,r===t.length)break}else n.nsp="/";var s=t.charAt(r+1);if(""!==s&&Number(s)==s){for(n.id="";++r;){var a;if(null==(a=t.charAt(r))||Number(a)!=a){--r;break}if(n.id+=t.charAt(r),r===t.length)break}n.id=Number(n.id)}if(t.charAt(++r)){var c=function(t){try{return JSON.parse(t)}catch(t){return!1}}(t.substr(r));if(!(!1!==c&&(n.type===e.ERROR||i(c))))return f("invalid payload");n.data=c}return n}(t),e.BINARY_EVENT===r.type||e.BINARY_ACK===r.type?(this.reconstructor=new u(r),0===this.reconstructor.reconPack.attachments&&this.emit("decoded",r)):this.emit("decoded",r);else{if(!s(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");(r=this.reconstructor.takeBinaryData(t))&&(this.reconstructor=null,this.emit("decoded",r))}},h.prototype.destroy=function(){this.reconstructor&&this.reconstructor.finishedReconstruction()},u.prototype.takeBinaryData=function(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){var e=o.reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null},u.prototype.finishedReconstruction=function(){this.reconPack=null,this.buffers=[]}},function(t,e,r){function n(t){if(t)return function(t){for(var e in n.prototype)t[e]=n.prototype[e];return t}(t)}t.exports=n,n.prototype.on=n.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},n.prototype.once=function(t,e){function r(){this.off(t,r),e.apply(this,arguments)}return r.fn=e,this.on(t,r),this},n.prototype.off=n.prototype.removeListener=n.prototype.removeAllListeners=n.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,n=this._callbacks["$"+t];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var o=0;o<n.length;o++)if((r=n[o])===e||r.fn===e){n.splice(o,1);break}return 0===n.length&&delete this._callbacks["$"+t],this},n.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),r=this._callbacks["$"+t],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(r){n=0;for(var o=(r=r.slice(0)).length;n<o;++n)r[n].apply(this,e)}return this},n.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},n.prototype.hasListeners=function(t){return!!this.listeners(t).length}},function(t,e,r){var n=r(7),o=r(8),i=Object.prototype.toString,s="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===i.call(Blob),a="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===i.call(File);function c(t,e){if(!t)return t;if(o(t)){var r={_placeholder:!0,num:e.length};return e.push(t),r}if(n(t)){for(var i=new Array(t.length),s=0;s<t.length;s++)i[s]=c(t[s],e);return i}if("object"==typeof t&&!(t instanceof Date)){i={};for(var a in t)i[a]=c(t[a],e);return i}return t}function p(t,e){if(!t)return t;if(t&&t._placeholder)return e[t.num];if(n(t))for(var r=0;r<t.length;r++)t[r]=p(t[r],e);else if("object"==typeof t)for(var o in t)t[o]=p(t[o],e);return t}e.deconstructPacket=function(t){var e=[],r=t.data,n=t;return n.data=c(r,e),n.attachments=e.length,{packet:n,buffers:e}},e.reconstructPacket=function(t,e){return t.data=p(t.data,e),t.attachments=void 0,t},e.removeBlobs=function(t,e){var r=0,i=t;!function t(c,p,h){if(!c)return c;if(s&&c instanceof Blob||a&&c instanceof File){r++;var u=new FileReader;u.onload=function(){h?h[p]=this.result:i=this.result,--r||e(i)},u.readAsArrayBuffer(c)}else if(n(c))for(var f=0;f<c.length;f++)t(c[f],f,c);else if("object"==typeof c&&!o(c))for(var l in c)t(c[l],l,c)}(i),r||e(i)}},function(t,e){var r={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==r.call(t)}},function(t,e){t.exports=function(t){return r&&Buffer.isBuffer(t)||n&&(t instanceof ArrayBuffer||function(t){return"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer}(t))};var r="function"==typeof Buffer&&"function"==typeof Buffer.isBuffer,n="function"==typeof ArrayBuffer},function(t,e,r){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},o=r(10),i=r(34),s=r(5),a=r(4),c=r(36),p=r(37),h=(r(3)("socket.io-client:manager"),r(33)),u=r(38),f=Object.prototype.hasOwnProperty;function l(t,e){if(!(this instanceof l))return new l(t,e);t&&"object"===(void 0===t?"undefined":n(t))&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.nsps={},this.subs=[],this.opts=e,this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(e.randomizationFactor||.5),this.backoff=new u({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this.readyState="closed",this.uri=t,this.connecting=[],this.lastPing=null,this.encoding=!1,this.packetBuffer=[];var r=e.parser||a;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this.autoConnect=!1!==e.autoConnect,this.autoConnect&&this.open()}t.exports=l,l.prototype.emitAll=function(){for(var t in this.emit.apply(this,arguments),this.nsps)f.call(this.nsps,t)&&this.nsps[t].emit.apply(this.nsps[t],arguments)},l.prototype.updateSocketIds=function(){for(var t in this.nsps)f.call(this.nsps,t)&&(this.nsps[t].id=this.generateId(t))},l.prototype.generateId=function(t){return("/"===t?"":t+"#")+this.engine.id},s(l.prototype),l.prototype.reconnection=function(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection},l.prototype.reconnectionAttempts=function(t){return arguments.length?(this._reconnectionAttempts=t,this):this._reconnectionAttempts},l.prototype.reconnectionDelay=function(t){return arguments.length?(this._reconnectionDelay=t,this.backoff&&this.backoff.setMin(t),this):this._reconnectionDelay},l.prototype.randomizationFactor=function(t){return arguments.length?(this._randomizationFactor=t,this.backoff&&this.backoff.setJitter(t),this):this._randomizationFactor},l.prototype.reconnectionDelayMax=function(t){return arguments.length?(this._reconnectionDelayMax=t,this.backoff&&this.backoff.setMax(t),this):this._reconnectionDelayMax},l.prototype.timeout=function(t){return arguments.length?(this._timeout=t,this):this._timeout},l.prototype.maybeReconnectOnOpen=function(){!this.reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()},l.prototype.open=l.prototype.connect=function(t,e){if(~this.readyState.indexOf("open"))return this;this.engine=o(this.uri,this.opts);var r=this.engine,n=this;this.readyState="opening",this.skipReconnect=!1;var i=c(r,"open",(function(){n.onopen(),t&&t()})),s=c(r,"error",(function(e){if(n.cleanup(),n.readyState="closed",n.emitAll("connect_error",e),t){var r=new Error("Connection error");r.data=e,t(r)}else n.maybeReconnectOnOpen()}));if(!1!==this._timeout){var a=this._timeout;0===a&&i.destroy();var p=setTimeout((function(){i.destroy(),r.close(),r.emit("error","timeout"),n.emitAll("connect_timeout",a)}),a);this.subs.push({destroy:function(){clearTimeout(p)}})}return this.subs.push(i),this.subs.push(s),this},l.prototype.onopen=function(){this.cleanup(),this.readyState="open",this.emit("open");var t=this.engine;this.subs.push(c(t,"data",p(this,"ondata"))),this.subs.push(c(t,"ping",p(this,"onping"))),this.subs.push(c(t,"pong",p(this,"onpong"))),this.subs.push(c(t,"error",p(this,"onerror"))),this.subs.push(c(t,"close",p(this,"onclose"))),this.subs.push(c(this.decoder,"decoded",p(this,"ondecoded")))},l.prototype.onping=function(){this.lastPing=new Date,this.emitAll("ping")},l.prototype.onpong=function(){this.emitAll("pong",new Date-this.lastPing)},l.prototype.ondata=function(t){this.decoder.add(t)},l.prototype.ondecoded=function(t){this.emit("packet",t)},l.prototype.onerror=function(t){this.emitAll("error",t)},l.prototype.socket=function(t,e){var r=this.nsps[t];if(!r){r=new i(this,t,e),this.nsps[t]=r;var n=this;r.on("connecting",o),r.on("connect",(function(){r.id=n.generateId(t)})),this.autoConnect&&o()}function o(){~h(n.connecting,r)||n.connecting.push(r)}return r},l.prototype.destroy=function(t){var e=h(this.connecting,t);~e&&this.connecting.splice(e,1),this.connecting.length||this.close()},l.prototype.packet=function(t){var e=this;t.query&&0===t.type&&(t.nsp+="?"+t.query),e.encoding?e.packetBuffer.push(t):(e.encoding=!0,this.encoder.encode(t,(function(r){for(var n=0;n<r.length;n++)e.engine.write(r[n],t.options);e.encoding=!1,e.processPacketQueue()})))},l.prototype.processPacketQueue=function(){if(this.packetBuffer.length>0&&!this.encoding){var t=this.packetBuffer.shift();this.packet(t)}},l.prototype.cleanup=function(){for(var t=this.subs.length,e=0;e<t;e++){this.subs.shift().destroy()}this.packetBuffer=[],this.encoding=!1,this.lastPing=null,this.decoder.destroy()},l.prototype.close=l.prototype.disconnect=function(){this.skipReconnect=!0,this.reconnecting=!1,"opening"===this.readyState&&this.cleanup(),this.backoff.reset(),this.readyState="closed",this.engine&&this.engine.close()},l.prototype.onclose=function(t){this.cleanup(),this.backoff.reset(),this.readyState="closed",this.emit("close",t),this._reconnection&&!this.skipReconnect&&this.reconnect()},l.prototype.reconnect=function(){if(this.reconnecting||this.skipReconnect)return this;var t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitAll("reconnect_failed"),this.reconnecting=!1;else{var e=this.backoff.duration();this.reconnecting=!0;var r=setTimeout((function(){t.skipReconnect||(t.emitAll("reconnect_attempt",t.backoff.attempts),t.emitAll("reconnecting",t.backoff.attempts),t.skipReconnect||t.open((function(e){e?(t.reconnecting=!1,t.reconnect(),t.emitAll("reconnect_error",e.data)):t.onreconnect()})))}),e);this.subs.push({destroy:function(){clearTimeout(r)}})}},l.prototype.onreconnect=function(){var t=this.backoff.attempts;this.reconnecting=!1,this.backoff.reset(),this.updateSocketIds(),this.emitAll("reconnect",t)}},function(t,e,r){t.exports=r(11),t.exports.parser=r(19)},function(t,e,r){var n=r(12),o=r(5),i=(r(3)("engine.io-client:socket"),r(33)),s=r(19),a=r(2),c=r(27);function p(t,e){if(!(this instanceof p))return new p(t,e);e=e||{},t&&"object"==typeof t&&(e=t,t=null),t?(t=a(t),e.hostname=t.host,e.secure="https"===t.protocol||"wss"===t.protocol,e.port=t.port,t.query&&(e.query=t.query)):e.host&&(e.hostname=a(e.host).host),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.agent=e.agent||!1,this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?443:80),this.query=e.query||{},"string"==typeof this.query&&(this.query=c.decode(this.query)),this.upgrade=!1!==e.upgrade,this.path=(e.path||"/engine.io").replace(/\/$/,"")+"/",this.forceJSONP=!!e.forceJSONP,this.jsonp=!1!==e.jsonp,this.forceBase64=!!e.forceBase64,this.enablesXDR=!!e.enablesXDR,this.withCredentials=!1!==e.withCredentials,this.timestampParam=e.timestampParam||"t",this.timestampRequests=e.timestampRequests,this.transports=e.transports||["polling","websocket"],this.transportOptions=e.transportOptions||{},this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.policyPort=e.policyPort||843,this.rememberUpgrade=e.rememberUpgrade||!1,this.binaryType=null,this.onlyBinaryUpgrades=e.onlyBinaryUpgrades,this.perMessageDeflate=!1!==e.perMessageDeflate&&(e.perMessageDeflate||{}),!0===this.perMessageDeflate&&(this.perMessageDeflate={}),this.perMessageDeflate&&null==this.perMessageDeflate.threshold&&(this.perMessageDeflate.threshold=1024),this.pfx=e.pfx||null,this.key=e.key||null,this.passphrase=e.passphrase||null,this.cert=e.cert||null,this.ca=e.ca||null,this.ciphers=e.ciphers||null,this.rejectUnauthorized=void 0===e.rejectUnauthorized||e.rejectUnauthorized,this.forceNode=!!e.forceNode,this.isReactNative="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),("undefined"==typeof self||this.isReactNative)&&(e.extraHeaders&&Object.keys(e.extraHeaders).length>0&&(this.extraHeaders=e.extraHeaders),e.localAddress&&(this.localAddress=e.localAddress)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingIntervalTimer=null,this.pingTimeoutTimer=null,this.open()}t.exports=p,p.priorWebsocketSuccess=!1,o(p.prototype),p.protocol=s.protocol,p.Socket=p,p.Transport=r(18),p.transports=r(12),p.parser=r(19),p.prototype.createTransport=function(t){var e=function(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);return e}(this.query);e.EIO=s.protocol,e.transport=t;var r=this.transportOptions[t]||{};return this.id&&(e.sid=this.id),new n[t]({query:e,socket:this,agent:r.agent||this.agent,hostname:r.hostname||this.hostname,port:r.port||this.port,secure:r.secure||this.secure,path:r.path||this.path,forceJSONP:r.forceJSONP||this.forceJSONP,jsonp:r.jsonp||this.jsonp,forceBase64:r.forceBase64||this.forceBase64,enablesXDR:r.enablesXDR||this.enablesXDR,withCredentials:r.withCredentials||this.withCredentials,timestampRequests:r.timestampRequests||this.timestampRequests,timestampParam:r.timestampParam||this.timestampParam,policyPort:r.policyPort||this.policyPort,pfx:r.pfx||this.pfx,key:r.key||this.key,passphrase:r.passphrase||this.passphrase,cert:r.cert||this.cert,ca:r.ca||this.ca,ciphers:r.ciphers||this.ciphers,rejectUnauthorized:r.rejectUnauthorized||this.rejectUnauthorized,perMessageDeflate:r.perMessageDeflate||this.perMessageDeflate,extraHeaders:r.extraHeaders||this.extraHeaders,forceNode:r.forceNode||this.forceNode,localAddress:r.localAddress||this.localAddress,requestTimeout:r.requestTimeout||this.requestTimeout,protocols:r.protocols||void 0,isReactNative:this.isReactNative})},p.prototype.open=function(){var t;if(this.rememberUpgrade&&p.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length){var e=this;return void setTimeout((function(){e.emit("error","No transports available")}),0)}t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(t){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)},p.prototype.setTransport=function(t){var e=this;this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",(function(){e.onDrain()})).on("packet",(function(t){e.onPacket(t)})).on("error",(function(t){e.onError(t)})).on("close",(function(){e.onClose("transport close")}))},p.prototype.probe=function(t){var e=this.createTransport(t,{probe:1}),r=!1,n=this;function o(){if(n.onlyBinaryUpgrades){var t=!this.supportsBinary&&n.transport.supportsBinary;r=r||t}r||(e.send([{type:"ping",data:"probe"}]),e.once("packet",(function(t){if(!r)if("pong"===t.type&&"probe"===t.data){if(n.upgrading=!0,n.emit("upgrading",e),!e)return;p.priorWebsocketSuccess="websocket"===e.name,n.transport.pause((function(){r||"closed"!==n.readyState&&(u(),n.setTransport(e),e.send([{type:"upgrade"}]),n.emit("upgrade",e),e=null,n.upgrading=!1,n.flush())}))}else{var o=new Error("probe error");o.transport=e.name,n.emit("upgradeError",o)}})))}function i(){r||(r=!0,u(),e.close(),e=null)}function s(t){var r=new Error("probe error: "+t);r.transport=e.name,i(),n.emit("upgradeError",r)}function a(){s("transport closed")}function c(){s("socket closed")}function h(t){e&&t.name!==e.name&&i()}function u(){e.removeListener("open",o),e.removeListener("error",s),e.removeListener("close",a),n.removeListener("close",c),n.removeListener("upgrading",h)}p.priorWebsocketSuccess=!1,e.once("open",o),e.once("error",s),e.once("close",a),this.once("close",c),this.once("upgrading",h),e.open()},p.prototype.onOpen=function(){if(this.readyState="open",p.priorWebsocketSuccess="websocket"===this.transport.name,this.emit("open"),this.flush(),"open"===this.readyState&&this.upgrade&&this.transport.pause)for(var t=0,e=this.upgrades.length;t<e;t++)this.probe(this.upgrades[t])},p.prototype.onPacket=function(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emit("packet",t),this.emit("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"pong":this.setPing(),this.emit("pong");break;case"error":var e=new Error("server error");e.code=t.data,this.onError(e);break;case"message":this.emit("data",t.data),this.emit("message",t.data)}},p.prototype.onHandshake=function(t){this.emit("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this.upgrades=this.filterUpgrades(t.upgrades),this.pingInterval=t.pingInterval,this.pingTimeout=t.pingTimeout,this.onOpen(),"closed"!==this.readyState&&(this.setPing(),this.removeListener("heartbeat",this.onHeartbeat),this.on("heartbeat",this.onHeartbeat))},p.prototype.onHeartbeat=function(t){clearTimeout(this.pingTimeoutTimer);var e=this;e.pingTimeoutTimer=setTimeout((function(){"closed"!==e.readyState&&e.onClose("ping timeout")}),t||e.pingInterval+e.pingTimeout)},p.prototype.setPing=function(){var t=this;clearTimeout(t.pingIntervalTimer),t.pingIntervalTimer=setTimeout((function(){t.ping(),t.onHeartbeat(t.pingTimeout)}),t.pingInterval)},p.prototype.ping=function(){var t=this;this.sendPacket("ping",(function(){t.emit("ping")}))},p.prototype.onDrain=function(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emit("drain"):this.flush()},p.prototype.flush=function(){"closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length&&(this.transport.send(this.writeBuffer),this.prevBufferLen=this.writeBuffer.length,this.emit("flush"))},p.prototype.write=p.prototype.send=function(t,e,r){return this.sendPacket("message",t,e,r),this},p.prototype.sendPacket=function(t,e,r,n){if("function"==typeof e&&(n=e,e=void 0),"function"==typeof r&&(n=r,r=null),"closing"!==this.readyState&&"closed"!==this.readyState){(r=r||{}).compress=!1!==r.compress;var o={type:t,data:e,options:r};this.emit("packetCreate",o),this.writeBuffer.push(o),n&&this.once("flush",n),this.flush()}},p.prototype.close=function(){if("opening"===this.readyState||"open"===this.readyState){this.readyState="closing";var t=this;this.writeBuffer.length?this.once("drain",(function(){this.upgrading?n():e()})):this.upgrading?n():e()}function e(){t.onClose("forced close"),t.transport.close()}function r(){t.removeListener("upgrade",r),t.removeListener("upgradeError",r),e()}function n(){t.once("upgrade",r),t.once("upgradeError",r)}return this},p.prototype.onError=function(t){p.priorWebsocketSuccess=!1,this.emit("error",t),this.onClose("transport error",t)},p.prototype.onClose=function(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){clearTimeout(this.pingIntervalTimer),clearTimeout(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),this.readyState="closed",this.id=null,this.emit("close",t,e),this.writeBuffer=[],this.prevBufferLen=0}},p.prototype.filterUpgrades=function(t){for(var e=[],r=0,n=t.length;r<n;r++)~i(this.transports,t[r])&&e.push(t[r]);return e}},function(t,e,r){var n=r(13),o=r(16),i=r(30),s=r(31);e.polling=function(t){var e=!1,r=!1,s=!1!==t.jsonp;if("undefined"!=typeof location){var a="https:"===location.protocol,c=location.port;c||(c=a?443:80),e=t.hostname!==location.hostname||c!==t.port,r=t.secure!==a}if(t.xdomain=e,t.xscheme=r,"open"in new n(t)&&!t.forceJSONP)return new o(t);if(!s)throw new Error("JSONP disabled");return new i(t)},e.websocket=s},function(t,e,r){var n=r(14),o=r(15);t.exports=function(t){var e=t.xdomain,r=t.xscheme,i=t.enablesXDR;try{if("undefined"!=typeof XMLHttpRequest&&(!e||n))return new XMLHttpRequest}catch(t){}try{if("undefined"!=typeof XDomainRequest&&!r&&i)return new XDomainRequest}catch(t){}if(!e)try{return new(o[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}},function(t,e){try{t.exports="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){t.exports=!1}},function(t,e){t.exports="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")()},function(t,e,r){var n=r(13),o=r(17),i=r(5),s=r(28),a=(r(3)("engine.io-client:polling-xhr"),r(15));function c(){}function p(t){if(o.call(this,t),this.requestTimeout=t.requestTimeout,this.extraHeaders=t.extraHeaders,"undefined"!=typeof location){var e="https:"===location.protocol,r=location.port;r||(r=e?443:80),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||r!==t.port,this.xs=t.secure!==e}}function h(t){this.method=t.method||"GET",this.uri=t.uri,this.xd=!!t.xd,this.xs=!!t.xs,this.async=!1!==t.async,this.data=void 0!==t.data?t.data:null,this.agent=t.agent,this.isBinary=t.isBinary,this.supportsBinary=t.supportsBinary,this.enablesXDR=t.enablesXDR,this.withCredentials=t.withCredentials,this.requestTimeout=t.requestTimeout,this.pfx=t.pfx,this.key=t.key,this.passphrase=t.passphrase,this.cert=t.cert,this.ca=t.ca,this.ciphers=t.ciphers,this.rejectUnauthorized=t.rejectUnauthorized,this.extraHeaders=t.extraHeaders,this.create()}if(t.exports=p,t.exports.Request=h,s(p,o),p.prototype.supportsBinary=!0,p.prototype.request=function(t){return(t=t||{}).uri=this.uri(),t.xd=this.xd,t.xs=this.xs,t.agent=this.agent||!1,t.supportsBinary=this.supportsBinary,t.enablesXDR=this.enablesXDR,t.withCredentials=this.withCredentials,t.pfx=this.pfx,t.key=this.key,t.passphrase=this.passphrase,t.cert=this.cert,t.ca=this.ca,t.ciphers=this.ciphers,t.rejectUnauthorized=this.rejectUnauthorized,t.requestTimeout=this.requestTimeout,t.extraHeaders=this.extraHeaders,new h(t)},p.prototype.doWrite=function(t,e){var r="string"!=typeof t&&void 0!==t,n=this.request({method:"POST",data:t,isBinary:r}),o=this;n.on("success",e),n.on("error",(function(t){o.onError("xhr post error",t)})),this.sendXhr=n},p.prototype.doPoll=function(){var t=this.request(),e=this;t.on("data",(function(t){e.onData(t)})),t.on("error",(function(t){e.onError("xhr poll error",t)})),this.pollXhr=t},i(h.prototype),h.prototype.create=function(){var t={agent:this.agent,xdomain:this.xd,xscheme:this.xs,enablesXDR:this.enablesXDR};t.pfx=this.pfx,t.key=this.key,t.passphrase=this.passphrase,t.cert=this.cert,t.ca=this.ca,t.ciphers=this.ciphers,t.rejectUnauthorized=this.rejectUnauthorized;var e=this.xhr=new n(t),r=this;try{e.open(this.method,this.uri,this.async);try{if(this.extraHeaders)for(var o in e.setDisableHeaderCheck&&e.setDisableHeaderCheck(!0),this.extraHeaders)this.extraHeaders.hasOwnProperty(o)&&e.setRequestHeader(o,this.extraHeaders[o])}catch(t){}if("POST"===this.method)try{this.isBinary?e.setRequestHeader("Content-type","application/octet-stream"):e.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{e.setRequestHeader("Accept","*/*")}catch(t){}"withCredentials"in e&&(e.withCredentials=this.withCredentials),this.requestTimeout&&(e.timeout=this.requestTimeout),this.hasXDR()?(e.onload=function(){r.onLoad()},e.onerror=function(){r.onError(e.responseText)}):e.onreadystatechange=function(){if(2===e.readyState)try{var t=e.getResponseHeader("Content-Type");(r.supportsBinary&&"application/octet-stream"===t||"application/octet-stream; charset=UTF-8"===t)&&(e.responseType="arraybuffer")}catch(t){}4===e.readyState&&(200===e.status||1223===e.status?r.onLoad():setTimeout((function(){r.onError("number"==typeof e.status?e.status:0)}),0))},e.send(this.data)}catch(t){return void setTimeout((function(){r.onError(t)}),0)}"undefined"!=typeof document&&(this.index=h.requestsCount++,h.requests[this.index]=this)},h.prototype.onSuccess=function(){this.emit("success"),this.cleanup()},h.prototype.onData=function(t){this.emit("data",t),this.onSuccess()},h.prototype.onError=function(t){this.emit("error",t),this.cleanup(!0)},h.prototype.cleanup=function(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.hasXDR()?this.xhr.onload=this.xhr.onerror=c:this.xhr.onreadystatechange=c,t)try{this.xhr.abort()}catch(t){}"undefined"!=typeof document&&delete h.requests[this.index],this.xhr=null}},h.prototype.onLoad=function(){var t;try{var e;try{e=this.xhr.getResponseHeader("Content-Type")}catch(t){}t=("application/octet-stream"===e||"application/octet-stream; charset=UTF-8"===e)&&this.xhr.response||this.xhr.responseText}catch(t){this.onError(t)}null!=t&&this.onData(t)},h.prototype.hasXDR=function(){return"undefined"!=typeof XDomainRequest&&!this.xs&&this.enablesXDR},h.prototype.abort=function(){this.cleanup()},h.requestsCount=0,h.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",u);else if("function"==typeof addEventListener){addEventListener("onpagehide"in a?"pagehide":"unload",u,!1)}function u(){for(var t in h.requests)h.requests.hasOwnProperty(t)&&h.requests[t].abort()}},function(t,e,r){var n=r(18),o=r(27),i=r(19),s=r(28),a=r(29);r(3)("engine.io-client:polling");t.exports=p;var c=null!=new(r(13))({xdomain:!1}).responseType;function p(t){var e=t&&t.forceBase64;c&&!e||(this.supportsBinary=!1),n.call(this,t)}s(p,n),p.prototype.name="polling",p.prototype.doOpen=function(){this.poll()},p.prototype.pause=function(t){var e=this;function r(){e.readyState="paused",t()}if(this.readyState="pausing",this.polling||!this.writable){var n=0;this.polling&&(n++,this.once("pollComplete",(function(){--n||r()}))),this.writable||(n++,this.once("drain",(function(){--n||r()})))}else r()},p.prototype.poll=function(){this.polling=!0,this.doPoll(),this.emit("poll")},p.prototype.onData=function(t){var e=this;i.decodePayload(t,this.socket.binaryType,(function(t,r,n){if("opening"===e.readyState&&"open"===t.type&&e.onOpen(),"close"===t.type)return e.onClose(),!1;e.onPacket(t)})),"closed"!==this.readyState&&(this.polling=!1,this.emit("pollComplete"),"open"===this.readyState&&this.poll())},p.prototype.doClose=function(){var t=this;function e(){t.write([{type:"close"}])}"open"===this.readyState?e():this.once("open",e)},p.prototype.write=function(t){var e=this;this.writable=!1;var r=function(){e.writable=!0,e.emit("drain")};i.encodePayload(t,this.supportsBinary,(function(t){e.doWrite(t,r)}))},p.prototype.uri=function(){var t=this.query||{},e=this.secure?"https":"http",r="";return!1!==this.timestampRequests&&(t[this.timestampParam]=a()),this.supportsBinary||t.sid||(t.b64=1),t=o.encode(t),this.port&&("https"===e&&443!==Number(this.port)||"http"===e&&80!==Number(this.port))&&(r=":"+this.port),t.length&&(t="?"+t),e+"://"+(-1!==this.hostname.indexOf(":")?"["+this.hostname+"]":this.hostname)+r+this.path+t}},function(t,e,r){var n=r(19),o=r(5);function i(t){this.path=t.path,this.hostname=t.hostname,this.port=t.port,this.secure=t.secure,this.query=t.query,this.timestampParam=t.timestampParam,this.timestampRequests=t.timestampRequests,this.readyState="",this.agent=t.agent||!1,this.socket=t.socket,this.enablesXDR=t.enablesXDR,this.withCredentials=t.withCredentials,this.pfx=t.pfx,this.key=t.key,this.passphrase=t.passphrase,this.cert=t.cert,this.ca=t.ca,this.ciphers=t.ciphers,this.rejectUnauthorized=t.rejectUnauthorized,this.forceNode=t.forceNode,this.isReactNative=t.isReactNative,this.extraHeaders=t.extraHeaders,this.localAddress=t.localAddress}t.exports=i,o(i.prototype),i.prototype.onError=function(t,e){var r=new Error(t);return r.type="TransportError",r.description=e,this.emit("error",r),this},i.prototype.open=function(){return"closed"!==this.readyState&&""!==this.readyState||(this.readyState="opening",this.doOpen()),this},i.prototype.close=function(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this},i.prototype.send=function(t){if("open"!==this.readyState)throw new Error("Transport not open");this.write(t)},i.prototype.onOpen=function(){this.readyState="open",this.writable=!0,this.emit("open")},i.prototype.onData=function(t){var e=n.decodePacket(t,this.socket.binaryType);this.onPacket(e)},i.prototype.onPacket=function(t){this.emit("packet",t)},i.prototype.onClose=function(){this.readyState="closed",this.emit("close")}},function(t,e,r){var n,o=r(20),i=r(21),s=r(22),a=r(23),c=r(24);"undefined"!=typeof ArrayBuffer&&(n=r(25));var p="undefined"!=typeof navigator&&/Android/i.test(navigator.userAgent),h="undefined"!=typeof navigator&&/PhantomJS/i.test(navigator.userAgent),u=p||h;e.protocol=3;var f=e.packets={open:0,close:1,ping:2,pong:3,message:4,upgrade:5,noop:6},l=o(f),d={type:"error",data:"parser error"},y=r(26);function m(t,e,r){for(var n=new Array(t.length),o=a(t.length,r),i=function(t,r,o){e(r,(function(e,r){n[t]=r,o(e,n)}))},s=0;s<t.length;s++)i(s,t[s],o)}e.encodePacket=function(t,r,n,o){"function"==typeof r&&(o=r,r=!1),"function"==typeof n&&(o=n,n=null);var i=void 0===t.data?void 0:t.data.buffer||t.data;if("undefined"!=typeof ArrayBuffer&&i instanceof ArrayBuffer)return function(t,r,n){if(!r)return e.encodeBase64Packet(t,n);var o=t.data,i=new Uint8Array(o),s=new Uint8Array(1+o.byteLength);s[0]=f[t.type];for(var a=0;a<i.length;a++)s[a+1]=i[a];return n(s.buffer)}(t,r,o);if(void 0!==y&&i instanceof y)return function(t,r,n){if(!r)return e.encodeBase64Packet(t,n);if(u)return function(t,r,n){if(!r)return e.encodeBase64Packet(t,n);var o=new FileReader;return o.onload=function(){e.encodePacket({type:t.type,data:o.result},r,!0,n)},o.readAsArrayBuffer(t.data)}(t,r,n);var o=new Uint8Array(1);o[0]=f[t.type];var i=new y([o.buffer,t.data]);return n(i)}(t,r,o);if(i&&i.base64)return function(t,r){var n="b"+e.packets[t.type]+t.data.data;return r(n)}(t,o);var s=f[t.type];return void 0!==t.data&&(s+=n?c.encode(String(t.data),{strict:!1}):String(t.data)),o(""+s)},e.encodeBase64Packet=function(t,r){var n,o="b"+e.packets[t.type];if(void 0!==y&&t.data instanceof y){var i=new FileReader;return i.onload=function(){var t=i.result.split(",")[1];r(o+t)},i.readAsDataURL(t.data)}try{n=String.fromCharCode.apply(null,new Uint8Array(t.data))}catch(e){for(var s=new Uint8Array(t.data),a=new Array(s.length),c=0;c<s.length;c++)a[c]=s[c];n=String.fromCharCode.apply(null,a)}return o+=btoa(n),r(o)},e.decodePacket=function(t,r,n){if(void 0===t)return d;if("string"==typeof t){if("b"===t.charAt(0))return e.decodeBase64Packet(t.substr(1),r);if(n&&!1===(t=function(t){try{t=c.decode(t,{strict:!1})}catch(t){return!1}return t}(t)))return d;var o=t.charAt(0);return Number(o)==o&&l[o]?t.length>1?{type:l[o],data:t.substring(1)}:{type:l[o]}:d}o=new Uint8Array(t)[0];var i=s(t,1);return y&&"blob"===r&&(i=new y([i])),{type:l[o],data:i}},e.decodeBase64Packet=function(t,e){var r=l[t.charAt(0)];if(!n)return{type:r,data:{base64:!0,data:t.substr(1)}};var o=n.decode(t.substr(1));return"blob"===e&&y&&(o=new y([o])),{type:r,data:o}},e.encodePayload=function(t,r,n){"function"==typeof r&&(n=r,r=null);var o=i(t);if(r&&o)return y&&!u?e.encodePayloadAsBlob(t,n):e.encodePayloadAsArrayBuffer(t,n);if(!t.length)return n("0:");m(t,(function(t,n){e.encodePacket(t,!!o&&r,!1,(function(t){n(null,function(t){return t.length+":"+t}(t))}))}),(function(t,e){return n(e.join(""))}))},e.decodePayload=function(t,r,n){if("string"!=typeof t)return e.decodePayloadAsBinary(t,r,n);var o;if("function"==typeof r&&(n=r,r=null),""===t)return n(d,0,1);for(var i,s,a="",c=0,p=t.length;c<p;c++){var h=t.charAt(c);if(":"===h){if(""===a||a!=(i=Number(a)))return n(d,0,1);if(a!=(s=t.substr(c+1,i)).length)return n(d,0,1);if(s.length){if(o=e.decodePacket(s,r,!1),d.type===o.type&&d.data===o.data)return n(d,0,1);if(!1===n(o,c+i,p))return}c+=i,a=""}else a+=h}return""!==a?n(d,0,1):void 0},e.encodePayloadAsArrayBuffer=function(t,r){if(!t.length)return r(new ArrayBuffer(0));m(t,(function(t,r){e.encodePacket(t,!0,!0,(function(t){return r(null,t)}))}),(function(t,e){var n=e.reduce((function(t,e){var r;return t+(r="string"==typeof e?e.length:e.byteLength).toString().length+r+2}),0),o=new Uint8Array(n),i=0;return e.forEach((function(t){var e="string"==typeof t,r=t;if(e){for(var n=new Uint8Array(t.length),s=0;s<t.length;s++)n[s]=t.charCodeAt(s);r=n.buffer}o[i++]=e?0:1;var a=r.byteLength.toString();for(s=0;s<a.length;s++)o[i++]=parseInt(a[s]);o[i++]=255;for(n=new Uint8Array(r),s=0;s<n.length;s++)o[i++]=n[s]})),r(o.buffer)}))},e.encodePayloadAsBlob=function(t,r){m(t,(function(t,r){e.encodePacket(t,!0,!0,(function(t){var e=new Uint8Array(1);if(e[0]=1,"string"==typeof t){for(var n=new Uint8Array(t.length),o=0;o<t.length;o++)n[o]=t.charCodeAt(o);t=n.buffer,e[0]=0}var i=(t instanceof ArrayBuffer?t.byteLength:t.size).toString(),s=new Uint8Array(i.length+1);for(o=0;o<i.length;o++)s[o]=parseInt(i[o]);if(s[i.length]=255,y){var a=new y([e.buffer,s.buffer,t]);r(null,a)}}))}),(function(t,e){return r(new y(e))}))},e.decodePayloadAsBinary=function(t,r,n){"function"==typeof r&&(n=r,r=null);for(var o=t,i=[];o.byteLength>0;){for(var a=new Uint8Array(o),c=0===a[0],p="",h=1;255!==a[h];h++){if(p.length>310)return n(d,0,1);p+=a[h]}o=s(o,2+p.length),p=parseInt(p);var u=s(o,0,p);if(c)try{u=String.fromCharCode.apply(null,new Uint8Array(u))}catch(t){var f=new Uint8Array(u);u="";for(h=0;h<f.length;h++)u+=String.fromCharCode(f[h])}i.push(u),o=s(o,p)}var l=i.length;i.forEach((function(t,o){n(e.decodePacket(t,r,!0),o,l)}))}},function(t,e){t.exports=Object.keys||function(t){var e=[],r=Object.prototype.hasOwnProperty;for(var n in t)r.call(t,n)&&e.push(n);return e}},function(t,e,r){var n=r(7),o=Object.prototype.toString,i="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===o.call(Blob),s="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===o.call(File);t.exports=function t(e){if(!e||"object"!=typeof e)return!1;if(n(e)){for(var r=0,o=e.length;r<o;r++)if(t(e[r]))return!0;return!1}if("function"==typeof Buffer&&Buffer.isBuffer&&Buffer.isBuffer(e)||"function"==typeof ArrayBuffer&&e instanceof ArrayBuffer||i&&e instanceof Blob||s&&e instanceof File)return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return t(e.toJSON(),!0);for(var a in e)if(Object.prototype.hasOwnProperty.call(e,a)&&t(e[a]))return!0;return!1}},function(t,e){t.exports=function(t,e,r){var n=t.byteLength;if(e=e||0,r=r||n,t.slice)return t.slice(e,r);if(e<0&&(e+=n),r<0&&(r+=n),r>n&&(r=n),e>=n||e>=r||0===n)return new ArrayBuffer(0);for(var o=new Uint8Array(t),i=new Uint8Array(r-e),s=e,a=0;s<r;s++,a++)i[a]=o[s];return i.buffer}},function(t,e){function r(){}t.exports=function(t,e,n){var o=!1;return n=n||r,i.count=t,0===t?e():i;function i(t,r){if(i.count<=0)throw new Error("after called too many times");--i.count,t?(o=!0,e(t),e=n):0!==i.count||o||e(null,r)}}},function(t,e){
+/*! https://mths.be/utf8js v2.1.2 by @mathias */
+var r,n,o,i=String.fromCharCode;function s(t){for(var e,r,n=[],o=0,i=t.length;o<i;)(e=t.charCodeAt(o++))>=55296&&e<=56319&&o<i?56320==(64512&(r=t.charCodeAt(o++)))?n.push(((1023&e)<<10)+(1023&r)+65536):(n.push(e),o--):n.push(e);return n}function a(t,e){if(t>=55296&&t<=57343){if(e)throw Error("Lone surrogate U+"+t.toString(16).toUpperCase()+" is not a scalar value");return!1}return!0}function c(t,e){return i(t>>e&63|128)}function p(t,e){if(0==(4294967168&t))return i(t);var r="";return 0==(4294965248&t)?r=i(t>>6&31|192):0==(4294901760&t)?(a(t,e)||(t=65533),r=i(t>>12&15|224),r+=c(t,6)):0==(4292870144&t)&&(r=i(t>>18&7|240),r+=c(t,12),r+=c(t,6)),r+=i(63&t|128)}function h(){if(o>=n)throw Error("Invalid byte index");var t=255&r[o];if(o++,128==(192&t))return 63&t;throw Error("Invalid continuation byte")}function u(t){var e,i;if(o>n)throw Error("Invalid byte index");if(o==n)return!1;if(e=255&r[o],o++,0==(128&e))return e;if(192==(224&e)){if((i=(31&e)<<6|h())>=128)return i;throw Error("Invalid continuation byte")}if(224==(240&e)){if((i=(15&e)<<12|h()<<6|h())>=2048)return a(i,t)?i:65533;throw Error("Invalid continuation byte")}if(240==(248&e)&&(i=(7&e)<<18|h()<<12|h()<<6|h())>=65536&&i<=1114111)return i;throw Error("Invalid UTF-8 detected")}t.exports={version:"2.1.2",encode:function(t,e){for(var r=!1!==(e=e||{}).strict,n=s(t),o=n.length,i=-1,a="";++i<o;)a+=p(n[i],r);return a},decode:function(t,e){var a=!1!==(e=e||{}).strict;r=s(t),n=r.length,o=0;for(var c,p=[];!1!==(c=u(a));)p.push(c);return function(t){for(var e,r=t.length,n=-1,o="";++n<r;)(e=t[n])>65535&&(o+=i((e-=65536)>>>10&1023|55296),e=56320|1023&e),o+=i(e);return o}(p)}}},function(t,e){!function(t){"use strict";e.encode=function(e){var r,n=new Uint8Array(e),o=n.length,i="";for(r=0;r<o;r+=3)i+=t[n[r]>>2],i+=t[(3&n[r])<<4|n[r+1]>>4],i+=t[(15&n[r+1])<<2|n[r+2]>>6],i+=t[63&n[r+2]];return o%3==2?i=i.substring(0,i.length-1)+"=":o%3==1&&(i=i.substring(0,i.length-2)+"=="),i},e.decode=function(e){var r,n,o,i,s,a=.75*e.length,c=e.length,p=0;"="===e[e.length-1]&&(a--,"="===e[e.length-2]&&a--);var h=new ArrayBuffer(a),u=new Uint8Array(h);for(r=0;r<c;r+=4)n=t.indexOf(e[r]),o=t.indexOf(e[r+1]),i=t.indexOf(e[r+2]),s=t.indexOf(e[r+3]),u[p++]=n<<2|o>>4,u[p++]=(15&o)<<4|i>>2,u[p++]=(3&i)<<6|63&s;return h}}("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")},function(t,e){var r=void 0!==r?r:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder&&MozBlobBuilder,n=function(){try{return 2===new Blob(["hi"]).size}catch(t){return!1}}(),o=n&&function(){try{return 2===new Blob([new Uint8Array([1,2])]).size}catch(t){return!1}}(),i=r&&r.prototype.append&&r.prototype.getBlob;function s(t){return t.map((function(t){if(t.buffer instanceof ArrayBuffer){var e=t.buffer;if(t.byteLength!==e.byteLength){var r=new Uint8Array(t.byteLength);r.set(new Uint8Array(e,t.byteOffset,t.byteLength)),e=r.buffer}return e}return t}))}function a(t,e){e=e||{};var n=new r;return s(t).forEach((function(t){n.append(t)})),e.type?n.getBlob(e.type):n.getBlob()}function c(t,e){return new Blob(s(t),e||{})}"undefined"!=typeof Blob&&(a.prototype=Blob.prototype,c.prototype=Blob.prototype),t.exports=n?o?Blob:c:i?a:void 0},function(t,e){e.encode=function(t){var e="";for(var r in t)t.hasOwnProperty(r)&&(e.length&&(e+="&"),e+=encodeURIComponent(r)+"="+encodeURIComponent(t[r]));return e},e.decode=function(t){for(var e={},r=t.split("&"),n=0,o=r.length;n<o;n++){var i=r[n].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}},function(t,e){t.exports=function(t,e){var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}},function(t,e){"use strict";var r,n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),o={},i=0,s=0;function a(t){var e="";do{e=n[t%64]+e,t=Math.floor(t/64)}while(t>0);return e}function c(){var t=a(+new Date);return t!==r?(i=0,r=t):t+"."+a(i++)}for(;s<64;s++)o[n[s]]=s;c.encode=a,c.decode=function(t){var e=0;for(s=0;s<t.length;s++)e=64*e+o[t.charAt(s)];return e},t.exports=c},function(t,e,r){var n=r(17),o=r(28),i=r(15);t.exports=h;var s,a=/\n/g,c=/\\n/g;function p(){}function h(t){n.call(this,t),this.query=this.query||{},s||(s=i.___eio=i.___eio||[]),this.index=s.length;var e=this;s.push((function(t){e.onData(t)})),this.query.j=this.index,"function"==typeof addEventListener&&addEventListener("beforeunload",(function(){e.script&&(e.script.onerror=p)}),!1)}o(h,n),h.prototype.supportsBinary=!1,h.prototype.doClose=function(){this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),this.form&&(this.form.parentNode.removeChild(this.form),this.form=null,this.iframe=null),n.prototype.doClose.call(this)},h.prototype.doPoll=function(){var t=this,e=document.createElement("script");this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),e.async=!0,e.src=this.uri(),e.onerror=function(e){t.onError("jsonp poll error",e)};var r=document.getElementsByTagName("script")[0];r?r.parentNode.insertBefore(e,r):(document.head||document.body).appendChild(e),this.script=e,"undefined"!=typeof navigator&&/gecko/i.test(navigator.userAgent)&&setTimeout((function(){var t=document.createElement("iframe");document.body.appendChild(t),document.body.removeChild(t)}),100)},h.prototype.doWrite=function(t,e){var r=this;if(!this.form){var n,o=document.createElement("form"),i=document.createElement("textarea"),s=this.iframeId="eio_iframe_"+this.index;o.className="socketio",o.style.position="absolute",o.style.top="-1000px",o.style.left="-1000px",o.target=s,o.method="POST",o.setAttribute("accept-charset","utf-8"),i.name="d",o.appendChild(i),document.body.appendChild(o),this.form=o,this.area=i}function p(){h(),e()}function h(){if(r.iframe)try{r.form.removeChild(r.iframe)}catch(t){r.onError("jsonp polling iframe removal error",t)}try{var t='<iframe src="javascript:0" name="'+r.iframeId+'">';n=document.createElement(t)}catch(t){(n=document.createElement("iframe")).name=r.iframeId,n.src="javascript:0"}n.id=r.iframeId,r.form.appendChild(n),r.iframe=n}this.form.action=this.uri(),h(),t=t.replace(c,"\\\n"),this.area.value=t.replace(a,"\\n");try{this.form.submit()}catch(t){}this.iframe.attachEvent?this.iframe.onreadystatechange=function(){"complete"===r.iframe.readyState&&p()}:this.iframe.onload=p}},function(t,e,r){var n,o,i=r(18),s=r(19),a=r(27),c=r(28),p=r(29);r(3)("engine.io-client:websocket");if("undefined"!=typeof WebSocket?n=WebSocket:"undefined"!=typeof self&&(n=self.WebSocket||self.MozWebSocket),"undefined"==typeof window)try{o=r(32)}catch(t){}var h=n||o;function u(t){t&&t.forceBase64&&(this.supportsBinary=!1),this.perMessageDeflate=t.perMessageDeflate,this.usingBrowserWebSocket=n&&!t.forceNode,this.protocols=t.protocols,this.usingBrowserWebSocket||(h=o),i.call(this,t)}t.exports=u,c(u,i),u.prototype.name="websocket",u.prototype.supportsBinary=!0,u.prototype.doOpen=function(){if(this.check()){var t=this.uri(),e=this.protocols,r={};this.isReactNative||(r.agent=this.agent,r.perMessageDeflate=this.perMessageDeflate,r.pfx=this.pfx,r.key=this.key,r.passphrase=this.passphrase,r.cert=this.cert,r.ca=this.ca,r.ciphers=this.ciphers,r.rejectUnauthorized=this.rejectUnauthorized),this.extraHeaders&&(r.headers=this.extraHeaders),this.localAddress&&(r.localAddress=this.localAddress);try{this.ws=this.usingBrowserWebSocket&&!this.isReactNative?e?new h(t,e):new h(t):new h(t,e,r)}catch(t){return this.emit("error",t)}void 0===this.ws.binaryType&&(this.supportsBinary=!1),this.ws.supports&&this.ws.supports.binary?(this.supportsBinary=!0,this.ws.binaryType="nodebuffer"):this.ws.binaryType="arraybuffer",this.addEventListeners()}},u.prototype.addEventListeners=function(){var t=this;this.ws.onopen=function(){t.onOpen()},this.ws.onclose=function(){t.onClose()},this.ws.onmessage=function(e){t.onData(e.data)},this.ws.onerror=function(e){t.onError("websocket error",e)}},u.prototype.write=function(t){var e=this;this.writable=!1;for(var r=t.length,n=0,o=r;n<o;n++)!function(t){s.encodePacket(t,e.supportsBinary,(function(n){if(!e.usingBrowserWebSocket){var o={};if(t.options&&(o.compress=t.options.compress),e.perMessageDeflate)("string"==typeof n?Buffer.byteLength(n):n.length)<e.perMessageDeflate.threshold&&(o.compress=!1)}try{e.usingBrowserWebSocket?e.ws.send(n):e.ws.send(n,o)}catch(t){}--r||i()}))}(t[n]);function i(){e.emit("flush"),setTimeout((function(){e.writable=!0,e.emit("drain")}),0)}},u.prototype.onClose=function(){i.prototype.onClose.call(this)},u.prototype.doClose=function(){void 0!==this.ws&&this.ws.close()},u.prototype.uri=function(){var t=this.query||{},e=this.secure?"wss":"ws",r="";return this.port&&("wss"===e&&443!==Number(this.port)||"ws"===e&&80!==Number(this.port))&&(r=":"+this.port),this.timestampRequests&&(t[this.timestampParam]=p()),this.supportsBinary||(t.b64=1),(t=a.encode(t)).length&&(t="?"+t),e+"://"+(-1!==this.hostname.indexOf(":")?"["+this.hostname+"]":this.hostname)+r+this.path+t},u.prototype.check=function(){return!(!h||"__initialize"in h&&this.name===u.prototype.name)}},function(t,e){},function(t,e){var r=[].indexOf;t.exports=function(t,e){if(r)return t.indexOf(e);for(var n=0;n<t.length;++n)if(t[n]===e)return n;return-1}},function(t,e,r){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},o=r(4),i=r(5),s=r(35),a=r(36),c=r(37),p=(r(3)("socket.io-client:socket"),r(27)),h=r(21);t.exports=l;var u={connect:1,connect_error:1,connect_timeout:1,connecting:1,disconnect:1,error:1,reconnect:1,reconnect_attempt:1,reconnect_failed:1,reconnect_error:1,reconnecting:1,ping:1,pong:1},f=i.prototype.emit;function l(t,e,r){this.io=t,this.nsp=e,this.json=this,this.ids=0,this.acks={},this.receiveBuffer=[],this.sendBuffer=[],this.connected=!1,this.disconnected=!0,this.flags={},r&&r.query&&(this.query=r.query),this.io.autoConnect&&this.open()}i(l.prototype),l.prototype.subEvents=function(){if(!this.subs){var t=this.io;this.subs=[a(t,"open",c(this,"onopen")),a(t,"packet",c(this,"onpacket")),a(t,"close",c(this,"onclose"))]}},l.prototype.open=l.prototype.connect=function(){return this.connected||(this.subEvents(),this.io.reconnecting||this.io.open(),"open"===this.io.readyState&&this.onopen(),this.emit("connecting")),this},l.prototype.send=function(){var t=s(arguments);return t.unshift("message"),this.emit.apply(this,t),this},l.prototype.emit=function(t){if(u.hasOwnProperty(t))return f.apply(this,arguments),this;var e=s(arguments),r={type:(void 0!==this.flags.binary?this.flags.binary:h(e))?o.BINARY_EVENT:o.EVENT,data:e,options:{}};return r.options.compress=!this.flags||!1!==this.flags.compress,"function"==typeof e[e.length-1]&&(this.acks[this.ids]=e.pop(),r.id=this.ids++),this.connected?this.packet(r):this.sendBuffer.push(r),this.flags={},this},l.prototype.packet=function(t){t.nsp=this.nsp,this.io.packet(t)},l.prototype.onopen=function(){if("/"!==this.nsp)if(this.query){var t="object"===n(this.query)?p.encode(this.query):this.query;this.packet({type:o.CONNECT,query:t})}else this.packet({type:o.CONNECT})},l.prototype.onclose=function(t){this.connected=!1,this.disconnected=!0,delete this.id,this.emit("disconnect",t)},l.prototype.onpacket=function(t){var e=t.nsp===this.nsp,r=t.type===o.ERROR&&"/"===t.nsp;if(e||r)switch(t.type){case o.CONNECT:this.onconnect();break;case o.EVENT:case o.BINARY_EVENT:this.onevent(t);break;case o.ACK:case o.BINARY_ACK:this.onack(t);break;case o.DISCONNECT:this.ondisconnect();break;case o.ERROR:this.emit("error",t.data)}},l.prototype.onevent=function(t){var e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?f.apply(this,e):this.receiveBuffer.push(e)},l.prototype.ack=function(t){var e=this,r=!1;return function(){if(!r){r=!0;var n=s(arguments);e.packet({type:h(n)?o.BINARY_ACK:o.ACK,id:t,data:n})}}},l.prototype.onack=function(t){var e=this.acks[t.id];"function"==typeof e&&(e.apply(this,t.data),delete this.acks[t.id])},l.prototype.onconnect=function(){this.connected=!0,this.disconnected=!1,this.emit("connect"),this.emitBuffered()},l.prototype.emitBuffered=function(){var t;for(t=0;t<this.receiveBuffer.length;t++)f.apply(this,this.receiveBuffer[t]);for(this.receiveBuffer=[],t=0;t<this.sendBuffer.length;t++)this.packet(this.sendBuffer[t]);this.sendBuffer=[]},l.prototype.ondisconnect=function(){this.destroy(),this.onclose("io server disconnect")},l.prototype.destroy=function(){if(this.subs){for(var t=0;t<this.subs.length;t++)this.subs[t].destroy();this.subs=null}this.io.destroy(this)},l.prototype.close=l.prototype.disconnect=function(){return this.connected&&this.packet({type:o.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this},l.prototype.compress=function(t){return this.flags.compress=t,this},l.prototype.binary=function(t){return this.flags.binary=t,this}},function(t,e){t.exports=function(t,e){for(var r=[],n=(e=e||0)||0;n<t.length;n++)r[n-e]=t[n];return r}},function(t,e){"use strict";t.exports=function(t,e,r){return t.on(e,r),{destroy:function(){t.removeListener(e,r)}}}},function(t,e){var r=[].slice;t.exports=function(t,e){if("string"==typeof e&&(e=t[e]),"function"!=typeof e)throw new Error("bind() requires a function");var n=r.call(arguments,2);return function(){return e.apply(t,n.concat(r.call(arguments)))}}},function(t,e){function r(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}t.exports=r,r.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),r=Math.floor(e*this.jitter*t);t=0==(1&Math.floor(10*e))?t-r:t+r}return 0|Math.min(t,this.max)},r.prototype.reset=function(){this.attempts=0},r.prototype.setMin=function(t){this.ms=t},r.prototype.setMax=function(t){this.max=t},r.prototype.setJitter=function(t){this.jitter=t}}])}));
\ No newline at end of file
index 52a2173..23e3823 100644 (file)
@@ -3,7 +3,5 @@
  * (c) 2014-2021 Guillermo Rauch
  * Released under the MIT License.
  */
-!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.io=e():t.io=e()}(this,function(){return function(t){function e(n){if(r[n])return r[n].exports;var o=r[n]={exports:{},id:n,loaded:!1};return t[n].call(o.exports,o,o.exports,e),o.loaded=!0,o.exports}var r={};return e.m=t,e.c=r,e.p="",e(0)}([function(t,e,r){"use strict";function n(t,e){"object"===("undefined"==typeof t?"undefined":o(t))&&(e=t,t=void 0),e=e||{};var r,n=i(t),s=n.source,p=n.id,h=n.path,u=c[p]&&h in c[p].nsps,f=e.forceNew||e["force new connection"]||!1===e.multiplex||u;return f?r=a(s,e):(c[p]||(c[p]=a(s,e)),r=c[p]),n.query&&!e.query&&(e.query=n.query),r.socket(n.path,e)}var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=r(1),s=r(4),a=r(9);r(3)("socket.io-client");t.exports=e=n;var c=e.managers={};e.protocol=s.protocol,e.connect=n,e.Manager=r(9),e.Socket=r(34)},function(t,e,r){"use strict";function n(t,e){var r=t;e=e||"undefined"!=typeof location&&location,null==t&&(t=e.protocol+"//"+e.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?e.protocol+t:e.host+t),/^(https?|wss?):\/\//.test(t)||(t="undefined"!=typeof e?e.protocol+"//"+t:"https://"+t),r=o(t)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";var n=r.host.indexOf(":")!==-1,i=n?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port,r.href=r.protocol+"://"+i+(e&&e.port===r.port?"":":"+r.port),r}var o=r(2);r(3)("socket.io-client:url");t.exports=n},function(t,e){function r(t,e){var r=/\/{2,9}/g,n=e.replace(r,"/").split("/");return"/"!=e.substr(0,1)&&0!==e.length||n.splice(0,1),"/"==e.substr(e.length-1,1)&&n.splice(n.length-1,1),n}function n(t,e){var r={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(t,e,n){e&&(r[e]=n)}),r}var o=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,i=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];t.exports=function(t){var e=t,s=t.indexOf("["),a=t.indexOf("]");s!=-1&&a!=-1&&(t=t.substring(0,s)+t.substring(s,a).replace(/:/g,";")+t.substring(a,t.length));for(var c=o.exec(t||""),p={},h=14;h--;)p[i[h]]=c[h]||"";return s!=-1&&a!=-1&&(p.source=e,p.host=p.host.substring(1,p.host.length-1).replace(/;/g,":"),p.authority=p.authority.replace("[","").replace("]","").replace(/;/g,":"),p.ipv6uri=!0),p.pathNames=r(p,p.path),p.queryKey=n(p,p.query),p}},function(t,e){"use strict";t.exports=function(){return function(){}}},function(t,e,r){function n(){}function o(t){var r=""+t.type;if(e.BINARY_EVENT!==t.type&&e.BINARY_ACK!==t.type||(r+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(r+=t.nsp+","),null!=t.id&&(r+=t.id),null!=t.data){var n=i(t.data);if(n===!1)return m;r+=n}return r}function i(t){try{return JSON.stringify(t)}catch(t){return!1}}function s(t,e){function r(t){var r=l.deconstructPacket(t),n=o(r.packet),i=r.buffers;i.unshift(n),e(i)}l.removeBlobs(t,r)}function a(){this.reconstructor=null}function c(t){var r=0,n={type:Number(t.charAt(0))};if(null==e.types[n.type])return u("unknown packet type "+n.type);if(e.BINARY_EVENT===n.type||e.BINARY_ACK===n.type){for(var o="";"-"!==t.charAt(++r)&&(o+=t.charAt(r),r!=t.length););if(o!=Number(o)||"-"!==t.charAt(r))throw new Error("Illegal attachments");n.attachments=Number(o)}if("/"===t.charAt(r+1))for(n.nsp="";++r;){var i=t.charAt(r);if(","===i)break;if(n.nsp+=i,r===t.length)break}else n.nsp="/";var s=t.charAt(r+1);if(""!==s&&Number(s)==s){for(n.id="";++r;){var i=t.charAt(r);if(null==i||Number(i)!=i){--r;break}if(n.id+=t.charAt(r),r===t.length)break}n.id=Number(n.id)}if(t.charAt(++r)){var a=p(t.substr(r)),c=a!==!1&&(n.type===e.ERROR||d(a));if(!c)return u("invalid payload");n.data=a}return n}function p(t){try{return JSON.parse(t)}catch(t){return!1}}function h(t){this.reconPack=t,this.buffers=[]}function u(t){return{type:e.ERROR,data:"parser error: "+t}}var f=(r(3)("socket.io-parser"),r(5)),l=r(6),d=r(7),y=r(8);e.protocol=4,e.types=["CONNECT","DISCONNECT","EVENT","ACK","ERROR","BINARY_EVENT","BINARY_ACK"],e.CONNECT=0,e.DISCONNECT=1,e.EVENT=2,e.ACK=3,e.ERROR=4,e.BINARY_EVENT=5,e.BINARY_ACK=6,e.Encoder=n,e.Decoder=a;var m=e.ERROR+'"encode error"';n.prototype.encode=function(t,r){if(e.BINARY_EVENT===t.type||e.BINARY_ACK===t.type)s(t,r);else{var n=o(t);r([n])}},f(a.prototype),a.prototype.add=function(t){var r;if("string"==typeof t)r=c(t),e.BINARY_EVENT===r.type||e.BINARY_ACK===r.type?(this.reconstructor=new h(r),0===this.reconstructor.reconPack.attachments&&this.emit("decoded",r)):this.emit("decoded",r);else{if(!y(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");r=this.reconstructor.takeBinaryData(t),r&&(this.reconstructor=null,this.emit("decoded",r))}},a.prototype.destroy=function(){this.reconstructor&&this.reconstructor.finishedReconstruction()},h.prototype.takeBinaryData=function(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){var e=l.reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null},h.prototype.finishedReconstruction=function(){this.reconPack=null,this.buffers=[]}},function(t,e,r){function n(t){if(t)return o(t)}function o(t){for(var e in n.prototype)t[e]=n.prototype[e];return t}t.exports=n,n.prototype.on=n.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},n.prototype.once=function(t,e){function r(){this.off(t,r),e.apply(this,arguments)}return r.fn=e,this.on(t,r),this},n.prototype.off=n.prototype.removeListener=n.prototype.removeAllListeners=n.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var n,o=0;o<r.length;o++)if(n=r[o],n===e||n.fn===e){r.splice(o,1);break}return 0===r.length&&delete this._callbacks["$"+t],this},n.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),r=this._callbacks["$"+t],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(r){r=r.slice(0);for(var n=0,o=r.length;n<o;++n)r[n].apply(this,e)}return this},n.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},n.prototype.hasListeners=function(t){return!!this.listeners(t).length}},function(t,e,r){function n(t,e){if(!t)return t;if(s(t)){var r={_placeholder:!0,num:e.length};return e.push(t),r}if(i(t)){for(var o=new Array(t.length),a=0;a<t.length;a++)o[a]=n(t[a],e);return o}if("object"==typeof t&&!(t instanceof Date)){var o={};for(var c in t)o[c]=n(t[c],e);return o}return t}function o(t,e){if(!t)return t;if(t&&t._placeholder)return e[t.num];if(i(t))for(var r=0;r<t.length;r++)t[r]=o(t[r],e);else if("object"==typeof t)for(var n in t)t[n]=o(t[n],e);return t}var i=r(7),s=r(8),a=Object.prototype.toString,c="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===a.call(Blob),p="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===a.call(File);e.deconstructPacket=function(t){var e=[],r=t.data,o=t;return o.data=n(r,e),o.attachments=e.length,{packet:o,buffers:e}},e.reconstructPacket=function(t,e){return t.data=o(t.data,e),t.attachments=void 0,t},e.removeBlobs=function(t,e){function r(t,a,h){if(!t)return t;if(c&&t instanceof Blob||p&&t instanceof File){n++;var u=new FileReader;u.onload=function(){h?h[a]=this.result:o=this.result,--n||e(o)},u.readAsArrayBuffer(t)}else if(i(t))for(var f=0;f<t.length;f++)r(t[f],f,t);else if("object"==typeof t&&!s(t))for(var l in t)r(t[l],l,t)}var n=0,o=t;r(o),n||e(o)}},function(t,e){var r={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==r.call(t)}},function(t,e){function r(t){return n&&Buffer.isBuffer(t)||o&&(t instanceof ArrayBuffer||i(t))}t.exports=r;var n="function"==typeof Buffer&&"function"==typeof Buffer.isBuffer,o="function"==typeof ArrayBuffer,i=function(t){return"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer}},function(t,e,r){"use strict";function n(t,e){if(!(this instanceof n))return new n(t,e);t&&"object"===("undefined"==typeof t?"undefined":o(t))&&(e=t,t=void 0),e=e||{},e.path=e.path||"/socket.io",this.nsps={},this.subs=[],this.opts=e,this.reconnection(e.reconnection!==!1),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(e.randomizationFactor||.5),this.backoff=new f({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this.readyState="closed",this.uri=t,this.connecting=[],this.lastPing=null,this.encoding=!1,this.packetBuffer=[];var r=e.parser||c;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this.autoConnect=e.autoConnect!==!1,this.autoConnect&&this.open()}var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=r(10),s=r(34),a=r(5),c=r(4),p=r(36),h=r(37),u=(r(3)("socket.io-client:manager"),r(33)),f=r(38),l=Object.prototype.hasOwnProperty;t.exports=n,n.prototype.emitAll=function(){this.emit.apply(this,arguments);for(var t in this.nsps)l.call(this.nsps,t)&&this.nsps[t].emit.apply(this.nsps[t],arguments)},n.prototype.updateSocketIds=function(){for(var t in this.nsps)l.call(this.nsps,t)&&(this.nsps[t].id=this.generateId(t))},n.prototype.generateId=function(t){return("/"===t?"":t+"#")+this.engine.id},a(n.prototype),n.prototype.reconnection=function(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection},n.prototype.reconnectionAttempts=function(t){return arguments.length?(this._reconnectionAttempts=t,this):this._reconnectionAttempts},n.prototype.reconnectionDelay=function(t){return arguments.length?(this._reconnectionDelay=t,this.backoff&&this.backoff.setMin(t),this):this._reconnectionDelay},n.prototype.randomizationFactor=function(t){return arguments.length?(this._randomizationFactor=t,this.backoff&&this.backoff.setJitter(t),this):this._randomizationFactor},n.prototype.reconnectionDelayMax=function(t){return arguments.length?(this._reconnectionDelayMax=t,this.backoff&&this.backoff.setMax(t),this):this._reconnectionDelayMax},n.prototype.timeout=function(t){return arguments.length?(this._timeout=t,this):this._timeout},n.prototype.maybeReconnectOnOpen=function(){!this.reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()},n.prototype.open=n.prototype.connect=function(t,e){if(~this.readyState.indexOf("open"))return this;this.engine=i(this.uri,this.opts);var r=this.engine,n=this;this.readyState="opening",this.skipReconnect=!1;var o=p(r,"open",function(){n.onopen(),t&&t()}),s=p(r,"error",function(e){if(n.cleanup(),n.readyState="closed",n.emitAll("connect_error",e),t){var r=new Error("Connection error");r.data=e,t(r)}else n.maybeReconnectOnOpen()});if(!1!==this._timeout){var a=this._timeout;0===a&&o.destroy();var c=setTimeout(function(){o.destroy(),r.close(),r.emit("error","timeout"),n.emitAll("connect_timeout",a)},a);this.subs.push({destroy:function(){clearTimeout(c)}})}return this.subs.push(o),this.subs.push(s),this},n.prototype.onopen=function(){this.cleanup(),this.readyState="open",this.emit("open");var t=this.engine;this.subs.push(p(t,"data",h(this,"ondata"))),this.subs.push(p(t,"ping",h(this,"onping"))),this.subs.push(p(t,"pong",h(this,"onpong"))),this.subs.push(p(t,"error",h(this,"onerror"))),this.subs.push(p(t,"close",h(this,"onclose"))),this.subs.push(p(this.decoder,"decoded",h(this,"ondecoded")))},n.prototype.onping=function(){this.lastPing=new Date,this.emitAll("ping")},n.prototype.onpong=function(){this.emitAll("pong",new Date-this.lastPing)},n.prototype.ondata=function(t){this.decoder.add(t)},n.prototype.ondecoded=function(t){this.emit("packet",t)},n.prototype.onerror=function(t){this.emitAll("error",t)},n.prototype.socket=function(t,e){function r(){~u(o.connecting,n)||o.connecting.push(n)}var n=this.nsps[t];if(!n){n=new s(this,t,e),this.nsps[t]=n;var o=this;n.on("connecting",r),n.on("connect",function(){n.id=o.generateId(t)}),this.autoConnect&&r()}return n},n.prototype.destroy=function(t){var e=u(this.connecting,t);~e&&this.connecting.splice(e,1),this.connecting.length||this.close()},n.prototype.packet=function(t){var e=this;t.query&&0===t.type&&(t.nsp+="?"+t.query),e.encoding?e.packetBuffer.push(t):(e.encoding=!0,this.encoder.encode(t,function(r){for(var n=0;n<r.length;n++)e.engine.write(r[n],t.options);e.encoding=!1,e.processPacketQueue()}))},n.prototype.processPacketQueue=function(){if(this.packetBuffer.length>0&&!this.encoding){var t=this.packetBuffer.shift();this.packet(t)}},n.prototype.cleanup=function(){for(var t=this.subs.length,e=0;e<t;e++){var r=this.subs.shift();r.destroy()}this.packetBuffer=[],this.encoding=!1,this.lastPing=null,this.decoder.destroy()},n.prototype.close=n.prototype.disconnect=function(){this.skipReconnect=!0,this.reconnecting=!1,"opening"===this.readyState&&this.cleanup(),this.backoff.reset(),this.readyState="closed",this.engine&&this.engine.close()},n.prototype.onclose=function(t){this.cleanup(),this.backoff.reset(),this.readyState="closed",this.emit("close",t),this._reconnection&&!this.skipReconnect&&this.reconnect()},n.prototype.reconnect=function(){if(this.reconnecting||this.skipReconnect)return this;var t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitAll("reconnect_failed"),this.reconnecting=!1;else{var e=this.backoff.duration();this.reconnecting=!0;var r=setTimeout(function(){t.skipReconnect||(t.emitAll("reconnect_attempt",t.backoff.attempts),t.emitAll("reconnecting",t.backoff.attempts),t.skipReconnect||t.open(function(e){e?(t.reconnecting=!1,t.reconnect(),t.emitAll("reconnect_error",e.data)):t.onreconnect()}))},e);this.subs.push({destroy:function(){clearTimeout(r)}})}},n.prototype.onreconnect=function(){var t=this.backoff.attempts;this.reconnecting=!1,this.backoff.reset(),this.updateSocketIds(),this.emitAll("reconnect",t)}},function(t,e,r){t.exports=r(11),t.exports.parser=r(19)},function(t,e,r){function n(t,e){return this instanceof n?(e=e||{},t&&"object"==typeof t&&(e=t,t=null),t?(t=p(t),e.hostname=t.host,e.secure="https"===t.protocol||"wss"===t.protocol,e.port=t.port,t.query&&(e.query=t.query)):e.host&&(e.hostname=p(e.host).host),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.agent=e.agent||!1,this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?443:80),this.query=e.query||{},"string"==typeof this.query&&(this.query=h.decode(this.query)),this.upgrade=!1!==e.upgrade,this.path=(e.path||"/engine.io").replace(/\/$/,"")+"/",this.forceJSONP=!!e.forceJSONP,this.jsonp=!1!==e.jsonp,this.forceBase64=!!e.forceBase64,this.enablesXDR=!!e.enablesXDR,this.withCredentials=!1!==e.withCredentials,this.timestampParam=e.timestampParam||"t",this.timestampRequests=e.timestampRequests,this.transports=e.transports||["polling","websocket"],this.transportOptions=e.transportOptions||{},this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.policyPort=e.policyPort||843,this.rememberUpgrade=e.rememberUpgrade||!1,this.binaryType=null,this.onlyBinaryUpgrades=e.onlyBinaryUpgrades,this.perMessageDeflate=!1!==e.perMessageDeflate&&(e.perMessageDeflate||{}),!0===this.perMessageDeflate&&(this.perMessageDeflate={}),this.perMessageDeflate&&null==this.perMessageDeflate.threshold&&(this.perMessageDeflate.threshold=1024),this.pfx=e.pfx||null,this.key=e.key||null,this.passphrase=e.passphrase||null,this.cert=e.cert||null,this.ca=e.ca||null,this.ciphers=e.ciphers||null,this.rejectUnauthorized=void 0===e.rejectUnauthorized||e.rejectUnauthorized,this.forceNode=!!e.forceNode,this.isReactNative="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),("undefined"==typeof self||this.isReactNative)&&(e.extraHeaders&&Object.keys(e.extraHeaders).length>0&&(this.extraHeaders=e.extraHeaders),e.localAddress&&(this.localAddress=e.localAddress)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingIntervalTimer=null,this.pingTimeoutTimer=null,void this.open()):new n(t,e)}function o(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);return e}var i=r(12),s=r(5),a=(r(3)("engine.io-client:socket"),r(33)),c=r(19),p=r(2),h=r(27);t.exports=n,n.priorWebsocketSuccess=!1,s(n.prototype),n.protocol=c.protocol,n.Socket=n,n.Transport=r(18),n.transports=r(12),n.parser=r(19),n.prototype.createTransport=function(t){var e=o(this.query);e.EIO=c.protocol,e.transport=t;var r=this.transportOptions[t]||{};this.id&&(e.sid=this.id);var n=new i[t]({query:e,socket:this,agent:r.agent||this.agent,hostname:r.hostname||this.hostname,port:r.port||this.port,secure:r.secure||this.secure,path:r.path||this.path,forceJSONP:r.forceJSONP||this.forceJSONP,jsonp:r.jsonp||this.jsonp,forceBase64:r.forceBase64||this.forceBase64,enablesXDR:r.enablesXDR||this.enablesXDR,withCredentials:r.withCredentials||this.withCredentials,timestampRequests:r.timestampRequests||this.timestampRequests,timestampParam:r.timestampParam||this.timestampParam,policyPort:r.policyPort||this.policyPort,pfx:r.pfx||this.pfx,key:r.key||this.key,passphrase:r.passphrase||this.passphrase,cert:r.cert||this.cert,ca:r.ca||this.ca,ciphers:r.ciphers||this.ciphers,rejectUnauthorized:r.rejectUnauthorized||this.rejectUnauthorized,perMessageDeflate:r.perMessageDeflate||this.perMessageDeflate,extraHeaders:r.extraHeaders||this.extraHeaders,forceNode:r.forceNode||this.forceNode,localAddress:r.localAddress||this.localAddress,requestTimeout:r.requestTimeout||this.requestTimeout,protocols:r.protocols||void 0,isReactNative:this.isReactNative});return n},n.prototype.open=function(){var t;if(this.rememberUpgrade&&n.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)t="websocket";else{if(0===this.transports.length){var e=this;return void setTimeout(function(){e.emit("error","No transports available")},0)}t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(t){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)},n.prototype.setTransport=function(t){var e=this;this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",function(){e.onDrain()}).on("packet",function(t){e.onPacket(t)}).on("error",function(t){e.onError(t)}).on("close",function(){e.onClose("transport close")})},n.prototype.probe=function(t){function e(){if(u.onlyBinaryUpgrades){var t=!this.supportsBinary&&u.transport.supportsBinary;h=h||t}h||(p.send([{type:"ping",data:"probe"}]),p.once("packet",function(t){if(!h)if("pong"===t.type&&"probe"===t.data){if(u.upgrading=!0,u.emit("upgrading",p),!p)return;n.priorWebsocketSuccess="websocket"===p.name,u.transport.pause(function(){h||"closed"!==u.readyState&&(c(),u.setTransport(p),p.send([{type:"upgrade"}]),u.emit("upgrade",p),p=null,u.upgrading=!1,u.flush())})}else{var e=new Error("probe error");e.transport=p.name,u.emit("upgradeError",e)}}))}function r(){h||(h=!0,c(),p.close(),p=null)}function o(t){var e=new Error("probe error: "+t);e.transport=p.name,r(),u.emit("upgradeError",e)}function i(){o("transport closed")}function s(){o("socket closed")}function a(t){p&&t.name!==p.name&&r()}function c(){p.removeListener("open",e),p.removeListener("error",o),p.removeListener("close",i),u.removeListener("close",s),u.removeListener("upgrading",a)}var p=this.createTransport(t,{probe:1}),h=!1,u=this;n.priorWebsocketSuccess=!1,p.once("open",e),p.once("error",o),p.once("close",i),this.once("close",s),this.once("upgrading",a),p.open()},n.prototype.onOpen=function(){if(this.readyState="open",n.priorWebsocketSuccess="websocket"===this.transport.name,this.emit("open"),this.flush(),"open"===this.readyState&&this.upgrade&&this.transport.pause)for(var t=0,e=this.upgrades.length;t<e;t++)this.probe(this.upgrades[t])},n.prototype.onPacket=function(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emit("packet",t),this.emit("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"pong":this.setPing(),this.emit("pong");break;case"error":var e=new Error("server error");e.code=t.data,this.onError(e);break;case"message":this.emit("data",t.data),this.emit("message",t.data)}},n.prototype.onHandshake=function(t){this.emit("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this.upgrades=this.filterUpgrades(t.upgrades),this.pingInterval=t.pingInterval,this.pingTimeout=t.pingTimeout,this.onOpen(),"closed"!==this.readyState&&(this.setPing(),this.removeListener("heartbeat",this.onHeartbeat),this.on("heartbeat",this.onHeartbeat))},n.prototype.onHeartbeat=function(t){clearTimeout(this.pingTimeoutTimer);var e=this;e.pingTimeoutTimer=setTimeout(function(){"closed"!==e.readyState&&e.onClose("ping timeout")},t||e.pingInterval+e.pingTimeout)},n.prototype.setPing=function(){var t=this;clearTimeout(t.pingIntervalTimer),t.pingIntervalTimer=setTimeout(function(){t.ping(),t.onHeartbeat(t.pingTimeout)},t.pingInterval)},n.prototype.ping=function(){var t=this;this.sendPacket("ping",function(){t.emit("ping")})},n.prototype.onDrain=function(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emit("drain"):this.flush()},n.prototype.flush=function(){"closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length&&(this.transport.send(this.writeBuffer),this.prevBufferLen=this.writeBuffer.length,this.emit("flush"))},n.prototype.write=n.prototype.send=function(t,e,r){return this.sendPacket("message",t,e,r),this},n.prototype.sendPacket=function(t,e,r,n){if("function"==typeof e&&(n=e,e=void 0),"function"==typeof r&&(n=r,r=null),"closing"!==this.readyState&&"closed"!==this.readyState){r=r||{},r.compress=!1!==r.compress;var o={type:t,data:e,options:r};this.emit("packetCreate",o),this.writeBuffer.push(o),n&&this.once("flush",n),this.flush()}},n.prototype.close=function(){function t(){n.onClose("forced close"),n.transport.close()}function e(){n.removeListener("upgrade",e),n.removeListener("upgradeError",e),t()}function r(){n.once("upgrade",e),n.once("upgradeError",e)}if("opening"===this.readyState||"open"===this.readyState){this.readyState="closing";var n=this;this.writeBuffer.length?this.once("drain",function(){this.upgrading?r():t()}):this.upgrading?r():t()}return this},n.prototype.onError=function(t){n.priorWebsocketSuccess=!1,this.emit("error",t),this.onClose("transport error",t)},n.prototype.onClose=function(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){var r=this;clearTimeout(this.pingIntervalTimer),clearTimeout(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),this.readyState="closed",this.id=null,this.emit("close",t,e),r.writeBuffer=[],r.prevBufferLen=0}},n.prototype.filterUpgrades=function(t){for(var e=[],r=0,n=t.length;r<n;r++)~a(this.transports,t[r])&&e.push(t[r]);return e}},function(t,e,r){function n(t){var e,r=!1,n=!1,a=!1!==t.jsonp;if("undefined"!=typeof location){var c="https:"===location.protocol,p=location.port;p||(p=c?443:80),r=t.hostname!==location.hostname||p!==t.port,n=t.secure!==c}if(t.xdomain=r,t.xscheme=n,e=new o(t),"open"in e&&!t.forceJSONP)return new i(t);if(!a)throw new Error("JSONP disabled");return new s(t)}var o=r(13),i=r(16),s=r(30),a=r(31);e.polling=n,e.websocket=a},function(t,e,r){var n=r(14),o=r(15);t.exports=function(t){var e=t.xdomain,r=t.xscheme,i=t.enablesXDR;try{if("undefined"!=typeof XMLHttpRequest&&(!e||n))return new XMLHttpRequest}catch(t){}try{if("undefined"!=typeof XDomainRequest&&!r&&i)return new XDomainRequest}catch(t){}if(!e)try{return new(o[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}},function(t,e){try{t.exports="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){t.exports=!1}},function(t,e){t.exports=function(){return"undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")()}()},function(t,e,r){function n(){}function o(t){if(c.call(this,t),this.requestTimeout=t.requestTimeout,this.extraHeaders=t.extraHeaders,"undefined"!=typeof location){var e="https:"===location.protocol,r=location.port;r||(r=e?443:80),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||r!==t.port,this.xs=t.secure!==e}}function i(t){this.method=t.method||"GET",this.uri=t.uri,this.xd=!!t.xd,this.xs=!!t.xs,this.async=!1!==t.async,this.data=void 0!==t.data?t.data:null,this.agent=t.agent,this.isBinary=t.isBinary,this.supportsBinary=t.supportsBinary,this.enablesXDR=t.enablesXDR,this.withCredentials=t.withCredentials,this.requestTimeout=t.requestTimeout,this.pfx=t.pfx,this.key=t.key,this.passphrase=t.passphrase,this.cert=t.cert,this.ca=t.ca,this.ciphers=t.ciphers,this.rejectUnauthorized=t.rejectUnauthorized,this.extraHeaders=t.extraHeaders,this.create()}function s(){for(var t in i.requests)i.requests.hasOwnProperty(t)&&i.requests[t].abort()}var a=r(13),c=r(17),p=r(5),h=r(28),u=(r(3)("engine.io-client:polling-xhr"),r(15));if(t.exports=o,t.exports.Request=i,h(o,c),o.prototype.supportsBinary=!0,o.prototype.request=function(t){return t=t||{},t.uri=this.uri(),t.xd=this.xd,t.xs=this.xs,t.agent=this.agent||!1,t.supportsBinary=this.supportsBinary,t.enablesXDR=this.enablesXDR,t.withCredentials=this.withCredentials,t.pfx=this.pfx,t.key=this.key,t.passphrase=this.passphrase,t.cert=this.cert,t.ca=this.ca,t.ciphers=this.ciphers,t.rejectUnauthorized=this.rejectUnauthorized,t.requestTimeout=this.requestTimeout,t.extraHeaders=this.extraHeaders,new i(t)},o.prototype.doWrite=function(t,e){var r="string"!=typeof t&&void 0!==t,n=this.request({method:"POST",data:t,isBinary:r}),o=this;n.on("success",e),n.on("error",function(t){o.onError("xhr post error",t)}),this.sendXhr=n},o.prototype.doPoll=function(){var t=this.request(),e=this;t.on("data",function(t){e.onData(t)}),t.on("error",function(t){e.onError("xhr poll error",t)}),this.pollXhr=t},p(i.prototype),i.prototype.create=function(){var t={agent:this.agent,xdomain:this.xd,xscheme:this.xs,enablesXDR:this.enablesXDR};t.pfx=this.pfx,t.key=this.key,t.passphrase=this.passphrase,t.cert=this.cert,t.ca=this.ca,t.ciphers=this.ciphers,t.rejectUnauthorized=this.rejectUnauthorized;var e=this.xhr=new a(t),r=this;try{e.open(this.method,this.uri,this.async);try{if(this.extraHeaders){e.setDisableHeaderCheck&&e.setDisableHeaderCheck(!0);for(var n in this.extraHeaders)this.extraHeaders.hasOwnProperty(n)&&e.setRequestHeader(n,this.extraHeaders[n])}}catch(t){}if("POST"===this.method)try{this.isBinary?e.setRequestHeader("Content-type","application/octet-stream"):e.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{e.setRequestHeader("Accept","*/*")}catch(t){}"withCredentials"in e&&(e.withCredentials=this.withCredentials),this.requestTimeout&&(e.timeout=this.requestTimeout),this.hasXDR()?(e.onload=function(){r.onLoad()},e.onerror=function(){r.onError(e.responseText)}):e.onreadystatechange=function(){if(2===e.readyState)try{var t=e.getResponseHeader("Content-Type");(r.supportsBinary&&"application/octet-stream"===t||"application/octet-stream; charset=UTF-8"===t)&&(e.responseType="arraybuffer")}catch(t){}4===e.readyState&&(200===e.status||1223===e.status?r.onLoad():setTimeout(function(){r.onError("number"==typeof e.status?e.status:0)},0))},e.send(this.data)}catch(t){return void setTimeout(function(){r.onError(t)},0)}"undefined"!=typeof document&&(this.index=i.requestsCount++,i.requests[this.index]=this)},i.prototype.onSuccess=function(){this.emit("success"),this.cleanup()},i.prototype.onData=function(t){this.emit("data",t),this.onSuccess()},i.prototype.onError=function(t){this.emit("error",t),this.cleanup(!0)},i.prototype.cleanup=function(t){if("undefined"!=typeof this.xhr&&null!==this.xhr){if(this.hasXDR()?this.xhr.onload=this.xhr.onerror=n:this.xhr.onreadystatechange=n,t)try{this.xhr.abort()}catch(t){}"undefined"!=typeof document&&delete i.requests[this.index],this.xhr=null}},i.prototype.onLoad=function(){var t;try{var e;try{e=this.xhr.getResponseHeader("Content-Type")}catch(t){}t="application/octet-stream"===e||"application/octet-stream; charset=UTF-8"===e?this.xhr.response||this.xhr.responseText:this.xhr.responseText}catch(t){this.onError(t)}null!=t&&this.onData(t)},i.prototype.hasXDR=function(){return"undefined"!=typeof XDomainRequest&&!this.xs&&this.enablesXDR},i.prototype.abort=function(){this.cleanup()},i.requestsCount=0,i.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",s);else if("function"==typeof addEventListener){var f="onpagehide"in u?"pagehide":"unload";addEventListener(f,s,!1)}},function(t,e,r){function n(t){var e=t&&t.forceBase64;p&&!e||(this.supportsBinary=!1),o.call(this,t)}var o=r(18),i=r(27),s=r(19),a=r(28),c=r(29);r(3)("engine.io-client:polling");t.exports=n;var p=function(){var t=r(13),e=new t({xdomain:!1});return null!=e.responseType}();a(n,o),n.prototype.name="polling",n.prototype.doOpen=function(){this.poll()},n.prototype.pause=function(t){function e(){r.readyState="paused",t()}var r=this;if(this.readyState="pausing",this.polling||!this.writable){var n=0;this.polling&&(n++,this.once("pollComplete",function(){--n||e()})),this.writable||(n++,this.once("drain",function(){--n||e()}))}else e()},n.prototype.poll=function(){this.polling=!0,this.doPoll(),this.emit("poll")},n.prototype.onData=function(t){var e=this,r=function(t,r,n){return"opening"===e.readyState&&"open"===t.type&&e.onOpen(),"close"===t.type?(e.onClose(),!1):void e.onPacket(t)};s.decodePayload(t,this.socket.binaryType,r),"closed"!==this.readyState&&(this.polling=!1,this.emit("pollComplete"),"open"===this.readyState&&this.poll())},n.prototype.doClose=function(){function t(){e.write([{type:"close"}])}var e=this;"open"===this.readyState?t():this.once("open",t)},n.prototype.write=function(t){var e=this;this.writable=!1;var r=function(){e.writable=!0,e.emit("drain")};s.encodePayload(t,this.supportsBinary,function(t){e.doWrite(t,r)})},n.prototype.uri=function(){var t=this.query||{},e=this.secure?"https":"http",r="";!1!==this.timestampRequests&&(t[this.timestampParam]=c()),this.supportsBinary||t.sid||(t.b64=1),t=i.encode(t),this.port&&("https"===e&&443!==Number(this.port)||"http"===e&&80!==Number(this.port))&&(r=":"+this.port),t.length&&(t="?"+t);var n=this.hostname.indexOf(":")!==-1;return e+"://"+(n?"["+this.hostname+"]":this.hostname)+r+this.path+t}},function(t,e,r){function n(t){this.path=t.path,this.hostname=t.hostname,this.port=t.port,this.secure=t.secure,this.query=t.query,this.timestampParam=t.timestampParam,this.timestampRequests=t.timestampRequests,this.readyState="",this.agent=t.agent||!1,this.socket=t.socket,this.enablesXDR=t.enablesXDR,this.withCredentials=t.withCredentials,this.pfx=t.pfx,this.key=t.key,this.passphrase=t.passphrase,this.cert=t.cert,this.ca=t.ca,this.ciphers=t.ciphers,this.rejectUnauthorized=t.rejectUnauthorized,this.forceNode=t.forceNode,
-this.isReactNative=t.isReactNative,this.extraHeaders=t.extraHeaders,this.localAddress=t.localAddress}var o=r(19),i=r(5);t.exports=n,i(n.prototype),n.prototype.onError=function(t,e){var r=new Error(t);return r.type="TransportError",r.description=e,this.emit("error",r),this},n.prototype.open=function(){return"closed"!==this.readyState&&""!==this.readyState||(this.readyState="opening",this.doOpen()),this},n.prototype.close=function(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this},n.prototype.send=function(t){if("open"!==this.readyState)throw new Error("Transport not open");this.write(t)},n.prototype.onOpen=function(){this.readyState="open",this.writable=!0,this.emit("open")},n.prototype.onData=function(t){var e=o.decodePacket(t,this.socket.binaryType);this.onPacket(e)},n.prototype.onPacket=function(t){this.emit("packet",t)},n.prototype.onClose=function(){this.readyState="closed",this.emit("close")}},function(t,e,r){function n(t,r){var n="b"+e.packets[t.type]+t.data.data;return r(n)}function o(t,r,n){if(!r)return e.encodeBase64Packet(t,n);var o=t.data,i=new Uint8Array(o),s=new Uint8Array(1+o.byteLength);s[0]=v[t.type];for(var a=0;a<i.length;a++)s[a+1]=i[a];return n(s.buffer)}function i(t,r,n){if(!r)return e.encodeBase64Packet(t,n);var o=new FileReader;return o.onload=function(){e.encodePacket({type:t.type,data:o.result},r,!0,n)},o.readAsArrayBuffer(t.data)}function s(t,r,n){if(!r)return e.encodeBase64Packet(t,n);if(g)return i(t,r,n);var o=new Uint8Array(1);o[0]=v[t.type];var s=new w([o.buffer,t.data]);return n(s)}function a(t){try{t=d.decode(t,{strict:!1})}catch(t){return!1}return t}function c(t,e,r){for(var n=new Array(t.length),o=l(t.length,r),i=function(t,r,o){e(r,function(e,r){n[t]=r,o(e,n)})},s=0;s<t.length;s++)i(s,t[s],o)}var p,h=r(20),u=r(21),f=r(22),l=r(23),d=r(24);"undefined"!=typeof ArrayBuffer&&(p=r(25));var y="undefined"!=typeof navigator&&/Android/i.test(navigator.userAgent),m="undefined"!=typeof navigator&&/PhantomJS/i.test(navigator.userAgent),g=y||m;e.protocol=3;var v=e.packets={open:0,close:1,ping:2,pong:3,message:4,upgrade:5,noop:6},b=h(v),k={type:"error",data:"parser error"},w=r(26);e.encodePacket=function(t,e,r,i){"function"==typeof e&&(i=e,e=!1),"function"==typeof r&&(i=r,r=null);var a=void 0===t.data?void 0:t.data.buffer||t.data;if("undefined"!=typeof ArrayBuffer&&a instanceof ArrayBuffer)return o(t,e,i);if("undefined"!=typeof w&&a instanceof w)return s(t,e,i);if(a&&a.base64)return n(t,i);var c=v[t.type];return void 0!==t.data&&(c+=r?d.encode(String(t.data),{strict:!1}):String(t.data)),i(""+c)},e.encodeBase64Packet=function(t,r){var n="b"+e.packets[t.type];if("undefined"!=typeof w&&t.data instanceof w){var o=new FileReader;return o.onload=function(){var t=o.result.split(",")[1];r(n+t)},o.readAsDataURL(t.data)}var i;try{i=String.fromCharCode.apply(null,new Uint8Array(t.data))}catch(e){for(var s=new Uint8Array(t.data),a=new Array(s.length),c=0;c<s.length;c++)a[c]=s[c];i=String.fromCharCode.apply(null,a)}return n+=btoa(i),r(n)},e.decodePacket=function(t,r,n){if(void 0===t)return k;if("string"==typeof t){if("b"===t.charAt(0))return e.decodeBase64Packet(t.substr(1),r);if(n&&(t=a(t),t===!1))return k;var o=t.charAt(0);return Number(o)==o&&b[o]?t.length>1?{type:b[o],data:t.substring(1)}:{type:b[o]}:k}var i=new Uint8Array(t),o=i[0],s=f(t,1);return w&&"blob"===r&&(s=new w([s])),{type:b[o],data:s}},e.decodeBase64Packet=function(t,e){var r=b[t.charAt(0)];if(!p)return{type:r,data:{base64:!0,data:t.substr(1)}};var n=p.decode(t.substr(1));return"blob"===e&&w&&(n=new w([n])),{type:r,data:n}},e.encodePayload=function(t,r,n){function o(t){return t.length+":"+t}function i(t,n){e.encodePacket(t,!!s&&r,!1,function(t){n(null,o(t))})}"function"==typeof r&&(n=r,r=null);var s=u(t);return r&&s?w&&!g?e.encodePayloadAsBlob(t,n):e.encodePayloadAsArrayBuffer(t,n):t.length?void c(t,i,function(t,e){return n(e.join(""))}):n("0:")},e.decodePayload=function(t,r,n){if("string"!=typeof t)return e.decodePayloadAsBinary(t,r,n);"function"==typeof r&&(n=r,r=null);var o;if(""===t)return n(k,0,1);for(var i,s,a="",c=0,p=t.length;c<p;c++){var h=t.charAt(c);if(":"===h){if(""===a||a!=(i=Number(a)))return n(k,0,1);if(s=t.substr(c+1,i),a!=s.length)return n(k,0,1);if(s.length){if(o=e.decodePacket(s,r,!1),k.type===o.type&&k.data===o.data)return n(k,0,1);var u=n(o,c+i,p);if(!1===u)return}c+=i,a=""}else a+=h}return""!==a?n(k,0,1):void 0},e.encodePayloadAsArrayBuffer=function(t,r){function n(t,r){e.encodePacket(t,!0,!0,function(t){return r(null,t)})}return t.length?void c(t,n,function(t,e){var n=e.reduce(function(t,e){var r;return r="string"==typeof e?e.length:e.byteLength,t+r.toString().length+r+2},0),o=new Uint8Array(n),i=0;return e.forEach(function(t){var e="string"==typeof t,r=t;if(e){for(var n=new Uint8Array(t.length),s=0;s<t.length;s++)n[s]=t.charCodeAt(s);r=n.buffer}e?o[i++]=0:o[i++]=1;for(var a=r.byteLength.toString(),s=0;s<a.length;s++)o[i++]=parseInt(a[s]);o[i++]=255;for(var n=new Uint8Array(r),s=0;s<n.length;s++)o[i++]=n[s]}),r(o.buffer)}):r(new ArrayBuffer(0))},e.encodePayloadAsBlob=function(t,r){function n(t,r){e.encodePacket(t,!0,!0,function(t){var e=new Uint8Array(1);if(e[0]=1,"string"==typeof t){for(var n=new Uint8Array(t.length),o=0;o<t.length;o++)n[o]=t.charCodeAt(o);t=n.buffer,e[0]=0}for(var i=t instanceof ArrayBuffer?t.byteLength:t.size,s=i.toString(),a=new Uint8Array(s.length+1),o=0;o<s.length;o++)a[o]=parseInt(s[o]);if(a[s.length]=255,w){var c=new w([e.buffer,a.buffer,t]);r(null,c)}})}c(t,n,function(t,e){return r(new w(e))})},e.decodePayloadAsBinary=function(t,r,n){"function"==typeof r&&(n=r,r=null);for(var o=t,i=[];o.byteLength>0;){for(var s=new Uint8Array(o),a=0===s[0],c="",p=1;255!==s[p];p++){if(c.length>310)return n(k,0,1);c+=s[p]}o=f(o,2+c.length),c=parseInt(c);var h=f(o,0,c);if(a)try{h=String.fromCharCode.apply(null,new Uint8Array(h))}catch(t){var u=new Uint8Array(h);h="";for(var p=0;p<u.length;p++)h+=String.fromCharCode(u[p])}i.push(h),o=f(o,c)}var l=i.length;i.forEach(function(t,o){n(e.decodePacket(t,r,!0),o,l)})}},function(t,e){t.exports=Object.keys||function(t){var e=[],r=Object.prototype.hasOwnProperty;for(var n in t)r.call(t,n)&&e.push(n);return e}},function(t,e,r){function n(t){if(!t||"object"!=typeof t)return!1;if(o(t)){for(var e=0,r=t.length;e<r;e++)if(n(t[e]))return!0;return!1}if("function"==typeof Buffer&&Buffer.isBuffer&&Buffer.isBuffer(t)||"function"==typeof ArrayBuffer&&t instanceof ArrayBuffer||s&&t instanceof Blob||a&&t instanceof File)return!0;if(t.toJSON&&"function"==typeof t.toJSON&&1===arguments.length)return n(t.toJSON(),!0);for(var i in t)if(Object.prototype.hasOwnProperty.call(t,i)&&n(t[i]))return!0;return!1}var o=r(7),i=Object.prototype.toString,s="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===i.call(Blob),a="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===i.call(File);t.exports=n},function(t,e){t.exports=function(t,e,r){var n=t.byteLength;if(e=e||0,r=r||n,t.slice)return t.slice(e,r);if(e<0&&(e+=n),r<0&&(r+=n),r>n&&(r=n),e>=n||e>=r||0===n)return new ArrayBuffer(0);for(var o=new Uint8Array(t),i=new Uint8Array(r-e),s=e,a=0;s<r;s++,a++)i[a]=o[s];return i.buffer}},function(t,e){function r(t,e,r){function o(t,n){if(o.count<=0)throw new Error("after called too many times");--o.count,t?(i=!0,e(t),e=r):0!==o.count||i||e(null,n)}var i=!1;return r=r||n,o.count=t,0===t?e():o}function n(){}t.exports=r},function(t,e){function r(t){for(var e,r,n=[],o=0,i=t.length;o<i;)e=t.charCodeAt(o++),e>=55296&&e<=56319&&o<i?(r=t.charCodeAt(o++),56320==(64512&r)?n.push(((1023&e)<<10)+(1023&r)+65536):(n.push(e),o--)):n.push(e);return n}function n(t){for(var e,r=t.length,n=-1,o="";++n<r;)e=t[n],e>65535&&(e-=65536,o+=d(e>>>10&1023|55296),e=56320|1023&e),o+=d(e);return o}function o(t,e){if(t>=55296&&t<=57343){if(e)throw Error("Lone surrogate U+"+t.toString(16).toUpperCase()+" is not a scalar value");return!1}return!0}function i(t,e){return d(t>>e&63|128)}function s(t,e){if(0==(4294967168&t))return d(t);var r="";return 0==(4294965248&t)?r=d(t>>6&31|192):0==(4294901760&t)?(o(t,e)||(t=65533),r=d(t>>12&15|224),r+=i(t,6)):0==(4292870144&t)&&(r=d(t>>18&7|240),r+=i(t,12),r+=i(t,6)),r+=d(63&t|128)}function a(t,e){e=e||{};for(var n,o=!1!==e.strict,i=r(t),a=i.length,c=-1,p="";++c<a;)n=i[c],p+=s(n,o);return p}function c(){if(l>=f)throw Error("Invalid byte index");var t=255&u[l];if(l++,128==(192&t))return 63&t;throw Error("Invalid continuation byte")}function p(t){var e,r,n,i,s;if(l>f)throw Error("Invalid byte index");if(l==f)return!1;if(e=255&u[l],l++,0==(128&e))return e;if(192==(224&e)){if(r=c(),s=(31&e)<<6|r,s>=128)return s;throw Error("Invalid continuation byte")}if(224==(240&e)){if(r=c(),n=c(),s=(15&e)<<12|r<<6|n,s>=2048)return o(s,t)?s:65533;throw Error("Invalid continuation byte")}if(240==(248&e)&&(r=c(),n=c(),i=c(),s=(7&e)<<18|r<<12|n<<6|i,s>=65536&&s<=1114111))return s;throw Error("Invalid UTF-8 detected")}function h(t,e){e=e||{};var o=!1!==e.strict;u=r(t),f=u.length,l=0;for(var i,s=[];(i=p(o))!==!1;)s.push(i);return n(s)}/*! https://mths.be/utf8js v2.1.2 by @mathias */
-var u,f,l,d=String.fromCharCode;t.exports={version:"2.1.2",encode:a,decode:h}},function(t,e){!function(t){"use strict";e.encode=function(e){var r,n=new Uint8Array(e),o=n.length,i="";for(r=0;r<o;r+=3)i+=t[n[r]>>2],i+=t[(3&n[r])<<4|n[r+1]>>4],i+=t[(15&n[r+1])<<2|n[r+2]>>6],i+=t[63&n[r+2]];return o%3===2?i=i.substring(0,i.length-1)+"=":o%3===1&&(i=i.substring(0,i.length-2)+"=="),i},e.decode=function(e){var r,n,o,i,s,a=.75*e.length,c=e.length,p=0;"="===e[e.length-1]&&(a--,"="===e[e.length-2]&&a--);var h=new ArrayBuffer(a),u=new Uint8Array(h);for(r=0;r<c;r+=4)n=t.indexOf(e[r]),o=t.indexOf(e[r+1]),i=t.indexOf(e[r+2]),s=t.indexOf(e[r+3]),u[p++]=n<<2|o>>4,u[p++]=(15&o)<<4|i>>2,u[p++]=(3&i)<<6|63&s;return h}}("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")},function(t,e){function r(t){return t.map(function(t){if(t.buffer instanceof ArrayBuffer){var e=t.buffer;if(t.byteLength!==e.byteLength){var r=new Uint8Array(t.byteLength);r.set(new Uint8Array(e,t.byteOffset,t.byteLength)),e=r.buffer}return e}return t})}function n(t,e){e=e||{};var n=new i;return r(t).forEach(function(t){n.append(t)}),e.type?n.getBlob(e.type):n.getBlob()}function o(t,e){return new Blob(r(t),e||{})}var i="undefined"!=typeof i?i:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder&&MozBlobBuilder,s=function(){try{var t=new Blob(["hi"]);return 2===t.size}catch(t){return!1}}(),a=s&&function(){try{var t=new Blob([new Uint8Array([1,2])]);return 2===t.size}catch(t){return!1}}(),c=i&&i.prototype.append&&i.prototype.getBlob;"undefined"!=typeof Blob&&(n.prototype=Blob.prototype,o.prototype=Blob.prototype),t.exports=function(){return s?a?Blob:o:c?n:void 0}()},function(t,e){e.encode=function(t){var e="";for(var r in t)t.hasOwnProperty(r)&&(e.length&&(e+="&"),e+=encodeURIComponent(r)+"="+encodeURIComponent(t[r]));return e},e.decode=function(t){for(var e={},r=t.split("&"),n=0,o=r.length;n<o;n++){var i=r[n].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}},function(t,e){t.exports=function(t,e){var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}},function(t,e){"use strict";function r(t){var e="";do e=s[t%a]+e,t=Math.floor(t/a);while(t>0);return e}function n(t){var e=0;for(h=0;h<t.length;h++)e=e*a+c[t.charAt(h)];return e}function o(){var t=r(+new Date);return t!==i?(p=0,i=t):t+"."+r(p++)}for(var i,s="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),a=64,c={},p=0,h=0;h<a;h++)c[s[h]]=h;o.encode=r,o.decode=n,t.exports=o},function(t,e,r){function n(){}function o(t){i.call(this,t),this.query=this.query||{},c||(c=a.___eio=a.___eio||[]),this.index=c.length;var e=this;c.push(function(t){e.onData(t)}),this.query.j=this.index,"function"==typeof addEventListener&&addEventListener("beforeunload",function(){e.script&&(e.script.onerror=n)},!1)}var i=r(17),s=r(28),a=r(15);t.exports=o;var c,p=/\n/g,h=/\\n/g;s(o,i),o.prototype.supportsBinary=!1,o.prototype.doClose=function(){this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),this.form&&(this.form.parentNode.removeChild(this.form),this.form=null,this.iframe=null),i.prototype.doClose.call(this)},o.prototype.doPoll=function(){var t=this,e=document.createElement("script");this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),e.async=!0,e.src=this.uri(),e.onerror=function(e){t.onError("jsonp poll error",e)};var r=document.getElementsByTagName("script")[0];r?r.parentNode.insertBefore(e,r):(document.head||document.body).appendChild(e),this.script=e;var n="undefined"!=typeof navigator&&/gecko/i.test(navigator.userAgent);n&&setTimeout(function(){var t=document.createElement("iframe");document.body.appendChild(t),document.body.removeChild(t)},100)},o.prototype.doWrite=function(t,e){function r(){n(),e()}function n(){if(o.iframe)try{o.form.removeChild(o.iframe)}catch(t){o.onError("jsonp polling iframe removal error",t)}try{var t='<iframe src="javascript:0" name="'+o.iframeId+'">';i=document.createElement(t)}catch(t){i=document.createElement("iframe"),i.name=o.iframeId,i.src="javascript:0"}i.id=o.iframeId,o.form.appendChild(i),o.iframe=i}var o=this;if(!this.form){var i,s=document.createElement("form"),a=document.createElement("textarea"),c=this.iframeId="eio_iframe_"+this.index;s.className="socketio",s.style.position="absolute",s.style.top="-1000px",s.style.left="-1000px",s.target=c,s.method="POST",s.setAttribute("accept-charset","utf-8"),a.name="d",s.appendChild(a),document.body.appendChild(s),this.form=s,this.area=a}this.form.action=this.uri(),n(),t=t.replace(h,"\\\n"),this.area.value=t.replace(p,"\\n");try{this.form.submit()}catch(t){}this.iframe.attachEvent?this.iframe.onreadystatechange=function(){"complete"===o.iframe.readyState&&r()}:this.iframe.onload=r}},function(t,e,r){function n(t){var e=t&&t.forceBase64;e&&(this.supportsBinary=!1),this.perMessageDeflate=t.perMessageDeflate,this.usingBrowserWebSocket=o&&!t.forceNode,this.protocols=t.protocols,this.usingBrowserWebSocket||(u=i),s.call(this,t)}var o,i,s=r(18),a=r(19),c=r(27),p=r(28),h=r(29);r(3)("engine.io-client:websocket");if("undefined"!=typeof WebSocket?o=WebSocket:"undefined"!=typeof self&&(o=self.WebSocket||self.MozWebSocket),"undefined"==typeof window)try{i=r(32)}catch(t){}var u=o||i;t.exports=n,p(n,s),n.prototype.name="websocket",n.prototype.supportsBinary=!0,n.prototype.doOpen=function(){if(this.check()){var t=this.uri(),e=this.protocols,r={};this.isReactNative||(r.agent=this.agent,r.perMessageDeflate=this.perMessageDeflate,r.pfx=this.pfx,r.key=this.key,r.passphrase=this.passphrase,r.cert=this.cert,r.ca=this.ca,r.ciphers=this.ciphers,r.rejectUnauthorized=this.rejectUnauthorized),this.extraHeaders&&(r.headers=this.extraHeaders),this.localAddress&&(r.localAddress=this.localAddress);try{this.ws=this.usingBrowserWebSocket&&!this.isReactNative?e?new u(t,e):new u(t):new u(t,e,r)}catch(t){return this.emit("error",t)}void 0===this.ws.binaryType&&(this.supportsBinary=!1),this.ws.supports&&this.ws.supports.binary?(this.supportsBinary=!0,this.ws.binaryType="nodebuffer"):this.ws.binaryType="arraybuffer",this.addEventListeners()}},n.prototype.addEventListeners=function(){var t=this;this.ws.onopen=function(){t.onOpen()},this.ws.onclose=function(){t.onClose()},this.ws.onmessage=function(e){t.onData(e.data)},this.ws.onerror=function(e){t.onError("websocket error",e)}},n.prototype.write=function(t){function e(){r.emit("flush"),setTimeout(function(){r.writable=!0,r.emit("drain")},0)}var r=this;this.writable=!1;for(var n=t.length,o=0,i=n;o<i;o++)!function(t){a.encodePacket(t,r.supportsBinary,function(o){if(!r.usingBrowserWebSocket){var i={};if(t.options&&(i.compress=t.options.compress),r.perMessageDeflate){var s="string"==typeof o?Buffer.byteLength(o):o.length;s<r.perMessageDeflate.threshold&&(i.compress=!1)}}try{r.usingBrowserWebSocket?r.ws.send(o):r.ws.send(o,i)}catch(t){}--n||e()})}(t[o])},n.prototype.onClose=function(){s.prototype.onClose.call(this)},n.prototype.doClose=function(){"undefined"!=typeof this.ws&&this.ws.close()},n.prototype.uri=function(){var t=this.query||{},e=this.secure?"wss":"ws",r="";this.port&&("wss"===e&&443!==Number(this.port)||"ws"===e&&80!==Number(this.port))&&(r=":"+this.port),this.timestampRequests&&(t[this.timestampParam]=h()),this.supportsBinary||(t.b64=1),t=c.encode(t),t.length&&(t="?"+t);var n=this.hostname.indexOf(":")!==-1;return e+"://"+(n?"["+this.hostname+"]":this.hostname)+r+this.path+t},n.prototype.check=function(){return!(!u||"__initialize"in u&&this.name===n.prototype.name)}},function(t,e){},function(t,e){var r=[].indexOf;t.exports=function(t,e){if(r)return t.indexOf(e);for(var n=0;n<t.length;++n)if(t[n]===e)return n;return-1}},function(t,e,r){"use strict";function n(t,e,r){this.io=t,this.nsp=e,this.json=this,this.ids=0,this.acks={},this.receiveBuffer=[],this.sendBuffer=[],this.connected=!1,this.disconnected=!0,this.flags={},r&&r.query&&(this.query=r.query),this.io.autoConnect&&this.open()}var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=r(4),s=r(5),a=r(35),c=r(36),p=r(37),h=(r(3)("socket.io-client:socket"),r(27)),u=r(21);t.exports=e=n;var f={connect:1,connect_error:1,connect_timeout:1,connecting:1,disconnect:1,error:1,reconnect:1,reconnect_attempt:1,reconnect_failed:1,reconnect_error:1,reconnecting:1,ping:1,pong:1},l=s.prototype.emit;s(n.prototype),n.prototype.subEvents=function(){if(!this.subs){var t=this.io;this.subs=[c(t,"open",p(this,"onopen")),c(t,"packet",p(this,"onpacket")),c(t,"close",p(this,"onclose"))]}},n.prototype.open=n.prototype.connect=function(){return this.connected?this:(this.subEvents(),this.io.reconnecting||this.io.open(),"open"===this.io.readyState&&this.onopen(),this.emit("connecting"),this)},n.prototype.send=function(){var t=a(arguments);return t.unshift("message"),this.emit.apply(this,t),this},n.prototype.emit=function(t){if(f.hasOwnProperty(t))return l.apply(this,arguments),this;var e=a(arguments),r={type:(void 0!==this.flags.binary?this.flags.binary:u(e))?i.BINARY_EVENT:i.EVENT,data:e};return r.options={},r.options.compress=!this.flags||!1!==this.flags.compress,"function"==typeof e[e.length-1]&&(this.acks[this.ids]=e.pop(),r.id=this.ids++),this.connected?this.packet(r):this.sendBuffer.push(r),this.flags={},this},n.prototype.packet=function(t){t.nsp=this.nsp,this.io.packet(t)},n.prototype.onopen=function(){if("/"!==this.nsp)if(this.query){var t="object"===o(this.query)?h.encode(this.query):this.query;this.packet({type:i.CONNECT,query:t})}else this.packet({type:i.CONNECT})},n.prototype.onclose=function(t){this.connected=!1,this.disconnected=!0,delete this.id,this.emit("disconnect",t)},n.prototype.onpacket=function(t){var e=t.nsp===this.nsp,r=t.type===i.ERROR&&"/"===t.nsp;if(e||r)switch(t.type){case i.CONNECT:this.onconnect();break;case i.EVENT:this.onevent(t);break;case i.BINARY_EVENT:this.onevent(t);break;case i.ACK:this.onack(t);break;case i.BINARY_ACK:this.onack(t);break;case i.DISCONNECT:this.ondisconnect();break;case i.ERROR:this.emit("error",t.data)}},n.prototype.onevent=function(t){var e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?l.apply(this,e):this.receiveBuffer.push(e)},n.prototype.ack=function(t){var e=this,r=!1;return function(){if(!r){r=!0;var n=a(arguments);e.packet({type:u(n)?i.BINARY_ACK:i.ACK,id:t,data:n})}}},n.prototype.onack=function(t){var e=this.acks[t.id];"function"==typeof e&&(e.apply(this,t.data),delete this.acks[t.id])},n.prototype.onconnect=function(){this.connected=!0,this.disconnected=!1,this.emit("connect"),this.emitBuffered()},n.prototype.emitBuffered=function(){var t;for(t=0;t<this.receiveBuffer.length;t++)l.apply(this,this.receiveBuffer[t]);for(this.receiveBuffer=[],t=0;t<this.sendBuffer.length;t++)this.packet(this.sendBuffer[t]);this.sendBuffer=[]},n.prototype.ondisconnect=function(){this.destroy(),this.onclose("io server disconnect")},n.prototype.destroy=function(){if(this.subs){for(var t=0;t<this.subs.length;t++)this.subs[t].destroy();this.subs=null}this.io.destroy(this)},n.prototype.close=n.prototype.disconnect=function(){return this.connected&&this.packet({type:i.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this},n.prototype.compress=function(t){return this.flags.compress=t,this},n.prototype.binary=function(t){return this.flags.binary=t,this}},function(t,e){function r(t,e){var r=[];e=e||0;for(var n=e||0;n<t.length;n++)r[n-e]=t[n];return r}t.exports=r},function(t,e){"use strict";function r(t,e,r){return t.on(e,r),{destroy:function(){t.removeListener(e,r)}}}t.exports=r},function(t,e){var r=[].slice;t.exports=function(t,e){if("string"==typeof e&&(e=t[e]),"function"!=typeof e)throw new Error("bind() requires a function");var n=r.call(arguments,2);return function(){return e.apply(t,n.concat(r.call(arguments)))}}},function(t,e){function r(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}t.exports=r,r.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),r=Math.floor(e*this.jitter*t);t=0==(1&Math.floor(10*e))?t-r:t+r}return 0|Math.min(t,this.max)},r.prototype.reset=function(){this.attempts=0},r.prototype.setMin=function(t){this.ms=t},r.prototype.setMax=function(t){this.max=t},r.prototype.setJitter=function(t){this.jitter=t}}])});
-//# sourceMappingURL=socket.io.slim.js.map
+!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.io=e():t.io=e()}(this,(function(){return function(t){function e(n){if(r[n])return r[n].exports;var o=r[n]={exports:{},id:n,loaded:!1};return t[n].call(o.exports,o,o.exports,e),o.loaded=!0,o.exports}var r={};return e.m=t,e.c=r,e.p="",e(0)}([function(t,e,r){"use strict";function n(t,e){"object"===(void 0===t?"undefined":o(t))&&(e=t,t=void 0),e=e||{};var r,n=i(t),s=n.source,p=n.id,h=n.path,u=c[p]&&h in c[p].nsps;return e.forceNew||e["force new connection"]||!1===e.multiplex||u?r=a(s,e):(c[p]||(c[p]=a(s,e)),r=c[p]),n.query&&!e.query&&(e.query=n.query),r.socket(n.path,e)}var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=r(1),s=r(4),a=r(9);r(3)("socket.io-client"),t.exports=e=n;var c=e.managers={};e.protocol=s.protocol,e.connect=n,e.Manager=r(9),e.Socket=r(34)},function(t,e,r){"use strict";var n=r(2);r(3)("socket.io-client:url"),t.exports=function(t,e){var r=t;e=e||"undefined"!=typeof location&&location,null==t&&(t=e.protocol+"//"+e.host),"string"==typeof t&&("/"===t.charAt(0)&&(t="/"===t.charAt(1)?e.protocol+t:e.host+t),/^(https?|wss?):\/\//.test(t)||(t=void 0!==e?e.protocol+"//"+t:"https://"+t),r=n(t)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";var o=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+o+":"+r.port,r.href=r.protocol+"://"+o+(e&&e.port===r.port?"":":"+r.port),r}},function(t,e){var r=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,n=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];t.exports=function(t){var e=t,o=t.indexOf("["),i=t.indexOf("]");-1!=o&&-1!=i&&(t=t.substring(0,o)+t.substring(o,i).replace(/:/g,";")+t.substring(i,t.length));for(var s=r.exec(t||""),a={},c=14;c--;)a[n[c]]=s[c]||"";return-1!=o&&-1!=i&&(a.source=e,a.host=a.host.substring(1,a.host.length-1).replace(/;/g,":"),a.authority=a.authority.replace("[","").replace("]","").replace(/;/g,":"),a.ipv6uri=!0),a.pathNames=function(t,e){var r=e.replace(/\/{2,9}/g,"/").split("/");return"/"!=e.substr(0,1)&&0!==e.length||r.splice(0,1),"/"==e.substr(e.length-1,1)&&r.splice(r.length-1,1),r}(0,a.path),a.queryKey=function(t,e){var r={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,(function(t,e,n){e&&(r[e]=n)})),r}(0,a.query),a}},function(t,e){"use strict";t.exports=function(){return function(){}}},function(t,e,r){function n(){}function o(t){var r=""+t.type;if(e.BINARY_EVENT!==t.type&&e.BINARY_ACK!==t.type||(r+=t.attachments+"-"),t.nsp&&"/"!==t.nsp&&(r+=t.nsp+","),null!=t.id&&(r+=t.id),null!=t.data){var n=function(t){try{return JSON.stringify(t)}catch(t){return!1}}(t.data);if(!1===n)return l;r+=n}return r}function i(){this.reconstructor=null}function s(t){var r=0,n={type:Number(t.charAt(0))};if(null==e.types[n.type])return c("unknown packet type "+n.type);if(e.BINARY_EVENT===n.type||e.BINARY_ACK===n.type){for(var o="";"-"!==t.charAt(++r)&&(o+=t.charAt(r),r!=t.length););if(o!=Number(o)||"-"!==t.charAt(r))throw new Error("Illegal attachments");n.attachments=Number(o)}if("/"===t.charAt(r+1))for(n.nsp="";++r;){if(","===(s=t.charAt(r)))break;if(n.nsp+=s,r===t.length)break}else n.nsp="/";var i=t.charAt(r+1);if(""!==i&&Number(i)==i){for(n.id="";++r;){var s;if(null==(s=t.charAt(r))||Number(s)!=s){--r;break}if(n.id+=t.charAt(r),r===t.length)break}n.id=Number(n.id)}if(t.charAt(++r)){var a=function(t){try{return JSON.parse(t)}catch(t){return!1}}(t.substr(r));if(!(!1!==a&&(n.type===e.ERROR||u(a))))return c("invalid payload");n.data=a}return n}function a(t){this.reconPack=t,this.buffers=[]}function c(t){return{type:e.ERROR,data:"parser error: "+t}}var p=(r(3)("socket.io-parser"),r(5)),h=r(6),u=r(7),f=r(8);e.protocol=4,e.types=["CONNECT","DISCONNECT","EVENT","ACK","ERROR","BINARY_EVENT","BINARY_ACK"],e.CONNECT=0,e.DISCONNECT=1,e.EVENT=2,e.ACK=3,e.ERROR=4,e.BINARY_EVENT=5,e.BINARY_ACK=6,e.Encoder=n,e.Decoder=i;var l=e.ERROR+'"encode error"';n.prototype.encode=function(t,r){e.BINARY_EVENT===t.type||e.BINARY_ACK===t.type?function(t,e){h.removeBlobs(t,(function(t){var r=h.deconstructPacket(t),n=o(r.packet),i=r.buffers;i.unshift(n),e(i)}))}(t,r):r([o(t)])},p(i.prototype),i.prototype.add=function(t){var r;if("string"==typeof t)r=s(t),e.BINARY_EVENT===r.type||e.BINARY_ACK===r.type?(this.reconstructor=new a(r),0===this.reconstructor.reconPack.attachments&&this.emit("decoded",r)):this.emit("decoded",r);else{if(!f(t)&&!t.base64)throw new Error("Unknown type: "+t);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");(r=this.reconstructor.takeBinaryData(t))&&(this.reconstructor=null,this.emit("decoded",r))}},i.prototype.destroy=function(){this.reconstructor&&this.reconstructor.finishedReconstruction()},a.prototype.takeBinaryData=function(t){if(this.buffers.push(t),this.buffers.length===this.reconPack.attachments){var e=h.reconstructPacket(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null},a.prototype.finishedReconstruction=function(){this.reconPack=null,this.buffers=[]}},function(t,e,r){function n(t){if(t)return function(t){for(var e in n.prototype)t[e]=n.prototype[e];return t}(t)}t.exports=n,n.prototype.on=n.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},n.prototype.once=function(t,e){function r(){this.off(t,r),e.apply(this,arguments)}return r.fn=e,this.on(t,r),this},n.prototype.off=n.prototype.removeListener=n.prototype.removeAllListeners=n.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r=this._callbacks["$"+t];if(!r)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var n,o=0;o<r.length;o++)if((n=r[o])===e||n.fn===e){r.splice(o,1);break}return 0===r.length&&delete this._callbacks["$"+t],this},n.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),r=this._callbacks["$"+t],n=1;n<arguments.length;n++)e[n-1]=arguments[n];if(r){n=0;for(var o=(r=r.slice(0)).length;n<o;++n)r[n].apply(this,e)}return this},n.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},n.prototype.hasListeners=function(t){return!!this.listeners(t).length}},function(t,e,r){function n(t,e){if(!t)return t;if(s(t)){var r={_placeholder:!0,num:e.length};return e.push(t),r}if(i(t)){for(var o=new Array(t.length),a=0;a<t.length;a++)o[a]=n(t[a],e);return o}if("object"==typeof t&&!(t instanceof Date)){o={};for(var c in t)o[c]=n(t[c],e);return o}return t}function o(t,e){if(!t)return t;if(t&&t._placeholder)return e[t.num];if(i(t))for(var r=0;r<t.length;r++)t[r]=o(t[r],e);else if("object"==typeof t)for(var n in t)t[n]=o(t[n],e);return t}var i=r(7),s=r(8),a=Object.prototype.toString,c="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===a.call(Blob),p="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===a.call(File);e.deconstructPacket=function(t){var e=[],r=t.data,o=t;return o.data=n(r,e),o.attachments=e.length,{packet:o,buffers:e}},e.reconstructPacket=function(t,e){return t.data=o(t.data,e),t.attachments=void 0,t},e.removeBlobs=function(t,e){var r=0,n=t;(function t(o,a,h){if(!o)return o;if(c&&o instanceof Blob||p&&o instanceof File){r++;var u=new FileReader;u.onload=function(){h?h[a]=this.result:n=this.result,--r||e(n)},u.readAsArrayBuffer(o)}else if(i(o))for(var f=0;f<o.length;f++)t(o[f],f,o);else if("object"==typeof o&&!s(o))for(var l in o)t(o[l],l,o)})(n),r||e(n)}},function(t,e){var r={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==r.call(t)}},function(t,e){t.exports=function(t){return r&&Buffer.isBuffer(t)||n&&(t instanceof ArrayBuffer||o(t))};var r="function"==typeof Buffer&&"function"==typeof Buffer.isBuffer,n="function"==typeof ArrayBuffer,o=function(t){return"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(t):t.buffer instanceof ArrayBuffer}},function(t,e,r){"use strict";function n(t,e){if(!(this instanceof n))return new n(t,e);t&&"object"===(void 0===t?"undefined":o(t))&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.nsps={},this.subs=[],this.opts=e,this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(e.randomizationFactor||.5),this.backoff=new f({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this.readyState="closed",this.uri=t,this.connecting=[],this.lastPing=null,this.encoding=!1,this.packetBuffer=[];var r=e.parser||c;this.encoder=new r.Encoder,this.decoder=new r.Decoder,this.autoConnect=!1!==e.autoConnect,this.autoConnect&&this.open()}var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=r(10),s=r(34),a=r(5),c=r(4),p=r(36),h=r(37),u=(r(3)("socket.io-client:manager"),r(33)),f=r(38),l=Object.prototype.hasOwnProperty;t.exports=n,n.prototype.emitAll=function(){for(var t in this.emit.apply(this,arguments),this.nsps)l.call(this.nsps,t)&&this.nsps[t].emit.apply(this.nsps[t],arguments)},n.prototype.updateSocketIds=function(){for(var t in this.nsps)l.call(this.nsps,t)&&(this.nsps[t].id=this.generateId(t))},n.prototype.generateId=function(t){return("/"===t?"":t+"#")+this.engine.id},a(n.prototype),n.prototype.reconnection=function(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection},n.prototype.reconnectionAttempts=function(t){return arguments.length?(this._reconnectionAttempts=t,this):this._reconnectionAttempts},n.prototype.reconnectionDelay=function(t){return arguments.length?(this._reconnectionDelay=t,this.backoff&&this.backoff.setMin(t),this):this._reconnectionDelay},n.prototype.randomizationFactor=function(t){return arguments.length?(this._randomizationFactor=t,this.backoff&&this.backoff.setJitter(t),this):this._randomizationFactor},n.prototype.reconnectionDelayMax=function(t){return arguments.length?(this._reconnectionDelayMax=t,this.backoff&&this.backoff.setMax(t),this):this._reconnectionDelayMax},n.prototype.timeout=function(t){return arguments.length?(this._timeout=t,this):this._timeout},n.prototype.maybeReconnectOnOpen=function(){!this.reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()},n.prototype.open=n.prototype.connect=function(t,e){if(~this.readyState.indexOf("open"))return this;this.engine=i(this.uri,this.opts);var r=this.engine,n=this;this.readyState="opening",this.skipReconnect=!1;var o=p(r,"open",(function(){n.onopen(),t&&t()})),s=p(r,"error",(function(e){if(n.cleanup(),n.readyState="closed",n.emitAll("connect_error",e),t){var r=new Error("Connection error");r.data=e,t(r)}else n.maybeReconnectOnOpen()}));if(!1!==this._timeout){var a=this._timeout;0===a&&o.destroy();var c=setTimeout((function(){o.destroy(),r.close(),r.emit("error","timeout"),n.emitAll("connect_timeout",a)}),a);this.subs.push({destroy:function(){clearTimeout(c)}})}return this.subs.push(o),this.subs.push(s),this},n.prototype.onopen=function(){this.cleanup(),this.readyState="open",this.emit("open");var t=this.engine;this.subs.push(p(t,"data",h(this,"ondata"))),this.subs.push(p(t,"ping",h(this,"onping"))),this.subs.push(p(t,"pong",h(this,"onpong"))),this.subs.push(p(t,"error",h(this,"onerror"))),this.subs.push(p(t,"close",h(this,"onclose"))),this.subs.push(p(this.decoder,"decoded",h(this,"ondecoded")))},n.prototype.onping=function(){this.lastPing=new Date,this.emitAll("ping")},n.prototype.onpong=function(){this.emitAll("pong",new Date-this.lastPing)},n.prototype.ondata=function(t){this.decoder.add(t)},n.prototype.ondecoded=function(t){this.emit("packet",t)},n.prototype.onerror=function(t){this.emitAll("error",t)},n.prototype.socket=function(t,e){function r(){~u(o.connecting,n)||o.connecting.push(n)}var n=this.nsps[t];if(!n){n=new s(this,t,e),this.nsps[t]=n;var o=this;n.on("connecting",r),n.on("connect",(function(){n.id=o.generateId(t)})),this.autoConnect&&r()}return n},n.prototype.destroy=function(t){var e=u(this.connecting,t);~e&&this.connecting.splice(e,1),this.connecting.length||this.close()},n.prototype.packet=function(t){var e=this;t.query&&0===t.type&&(t.nsp+="?"+t.query),e.encoding?e.packetBuffer.push(t):(e.encoding=!0,this.encoder.encode(t,(function(r){for(var n=0;n<r.length;n++)e.engine.write(r[n],t.options);e.encoding=!1,e.processPacketQueue()})))},n.prototype.processPacketQueue=function(){if(this.packetBuffer.length>0&&!this.encoding){var t=this.packetBuffer.shift();this.packet(t)}},n.prototype.cleanup=function(){for(var t=this.subs.length,e=0;e<t;e++){this.subs.shift().destroy()}this.packetBuffer=[],this.encoding=!1,this.lastPing=null,this.decoder.destroy()},n.prototype.close=n.prototype.disconnect=function(){this.skipReconnect=!0,this.reconnecting=!1,"opening"===this.readyState&&this.cleanup(),this.backoff.reset(),this.readyState="closed",this.engine&&this.engine.close()},n.prototype.onclose=function(t){this.cleanup(),this.backoff.reset(),this.readyState="closed",this.emit("close",t),this._reconnection&&!this.skipReconnect&&this.reconnect()},n.prototype.reconnect=function(){if(this.reconnecting||this.skipReconnect)return this;var t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitAll("reconnect_failed"),this.reconnecting=!1;else{var e=this.backoff.duration();this.reconnecting=!0;var r=setTimeout((function(){t.skipReconnect||(t.emitAll("reconnect_attempt",t.backoff.attempts),t.emitAll("reconnecting",t.backoff.attempts),t.skipReconnect||t.open((function(e){e?(t.reconnecting=!1,t.reconnect(),t.emitAll("reconnect_error",e.data)):t.onreconnect()})))}),e);this.subs.push({destroy:function(){clearTimeout(r)}})}},n.prototype.onreconnect=function(){var t=this.backoff.attempts;this.reconnecting=!1,this.backoff.reset(),this.updateSocketIds(),this.emitAll("reconnect",t)}},function(t,e,r){t.exports=r(11),t.exports.parser=r(19)},function(t,e,r){function n(t,e){return this instanceof n?(e=e||{},t&&"object"==typeof t&&(e=t,t=null),t?(t=c(t),e.hostname=t.host,e.secure="https"===t.protocol||"wss"===t.protocol,e.port=t.port,t.query&&(e.query=t.query)):e.host&&(e.hostname=c(e.host).host),this.secure=null!=e.secure?e.secure:"undefined"!=typeof location&&"https:"===location.protocol,e.hostname&&!e.port&&(e.port=this.secure?"443":"80"),this.agent=e.agent||!1,this.hostname=e.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=e.port||("undefined"!=typeof location&&location.port?location.port:this.secure?443:80),this.query=e.query||{},"string"==typeof this.query&&(this.query=p.decode(this.query)),this.upgrade=!1!==e.upgrade,this.path=(e.path||"/engine.io").replace(/\/$/,"")+"/",this.forceJSONP=!!e.forceJSONP,this.jsonp=!1!==e.jsonp,this.forceBase64=!!e.forceBase64,this.enablesXDR=!!e.enablesXDR,this.withCredentials=!1!==e.withCredentials,this.timestampParam=e.timestampParam||"t",this.timestampRequests=e.timestampRequests,this.transports=e.transports||["polling","websocket"],this.transportOptions=e.transportOptions||{},this.readyState="",this.writeBuffer=[],this.prevBufferLen=0,this.policyPort=e.policyPort||843,this.rememberUpgrade=e.rememberUpgrade||!1,this.binaryType=null,this.onlyBinaryUpgrades=e.onlyBinaryUpgrades,this.perMessageDeflate=!1!==e.perMessageDeflate&&(e.perMessageDeflate||{}),!0===this.perMessageDeflate&&(this.perMessageDeflate={}),this.perMessageDeflate&&null==this.perMessageDeflate.threshold&&(this.perMessageDeflate.threshold=1024),this.pfx=e.pfx||null,this.key=e.key||null,this.passphrase=e.passphrase||null,this.cert=e.cert||null,this.ca=e.ca||null,this.ciphers=e.ciphers||null,this.rejectUnauthorized=void 0===e.rejectUnauthorized||e.rejectUnauthorized,this.forceNode=!!e.forceNode,this.isReactNative="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase(),("undefined"==typeof self||this.isReactNative)&&(e.extraHeaders&&Object.keys(e.extraHeaders).length>0&&(this.extraHeaders=e.extraHeaders),e.localAddress&&(this.localAddress=e.localAddress)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingIntervalTimer=null,this.pingTimeoutTimer=null,void this.open()):new n(t,e)}var o=r(12),i=r(5),s=(r(3)("engine.io-client:socket"),r(33)),a=r(19),c=r(2),p=r(27);t.exports=n,n.priorWebsocketSuccess=!1,i(n.prototype),n.protocol=a.protocol,n.Socket=n,n.Transport=r(18),n.transports=r(12),n.parser=r(19),n.prototype.createTransport=function(t){var e=function(t){var e={};for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);return e}(this.query);e.EIO=a.protocol,e.transport=t;var r=this.transportOptions[t]||{};return this.id&&(e.sid=this.id),new o[t]({query:e,socket:this,agent:r.agent||this.agent,hostname:r.hostname||this.hostname,port:r.port||this.port,secure:r.secure||this.secure,path:r.path||this.path,forceJSONP:r.forceJSONP||this.forceJSONP,jsonp:r.jsonp||this.jsonp,forceBase64:r.forceBase64||this.forceBase64,enablesXDR:r.enablesXDR||this.enablesXDR,withCredentials:r.withCredentials||this.withCredentials,timestampRequests:r.timestampRequests||this.timestampRequests,timestampParam:r.timestampParam||this.timestampParam,policyPort:r.policyPort||this.policyPort,pfx:r.pfx||this.pfx,key:r.key||this.key,passphrase:r.passphrase||this.passphrase,cert:r.cert||this.cert,ca:r.ca||this.ca,ciphers:r.ciphers||this.ciphers,rejectUnauthorized:r.rejectUnauthorized||this.rejectUnauthorized,perMessageDeflate:r.perMessageDeflate||this.perMessageDeflate,extraHeaders:r.extraHeaders||this.extraHeaders,forceNode:r.forceNode||this.forceNode,localAddress:r.localAddress||this.localAddress,requestTimeout:r.requestTimeout||this.requestTimeout,protocols:r.protocols||void 0,isReactNative:this.isReactNative})},n.prototype.open=function(){var t;if(this.rememberUpgrade&&n.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket"))t="websocket";else{if(0===this.transports.length){var e=this;return void setTimeout((function(){e.emit("error","No transports available")}),0)}t=this.transports[0]}this.readyState="opening";try{t=this.createTransport(t)}catch(t){return this.transports.shift(),void this.open()}t.open(),this.setTransport(t)},n.prototype.setTransport=function(t){var e=this;this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",(function(){e.onDrain()})).on("packet",(function(t){e.onPacket(t)})).on("error",(function(t){e.onError(t)})).on("close",(function(){e.onClose("transport close")}))},n.prototype.probe=function(t){function e(){if(u.onlyBinaryUpgrades){var t=!this.supportsBinary&&u.transport.supportsBinary;h=h||t}h||(p.send([{type:"ping",data:"probe"}]),p.once("packet",(function(t){if(!h)if("pong"===t.type&&"probe"===t.data){if(u.upgrading=!0,u.emit("upgrading",p),!p)return;n.priorWebsocketSuccess="websocket"===p.name,u.transport.pause((function(){h||"closed"!==u.readyState&&(c(),u.setTransport(p),p.send([{type:"upgrade"}]),u.emit("upgrade",p),p=null,u.upgrading=!1,u.flush())}))}else{var e=new Error("probe error");e.transport=p.name,u.emit("upgradeError",e)}})))}function r(){h||(h=!0,c(),p.close(),p=null)}function o(t){var e=new Error("probe error: "+t);e.transport=p.name,r(),u.emit("upgradeError",e)}function i(){o("transport closed")}function s(){o("socket closed")}function a(t){p&&t.name!==p.name&&r()}function c(){p.removeListener("open",e),p.removeListener("error",o),p.removeListener("close",i),u.removeListener("close",s),u.removeListener("upgrading",a)}var p=this.createTransport(t,{probe:1}),h=!1,u=this;n.priorWebsocketSuccess=!1,p.once("open",e),p.once("error",o),p.once("close",i),this.once("close",s),this.once("upgrading",a),p.open()},n.prototype.onOpen=function(){if(this.readyState="open",n.priorWebsocketSuccess="websocket"===this.transport.name,this.emit("open"),this.flush(),"open"===this.readyState&&this.upgrade&&this.transport.pause)for(var t=0,e=this.upgrades.length;t<e;t++)this.probe(this.upgrades[t])},n.prototype.onPacket=function(t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emit("packet",t),this.emit("heartbeat"),t.type){case"open":this.onHandshake(JSON.parse(t.data));break;case"pong":this.setPing(),this.emit("pong");break;case"error":var e=new Error("server error");e.code=t.data,this.onError(e);break;case"message":this.emit("data",t.data),this.emit("message",t.data)}},n.prototype.onHandshake=function(t){this.emit("handshake",t),this.id=t.sid,this.transport.query.sid=t.sid,this.upgrades=this.filterUpgrades(t.upgrades),this.pingInterval=t.pingInterval,this.pingTimeout=t.pingTimeout,this.onOpen(),"closed"!==this.readyState&&(this.setPing(),this.removeListener("heartbeat",this.onHeartbeat),this.on("heartbeat",this.onHeartbeat))},n.prototype.onHeartbeat=function(t){clearTimeout(this.pingTimeoutTimer);var e=this;e.pingTimeoutTimer=setTimeout((function(){"closed"!==e.readyState&&e.onClose("ping timeout")}),t||e.pingInterval+e.pingTimeout)},n.prototype.setPing=function(){var t=this;clearTimeout(t.pingIntervalTimer),t.pingIntervalTimer=setTimeout((function(){t.ping(),t.onHeartbeat(t.pingTimeout)}),t.pingInterval)},n.prototype.ping=function(){var t=this;this.sendPacket("ping",(function(){t.emit("ping")}))},n.prototype.onDrain=function(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,0===this.writeBuffer.length?this.emit("drain"):this.flush()},n.prototype.flush=function(){"closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length&&(this.transport.send(this.writeBuffer),this.prevBufferLen=this.writeBuffer.length,this.emit("flush"))},n.prototype.write=n.prototype.send=function(t,e,r){return this.sendPacket("message",t,e,r),this},n.prototype.sendPacket=function(t,e,r,n){if("function"==typeof e&&(n=e,e=void 0),"function"==typeof r&&(n=r,r=null),"closing"!==this.readyState&&"closed"!==this.readyState){(r=r||{}).compress=!1!==r.compress;var o={type:t,data:e,options:r};this.emit("packetCreate",o),this.writeBuffer.push(o),n&&this.once("flush",n),this.flush()}},n.prototype.close=function(){function t(){n.onClose("forced close"),n.transport.close()}function e(){n.removeListener("upgrade",e),n.removeListener("upgradeError",e),t()}function r(){n.once("upgrade",e),n.once("upgradeError",e)}if("opening"===this.readyState||"open"===this.readyState){this.readyState="closing";var n=this;this.writeBuffer.length?this.once("drain",(function(){this.upgrading?r():t()})):this.upgrading?r():t()}return this},n.prototype.onError=function(t){n.priorWebsocketSuccess=!1,this.emit("error",t),this.onClose("transport error",t)},n.prototype.onClose=function(t,e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){clearTimeout(this.pingIntervalTimer),clearTimeout(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),this.readyState="closed",this.id=null,this.emit("close",t,e),this.writeBuffer=[],this.prevBufferLen=0}},n.prototype.filterUpgrades=function(t){for(var e=[],r=0,n=t.length;r<n;r++)~s(this.transports,t[r])&&e.push(t[r]);return e}},function(t,e,r){var n=r(13),o=r(16),i=r(30),s=r(31);e.polling=function(t){var e=!1,r=!1,s=!1!==t.jsonp;if("undefined"!=typeof location){var a="https:"===location.protocol,c=location.port;c||(c=a?443:80),e=t.hostname!==location.hostname||c!==t.port,r=t.secure!==a}if(t.xdomain=e,t.xscheme=r,"open"in new n(t)&&!t.forceJSONP)return new o(t);if(!s)throw new Error("JSONP disabled");return new i(t)},e.websocket=s},function(t,e,r){var n=r(14),o=r(15);t.exports=function(t){var e=t.xdomain,r=t.xscheme,i=t.enablesXDR;try{if("undefined"!=typeof XMLHttpRequest&&(!e||n))return new XMLHttpRequest}catch(t){}try{if("undefined"!=typeof XDomainRequest&&!r&&i)return new XDomainRequest}catch(t){}if(!e)try{return new(o[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(t){}}},function(t,e){try{t.exports="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(e){t.exports=!1}},function(t,e){t.exports="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")()},function(t,e,r){function n(){}function o(t){if(c.call(this,t),this.requestTimeout=t.requestTimeout,this.extraHeaders=t.extraHeaders,"undefined"!=typeof location){var e="https:"===location.protocol,r=location.port;r||(r=e?443:80),this.xd="undefined"!=typeof location&&t.hostname!==location.hostname||r!==t.port,this.xs=t.secure!==e}}function i(t){this.method=t.method||"GET",this.uri=t.uri,this.xd=!!t.xd,this.xs=!!t.xs,this.async=!1!==t.async,this.data=void 0!==t.data?t.data:null,this.agent=t.agent,this.isBinary=t.isBinary,this.supportsBinary=t.supportsBinary,this.enablesXDR=t.enablesXDR,this.withCredentials=t.withCredentials,this.requestTimeout=t.requestTimeout,this.pfx=t.pfx,this.key=t.key,this.passphrase=t.passphrase,this.cert=t.cert,this.ca=t.ca,this.ciphers=t.ciphers,this.rejectUnauthorized=t.rejectUnauthorized,this.extraHeaders=t.extraHeaders,this.create()}function s(){for(var t in i.requests)i.requests.hasOwnProperty(t)&&i.requests[t].abort()}var a=r(13),c=r(17),p=r(5),h=r(28),u=(r(3)("engine.io-client:polling-xhr"),r(15));if(t.exports=o,t.exports.Request=i,h(o,c),o.prototype.supportsBinary=!0,o.prototype.request=function(t){return(t=t||{}).uri=this.uri(),t.xd=this.xd,t.xs=this.xs,t.agent=this.agent||!1,t.supportsBinary=this.supportsBinary,t.enablesXDR=this.enablesXDR,t.withCredentials=this.withCredentials,t.pfx=this.pfx,t.key=this.key,t.passphrase=this.passphrase,t.cert=this.cert,t.ca=this.ca,t.ciphers=this.ciphers,t.rejectUnauthorized=this.rejectUnauthorized,t.requestTimeout=this.requestTimeout,t.extraHeaders=this.extraHeaders,new i(t)},o.prototype.doWrite=function(t,e){var r="string"!=typeof t&&void 0!==t,n=this.request({method:"POST",data:t,isBinary:r}),o=this;n.on("success",e),n.on("error",(function(t){o.onError("xhr post error",t)})),this.sendXhr=n},o.prototype.doPoll=function(){var t=this.request(),e=this;t.on("data",(function(t){e.onData(t)})),t.on("error",(function(t){e.onError("xhr poll error",t)})),this.pollXhr=t},p(i.prototype),i.prototype.create=function(){var t={agent:this.agent,xdomain:this.xd,xscheme:this.xs,enablesXDR:this.enablesXDR};t.pfx=this.pfx,t.key=this.key,t.passphrase=this.passphrase,t.cert=this.cert,t.ca=this.ca,t.ciphers=this.ciphers,t.rejectUnauthorized=this.rejectUnauthorized;var e=this.xhr=new a(t),r=this;try{e.open(this.method,this.uri,this.async);try{if(this.extraHeaders)for(var n in e.setDisableHeaderCheck&&e.setDisableHeaderCheck(!0),this.extraHeaders)this.extraHeaders.hasOwnProperty(n)&&e.setRequestHeader(n,this.extraHeaders[n])}catch(t){}if("POST"===this.method)try{this.isBinary?e.setRequestHeader("Content-type","application/octet-stream"):e.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(t){}try{e.setRequestHeader("Accept","*/*")}catch(t){}"withCredentials"in e&&(e.withCredentials=this.withCredentials),this.requestTimeout&&(e.timeout=this.requestTimeout),this.hasXDR()?(e.onload=function(){r.onLoad()},e.onerror=function(){r.onError(e.responseText)}):e.onreadystatechange=function(){if(2===e.readyState)try{var t=e.getResponseHeader("Content-Type");(r.supportsBinary&&"application/octet-stream"===t||"application/octet-stream; charset=UTF-8"===t)&&(e.responseType="arraybuffer")}catch(t){}4===e.readyState&&(200===e.status||1223===e.status?r.onLoad():setTimeout((function(){r.onError("number"==typeof e.status?e.status:0)}),0))},e.send(this.data)}catch(t){return void setTimeout((function(){r.onError(t)}),0)}"undefined"!=typeof document&&(this.index=i.requestsCount++,i.requests[this.index]=this)},i.prototype.onSuccess=function(){this.emit("success"),this.cleanup()},i.prototype.onData=function(t){this.emit("data",t),this.onSuccess()},i.prototype.onError=function(t){this.emit("error",t),this.cleanup(!0)},i.prototype.cleanup=function(t){if(void 0!==this.xhr&&null!==this.xhr){if(this.hasXDR()?this.xhr.onload=this.xhr.onerror=n:this.xhr.onreadystatechange=n,t)try{this.xhr.abort()}catch(t){}"undefined"!=typeof document&&delete i.requests[this.index],this.xhr=null}},i.prototype.onLoad=function(){var t;try{var e;try{e=this.xhr.getResponseHeader("Content-Type")}catch(t){}t=("application/octet-stream"===e||"application/octet-stream; charset=UTF-8"===e)&&this.xhr.response||this.xhr.responseText}catch(t){this.onError(t)}null!=t&&this.onData(t)},i.prototype.hasXDR=function(){return"undefined"!=typeof XDomainRequest&&!this.xs&&this.enablesXDR},i.prototype.abort=function(){this.cleanup()},i.requestsCount=0,i.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",s);else if("function"==typeof addEventListener){addEventListener("onpagehide"in u?"pagehide":"unload",s,!1)}},function(t,e,r){function n(t){var e=t&&t.forceBase64;p&&!e||(this.supportsBinary=!1),o.call(this,t)}var o=r(18),i=r(27),s=r(19),a=r(28),c=r(29);r(3)("engine.io-client:polling"),t.exports=n;var p=null!=new(r(13))({xdomain:!1}).responseType;a(n,o),n.prototype.name="polling",n.prototype.doOpen=function(){this.poll()},n.prototype.pause=function(t){function e(){r.readyState="paused",t()}var r=this;if(this.readyState="pausing",this.polling||!this.writable){var n=0;this.polling&&(n++,this.once("pollComplete",(function(){--n||e()}))),this.writable||(n++,this.once("drain",(function(){--n||e()})))}else e()},n.prototype.poll=function(){this.polling=!0,this.doPoll(),this.emit("poll")},n.prototype.onData=function(t){var e=this;s.decodePayload(t,this.socket.binaryType,(function(t,r,n){return"opening"===e.readyState&&"open"===t.type&&e.onOpen(),"close"===t.type?(e.onClose(),!1):void e.onPacket(t)})),"closed"!==this.readyState&&(this.polling=!1,this.emit("pollComplete"),"open"===this.readyState&&this.poll())},n.prototype.doClose=function(){function t(){e.write([{type:"close"}])}var e=this;"open"===this.readyState?t():this.once("open",t)},n.prototype.write=function(t){var e=this;this.writable=!1;var r=function(){e.writable=!0,e.emit("drain")};s.encodePayload(t,this.supportsBinary,(function(t){e.doWrite(t,r)}))},n.prototype.uri=function(){var t=this.query||{},e=this.secure?"https":"http",r="";return!1!==this.timestampRequests&&(t[this.timestampParam]=c()),this.supportsBinary||t.sid||(t.b64=1),t=i.encode(t),this.port&&("https"===e&&443!==Number(this.port)||"http"===e&&80!==Number(this.port))&&(r=":"+this.port),t.length&&(t="?"+t),e+"://"+(-1!==this.hostname.indexOf(":")?"["+this.hostname+"]":this.hostname)+r+this.path+t}},function(t,e,r){function n(t){this.path=t.path,this.hostname=t.hostname,this.port=t.port,this.secure=t.secure,this.query=t.query,this.timestampParam=t.timestampParam,this.timestampRequests=t.timestampRequests,this.readyState="",this.agent=t.agent||!1,this.socket=t.socket,this.enablesXDR=t.enablesXDR,this.withCredentials=t.withCredentials,this.pfx=t.pfx,this.key=t.key,this.passphrase=t.passphrase,this.cert=t.cert,this.ca=t.ca,this.ciphers=t.ciphers,this.rejectUnauthorized=t.rejectUnauthorized,this.forceNode=t.forceNode,this.isReactNative=t.isReactNative,this.extraHeaders=t.extraHeaders,this.localAddress=t.localAddress}var o=r(19),i=r(5);t.exports=n,i(n.prototype),n.prototype.onError=function(t,e){var r=new Error(t);return r.type="TransportError",r.description=e,this.emit("error",r),this},n.prototype.open=function(){return"closed"!==this.readyState&&""!==this.readyState||(this.readyState="opening",this.doOpen()),this},n.prototype.close=function(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this},n.prototype.send=function(t){if("open"!==this.readyState)throw new Error("Transport not open");this.write(t)},n.prototype.onOpen=function(){this.readyState="open",this.writable=!0,this.emit("open")},n.prototype.onData=function(t){var e=o.decodePacket(t,this.socket.binaryType);this.onPacket(e)},n.prototype.onPacket=function(t){this.emit("packet",t)},n.prototype.onClose=function(){this.readyState="closed",this.emit("close")}},function(t,e,r){function n(t,r){return r("b"+e.packets[t.type]+t.data.data)}function o(t,r,n){if(!r)return e.encodeBase64Packet(t,n);var o=t.data,i=new Uint8Array(o),s=new Uint8Array(1+o.byteLength);s[0]=m[t.type];for(var a=0;a<i.length;a++)s[a+1]=i[a];return n(s.buffer)}function i(t,r,n){if(!r)return e.encodeBase64Packet(t,n);if(y)return function(t,r,n){if(!r)return e.encodeBase64Packet(t,n);var o=new FileReader;return o.onload=function(){e.encodePacket({type:t.type,data:o.result},r,!0,n)},o.readAsArrayBuffer(t.data)}(t,r,n);var o=new Uint8Array(1);return o[0]=m[t.type],n(new b([o.buffer,t.data]))}function s(t,e,r){for(var n=new Array(t.length),o=u(t.length,r),i=function(t,r,o){e(r,(function(e,r){n[t]=r,o(e,n)}))},s=0;s<t.length;s++)i(s,t[s],o)}var a,c=r(20),p=r(21),h=r(22),u=r(23),f=r(24);"undefined"!=typeof ArrayBuffer&&(a=r(25));var l="undefined"!=typeof navigator&&/Android/i.test(navigator.userAgent),d="undefined"!=typeof navigator&&/PhantomJS/i.test(navigator.userAgent),y=l||d;e.protocol=3;var m=e.packets={open:0,close:1,ping:2,pong:3,message:4,upgrade:5,noop:6},g=c(m),v={type:"error",data:"parser error"},b=r(26);e.encodePacket=function(t,e,r,s){"function"==typeof e&&(s=e,e=!1),"function"==typeof r&&(s=r,r=null);var a=void 0===t.data?void 0:t.data.buffer||t.data;if("undefined"!=typeof ArrayBuffer&&a instanceof ArrayBuffer)return o(t,e,s);if(void 0!==b&&a instanceof b)return i(t,e,s);if(a&&a.base64)return n(t,s);var c=m[t.type];return void 0!==t.data&&(c+=r?f.encode(String(t.data),{strict:!1}):String(t.data)),s(""+c)},e.encodeBase64Packet=function(t,r){var n,o="b"+e.packets[t.type];if(void 0!==b&&t.data instanceof b){var i=new FileReader;return i.onload=function(){var t=i.result.split(",")[1];r(o+t)},i.readAsDataURL(t.data)}try{n=String.fromCharCode.apply(null,new Uint8Array(t.data))}catch(e){for(var s=new Uint8Array(t.data),a=new Array(s.length),c=0;c<s.length;c++)a[c]=s[c];n=String.fromCharCode.apply(null,a)}return o+=btoa(n),r(o)},e.decodePacket=function(t,r,n){if(void 0===t)return v;if("string"==typeof t){if("b"===t.charAt(0))return e.decodeBase64Packet(t.substr(1),r);if(n&&!1===(t=function(t){try{t=f.decode(t,{strict:!1})}catch(t){return!1}return t}(t)))return v;var o=t.charAt(0);return Number(o)==o&&g[o]?t.length>1?{type:g[o],data:t.substring(1)}:{type:g[o]}:v}o=new Uint8Array(t)[0];var i=h(t,1);return b&&"blob"===r&&(i=new b([i])),{type:g[o],data:i}},e.decodeBase64Packet=function(t,e){var r=g[t.charAt(0)];if(!a)return{type:r,data:{base64:!0,data:t.substr(1)}};var n=a.decode(t.substr(1));return"blob"===e&&b&&(n=new b([n])),{type:r,data:n}},e.encodePayload=function(t,r,n){"function"==typeof r&&(n=r,r=null);var o=p(t);return r&&o?b&&!y?e.encodePayloadAsBlob(t,n):e.encodePayloadAsArrayBuffer(t,n):t.length?void s(t,(function(t,n){e.encodePacket(t,!!o&&r,!1,(function(t){n(null,function(t){return t.length+":"+t}(t))}))}),(function(t,e){return n(e.join(""))})):n("0:")},e.decodePayload=function(t,r,n){if("string"!=typeof t)return e.decodePayloadAsBinary(t,r,n);var o;if("function"==typeof r&&(n=r,r=null),""===t)return n(v,0,1);for(var i,s,a="",c=0,p=t.length;c<p;c++){var h=t.charAt(c);if(":"===h){if(""===a||a!=(i=Number(a)))return n(v,0,1);if(a!=(s=t.substr(c+1,i)).length)return n(v,0,1);if(s.length){if(o=e.decodePacket(s,r,!1),v.type===o.type&&v.data===o.data)return n(v,0,1);if(!1===n(o,c+i,p))return}c+=i,a=""}else a+=h}return""!==a?n(v,0,1):void 0},e.encodePayloadAsArrayBuffer=function(t,r){return t.length?void s(t,(function(t,r){e.encodePacket(t,!0,!0,(function(t){return r(null,t)}))}),(function(t,e){var n=e.reduce((function(t,e){var r;return t+(r="string"==typeof e?e.length:e.byteLength).toString().length+r+2}),0),o=new Uint8Array(n),i=0;return e.forEach((function(t){var e="string"==typeof t,r=t;if(e){for(var n=new Uint8Array(t.length),s=0;s<t.length;s++)n[s]=t.charCodeAt(s);r=n.buffer}o[i++]=e?0:1;var a=r.byteLength.toString();for(s=0;s<a.length;s++)o[i++]=parseInt(a[s]);o[i++]=255;for(n=new Uint8Array(r),s=0;s<n.length;s++)o[i++]=n[s]})),r(o.buffer)})):r(new ArrayBuffer(0))},e.encodePayloadAsBlob=function(t,r){s(t,(function(t,r){e.encodePacket(t,!0,!0,(function(t){var e=new Uint8Array(1);if(e[0]=1,"string"==typeof t){for(var n=new Uint8Array(t.length),o=0;o<t.length;o++)n[o]=t.charCodeAt(o);t=n.buffer,e[0]=0}var i=(t instanceof ArrayBuffer?t.byteLength:t.size).toString(),s=new Uint8Array(i.length+1);for(o=0;o<i.length;o++)s[o]=parseInt(i[o]);if(s[i.length]=255,b){var a=new b([e.buffer,s.buffer,t]);r(null,a)}}))}),(function(t,e){return r(new b(e))}))},e.decodePayloadAsBinary=function(t,r,n){"function"==typeof r&&(n=r,r=null);for(var o=t,i=[];o.byteLength>0;){for(var s=new Uint8Array(o),a=0===s[0],c="",p=1;255!==s[p];p++){if(c.length>310)return n(v,0,1);c+=s[p]}o=h(o,2+c.length),c=parseInt(c);var u=h(o,0,c);if(a)try{u=String.fromCharCode.apply(null,new Uint8Array(u))}catch(t){var f=new Uint8Array(u);u="";for(p=0;p<f.length;p++)u+=String.fromCharCode(f[p])}i.push(u),o=h(o,c)}var l=i.length;i.forEach((function(t,o){n(e.decodePacket(t,r,!0),o,l)}))}},function(t,e){t.exports=Object.keys||function(t){var e=[],r=Object.prototype.hasOwnProperty;for(var n in t)r.call(t,n)&&e.push(n);return e}},function(t,e,r){var n=r(7),o=Object.prototype.toString,i="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===o.call(Blob),s="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===o.call(File);t.exports=function t(e){if(!e||"object"!=typeof e)return!1;if(n(e)){for(var r=0,o=e.length;r<o;r++)if(t(e[r]))return!0;return!1}if("function"==typeof Buffer&&Buffer.isBuffer&&Buffer.isBuffer(e)||"function"==typeof ArrayBuffer&&e instanceof ArrayBuffer||i&&e instanceof Blob||s&&e instanceof File)return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return t(e.toJSON(),!0);for(var a in e)if(Object.prototype.hasOwnProperty.call(e,a)&&t(e[a]))return!0;return!1}},function(t,e){t.exports=function(t,e,r){var n=t.byteLength;if(e=e||0,r=r||n,t.slice)return t.slice(e,r);if(e<0&&(e+=n),r<0&&(r+=n),r>n&&(r=n),e>=n||e>=r||0===n)return new ArrayBuffer(0);for(var o=new Uint8Array(t),i=new Uint8Array(r-e),s=e,a=0;s<r;s++,a++)i[a]=o[s];return i.buffer}},function(t,e){function r(){}t.exports=function(t,e,n){function o(t,r){if(o.count<=0)throw new Error("after called too many times");--o.count,t?(i=!0,e(t),e=n):0!==o.count||i||e(null,r)}var i=!1;return n=n||r,o.count=t,0===t?e():o}},function(t,e){function r(t){for(var e,r,n=[],o=0,i=t.length;o<i;)(e=t.charCodeAt(o++))>=55296&&e<=56319&&o<i?56320==(64512&(r=t.charCodeAt(o++)))?n.push(((1023&e)<<10)+(1023&r)+65536):(n.push(e),o--):n.push(e);return n}function n(t,e){if(t>=55296&&t<=57343){if(e)throw Error("Lone surrogate U+"+t.toString(16).toUpperCase()+" is not a scalar value");return!1}return!0}function o(t,e){return u(t>>e&63|128)}function i(t,e){if(0==(4294967168&t))return u(t);var r="";return 0==(4294965248&t)?r=u(t>>6&31|192):0==(4294901760&t)?(n(t,e)||(t=65533),r=u(t>>12&15|224),r+=o(t,6)):0==(4292870144&t)&&(r=u(t>>18&7|240),r+=o(t,12),r+=o(t,6)),r+u(63&t|128)}function s(){if(h>=p)throw Error("Invalid byte index");var t=255&c[h];if(h++,128==(192&t))return 63&t;throw Error("Invalid continuation byte")}function a(t){var e,r;if(h>p)throw Error("Invalid byte index");if(h==p)return!1;if(e=255&c[h],h++,0==(128&e))return e;if(192==(224&e)){if((r=(31&e)<<6|s())>=128)return r;throw Error("Invalid continuation byte")}if(224==(240&e)){if((r=(15&e)<<12|s()<<6|s())>=2048)return n(r,t)?r:65533;throw Error("Invalid continuation byte")}if(240==(248&e)&&((r=(7&e)<<18|s()<<12|s()<<6|s())>=65536&&r<=1114111))return r;throw Error("Invalid UTF-8 detected")}/*! https://mths.be/utf8js v2.1.2 by @mathias */
+var c,p,h,u=String.fromCharCode;t.exports={version:"2.1.2",encode:function(t,e){for(var n=!1!==(e=e||{}).strict,o=r(t),s=o.length,a=-1,c="";++a<s;)c+=i(o[a],n);return c},decode:function(t,e){var n=!1!==(e=e||{}).strict;c=r(t),p=c.length,h=0;for(var o,i=[];!1!==(o=a(n));)i.push(o);return function(t){for(var e,r=t.length,n=-1,o="";++n<r;)(e=t[n])>65535&&(o+=u((e-=65536)>>>10&1023|55296),e=56320|1023&e),o+=u(e);return o}(i)}}},function(t,e){!function(t){"use strict";e.encode=function(e){var r,n=new Uint8Array(e),o=n.length,i="";for(r=0;r<o;r+=3)i+=t[n[r]>>2],i+=t[(3&n[r])<<4|n[r+1]>>4],i+=t[(15&n[r+1])<<2|n[r+2]>>6],i+=t[63&n[r+2]];return o%3==2?i=i.substring(0,i.length-1)+"=":o%3==1&&(i=i.substring(0,i.length-2)+"=="),i},e.decode=function(e){var r,n,o,i,s,a=.75*e.length,c=e.length,p=0;"="===e[e.length-1]&&(a--,"="===e[e.length-2]&&a--);var h=new ArrayBuffer(a),u=new Uint8Array(h);for(r=0;r<c;r+=4)n=t.indexOf(e[r]),o=t.indexOf(e[r+1]),i=t.indexOf(e[r+2]),s=t.indexOf(e[r+3]),u[p++]=n<<2|o>>4,u[p++]=(15&o)<<4|i>>2,u[p++]=(3&i)<<6|63&s;return h}}("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")},function(t,e){function r(t){return t.map((function(t){if(t.buffer instanceof ArrayBuffer){var e=t.buffer;if(t.byteLength!==e.byteLength){var r=new Uint8Array(t.byteLength);r.set(new Uint8Array(e,t.byteOffset,t.byteLength)),e=r.buffer}return e}return t}))}function n(t,e){e=e||{};var n=new i;return r(t).forEach((function(t){n.append(t)})),e.type?n.getBlob(e.type):n.getBlob()}function o(t,e){return new Blob(r(t),e||{})}var i=void 0!==i?i:"undefined"!=typeof WebKitBlobBuilder?WebKitBlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder&&MozBlobBuilder,s=function(){try{return 2===new Blob(["hi"]).size}catch(t){return!1}}(),a=s&&function(){try{return 2===new Blob([new Uint8Array([1,2])]).size}catch(t){return!1}}(),c=i&&i.prototype.append&&i.prototype.getBlob;"undefined"!=typeof Blob&&(n.prototype=Blob.prototype,o.prototype=Blob.prototype),t.exports=s?a?Blob:o:c?n:void 0},function(t,e){e.encode=function(t){var e="";for(var r in t)t.hasOwnProperty(r)&&(e.length&&(e+="&"),e+=encodeURIComponent(r)+"="+encodeURIComponent(t[r]));return e},e.decode=function(t){for(var e={},r=t.split("&"),n=0,o=r.length;n<o;n++){var i=r[n].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}},function(t,e){t.exports=function(t,e){var r=function(){};r.prototype=e.prototype,t.prototype=new r,t.prototype.constructor=t}},function(t,e){"use strict";function r(t){var e="";do{e=i[t%s]+e,t=Math.floor(t/s)}while(t>0);return e}function n(){var t=r(+new Date);return t!==o?(c=0,o=t):t+"."+r(c++)}for(var o,i="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),s=64,a={},c=0,p=0;p<s;p++)a[i[p]]=p;n.encode=r,n.decode=function(t){var e=0;for(p=0;p<t.length;p++)e=e*s+a[t.charAt(p)];return e},t.exports=n},function(t,e,r){function n(){}function o(t){i.call(this,t),this.query=this.query||{},c||(c=a.___eio=a.___eio||[]),this.index=c.length;var e=this;c.push((function(t){e.onData(t)})),this.query.j=this.index,"function"==typeof addEventListener&&addEventListener("beforeunload",(function(){e.script&&(e.script.onerror=n)}),!1)}var i=r(17),s=r(28),a=r(15);t.exports=o;var c,p=/\n/g,h=/\\n/g;s(o,i),o.prototype.supportsBinary=!1,o.prototype.doClose=function(){this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),this.form&&(this.form.parentNode.removeChild(this.form),this.form=null,this.iframe=null),i.prototype.doClose.call(this)},o.prototype.doPoll=function(){var t=this,e=document.createElement("script");this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),e.async=!0,e.src=this.uri(),e.onerror=function(e){t.onError("jsonp poll error",e)};var r=document.getElementsByTagName("script")[0];r?r.parentNode.insertBefore(e,r):(document.head||document.body).appendChild(e),this.script=e,"undefined"!=typeof navigator&&/gecko/i.test(navigator.userAgent)&&setTimeout((function(){var t=document.createElement("iframe");document.body.appendChild(t),document.body.removeChild(t)}),100)},o.prototype.doWrite=function(t,e){function r(){n(),e()}function n(){if(o.iframe)try{o.form.removeChild(o.iframe)}catch(t){o.onError("jsonp polling iframe removal error",t)}try{var t='<iframe src="javascript:0" name="'+o.iframeId+'">';i=document.createElement(t)}catch(t){(i=document.createElement("iframe")).name=o.iframeId,i.src="javascript:0"}i.id=o.iframeId,o.form.appendChild(i),o.iframe=i}var o=this;if(!this.form){var i,s=document.createElement("form"),a=document.createElement("textarea"),c=this.iframeId="eio_iframe_"+this.index;s.className="socketio",s.style.position="absolute",s.style.top="-1000px",s.style.left="-1000px",s.target=c,s.method="POST",s.setAttribute("accept-charset","utf-8"),a.name="d",s.appendChild(a),document.body.appendChild(s),this.form=s,this.area=a}this.form.action=this.uri(),n(),t=t.replace(h,"\\\n"),this.area.value=t.replace(p,"\\n");try{this.form.submit()}catch(t){}this.iframe.attachEvent?this.iframe.onreadystatechange=function(){"complete"===o.iframe.readyState&&r()}:this.iframe.onload=r}},function(t,e,r){function n(t){t&&t.forceBase64&&(this.supportsBinary=!1),this.perMessageDeflate=t.perMessageDeflate,this.usingBrowserWebSocket=o&&!t.forceNode,this.protocols=t.protocols,this.usingBrowserWebSocket||(u=i),s.call(this,t)}var o,i,s=r(18),a=r(19),c=r(27),p=r(28),h=r(29);if(r(3)("engine.io-client:websocket"),"undefined"!=typeof WebSocket?o=WebSocket:"undefined"!=typeof self&&(o=self.WebSocket||self.MozWebSocket),"undefined"==typeof window)try{i=r(32)}catch(t){}var u=o||i;t.exports=n,p(n,s),n.prototype.name="websocket",n.prototype.supportsBinary=!0,n.prototype.doOpen=function(){if(this.check()){var t=this.uri(),e=this.protocols,r={};this.isReactNative||(r.agent=this.agent,r.perMessageDeflate=this.perMessageDeflate,r.pfx=this.pfx,r.key=this.key,r.passphrase=this.passphrase,r.cert=this.cert,r.ca=this.ca,r.ciphers=this.ciphers,r.rejectUnauthorized=this.rejectUnauthorized),this.extraHeaders&&(r.headers=this.extraHeaders),this.localAddress&&(r.localAddress=this.localAddress);try{this.ws=this.usingBrowserWebSocket&&!this.isReactNative?e?new u(t,e):new u(t):new u(t,e,r)}catch(t){return this.emit("error",t)}void 0===this.ws.binaryType&&(this.supportsBinary=!1),this.ws.supports&&this.ws.supports.binary?(this.supportsBinary=!0,this.ws.binaryType="nodebuffer"):this.ws.binaryType="arraybuffer",this.addEventListeners()}},n.prototype.addEventListeners=function(){var t=this;this.ws.onopen=function(){t.onOpen()},this.ws.onclose=function(){t.onClose()},this.ws.onmessage=function(e){t.onData(e.data)},this.ws.onerror=function(e){t.onError("websocket error",e)}},n.prototype.write=function(t){var e=this;this.writable=!1;for(var r=t.length,n=0,o=r;n<o;n++)!function(t){a.encodePacket(t,e.supportsBinary,(function(n){if(!e.usingBrowserWebSocket){var o={};if(t.options&&(o.compress=t.options.compress),e.perMessageDeflate)("string"==typeof n?Buffer.byteLength(n):n.length)<e.perMessageDeflate.threshold&&(o.compress=!1)}try{e.usingBrowserWebSocket?e.ws.send(n):e.ws.send(n,o)}catch(t){}--r||(e.emit("flush"),setTimeout((function(){e.writable=!0,e.emit("drain")}),0))}))}(t[n])},n.prototype.onClose=function(){s.prototype.onClose.call(this)},n.prototype.doClose=function(){void 0!==this.ws&&this.ws.close()},n.prototype.uri=function(){var t=this.query||{},e=this.secure?"wss":"ws",r="";return this.port&&("wss"===e&&443!==Number(this.port)||"ws"===e&&80!==Number(this.port))&&(r=":"+this.port),this.timestampRequests&&(t[this.timestampParam]=h()),this.supportsBinary||(t.b64=1),(t=c.encode(t)).length&&(t="?"+t),e+"://"+(-1!==this.hostname.indexOf(":")?"["+this.hostname+"]":this.hostname)+r+this.path+t},n.prototype.check=function(){return!(!u||"__initialize"in u&&this.name===n.prototype.name)}},function(t,e){},function(t,e){var r=[].indexOf;t.exports=function(t,e){if(r)return t.indexOf(e);for(var n=0;n<t.length;++n)if(t[n]===e)return n;return-1}},function(t,e,r){"use strict";function n(t,e,r){this.io=t,this.nsp=e,this.json=this,this.ids=0,this.acks={},this.receiveBuffer=[],this.sendBuffer=[],this.connected=!1,this.disconnected=!0,this.flags={},r&&r.query&&(this.query=r.query),this.io.autoConnect&&this.open()}var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i=r(4),s=r(5),a=r(35),c=r(36),p=r(37),h=(r(3)("socket.io-client:socket"),r(27)),u=r(21);t.exports=n;var f={connect:1,connect_error:1,connect_timeout:1,connecting:1,disconnect:1,error:1,reconnect:1,reconnect_attempt:1,reconnect_failed:1,reconnect_error:1,reconnecting:1,ping:1,pong:1},l=s.prototype.emit;s(n.prototype),n.prototype.subEvents=function(){if(!this.subs){var t=this.io;this.subs=[c(t,"open",p(this,"onopen")),c(t,"packet",p(this,"onpacket")),c(t,"close",p(this,"onclose"))]}},n.prototype.open=n.prototype.connect=function(){return this.connected||(this.subEvents(),this.io.reconnecting||this.io.open(),"open"===this.io.readyState&&this.onopen(),this.emit("connecting")),this},n.prototype.send=function(){var t=a(arguments);return t.unshift("message"),this.emit.apply(this,t),this},n.prototype.emit=function(t){if(f.hasOwnProperty(t))return l.apply(this,arguments),this;var e=a(arguments),r={type:(void 0!==this.flags.binary?this.flags.binary:u(e))?i.BINARY_EVENT:i.EVENT,data:e,options:{}};return r.options.compress=!this.flags||!1!==this.flags.compress,"function"==typeof e[e.length-1]&&(this.acks[this.ids]=e.pop(),r.id=this.ids++),this.connected?this.packet(r):this.sendBuffer.push(r),this.flags={},this},n.prototype.packet=function(t){t.nsp=this.nsp,this.io.packet(t)},n.prototype.onopen=function(){if("/"!==this.nsp)if(this.query){var t="object"===o(this.query)?h.encode(this.query):this.query;this.packet({type:i.CONNECT,query:t})}else this.packet({type:i.CONNECT})},n.prototype.onclose=function(t){this.connected=!1,this.disconnected=!0,delete this.id,this.emit("disconnect",t)},n.prototype.onpacket=function(t){var e=t.nsp===this.nsp,r=t.type===i.ERROR&&"/"===t.nsp;if(e||r)switch(t.type){case i.CONNECT:this.onconnect();break;case i.EVENT:case i.BINARY_EVENT:this.onevent(t);break;case i.ACK:case i.BINARY_ACK:this.onack(t);break;case i.DISCONNECT:this.ondisconnect();break;case i.ERROR:this.emit("error",t.data)}},n.prototype.onevent=function(t){var e=t.data||[];null!=t.id&&e.push(this.ack(t.id)),this.connected?l.apply(this,e):this.receiveBuffer.push(e)},n.prototype.ack=function(t){var e=this,r=!1;return function(){if(!r){r=!0;var n=a(arguments);e.packet({type:u(n)?i.BINARY_ACK:i.ACK,id:t,data:n})}}},n.prototype.onack=function(t){var e=this.acks[t.id];"function"==typeof e&&(e.apply(this,t.data),delete this.acks[t.id])},n.prototype.onconnect=function(){this.connected=!0,this.disconnected=!1,this.emit("connect"),this.emitBuffered()},n.prototype.emitBuffered=function(){var t;for(t=0;t<this.receiveBuffer.length;t++)l.apply(this,this.receiveBuffer[t]);for(this.receiveBuffer=[],t=0;t<this.sendBuffer.length;t++)this.packet(this.sendBuffer[t]);this.sendBuffer=[]},n.prototype.ondisconnect=function(){this.destroy(),this.onclose("io server disconnect")},n.prototype.destroy=function(){if(this.subs){for(var t=0;t<this.subs.length;t++)this.subs[t].destroy();this.subs=null}this.io.destroy(this)},n.prototype.close=n.prototype.disconnect=function(){return this.connected&&this.packet({type:i.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this},n.prototype.compress=function(t){return this.flags.compress=t,this},n.prototype.binary=function(t){return this.flags.binary=t,this}},function(t,e){t.exports=function(t,e){for(var r=[],n=(e=e||0)||0;n<t.length;n++)r[n-e]=t[n];return r}},function(t,e){"use strict";t.exports=function(t,e,r){return t.on(e,r),{destroy:function(){t.removeListener(e,r)}}}},function(t,e){var r=[].slice;t.exports=function(t,e){if("string"==typeof e&&(e=t[e]),"function"!=typeof e)throw new Error("bind() requires a function");var n=r.call(arguments,2);return function(){return e.apply(t,n.concat(r.call(arguments)))}}},function(t,e){function r(t){t=t||{},this.ms=t.min||100,this.max=t.max||1e4,this.factor=t.factor||2,this.jitter=t.jitter>0&&t.jitter<=1?t.jitter:0,this.attempts=0}t.exports=r,r.prototype.duration=function(){var t=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),r=Math.floor(e*this.jitter*t);t=0==(1&Math.floor(10*e))?t-r:t+r}return 0|Math.min(t,this.max)},r.prototype.reset=function(){this.attempts=0},r.prototype.setMin=function(t){this.ms=t},r.prototype.setMax=function(t){this.max=t},r.prototype.setJitter=function(t){this.jitter=t}}])}));
\ No newline at end of file
index 6bc993c..61cbf74 100644 (file)
@@ -1,94 +1 @@
-
-/**
- * Module dependencies.
- */
-
-var url = require('./url');
-var parser = require('socket.io-parser');
-var Manager = require('./manager');
-var debug = require('debug')('socket.io-client');
-
-/**
- * Module exports.
- */
-
-module.exports = exports = lookup;
-
-/**
- * Managers cache.
- */
-
-var cache = exports.managers = {};
-
-/**
- * Looks up an existing `Manager` for multiplexing.
- * If the user summons:
- *
- *   `io('http://localhost/a');`
- *   `io('http://localhost/b');`
- *
- * We reuse the existing instance based on same scheme/port/host,
- * and we initialize sockets for each namespace.
- *
- * @api public
- */
-
-function lookup (uri, opts) {
-  if (typeof uri === 'object') {
-    opts = uri;
-    uri = undefined;
-  }
-
-  opts = opts || {};
-
-  var parsed = url(uri);
-  var source = parsed.source;
-  var id = parsed.id;
-  var path = parsed.path;
-  var sameNamespace = cache[id] && path in cache[id].nsps;
-  var newConnection = opts.forceNew || opts['force new connection'] ||
-                      false === opts.multiplex || sameNamespace;
-
-  var io;
-
-  if (newConnection) {
-    debug('ignoring socket cache for %s', source);
-    io = Manager(source, opts);
-  } else {
-    if (!cache[id]) {
-      debug('new io instance for %s', source);
-      cache[id] = Manager(source, opts);
-    }
-    io = cache[id];
-  }
-  if (parsed.query && !opts.query) {
-    opts.query = parsed.query;
-  }
-  return io.socket(parsed.path, opts);
-}
-
-/**
- * Protocol version.
- *
- * @api public
- */
-
-exports.protocol = parser.protocol;
-
-/**
- * `connect`.
- *
- * @param {String} uri
- * @api public
- */
-
-exports.connect = lookup;
-
-/**
- * Expose constructors for standalone build.
- *
- * @api public
- */
-
-exports.Manager = require('./manager');
-exports.Socket = require('./socket');
+var url=require("./url"),parser=require("socket.io-parser"),Manager=require("./manager"),debug=require("debug")("socket.io-client");module.exports=exports=lookup;var cache=exports.managers={};function lookup(e,r){"object"==typeof e&&(r=e,e=void 0),r=r||{};var o,c=url(e),a=c.source,t=c.id,u=c.path,n=cache[t]&&u in cache[t].nsps;return r.forceNew||r["force new connection"]||!1===r.multiplex||n?(debug("ignoring socket cache for %s",a),o=Manager(a,r)):(cache[t]||(debug("new io instance for %s",a),cache[t]=Manager(a,r)),o=cache[t]),c.query&&!r.query&&(r.query=c.query),o.socket(c.path,r)}exports.protocol=parser.protocol,exports.connect=lookup,exports.Manager=require("./manager"),exports.Socket=require("./socket");
\ No newline at end of file
index 8fb6403..745962e 100644 (file)
@@ -1,577 +1 @@
-
-/**
- * Module dependencies.
- */
-
-var eio = require('engine.io-client');
-var Socket = require('./socket');
-var Emitter = require('component-emitter');
-var parser = require('socket.io-parser');
-var on = require('./on');
-var bind = require('component-bind');
-var debug = require('debug')('socket.io-client:manager');
-var indexOf = require('indexof');
-var Backoff = require('backo2');
-
-/**
- * IE6+ hasOwnProperty
- */
-
-var has = Object.prototype.hasOwnProperty;
-
-/**
- * Module exports
- */
-
-module.exports = Manager;
-
-/**
- * `Manager` constructor.
- *
- * @param {String} engine instance or engine uri/opts
- * @param {Object} options
- * @api public
- */
-
-function Manager (uri, opts) {
-  if (!(this instanceof Manager)) return new Manager(uri, opts);
-  if (uri && ('object' === typeof uri)) {
-    opts = uri;
-    uri = undefined;
-  }
-  opts = opts || {};
-
-  opts.path = opts.path || '/socket.io';
-  this.nsps = {};
-  this.subs = [];
-  this.opts = opts;
-  this.reconnection(opts.reconnection !== false);
-  this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
-  this.reconnectionDelay(opts.reconnectionDelay || 1000);
-  this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
-  this.randomizationFactor(opts.randomizationFactor || 0.5);
-  this.backoff = new Backoff({
-    min: this.reconnectionDelay(),
-    max: this.reconnectionDelayMax(),
-    jitter: this.randomizationFactor()
-  });
-  this.timeout(null == opts.timeout ? 20000 : opts.timeout);
-  this.readyState = 'closed';
-  this.uri = uri;
-  this.connecting = [];
-  this.lastPing = null;
-  this.encoding = false;
-  this.packetBuffer = [];
-  var _parser = opts.parser || parser;
-  this.encoder = new _parser.Encoder();
-  this.decoder = new _parser.Decoder();
-  this.autoConnect = opts.autoConnect !== false;
-  if (this.autoConnect) this.open();
-}
-
-/**
- * Propagate given event to sockets and emit on `this`
- *
- * @api private
- */
-
-Manager.prototype.emitAll = function () {
-  this.emit.apply(this, arguments);
-  for (var nsp in this.nsps) {
-    if (has.call(this.nsps, nsp)) {
-      this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
-    }
-  }
-};
-
-/**
- * Update `socket.id` of all sockets
- *
- * @api private
- */
-
-Manager.prototype.updateSocketIds = function () {
-  for (var nsp in this.nsps) {
-    if (has.call(this.nsps, nsp)) {
-      this.nsps[nsp].id = this.generateId(nsp);
-    }
-  }
-};
-
-/**
- * generate `socket.id` for the given `nsp`
- *
- * @param {String} nsp
- * @return {String}
- * @api private
- */
-
-Manager.prototype.generateId = function (nsp) {
-  return (nsp === '/' ? '' : (nsp + '#')) + this.engine.id;
-};
-
-/**
- * Mix in `Emitter`.
- */
-
-Emitter(Manager.prototype);
-
-/**
- * Sets the `reconnection` config.
- *
- * @param {Boolean} true/false if it should automatically reconnect
- * @return {Manager} self or value
- * @api public
- */
-
-Manager.prototype.reconnection = function (v) {
-  if (!arguments.length) return this._reconnection;
-  this._reconnection = !!v;
-  return this;
-};
-
-/**
- * Sets the reconnection attempts config.
- *
- * @param {Number} max reconnection attempts before giving up
- * @return {Manager} self or value
- * @api public
- */
-
-Manager.prototype.reconnectionAttempts = function (v) {
-  if (!arguments.length) return this._reconnectionAttempts;
-  this._reconnectionAttempts = v;
-  return this;
-};
-
-/**
- * Sets the delay between reconnections.
- *
- * @param {Number} delay
- * @return {Manager} self or value
- * @api public
- */
-
-Manager.prototype.reconnectionDelay = function (v) {
-  if (!arguments.length) return this._reconnectionDelay;
-  this._reconnectionDelay = v;
-  this.backoff && this.backoff.setMin(v);
-  return this;
-};
-
-Manager.prototype.randomizationFactor = function (v) {
-  if (!arguments.length) return this._randomizationFactor;
-  this._randomizationFactor = v;
-  this.backoff && this.backoff.setJitter(v);
-  return this;
-};
-
-/**
- * Sets the maximum delay between reconnections.
- *
- * @param {Number} delay
- * @return {Manager} self or value
- * @api public
- */
-
-Manager.prototype.reconnectionDelayMax = function (v) {
-  if (!arguments.length) return this._reconnectionDelayMax;
-  this._reconnectionDelayMax = v;
-  this.backoff && this.backoff.setMax(v);
-  return this;
-};
-
-/**
- * Sets the connection timeout. `false` to disable
- *
- * @return {Manager} self or value
- * @api public
- */
-
-Manager.prototype.timeout = function (v) {
-  if (!arguments.length) return this._timeout;
-  this._timeout = v;
-  return this;
-};
-
-/**
- * Starts trying to reconnect if reconnection is enabled and we have not
- * started reconnecting yet
- *
- * @api private
- */
-
-Manager.prototype.maybeReconnectOnOpen = function () {
-  // Only try to reconnect if it's the first time we're connecting
-  if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
-    // keeps reconnection from firing twice for the same reconnection loop
-    this.reconnect();
-  }
-};
-
-/**
- * Sets the current transport `socket`.
- *
- * @param {Function} optional, callback
- * @return {Manager} self
- * @api public
- */
-
-Manager.prototype.open =
-Manager.prototype.connect = function (fn, opts) {
-  debug('readyState %s', this.readyState);
-  if (~this.readyState.indexOf('open')) return this;
-
-  debug('opening %s', this.uri);
-  this.engine = eio(this.uri, this.opts);
-  var socket = this.engine;
-  var self = this;
-  this.readyState = 'opening';
-  this.skipReconnect = false;
-
-  // emit `open`
-  var openSub = on(socket, 'open', function () {
-    self.onopen();
-    fn && fn();
-  });
-
-  // emit `connect_error`
-  var errorSub = on(socket, 'error', function (data) {
-    debug('connect_error');
-    self.cleanup();
-    self.readyState = 'closed';
-    self.emitAll('connect_error', data);
-    if (fn) {
-      var err = new Error('Connection error');
-      err.data = data;
-      fn(err);
-    } else {
-      // Only do this if there is no fn to handle the error
-      self.maybeReconnectOnOpen();
-    }
-  });
-
-  // emit `connect_timeout`
-  if (false !== this._timeout) {
-    var timeout = this._timeout;
-    debug('connect attempt will timeout after %d', timeout);
-
-    if (timeout === 0) {
-      openSub.destroy(); // prevents a race condition with the 'open' event
-    }
-
-    // set timer
-    var timer = setTimeout(function () {
-      debug('connect attempt timed out after %d', timeout);
-      openSub.destroy();
-      socket.close();
-      socket.emit('error', 'timeout');
-      self.emitAll('connect_timeout', timeout);
-    }, timeout);
-
-    this.subs.push({
-      destroy: function () {
-        clearTimeout(timer);
-      }
-    });
-  }
-
-  this.subs.push(openSub);
-  this.subs.push(errorSub);
-
-  return this;
-};
-
-/**
- * Called upon transport open.
- *
- * @api private
- */
-
-Manager.prototype.onopen = function () {
-  debug('open');
-
-  // clear old subs
-  this.cleanup();
-
-  // mark as open
-  this.readyState = 'open';
-  this.emit('open');
-
-  // add new subs
-  var socket = this.engine;
-  this.subs.push(on(socket, 'data', bind(this, 'ondata')));
-  this.subs.push(on(socket, 'ping', bind(this, 'onping')));
-  this.subs.push(on(socket, 'pong', bind(this, 'onpong')));
-  this.subs.push(on(socket, 'error', bind(this, 'onerror')));
-  this.subs.push(on(socket, 'close', bind(this, 'onclose')));
-  this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
-};
-
-/**
- * Called upon a ping.
- *
- * @api private
- */
-
-Manager.prototype.onping = function () {
-  this.lastPing = new Date();
-  this.emitAll('ping');
-};
-
-/**
- * Called upon a packet.
- *
- * @api private
- */
-
-Manager.prototype.onpong = function () {
-  this.emitAll('pong', new Date() - this.lastPing);
-};
-
-/**
- * Called with data.
- *
- * @api private
- */
-
-Manager.prototype.ondata = function (data) {
-  this.decoder.add(data);
-};
-
-/**
- * Called when parser fully decodes a packet.
- *
- * @api private
- */
-
-Manager.prototype.ondecoded = function (packet) {
-  this.emit('packet', packet);
-};
-
-/**
- * Called upon socket error.
- *
- * @api private
- */
-
-Manager.prototype.onerror = function (err) {
-  debug('error', err);
-  this.emitAll('error', err);
-};
-
-/**
- * Creates a new socket for the given `nsp`.
- *
- * @return {Socket}
- * @api public
- */
-
-Manager.prototype.socket = function (nsp, opts) {
-  var socket = this.nsps[nsp];
-  if (!socket) {
-    socket = new Socket(this, nsp, opts);
-    this.nsps[nsp] = socket;
-    var self = this;
-    socket.on('connecting', onConnecting);
-    socket.on('connect', function () {
-      socket.id = self.generateId(nsp);
-    });
-
-    if (this.autoConnect) {
-      // manually call here since connecting event is fired before listening
-      onConnecting();
-    }
-  }
-
-  function onConnecting () {
-    if (!~indexOf(self.connecting, socket)) {
-      self.connecting.push(socket);
-    }
-  }
-
-  return socket;
-};
-
-/**
- * Called upon a socket close.
- *
- * @param {Socket} socket
- */
-
-Manager.prototype.destroy = function (socket) {
-  var index = indexOf(this.connecting, socket);
-  if (~index) this.connecting.splice(index, 1);
-  if (this.connecting.length) return;
-
-  this.close();
-};
-
-/**
- * Writes a packet.
- *
- * @param {Object} packet
- * @api private
- */
-
-Manager.prototype.packet = function (packet) {
-  debug('writing packet %j', packet);
-  var self = this;
-  if (packet.query && packet.type === 0) packet.nsp += '?' + packet.query;
-
-  if (!self.encoding) {
-    // encode, then write to engine with result
-    self.encoding = true;
-    this.encoder.encode(packet, function (encodedPackets) {
-      for (var i = 0; i < encodedPackets.length; i++) {
-        self.engine.write(encodedPackets[i], packet.options);
-      }
-      self.encoding = false;
-      self.processPacketQueue();
-    });
-  } else { // add packet to the queue
-    self.packetBuffer.push(packet);
-  }
-};
-
-/**
- * If packet buffer is non-empty, begins encoding the
- * next packet in line.
- *
- * @api private
- */
-
-Manager.prototype.processPacketQueue = function () {
-  if (this.packetBuffer.length > 0 && !this.encoding) {
-    var pack = this.packetBuffer.shift();
-    this.packet(pack);
-  }
-};
-
-/**
- * Clean up transport subscriptions and packet buffer.
- *
- * @api private
- */
-
-Manager.prototype.cleanup = function () {
-  debug('cleanup');
-
-  var subsLength = this.subs.length;
-  for (var i = 0; i < subsLength; i++) {
-    var sub = this.subs.shift();
-    sub.destroy();
-  }
-
-  this.packetBuffer = [];
-  this.encoding = false;
-  this.lastPing = null;
-
-  this.decoder.destroy();
-};
-
-/**
- * Close the current socket.
- *
- * @api private
- */
-
-Manager.prototype.close =
-Manager.prototype.disconnect = function () {
-  debug('disconnect');
-  this.skipReconnect = true;
-  this.reconnecting = false;
-  if ('opening' === this.readyState) {
-    // `onclose` will not fire because
-    // an open event never happened
-    this.cleanup();
-  }
-  this.backoff.reset();
-  this.readyState = 'closed';
-  if (this.engine) this.engine.close();
-};
-
-/**
- * Called upon engine close.
- *
- * @api private
- */
-
-Manager.prototype.onclose = function (reason) {
-  debug('onclose');
-
-  this.cleanup();
-  this.backoff.reset();
-  this.readyState = 'closed';
-  this.emit('close', reason);
-
-  if (this._reconnection && !this.skipReconnect) {
-    this.reconnect();
-  }
-};
-
-/**
- * Attempt a reconnection.
- *
- * @api private
- */
-
-Manager.prototype.reconnect = function () {
-  if (this.reconnecting || this.skipReconnect) return this;
-
-  var self = this;
-
-  if (this.backoff.attempts >= this._reconnectionAttempts) {
-    debug('reconnect failed');
-    this.backoff.reset();
-    this.emitAll('reconnect_failed');
-    this.reconnecting = false;
-  } else {
-    var delay = this.backoff.duration();
-    debug('will wait %dms before reconnect attempt', delay);
-
-    this.reconnecting = true;
-    var timer = setTimeout(function () {
-      if (self.skipReconnect) return;
-
-      debug('attempting reconnect');
-      self.emitAll('reconnect_attempt', self.backoff.attempts);
-      self.emitAll('reconnecting', self.backoff.attempts);
-
-      // check again for the case socket closed in above events
-      if (self.skipReconnect) return;
-
-      self.open(function (err) {
-        if (err) {
-          debug('reconnect attempt error');
-          self.reconnecting = false;
-          self.reconnect();
-          self.emitAll('reconnect_error', err.data);
-        } else {
-          debug('reconnect success');
-          self.onreconnect();
-        }
-      });
-    }, delay);
-
-    this.subs.push({
-      destroy: function () {
-        clearTimeout(timer);
-      }
-    });
-  }
-};
-
-/**
- * Called upon successful reconnect.
- *
- * @api private
- */
-
-Manager.prototype.onreconnect = function () {
-  var attempt = this.backoff.attempts;
-  this.reconnecting = false;
-  this.backoff.reset();
-  this.updateSocketIds();
-  this.emitAll('reconnect', attempt);
-};
+var eio=require("engine.io-client"),Socket=require("./socket"),Emitter=require("component-emitter"),parser=require("socket.io-parser"),on=require("./on"),bind=require("component-bind"),debug=require("debug")("socket.io-client:manager"),indexOf=require("indexof"),Backoff=require("backo2"),has=Object.prototype.hasOwnProperty;function Manager(t,e){if(!(this instanceof Manager))return new Manager(t,e);t&&"object"==typeof t&&(e=t,t=void 0),(e=e||{}).path=e.path||"/socket.io",this.nsps={},this.subs=[],this.opts=e,this.reconnection(!1!==e.reconnection),this.reconnectionAttempts(e.reconnectionAttempts||1/0),this.reconnectionDelay(e.reconnectionDelay||1e3),this.reconnectionDelayMax(e.reconnectionDelayMax||5e3),this.randomizationFactor(e.randomizationFactor||.5),this.backoff=new Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==e.timeout?2e4:e.timeout),this.readyState="closed",this.uri=t,this.connecting=[],this.lastPing=null,this.encoding=!1,this.packetBuffer=[];var n=e.parser||parser;this.encoder=new n.Encoder,this.decoder=new n.Decoder,this.autoConnect=!1!==e.autoConnect,this.autoConnect&&this.open()}module.exports=Manager,Manager.prototype.emitAll=function(){for(var t in this.emit.apply(this,arguments),this.nsps)has.call(this.nsps,t)&&this.nsps[t].emit.apply(this.nsps[t],arguments)},Manager.prototype.updateSocketIds=function(){for(var t in this.nsps)has.call(this.nsps,t)&&(this.nsps[t].id=this.generateId(t))},Manager.prototype.generateId=function(t){return("/"===t?"":t+"#")+this.engine.id},Emitter(Manager.prototype),Manager.prototype.reconnection=function(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection},Manager.prototype.reconnectionAttempts=function(t){return arguments.length?(this._reconnectionAttempts=t,this):this._reconnectionAttempts},Manager.prototype.reconnectionDelay=function(t){return arguments.length?(this._reconnectionDelay=t,this.backoff&&this.backoff.setMin(t),this):this._reconnectionDelay},Manager.prototype.randomizationFactor=function(t){return arguments.length?(this._randomizationFactor=t,this.backoff&&this.backoff.setJitter(t),this):this._randomizationFactor},Manager.prototype.reconnectionDelayMax=function(t){return arguments.length?(this._reconnectionDelayMax=t,this.backoff&&this.backoff.setMax(t),this):this._reconnectionDelayMax},Manager.prototype.timeout=function(t){return arguments.length?(this._timeout=t,this):this._timeout},Manager.prototype.maybeReconnectOnOpen=function(){!this.reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()},Manager.prototype.open=Manager.prototype.connect=function(t,e){if(debug("readyState %s",this.readyState),~this.readyState.indexOf("open"))return this;debug("opening %s",this.uri),this.engine=eio(this.uri,this.opts);var n=this.engine,o=this;this.readyState="opening",this.skipReconnect=!1;var i=on(n,"open",(function(){o.onopen(),t&&t()})),s=on(n,"error",(function(e){if(debug("connect_error"),o.cleanup(),o.readyState="closed",o.emitAll("connect_error",e),t){var n=new Error("Connection error");n.data=e,t(n)}else o.maybeReconnectOnOpen()}));if(!1!==this._timeout){var r=this._timeout;debug("connect attempt will timeout after %d",r),0===r&&i.destroy();var c=setTimeout((function(){debug("connect attempt timed out after %d",r),i.destroy(),n.close(),n.emit("error","timeout"),o.emitAll("connect_timeout",r)}),r);this.subs.push({destroy:function(){clearTimeout(c)}})}return this.subs.push(i),this.subs.push(s),this},Manager.prototype.onopen=function(){debug("open"),this.cleanup(),this.readyState="open",this.emit("open");var t=this.engine;this.subs.push(on(t,"data",bind(this,"ondata"))),this.subs.push(on(t,"ping",bind(this,"onping"))),this.subs.push(on(t,"pong",bind(this,"onpong"))),this.subs.push(on(t,"error",bind(this,"onerror"))),this.subs.push(on(t,"close",bind(this,"onclose"))),this.subs.push(on(this.decoder,"decoded",bind(this,"ondecoded")))},Manager.prototype.onping=function(){this.lastPing=new Date,this.emitAll("ping")},Manager.prototype.onpong=function(){this.emitAll("pong",new Date-this.lastPing)},Manager.prototype.ondata=function(t){this.decoder.add(t)},Manager.prototype.ondecoded=function(t){this.emit("packet",t)},Manager.prototype.onerror=function(t){debug("error",t),this.emitAll("error",t)},Manager.prototype.socket=function(t,e){var n=this.nsps[t];if(!n){n=new Socket(this,t,e),this.nsps[t]=n;var o=this;n.on("connecting",i),n.on("connect",(function(){n.id=o.generateId(t)})),this.autoConnect&&i()}function i(){~indexOf(o.connecting,n)||o.connecting.push(n)}return n},Manager.prototype.destroy=function(t){var e=indexOf(this.connecting,t);~e&&this.connecting.splice(e,1),this.connecting.length||this.close()},Manager.prototype.packet=function(t){debug("writing packet %j",t);var e=this;t.query&&0===t.type&&(t.nsp+="?"+t.query),e.encoding?e.packetBuffer.push(t):(e.encoding=!0,this.encoder.encode(t,(function(n){for(var o=0;o<n.length;o++)e.engine.write(n[o],t.options);e.encoding=!1,e.processPacketQueue()})))},Manager.prototype.processPacketQueue=function(){if(this.packetBuffer.length>0&&!this.encoding){var t=this.packetBuffer.shift();this.packet(t)}},Manager.prototype.cleanup=function(){debug("cleanup");for(var t=this.subs.length,e=0;e<t;e++){this.subs.shift().destroy()}this.packetBuffer=[],this.encoding=!1,this.lastPing=null,this.decoder.destroy()},Manager.prototype.close=Manager.prototype.disconnect=function(){debug("disconnect"),this.skipReconnect=!0,this.reconnecting=!1,"opening"===this.readyState&&this.cleanup(),this.backoff.reset(),this.readyState="closed",this.engine&&this.engine.close()},Manager.prototype.onclose=function(t){debug("onclose"),this.cleanup(),this.backoff.reset(),this.readyState="closed",this.emit("close",t),this._reconnection&&!this.skipReconnect&&this.reconnect()},Manager.prototype.reconnect=function(){if(this.reconnecting||this.skipReconnect)return this;var t=this;if(this.backoff.attempts>=this._reconnectionAttempts)debug("reconnect failed"),this.backoff.reset(),this.emitAll("reconnect_failed"),this.reconnecting=!1;else{var e=this.backoff.duration();debug("will wait %dms before reconnect attempt",e),this.reconnecting=!0;var n=setTimeout((function(){t.skipReconnect||(debug("attempting reconnect"),t.emitAll("reconnect_attempt",t.backoff.attempts),t.emitAll("reconnecting",t.backoff.attempts),t.skipReconnect||t.open((function(e){e?(debug("reconnect attempt error"),t.reconnecting=!1,t.reconnect(),t.emitAll("reconnect_error",e.data)):(debug("reconnect success"),t.onreconnect())})))}),e);this.subs.push({destroy:function(){clearTimeout(n)}})}},Manager.prototype.onreconnect=function(){var t=this.backoff.attempts;this.reconnecting=!1,this.backoff.reset(),this.updateSocketIds(),this.emitAll("reconnect",t)};
\ No newline at end of file
index fad9264..fc21c2d 100644 (file)
@@ -1,24 +1 @@
-
-/**
- * Module exports.
- */
-
-module.exports = on;
-
-/**
- * Helper for subscriptions.
- *
- * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
- * @param {String} event name
- * @param {Function} callback
- * @api public
- */
-
-function on (obj, ev, fn) {
-  obj.on(ev, fn);
-  return {
-    destroy: function () {
-      obj.removeListener(ev, fn);
-    }
-  };
-}
+function on(n,o,e){return n.on(o,e),{destroy:function(){n.removeListener(o,e)}}}module.exports=on;
\ No newline at end of file
index a0e1d13..20a2b52 100644 (file)
@@ -1,438 +1 @@
-
-/**
- * Module dependencies.
- */
-
-var parser = require('socket.io-parser');
-var Emitter = require('component-emitter');
-var toArray = require('to-array');
-var on = require('./on');
-var bind = require('component-bind');
-var debug = require('debug')('socket.io-client:socket');
-var parseqs = require('parseqs');
-var hasBin = require('has-binary2');
-
-/**
- * Module exports.
- */
-
-module.exports = exports = Socket;
-
-/**
- * Internal events (blacklisted).
- * These events can't be emitted by the user.
- *
- * @api private
- */
-
-var events = {
-  connect: 1,
-  connect_error: 1,
-  connect_timeout: 1,
-  connecting: 1,
-  disconnect: 1,
-  error: 1,
-  reconnect: 1,
-  reconnect_attempt: 1,
-  reconnect_failed: 1,
-  reconnect_error: 1,
-  reconnecting: 1,
-  ping: 1,
-  pong: 1
-};
-
-/**
- * Shortcut to `Emitter#emit`.
- */
-
-var emit = Emitter.prototype.emit;
-
-/**
- * `Socket` constructor.
- *
- * @api public
- */
-
-function Socket (io, nsp, opts) {
-  this.io = io;
-  this.nsp = nsp;
-  this.json = this; // compat
-  this.ids = 0;
-  this.acks = {};
-  this.receiveBuffer = [];
-  this.sendBuffer = [];
-  this.connected = false;
-  this.disconnected = true;
-  this.flags = {};
-  if (opts && opts.query) {
-    this.query = opts.query;
-  }
-  if (this.io.autoConnect) this.open();
-}
-
-/**
- * Mix in `Emitter`.
- */
-
-Emitter(Socket.prototype);
-
-/**
- * Subscribe to open, close and packet events
- *
- * @api private
- */
-
-Socket.prototype.subEvents = function () {
-  if (this.subs) return;
-
-  var io = this.io;
-  this.subs = [
-    on(io, 'open', bind(this, 'onopen')),
-    on(io, 'packet', bind(this, 'onpacket')),
-    on(io, 'close', bind(this, 'onclose'))
-  ];
-};
-
-/**
- * "Opens" the socket.
- *
- * @api public
- */
-
-Socket.prototype.open =
-Socket.prototype.connect = function () {
-  if (this.connected) return this;
-
-  this.subEvents();
-  if (!this.io.reconnecting) this.io.open(); // ensure open
-  if ('open' === this.io.readyState) this.onopen();
-  this.emit('connecting');
-  return this;
-};
-
-/**
- * Sends a `message` event.
- *
- * @return {Socket} self
- * @api public
- */
-
-Socket.prototype.send = function () {
-  var args = toArray(arguments);
-  args.unshift('message');
-  this.emit.apply(this, args);
-  return this;
-};
-
-/**
- * Override `emit`.
- * If the event is in `events`, it's emitted normally.
- *
- * @param {String} event name
- * @return {Socket} self
- * @api public
- */
-
-Socket.prototype.emit = function (ev) {
-  if (events.hasOwnProperty(ev)) {
-    emit.apply(this, arguments);
-    return this;
-  }
-
-  var args = toArray(arguments);
-  var packet = {
-    type: (this.flags.binary !== undefined ? this.flags.binary : hasBin(args)) ? parser.BINARY_EVENT : parser.EVENT,
-    data: args
-  };
-
-  packet.options = {};
-  packet.options.compress = !this.flags || false !== this.flags.compress;
-
-  // event ack callback
-  if ('function' === typeof args[args.length - 1]) {
-    debug('emitting packet with ack id %d', this.ids);
-    this.acks[this.ids] = args.pop();
-    packet.id = this.ids++;
-  }
-
-  if (this.connected) {
-    this.packet(packet);
-  } else {
-    this.sendBuffer.push(packet);
-  }
-
-  this.flags = {};
-
-  return this;
-};
-
-/**
- * Sends a packet.
- *
- * @param {Object} packet
- * @api private
- */
-
-Socket.prototype.packet = function (packet) {
-  packet.nsp = this.nsp;
-  this.io.packet(packet);
-};
-
-/**
- * Called upon engine `open`.
- *
- * @api private
- */
-
-Socket.prototype.onopen = function () {
-  debug('transport is open - connecting');
-
-  // write connect packet if necessary
-  if ('/' !== this.nsp) {
-    if (this.query) {
-      var query = typeof this.query === 'object' ? parseqs.encode(this.query) : this.query;
-      debug('sending connect packet with query %s', query);
-      this.packet({type: parser.CONNECT, query: query});
-    } else {
-      this.packet({type: parser.CONNECT});
-    }
-  }
-};
-
-/**
- * Called upon engine `close`.
- *
- * @param {String} reason
- * @api private
- */
-
-Socket.prototype.onclose = function (reason) {
-  debug('close (%s)', reason);
-  this.connected = false;
-  this.disconnected = true;
-  delete this.id;
-  this.emit('disconnect', reason);
-};
-
-/**
- * Called with socket packet.
- *
- * @param {Object} packet
- * @api private
- */
-
-Socket.prototype.onpacket = function (packet) {
-  var sameNamespace = packet.nsp === this.nsp;
-  var rootNamespaceError = packet.type === parser.ERROR && packet.nsp === '/';
-
-  if (!sameNamespace && !rootNamespaceError) return;
-
-  switch (packet.type) {
-    case parser.CONNECT:
-      this.onconnect();
-      break;
-
-    case parser.EVENT:
-      this.onevent(packet);
-      break;
-
-    case parser.BINARY_EVENT:
-      this.onevent(packet);
-      break;
-
-    case parser.ACK:
-      this.onack(packet);
-      break;
-
-    case parser.BINARY_ACK:
-      this.onack(packet);
-      break;
-
-    case parser.DISCONNECT:
-      this.ondisconnect();
-      break;
-
-    case parser.ERROR:
-      this.emit('error', packet.data);
-      break;
-  }
-};
-
-/**
- * Called upon a server event.
- *
- * @param {Object} packet
- * @api private
- */
-
-Socket.prototype.onevent = function (packet) {
-  var args = packet.data || [];
-  debug('emitting event %j', args);
-
-  if (null != packet.id) {
-    debug('attaching ack callback to event');
-    args.push(this.ack(packet.id));
-  }
-
-  if (this.connected) {
-    emit.apply(this, args);
-  } else {
-    this.receiveBuffer.push(args);
-  }
-};
-
-/**
- * Produces an ack callback to emit with an event.
- *
- * @api private
- */
-
-Socket.prototype.ack = function (id) {
-  var self = this;
-  var sent = false;
-  return function () {
-    // prevent double callbacks
-    if (sent) return;
-    sent = true;
-    var args = toArray(arguments);
-    debug('sending ack %j', args);
-
-    self.packet({
-      type: hasBin(args) ? parser.BINARY_ACK : parser.ACK,
-      id: id,
-      data: args
-    });
-  };
-};
-
-/**
- * Called upon a server acknowlegement.
- *
- * @param {Object} packet
- * @api private
- */
-
-Socket.prototype.onack = function (packet) {
-  var ack = this.acks[packet.id];
-  if ('function' === typeof ack) {
-    debug('calling ack %s with %j', packet.id, packet.data);
-    ack.apply(this, packet.data);
-    delete this.acks[packet.id];
-  } else {
-    debug('bad ack %s', packet.id);
-  }
-};
-
-/**
- * Called upon server connect.
- *
- * @api private
- */
-
-Socket.prototype.onconnect = function () {
-  this.connected = true;
-  this.disconnected = false;
-  this.emit('connect');
-  this.emitBuffered();
-};
-
-/**
- * Emit buffered events (received and emitted).
- *
- * @api private
- */
-
-Socket.prototype.emitBuffered = function () {
-  var i;
-  for (i = 0; i < this.receiveBuffer.length; i++) {
-    emit.apply(this, this.receiveBuffer[i]);
-  }
-  this.receiveBuffer = [];
-
-  for (i = 0; i < this.sendBuffer.length; i++) {
-    this.packet(this.sendBuffer[i]);
-  }
-  this.sendBuffer = [];
-};
-
-/**
- * Called upon server disconnect.
- *
- * @api private
- */
-
-Socket.prototype.ondisconnect = function () {
-  debug('server disconnect (%s)', this.nsp);
-  this.destroy();
-  this.onclose('io server disconnect');
-};
-
-/**
- * Called upon forced client/server side disconnections,
- * this method ensures the manager stops tracking us and
- * that reconnections don't get triggered for this.
- *
- * @api private.
- */
-
-Socket.prototype.destroy = function () {
-  if (this.subs) {
-    // clean subscriptions to avoid reconnections
-    for (var i = 0; i < this.subs.length; i++) {
-      this.subs[i].destroy();
-    }
-    this.subs = null;
-  }
-
-  this.io.destroy(this);
-};
-
-/**
- * Disconnects the socket manually.
- *
- * @return {Socket} self
- * @api public
- */
-
-Socket.prototype.close =
-Socket.prototype.disconnect = function () {
-  if (this.connected) {
-    debug('performing disconnect (%s)', this.nsp);
-    this.packet({ type: parser.DISCONNECT });
-  }
-
-  // remove socket from pool
-  this.destroy();
-
-  if (this.connected) {
-    // fire events
-    this.onclose('io client disconnect');
-  }
-  return this;
-};
-
-/**
- * Sets the compress flag.
- *
- * @param {Boolean} if `true`, compresses the sending data
- * @return {Socket} self
- * @api public
- */
-
-Socket.prototype.compress = function (compress) {
-  this.flags.compress = compress;
-  return this;
-};
-
-/**
- * Sets the binary flag
- *
- * @param {Boolean} whether the emitted data contains binary
- * @return {Socket} self
- * @api public
- */
-
-Socket.prototype.binary = function (binary) {
-  this.flags.binary = binary;
-  return this;
-};
+var parser=require("socket.io-parser"),Emitter=require("component-emitter"),toArray=require("to-array"),on=require("./on"),bind=require("component-bind"),debug=require("debug")("socket.io-client:socket"),parseqs=require("parseqs"),hasBin=require("has-binary2");module.exports=exports=Socket;var events={connect:1,connect_error:1,connect_timeout:1,connecting:1,disconnect:1,error:1,reconnect:1,reconnect_attempt:1,reconnect_failed:1,reconnect_error:1,reconnecting:1,ping:1,pong:1},emit=Emitter.prototype.emit;function Socket(t,e,s){this.io=t,this.nsp=e,this.json=this,this.ids=0,this.acks={},this.receiveBuffer=[],this.sendBuffer=[],this.connected=!1,this.disconnected=!0,this.flags={},s&&s.query&&(this.query=s.query),this.io.autoConnect&&this.open()}Emitter(Socket.prototype),Socket.prototype.subEvents=function(){if(!this.subs){var t=this.io;this.subs=[on(t,"open",bind(this,"onopen")),on(t,"packet",bind(this,"onpacket")),on(t,"close",bind(this,"onclose"))]}},Socket.prototype.open=Socket.prototype.connect=function(){return this.connected||(this.subEvents(),this.io.reconnecting||this.io.open(),"open"===this.io.readyState&&this.onopen(),this.emit("connecting")),this},Socket.prototype.send=function(){var t=toArray(arguments);return t.unshift("message"),this.emit.apply(this,t),this},Socket.prototype.emit=function(t){if(events.hasOwnProperty(t))return emit.apply(this,arguments),this;var e=toArray(arguments),s={type:(void 0!==this.flags.binary?this.flags.binary:hasBin(e))?parser.BINARY_EVENT:parser.EVENT,data:e,options:{}};return s.options.compress=!this.flags||!1!==this.flags.compress,"function"==typeof e[e.length-1]&&(debug("emitting packet with ack id %d",this.ids),this.acks[this.ids]=e.pop(),s.id=this.ids++),this.connected?this.packet(s):this.sendBuffer.push(s),this.flags={},this},Socket.prototype.packet=function(t){t.nsp=this.nsp,this.io.packet(t)},Socket.prototype.onopen=function(){if(debug("transport is open - connecting"),"/"!==this.nsp)if(this.query){var t="object"==typeof this.query?parseqs.encode(this.query):this.query;debug("sending connect packet with query %s",t),this.packet({type:parser.CONNECT,query:t})}else this.packet({type:parser.CONNECT})},Socket.prototype.onclose=function(t){debug("close (%s)",t),this.connected=!1,this.disconnected=!0,delete this.id,this.emit("disconnect",t)},Socket.prototype.onpacket=function(t){var e=t.nsp===this.nsp,s=t.type===parser.ERROR&&"/"===t.nsp;if(e||s)switch(t.type){case parser.CONNECT:this.onconnect();break;case parser.EVENT:case parser.BINARY_EVENT:this.onevent(t);break;case parser.ACK:case parser.BINARY_ACK:this.onack(t);break;case parser.DISCONNECT:this.ondisconnect();break;case parser.ERROR:this.emit("error",t.data)}},Socket.prototype.onevent=function(t){var e=t.data||[];debug("emitting event %j",e),null!=t.id&&(debug("attaching ack callback to event"),e.push(this.ack(t.id))),this.connected?emit.apply(this,e):this.receiveBuffer.push(e)},Socket.prototype.ack=function(t){var e=this,s=!1;return function(){if(!s){s=!0;var i=toArray(arguments);debug("sending ack %j",i),e.packet({type:hasBin(i)?parser.BINARY_ACK:parser.ACK,id:t,data:i})}}},Socket.prototype.onack=function(t){var e=this.acks[t.id];"function"==typeof e?(debug("calling ack %s with %j",t.id,t.data),e.apply(this,t.data),delete this.acks[t.id]):debug("bad ack %s",t.id)},Socket.prototype.onconnect=function(){this.connected=!0,this.disconnected=!1,this.emit("connect"),this.emitBuffered()},Socket.prototype.emitBuffered=function(){var t;for(t=0;t<this.receiveBuffer.length;t++)emit.apply(this,this.receiveBuffer[t]);for(this.receiveBuffer=[],t=0;t<this.sendBuffer.length;t++)this.packet(this.sendBuffer[t]);this.sendBuffer=[]},Socket.prototype.ondisconnect=function(){debug("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")},Socket.prototype.destroy=function(){if(this.subs){for(var t=0;t<this.subs.length;t++)this.subs[t].destroy();this.subs=null}this.io.destroy(this)},Socket.prototype.close=Socket.prototype.disconnect=function(){return this.connected&&(debug("performing disconnect (%s)",this.nsp),this.packet({type:parser.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this},Socket.prototype.compress=function(t){return this.flags.compress=t,this},Socket.prototype.binary=function(t){return this.flags.binary=t,this};
\ No newline at end of file
index 1b51c3c..82e7bd0 100644 (file)
@@ -1,75 +1 @@
-
-/**
- * Module dependencies.
- */
-
-var parseuri = require('parseuri');
-var debug = require('debug')('socket.io-client:url');
-
-/**
- * Module exports.
- */
-
-module.exports = url;
-
-/**
- * URL parser.
- *
- * @param {String} url
- * @param {Object} An object meant to mimic window.location.
- *                 Defaults to window.location.
- * @api public
- */
-
-function url (uri, loc) {
-  var obj = uri;
-
-  // default to window.location
-  loc = loc || (typeof location !== 'undefined' && location);
-  if (null == uri) uri = loc.protocol + '//' + loc.host;
-
-  // relative path support
-  if ('string' === typeof uri) {
-    if ('/' === uri.charAt(0)) {
-      if ('/' === uri.charAt(1)) {
-        uri = loc.protocol + uri;
-      } else {
-        uri = loc.host + uri;
-      }
-    }
-
-    if (!/^(https?|wss?):\/\//.test(uri)) {
-      debug('protocol-less url %s', uri);
-      if ('undefined' !== typeof loc) {
-        uri = loc.protocol + '//' + uri;
-      } else {
-        uri = 'https://' + uri;
-      }
-    }
-
-    // parse
-    debug('parse %s', uri);
-    obj = parseuri(uri);
-  }
-
-  // make sure we treat `localhost:80` and `localhost` equally
-  if (!obj.port) {
-    if (/^(http|ws)$/.test(obj.protocol)) {
-      obj.port = '80';
-    } else if (/^(http|ws)s$/.test(obj.protocol)) {
-      obj.port = '443';
-    }
-  }
-
-  obj.path = obj.path || '/';
-
-  var ipv6 = obj.host.indexOf(':') !== -1;
-  var host = ipv6 ? '[' + obj.host + ']' : obj.host;
-
-  // define unique id
-  obj.id = obj.protocol + '://' + host + ':' + obj.port;
-  // define href
-  obj.href = obj.protocol + '://' + host + (loc && loc.port === obj.port ? '' : (':' + obj.port));
-
-  return obj;
-}
+var parseuri=require("parseuri"),debug=require("debug")("socket.io-client:url");function url(o,t){var r=o;t=t||"undefined"!=typeof location&&location,null==o&&(o=t.protocol+"//"+t.host),"string"==typeof o&&("/"===o.charAt(0)&&(o="/"===o.charAt(1)?t.protocol+o:t.host+o),/^(https?|wss?):\/\//.test(o)||(debug("protocol-less url %s",o),o=void 0!==t?t.protocol+"//"+o:"https://"+o),debug("parse %s",o),r=parseuri(o)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";var p=-1!==r.host.indexOf(":")?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+p+":"+r.port,r.href=r.protocol+"://"+p+(t&&t.port===r.port?"":":"+r.port),r}module.exports=url;
\ No newline at end of file
index 4df469a..63c8e46 100644 (file)
@@ -4,110 +4,4 @@
  * Copyright(c) 2016 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module dependencies.
- * @private
- */
-
-var codes = require('./codes.json')
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = status
-
-// status code to message map
-status.STATUS_CODES = codes
-
-// array of status codes
-status.codes = populateStatusesMap(status, codes)
-
-// status codes for redirects
-status.redirect = {
-  300: true,
-  301: true,
-  302: true,
-  303: true,
-  305: true,
-  307: true,
-  308: true
-}
-
-// status codes for empty bodies
-status.empty = {
-  204: true,
-  205: true,
-  304: true
-}
-
-// status codes for when you should retry the request
-status.retry = {
-  502: true,
-  503: true,
-  504: true
-}
-
-/**
- * Populate the statuses map for given codes.
- * @private
- */
-
-function populateStatusesMap (statuses, codes) {
-  var arr = []
-
-  Object.keys(codes).forEach(function forEachCode (code) {
-    var message = codes[code]
-    var status = Number(code)
-
-    // Populate properties
-    statuses[status] = message
-    statuses[message] = status
-    statuses[message.toLowerCase()] = status
-
-    // Add to array
-    arr.push(status)
-  })
-
-  return arr
-}
-
-/**
- * Get the status code.
- *
- * Given a number, this will throw if it is not a known status
- * code, otherwise the code will be returned. Given a string,
- * the string will be parsed for a number and return the code
- * if valid, otherwise will lookup the code assuming this is
- * the status message.
- *
- * @param {string|number} code
- * @returns {number}
- * @public
- */
-
-function status (code) {
-  if (typeof code === 'number') {
-    if (!status[code]) throw new Error('invalid status code: ' + code)
-    return code
-  }
-
-  if (typeof code !== 'string') {
-    throw new TypeError('code must be a number or string')
-  }
-
-  // '403'
-  var n = parseInt(code, 10)
-  if (!isNaN(n)) {
-    if (!status[n]) throw new Error('invalid status code: ' + n)
-    return n
-  }
-
-  n = status[code.toLowerCase()]
-  if (!n) throw new Error('invalid status message: "' + code + '"')
-  return n
-}
+"use strict";var codes=require("./codes.json");function populateStatusesMap(t,s){var r=[];return Object.keys(s).forEach((function(e){var a=s[e],u=Number(e);t[u]=a,t[a]=u,t[a.toLowerCase()]=u,r.push(u)})),r}function status(t){if("number"==typeof t){if(!status[t])throw new Error("invalid status code: "+t);return t}if("string"!=typeof t)throw new TypeError("code must be a number or string");var s=parseInt(t,10);if(!isNaN(s)){if(!status[s])throw new Error("invalid status code: "+s);return s}if(!(s=status[t.toLowerCase()]))throw new Error('invalid status message: "'+t+'"');return s}module.exports=status,status.STATUS_CODES=codes,status.codes=populateStatusesMap(status,codes),status.redirect={300:!0,301:!0,302:!0,303:!0,305:!0,307:!0,308:!0},status.empty={204:!0,205:!0,304:!0},status.retry={502:!0,503:!0,504:!0};
\ No newline at end of file
index 33c9d6c..3964ddf 100644 (file)
@@ -1,39 +1 @@
-'use strict';
-const stripAnsi = require('strip-ansi');
-const isFullwidthCodePoint = require('is-fullwidth-code-point');
-const emojiRegex = require('emoji-regex')();
-
-module.exports = input => {
-       input = input.replace(emojiRegex, '  ');
-
-       if (typeof input !== 'string' || input.length === 0) {
-               return 0;
-       }
-
-       input = stripAnsi(input);
-
-       let width = 0;
-
-       for (let i = 0; i < input.length; i++) {
-               const code = input.codePointAt(i);
-
-               // Ignore control characters
-               if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) {
-                       continue;
-               }
-
-               // Ignore combining characters
-               if (code >= 0x300 && code <= 0x36F) {
-                       continue;
-               }
-
-               // Surrogates
-               if (code > 0xFFFF) {
-                       i++;
-               }
-
-               width += isFullwidthCodePoint(code) ? 2 : 1;
-       }
-
-       return width;
-};
+"use strict";const stripAnsi=require("strip-ansi"),isFullwidthCodePoint=require("is-fullwidth-code-point"),emojiRegex=require("emoji-regex")();module.exports=e=>{if("string"!=typeof(e=e.replace(emojiRegex,"  "))||0===e.length)return 0;e=stripAnsi(e);let i=0;for(let t=0;t<e.length;t++){const r=e.codePointAt(t);r<=31||r>=127&&r<=159||(r>=768&&r<=879||(r>65535&&t++,i+=isFullwidthCodePoint(r)?2:1))}return i};
\ No newline at end of file
index 9788c96..f1cbe9e 100644 (file)
@@ -1,7 +1 @@
-'use strict';
-const ansiRegex = require('ansi-regex');
-
-const stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string;
-
-module.exports = stripAnsi;
-module.exports.default = stripAnsi;
+"use strict";const ansiRegex=require("ansi-regex"),stripAnsi=e=>"string"==typeof e?e.replace(ansiRegex(),""):e;module.exports=stripAnsi,module.exports.default=stripAnsi;
\ No newline at end of file
index 62afa3a..826e8a4 100755 (executable)
@@ -1,5 +1 @@
-'use strict';
-module.exports = {
-       stdout: false,
-       stderr: false
-};
+"use strict";module.exports={stdout:!1,stderr:!1};
\ No newline at end of file
index 1704131..067a221 100755 (executable)
@@ -1,131 +1 @@
-'use strict';
-const os = require('os');
-const hasFlag = require('has-flag');
-
-const env = process.env;
-
-let forceColor;
-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,
-               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;
-       }
-
-       const 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.
-               const 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(sign => 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 (env.COLORTERM === 'truecolor') {
-               return 3;
-       }
-
-       if ('TERM_PROGRAM' in env) {
-               const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
-
-               switch (env.TERM_PROGRAM) {
-                       case 'iTerm.app':
-                               return version >= 3 ? 3 : 2;
-                       case 'Apple_Terminal':
-                               return 2;
-                       // No default
-               }
-       }
-
-       if (/-256(color)?$/i.test(env.TERM)) {
-               return 2;
-       }
-
-       if (/^screen|^xterm|^vt100|^vt220|^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) {
-       const level = supportsColor(stream);
-       return translateLevel(level);
-}
-
-module.exports = {
-       supportsColor: getSupportLevel,
-       stdout: getSupportLevel(process.stdout),
-       stderr: getSupportLevel(process.stderr)
-};
+"use strict";const os=require("os"),hasFlag=require("has-flag"),env=process.env;let forceColor;function translateLevel(e){return 0!==e&&{level:e,hasBasic:!0,has256:e>=2,has16m:e>=3}}function supportsColor(e){if(!1===forceColor)return 0;if(hasFlag("color=16m")||hasFlag("color=full")||hasFlag("color=truecolor"))return 3;if(hasFlag("color=256"))return 2;if(e&&!e.isTTY&&!0!==forceColor)return 0;const r=forceColor?1:0;if("win32"===process.platform){const e=os.release().split(".");return Number(process.versions.node.split(".")[0])>=8&&Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if("CI"in env)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI"].some((e=>e in env))||"codeship"===env.CI_NAME?1:r;if("TEAMCITY_VERSION"in env)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION)?1:0;if("truecolor"===env.COLORTERM)return 3;if("TERM_PROGRAM"in env){const e=parseInt((env.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(env.TERM_PROGRAM){case"iTerm.app":return e>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(env.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)||"COLORTERM"in env?1:(env.TERM,r)}function getSupportLevel(e){return translateLevel(supportsColor(e))}hasFlag("no-color")||hasFlag("no-colors")||hasFlag("color=false")?forceColor=!1:(hasFlag("color")||hasFlag("colors")||hasFlag("color=true")||hasFlag("color=always"))&&(forceColor=!0),"FORCE_COLOR"in env&&(forceColor=0===env.FORCE_COLOR.length||0!==parseInt(env.FORCE_COLOR,10)),module.exports={supportsColor:getSupportLevel,stdout:getSupportLevel(process.stdout),stderr:getSupportLevel(process.stderr)};
\ No newline at end of file
index 6a38a69..11f1c6b 100644 (file)
@@ -1,13 +1 @@
-module.exports = toArray
-
-function toArray(list, index) {
-    var array = []
-
-    index = index || 0
-
-    for (var i = index || 0; i < list.length; i++) {
-        array[i - index] = list[i]
-    }
-
-    return array
-}
+function toArray(r,o){for(var t=[],e=(o=o||0)||0;e<r.length;e++)t[e-o]=r[e];return t}module.exports=toArray;
\ No newline at end of file
index bba5411..321a211 100644 (file)
@@ -3,28 +3,4 @@
  * Copyright(c) 2016 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = toIdentifier
-
-/**
- * Trasform the given string into a JavaScript identifier
- *
- * @param {string} str
- * @returns {string}
- * @public
- */
-
-function toIdentifier (str) {
-  return str
-    .split(' ')
-    .map(function (token) {
-      return token.slice(0, 1).toUpperCase() + token.slice(1)
-    })
-    .join('')
-    .replace(/[^ _0-9a-z]/gi, '')
-}
+function toIdentifier(e){return e.split(" ").map((function(e){return e.slice(0,1).toUpperCase()+e.slice(1)})).join("").replace(/[^ _0-9a-z]/gi,"")}module.exports=toIdentifier;
\ No newline at end of file
index 890ad76..2330ee8 100644 (file)
@@ -4,263 +4,4 @@
  * Copyright(c) 2014-2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module dependencies.
- * @private
- */
-
-var typer = require('media-typer')
-var mime = require('mime-types')
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = typeofrequest
-module.exports.is = typeis
-module.exports.hasBody = hasbody
-module.exports.normalize = normalize
-module.exports.match = mimeMatch
-
-/**
- * Compare a `value` content-type with `types`.
- * Each `type` can be an extension like `html`,
- * a special shortcut like `multipart` or `urlencoded`,
- * or a mime type.
- *
- * If no types match, `false` is returned.
- * Otherwise, the first `type` that matches is returned.
- *
- * @param {String} value
- * @param {Array} types
- * @public
- */
-
-function typeis (value, types_) {
-  var i
-  var types = types_
-
-  // remove parameters and normalize
-  var val = tryNormalizeType(value)
-
-  // no type or invalid
-  if (!val) {
-    return false
-  }
-
-  // support flattened arguments
-  if (types && !Array.isArray(types)) {
-    types = new Array(arguments.length - 1)
-    for (i = 0; i < types.length; i++) {
-      types[i] = arguments[i + 1]
-    }
-  }
-
-  // no types, return the content type
-  if (!types || !types.length) {
-    return val
-  }
-
-  var type
-  for (i = 0; i < types.length; i++) {
-    if (mimeMatch(normalize(type = types[i]), val)) {
-      return type[0] === '+' || type.indexOf('*') !== -1
-        ? val
-        : type
-    }
-  }
-
-  // no matches
-  return false
-}
-
-/**
- * Check if a request has a request body.
- * A request with a body __must__ either have `transfer-encoding`
- * or `content-length` headers set.
- * http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.3
- *
- * @param {Object} request
- * @return {Boolean}
- * @public
- */
-
-function hasbody (req) {
-  return req.headers['transfer-encoding'] !== undefined ||
-    !isNaN(req.headers['content-length'])
-}
-
-/**
- * Check if the incoming request contains the "Content-Type"
- * header field, and it contains any of the give mime `type`s.
- * If there is no request body, `null` is returned.
- * If there is no content type, `false` is returned.
- * Otherwise, it returns the first `type` that matches.
- *
- * Examples:
- *
- *     // With Content-Type: text/html; charset=utf-8
- *     this.is('html'); // => 'html'
- *     this.is('text/html'); // => 'text/html'
- *     this.is('text/*', 'application/json'); // => 'text/html'
- *
- *     // When Content-Type is application/json
- *     this.is('json', 'urlencoded'); // => 'json'
- *     this.is('application/json'); // => 'application/json'
- *     this.is('html', 'application/*'); // => 'application/json'
- *
- *     this.is('html'); // => false
- *
- * @param {String|Array} types...
- * @return {String|false|null}
- * @public
- */
-
-function typeofrequest (req, types_) {
-  var types = types_
-
-  // no body
-  if (!hasbody(req)) {
-    return null
-  }
-
-  // support flattened arguments
-  if (arguments.length > 2) {
-    types = new Array(arguments.length - 1)
-    for (var i = 0; i < types.length; i++) {
-      types[i] = arguments[i + 1]
-    }
-  }
-
-  // request content type
-  var value = req.headers['content-type']
-
-  return typeis(value, types)
-}
-
-/**
- * Normalize a mime type.
- * If it's a shorthand, expand it to a valid mime type.
- *
- * In general, you probably want:
- *
- *   var type = is(req, ['urlencoded', 'json', 'multipart']);
- *
- * Then use the appropriate body parsers.
- * These three are the most common request body types
- * and are thus ensured to work.
- *
- * @param {String} type
- * @private
- */
-
-function normalize (type) {
-  if (typeof type !== 'string') {
-    // invalid type
-    return false
-  }
-
-  switch (type) {
-    case 'urlencoded':
-      return 'application/x-www-form-urlencoded'
-    case 'multipart':
-      return 'multipart/*'
-  }
-
-  if (type[0] === '+') {
-    // "+json" -> "*/*+json" expando
-    return '*/*' + type
-  }
-
-  return type.indexOf('/') === -1
-    ? mime.lookup(type)
-    : type
-}
-
-/**
- * Check if `expected` mime type
- * matches `actual` mime type with
- * wildcard and +suffix support.
- *
- * @param {String} expected
- * @param {String} actual
- * @return {Boolean}
- * @private
- */
-
-function mimeMatch (expected, actual) {
-  // invalid type
-  if (expected === false) {
-    return false
-  }
-
-  // split types
-  var actualParts = actual.split('/')
-  var expectedParts = expected.split('/')
-
-  // invalid format
-  if (actualParts.length !== 2 || expectedParts.length !== 2) {
-    return false
-  }
-
-  // validate type
-  if (expectedParts[0] !== '*' && expectedParts[0] !== actualParts[0]) {
-    return false
-  }
-
-  // validate suffix wildcard
-  if (expectedParts[1].substr(0, 2) === '*+') {
-    return expectedParts[1].length <= actualParts[1].length + 1 &&
-      expectedParts[1].substr(1) === actualParts[1].substr(1 - expectedParts[1].length)
-  }
-
-  // validate subtype
-  if (expectedParts[1] !== '*' && expectedParts[1] !== actualParts[1]) {
-    return false
-  }
-
-  return true
-}
-
-/**
- * Normalize a type and remove parameters.
- *
- * @param {string} value
- * @return {string}
- * @private
- */
-
-function normalizeType (value) {
-  // parse the type
-  var type = typer.parse(value)
-
-  // remove the parameters
-  type.parameters = undefined
-
-  // reformat it
-  return typer.format(type)
-}
-
-/**
- * Try to normalize a type and remove parameters.
- *
- * @param {string} value
- * @return {string}
- * @private
- */
-
-function tryNormalizeType (value) {
-  if (!value) {
-    return null
-  }
-
-  try {
-    return normalizeType(value)
-  } catch (err) {
-    return null
-  }
-}
+"use strict";var typer=require("media-typer"),mime=require("mime-types");function typeis(e,r){var t,n,i=r,o=tryNormalizeType(e);if(!o)return!1;if(i&&!Array.isArray(i))for(i=new Array(arguments.length-1),t=0;t<i.length;t++)i[t]=arguments[t+1];if(!i||!i.length)return o;for(t=0;t<i.length;t++)if(mimeMatch(normalize(n=i[t]),o))return"+"===n[0]||-1!==n.indexOf("*")?o:n;return!1}function hasbody(e){return void 0!==e.headers["transfer-encoding"]||!isNaN(e.headers["content-length"])}function typeofrequest(e,r){var t=r;if(!hasbody(e))return null;if(arguments.length>2){t=new Array(arguments.length-1);for(var n=0;n<t.length;n++)t[n]=arguments[n+1]}var i=e.headers["content-type"];return typeis(i,t)}function normalize(e){if("string"!=typeof e)return!1;switch(e){case"urlencoded":return"application/x-www-form-urlencoded";case"multipart":return"multipart/*"}return"+"===e[0]?"*/*"+e:-1===e.indexOf("/")?mime.lookup(e):e}function mimeMatch(e,r){if(!1===e)return!1;var t=r.split("/"),n=e.split("/");return 2===t.length&&2===n.length&&(("*"===n[0]||n[0]===t[0])&&("*+"===n[1].substr(0,2)?n[1].length<=t[1].length+1&&n[1].substr(1)===t[1].substr(1-n[1].length):"*"===n[1]||n[1]===t[1]))}function normalizeType(e){var r=typer.parse(e);return r.parameters=void 0,typer.format(r)}function tryNormalizeType(e){if(!e)return null;try{return normalizeType(e)}catch(e){return null}}module.exports=typeofrequest,module.exports.is=typeis,module.exports.hasBody=hasbody,module.exports.normalize=normalize,module.exports.match=mimeMatch;
\ No newline at end of file
index 18e8492..68fd4fd 100755 (executable)
@@ -4,104 +4,4 @@
  * Copyright(c) 2015-2017 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module dependencies.
- * @private
- */
-
-var randomBytes = require('random-bytes')
-
-/**
- * Module variables.
- * @private
- */
-
-var EQUAL_END_REGEXP = /=+$/
-var PLUS_GLOBAL_REGEXP = /\+/g
-var SLASH_GLOBAL_REGEXP = /\//g
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = uid
-module.exports.sync = uidSync
-
-/**
- * Create a unique ID.
- *
- * @param {number} length
- * @param {function} [callback]
- * @return {Promise}
- * @public
- */
-
-function uid (length, callback) {
-  // validate callback is a function, if provided
-  if (callback !== undefined && typeof callback !== 'function') {
-    throw new TypeError('argument callback must be a function')
-  }
-
-  // require the callback without promises
-  if (!callback && !global.Promise) {
-    throw new TypeError('argument callback is required')
-  }
-
-  if (callback) {
-    // classic callback style
-    return generateUid(length, callback)
-  }
-
-  return new Promise(function executor (resolve, reject) {
-    generateUid(length, function onUid (err, str) {
-      if (err) return reject(err)
-      resolve(str)
-    })
-  })
-}
-
-/**
- * Create a unique ID sync.
- *
- * @param {number} length
- * @return {string}
- * @public
- */
-
-function uidSync (length) {
-  return toString(randomBytes.sync(length))
-}
-
-/**
- * Generate a unique ID string.
- *
- * @param {number} length
- * @param {function} callback
- * @private
- */
-
-function generateUid (length, callback) {
-  randomBytes(length, function (err, buf) {
-    if (err) return callback(err)
-    callback(null, toString(buf))
-  })
-}
-
-/**
- * Change a Buffer into a string.
- *
- * @param {Buffer} buf
- * @return {string}
- * @private
- */
-
-function toString (buf) {
-  return buf.toString('base64')
-    .replace(EQUAL_END_REGEXP, '')
-    .replace(PLUS_GLOBAL_REGEXP, '-')
-    .replace(SLASH_GLOBAL_REGEXP, '_')
-}
+"use strict";var randomBytes=require("random-bytes"),EQUAL_END_REGEXP=/=+$/,PLUS_GLOBAL_REGEXP=/\+/g,SLASH_GLOBAL_REGEXP=/\//g;function uid(e,n){if(void 0!==n&&"function"!=typeof n)throw new TypeError("argument callback must be a function");if(!n&&!global.Promise)throw new TypeError("argument callback is required");return n?generateUid(e,n):new Promise((function(n,r){generateUid(e,(function(e,t){if(e)return r(e);n(t)}))}))}function uidSync(e){return toString(randomBytes.sync(e))}function generateUid(e,n){randomBytes(e,(function(e,r){if(e)return n(e);n(null,toString(r))}))}function toString(e){return e.toString("base64").replace(EQUAL_END_REGEXP,"").replace(PLUS_GLOBAL_REGEXP,"-").replace(SLASH_GLOBAL_REGEXP,"_")}module.exports=uid,module.exports.sync=uidSync;
\ No newline at end of file
index 15c3d97..6d74112 100644 (file)
@@ -3,67 +3,4 @@
  * Copyright(c) 2015 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module exports.
- * @public
- */
-
-module.exports = unpipe
-
-/**
- * Determine if there are Node.js pipe-like data listeners.
- * @private
- */
-
-function hasPipeDataListeners(stream) {
-  var listeners = stream.listeners('data')
-
-  for (var i = 0; i < listeners.length; i++) {
-    if (listeners[i].name === 'ondata') {
-      return true
-    }
-  }
-
-  return false
-}
-
-/**
- * Unpipe a stream from all destinations.
- *
- * @param {object} stream
- * @public
- */
-
-function unpipe(stream) {
-  if (!stream) {
-    throw new TypeError('argument stream is required')
-  }
-
-  if (typeof stream.unpipe === 'function') {
-    // new-style
-    stream.unpipe()
-    return
-  }
-
-  // Node.js 0.8 hack
-  if (!hasPipeDataListeners(stream)) {
-    return
-  }
-
-  var listener
-  var listeners = stream.listeners('close')
-
-  for (var i = 0; i < listeners.length; i++) {
-    listener = listeners[i]
-
-    if (listener.name !== 'cleanup' && listener.name !== 'onclose') {
-      continue
-    }
-
-    // invoke the listener
-    listener.call(stream)
-  }
-}
+"use strict";function hasPipeDataListeners(e){for(var n=e.listeners("data"),r=0;r<n.length;r++)if("ondata"===n[r].name)return!0;return!1}function unpipe(e){if(!e)throw new TypeError("argument stream is required");if("function"!=typeof e.unpipe){if(hasPipeDataListeners(e))for(var n,r=e.listeners("close"),t=0;t<r.length;t++)"cleanup"!==(n=r[t]).name&&"onclose"!==n.name||n.call(e)}else e.unpipe()}module.exports=unpipe;
\ No newline at end of file
index 4265c69..c0deca2 100644 (file)
@@ -1,23 +1 @@
-/**
- * Merge object b with object a.
- *
- *     var a = { foo: 'bar' }
- *       , b = { bar: 'baz' };
- *
- *     merge(a, b);
- *     // => { foo: 'bar', bar: 'baz' }
- *
- * @param {Object} a
- * @param {Object} b
- * @return {Object}
- * @api public
- */
-
-exports = module.exports = function(a, b){
-  if (a && b) {
-    for (var key in b) {
-      a[key] = b[key];
-    }
-  }
-  return a;
-};
+exports=module.exports=function(r,o){if(r&&o)for(var e in o)r[e]=o[e];return r};
\ No newline at end of file
index 5b5e741..e4a4e7f 100644 (file)
@@ -3,147 +3,4 @@
  * Copyright(c) 2014-2017 Douglas Christopher Wilson
  * MIT Licensed
  */
-
-'use strict'
-
-/**
- * Module exports.
- */
-
-module.exports = vary
-module.exports.append = append
-
-/**
- * RegExp to match field-name in RFC 7230 sec 3.2
- *
- * field-name    = token
- * token         = 1*tchar
- * tchar         = "!" / "#" / "$" / "%" / "&" / "'" / "*"
- *               / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
- *               / DIGIT / ALPHA
- *               ; any VCHAR, except delimiters
- */
-
-var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/
-
-/**
- * Append a field to a vary header.
- *
- * @param {String} header
- * @param {String|Array} field
- * @return {String}
- * @public
- */
-
-function append (header, field) {
-  if (typeof header !== 'string') {
-    throw new TypeError('header argument is required')
-  }
-
-  if (!field) {
-    throw new TypeError('field argument is required')
-  }
-
-  // get fields array
-  var fields = !Array.isArray(field)
-    ? parse(String(field))
-    : field
-
-  // assert on invalid field names
-  for (var j = 0; j < fields.length; j++) {
-    if (!FIELD_NAME_REGEXP.test(fields[j])) {
-      throw new TypeError('field argument contains an invalid header name')
-    }
-  }
-
-  // existing, unspecified vary
-  if (header === '*') {
-    return header
-  }
-
-  // enumerate current values
-  var val = header
-  var vals = parse(header.toLowerCase())
-
-  // unspecified vary
-  if (fields.indexOf('*') !== -1 || vals.indexOf('*') !== -1) {
-    return '*'
-  }
-
-  for (var i = 0; i < fields.length; i++) {
-    var fld = fields[i].toLowerCase()
-
-    // append value (case-preserving)
-    if (vals.indexOf(fld) === -1) {
-      vals.push(fld)
-      val = val
-        ? val + ', ' + fields[i]
-        : fields[i]
-    }
-  }
-
-  return val
-}
-
-/**
- * Parse a vary header into an array.
- *
- * @param {String} header
- * @return {Array}
- * @private
- */
-
-function parse (header) {
-  var end = 0
-  var list = []
-  var start = 0
-
-  // gather tokens
-  for (var i = 0, len = header.length; i < len; i++) {
-    switch (header.charCodeAt(i)) {
-      case 0x20: /*   */
-        if (start === end) {
-          start = end = i + 1
-        }
-        break
-      case 0x2c: /* , */
-        list.push(header.substring(start, end))
-        start = end = i + 1
-        break
-      default:
-        end = i + 1
-        break
-    }
-  }
-
-  // final token
-  list.push(header.substring(start, end))
-
-  return list
-}
-
-/**
- * Mark that a request is varied on a header field.
- *
- * @param {Object} res
- * @param {String|Array} field
- * @public
- */
-
-function vary (res, field) {
-  if (!res || !res.getHeader || !res.setHeader) {
-    // quack quack
-    throw new TypeError('res argument is required')
-  }
-
-  // get existing header
-  var val = res.getHeader('Vary') || ''
-  var header = Array.isArray(val)
-    ? val.join(', ')
-    : String(val)
-
-  // set new header
-  if ((val = append(header, field))) {
-    res.setHeader('Vary', val)
-  }
-}
+"use strict";module.exports=vary,module.exports.append=append;var FIELD_NAME_REGEXP=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function append(r,e){if("string"!=typeof r)throw new TypeError("header argument is required");if(!e)throw new TypeError("field argument is required");for(var a=Array.isArray(e)?e:parse(String(e)),t=0;t<a.length;t++)if(!FIELD_NAME_REGEXP.test(a[t]))throw new TypeError("field argument contains an invalid header name");if("*"===r)return r;var n=r,i=parse(r.toLowerCase());if(-1!==a.indexOf("*")||-1!==i.indexOf("*"))return"*";for(var s=0;s<a.length;s++){var o=a[s].toLowerCase();-1===i.indexOf(o)&&(i.push(o),n=n?n+", "+a[s]:a[s])}return n}function parse(r){for(var e=0,a=[],t=0,n=0,i=r.length;n<i;n++)switch(r.charCodeAt(n)){case 32:t===e&&(t=e=n+1);break;case 44:a.push(r.substring(t,e)),t=e=n+1;break;default:e=n+1}return a.push(r.substring(t,e)),a}function vary(r,e){if(!r||!r.getHeader||!r.setHeader)throw new TypeError("res argument is required");var a=r.getHeader("Vary")||"",t=Array.isArray(a)?a.join(", "):String(a);(a=append(t,e))&&r.setHeader("Vary",a)}
\ No newline at end of file
index 45559b7..1895c1b 100644 (file)
@@ -1,9 +1 @@
-'use strict'
-
-module.exports = function whichModule (exported) {
-  for (var i = 0, files = Object.keys(require.cache), mod; i < files.length; i++) {
-    mod = require.cache[files[i]]
-    if (mod.exports === exported) return mod
-  }
-  return null
-}
+"use strict";module.exports=function(e){for(var r,t=0,u=Object.keys(require.cache);t<u.length;t++)if((r=require.cache[u[t]]).exports===e)return r;return null};
\ No newline at end of file
index 5038bb0..ff34a1d 100755 (executable)
@@ -1,188 +1 @@
-'use strict';
-const stringWidth = require('string-width');
-const stripAnsi = require('strip-ansi');
-const ansiStyles = require('ansi-styles');
-
-const ESCAPES = new Set([
-       '\u001B',
-       '\u009B'
-]);
-
-const END_CODE = 39;
-
-const wrapAnsi = code => `${ESCAPES.values().next().value}[${code}m`;
-
-// Calculate the length of words split on ' ', ignoring
-// the extra characters added by ansi escape codes
-const wordLengths = string => string.split(' ').map(character => stringWidth(character));
-
-// Wrap a long word across multiple rows
-// Ansi escape codes do not count towards length
-const wrapWord = (rows, word, columns) => {
-       const characters = [...word];
-
-       let insideEscape = false;
-       let visible = stringWidth(stripAnsi(rows[rows.length - 1]));
-
-       for (const [index, character] of characters.entries()) {
-               const characterLength = stringWidth(character);
-
-               if (visible + characterLength <= columns) {
-                       rows[rows.length - 1] += character;
-               } else {
-                       rows.push(character);
-                       visible = 0;
-               }
-
-               if (ESCAPES.has(character)) {
-                       insideEscape = true;
-               } else if (insideEscape && character === 'm') {
-                       insideEscape = false;
-                       continue;
-               }
-
-               if (insideEscape) {
-                       continue;
-               }
-
-               visible += characterLength;
-
-               if (visible === columns && index < characters.length - 1) {
-                       rows.push('');
-                       visible = 0;
-               }
-       }
-
-       // It's possible that the last row we copy over is only
-       // ansi escape characters, handle this edge-case
-       if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) {
-               rows[rows.length - 2] += rows.pop();
-       }
-};
-
-// Trims spaces from a string ignoring invisible sequences
-const stringVisibleTrimSpacesRight = str => {
-       const words = str.split(' ');
-       let last = words.length;
-
-       while (last > 0) {
-               if (stringWidth(words[last - 1]) > 0) {
-                       break;
-               }
-
-               last--;
-       }
-
-       if (last === words.length) {
-               return str;
-       }
-
-       return words.slice(0, last).join(' ') + words.slice(last).join('');
-};
-
-// The wrap-ansi module can be invoked
-// in either 'hard' or 'soft' wrap mode
-//
-// 'hard' will never allow a string to take up more
-// than columns characters
-//
-// 'soft' allows long words to expand past the column length
-const exec = (string, columns, options = {}) => {
-       if (options.trim !== false && string.trim() === '') {
-               return '';
-       }
-
-       let pre = '';
-       let ret = '';
-       let escapeCode;
-
-       const lengths = wordLengths(string);
-       let rows = [''];
-
-       for (const [index, word] of string.split(' ').entries()) {
-               if (options.trim !== false) {
-                       rows[rows.length - 1] = rows[rows.length - 1].trimLeft();
-               }
-
-               let rowLength = stringWidth(rows[rows.length - 1]);
-
-               if (index !== 0) {
-                       if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) {
-                               // If we start with a new word but the current row length equals the length of the columns, add a new row
-                               rows.push('');
-                               rowLength = 0;
-                       }
-
-                       if (rowLength > 0 || options.trim === false) {
-                               rows[rows.length - 1] += ' ';
-                               rowLength++;
-                       }
-               }
-
-               // In 'hard' wrap mode, the length of a line is
-               // never allowed to extend past 'columns'
-               if (options.hard && lengths[index] > columns) {
-                       const remainingColumns = (columns - rowLength);
-                       const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns);
-                       const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns);
-                       if (breaksStartingNextLine < breaksStartingThisLine) {
-                               rows.push('');
-                       }
-
-                       wrapWord(rows, word, columns);
-                       continue;
-               }
-
-               if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) {
-                       if (options.wordWrap === false && rowLength < columns) {
-                               wrapWord(rows, word, columns);
-                               continue;
-                       }
-
-                       rows.push('');
-               }
-
-               if (rowLength + lengths[index] > columns && options.wordWrap === false) {
-                       wrapWord(rows, word, columns);
-                       continue;
-               }
-
-               rows[rows.length - 1] += word;
-       }
-
-       if (options.trim !== false) {
-               rows = rows.map(stringVisibleTrimSpacesRight);
-       }
-
-       pre = rows.join('\n');
-
-       for (const [index, character] of [...pre].entries()) {
-               ret += character;
-
-               if (ESCAPES.has(character)) {
-                       const code = parseFloat(/\d[^m]*/.exec(pre.slice(index, index + 4)));
-                       escapeCode = code === END_CODE ? null : code;
-               }
-
-               const code = ansiStyles.codes.get(Number(escapeCode));
-
-               if (escapeCode && code) {
-                       if (pre[index + 1] === '\n') {
-                               ret += wrapAnsi(code);
-                       } else if (character === '\n') {
-                               ret += wrapAnsi(escapeCode);
-                       }
-               }
-       }
-
-       return ret;
-};
-
-// For each newline, invoke the method separately
-module.exports = (string, columns, options) => {
-       return String(string)
-               .normalize()
-               .split('\n')
-               .map(line => exec(line, columns, options))
-               .join('\n');
-};
+"use strict";const stringWidth=require("string-width"),stripAnsi=require("strip-ansi"),ansiStyles=require("ansi-styles"),ESCAPES=new Set(["\e","\9b"]),END_CODE=39,wrapAnsi=t=>`${ESCAPES.values().next().value}[${t}m`,wordLengths=t=>t.split(" ").map((t=>stringWidth(t))),wrapWord=(t,e,i)=>{const n=[...e];let r=!1,s=stringWidth(stripAnsi(t[t.length-1]));for(const[e,o]of n.entries()){const l=stringWidth(o);if(s+l<=i?t[t.length-1]+=o:(t.push(o),s=0),ESCAPES.has(o))r=!0;else if(r&&"m"===o){r=!1;continue}r||(s+=l,s===i&&e<n.length-1&&(t.push(""),s=0))}!s&&t[t.length-1].length>0&&t.length>1&&(t[t.length-2]+=t.pop())},stringVisibleTrimSpacesRight=t=>{const e=t.split(" ");let i=e.length;for(;i>0&&!(stringWidth(e[i-1])>0);)i--;return i===e.length?t:e.slice(0,i).join(" ")+e.slice(i).join("")},exec=(t,e,i={})=>{if(!1!==i.trim&&""===t.trim())return"";let n,r="",s="";const o=wordLengths(t);let l=[""];for(const[n,r]of t.split(" ").entries()){!1!==i.trim&&(l[l.length-1]=l[l.length-1].trimLeft());let t=stringWidth(l[l.length-1]);if(0!==n&&(t>=e&&(!1===i.wordWrap||!1===i.trim)&&(l.push(""),t=0),(t>0||!1===i.trim)&&(l[l.length-1]+=" ",t++)),i.hard&&o[n]>e){const i=e-t,s=1+Math.floor((o[n]-i-1)/e);Math.floor((o[n]-1)/e)<s&&l.push(""),wrapWord(l,r,e)}else{if(t+o[n]>e&&t>0&&o[n]>0){if(!1===i.wordWrap&&t<e){wrapWord(l,r,e);continue}l.push("")}t+o[n]>e&&!1===i.wordWrap?wrapWord(l,r,e):l[l.length-1]+=r}}!1!==i.trim&&(l=l.map(stringVisibleTrimSpacesRight)),r=l.join("\n");for(const[t,e]of[...r].entries()){if(s+=e,ESCAPES.has(e)){const e=parseFloat(/\d[^m]*/.exec(r.slice(t,t+4)));n=39===e?null:e}const i=ansiStyles.codes.get(Number(n));n&&i&&("\n"===r[t+1]?s+=wrapAnsi(i):"\n"===e&&(s+=wrapAnsi(n)))}return s};module.exports=(t,e,i)=>String(t).normalize().split("\n").map((t=>exec(t,e,i))).join("\n");
\ No newline at end of file
index b8d6be1..14dba9f 100755 (executable)
@@ -1,9 +1 @@
-'use strict';
-
-const WebSocket = require('./lib/websocket');
-
-WebSocket.Server = require('./lib/websocket-server');
-WebSocket.Receiver = require('./lib/receiver');
-WebSocket.Sender = require('./lib/sender');
-
-module.exports = WebSocket;
+"use strict";const WebSocket=require("./lib/websocket");WebSocket.Server=require("./lib/websocket-server"),WebSocket.Receiver=require("./lib/receiver"),WebSocket.Sender=require("./lib/sender"),module.exports=WebSocket;
\ No newline at end of file
index 6974dd6..85e1e0d 100755 (executable)
@@ -1,72 +1 @@
-'use strict';
-
-/**
- * Merges an array of buffers into a new buffer.
- *
- * @param {Buffer[]} list The array of buffers to concat
- * @param {Number} totalLength The total length of buffers in the list
- * @return {Buffer} The resulting buffer
- * @public
- */
-function concat (list, totalLength) {
-  const target = Buffer.allocUnsafe(totalLength);
-  var offset = 0;
-
-  for (var i = 0; i < list.length; i++) {
-    const buf = list[i];
-    buf.copy(target, offset);
-    offset += buf.length;
-  }
-
-  return target;
-}
-
-/**
- * Masks a buffer using the given mask.
- *
- * @param {Buffer} source The buffer to mask
- * @param {Buffer} mask The mask to use
- * @param {Buffer} output The buffer where to store the result
- * @param {Number} offset The offset at which to start writing
- * @param {Number} length The number of bytes to mask.
- * @public
- */
-function _mask (source, mask, output, offset, length) {
-  for (var i = 0; i < length; i++) {
-    output[offset + i] = source[i] ^ mask[i & 3];
-  }
-}
-
-/**
- * Unmasks a buffer using the given mask.
- *
- * @param {Buffer} buffer The buffer to unmask
- * @param {Buffer} mask The mask to use
- * @public
- */
-function _unmask (buffer, mask) {
-  // Required until https://github.com/nodejs/node/issues/9006 is resolved.
-  const length = buffer.length;
-  for (var i = 0; i < length; i++) {
-    buffer[i] ^= mask[i & 3];
-  }
-}
-
-try {
-  const bufferUtil = require('bufferutil');
-  const bu = bufferUtil.BufferUtil || bufferUtil;
-
-  module.exports = {
-    mask (source, mask, output, offset, length) {
-      if (length < 48) _mask(source, mask, output, offset, length);
-      else bu.mask(source, mask, output, offset, length);
-    },
-    unmask (buffer, mask) {
-      if (buffer.length < 32) _unmask(buffer, mask);
-      else bu.unmask(buffer, mask);
-    },
-    concat
-  };
-} catch (e) /* istanbul ignore next */ {
-  module.exports = { concat, mask: _mask, unmask: _unmask };
-}
+"use strict";function concat(n,t){const a=Buffer.allocUnsafe(t);for(var c=0,o=0;o<n.length;o++){const t=n[o];t.copy(a,c),c+=t.length}return a}function _mask(n,t,a,c,o){for(var s=0;s<o;s++)a[c+s]=n[s]^t[3&s]}function _unmask(n,t){const a=n.length;for(var c=0;c<a;c++)n[c]^=t[3&c]}try{const n=require("bufferutil"),t=n.BufferUtil||n;module.exports={mask(n,a,c,o,s){s<48?_mask(n,a,c,o,s):t.mask(n,a,c,o,s)},unmask(n,a){n.length<32?_unmask(n,a):t.unmask(n,a)},concat:concat}}catch(n){module.exports={concat:concat,mask:_mask,unmask:_unmask}}
\ No newline at end of file
index 4082981..913f3e0 100755 (executable)
@@ -1,10 +1 @@
-'use strict';
-
-module.exports = {
-  BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'],
-  GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',
-  kStatusCode: Symbol('status-code'),
-  kWebSocket: Symbol('websocket'),
-  EMPTY_BUFFER: Buffer.alloc(0),
-  NOOP: () => {}
-};
+"use strict";module.exports={BINARY_TYPES:["nodebuffer","arraybuffer","fragments"],GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),EMPTY_BUFFER:Buffer.alloc(0),NOOP:()=>{}};
\ No newline at end of file
index 574e908..615f167 100755 (executable)
@@ -1,170 +1 @@
-'use strict';
-
-/**
- * Class representing an event.
- *
- * @private
- */
-class Event {
-  /**
-   * Create a new `Event`.
-   *
-   * @param {String} type The name of the event
-   * @param {Object} target A reference to the target to which the event was dispatched
-   */
-  constructor (type, target) {
-    this.target = target;
-    this.type = type;
-  }
-}
-
-/**
- * Class representing a message event.
- *
- * @extends Event
- * @private
- */
-class MessageEvent extends Event {
-  /**
-   * Create a new `MessageEvent`.
-   *
-   * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The received data
-   * @param {WebSocket} target A reference to the target to which the event was dispatched
-   */
-  constructor (data, target) {
-    super('message', target);
-
-    this.data = data;
-  }
-}
-
-/**
- * Class representing a close event.
- *
- * @extends Event
- * @private
- */
-class CloseEvent extends Event {
-  /**
-   * Create a new `CloseEvent`.
-   *
-   * @param {Number} code The status code explaining why the connection is being closed
-   * @param {String} reason A human-readable string explaining why the connection is closing
-   * @param {WebSocket} target A reference to the target to which the event was dispatched
-   */
-  constructor (code, reason, target) {
-    super('close', target);
-
-    this.wasClean = target._closeFrameReceived && target._closeFrameSent;
-    this.reason = reason;
-    this.code = code;
-  }
-}
-
-/**
- * Class representing an open event.
- *
- * @extends Event
- * @private
- */
-class OpenEvent extends Event {
-  /**
-   * Create a new `OpenEvent`.
-   *
-   * @param {WebSocket} target A reference to the target to which the event was dispatched
-   */
-  constructor (target) {
-    super('open', target);
-  }
-}
-
-/**
- * Class representing an error event.
- *
- * @extends Event
- * @private
- */
-class ErrorEvent extends Event {
-  /**
-   * Create a new `ErrorEvent`.
-   *
-   * @param {Object} error The error that generated this event
-   * @param {WebSocket} target A reference to the target to which the event was dispatched
-   */
-  constructor (error, target) {
-    super('error', target);
-
-    this.message = error.message;
-    this.error = error;
-  }
-}
-
-/**
- * This provides methods for emulating the `EventTarget` interface. It's not
- * meant to be used directly.
- *
- * @mixin
- */
-const EventTarget = {
-  /**
-   * Register an event listener.
-   *
-   * @param {String} method A string representing the event type to listen for
-   * @param {Function} listener The listener to add
-   * @public
-   */
-  addEventListener (method, listener) {
-    if (typeof listener !== 'function') return;
-
-    function onMessage (data) {
-      listener.call(this, new MessageEvent(data, this));
-    }
-
-    function onClose (code, message) {
-      listener.call(this, new CloseEvent(code, message, this));
-    }
-
-    function onError (error) {
-      listener.call(this, new ErrorEvent(error, this));
-    }
-
-    function onOpen () {
-      listener.call(this, new OpenEvent(this));
-    }
-
-    if (method === 'message') {
-      onMessage._listener = listener;
-      this.on(method, onMessage);
-    } else if (method === 'close') {
-      onClose._listener = listener;
-      this.on(method, onClose);
-    } else if (method === 'error') {
-      onError._listener = listener;
-      this.on(method, onError);
-    } else if (method === 'open') {
-      onOpen._listener = listener;
-      this.on(method, onOpen);
-    } else {
-      this.on(method, listener);
-    }
-  },
-
-  /**
-   * Remove an event listener.
-   *
-   * @param {String} method A string representing the event type to remove
-   * @param {Function} listener The listener to remove
-   * @public
-   */
-  removeEventListener (method, listener) {
-    const listeners = this.listeners(method);
-
-    for (var i = 0; i < listeners.length; i++) {
-      if (listeners[i] === listener || listeners[i]._listener === listener) {
-        this.removeListener(method, listeners[i]);
-      }
-    }
-  }
-};
-
-module.exports = EventTarget;
+"use strict";class Event{constructor(e,t){this.target=t,this.type=e}}class MessageEvent extends Event{constructor(e,t){super("message",t),this.data=e}}class CloseEvent extends Event{constructor(e,t,s){super("close",s),this.wasClean=s._closeFrameReceived&&s._closeFrameSent,this.reason=t,this.code=e}}class OpenEvent extends Event{constructor(e){super("open",e)}}class ErrorEvent extends Event{constructor(e,t){super("error",t),this.message=e.message,this.error=e}}const EventTarget={addEventListener(e,t){function s(e){t.call(this,new MessageEvent(e,this))}function n(e,s){t.call(this,new CloseEvent(e,s,this))}function r(e){t.call(this,new ErrorEvent(e,this))}function o(){t.call(this,new OpenEvent(this))}"function"==typeof t&&("message"===e?(s._listener=t,this.on(e,s)):"close"===e?(n._listener=t,this.on(e,n)):"error"===e?(r._listener=t,this.on(e,r)):"open"===e?(o._listener=t,this.on(e,o)):this.on(e,t))},removeEventListener(e,t){const s=this.listeners(e);for(var n=0;n<s.length;n++)s[n]!==t&&s[n]._listener!==t||this.removeListener(e,s[n])}};module.exports=EventTarget;
\ No newline at end of file
index 3f48d75..9a0f363 100755 (executable)
@@ -1,211 +1 @@
-'use strict';
-
-//
-// Allowed token characters:
-//
-// '!', '#', '$', '%', '&', ''', '*', '+', '-',
-// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'
-//
-// tokenChars[32] === 0 // ' '
-// tokenChars[33] === 1 // '!'
-// tokenChars[34] === 0 // '"'
-// ...
-//
-const tokenChars = [
-  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15
-  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31
-  0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47
-  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63
-  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79
-  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95
-  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111
-  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127
-];
-
-/**
- * Adds an offer to the map of extension offers or a parameter to the map of
- * parameters.
- *
- * @param {Object} dest The map of extension offers or parameters
- * @param {String} name The extension or parameter name
- * @param {(Object|Boolean|String)} elem The extension parameters or the
- *     parameter value
- * @private
- */
-function push (dest, name, elem) {
-  if (Object.prototype.hasOwnProperty.call(dest, name)) dest[name].push(elem);
-  else dest[name] = [elem];
-}
-
-/**
- * Parses the `Sec-WebSocket-Extensions` header into an object.
- *
- * @param {String} header The field value of the header
- * @return {Object} The parsed object
- * @public
- */
-function parse (header) {
-  const offers = {};
-
-  if (header === undefined || header === '') return offers;
-
-  var params = {};
-  var mustUnescape = false;
-  var isEscaping = false;
-  var inQuotes = false;
-  var extensionName;
-  var paramName;
-  var start = -1;
-  var end = -1;
-
-  for (var i = 0; i < header.length; i++) {
-    const code = header.charCodeAt(i);
-
-    if (extensionName === undefined) {
-      if (end === -1 && tokenChars[code] === 1) {
-        if (start === -1) start = i;
-      } else if (code === 0x20/* ' ' */|| code === 0x09/* '\t' */) {
-        if (end === -1 && start !== -1) end = i;
-      } else if (code === 0x3b/* ';' */ || code === 0x2c/* ',' */) {
-        if (start === -1) {
-          throw new SyntaxError(`Unexpected character at index ${i}`);
-        }
-
-        if (end === -1) end = i;
-        const name = header.slice(start, end);
-        if (code === 0x2c) {
-          push(offers, name, params);
-          params = {};
-        } else {
-          extensionName = name;
-        }
-
-        start = end = -1;
-      } else {
-        throw new SyntaxError(`Unexpected character at index ${i}`);
-      }
-    } else if (paramName === undefined) {
-      if (end === -1 && tokenChars[code] === 1) {
-        if (start === -1) start = i;
-      } else if (code === 0x20 || code === 0x09) {
-        if (end === -1 && start !== -1) end = i;
-      } else if (code === 0x3b || code === 0x2c) {
-        if (start === -1) {
-          throw new SyntaxError(`Unexpected character at index ${i}`);
-        }
-
-        if (end === -1) end = i;
-        push(params, header.slice(start, end), true);
-        if (code === 0x2c) {
-          push(offers, extensionName, params);
-          params = {};
-          extensionName = undefined;
-        }
-
-        start = end = -1;
-      } else if (code === 0x3d/* '=' */&& start !== -1 && end === -1) {
-        paramName = header.slice(start, i);
-        start = end = -1;
-      } else {
-        throw new SyntaxError(`Unexpected character at index ${i}`);
-      }
-    } else {
-      //
-      // The value of a quoted-string after unescaping must conform to the
-      // token ABNF, so only token characters are valid.
-      // Ref: https://tools.ietf.org/html/rfc6455#section-9.1
-      //
-      if (isEscaping) {
-        if (tokenChars[code] !== 1) {
-          throw new SyntaxError(`Unexpected character at index ${i}`);
-        }
-        if (start === -1) start = i;
-        else if (!mustUnescape) mustUnescape = true;
-        isEscaping = false;
-      } else if (inQuotes) {
-        if (tokenChars[code] === 1) {
-          if (start === -1) start = i;
-        } else if (code === 0x22/* '"' */ && start !== -1) {
-          inQuotes = false;
-          end = i;
-        } else if (code === 0x5c/* '\' */) {
-          isEscaping = true;
-        } else {
-          throw new SyntaxError(`Unexpected character at index ${i}`);
-        }
-      } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {
-        inQuotes = true;
-      } else if (end === -1 && tokenChars[code] === 1) {
-        if (start === -1) start = i;
-      } else if (start !== -1 && (code === 0x20 || code === 0x09)) {
-        if (end === -1) end = i;
-      } else if (code === 0x3b || code === 0x2c) {
-        if (start === -1) {
-          throw new SyntaxError(`Unexpected character at index ${i}`);
-        }
-
-        if (end === -1) end = i;
-        var value = header.slice(start, end);
-        if (mustUnescape) {
-          value = value.replace(/\\/g, '');
-          mustUnescape = false;
-        }
-        push(params, paramName, value);
-        if (code === 0x2c) {
-          push(offers, extensionName, params);
-          params = {};
-          extensionName = undefined;
-        }
-
-        paramName = undefined;
-        start = end = -1;
-      } else {
-        throw new SyntaxError(`Unexpected character at index ${i}`);
-      }
-    }
-  }
-
-  if (start === -1 || inQuotes) {
-    throw new SyntaxError('Unexpected end of input');
-  }
-
-  if (end === -1) end = i;
-  const token = header.slice(start, end);
-  if (extensionName === undefined) {
-    push(offers, token, {});
-  } else {
-    if (paramName === undefined) {
-      push(params, token, true);
-    } else if (mustUnescape) {
-      push(params, paramName, token.replace(/\\/g, ''));
-    } else {
-      push(params, paramName, token);
-    }
-    push(offers, extensionName, params);
-  }
-
-  return offers;
-}
-
-/**
- * Builds the `Sec-WebSocket-Extensions` header field value.
- *
- * @param {Object} extensions The map of extensions and parameters to format
- * @return {String} A string representing the given object
- * @public
- */
-function format (extensions) {
-  return Object.keys(extensions).map((extension) => {
-    var configurations = extensions[extension];
-    if (!Array.isArray(configurations)) configurations = [configurations];
-    return configurations.map((params) => {
-      return [extension].concat(Object.keys(params).map((k) => {
-        var values = params[k];
-        if (!Array.isArray(values)) values = [values];
-        return values.map((v) => v === true ? k : `${k}=${v}`).join('; ');
-      })).join('; ');
-    }).join(', ');
-  }).join(', ');
-}
-
-module.exports = { format, parse };
+"use strict";const tokenChars=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function push(e,r,t){Object.prototype.hasOwnProperty.call(e,r)?e[r].push(t):e[r]=[t]}function parse(e){const r={};if(void 0===e||""===e)return r;for(var t,n,a={},o=!1,i=!1,s=!1,c=-1,h=-1,p=0;p<e.length;p++){const d=e.charCodeAt(p);if(void 0===t)if(-1===h&&1===tokenChars[d])-1===c&&(c=p);else if(32===d||9===d)-1===h&&-1!==c&&(h=p);else{if(59!==d&&44!==d)throw new SyntaxError(`Unexpected character at index ${p}`);{if(-1===c)throw new SyntaxError(`Unexpected character at index ${p}`);-1===h&&(h=p);const n=e.slice(c,h);44===d?(push(r,n,a),a={}):t=n,c=h=-1}}else if(void 0===n)if(-1===h&&1===tokenChars[d])-1===c&&(c=p);else if(32===d||9===d)-1===h&&-1!==c&&(h=p);else if(59===d||44===d){if(-1===c)throw new SyntaxError(`Unexpected character at index ${p}`);-1===h&&(h=p),push(a,e.slice(c,h),!0),44===d&&(push(r,t,a),a={},t=void 0),c=h=-1}else{if(61!==d||-1===c||-1!==h)throw new SyntaxError(`Unexpected character at index ${p}`);n=e.slice(c,p),c=h=-1}else if(i){if(1!==tokenChars[d])throw new SyntaxError(`Unexpected character at index ${p}`);-1===c?c=p:o||(o=!0),i=!1}else if(s)if(1===tokenChars[d])-1===c&&(c=p);else if(34===d&&-1!==c)s=!1,h=p;else{if(92!==d)throw new SyntaxError(`Unexpected character at index ${p}`);i=!0}else if(34===d&&61===e.charCodeAt(p-1))s=!0;else if(-1===h&&1===tokenChars[d])-1===c&&(c=p);else if(-1===c||32!==d&&9!==d){if(59!==d&&44!==d)throw new SyntaxError(`Unexpected character at index ${p}`);if(-1===c)throw new SyntaxError(`Unexpected character at index ${p}`);-1===h&&(h=p);var f=e.slice(c,h);o&&(f=f.replace(/\\/g,""),o=!1),push(a,n,f),44===d&&(push(r,t,a),a={},t=void 0),n=void 0,c=h=-1}else-1===h&&(h=p)}if(-1===c||s)throw new SyntaxError("Unexpected end of input");-1===h&&(h=p);const d=e.slice(c,h);return void 0===t?push(r,d,{}):(void 0===n?push(a,d,!0):push(a,n,o?d.replace(/\\/g,""):d),push(r,t,a)),r}function format(e){return Object.keys(e).map((r=>{var t=e[r];return Array.isArray(t)||(t=[t]),t.map((e=>[r].concat(Object.keys(e).map((r=>{var t=e[r];return Array.isArray(t)||(t=[t]),t.map((e=>!0===e?r:`${r}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")}module.exports={format:format,parse:parse};
\ No newline at end of file
index 0d54f03..14dbb47 100755 (executable)
@@ -1,516 +1 @@
-'use strict';
-
-const Limiter = require('async-limiter');
-const zlib = require('zlib');
-
-const bufferUtil = require('./buffer-util');
-const constants = require('./constants');
-
-const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);
-const EMPTY_BLOCK = Buffer.from([0x00]);
-
-const kPerMessageDeflate = Symbol('permessage-deflate');
-const kWriteInProgress = Symbol('write-in-progress');
-const kPendingClose = Symbol('pending-close');
-const kTotalLength = Symbol('total-length');
-const kCallback = Symbol('callback');
-const kBuffers = Symbol('buffers');
-const kError = Symbol('error');
-
-//
-// We limit zlib concurrency, which prevents severe memory fragmentation
-// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913
-// and https://github.com/websockets/ws/issues/1202
-//
-// Intentionally global; it's the global thread pool that's an issue.
-//
-let zlibLimiter;
-
-/**
- * permessage-deflate implementation.
- */
-class PerMessageDeflate {
-  /**
-   * Creates a PerMessageDeflate instance.
-   *
-   * @param {Object} options Configuration options
-   * @param {Boolean} options.serverNoContextTakeover Request/accept disabling
-   *     of server context takeover
-   * @param {Boolean} options.clientNoContextTakeover Advertise/acknowledge
-   *     disabling of client context takeover
-   * @param {(Boolean|Number)} options.serverMaxWindowBits Request/confirm the
-   *     use of a custom server window size
-   * @param {(Boolean|Number)} options.clientMaxWindowBits Advertise support
-   *     for, or request, a custom client window size
-   * @param {Object} options.zlibDeflateOptions Options to pass to zlib on deflate
-   * @param {Object} options.zlibInflateOptions Options to pass to zlib on inflate
-   * @param {Number} options.threshold Size (in bytes) below which messages
-   *     should not be compressed
-   * @param {Number} options.concurrencyLimit The number of concurrent calls to
-   *     zlib
-   * @param {Boolean} isServer Create the instance in either server or client
-   *     mode
-   * @param {Number} maxPayload The maximum allowed message length
-   */
-  constructor (options, isServer, maxPayload) {
-    this._maxPayload = maxPayload | 0;
-    this._options = options || {};
-    this._threshold = this._options.threshold !== undefined
-      ? this._options.threshold
-      : 1024;
-    this._isServer = !!isServer;
-    this._deflate = null;
-    this._inflate = null;
-
-    this.params = null;
-
-    if (!zlibLimiter) {
-      const concurrency = this._options.concurrencyLimit !== undefined
-        ? this._options.concurrencyLimit
-        : 10;
-      zlibLimiter = new Limiter({ concurrency });
-    }
-  }
-
-  /**
-   * @type {String}
-   */
-  static get extensionName () {
-    return 'permessage-deflate';
-  }
-
-  /**
-   * Create an extension negotiation offer.
-   *
-   * @return {Object} Extension parameters
-   * @public
-   */
-  offer () {
-    const params = {};
-
-    if (this._options.serverNoContextTakeover) {
-      params.server_no_context_takeover = true;
-    }
-    if (this._options.clientNoContextTakeover) {
-      params.client_no_context_takeover = true;
-    }
-    if (this._options.serverMaxWindowBits) {
-      params.server_max_window_bits = this._options.serverMaxWindowBits;
-    }
-    if (this._options.clientMaxWindowBits) {
-      params.client_max_window_bits = this._options.clientMaxWindowBits;
-    } else if (this._options.clientMaxWindowBits == null) {
-      params.client_max_window_bits = true;
-    }
-
-    return params;
-  }
-
-  /**
-   * Accept an extension negotiation offer/response.
-   *
-   * @param {Array} configurations The extension negotiation offers/reponse
-   * @return {Object} Accepted configuration
-   * @public
-   */
-  accept (configurations) {
-    configurations = this.normalizeParams(configurations);
-
-    this.params = this._isServer
-      ? this.acceptAsServer(configurations)
-      : this.acceptAsClient(configurations);
-
-    return this.params;
-  }
-
-  /**
-   * Releases all resources used by the extension.
-   *
-   * @public
-   */
-  cleanup () {
-    if (this._inflate) {
-      if (this._inflate[kWriteInProgress]) {
-        this._inflate[kPendingClose] = true;
-      } else {
-        this._inflate.close();
-        this._inflate = null;
-      }
-    }
-    if (this._deflate) {
-      if (this._deflate[kWriteInProgress]) {
-        this._deflate[kPendingClose] = true;
-      } else {
-        this._deflate.close();
-        this._deflate = null;
-      }
-    }
-  }
-
-  /**
-   *  Accept an extension negotiation offer.
-   *
-   * @param {Array} offers The extension negotiation offers
-   * @return {Object} Accepted configuration
-   * @private
-   */
-  acceptAsServer (offers) {
-    const opts = this._options;
-    const accepted = offers.find((params) => {
-      if (
-        (opts.serverNoContextTakeover === false &&
-          params.server_no_context_takeover) ||
-        (params.server_max_window_bits &&
-          (opts.serverMaxWindowBits === false ||
-            (typeof opts.serverMaxWindowBits === 'number' &&
-              opts.serverMaxWindowBits > params.server_max_window_bits))) ||
-        (typeof opts.clientMaxWindowBits === 'number' &&
-          !params.client_max_window_bits)
-      ) {
-        return false;
-      }
-
-      return true;
-    });
-
-    if (!accepted) {
-      throw new Error('None of the extension offers can be accepted');
-    }
-
-    if (opts.serverNoContextTakeover) {
-      accepted.server_no_context_takeover = true;
-    }
-    if (opts.clientNoContextTakeover) {
-      accepted.client_no_context_takeover = true;
-    }
-    if (typeof opts.serverMaxWindowBits === 'number') {
-      accepted.server_max_window_bits = opts.serverMaxWindowBits;
-    }
-    if (typeof opts.clientMaxWindowBits === 'number') {
-      accepted.client_max_window_bits = opts.clientMaxWindowBits;
-    } else if (
-      accepted.client_max_window_bits === true ||
-      opts.clientMaxWindowBits === false
-    ) {
-      delete accepted.client_max_window_bits;
-    }
-
-    return accepted;
-  }
-
-  /**
-   * Accept the extension negotiation response.
-   *
-   * @param {Array} response The extension negotiation response
-   * @return {Object} Accepted configuration
-   * @private
-   */
-  acceptAsClient (response) {
-    const params = response[0];
-
-    if (
-      this._options.clientNoContextTakeover === false &&
-      params.client_no_context_takeover
-    ) {
-      throw new Error('Unexpected parameter "client_no_context_takeover"');
-    }
-
-    if (!params.client_max_window_bits) {
-      if (typeof this._options.clientMaxWindowBits === 'number') {
-        params.client_max_window_bits = this._options.clientMaxWindowBits;
-      }
-    } else if (
-      this._options.clientMaxWindowBits === false ||
-      (typeof this._options.clientMaxWindowBits === 'number' &&
-        params.client_max_window_bits > this._options.clientMaxWindowBits)
-    ) {
-      throw new Error(
-        'Unexpected or invalid parameter "client_max_window_bits"'
-      );
-    }
-
-    return params;
-  }
-
-  /**
-   * Normalize parameters.
-   *
-   * @param {Array} configurations The extension negotiation offers/reponse
-   * @return {Array} The offers/response with normalized parameters
-   * @private
-   */
-  normalizeParams (configurations) {
-    configurations.forEach((params) => {
-      Object.keys(params).forEach((key) => {
-        var value = params[key];
-
-        if (value.length > 1) {
-          throw new Error(`Parameter "${key}" must have only a single value`);
-        }
-
-        value = value[0];
-
-        if (key === 'client_max_window_bits') {
-          if (value !== true) {
-            const num = +value;
-            if (!Number.isInteger(num) || num < 8 || num > 15) {
-              throw new TypeError(
-                `Invalid value for parameter "${key}": ${value}`
-              );
-            }
-            value = num;
-          } else if (!this._isServer) {
-            throw new TypeError(
-              `Invalid value for parameter "${key}": ${value}`
-            );
-          }
-        } else if (key === 'server_max_window_bits') {
-          const num = +value;
-          if (!Number.isInteger(num) || num < 8 || num > 15) {
-            throw new TypeError(
-              `Invalid value for parameter "${key}": ${value}`
-            );
-          }
-          value = num;
-        } else if (
-          key === 'client_no_context_takeover' ||
-          key === 'server_no_context_takeover'
-        ) {
-          if (value !== true) {
-            throw new TypeError(
-              `Invalid value for parameter "${key}": ${value}`
-            );
-          }
-        } else {
-          throw new Error(`Unknown parameter "${key}"`);
-        }
-
-        params[key] = value;
-      });
-    });
-
-    return configurations;
-  }
-
-  /**
-   * Decompress data. Concurrency limited by async-limiter.
-   *
-   * @param {Buffer} data Compressed data
-   * @param {Boolean} fin Specifies whether or not this is the last fragment
-   * @param {Function} callback Callback
-   * @public
-   */
-  decompress (data, fin, callback) {
-    zlibLimiter.push((done) => {
-      this._decompress(data, fin, (err, result) => {
-        done();
-        callback(err, result);
-      });
-    });
-  }
-
-  /**
-   * Compress data. Concurrency limited by async-limiter.
-   *
-   * @param {Buffer} data Data to compress
-   * @param {Boolean} fin Specifies whether or not this is the last fragment
-   * @param {Function} callback Callback
-   * @public
-   */
-  compress (data, fin, callback) {
-    zlibLimiter.push((done) => {
-      this._compress(data, fin, (err, result) => {
-        done();
-        callback(err, result);
-      });
-    });
-  }
-
-  /**
-   * Decompress data.
-   *
-   * @param {Buffer} data Compressed data
-   * @param {Boolean} fin Specifies whether or not this is the last fragment
-   * @param {Function} callback Callback
-   * @private
-   */
-  _decompress (data, fin, callback) {
-    const endpoint = this._isServer ? 'client' : 'server';
-
-    if (!this._inflate) {
-      const key = `${endpoint}_max_window_bits`;
-      const windowBits = typeof this.params[key] !== 'number'
-        ? zlib.Z_DEFAULT_WINDOWBITS
-        : this.params[key];
-
-      this._inflate = zlib.createInflateRaw(
-        Object.assign({}, this._options.zlibInflateOptions, { windowBits })
-      );
-      this._inflate[kPerMessageDeflate] = this;
-      this._inflate[kTotalLength] = 0;
-      this._inflate[kBuffers] = [];
-      this._inflate.on('error', inflateOnError);
-      this._inflate.on('data', inflateOnData);
-    }
-
-    this._inflate[kCallback] = callback;
-    this._inflate[kWriteInProgress] = true;
-
-    this._inflate.write(data);
-    if (fin) this._inflate.write(TRAILER);
-
-    this._inflate.flush(() => {
-      const err = this._inflate[kError];
-
-      if (err) {
-        this._inflate.close();
-        this._inflate = null;
-        callback(err);
-        return;
-      }
-
-      const data = bufferUtil.concat(
-        this._inflate[kBuffers],
-        this._inflate[kTotalLength]
-      );
-
-      if (
-        (fin && this.params[`${endpoint}_no_context_takeover`]) ||
-        this._inflate[kPendingClose]
-      ) {
-        this._inflate.close();
-        this._inflate = null;
-      } else {
-        this._inflate[kWriteInProgress] = false;
-        this._inflate[kTotalLength] = 0;
-        this._inflate[kBuffers] = [];
-      }
-
-      callback(null, data);
-    });
-  }
-
-  /**
-   * Compress data.
-   *
-   * @param {Buffer} data Data to compress
-   * @param {Boolean} fin Specifies whether or not this is the last fragment
-   * @param {Function} callback Callback
-   * @private
-   */
-  _compress (data, fin, callback) {
-    if (!data || data.length === 0) {
-      process.nextTick(callback, null, EMPTY_BLOCK);
-      return;
-    }
-
-    const endpoint = this._isServer ? 'server' : 'client';
-
-    if (!this._deflate) {
-      const key = `${endpoint}_max_window_bits`;
-      const windowBits = typeof this.params[key] !== 'number'
-        ? zlib.Z_DEFAULT_WINDOWBITS
-        : this.params[key];
-
-      this._deflate = zlib.createDeflateRaw(
-        Object.assign(
-          // TODO deprecate memLevel/level and recommend zlibDeflateOptions instead
-          {
-            memLevel: this._options.memLevel,
-            level: this._options.level
-          },
-          this._options.zlibDeflateOptions,
-          { windowBits }
-        )
-      );
-
-      this._deflate[kTotalLength] = 0;
-      this._deflate[kBuffers] = [];
-
-      //
-      // `zlib.DeflateRaw` emits an `'error'` event only when an attempt to use
-      // it is made after it has already been closed. This cannot happen here,
-      // so we only add a listener for the `'data'` event.
-      //
-      this._deflate.on('data', deflateOnData);
-    }
-
-    this._deflate[kWriteInProgress] = true;
-
-    this._deflate.write(data);
-    this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
-      var data = bufferUtil.concat(
-        this._deflate[kBuffers],
-        this._deflate[kTotalLength]
-      );
-
-      if (fin) data = data.slice(0, data.length - 4);
-
-      if (
-        (fin && this.params[`${endpoint}_no_context_takeover`]) ||
-        this._deflate[kPendingClose]
-      ) {
-        this._deflate.close();
-        this._deflate = null;
-      } else {
-        this._deflate[kWriteInProgress] = false;
-        this._deflate[kTotalLength] = 0;
-        this._deflate[kBuffers] = [];
-      }
-
-      callback(null, data);
-    });
-  }
-}
-
-module.exports = PerMessageDeflate;
-
-/**
- * The listener of the `zlib.DeflateRaw` stream `'data'` event.
- *
- * @param {Buffer} chunk A chunk of data
- * @private
- */
-function deflateOnData (chunk) {
-  this[kBuffers].push(chunk);
-  this[kTotalLength] += chunk.length;
-}
-
-/**
- * The listener of the `zlib.InflateRaw` stream `'data'` event.
- *
- * @param {Buffer} chunk A chunk of data
- * @private
- */
-function inflateOnData (chunk) {
-  this[kTotalLength] += chunk.length;
-
-  if (
-    this[kPerMessageDeflate]._maxPayload < 1 ||
-    this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload
-  ) {
-    this[kBuffers].push(chunk);
-    return;
-  }
-
-  this[kError] = new RangeError('Max payload size exceeded');
-  this[kError][constants.kStatusCode] = 1009;
-  this.removeListener('data', inflateOnData);
-  this.reset();
-}
-
-/**
- * The listener of the `zlib.InflateRaw` stream `'error'` event.
- *
- * @param {Error} err The emitted error
- * @private
- */
-function inflateOnError (err) {
-  //
-  // There is no need to call `Zlib#close()` as the handle is automatically
-  // closed when an error is emitted.
-  //
-  this[kPerMessageDeflate]._inflate = null;
-  err[constants.kStatusCode] = 1007;
-  this[kCallback](err);
-}
+"use strict";const Limiter=require("async-limiter"),zlib=require("zlib"),bufferUtil=require("./buffer-util"),constants=require("./constants"),TRAILER=Buffer.from([0,0,255,255]),EMPTY_BLOCK=Buffer.from([0]),kPerMessageDeflate=Symbol("permessage-deflate"),kWriteInProgress=Symbol("write-in-progress"),kPendingClose=Symbol("pending-close"),kTotalLength=Symbol("total-length"),kCallback=Symbol("callback"),kBuffers=Symbol("buffers"),kError=Symbol("error");let zlibLimiter;class PerMessageDeflate{constructor(e,t,i){if(this._maxPayload=0|i,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!zlibLimiter){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;zlibLimiter=new Limiter({concurrency:e})}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){this._inflate&&(this._inflate[kWriteInProgress]?this._inflate[kPendingClose]=!0:(this._inflate.close(),this._inflate=null)),this._deflate&&(this._deflate[kWriteInProgress]?this._deflate[kPendingClose]=!0:(this._deflate.close(),this._deflate=null))}acceptAsServer(e){const t=this._options,i=e.find((e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits)));if(!i)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(i.server_no_context_takeover=!0),t.clientNoContextTakeover&&(i.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(i.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?i.client_max_window_bits=t.clientMaxWindowBits:!0!==i.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete i.client_max_window_bits,i}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach((e=>{Object.keys(e).forEach((t=>{var i=e[t];if(i.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(i=i[0],"client_max_window_bits"===t){if(!0!==i){const e=+i;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${i}`);i=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${i}`)}else if("server_max_window_bits"===t){const e=+i;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${i}`);i=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==i)throw new TypeError(`Invalid value for parameter "${t}": ${i}`)}e[t]=i}))})),e}decompress(e,t,i){zlibLimiter.push((s=>{this._decompress(e,t,((e,t)=>{s(),i(e,t)}))}))}compress(e,t,i){zlibLimiter.push((s=>{this._compress(e,t,((e,t)=>{s(),i(e,t)}))}))}_decompress(e,t,i){const s=this._isServer?"client":"server";if(!this._inflate){const e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?zlib.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=zlib.createInflateRaw(Object.assign({},this._options.zlibInflateOptions,{windowBits:t})),this._inflate[kPerMessageDeflate]=this,this._inflate[kTotalLength]=0,this._inflate[kBuffers]=[],this._inflate.on("error",inflateOnError),this._inflate.on("data",inflateOnData)}this._inflate[kCallback]=i,this._inflate[kWriteInProgress]=!0,this._inflate.write(e),t&&this._inflate.write(TRAILER),this._inflate.flush((()=>{const e=this._inflate[kError];if(e)return this._inflate.close(),this._inflate=null,void i(e);const n=bufferUtil.concat(this._inflate[kBuffers],this._inflate[kTotalLength]);t&&this.params[`${s}_no_context_takeover`]||this._inflate[kPendingClose]?(this._inflate.close(),this._inflate=null):(this._inflate[kWriteInProgress]=!1,this._inflate[kTotalLength]=0,this._inflate[kBuffers]=[]),i(null,n)}))}_compress(e,t,i){if(!e||0===e.length)return void process.nextTick(i,null,EMPTY_BLOCK);const s=this._isServer?"server":"client";if(!this._deflate){const e=`${s}_max_window_bits`,t="number"!=typeof this.params[e]?zlib.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=zlib.createDeflateRaw(Object.assign({memLevel:this._options.memLevel,level:this._options.level},this._options.zlibDeflateOptions,{windowBits:t})),this._deflate[kTotalLength]=0,this._deflate[kBuffers]=[],this._deflate.on("data",deflateOnData)}this._deflate[kWriteInProgress]=!0,this._deflate.write(e),this._deflate.flush(zlib.Z_SYNC_FLUSH,(()=>{var e=bufferUtil.concat(this._deflate[kBuffers],this._deflate[kTotalLength]);t&&(e=e.slice(0,e.length-4)),t&&this.params[`${s}_no_context_takeover`]||this._deflate[kPendingClose]?(this._deflate.close(),this._deflate=null):(this._deflate[kWriteInProgress]=!1,this._deflate[kTotalLength]=0,this._deflate[kBuffers]=[]),i(null,e)}))}}function deflateOnData(e){this[kBuffers].push(e),this[kTotalLength]+=e.length}function inflateOnData(e){this[kTotalLength]+=e.length,this[kPerMessageDeflate]._maxPayload<1||this[kTotalLength]<=this[kPerMessageDeflate]._maxPayload?this[kBuffers].push(e):(this[kError]=new RangeError("Max payload size exceeded"),this[kError][constants.kStatusCode]=1009,this.removeListener("data",inflateOnData),this.reset())}function inflateOnError(e){this[kPerMessageDeflate]._inflate=null,e[constants.kStatusCode]=1007,this[kCallback](e)}module.exports=PerMessageDeflate;
\ No newline at end of file
index 81dc0bf..6629410 100755 (executable)
@@ -1,513 +1 @@
-'use strict';
-
-const stream = require('stream');
-
-const PerMessageDeflate = require('./permessage-deflate');
-const bufferUtil = require('./buffer-util');
-const validation = require('./validation');
-const constants = require('./constants');
-
-const GET_INFO = 0;
-const GET_PAYLOAD_LENGTH_16 = 1;
-const GET_PAYLOAD_LENGTH_64 = 2;
-const GET_MASK = 3;
-const GET_DATA = 4;
-const INFLATING = 5;
-
-/**
- * HyBi Receiver implementation.
- *
- * @extends stream.Writable
- */
-class Receiver extends stream.Writable {
-  /**
-   * Creates a Receiver instance.
-   *
-   * @param {String} binaryType The type for binary data
-   * @param {Object} extensions An object containing the negotiated extensions
-   * @param {Number} maxPayload The maximum allowed message length
-   */
-  constructor (binaryType, extensions, maxPayload) {
-    super();
-
-    this._binaryType = binaryType || constants.BINARY_TYPES[0];
-    this[constants.kWebSocket] = undefined;
-    this._extensions = extensions || {};
-    this._maxPayload = maxPayload | 0;
-
-    this._bufferedBytes = 0;
-    this._buffers = [];
-
-    this._compressed = false;
-    this._payloadLength = 0;
-    this._mask = undefined;
-    this._fragmented = 0;
-    this._masked = false;
-    this._fin = false;
-    this._opcode = 0;
-
-    this._totalPayloadLength = 0;
-    this._messageLength = 0;
-    this._fragments = [];
-
-    this._state = GET_INFO;
-    this._loop = false;
-  }
-
-  /**
-   * Implements `Writable.prototype._write()`.
-   *
-   * @param {Buffer} chunk The chunk of data to write
-   * @param {String} encoding The character encoding of `chunk`
-   * @param {Function} cb Callback
-   */
-  _write (chunk, encoding, cb) {
-    if (this._opcode === 0x08) return cb();
-
-    this._bufferedBytes += chunk.length;
-    this._buffers.push(chunk);
-    this.startLoop(cb);
-  }
-
-  /**
-   * Consumes `n` bytes from the buffered data.
-   *
-   * @param {Number} n The number of bytes to consume
-   * @return {Buffer} The consumed bytes
-   * @private
-   */
-  consume (n) {
-    this._bufferedBytes -= n;
-
-    if (n === this._buffers[0].length) return this._buffers.shift();
-
-    if (n < this._buffers[0].length) {
-      const buf = this._buffers[0];
-      this._buffers[0] = buf.slice(n);
-      return buf.slice(0, n);
-    }
-
-    const dst = Buffer.allocUnsafe(n);
-
-    do {
-      const buf = this._buffers[0];
-
-      if (n >= buf.length) {
-        this._buffers.shift().copy(dst, dst.length - n);
-      } else {
-        buf.copy(dst, dst.length - n, 0, n);
-        this._buffers[0] = buf.slice(n);
-      }
-
-      n -= buf.length;
-    } while (n > 0);
-
-    return dst;
-  }
-
-  /**
-   * Starts the parsing loop.
-   *
-   * @param {Function} cb Callback
-   * @private
-   */
-  startLoop (cb) {
-    var err;
-    this._loop = true;
-
-    do {
-      switch (this._state) {
-        case GET_INFO:
-          err = this.getInfo();
-          break;
-        case GET_PAYLOAD_LENGTH_16:
-          err = this.getPayloadLength16();
-          break;
-        case GET_PAYLOAD_LENGTH_64:
-          err = this.getPayloadLength64();
-          break;
-        case GET_MASK:
-          this.getMask();
-          break;
-        case GET_DATA:
-          err = this.getData(cb);
-          break;
-        default: // `INFLATING`
-          this._loop = false;
-          return;
-      }
-    } while (this._loop);
-
-    cb(err);
-  }
-
-  /**
-   * Reads the first two bytes of a frame.
-   *
-   * @return {(RangeError|undefined)} A possible error
-   * @private
-   */
-  getInfo () {
-    if (this._bufferedBytes < 2) {
-      this._loop = false;
-      return;
-    }
-
-    const buf = this.consume(2);
-
-    if ((buf[0] & 0x30) !== 0x00) {
-      this._loop = false;
-      return error(RangeError, 'RSV2 and RSV3 must be clear', true, 1002);
-    }
-
-    const compressed = (buf[0] & 0x40) === 0x40;
-
-    if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
-      this._loop = false;
-      return error(RangeError, 'RSV1 must be clear', true, 1002);
-    }
-
-    this._fin = (buf[0] & 0x80) === 0x80;
-    this._opcode = buf[0] & 0x0f;
-    this._payloadLength = buf[1] & 0x7f;
-
-    if (this._opcode === 0x00) {
-      if (compressed) {
-        this._loop = false;
-        return error(RangeError, 'RSV1 must be clear', true, 1002);
-      }
-
-      if (!this._fragmented) {
-        this._loop = false;
-        return error(RangeError, 'invalid opcode 0', true, 1002);
-      }
-
-      this._opcode = this._fragmented;
-    } else if (this._opcode === 0x01 || this._opcode === 0x02) {
-      if (this._fragmented) {
-        this._loop = false;
-        return error(RangeError, `invalid opcode ${this._opcode}`, true, 1002);
-      }
-
-      this._compressed = compressed;
-    } else if (this._opcode > 0x07 && this._opcode < 0x0b) {
-      if (!this._fin) {
-        this._loop = false;
-        return error(RangeError, 'FIN must be set', true, 1002);
-      }
-
-      if (compressed) {
-        this._loop = false;
-        return error(RangeError, 'RSV1 must be clear', true, 1002);
-      }
-
-      if (this._payloadLength > 0x7d) {
-        this._loop = false;
-        return error(
-          RangeError,
-          `invalid payload length ${this._payloadLength}`,
-          true,
-          1002
-        );
-      }
-    } else {
-      this._loop = false;
-      return error(RangeError, `invalid opcode ${this._opcode}`, true, 1002);
-    }
-
-    if (!this._fin && !this._fragmented) this._fragmented = this._opcode;
-    this._masked = (buf[1] & 0x80) === 0x80;
-
-    if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;
-    else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;
-    else return this.haveLength();
-  }
-
-  /**
-   * Gets extended payload length (7+16).
-   *
-   * @return {(RangeError|undefined)} A possible error
-   * @private
-   */
-  getPayloadLength16 () {
-    if (this._bufferedBytes < 2) {
-      this._loop = false;
-      return;
-    }
-
-    this._payloadLength = this.consume(2).readUInt16BE(0);
-    return this.haveLength();
-  }
-
-  /**
-   * Gets extended payload length (7+64).
-   *
-   * @return {(RangeError|undefined)} A possible error
-   * @private
-   */
-  getPayloadLength64 () {
-    if (this._bufferedBytes < 8) {
-      this._loop = false;
-      return;
-    }
-
-    const buf = this.consume(8);
-    const num = buf.readUInt32BE(0);
-
-    //
-    // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned
-    // if payload length is greater than this number.
-    //
-    if (num > Math.pow(2, 53 - 32) - 1) {
-      this._loop = false;
-      return error(
-        RangeError,
-        'Unsupported WebSocket frame: payload length > 2^53 - 1',
-        false,
-        1009
-      );
-    }
-
-    this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
-    return this.haveLength();
-  }
-
-  /**
-   * Payload length has been read.
-   *
-   * @return {(RangeError|undefined)} A possible error
-   * @private
-   */
-  haveLength () {
-    if (this._payloadLength && this._opcode < 0x08) {
-      this._totalPayloadLength += this._payloadLength;
-      if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
-        this._loop = false;
-        return error(RangeError, 'Max payload size exceeded', false, 1009);
-      }
-    }
-
-    if (this._masked) this._state = GET_MASK;
-    else this._state = GET_DATA;
-  }
-
-  /**
-   * Reads mask bytes.
-   *
-   * @private
-   */
-  getMask () {
-    if (this._bufferedBytes < 4) {
-      this._loop = false;
-      return;
-    }
-
-    this._mask = this.consume(4);
-    this._state = GET_DATA;
-  }
-
-  /**
-   * Reads data bytes.
-   *
-   * @param {Function} cb Callback
-   * @return {(Error|RangeError|undefined)} A possible error
-   * @private
-   */
-  getData (cb) {
-    var data = constants.EMPTY_BUFFER;
-
-    if (this._payloadLength) {
-      if (this._bufferedBytes < this._payloadLength) {
-        this._loop = false;
-        return;
-      }
-
-      data = this.consume(this._payloadLength);
-      if (this._masked) bufferUtil.unmask(data, this._mask);
-    }
-
-    if (this._opcode > 0x07) return this.controlMessage(data);
-
-    if (this._compressed) {
-      this._state = INFLATING;
-      this.decompress(data, cb);
-      return;
-    }
-
-    if (data.length) {
-      //
-      // This message is not compressed so its lenght is the sum of the payload
-      // length of all fragments.
-      //
-      this._messageLength = this._totalPayloadLength;
-      this._fragments.push(data);
-    }
-
-    return this.dataMessage();
-  }
-
-  /**
-   * Decompresses data.
-   *
-   * @param {Buffer} data Compressed data
-   * @param {Function} cb Callback
-   * @private
-   */
-  decompress (data, cb) {
-    const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
-
-    perMessageDeflate.decompress(data, this._fin, (err, buf) => {
-      if (err) return cb(err);
-
-      if (buf.length) {
-        this._messageLength += buf.length;
-        if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
-          return cb(error(RangeError, 'Max payload size exceeded', false, 1009));
-        }
-
-        this._fragments.push(buf);
-      }
-
-      const er = this.dataMessage();
-      if (er) return cb(er);
-
-      this.startLoop(cb);
-    });
-  }
-
-  /**
-   * Handles a data message.
-   *
-   * @return {(Error|undefined)} A possible error
-   * @private
-   */
-  dataMessage () {
-    if (this._fin) {
-      const messageLength = this._messageLength;
-      const fragments = this._fragments;
-
-      this._totalPayloadLength = 0;
-      this._messageLength = 0;
-      this._fragmented = 0;
-      this._fragments = [];
-
-      if (this._opcode === 2) {
-        var data;
-
-        if (this._binaryType === 'nodebuffer') {
-          data = toBuffer(fragments, messageLength);
-        } else if (this._binaryType === 'arraybuffer') {
-          data = toArrayBuffer(toBuffer(fragments, messageLength));
-        } else {
-          data = fragments;
-        }
-
-        this.emit('message', data);
-      } else {
-        const buf = toBuffer(fragments, messageLength);
-
-        if (!validation.isValidUTF8(buf)) {
-          this._loop = false;
-          return error(Error, 'invalid UTF-8 sequence', true, 1007);
-        }
-
-        this.emit('message', buf.toString());
-      }
-    }
-
-    this._state = GET_INFO;
-  }
-
-  /**
-   * Handles a control message.
-   *
-   * @param {Buffer} data Data to handle
-   * @return {(Error|RangeError|undefined)} A possible error
-   * @private
-   */
-  controlMessage (data) {
-    if (this._opcode === 0x08) {
-      this._loop = false;
-
-      if (data.length === 0) {
-        this.emit('conclude', 1005, '');
-        this.end();
-      } else if (data.length === 1) {
-        return error(RangeError, 'invalid payload length 1', true, 1002);
-      } else {
-        const code = data.readUInt16BE(0);
-
-        if (!validation.isValidStatusCode(code)) {
-          return error(RangeError, `invalid status code ${code}`, true, 1002);
-        }
-
-        const buf = data.slice(2);
-
-        if (!validation.isValidUTF8(buf)) {
-          return error(Error, 'invalid UTF-8 sequence', true, 1007);
-        }
-
-        this.emit('conclude', code, buf.toString());
-        this.end();
-      }
-
-      return;
-    }
-
-    if (this._opcode === 0x09) this.emit('ping', data);
-    else this.emit('pong', data);
-
-    this._state = GET_INFO;
-  }
-}
-
-module.exports = Receiver;
-
-/**
- * Builds an error object.
- *
- * @param {(Error|RangeError)} ErrorCtor The error constructor
- * @param {String} message The error message
- * @param {Boolean} prefix Specifies whether or not to add a default prefix to
- *     `message`
- * @param {Number} statusCode The status code
- * @return {(Error|RangeError)} The error
- * @private
- */
-function error (ErrorCtor, message, prefix, statusCode) {
-  const err = new ErrorCtor(
-    prefix ? `Invalid WebSocket frame: ${message}` : message
-  );
-
-  Error.captureStackTrace(err, error);
-  err[constants.kStatusCode] = statusCode;
-  return err;
-}
-
-/**
- * Makes a buffer from a list of fragments.
- *
- * @param {Buffer[]} fragments The list of fragments composing the message
- * @param {Number} messageLength The length of the message
- * @return {Buffer}
- * @private
- */
-function toBuffer (fragments, messageLength) {
-  if (fragments.length === 1) return fragments[0];
-  if (fragments.length > 1) return bufferUtil.concat(fragments, messageLength);
-  return constants.EMPTY_BUFFER;
-}
-
-/**
- * Converts a buffer to an `ArrayBuffer`.
- *
- * @param {Buffer} The buffer to convert
- * @return {ArrayBuffer} Converted buffer
- */
-function toArrayBuffer (buf) {
-  if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) {
-    return buf.buffer;
-  }
-
-  return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
-}
+"use strict";const stream=require("stream"),PerMessageDeflate=require("./permessage-deflate"),bufferUtil=require("./buffer-util"),validation=require("./validation"),constants=require("./constants"),GET_INFO=0,GET_PAYLOAD_LENGTH_16=1,GET_PAYLOAD_LENGTH_64=2,GET_MASK=3,GET_DATA=4,INFLATING=5;class Receiver extends stream.Writable{constructor(e,t,s){super(),this._binaryType=e||constants.BINARY_TYPES[0],this[constants.kWebSocket]=void 0,this._extensions=t||{},this._maxPayload=0|s,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._state=0,this._loop=!1}_write(e,t,s){if(8===this._opcode)return s();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){const t=this._buffers[0];return this._buffers[0]=t.slice(e),t.slice(0,e)}const t=Buffer.allocUnsafe(e);do{const s=this._buffers[0];e>=s.length?this._buffers.shift().copy(t,t.length-e):(s.copy(t,t.length-e,0,e),this._buffers[0]=s.slice(e)),e-=s.length}while(e>0);return t}startLoop(e){var t;this._loop=!0;do{switch(this._state){case 0:t=this.getInfo();break;case 1:t=this.getPayloadLength16();break;case 2:t=this.getPayloadLength64();break;case 3:this.getMask();break;case 4:t=this.getData(e);break;default:return void(this._loop=!1)}}while(this._loop);e(t)}getInfo(){if(this._bufferedBytes<2)return void(this._loop=!1);const e=this.consume(2);if(0!=(48&e[0]))return this._loop=!1,error(RangeError,"RSV2 and RSV3 must be clear",!0,1002);const t=64==(64&e[0]);if(t&&!this._extensions[PerMessageDeflate.extensionName])return this._loop=!1,error(RangeError,"RSV1 must be clear",!0,1002);if(this._fin=128==(128&e[0]),this._opcode=15&e[0],this._payloadLength=127&e[1],0===this._opcode){if(t)return this._loop=!1,error(RangeError,"RSV1 must be clear",!0,1002);if(!this._fragmented)return this._loop=!1,error(RangeError,"invalid opcode 0",!0,1002);this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented)return this._loop=!1,error(RangeError,`invalid opcode ${this._opcode}`,!0,1002);this._compressed=t}else{if(!(this._opcode>7&&this._opcode<11))return this._loop=!1,error(RangeError,`invalid opcode ${this._opcode}`,!0,1002);if(!this._fin)return this._loop=!1,error(RangeError,"FIN must be set",!0,1002);if(t)return this._loop=!1,error(RangeError,"RSV1 must be clear",!0,1002);if(this._payloadLength>125)return this._loop=!1,error(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002)}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=128==(128&e[1]),126===this._payloadLength)this._state=1;else{if(127!==this._payloadLength)return this.haveLength();this._state=2}}getPayloadLength16(){if(!(this._bufferedBytes<2))return this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength();this._loop=!1}getPayloadLength64(){if(this._bufferedBytes<8)return void(this._loop=!1);const e=this.consume(8),t=e.readUInt32BE(0);return t>Math.pow(2,21)-1?(this._loop=!1,error(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009)):(this._payloadLength=t*Math.pow(2,32)+e.readUInt32BE(4),this.haveLength())}haveLength(){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0))return this._loop=!1,error(RangeError,"Max payload size exceeded",!1,1009);this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){var t=constants.EMPTY_BUFFER;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength)return void(this._loop=!1);t=this.consume(this._payloadLength),this._masked&&bufferUtil.unmask(t,this._mask)}return this._opcode>7?this.controlMessage(t):this._compressed?(this._state=5,void this.decompress(t,e)):(t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage())}decompress(e,t){this._extensions[PerMessageDeflate.extensionName].decompress(e,this._fin,((e,s)=>{if(e)return t(e);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0)return t(error(RangeError,"Max payload size exceeded",!1,1009));this._fragments.push(s)}const i=this.dataMessage();if(i)return t(i);this.startLoop(t)}))}dataMessage(){if(this._fin){const t=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){var e;e="nodebuffer"===this._binaryType?toBuffer(s,t):"arraybuffer"===this._binaryType?toArrayBuffer(toBuffer(s,t)):s,this.emit("message",e)}else{const e=toBuffer(s,t);if(!validation.isValidUTF8(e))return this._loop=!1,error(Error,"invalid UTF-8 sequence",!0,1007);this.emit("message",e.toString())}}this._state=0}controlMessage(e){if(8!==this._opcode)9===this._opcode?this.emit("ping",e):this.emit("pong",e),this._state=0;else if(this._loop=!1,0===e.length)this.emit("conclude",1005,""),this.end();else{if(1===e.length)return error(RangeError,"invalid payload length 1",!0,1002);{const t=e.readUInt16BE(0);if(!validation.isValidStatusCode(t))return error(RangeError,`invalid status code ${t}`,!0,1002);const s=e.slice(2);if(!validation.isValidUTF8(s))return error(Error,"invalid UTF-8 sequence",!0,1007);this.emit("conclude",t,s.toString()),this.end()}}}}function error(e,t,s,i){const r=new e(s?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(r,error),r[constants.kStatusCode]=i,r}function toBuffer(e,t){return 1===e.length?e[0]:e.length>1?bufferUtil.concat(e,t):constants.EMPTY_BUFFER}function toArrayBuffer(e){return 0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}module.exports=Receiver;
\ No newline at end of file
index 060e553..c46ba95 100755 (executable)
@@ -1,401 +1 @@
-'use strict';
-
-const crypto = require('crypto');
-
-const PerMessageDeflate = require('./permessage-deflate');
-const bufferUtil = require('./buffer-util');
-const validation = require('./validation');
-const constants = require('./constants');
-
-/**
- * HyBi Sender implementation.
- */
-class Sender {
-  /**
-   * Creates a Sender instance.
-   *
-   * @param {net.Socket} socket The connection socket
-   * @param {Object} extensions An object containing the negotiated extensions
-   */
-  constructor (socket, extensions) {
-    this._extensions = extensions || {};
-    this._socket = socket;
-
-    this._firstFragment = true;
-    this._compress = false;
-
-    this._bufferedBytes = 0;
-    this._deflating = false;
-    this._queue = [];
-  }
-
-  /**
-   * Frames a piece of data according to the HyBi WebSocket protocol.
-   *
-   * @param {Buffer} data The data to frame
-   * @param {Object} options Options object
-   * @param {Number} options.opcode The opcode
-   * @param {Boolean} options.readOnly Specifies whether `data` can be modified
-   * @param {Boolean} options.fin Specifies whether or not to set the FIN bit
-   * @param {Boolean} options.mask Specifies whether or not to mask `data`
-   * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit
-   * @return {Buffer[]} The framed data as a list of `Buffer` instances
-   * @public
-   */
-  static frame (data, options) {
-    const merge = data.length < 1024 || (options.mask && options.readOnly);
-    var offset = options.mask ? 6 : 2;
-    var payloadLength = data.length;
-
-    if (data.length >= 65536) {
-      offset += 8;
-      payloadLength = 127;
-    } else if (data.length > 125) {
-      offset += 2;
-      payloadLength = 126;
-    }
-
-    const target = Buffer.allocUnsafe(merge ? data.length + offset : offset);
-
-    target[0] = options.fin ? options.opcode | 0x80 : options.opcode;
-    if (options.rsv1) target[0] |= 0x40;
-
-    if (payloadLength === 126) {
-      target.writeUInt16BE(data.length, 2);
-    } else if (payloadLength === 127) {
-      target.writeUInt32BE(0, 2);
-      target.writeUInt32BE(data.length, 6);
-    }
-
-    if (!options.mask) {
-      target[1] = payloadLength;
-      if (merge) {
-        data.copy(target, offset);
-        return [target];
-      }
-
-      return [target, data];
-    }
-
-    const mask = crypto.randomBytes(4);
-
-    target[1] = payloadLength | 0x80;
-    target[offset - 4] = mask[0];
-    target[offset - 3] = mask[1];
-    target[offset - 2] = mask[2];
-    target[offset - 1] = mask[3];
-
-    if (merge) {
-      bufferUtil.mask(data, mask, target, offset, data.length);
-      return [target];
-    }
-
-    bufferUtil.mask(data, mask, data, 0, data.length);
-    return [target, data];
-  }
-
-  /**
-   * Sends a close message to the other peer.
-   *
-   * @param {(Number|undefined)} code The status code component of the body
-   * @param {String} data The message component of the body
-   * @param {Boolean} mask Specifies whether or not to mask the message
-   * @param {Function} cb Callback
-   * @public
-   */
-  close (code, data, mask, cb) {
-    var buf;
-
-    if (code === undefined) {
-      buf = constants.EMPTY_BUFFER;
-    } else if (typeof code !== 'number' || !validation.isValidStatusCode(code)) {
-      throw new TypeError('First argument must be a valid error code number');
-    } else if (data === undefined || data === '') {
-      buf = Buffer.allocUnsafe(2);
-      buf.writeUInt16BE(code, 0);
-    } else {
-      buf = Buffer.allocUnsafe(2 + Buffer.byteLength(data));
-      buf.writeUInt16BE(code, 0);
-      buf.write(data, 2);
-    }
-
-    if (this._deflating) {
-      this.enqueue([this.doClose, buf, mask, cb]);
-    } else {
-      this.doClose(buf, mask, cb);
-    }
-  }
-
-  /**
-   * Frames and sends a close message.
-   *
-   * @param {Buffer} data The message to send
-   * @param {Boolean} mask Specifies whether or not to mask `data`
-   * @param {Function} cb Callback
-   * @private
-   */
-  doClose (data, mask, cb) {
-    this.sendFrame(Sender.frame(data, {
-      fin: true,
-      rsv1: false,
-      opcode: 0x08,
-      mask,
-      readOnly: false
-    }), cb);
-  }
-
-  /**
-   * Sends a ping message to the other peer.
-   *
-   * @param {*} data The message to send
-   * @param {Boolean} mask Specifies whether or not to mask `data`
-   * @param {Function} cb Callback
-   * @public
-   */
-  ping (data, mask, cb) {
-    var readOnly = true;
-
-    if (!Buffer.isBuffer(data)) {
-      if (data instanceof ArrayBuffer) {
-        data = Buffer.from(data);
-      } else if (ArrayBuffer.isView(data)) {
-        data = viewToBuffer(data);
-      } else {
-        data = Buffer.from(data);
-        readOnly = false;
-      }
-    }
-
-    if (this._deflating) {
-      this.enqueue([this.doPing, data, mask, readOnly, cb]);
-    } else {
-      this.doPing(data, mask, readOnly, cb);
-    }
-  }
-
-  /**
-   * Frames and sends a ping message.
-   *
-   * @param {*} data The message to send
-   * @param {Boolean} mask Specifies whether or not to mask `data`
-   * @param {Boolean} readOnly Specifies whether `data` can be modified
-   * @param {Function} cb Callback
-   * @private
-   */
-  doPing (data, mask, readOnly, cb) {
-    this.sendFrame(Sender.frame(data, {
-      fin: true,
-      rsv1: false,
-      opcode: 0x09,
-      mask,
-      readOnly
-    }), cb);
-  }
-
-  /**
-   * Sends a pong message to the other peer.
-   *
-   * @param {*} data The message to send
-   * @param {Boolean} mask Specifies whether or not to mask `data`
-   * @param {Function} cb Callback
-   * @public
-   */
-  pong (data, mask, cb) {
-    var readOnly = true;
-
-    if (!Buffer.isBuffer(data)) {
-      if (data instanceof ArrayBuffer) {
-        data = Buffer.from(data);
-      } else if (ArrayBuffer.isView(data)) {
-        data = viewToBuffer(data);
-      } else {
-        data = Buffer.from(data);
-        readOnly = false;
-      }
-    }
-
-    if (this._deflating) {
-      this.enqueue([this.doPong, data, mask, readOnly, cb]);
-    } else {
-      this.doPong(data, mask, readOnly, cb);
-    }
-  }
-
-  /**
-   * Frames and sends a pong message.
-   *
-   * @param {*} data The message to send
-   * @param {Boolean} mask Specifies whether or not to mask `data`
-   * @param {Boolean} readOnly Specifies whether `data` can be modified
-   * @param {Function} cb Callback
-   * @private
-   */
-  doPong (data, mask, readOnly, cb) {
-    this.sendFrame(Sender.frame(data, {
-      fin: true,
-      rsv1: false,
-      opcode: 0x0a,
-      mask,
-      readOnly
-    }), cb);
-  }
-
-  /**
-   * Sends a data message to the other peer.
-   *
-   * @param {*} data The message to send
-   * @param {Object} options Options object
-   * @param {Boolean} options.compress Specifies whether or not to compress `data`
-   * @param {Boolean} options.binary Specifies whether `data` is binary or text
-   * @param {Boolean} options.fin Specifies whether the fragment is the last one
-   * @param {Boolean} options.mask Specifies whether or not to mask `data`
-   * @param {Function} cb Callback
-   * @public
-   */
-  send (data, options, cb) {
-    var opcode = options.binary ? 2 : 1;
-    var rsv1 = options.compress;
-    var readOnly = true;
-
-    if (!Buffer.isBuffer(data)) {
-      if (data instanceof ArrayBuffer) {
-        data = Buffer.from(data);
-      } else if (ArrayBuffer.isView(data)) {
-        data = viewToBuffer(data);
-      } else {
-        data = Buffer.from(data);
-        readOnly = false;
-      }
-    }
-
-    const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
-
-    if (this._firstFragment) {
-      this._firstFragment = false;
-      if (rsv1 && perMessageDeflate) {
-        rsv1 = data.length >= perMessageDeflate._threshold;
-      }
-      this._compress = rsv1;
-    } else {
-      rsv1 = false;
-      opcode = 0;
-    }
-
-    if (options.fin) this._firstFragment = true;
-
-    if (perMessageDeflate) {
-      const opts = {
-        fin: options.fin,
-        rsv1,
-        opcode,
-        mask: options.mask,
-        readOnly
-      };
-
-      if (this._deflating) {
-        this.enqueue([this.dispatch, data, this._compress, opts, cb]);
-      } else {
-        this.dispatch(data, this._compress, opts, cb);
-      }
-    } else {
-      this.sendFrame(Sender.frame(data, {
-        fin: options.fin,
-        rsv1: false,
-        opcode,
-        mask: options.mask,
-        readOnly
-      }), cb);
-    }
-  }
-
-  /**
-   * Dispatches a data message.
-   *
-   * @param {Buffer} data The message to send
-   * @param {Boolean} compress Specifies whether or not to compress `data`
-   * @param {Object} options Options object
-   * @param {Number} options.opcode The opcode
-   * @param {Boolean} options.readOnly Specifies whether `data` can be modified
-   * @param {Boolean} options.fin Specifies whether or not to set the FIN bit
-   * @param {Boolean} options.mask Specifies whether or not to mask `data`
-   * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit
-   * @param {Function} cb Callback
-   * @private
-   */
-  dispatch (data, compress, options, cb) {
-    if (!compress) {
-      this.sendFrame(Sender.frame(data, options), cb);
-      return;
-    }
-
-    const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
-
-    this._deflating = true;
-    perMessageDeflate.compress(data, options.fin, (_, buf) => {
-      options.readOnly = false;
-      this.sendFrame(Sender.frame(buf, options), cb);
-      this._deflating = false;
-      this.dequeue();
-    });
-  }
-
-  /**
-   * Executes queued send operations.
-   *
-   * @private
-   */
-  dequeue () {
-    while (!this._deflating && this._queue.length) {
-      const params = this._queue.shift();
-
-      this._bufferedBytes -= params[1].length;
-      params[0].apply(this, params.slice(1));
-    }
-  }
-
-  /**
-   * Enqueues a send operation.
-   *
-   * @param {Array} params Send operation parameters.
-   * @private
-   */
-  enqueue (params) {
-    this._bufferedBytes += params[1].length;
-    this._queue.push(params);
-  }
-
-  /**
-   * Sends a frame.
-   *
-   * @param {Buffer[]} list The frame to send
-   * @param {Function} cb Callback
-   * @private
-   */
-  sendFrame (list, cb) {
-    if (list.length === 2) {
-      this._socket.write(list[0]);
-      this._socket.write(list[1], cb);
-    } else {
-      this._socket.write(list[0], cb);
-    }
-  }
-}
-
-module.exports = Sender;
-
-/**
- * Converts an `ArrayBuffer` view into a buffer.
- *
- * @param {(DataView|TypedArray)} view The view to convert
- * @return {Buffer} Converted view
- * @private
- */
-function viewToBuffer (view) {
-  const buf = Buffer.from(view.buffer);
-
-  if (view.byteLength !== view.buffer.byteLength) {
-    return buf.slice(view.byteOffset, view.byteOffset + view.byteLength);
-  }
-
-  return buf;
-}
+"use strict";const crypto=require("crypto"),PerMessageDeflate=require("./permessage-deflate"),bufferUtil=require("./buffer-util"),validation=require("./validation"),constants=require("./constants");class Sender{constructor(e,t){this._extensions=t||{},this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._deflating=!1,this._queue=[]}static frame(e,t){const s=e.length<1024||t.mask&&t.readOnly;var r=t.mask?6:2,i=e.length;e.length>=65536?(r+=8,i=127):e.length>125&&(r+=2,i=126);const f=Buffer.allocUnsafe(s?e.length+r:r);if(f[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(f[0]|=64),126===i?f.writeUInt16BE(e.length,2):127===i&&(f.writeUInt32BE(0,2),f.writeUInt32BE(e.length,6)),!t.mask)return f[1]=i,s?(e.copy(f,r),[f]):[f,e];const n=crypto.randomBytes(4);return f[1]=128|i,f[r-4]=n[0],f[r-3]=n[1],f[r-2]=n[2],f[r-1]=n[3],s?(bufferUtil.mask(e,n,f,r,e.length),[f]):(bufferUtil.mask(e,n,e,0,e.length),[f,e])}close(e,t,s,r){var i;if(void 0===e)i=constants.EMPTY_BUFFER;else{if("number"!=typeof e||!validation.isValidStatusCode(e))throw new TypeError("First argument must be a valid error code number");void 0===t||""===t?(i=Buffer.allocUnsafe(2)).writeUInt16BE(e,0):((i=Buffer.allocUnsafe(2+Buffer.byteLength(t))).writeUInt16BE(e,0),i.write(t,2))}this._deflating?this.enqueue([this.doClose,i,s,r]):this.doClose(i,s,r)}doClose(e,t,s){this.sendFrame(Sender.frame(e,{fin:!0,rsv1:!1,opcode:8,mask:t,readOnly:!1}),s)}ping(e,t,s){var r=!0;Buffer.isBuffer(e)||(e instanceof ArrayBuffer?e=Buffer.from(e):ArrayBuffer.isView(e)?e=viewToBuffer(e):(e=Buffer.from(e),r=!1)),this._deflating?this.enqueue([this.doPing,e,t,r,s]):this.doPing(e,t,r,s)}doPing(e,t,s,r){this.sendFrame(Sender.frame(e,{fin:!0,rsv1:!1,opcode:9,mask:t,readOnly:s}),r)}pong(e,t,s){var r=!0;Buffer.isBuffer(e)||(e instanceof ArrayBuffer?e=Buffer.from(e):ArrayBuffer.isView(e)?e=viewToBuffer(e):(e=Buffer.from(e),r=!1)),this._deflating?this.enqueue([this.doPong,e,t,r,s]):this.doPong(e,t,r,s)}doPong(e,t,s,r){this.sendFrame(Sender.frame(e,{fin:!0,rsv1:!1,opcode:10,mask:t,readOnly:s}),r)}send(e,t,s){var r=t.binary?2:1,i=t.compress,f=!0;Buffer.isBuffer(e)||(e instanceof ArrayBuffer?e=Buffer.from(e):ArrayBuffer.isView(e)?e=viewToBuffer(e):(e=Buffer.from(e),f=!1));const n=this._extensions[PerMessageDeflate.extensionName];if(this._firstFragment?(this._firstFragment=!1,i&&n&&(i=e.length>=n._threshold),this._compress=i):(i=!1,r=0),t.fin&&(this._firstFragment=!0),n){const n={fin:t.fin,rsv1:i,opcode:r,mask:t.mask,readOnly:f};this._deflating?this.enqueue([this.dispatch,e,this._compress,n,s]):this.dispatch(e,this._compress,n,s)}else this.sendFrame(Sender.frame(e,{fin:t.fin,rsv1:!1,opcode:r,mask:t.mask,readOnly:f}),s)}dispatch(e,t,s,r){if(!t)return void this.sendFrame(Sender.frame(e,s),r);const i=this._extensions[PerMessageDeflate.extensionName];this._deflating=!0,i.compress(e,s.fin,((e,t)=>{s.readOnly=!1,this.sendFrame(Sender.frame(t,s),r),this._deflating=!1,this.dequeue()}))}dequeue(){for(;!this._deflating&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[1].length,e[0].apply(this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[1].length,this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.write(e[0]),this._socket.write(e[1],t)):this._socket.write(e[0],t)}}function viewToBuffer(e){const t=Buffer.from(e.buffer);return e.byteLength!==e.buffer.byteLength?t.slice(e.byteOffset,e.byteOffset+e.byteLength):t}module.exports=Sender;
\ No newline at end of file
index 06269fc..968ec65 100755 (executable)
@@ -1,29 +1 @@
-'use strict';
-
-try {
-  const isValidUTF8 = require('utf-8-validate');
-
-  exports.isValidUTF8 = typeof isValidUTF8 === 'object'
-    ? isValidUTF8.Validation.isValidUTF8 // utf-8-validate@<3.0.0
-    : isValidUTF8;
-} catch (e) /* istanbul ignore next */ {
-  exports.isValidUTF8 = () => true;
-}
-
-/**
- * Checks if a status code is allowed in a close frame.
- *
- * @param {Number} code The status code
- * @return {Boolean} `true` if the status code is valid, else `false`
- * @public
- */
-exports.isValidStatusCode = (code) => {
-  return (
-    (code >= 1000 &&
-      code <= 1013 &&
-      code !== 1004 &&
-      code !== 1005 &&
-      code !== 1006) ||
-    (code >= 3000 && code <= 4999)
-  );
-};
+"use strict";try{const t=require("utf-8-validate");exports.isValidUTF8="object"==typeof t?t.Validation.isValidUTF8:t}catch(t){exports.isValidUTF8=()=>!0}exports.isValidStatusCode=t=>t>=1e3&&t<=1013&&1004!==t&&1005!==t&&1006!==t||t>=3e3&&t<=4999;
\ No newline at end of file
index 70513ed..dcdfb60 100755 (executable)
@@ -1,357 +1 @@
-'use strict';
-
-const EventEmitter = require('events');
-const crypto = require('crypto');
-const http = require('http');
-const url = require('url');
-
-const PerMessageDeflate = require('./permessage-deflate');
-const extension = require('./extension');
-const constants = require('./constants');
-const WebSocket = require('./websocket');
-
-/**
- * Class representing a WebSocket server.
- *
- * @extends EventEmitter
- */
-class WebSocketServer extends EventEmitter {
-  /**
-   * Create a `WebSocketServer` instance.
-   *
-   * @param {Object} options Configuration options
-   * @param {String} options.host The hostname where to bind the server
-   * @param {Number} options.port The port where to bind the server
-   * @param {http.Server} options.server A pre-created HTTP/S server to use
-   * @param {Function} options.verifyClient An hook to reject connections
-   * @param {Function} options.handleProtocols An hook to handle protocols
-   * @param {String} options.path Accept only connections matching this path
-   * @param {Boolean} options.noServer Enable no server mode
-   * @param {Boolean} options.clientTracking Specifies whether or not to track clients
-   * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable permessage-deflate
-   * @param {Number} options.maxPayload The maximum allowed message size
-   * @param {Function} callback A listener for the `listening` event
-   */
-  constructor (options, callback) {
-    super();
-
-    options = Object.assign({
-      maxPayload: 100 * 1024 * 1024,
-      perMessageDeflate: false,
-      handleProtocols: null,
-      clientTracking: true,
-      verifyClient: null,
-      noServer: false,
-      backlog: null, // use default (511 as implemented in net.js)
-      server: null,
-      host: null,
-      path: null,
-      port: null
-    }, options);
-
-    if (options.port == null && !options.server && !options.noServer) {
-      throw new TypeError(
-        'One of the "port", "server", or "noServer" options must be specified'
-      );
-    }
-
-    if (options.port != null) {
-      this._server = http.createServer((req, res) => {
-        const body = http.STATUS_CODES[426];
-
-        res.writeHead(426, {
-          'Content-Length': body.length,
-          'Content-Type': 'text/plain'
-        });
-        res.end(body);
-      });
-      this._server.listen(options.port, options.host, options.backlog, callback);
-    } else if (options.server) {
-      this._server = options.server;
-    }
-
-    if (this._server) {
-      this._removeListeners = addListeners(this._server, {
-        listening: this.emit.bind(this, 'listening'),
-        error: this.emit.bind(this, 'error'),
-        upgrade: (req, socket, head) => {
-          this.handleUpgrade(req, socket, head, (ws) => {
-            this.emit('connection', ws, req);
-          });
-        }
-      });
-    }
-
-    if (options.perMessageDeflate === true) options.perMessageDeflate = {};
-    if (options.clientTracking) this.clients = new Set();
-    this.options = options;
-  }
-
-  /**
-   * Returns the bound address, the address family name, and port of the server
-   * as reported by the operating system if listening on an IP socket.
-   * If the server is listening on a pipe or UNIX domain socket, the name is
-   * returned as a string.
-   *
-   * @return {(Object|String|null)} The address of the server
-   * @public
-   */
-  address () {
-    if (this.options.noServer) {
-      throw new Error('The server is operating in "noServer" mode');
-    }
-
-    if (!this._server) return null;
-    return this._server.address();
-  }
-
-  /**
-   * Close the server.
-   *
-   * @param {Function} cb Callback
-   * @public
-   */
-  close (cb) {
-    //
-    // Terminate all associated clients.
-    //
-    if (this.clients) {
-      for (const client of this.clients) client.terminate();
-    }
-
-    const server = this._server;
-
-    if (server) {
-      this._removeListeners();
-      this._removeListeners = this._server = null;
-
-      //
-      // Close the http server if it was internally created.
-      //
-      if (this.options.port != null) return server.close(cb);
-    }
-
-    if (cb) cb();
-  }
-
-  /**
-   * See if a given request should be handled by this server instance.
-   *
-   * @param {http.IncomingMessage} req Request object to inspect
-   * @return {Boolean} `true` if the request is valid, else `false`
-   * @public
-   */
-  shouldHandle (req) {
-    if (this.options.path && url.parse(req.url).pathname !== this.options.path) {
-      return false;
-    }
-
-    return true;
-  }
-
-  /**
-   * Handle a HTTP Upgrade request.
-   *
-   * @param {http.IncomingMessage} req The request object
-   * @param {net.Socket} socket The network socket between the server and client
-   * @param {Buffer} head The first packet of the upgraded stream
-   * @param {Function} cb Callback
-   * @public
-   */
-  handleUpgrade (req, socket, head, cb) {
-    socket.on('error', socketOnError);
-
-    const version = +req.headers['sec-websocket-version'];
-    const extensions = {};
-
-    if (
-      req.method !== 'GET' || req.headers.upgrade.toLowerCase() !== 'websocket' ||
-      !req.headers['sec-websocket-key'] || (version !== 8 && version !== 13) ||
-      !this.shouldHandle(req)
-    ) {
-      return abortHandshake(socket, 400);
-    }
-
-    if (this.options.perMessageDeflate) {
-      const perMessageDeflate = new PerMessageDeflate(
-        this.options.perMessageDeflate,
-        true,
-        this.options.maxPayload
-      );
-
-      try {
-        const offers = extension.parse(
-          req.headers['sec-websocket-extensions']
-        );
-
-        if (offers[PerMessageDeflate.extensionName]) {
-          perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
-          extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
-        }
-      } catch (err) {
-        return abortHandshake(socket, 400);
-      }
-    }
-
-    //
-    // Optionally call external client verification handler.
-    //
-    if (this.options.verifyClient) {
-      const info = {
-        origin: req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
-        secure: !!(req.connection.authorized || req.connection.encrypted),
-        req
-      };
-
-      if (this.options.verifyClient.length === 2) {
-        this.options.verifyClient(info, (verified, code, message, headers) => {
-          if (!verified) {
-            return abortHandshake(socket, code || 401, message, headers);
-          }
-
-          this.completeUpgrade(extensions, req, socket, head, cb);
-        });
-        return;
-      }
-
-      if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
-    }
-
-    this.completeUpgrade(extensions, req, socket, head, cb);
-  }
-
-  /**
-   * Upgrade the connection to WebSocket.
-   *
-   * @param {Object} extensions The accepted extensions
-   * @param {http.IncomingMessage} req The request object
-   * @param {net.Socket} socket The network socket between the server and client
-   * @param {Buffer} head The first packet of the upgraded stream
-   * @param {Function} cb Callback
-   * @private
-   */
-  completeUpgrade (extensions, req, socket, head, cb) {
-    //
-    // Destroy the socket if the client has already sent a FIN packet.
-    //
-    if (!socket.readable || !socket.writable) return socket.destroy();
-
-    const key = crypto.createHash('sha1')
-      .update(req.headers['sec-websocket-key'] + constants.GUID, 'binary')
-      .digest('base64');
-
-    const headers = [
-      'HTTP/1.1 101 Switching Protocols',
-      'Upgrade: websocket',
-      'Connection: Upgrade',
-      `Sec-WebSocket-Accept: ${key}`
-    ];
-
-    const ws = new WebSocket(null);
-    var protocol = req.headers['sec-websocket-protocol'];
-
-    if (protocol) {
-      protocol = protocol.trim().split(/ *, */);
-
-      //
-      // Optionally call external protocol selection handler.
-      //
-      if (this.options.handleProtocols) {
-        protocol = this.options.handleProtocols(protocol, req);
-      } else {
-        protocol = protocol[0];
-      }
-
-      if (protocol) {
-        headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
-        ws.protocol = protocol;
-      }
-    }
-
-    if (extensions[PerMessageDeflate.extensionName]) {
-      const params = extensions[PerMessageDeflate.extensionName].params;
-      const value = extension.format({
-        [PerMessageDeflate.extensionName]: [params]
-      });
-      headers.push(`Sec-WebSocket-Extensions: ${value}`);
-      ws._extensions = extensions;
-    }
-
-    //
-    // Allow external modification/inspection of handshake headers.
-    //
-    this.emit('headers', headers, req);
-
-    socket.write(headers.concat('\r\n').join('\r\n'));
-    socket.removeListener('error', socketOnError);
-
-    ws.setSocket(socket, head, this.options.maxPayload);
-
-    if (this.clients) {
-      this.clients.add(ws);
-      ws.on('close', () => this.clients.delete(ws));
-    }
-
-    cb(ws);
-  }
-}
-
-module.exports = WebSocketServer;
-
-/**
- * Add event listeners on an `EventEmitter` using a map of <event, listener>
- * pairs.
- *
- * @param {EventEmitter} server The event emitter
- * @param {Object.<String, Function>} map The listeners to add
- * @return {Function} A function that will remove the added listeners when called
- * @private
- */
-function addListeners (server, map) {
-  for (const event of Object.keys(map)) server.on(event, map[event]);
-
-  return function removeListeners () {
-    for (const event of Object.keys(map)) {
-      server.removeListener(event, map[event]);
-    }
-  };
-}
-
-/**
- * Handle premature socket errors.
- *
- * @private
- */
-function socketOnError () {
-  this.destroy();
-}
-
-/**
- * Close the connection when preconditions are not fulfilled.
- *
- * @param {net.Socket} socket The socket of the upgrade request
- * @param {Number} code The HTTP response status code
- * @param {String} [message] The HTTP response body
- * @param {Object} [headers] Additional HTTP response headers
- * @private
- */
-function abortHandshake (socket, code, message, headers) {
-  if (socket.writable) {
-    message = message || http.STATUS_CODES[code];
-    headers = Object.assign({
-      'Connection': 'close',
-      'Content-type': 'text/html',
-      'Content-Length': Buffer.byteLength(message)
-    }, headers);
-
-    socket.write(
-      `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` +
-      Object.keys(headers).map(h => `${h}: ${headers[h]}`).join('\r\n') +
-      '\r\n\r\n' +
-      message
-    );
-  }
-
-  socket.removeListener('error', socketOnError);
-  socket.destroy();
-}
+"use strict";const EventEmitter=require("events"),crypto=require("crypto"),http=require("http"),url=require("url"),PerMessageDeflate=require("./permessage-deflate"),extension=require("./extension"),constants=require("./constants"),WebSocket=require("./websocket");class WebSocketServer extends EventEmitter{constructor(e,t){if(super(),null==(e=Object.assign({maxPayload:104857600,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null},e)).port&&!e.server&&!e.noServer)throw new TypeError('One of the "port", "server", or "noServer" options must be specified');null!=e.port?(this._server=http.createServer(((e,t)=>{const r=http.STATUS_CODES[426];t.writeHead(426,{"Content-Length":r.length,"Content-Type":"text/plain"}),t.end(r)})),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server&&(this._removeListeners=addListeners(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(e,t,r)=>{this.handleUpgrade(e,t,r,(t=>{this.emit("connection",t,e)}))}})),!0===e.perMessageDeflate&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set),this.options=e}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this.clients)for(const e of this.clients)e.terminate();const t=this._server;if(t&&(this._removeListeners(),this._removeListeners=this._server=null,null!=this.options.port))return t.close(e);e&&e()}shouldHandle(e){return!this.options.path||url.parse(e.url).pathname===this.options.path}handleUpgrade(e,t,r,s){t.on("error",socketOnError);const n=+e.headers["sec-websocket-version"],o={};if("GET"!==e.method||"websocket"!==e.headers.upgrade.toLowerCase()||!e.headers["sec-websocket-key"]||8!==n&&13!==n||!this.shouldHandle(e))return abortHandshake(t,400);if(this.options.perMessageDeflate){const r=new PerMessageDeflate(this.options.perMessageDeflate,!0,this.options.maxPayload);try{const t=extension.parse(e.headers["sec-websocket-extensions"]);t[PerMessageDeflate.extensionName]&&(r.accept(t[PerMessageDeflate.extensionName]),o[PerMessageDeflate.extensionName]=r)}catch(e){return abortHandshake(t,400)}}if(this.options.verifyClient){const i={origin:e.headers[""+(8===n?"sec-websocket-origin":"origin")],secure:!(!e.connection.authorized&&!e.connection.encrypted),req:e};if(2===this.options.verifyClient.length)return void this.options.verifyClient(i,((n,i,a,c)=>{if(!n)return abortHandshake(t,i||401,a,c);this.completeUpgrade(o,e,t,r,s)}));if(!this.options.verifyClient(i))return abortHandshake(t,401)}this.completeUpgrade(o,e,t,r,s)}completeUpgrade(e,t,r,s,n){if(!r.readable||!r.writable)return r.destroy();const o=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${crypto.createHash("sha1").update(t.headers["sec-websocket-key"]+constants.GUID,"binary").digest("base64")}`],i=new WebSocket(null);var a=t.headers["sec-websocket-protocol"];if(a&&(a=a.trim().split(/ *, */),(a=this.options.handleProtocols?this.options.handleProtocols(a,t):a[0])&&(o.push(`Sec-WebSocket-Protocol: ${a}`),i.protocol=a)),e[PerMessageDeflate.extensionName]){const t=e[PerMessageDeflate.extensionName].params,r=extension.format({[PerMessageDeflate.extensionName]:[t]});o.push(`Sec-WebSocket-Extensions: ${r}`),i._extensions=e}this.emit("headers",o,t),r.write(o.concat("\r\n").join("\r\n")),r.removeListener("error",socketOnError),i.setSocket(r,s,this.options.maxPayload),this.clients&&(this.clients.add(i),i.on("close",(()=>this.clients.delete(i)))),n(i)}}function addListeners(e,t){for(const r of Object.keys(t))e.on(r,t[r]);return function(){for(const r of Object.keys(t))e.removeListener(r,t[r])}}function socketOnError(){this.destroy()}function abortHandshake(e,t,r,s){e.writable&&(r=r||http.STATUS_CODES[t],s=Object.assign({Connection:"close","Content-type":"text/html","Content-Length":Buffer.byteLength(r)},s),e.write(`HTTP/1.1 ${t} ${http.STATUS_CODES[t]}\r\n`+Object.keys(s).map((e=>`${e}: ${s[e]}`)).join("\r\n")+"\r\n\r\n"+r)),e.removeListener("error",socketOnError),e.destroy()}module.exports=WebSocketServer;
\ No newline at end of file
index f2bdf0d..d8359a1 100755 (executable)
@@ -1,828 +1 @@
-'use strict';
-
-const EventEmitter = require('events');
-const crypto = require('crypto');
-const https = require('https');
-const http = require('http');
-const net = require('net');
-const tls = require('tls');
-const url = require('url');
-
-const PerMessageDeflate = require('./permessage-deflate');
-const EventTarget = require('./event-target');
-const extension = require('./extension');
-const constants = require('./constants');
-const Receiver = require('./receiver');
-const Sender = require('./sender');
-
-const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];
-const kWebSocket = constants.kWebSocket;
-const protocolVersions = [8, 13];
-const closeTimeout = 30 * 1000; // Allow 30 seconds to terminate the connection cleanly.
-
-/**
- * Class representing a WebSocket.
- *
- * @extends EventEmitter
- */
-class WebSocket extends EventEmitter {
-  /**
-   * Create a new `WebSocket`.
-   *
-   * @param {(String|url.Url|url.URL)} address The URL to which to connect
-   * @param {(String|String[])} protocols The subprotocols
-   * @param {Object} options Connection options
-   */
-  constructor (address, protocols, options) {
-    super();
-
-    this.readyState = WebSocket.CONNECTING;
-    this.protocol = '';
-
-    this._binaryType = constants.BINARY_TYPES[0];
-    this._closeFrameReceived = false;
-    this._closeFrameSent = false;
-    this._closeMessage = '';
-    this._closeTimer = null;
-    this._closeCode = 1006;
-    this._extensions = {};
-    this._isServer = true;
-    this._receiver = null;
-    this._sender = null;
-    this._socket = null;
-
-    if (address !== null) {
-      if (Array.isArray(protocols)) {
-        protocols = protocols.join(', ');
-      } else if (typeof protocols === 'object' && protocols !== null) {
-        options = protocols;
-        protocols = undefined;
-      }
-
-      initAsClient.call(this, address, protocols, options);
-    }
-  }
-
-  get CONNECTING () { return WebSocket.CONNECTING; }
-  get CLOSING () { return WebSocket.CLOSING; }
-  get CLOSED () { return WebSocket.CLOSED; }
-  get OPEN () { return WebSocket.OPEN; }
-
-  /**
-   * This deviates from the WHATWG interface since ws doesn't support the required
-   * default "blob" type (instead we define a custom "nodebuffer" type).
-   *
-   * @type {String}
-   */
-  get binaryType () {
-    return this._binaryType;
-  }
-
-  set binaryType (type) {
-    if (constants.BINARY_TYPES.indexOf(type) < 0) return;
-
-    this._binaryType = type;
-
-    //
-    // Allow to change `binaryType` on the fly.
-    //
-    if (this._receiver) this._receiver._binaryType = type;
-  }
-
-  /**
-   * @type {Number}
-   */
-  get bufferedAmount () {
-    if (!this._socket) return 0;
-
-    //
-    // `socket.bufferSize` is `undefined` if the socket is closed.
-    //
-    return (this._socket.bufferSize || 0) + this._sender._bufferedBytes;
-  }
-
-  /**
-   * @type {String}
-   */
-  get extensions () {
-    return Object.keys(this._extensions).join();
-  }
-
-  /**
-   * Set up the socket and the internal resources.
-   *
-   * @param {net.Socket} socket The network socket between the server and client
-   * @param {Buffer} head The first packet of the upgraded stream
-   * @param {Number} maxPayload The maximum allowed message size
-   * @private
-   */
-  setSocket (socket, head, maxPayload) {
-    const receiver = new Receiver(
-      this._binaryType,
-      this._extensions,
-      maxPayload
-    );
-
-    this._sender = new Sender(socket, this._extensions);
-    this._receiver = receiver;
-    this._socket = socket;
-
-    receiver[kWebSocket] = this;
-    socket[kWebSocket] = this;
-
-    receiver.on('conclude', receiverOnConclude);
-    receiver.on('drain', receiverOnDrain);
-    receiver.on('error', receiverOnError);
-    receiver.on('message', receiverOnMessage);
-    receiver.on('ping', receiverOnPing);
-    receiver.on('pong', receiverOnPong);
-
-    socket.setTimeout(0);
-    socket.setNoDelay();
-
-    if (head.length > 0) socket.unshift(head);
-
-    socket.on('close', socketOnClose);
-    socket.on('data', socketOnData);
-    socket.on('end', socketOnEnd);
-    socket.on('error', socketOnError);
-
-    this.readyState = WebSocket.OPEN;
-    this.emit('open');
-  }
-
-  /**
-   * Emit the `'close'` event.
-   *
-   * @private
-   */
-  emitClose () {
-    this.readyState = WebSocket.CLOSED;
-
-    if (!this._socket) {
-      this.emit('close', this._closeCode, this._closeMessage);
-      return;
-    }
-
-    if (this._extensions[PerMessageDeflate.extensionName]) {
-      this._extensions[PerMessageDeflate.extensionName].cleanup();
-    }
-
-    this._receiver.removeAllListeners();
-    this.emit('close', this._closeCode, this._closeMessage);
-  }
-
-  /**
-   * Start a closing handshake.
-   *
-   *          +----------+   +-----------+   +----------+
-   *     - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
-   *    |     +----------+   +-----------+   +----------+     |
-   *          +----------+   +-----------+         |
-   * CLOSING  |ws.close()|<--|close frame|<--+-----+       CLOSING
-   *          +----------+   +-----------+   |
-   *    |           |                        |   +---+        |
-   *                +------------------------+-->|fin| - - - -
-   *    |         +---+                      |   +---+
-   *     - - - - -|fin|<---------------------+
-   *              +---+
-   *
-   * @param {Number} code Status code explaining why the connection is closing
-   * @param {String} data A string explaining why the connection is closing
-   * @public
-   */
-  close (code, data) {
-    if (this.readyState === WebSocket.CLOSED) return;
-    if (this.readyState === WebSocket.CONNECTING) {
-      const msg = 'WebSocket was closed before the connection was established';
-      return abortHandshake(this, this._req, msg);
-    }
-
-    if (this.readyState === WebSocket.CLOSING) {
-      if (this._closeFrameSent && this._closeFrameReceived) this._socket.end();
-      return;
-    }
-
-    this.readyState = WebSocket.CLOSING;
-    this._sender.close(code, data, !this._isServer, (err) => {
-      //
-      // This error is handled by the `'error'` listener on the socket. We only
-      // want to know if the close frame has been sent here.
-      //
-      if (err) return;
-
-      this._closeFrameSent = true;
-
-      if (this._socket.writable) {
-        if (this._closeFrameReceived) this._socket.end();
-
-        //
-        // Ensure that the connection is closed even if the closing handshake
-        // fails.
-        //
-        this._closeTimer = setTimeout(
-          this._socket.destroy.bind(this._socket),
-          closeTimeout
-        );
-      }
-    });
-  }
-
-  /**
-   * Send a ping.
-   *
-   * @param {*} data The data to send
-   * @param {Boolean} mask Indicates whether or not to mask `data`
-   * @param {Function} cb Callback which is executed when the ping is sent
-   * @public
-   */
-  ping (data, mask, cb) {
-    if (typeof data === 'function') {
-      cb = data;
-      data = mask = undefined;
-    } else if (typeof mask === 'function') {
-      cb = mask;
-      mask = undefined;
-    }
-
-    if (this.readyState !== WebSocket.OPEN) {
-      const err = new Error(
-        `WebSocket is not open: readyState ${this.readyState} ` +
-          `(${readyStates[this.readyState]})`
-      );
-
-      if (cb) return cb(err);
-      throw err;
-    }
-
-    if (typeof data === 'number') data = data.toString();
-    if (mask === undefined) mask = !this._isServer;
-    this._sender.ping(data || constants.EMPTY_BUFFER, mask, cb);
-  }
-
-  /**
-   * Send a pong.
-   *
-   * @param {*} data The data to send
-   * @param {Boolean} mask Indicates whether or not to mask `data`
-   * @param {Function} cb Callback which is executed when the pong is sent
-   * @public
-   */
-  pong (data, mask, cb) {
-    if (typeof data === 'function') {
-      cb = data;
-      data = mask = undefined;
-    } else if (typeof mask === 'function') {
-      cb = mask;
-      mask = undefined;
-    }
-
-    if (this.readyState !== WebSocket.OPEN) {
-      const err = new Error(
-        `WebSocket is not open: readyState ${this.readyState} ` +
-          `(${readyStates[this.readyState]})`
-      );
-
-      if (cb) return cb(err);
-      throw err;
-    }
-
-    if (typeof data === 'number') data = data.toString();
-    if (mask === undefined) mask = !this._isServer;
-    this._sender.pong(data || constants.EMPTY_BUFFER, mask, cb);
-  }
-
-  /**
-   * Send a data message.
-   *
-   * @param {*} data The message to send
-   * @param {Object} options Options object
-   * @param {Boolean} options.compress Specifies whether or not to compress `data`
-   * @param {Boolean} options.binary Specifies whether `data` is binary or text
-   * @param {Boolean} options.fin Specifies whether the fragment is the last one
-   * @param {Boolean} options.mask Specifies whether or not to mask `data`
-   * @param {Function} cb Callback which is executed when data is written out
-   * @public
-   */
-  send (data, options, cb) {
-    if (typeof options === 'function') {
-      cb = options;
-      options = {};
-    }
-
-    if (this.readyState !== WebSocket.OPEN) {
-      const err = new Error(
-        `WebSocket is not open: readyState ${this.readyState} ` +
-          `(${readyStates[this.readyState]})`
-      );
-
-      if (cb) return cb(err);
-      throw err;
-    }
-
-    if (typeof data === 'number') data = data.toString();
-
-    const opts = Object.assign({
-      binary: typeof data !== 'string',
-      mask: !this._isServer,
-      compress: true,
-      fin: true
-    }, options);
-
-    if (!this._extensions[PerMessageDeflate.extensionName]) {
-      opts.compress = false;
-    }
-
-    this._sender.send(data || constants.EMPTY_BUFFER, opts, cb);
-  }
-
-  /**
-   * Forcibly close the connection.
-   *
-   * @public
-   */
-  terminate () {
-    if (this.readyState === WebSocket.CLOSED) return;
-    if (this.readyState === WebSocket.CONNECTING) {
-      const msg = 'WebSocket was closed before the connection was established';
-      return abortHandshake(this, this._req, msg);
-    }
-
-    if (this._socket) {
-      this.readyState = WebSocket.CLOSING;
-      this._socket.destroy();
-    }
-  }
-}
-
-readyStates.forEach((readyState, i) => {
-  WebSocket[readyStates[i]] = i;
-});
-
-//
-// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.
-// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface
-//
-['open', 'error', 'close', 'message'].forEach((method) => {
-  Object.defineProperty(WebSocket.prototype, `on${method}`, {
-    /**
-     * Return the listener of the event.
-     *
-     * @return {(Function|undefined)} The event listener or `undefined`
-     * @public
-     */
-    get () {
-      const listeners = this.listeners(method);
-      for (var i = 0; i < listeners.length; i++) {
-        if (listeners[i]._listener) return listeners[i]._listener;
-      }
-    },
-    /**
-     * Add a listener for the event.
-     *
-     * @param {Function} listener The listener to add
-     * @public
-     */
-    set (listener) {
-      const listeners = this.listeners(method);
-      for (var i = 0; i < listeners.length; i++) {
-        //
-        // Remove only the listeners added via `addEventListener`.
-        //
-        if (listeners[i]._listener) this.removeListener(method, listeners[i]);
-      }
-      this.addEventListener(method, listener);
-    }
-  });
-});
-
-WebSocket.prototype.addEventListener = EventTarget.addEventListener;
-WebSocket.prototype.removeEventListener = EventTarget.removeEventListener;
-
-module.exports = WebSocket;
-
-/**
- * Initialize a WebSocket client.
- *
- * @param {(String|url.Url|url.URL)} address The URL to which to connect
- * @param {String} protocols The subprotocols
- * @param {Object} options Connection options
- * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable permessage-deflate
- * @param {Number} options.handshakeTimeout Timeout in milliseconds for the handshake request
- * @param {Number} options.protocolVersion Value of the `Sec-WebSocket-Version` header
- * @param {String} options.origin Value of the `Origin` or `Sec-WebSocket-Origin` header
- * @private
- */
-function initAsClient (address, protocols, options) {
-  options = Object.assign({
-    protocolVersion: protocolVersions[1],
-    perMessageDeflate: true
-  }, options, {
-    createConnection: undefined,
-    socketPath: undefined,
-    hostname: undefined,
-    protocol: undefined,
-    timeout: undefined,
-    method: undefined,
-    auth: undefined,
-    host: undefined,
-    path: undefined,
-    port: undefined
-  });
-
-  if (protocolVersions.indexOf(options.protocolVersion) === -1) {
-    throw new RangeError(
-      `Unsupported protocol version: ${options.protocolVersion} ` +
-        `(supported versions: ${protocolVersions.join(', ')})`
-    );
-  }
-
-  this._isServer = false;
-
-  var parsedUrl;
-
-  if (typeof address === 'object' && address.href !== undefined) {
-    parsedUrl = address;
-    this.url = address.href;
-  } else {
-    parsedUrl = url.parse(address);
-    this.url = address;
-  }
-
-  const isUnixSocket = parsedUrl.protocol === 'ws+unix:';
-
-  if (!parsedUrl.host && (!isUnixSocket || !parsedUrl.pathname)) {
-    throw new Error(`Invalid URL: ${this.url}`);
-  }
-
-  const isSecure = parsedUrl.protocol === 'wss:' || parsedUrl.protocol === 'https:';
-  const key = crypto.randomBytes(16).toString('base64');
-  const httpObj = isSecure ? https : http;
-  const path = parsedUrl.search
-    ? `${parsedUrl.pathname || '/'}${parsedUrl.search}`
-    : parsedUrl.pathname || '/';
-  var perMessageDeflate;
-
-  options.createConnection = isSecure ? tlsConnect : netConnect;
-  options.port = parsedUrl.port || (isSecure ? 443 : 80);
-  options.host = parsedUrl.hostname.startsWith('[')
-    ? parsedUrl.hostname.slice(1, -1)
-    : parsedUrl.hostname;
-  options.headers = Object.assign({
-    'Sec-WebSocket-Version': options.protocolVersion,
-    'Sec-WebSocket-Key': key,
-    'Connection': 'Upgrade',
-    'Upgrade': 'websocket'
-  }, options.headers);
-  options.path = path;
-
-  if (options.perMessageDeflate) {
-    perMessageDeflate = new PerMessageDeflate(
-      options.perMessageDeflate !== true ? options.perMessageDeflate : {},
-      false
-    );
-    options.headers['Sec-WebSocket-Extensions'] = extension.format({
-      [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
-    });
-  }
-  if (protocols) {
-    options.headers['Sec-WebSocket-Protocol'] = protocols;
-  }
-  if (options.origin) {
-    if (options.protocolVersion < 13) {
-      options.headers['Sec-WebSocket-Origin'] = options.origin;
-    } else {
-      options.headers.Origin = options.origin;
-    }
-  }
-  if (parsedUrl.auth) {
-    options.auth = parsedUrl.auth;
-  } else if (parsedUrl.username || parsedUrl.password) {
-    options.auth = `${parsedUrl.username}:${parsedUrl.password}`;
-  }
-
-  if (isUnixSocket) {
-    const parts = path.split(':');
-
-    if (options.agent == null && process.versions.modules < 57) {
-      //
-      // Setting `socketPath` in conjunction with `createConnection` without an
-      // agent throws an error on Node.js < 8. Work around the issue by using a
-      // different property.
-      //
-      options._socketPath = parts[0];
-    } else {
-      options.socketPath = parts[0];
-    }
-
-    options.path = parts[1];
-  }
-
-  var req = this._req = httpObj.get(options);
-
-  if (options.handshakeTimeout) {
-    req.setTimeout(
-      options.handshakeTimeout,
-      () => abortHandshake(this, req, 'Opening handshake has timed out')
-    );
-  }
-
-  req.on('error', (err) => {
-    if (this._req.aborted) return;
-
-    req = this._req = null;
-    this.readyState = WebSocket.CLOSING;
-    this.emit('error', err);
-    this.emitClose();
-  });
-
-  req.on('response', (res) => {
-    if (this.emit('unexpected-response', req, res)) return;
-
-    abortHandshake(this, req, `Unexpected server response: ${res.statusCode}`);
-  });
-
-  req.on('upgrade', (res, socket, head) => {
-    this.emit('upgrade', res);
-
-    //
-    // The user may have closed the connection from a listener of the `upgrade`
-    // event.
-    //
-    if (this.readyState !== WebSocket.CONNECTING) return;
-
-    req = this._req = null;
-
-    const digest = crypto.createHash('sha1')
-      .update(key + constants.GUID, 'binary')
-      .digest('base64');
-
-    if (res.headers['sec-websocket-accept'] !== digest) {
-      abortHandshake(this, socket, 'Invalid Sec-WebSocket-Accept header');
-      return;
-    }
-
-    const serverProt = res.headers['sec-websocket-protocol'];
-    const protList = (protocols || '').split(/, */);
-    var protError;
-
-    if (!protocols && serverProt) {
-      protError = 'Server sent a subprotocol but none was requested';
-    } else if (protocols && !serverProt) {
-      protError = 'Server sent no subprotocol';
-    } else if (serverProt && protList.indexOf(serverProt) === -1) {
-      protError = 'Server sent an invalid subprotocol';
-    }
-
-    if (protError) {
-      abortHandshake(this, socket, protError);
-      return;
-    }
-
-    if (serverProt) this.protocol = serverProt;
-
-    if (perMessageDeflate) {
-      try {
-        const extensions = extension.parse(
-          res.headers['sec-websocket-extensions']
-        );
-
-        if (extensions[PerMessageDeflate.extensionName]) {
-          perMessageDeflate.accept(
-            extensions[PerMessageDeflate.extensionName]
-          );
-          this._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
-        }
-      } catch (err) {
-        abortHandshake(this, socket, 'Invalid Sec-WebSocket-Extensions header');
-        return;
-      }
-    }
-
-    this.setSocket(socket, head, 0);
-  });
-}
-
-/**
- * Create a `net.Socket` and initiate a connection.
- *
- * @param {Object} options Connection options
- * @return {net.Socket} The newly created socket used to start the connection
- * @private
- */
-function netConnect (options) {
-  options.path = options.socketPath || options._socketPath || undefined;
-  return net.connect(options);
-}
-
-/**
- * Create a `tls.TLSSocket` and initiate a connection.
- *
- * @param {Object} options Connection options
- * @return {tls.TLSSocket} The newly created socket used to start the connection
- * @private
- */
-function tlsConnect (options) {
-  options.path = options.socketPath || options._socketPath || undefined;
-  options.servername = options.servername || options.host;
-  return tls.connect(options);
-}
-
-/**
- * Abort the handshake and emit an error.
- *
- * @param {WebSocket} websocket The WebSocket instance
- * @param {(http.ClientRequest|net.Socket)} stream The request to abort or the
- *     socket to destroy
- * @param {String} message The error message
- * @private
- */
-function abortHandshake (websocket, stream, message) {
-  websocket.readyState = WebSocket.CLOSING;
-
-  const err = new Error(message);
-  Error.captureStackTrace(err, abortHandshake);
-
-  if (stream.setHeader) {
-    stream.abort();
-    stream.once('abort', websocket.emitClose.bind(websocket));
-    websocket.emit('error', err);
-  } else {
-    stream.destroy(err);
-    stream.once('error', websocket.emit.bind(websocket, 'error'));
-    stream.once('close', websocket.emitClose.bind(websocket));
-  }
-}
-
-/**
- * The listener of the `Receiver` `'conclude'` event.
- *
- * @param {Number} code The status code
- * @param {String} reason The reason for closing
- * @private
- */
-function receiverOnConclude (code, reason) {
-  const websocket = this[kWebSocket];
-
-  websocket._socket.removeListener('data', socketOnData);
-  websocket._socket.resume();
-
-  websocket._closeFrameReceived = true;
-  websocket._closeMessage = reason;
-  websocket._closeCode = code;
-
-  if (code === 1005) websocket.close();
-  else websocket.close(code, reason);
-}
-
-/**
- * The listener of the `Receiver` `'drain'` event.
- *
- * @private
- */
-function receiverOnDrain () {
-  this[kWebSocket]._socket.resume();
-}
-
-/**
- * The listener of the `Receiver` `'error'` event.
- *
- * @param {(RangeError|Error)} err The emitted error
- * @private
- */
-function receiverOnError (err) {
-  const websocket = this[kWebSocket];
-
-  websocket._socket.removeListener('data', socketOnData);
-
-  websocket.readyState = WebSocket.CLOSING;
-  websocket._closeCode = err[constants.kStatusCode];
-  websocket.emit('error', err);
-  websocket._socket.destroy();
-}
-
-/**
- * The listener of the `Receiver` `'finish'` event.
- *
- * @private
- */
-function receiverOnFinish () {
-  this[kWebSocket].emitClose();
-}
-
-/**
- * The listener of the `Receiver` `'message'` event.
- *
- * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The message
- * @private
- */
-function receiverOnMessage (data) {
-  this[kWebSocket].emit('message', data);
-}
-
-/**
- * The listener of the `Receiver` `'ping'` event.
- *
- * @param {Buffer} data The data included in the ping frame
- * @private
- */
-function receiverOnPing (data) {
-  const websocket = this[kWebSocket];
-
-  websocket.pong(data, !websocket._isServer, constants.NOOP);
-  websocket.emit('ping', data);
-}
-
-/**
- * The listener of the `Receiver` `'pong'` event.
- *
- * @param {Buffer} data The data included in the pong frame
- * @private
- */
-function receiverOnPong (data) {
-  this[kWebSocket].emit('pong', data);
-}
-
-/**
- * The listener of the `net.Socket` `'close'` event.
- *
- * @private
- */
-function socketOnClose () {
-  const websocket = this[kWebSocket];
-
-  this.removeListener('close', socketOnClose);
-  this.removeListener('end', socketOnEnd);
-
-  websocket.readyState = WebSocket.CLOSING;
-
-  //
-  // The close frame might not have been received or the `'end'` event emitted,
-  // for example, if the socket was destroyed due to an error. Ensure that the
-  // `receiver` stream is closed after writing any remaining buffered data to
-  // it. If the readable side of the socket is in flowing mode then there is no
-  // buffered data as everything has been already written and `readable.read()`
-  // will return `null`. If instead, the socket is paused, any possible buffered
-  // data will be read as a single chunk and emitted synchronously in a single
-  // `'data'` event.
-  //
-  websocket._socket.read();
-  websocket._receiver.end();
-
-  this.removeListener('data', socketOnData);
-  this[kWebSocket] = undefined;
-
-  clearTimeout(websocket._closeTimer);
-
-  if (
-    websocket._receiver._writableState.finished ||
-    websocket._receiver._writableState.errorEmitted
-  ) {
-    websocket.emitClose();
-  } else {
-    websocket._receiver.on('error', receiverOnFinish);
-    websocket._receiver.on('finish', receiverOnFinish);
-  }
-}
-
-/**
- * The listener of the `net.Socket` `'data'` event.
- *
- * @param {Buffer} chunk A chunk of data
- * @private
- */
-function socketOnData (chunk) {
-  if (!this[kWebSocket]._receiver.write(chunk)) {
-    this.pause();
-  }
-}
-
-/**
- * The listener of the `net.Socket` `'end'` event.
- *
- * @private
- */
-function socketOnEnd () {
-  const websocket = this[kWebSocket];
-
-  websocket.readyState = WebSocket.CLOSING;
-  websocket._receiver.end();
-  this.end();
-}
-
-/**
- * The listener of the `net.Socket` `'error'` event.
- *
- * @private
- */
-function socketOnError () {
-  const websocket = this[kWebSocket];
-
-  this.removeListener('error', socketOnError);
-  this.on('error', constants.NOOP);
-
-  if (websocket) {
-    websocket.readyState = WebSocket.CLOSING;
-    this.destroy();
-  }
-}
+"use strict";const EventEmitter=require("events"),crypto=require("crypto"),https=require("https"),http=require("http"),net=require("net"),tls=require("tls"),url=require("url"),PerMessageDeflate=require("./permessage-deflate"),EventTarget=require("./event-target"),extension=require("./extension"),constants=require("./constants"),Receiver=require("./receiver"),Sender=require("./sender"),readyStates=["CONNECTING","OPEN","CLOSING","CLOSED"],kWebSocket=constants.kWebSocket,protocolVersions=[8,13],closeTimeout=3e4;class WebSocket extends EventEmitter{constructor(e,t,s){super(),this.readyState=WebSocket.CONNECTING,this.protocol="",this._binaryType=constants.BINARY_TYPES[0],this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage="",this._closeTimer=null,this._closeCode=1006,this._extensions={},this._isServer=!0,this._receiver=null,this._sender=null,this._socket=null,null!==e&&(Array.isArray(t)?t=t.join(", "):"object"==typeof t&&null!==t&&(s=t,t=void 0),initAsClient.call(this,e,t,s))}get CONNECTING(){return WebSocket.CONNECTING}get CLOSING(){return WebSocket.CLOSING}get CLOSED(){return WebSocket.CLOSED}get OPEN(){return WebSocket.OPEN}get binaryType(){return this._binaryType}set binaryType(e){constants.BINARY_TYPES.indexOf(e)<0||(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?(this._socket.bufferSize||0)+this._sender._bufferedBytes:0}get extensions(){return Object.keys(this._extensions).join()}setSocket(e,t,s){const o=new Receiver(this._binaryType,this._extensions,s);this._sender=new Sender(e,this._extensions),this._receiver=o,this._socket=e,o[kWebSocket]=this,e[kWebSocket]=this,o.on("conclude",receiverOnConclude),o.on("drain",receiverOnDrain),o.on("error",receiverOnError),o.on("message",receiverOnMessage),o.on("ping",receiverOnPing),o.on("pong",receiverOnPong),e.setTimeout(0),e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",socketOnClose),e.on("data",socketOnData),e.on("end",socketOnEnd),e.on("error",socketOnError),this.readyState=WebSocket.OPEN,this.emit("open")}emitClose(){this.readyState=WebSocket.CLOSED,this._socket?(this._extensions[PerMessageDeflate.extensionName]&&this._extensions[PerMessageDeflate.extensionName].cleanup(),this._receiver.removeAllListeners(),this.emit("close",this._closeCode,this._closeMessage)):this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==WebSocket.CLOSED){if(this.readyState===WebSocket.CONNECTING){const e="WebSocket was closed before the connection was established";return abortHandshake(this,this._req,e)}this.readyState!==WebSocket.CLOSING?(this.readyState=WebSocket.CLOSING,this._sender.close(e,t,!this._isServer,(e=>{e||(this._closeFrameSent=!0,this._socket.writable&&(this._closeFrameReceived&&this._socket.end(),this._closeTimer=setTimeout(this._socket.destroy.bind(this._socket),3e4)))}))):this._closeFrameSent&&this._closeFrameReceived&&this._socket.end()}}ping(e,t,s){if("function"==typeof e?(s=e,e=t=void 0):"function"==typeof t&&(s=t,t=void 0),this.readyState!==WebSocket.OPEN){const e=new Error(`WebSocket is not open: readyState ${this.readyState} (${readyStates[this.readyState]})`);if(s)return s(e);throw e}"number"==typeof e&&(e=e.toString()),void 0===t&&(t=!this._isServer),this._sender.ping(e||constants.EMPTY_BUFFER,t,s)}pong(e,t,s){if("function"==typeof e?(s=e,e=t=void 0):"function"==typeof t&&(s=t,t=void 0),this.readyState!==WebSocket.OPEN){const e=new Error(`WebSocket is not open: readyState ${this.readyState} (${readyStates[this.readyState]})`);if(s)return s(e);throw e}"number"==typeof e&&(e=e.toString()),void 0===t&&(t=!this._isServer),this._sender.pong(e||constants.EMPTY_BUFFER,t,s)}send(e,t,s){if("function"==typeof t&&(s=t,t={}),this.readyState!==WebSocket.OPEN){const e=new Error(`WebSocket is not open: readyState ${this.readyState} (${readyStates[this.readyState]})`);if(s)return s(e);throw e}"number"==typeof e&&(e=e.toString());const o=Object.assign({binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0},t);this._extensions[PerMessageDeflate.extensionName]||(o.compress=!1),this._sender.send(e||constants.EMPTY_BUFFER,o,s)}terminate(){if(this.readyState!==WebSocket.CLOSED){if(this.readyState===WebSocket.CONNECTING){const e="WebSocket was closed before the connection was established";return abortHandshake(this,this._req,e)}this._socket&&(this.readyState=WebSocket.CLOSING,this._socket.destroy())}}}function initAsClient(e,t,s){if(s=Object.assign({protocolVersion:protocolVersions[1],perMessageDeflate:!0},s,{createConnection:void 0,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:void 0,auth:void 0,host:void 0,path:void 0,port:void 0}),-1===protocolVersions.indexOf(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`);var o;this._isServer=!1,"object"==typeof e&&void 0!==e.href?(o=e,this.url=e.href):(o=url.parse(e),this.url=e);const r="ws+unix:"===o.protocol;if(!(o.host||r&&o.pathname))throw new Error(`Invalid URL: ${this.url}`);const n="wss:"===o.protocol||"https:"===o.protocol,i=crypto.randomBytes(16).toString("base64"),a=n?https:http,c=o.search?`${o.pathname||"/"}${o.search}`:o.pathname||"/";var h;if(s.createConnection=n?tlsConnect:netConnect,s.port=o.port||(n?443:80),s.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,s.headers=Object.assign({"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":i,Connection:"Upgrade",Upgrade:"websocket"},s.headers),s.path=c,s.perMessageDeflate&&(h=new PerMessageDeflate(!0!==s.perMessageDeflate?s.perMessageDeflate:{},!1),s.headers["Sec-WebSocket-Extensions"]=extension.format({[PerMessageDeflate.extensionName]:h.offer()})),t&&(s.headers["Sec-WebSocket-Protocol"]=t),s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),o.auth?s.auth=o.auth:(o.username||o.password)&&(s.auth=`${o.username}:${o.password}`),r){const e=c.split(":");null==s.agent&&process.versions.modules<57?s._socketPath=e[0]:s.socketPath=e[0],s.path=e[1]}var d=this._req=a.get(s);s.handshakeTimeout&&d.setTimeout(s.handshakeTimeout,(()=>abortHandshake(this,d,"Opening handshake has timed out"))),d.on("error",(e=>{this._req.aborted||(d=this._req=null,this.readyState=WebSocket.CLOSING,this.emit("error",e),this.emitClose())})),d.on("response",(e=>{this.emit("unexpected-response",d,e)||abortHandshake(this,d,`Unexpected server response: ${e.statusCode}`)})),d.on("upgrade",((e,s,o)=>{if(this.emit("upgrade",e),this.readyState!==WebSocket.CONNECTING)return;d=this._req=null;const r=crypto.createHash("sha1").update(i+constants.GUID,"binary").digest("base64");if(e.headers["sec-websocket-accept"]!==r)return void abortHandshake(this,s,"Invalid Sec-WebSocket-Accept header");const n=e.headers["sec-websocket-protocol"],a=(t||"").split(/, */);var c;if(!t&&n?c="Server sent a subprotocol but none was requested":t&&!n?c="Server sent no subprotocol":n&&-1===a.indexOf(n)&&(c="Server sent an invalid subprotocol"),c)abortHandshake(this,s,c);else{if(n&&(this.protocol=n),h)try{const t=extension.parse(e.headers["sec-websocket-extensions"]);t[PerMessageDeflate.extensionName]&&(h.accept(t[PerMessageDeflate.extensionName]),this._extensions[PerMessageDeflate.extensionName]=h)}catch(e){return void abortHandshake(this,s,"Invalid Sec-WebSocket-Extensions header")}this.setSocket(s,o,0)}}))}function netConnect(e){return e.path=e.socketPath||e._socketPath||void 0,net.connect(e)}function tlsConnect(e){return e.path=e.socketPath||e._socketPath||void 0,e.servername=e.servername||e.host,tls.connect(e)}function abortHandshake(e,t,s){e.readyState=WebSocket.CLOSING;const o=new Error(s);Error.captureStackTrace(o,abortHandshake),t.setHeader?(t.abort(),t.once("abort",e.emitClose.bind(e)),e.emit("error",o)):(t.destroy(o),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function receiverOnConclude(e,t){const s=this[kWebSocket];s._socket.removeListener("data",socketOnData),s._socket.resume(),s._closeFrameReceived=!0,s._closeMessage=t,s._closeCode=e,1005===e?s.close():s.close(e,t)}function receiverOnDrain(){this[kWebSocket]._socket.resume()}function receiverOnError(e){const t=this[kWebSocket];t._socket.removeListener("data",socketOnData),t.readyState=WebSocket.CLOSING,t._closeCode=e[constants.kStatusCode],t.emit("error",e),t._socket.destroy()}function receiverOnFinish(){this[kWebSocket].emitClose()}function receiverOnMessage(e){this[kWebSocket].emit("message",e)}function receiverOnPing(e){const t=this[kWebSocket];t.pong(e,!t._isServer,constants.NOOP),t.emit("ping",e)}function receiverOnPong(e){this[kWebSocket].emit("pong",e)}function socketOnClose(){const e=this[kWebSocket];this.removeListener("close",socketOnClose),this.removeListener("end",socketOnEnd),e.readyState=WebSocket.CLOSING,e._socket.read(),e._receiver.end(),this.removeListener("data",socketOnData),this[kWebSocket]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",receiverOnFinish),e._receiver.on("finish",receiverOnFinish))}function socketOnData(e){this[kWebSocket]._receiver.write(e)||this.pause()}function socketOnEnd(){const e=this[kWebSocket];e.readyState=WebSocket.CLOSING,e._receiver.end(),this.end()}function socketOnError(){const e=this[kWebSocket];this.removeListener("error",socketOnError),this.on("error",constants.NOOP),e&&(e.readyState=WebSocket.CLOSING,this.destroy())}readyStates.forEach(((e,t)=>{WebSocket[readyStates[t]]=t})),["open","error","close","message"].forEach((e=>{Object.defineProperty(WebSocket.prototype,`on${e}`,{get(){const t=this.listeners(e);for(var s=0;s<t.length;s++)if(t[s]._listener)return t[s]._listener},set(t){const s=this.listeners(e);for(var o=0;o<s.length;o++)s[o]._listener&&this.removeListener(e,s[o]);this.addEventListener(e,t)}})})),WebSocket.prototype.addEventListener=EventTarget.addEventListener,WebSocket.prototype.removeEventListener=EventTarget.removeEventListener,module.exports=WebSocket;
\ No newline at end of file
index c9bd2f9..7c35cd9 100755 (executable)
@@ -1,67 +1 @@
-'use strict';
-
-function Queue(options) {
-  if (!(this instanceof Queue)) {
-    return new Queue(options);
-  }
-
-  options = options || {};
-  this.concurrency = options.concurrency || Infinity;
-  this.pending = 0;
-  this.jobs = [];
-  this.cbs = [];
-  this._done = done.bind(this);
-}
-
-var arrayAddMethods = [
-  'push',
-  'unshift',
-  'splice'
-];
-
-arrayAddMethods.forEach(function(method) {
-  Queue.prototype[method] = function() {
-    var methodResult = Array.prototype[method].apply(this.jobs, arguments);
-    this._run();
-    return methodResult;
-  };
-});
-
-Object.defineProperty(Queue.prototype, 'length', {
-  get: function() {
-    return this.pending + this.jobs.length;
-  }
-});
-
-Queue.prototype._run = function() {
-  if (this.pending === this.concurrency) {
-    return;
-  }
-  if (this.jobs.length) {
-    var job = this.jobs.shift();
-    this.pending++;
-    job(this._done);
-    this._run();
-  }
-
-  if (this.pending === 0) {
-    while (this.cbs.length !== 0) {
-      var cb = this.cbs.pop();
-      process.nextTick(cb);
-    }
-  }
-};
-
-Queue.prototype.onDone = function(cb) {
-  if (typeof cb === 'function') {
-    this.cbs.push(cb);
-    this._run();
-  }
-};
-
-function done() {
-  this.pending--;
-  this._run();
-}
-
-module.exports = Queue;
+"use strict";function Queue(t){if(!(this instanceof Queue))return new Queue(t);t=t||{},this.concurrency=t.concurrency||1/0,this.pending=0,this.jobs=[],this.cbs=[],this._done=done.bind(this)}var arrayAddMethods=["push","unshift","splice"];function done(){this.pending--,this._run()}arrayAddMethods.forEach((function(t){Queue.prototype[t]=function(){var n=Array.prototype[t].apply(this.jobs,arguments);return this._run(),n}})),Object.defineProperty(Queue.prototype,"length",{get:function(){return this.pending+this.jobs.length}}),Queue.prototype._run=function(){if(this.pending!==this.concurrency){if(this.jobs.length){var t=this.jobs.shift();this.pending++,t(this._done),this._run()}if(0===this.pending)for(;0!==this.cbs.length;){var n=this.cbs.pop();process.nextTick(n)}}},Queue.prototype.onDone=function(t){"function"==typeof t&&(this.cbs.push(t),this._run())},module.exports=Queue;
\ No newline at end of file
index 4f333de..06fedbc 100644 (file)
@@ -1,16 +1 @@
-var sys = require('util');
-var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
-
-var xhr = new XMLHttpRequest();
-
-xhr.onreadystatechange = function() {
-       sys.puts("State: " + this.readyState);
-       
-       if (this.readyState == 4) {
-               sys.puts("Complete.\nBody length: " + this.responseText.length);
-               sys.puts("Body:\n" + this.responseText);
-       }
-};
-
-xhr.open("GET", "http://driverdan.com");
-xhr.send();
+var sys=require("util"),XMLHttpRequest=require("xmlhttprequest").XMLHttpRequest,xhr=new XMLHttpRequest;xhr.onreadystatechange=function(){sys.puts("State: "+this.readyState),4==this.readyState&&(sys.puts("Complete.\nBody length: "+this.responseText.length),sys.puts("Body:\n"+this.responseText))},xhr.open("GET","http://driverdan.com"),xhr.send();
\ No newline at end of file
index 3223020..8f62d01 100644 (file)
  * @contributor David Ellis <d.f.ellis@ieee.org>
  * @license MIT
  */
-
-var fs = require('fs');
-var Url = require('url');
-var spawn = require('child_process').spawn;
-
-/**
- * Module exports.
- */
-
-module.exports = XMLHttpRequest;
-
-// backwards-compat
-XMLHttpRequest.XMLHttpRequest = XMLHttpRequest;
-
-/**
- * `XMLHttpRequest` constructor.
- *
- * Supported options for the `opts` object are:
- *
- *  - `agent`: An http.Agent instance; http.globalAgent may be used; if 'undefined', agent usage is disabled
- *
- * @param {Object} opts optional "options" object
- */
-
-function XMLHttpRequest(opts) {
-  "use strict";
-
-  opts = opts || {};
-
-  /**
-   * Private variables
-   */
-  var self = this;
-  var http = require('http');
-  var https = require('https');
-
-  // Holds http.js objects
-  var request;
-  var response;
-
-  // Request settings
-  var settings = {};
-
-  // Disable header blacklist.
-  // Not part of XHR specs.
-  var disableHeaderCheck = false;
-
-  // Set some default headers
-  var defaultHeaders = {
-    "User-Agent": "node-XMLHttpRequest",
-    "Accept": "*/*"
-  };
-
-  var headers = Object.assign({}, defaultHeaders);
-
-  // These headers are not user setable.
-  // The following are allowed but banned in the spec:
-  // * user-agent
-  var forbiddenRequestHeaders = [
-    "accept-charset",
-    "accept-encoding",
-    "access-control-request-headers",
-    "access-control-request-method",
-    "connection",
-    "content-length",
-    "content-transfer-encoding",
-    "cookie",
-    "cookie2",
-    "date",
-    "expect",
-    "host",
-    "keep-alive",
-    "origin",
-    "referer",
-    "te",
-    "trailer",
-    "transfer-encoding",
-    "upgrade",
-    "via"
-  ];
-
-  // These request methods are not allowed
-  var forbiddenRequestMethods = [
-    "TRACE",
-    "TRACK",
-    "CONNECT"
-  ];
-
-  // Send flag
-  var sendFlag = false;
-  // Error flag, used when errors occur or abort is called
-  var errorFlag = false;
-
-  // Event listeners
-  var listeners = {};
-
-  /**
-   * Constants
-   */
-
-  this.UNSENT = 0;
-  this.OPENED = 1;
-  this.HEADERS_RECEIVED = 2;
-  this.LOADING = 3;
-  this.DONE = 4;
-
-  /**
-   * Public vars
-   */
-
-  // Current state
-  this.readyState = this.UNSENT;
-
-  // default ready state change handler in case one is not set or is set late
-  this.onreadystatechange = null;
-
-  // Result & response
-  this.responseText = "";
-  this.responseXML = "";
-  this.status = null;
-  this.statusText = null;
-
-  /**
-   * Private methods
-   */
-
-  /**
-   * Check if the specified header is allowed.
-   *
-   * @param string header Header to validate
-   * @return boolean False if not allowed, otherwise true
-   */
-  var isAllowedHttpHeader = function(header) {
-    return disableHeaderCheck || (header && forbiddenRequestHeaders.indexOf(header.toLowerCase()) === -1);
-  };
-
-  /**
-   * Check if the specified method is allowed.
-   *
-   * @param string method Request method to validate
-   * @return boolean False if not allowed, otherwise true
-   */
-  var isAllowedHttpMethod = function(method) {
-    return (method && forbiddenRequestMethods.indexOf(method) === -1);
-  };
-
-  /**
-   * Public methods
-   */
-
-  /**
-   * Open the connection. Currently supports local server requests.
-   *
-   * @param string method Connection method (eg GET, POST)
-   * @param string url URL for the connection.
-   * @param boolean async Asynchronous connection. Default is true.
-   * @param string user Username for basic authentication (optional)
-   * @param string password Password for basic authentication (optional)
-   */
-  this.open = function(method, url, async, user, password) {
-    this.abort();
-    errorFlag = false;
-
-    // Check for valid request method
-    if (!isAllowedHttpMethod(method)) {
-      throw "SecurityError: Request method not allowed";
-    }
-
-    settings = {
-      "method": method,
-      "url": url.toString(),
-      "async": (typeof async !== "boolean" ? true : async),
-      "user": user || null,
-      "password": password || null
-    };
-
-    setState(this.OPENED);
-  };
-
-  /**
-   * Disables or enables isAllowedHttpHeader() check the request. Enabled by default.
-   * This does not conform to the W3C spec.
-   *
-   * @param boolean state Enable or disable header checking.
-   */
-  this.setDisableHeaderCheck = function(state) {
-    disableHeaderCheck = state;
-  };
-
-  /**
-   * Sets a header for the request.
-   *
-   * @param string header Header name
-   * @param string value Header value
-   * @return boolean Header added
-   */
-  this.setRequestHeader = function(header, value) {
-    if (this.readyState != this.OPENED) {
-      throw "INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN";
-      return false;
-    }
-    if (!isAllowedHttpHeader(header)) {
-      console.warn('Refused to set unsafe header "' + header + '"');
-      return false;
-    }
-    if (sendFlag) {
-      throw "INVALID_STATE_ERR: send flag is true";
-      return false;
-    }
-    headers[header] = value;
-    return true;
-  };
-
-  /**
-   * Gets a header from the server response.
-   *
-   * @param string header Name of header to get.
-   * @return string Text of the header or null if it doesn't exist.
-   */
-  this.getResponseHeader = function(header) {
-    if (typeof header === "string"
-      && this.readyState > this.OPENED
-      && response.headers[header.toLowerCase()]
-      && !errorFlag
-    ) {
-      return response.headers[header.toLowerCase()];
-    }
-
-    return null;
-  };
-
-  /**
-   * Gets all the response headers.
-   *
-   * @return string A string with all response headers separated by CR+LF
-   */
-  this.getAllResponseHeaders = function() {
-    if (this.readyState < this.HEADERS_RECEIVED || errorFlag) {
-      return "";
-    }
-    var result = "";
-
-    for (var i in response.headers) {
-      // Cookie headers are excluded
-      if (i !== "set-cookie" && i !== "set-cookie2") {
-        result += i + ": " + response.headers[i] + "\r\n";
-      }
-    }
-    return result.substr(0, result.length - 2);
-  };
-
-  /**
-   * Gets a request header
-   *
-   * @param string name Name of header to get
-   * @return string Returns the request header or empty string if not set
-   */
-  this.getRequestHeader = function(name) {
-    // @TODO Make this case insensitive
-    if (typeof name === "string" && headers[name]) {
-      return headers[name];
-    }
-
-    return "";
-  };
-
-  /**
-   * Sends the request to the server.
-   *
-   * @param string data Optional data to send as request body.
-   */
-  this.send = function(data) {
-    if (this.readyState != this.OPENED) {
-      throw "INVALID_STATE_ERR: connection must be opened before send() is called";
-    }
-
-    if (sendFlag) {
-      throw "INVALID_STATE_ERR: send has already been called";
-    }
-
-    var ssl = false, local = false;
-    var url = Url.parse(settings.url);
-    var host;
-    // Determine the server
-    switch (url.protocol) {
-      case 'https:':
-        ssl = true;
-        // SSL & non-SSL both need host, no break here.
-      case 'http:':
-        host = url.hostname;
-        break;
-
-      case 'file:':
-        local = true;
-        break;
-
-      case undefined:
-      case '':
-        host = "localhost";
-        break;
-
-      default:
-        throw "Protocol not supported.";
-    }
-
-    // Load files off the local filesystem (file://)
-    if (local) {
-      if (settings.method !== "GET") {
-        throw "XMLHttpRequest: Only GET method is supported";
-      }
-
-      if (settings.async) {
-        fs.readFile(url.pathname, 'utf8', function(error, data) {
-          if (error) {
-            self.handleError(error);
-          } else {
-            self.status = 200;
-            self.responseText = data;
-            setState(self.DONE);
-          }
-        });
-      } else {
-        try {
-          this.responseText = fs.readFileSync(url.pathname, 'utf8');
-          this.status = 200;
-          setState(self.DONE);
-        } catch(e) {
-          this.handleError(e);
-        }
-      }
-
-      return;
-    }
-
-    // Default to port 80. If accessing localhost on another port be sure
-    // to use http://localhost:port/path
-    var port = url.port || (ssl ? 443 : 80);
-    // Add query string if one is used
-    var uri = url.pathname + (url.search ? url.search : '');
-
-    // Set the Host header or the server may reject the request
-    headers["Host"] = host;
-    if (!((ssl && port === 443) || port === 80)) {
-      headers["Host"] += ':' + url.port;
-    }
-
-    // Set Basic Auth if necessary
-    if (settings.user) {
-      if (typeof settings.password == "undefined") {
-        settings.password = "";
-      }
-      var authBuf = new Buffer(settings.user + ":" + settings.password);
-      headers["Authorization"] = "Basic " + authBuf.toString("base64");
-    }
-
-    // Set content length header
-    if (settings.method === "GET" || settings.method === "HEAD") {
-      data = null;
-    } else if (data) {
-      headers["Content-Length"] = Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data);
-
-      if (!headers["Content-Type"]) {
-        headers["Content-Type"] = "text/plain;charset=UTF-8";
-      }
-    } else if (settings.method === "POST") {
-      // For a post with no data set Content-Length: 0.
-      // This is required by buggy servers that don't meet the specs.
-      headers["Content-Length"] = 0;
-    }
-
-    var agent = opts.agent || false;
-    var options = {
-      host: host,
-      port: port,
-      path: uri,
-      method: settings.method,
-      headers: headers,
-      agent: agent
-    };
-
-    if (ssl) {
-      options.pfx = opts.pfx;
-      options.key = opts.key;
-      options.passphrase = opts.passphrase;
-      options.cert = opts.cert;
-      options.ca = opts.ca;
-      options.ciphers = opts.ciphers;
-      options.rejectUnauthorized = opts.rejectUnauthorized;
-    }
-
-    // Reset error flag
-    errorFlag = false;
-
-    // Handle async requests
-    if (settings.async) {
-      // Use the proper protocol
-      var doRequest = ssl ? https.request : http.request;
-
-      // Request is being sent, set send flag
-      sendFlag = true;
-
-      // As per spec, this is called here for historical reasons.
-      self.dispatchEvent("readystatechange");
-
-      // Handler for the response
-      var responseHandler = function(resp) {
-        // Set response var to the response we got back
-        // This is so it remains accessable outside this scope
-        response = resp;
-        // Check for redirect
-        // @TODO Prevent looped redirects
-        if (response.statusCode === 302 || response.statusCode === 303 || response.statusCode === 307) {
-          // Change URL to the redirect location
-          settings.url = response.headers.location;
-          var url = Url.parse(settings.url);
-          // Set host var in case it's used later
-          host = url.hostname;
-          // Options for the new request
-          var newOptions = {
-            hostname: url.hostname,
-            port: url.port,
-            path: url.path,
-            method: response.statusCode === 303 ? 'GET' : settings.method,
-            headers: headers
-          };
-
-          if (ssl) {
-            newOptions.pfx = opts.pfx;
-            newOptions.key = opts.key;
-            newOptions.passphrase = opts.passphrase;
-            newOptions.cert = opts.cert;
-            newOptions.ca = opts.ca;
-            newOptions.ciphers = opts.ciphers;
-            newOptions.rejectUnauthorized = opts.rejectUnauthorized;
-          }
-
-          // Issue the new request
-          request = doRequest(newOptions, responseHandler).on('error', errorHandler);
-          request.end();
-          // @TODO Check if an XHR event needs to be fired here
-          return;
-        }
-
-        if (response && response.setEncoding) {
-          response.setEncoding("utf8");
-        }
-
-        setState(self.HEADERS_RECEIVED);
-        self.status = response.statusCode;
-
-        response.on('data', function(chunk) {
-          // Make sure there's some data
-          if (chunk) {
-            self.responseText += chunk;
-          }
-          // Don't emit state changes if the connection has been aborted.
-          if (sendFlag) {
-            setState(self.LOADING);
-          }
-        });
-
-        response.on('end', function() {
-          if (sendFlag) {
-            // The sendFlag needs to be set before setState is called.  Otherwise if we are chaining callbacks
-            // there can be a timing issue (the callback is called and a new call is made before the flag is reset).
-            sendFlag = false;
-            // Discard the 'end' event if the connection has been aborted
-            setState(self.DONE);
-          }
-        });
-
-        response.on('error', function(error) {
-          self.handleError(error);
-        });
-      }
-
-      // Error handler for the request
-      var errorHandler = function(error) {
-        self.handleError(error);
-      }
-
-      // Create the request
-      request = doRequest(options, responseHandler).on('error', errorHandler);
-
-      // Node 0.4 and later won't accept empty data. Make sure it's needed.
-      if (data) {
-        request.write(data);
-      }
-
-      request.end();
-
-      self.dispatchEvent("loadstart");
-    } else { // Synchronous
-      // Create a temporary file for communication with the other Node process
-      var contentFile = ".node-xmlhttprequest-content-" + process.pid;
-      var syncFile = ".node-xmlhttprequest-sync-" + process.pid;
-      fs.writeFileSync(syncFile, "", "utf8");
-      // The async request the other Node process executes
-      var execString = "var http = require('http'), https = require('https'), fs = require('fs');"
-        + "var doRequest = http" + (ssl ? "s" : "") + ".request;"
-        + "var options = " + JSON.stringify(options) + ";"
-        + "var responseText = '';"
-        + "var req = doRequest(options, function(response) {"
-        + "response.setEncoding('utf8');"
-        + "response.on('data', function(chunk) {"
-        + "  responseText += chunk;"
-        + "});"
-        + "response.on('end', function() {"
-        + "fs.writeFileSync('" + contentFile + "', 'NODE-XMLHTTPREQUEST-STATUS:' + response.statusCode + ',' + responseText, 'utf8');"
-        + "fs.unlinkSync('" + syncFile + "');"
-        + "});"
-        + "response.on('error', function(error) {"
-        + "fs.writeFileSync('" + contentFile + "', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');"
-        + "fs.unlinkSync('" + syncFile + "');"
-        + "});"
-        + "}).on('error', function(error) {"
-        + "fs.writeFileSync('" + contentFile + "', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');"
-        + "fs.unlinkSync('" + syncFile + "');"
-        + "});"
-        + (data ? "req.write('" + data.replace(/'/g, "\\'") + "');":"")
-        + "req.end();";
-      // Start the other Node Process, executing this string
-      var syncProc = spawn(process.argv[0], ["-e", execString]);
-      var statusText;
-      while(fs.existsSync(syncFile)) {
-        // Wait while the sync file is empty
-      }
-      self.responseText = fs.readFileSync(contentFile, 'utf8');
-      // Kill the child process once the file has data
-      syncProc.stdin.end();
-      // Remove the temporary file
-      fs.unlinkSync(contentFile);
-      if (self.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)) {
-        // If the file returned an error, handle it
-        var errorObj = self.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/, "");
-        self.handleError(errorObj);
-      } else {
-        // If the file returned okay, parse its data and move to the DONE state
-        self.status = self.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/, "$1");
-        self.responseText = self.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/, "$1");
-        setState(self.DONE);
-      }
-    }
-  };
-
-  /**
-   * Called when an error is encountered to deal with it.
-   */
-  this.handleError = function(error) {
-    this.status = 503;
-    this.statusText = error;
-    this.responseText = error.stack;
-    errorFlag = true;
-    setState(this.DONE);
-  };
-
-  /**
-   * Aborts a request.
-   */
-  this.abort = function() {
-    if (request) {
-      request.abort();
-      request = null;
-    }
-
-    headers = Object.assign({}, defaultHeaders);
-    this.responseText = "";
-    this.responseXML = "";
-
-    errorFlag = true;
-
-    if (this.readyState !== this.UNSENT
-        && (this.readyState !== this.OPENED || sendFlag)
-        && this.readyState !== this.DONE) {
-      sendFlag = false;
-      setState(this.DONE);
-    }
-    this.readyState = this.UNSENT;
-  };
-
-  /**
-   * Adds an event listener. Preferred method of binding to events.
-   */
-  this.addEventListener = function(event, callback) {
-    if (!(event in listeners)) {
-      listeners[event] = [];
-    }
-    // Currently allows duplicate callbacks. Should it?
-    listeners[event].push(callback);
-  };
-
-  /**
-   * Remove an event callback that has already been bound.
-   * Only works on the matching funciton, cannot be a copy.
-   */
-  this.removeEventListener = function(event, callback) {
-    if (event in listeners) {
-      // Filter will return a new array with the callback removed
-      listeners[event] = listeners[event].filter(function(ev) {
-        return ev !== callback;
-      });
-    }
-  };
-
-  /**
-   * Dispatch any events, including both "on" methods and events attached using addEventListener.
-   */
-  this.dispatchEvent = function(event) {
-    if (typeof self["on" + event] === "function") {
-      self["on" + event]();
-    }
-    if (event in listeners) {
-      for (var i = 0, len = listeners[event].length; i < len; i++) {
-        listeners[event][i].call(self);
-      }
-    }
-  };
-
-  /**
-   * Changes readyState and calls onreadystatechange.
-   *
-   * @param int state New state
-   */
-  var setState = function(state) {
-    if (self.readyState !== state) {
-      self.readyState = state;
-
-      if (settings.async || self.readyState < self.OPENED || self.readyState === self.DONE) {
-        self.dispatchEvent("readystatechange");
-      }
-
-      if (self.readyState === self.DONE && !errorFlag) {
-        self.dispatchEvent("load");
-        // @TODO figure out InspectorInstrumentation::didLoadXHR(cookie)
-        self.dispatchEvent("loadend");
-      }
-    }
-  };
-};
+var fs=require("fs"),Url=require("url"),spawn=require("child_process").spawn;function XMLHttpRequest(e){"use strict";e=e||{};var t,s,r=this,n=require("http"),o=require("https"),a={},i=!1,h={"User-Agent":"node-XMLHttpRequest",Accept:"*/*"},c=Object.assign({},h),u=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","content-transfer-encoding","cookie","cookie2","date","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"],d=["TRACE","TRACK","CONNECT"],p=!1,f=!1,E={};this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.readyState=this.UNSENT,this.onreadystatechange=null,this.responseText="",this.responseXML="",this.status=null,this.statusText=null;this.open=function(e,t,s,r,n){if(this.abort(),f=!1,!function(e){return e&&-1===d.indexOf(e)}(e))throw"SecurityError: Request method not allowed";a={method:e,url:t.toString(),async:"boolean"!=typeof s||s,user:r||null,password:n||null},l(this.OPENED)},this.setDisableHeaderCheck=function(e){i=e},this.setRequestHeader=function(e,t){if(this.readyState!=this.OPENED)throw"INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN";if(!function(e){return i||e&&-1===u.indexOf(e.toLowerCase())}(e))return console.warn('Refused to set unsafe header "'+e+'"'),!1;if(p)throw"INVALID_STATE_ERR: send flag is true";return c[e]=t,!0},this.getResponseHeader=function(e){return"string"==typeof e&&this.readyState>this.OPENED&&s.headers[e.toLowerCase()]&&!f?s.headers[e.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||f)return"";var e="";for(var t in s.headers)"set-cookie"!==t&&"set-cookie2"!==t&&(e+=t+": "+s.headers[t]+"\r\n");return e.substr(0,e.length-2)},this.getRequestHeader=function(e){return"string"==typeof e&&c[e]?c[e]:""},this.send=function(i){if(this.readyState!=this.OPENED)throw"INVALID_STATE_ERR: connection must be opened before send() is called";if(p)throw"INVALID_STATE_ERR: send has already been called";var h,u=!1,d=!1,E=Url.parse(a.url);switch(E.protocol){case"https:":u=!0;case"http:":h=E.hostname;break;case"file:":d=!0;break;case void 0:case"":h="localhost";break;default:throw"Protocol not supported."}if(d){if("GET"!==a.method)throw"XMLHttpRequest: Only GET method is supported";if(a.async)fs.readFile(E.pathname,"utf8",(function(e,t){e?r.handleError(e):(r.status=200,r.responseText=t,l(r.DONE))}));else try{this.responseText=fs.readFileSync(E.pathname,"utf8"),this.status=200,l(r.DONE)}catch(e){this.handleError(e)}}else{var T=E.port||(u?443:80),S=E.pathname+(E.search?E.search:"");if(c.Host=h,u&&443===T||80===T||(c.Host+=":"+E.port),a.user){void 0===a.password&&(a.password="");var y=new Buffer(a.user+":"+a.password);c.Authorization="Basic "+y.toString("base64")}"GET"===a.method||"HEAD"===a.method?i=null:i?(c["Content-Length"]=Buffer.isBuffer(i)?i.length:Buffer.byteLength(i),c["Content-Type"]||(c["Content-Type"]="text/plain;charset=UTF-8")):"POST"===a.method&&(c["Content-Length"]=0);var R=e.agent||!1,N={host:h,port:T,path:S,method:a.method,headers:c,agent:R};if(u&&(N.pfx=e.pfx,N.key=e.key,N.passphrase=e.passphrase,N.cert=e.cert,N.ca=e.ca,N.ciphers=e.ciphers,N.rejectUnauthorized=e.rejectUnauthorized),f=!1,a.async){var O=u?o.request:n.request;p=!0,r.dispatchEvent("readystatechange");var D=function(n){if(302===(s=n).statusCode||303===s.statusCode||307===s.statusCode){a.url=s.headers.location;var o=Url.parse(a.url);h=o.hostname;var i={hostname:o.hostname,port:o.port,path:o.path,method:303===s.statusCode?"GET":a.method,headers:c};return u&&(i.pfx=e.pfx,i.key=e.key,i.passphrase=e.passphrase,i.cert=e.cert,i.ca=e.ca,i.ciphers=e.ciphers,i.rejectUnauthorized=e.rejectUnauthorized),void(t=O(i,D).on("error",v)).end()}s&&s.setEncoding&&s.setEncoding("utf8"),l(r.HEADERS_RECEIVED),r.status=s.statusCode,s.on("data",(function(e){e&&(r.responseText+=e),p&&l(r.LOADING)})),s.on("end",(function(){p&&(p=!1,l(r.DONE))})),s.on("error",(function(e){r.handleError(e)}))},v=function(e){r.handleError(e)};t=O(N,D).on("error",v),i&&t.write(i),t.end(),r.dispatchEvent("loadstart")}else{var g=".node-xmlhttprequest-content-"+process.pid,q=".node-xmlhttprequest-sync-"+process.pid;fs.writeFileSync(q,"","utf8");for(var L="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(u?"s":"")+".request;var options = "+JSON.stringify(N)+";var responseText = '';var req = doRequest(options, function(response) {response.setEncoding('utf8');response.on('data', function(chunk) {  responseText += chunk;});response.on('end', function() {fs.writeFileSync('"+g+"', 'NODE-XMLHTTPREQUEST-STATUS:' + response.statusCode + ',' + responseText, 'utf8');fs.unlinkSync('"+q+"');});response.on('error', function(error) {fs.writeFileSync('"+g+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+q+"');});}).on('error', function(error) {fs.writeFileSync('"+g+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+q+"');});"+(i?"req.write('"+i.replace(/'/g,"\\'")+"');":"")+"req.end();",x=spawn(process.argv[0],["-e",L]);fs.existsSync(q););if(r.responseText=fs.readFileSync(g,"utf8"),x.stdin.end(),fs.unlinkSync(g),r.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var w=r.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,"");r.handleError(w)}else r.status=r.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/,"$1"),r.responseText=r.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"),l(r.DONE)}}},this.handleError=function(e){this.status=503,this.statusText=e,this.responseText=e.stack,f=!0,l(this.DONE)},this.abort=function(){t&&(t.abort(),t=null),c=Object.assign({},h),this.responseText="",this.responseXML="",f=!0,this.readyState===this.UNSENT||this.readyState===this.OPENED&&!p||this.readyState===this.DONE||(p=!1,l(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(e,t){e in E||(E[e]=[]),E[e].push(t)},this.removeEventListener=function(e,t){e in E&&(E[e]=E[e].filter((function(e){return e!==t})))},this.dispatchEvent=function(e){if("function"==typeof r["on"+e]&&r["on"+e](),e in E)for(var t=0,s=E[e].length;t<s;t++)E[e][t].call(r)};var l=function(e){r.readyState!==e&&(r.readyState=e,(a.async||r.readyState<r.OPENED||r.readyState===r.DONE)&&r.dispatchEvent("readystatechange"),r.readyState!==r.DONE||f||(r.dispatchEvent("load"),r.dispatchEvent("loadend")))}}module.exports=XMLHttpRequest,XMLHttpRequest.XMLHttpRequest=XMLHttpRequest;
\ No newline at end of file
index 372e46c..d9075b0 100644 (file)
@@ -1,13 +1 @@
-var sys = require("util")
-  , assert = require("assert")
-  , XMLHttpRequest = require("../lib/XMLHttpRequest").XMLHttpRequest
-  , xhr = new XMLHttpRequest();
-
-// Test constant values
-assert.equal(0, xhr.UNSENT);
-assert.equal(1, xhr.OPENED);
-assert.equal(2, xhr.HEADERS_RECEIVED);
-assert.equal(3, xhr.LOADING);
-assert.equal(4, xhr.DONE);
-
-sys.puts("done");
+var sys=require("util"),assert=require("assert"),XMLHttpRequest=require("../lib/XMLHttpRequest").XMLHttpRequest,xhr=new XMLHttpRequest;assert.equal(0,xhr.UNSENT),assert.equal(1,xhr.OPENED),assert.equal(2,xhr.HEADERS_RECEIVED),assert.equal(3,xhr.LOADING),assert.equal(4,xhr.DONE),sys.puts("done");
\ No newline at end of file
index c72f001..ff0ed56 100644 (file)
@@ -1,50 +1 @@
-var sys = require("util")
-  , assert = require("assert")
-  , http = require("http")
-  , XMLHttpRequest = require("../lib/XMLHttpRequest").XMLHttpRequest
-  , xhr;
-
-// Test server
-var server = http.createServer(function (req, res) {
-  var body = (req.method != "HEAD" ? "Hello World" : "");
-
-  res.writeHead(200, {
-    "Content-Type": "text/plain",
-    "Content-Length": Buffer.byteLength(body)
-  });
-  // HEAD has no body
-  if (req.method != "HEAD") {
-    res.write(body);
-  }
-  res.end();
-  assert.equal(onreadystatechange, true);
-  assert.equal(readystatechange, true);
-  assert.equal(removed, true);
-  sys.puts("done");
-  this.close();
-}).listen(8000);
-
-xhr = new XMLHttpRequest();
-
-// Track event calls
-var onreadystatechange = false;
-var readystatechange = false;
-var removed = true;
-var removedEvent = function() {
-  removed = false;
-};
-
-xhr.onreadystatechange = function() {
-  onreadystatechange = true;
-};
-
-xhr.addEventListener("readystatechange", function() {
-  readystatechange = true;
-});
-
-// This isn't perfect, won't guarantee it was added in the first place
-xhr.addEventListener("readystatechange", removedEvent);
-xhr.removeEventListener("readystatechange", removedEvent);
-
-xhr.open("GET", "http://localhost:8000");
-xhr.send();
+var xhr,sys=require("util"),assert=require("assert"),http=require("http"),XMLHttpRequest=require("../lib/XMLHttpRequest").XMLHttpRequest,server=http.createServer((function(e,t){var r="HEAD"!=e.method?"Hello World":"";t.writeHead(200,{"Content-Type":"text/plain","Content-Length":Buffer.byteLength(r)}),"HEAD"!=e.method&&t.write(r),t.end(),assert.equal(onreadystatechange,!0),assert.equal(readystatechange,!0),assert.equal(removed,!0),sys.puts("done"),this.close()})).listen(8e3);xhr=new XMLHttpRequest;var onreadystatechange=!1,readystatechange=!1,removed=!0,removedEvent=function(){removed=!1};xhr.onreadystatechange=function(){onreadystatechange=!0},xhr.addEventListener("readystatechange",(function(){readystatechange=!0})),xhr.addEventListener("readystatechange",removedEvent),xhr.removeEventListener("readystatechange",removedEvent),xhr.open("GET","http://localhost:8000"),xhr.send();
\ No newline at end of file
index 10eaea2..3d576bc 100644 (file)
@@ -1,59 +1 @@
-var sys = require("util")
-  , assert = require("assert")
-  , XMLHttpRequest = require("../lib/XMLHttpRequest").XMLHttpRequest
-  , xhr = new XMLHttpRequest();
-
-// Test request methods that aren't allowed
-try {
-  xhr.open("TRACK", "http://localhost:8000/");
-  console.log("ERROR: TRACK should have thrown exception");
-} catch(e) {}
-try {
-  xhr.open("TRACE", "http://localhost:8000/");
-  console.log("ERROR: TRACE should have thrown exception");
-} catch(e) {}
-try {
-  xhr.open("CONNECT", "http://localhost:8000/");
-  console.log("ERROR: CONNECT should have thrown exception");
-} catch(e) {}
-// Test valid request method
-try {
-  xhr.open("GET", "http://localhost:8000/");
-} catch(e) {
-  console.log("ERROR: Invalid exception for GET", e);
-}
-
-// Test forbidden headers
-var forbiddenRequestHeaders = [
-  "accept-charset",
-  "accept-encoding",
-  "access-control-request-headers",
-  "access-control-request-method",
-  "connection",
-  "content-length",
-  "content-transfer-encoding",
-  "cookie",
-  "cookie2",
-  "date",
-  "expect",
-  "host",
-  "keep-alive",
-  "origin",
-  "referer",
-  "te",
-  "trailer",
-  "transfer-encoding",
-  "upgrade",
-  "via"
-];
-
-for (var i in forbiddenRequestHeaders) {
-  if(xhr.setRequestHeader(forbiddenRequestHeaders[i], "Test") !== false) {
-    console.log("ERROR: " + forbiddenRequestHeaders[i] + " should have thrown exception");
-  }
-}
-
-// Try valid header
-xhr.setRequestHeader("X-Foobar", "Test");
-
-console.log("Done");
+var sys=require("util"),assert=require("assert"),XMLHttpRequest=require("../lib/XMLHttpRequest").XMLHttpRequest,xhr=new XMLHttpRequest;try{xhr.open("TRACK","http://localhost:8000/"),console.log("ERROR: TRACK should have thrown exception")}catch(e){}try{xhr.open("TRACE","http://localhost:8000/"),console.log("ERROR: TRACE should have thrown exception")}catch(e){}try{xhr.open("CONNECT","http://localhost:8000/"),console.log("ERROR: CONNECT should have thrown exception")}catch(e){}try{xhr.open("GET","http://localhost:8000/")}catch(e){console.log("ERROR: Invalid exception for GET",e)}var forbiddenRequestHeaders=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","content-transfer-encoding","cookie","cookie2","date","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"];for(var i in forbiddenRequestHeaders)!1!==xhr.setRequestHeader(forbiddenRequestHeaders[i],"Test")&&console.log("ERROR: "+forbiddenRequestHeaders[i]+" should have thrown exception");xhr.setRequestHeader("X-Foobar","Test"),console.log("Done");
\ No newline at end of file
index 76454f1..88f657c 100644 (file)
@@ -1,76 +1 @@
-var sys = require("util")
-  , assert = require("assert")
-  , XMLHttpRequest = require("../lib/XMLHttpRequest").XMLHttpRequest
-  , xhr = new XMLHttpRequest()
-  , http = require("http");
-
-// Test server
-var server = http.createServer(function (req, res) {
-  // Test setRequestHeader
-  assert.equal("Foobar", req.headers["x-test"]);
-  // Test non-conforming allowed header
-  assert.equal("node-XMLHttpRequest-test", req.headers["user-agent"]);
-  // Test header set with blacklist disabled
-  assert.equal("http://github.com", req.headers["referer"]);
-
-  var body = "Hello World";
-  res.writeHead(200, {
-    "Content-Type": "text/plain",
-    "Content-Length": Buffer.byteLength(body),
-    // Set cookie headers to see if they're correctly suppressed
-    // Actual values don't matter
-    "Set-Cookie": "foo=bar",
-    "Set-Cookie2": "bar=baz",
-    "Date": "Thu, 30 Aug 2012 18:17:53 GMT",
-    "Connection": "close"
-  });
-  res.write("Hello World");
-  res.end();
-
-  this.close();
-}).listen(8000);
-
-xhr.onreadystatechange = function() {
-  if (this.readyState == 4) {
-    // Test getAllResponseHeaders()
-    var headers = "content-type: text/plain\r\ncontent-length: 11\r\ndate: Thu, 30 Aug 2012 18:17:53 GMT\r\nconnection: close";
-    assert.equal(headers, this.getAllResponseHeaders());
-
-    // Test case insensitivity
-    assert.equal('text/plain', this.getResponseHeader('Content-Type'));
-    assert.equal('text/plain', this.getResponseHeader('Content-type'));
-    assert.equal('text/plain', this.getResponseHeader('content-Type'));
-    assert.equal('text/plain', this.getResponseHeader('content-type'));
-
-    // Test aborted getAllResponseHeaders
-    this.abort();
-    assert.equal("", this.getAllResponseHeaders());
-    assert.equal(null, this.getResponseHeader("Connection"));
-
-    sys.puts("done");
-  }
-};
-
-assert.equal(null, xhr.getResponseHeader("Content-Type"));
-try {
-  xhr.open("GET", "http://localhost:8000/");
-  // Valid header
-  xhr.setRequestHeader("X-Test", "Foobar");
-  // Invalid header
-  xhr.setRequestHeader("Content-Length", 0);
-  // Allowed header outside of specs
-  xhr.setRequestHeader("user-agent", "node-XMLHttpRequest-test");
-  // Test getRequestHeader
-  assert.equal("Foobar", xhr.getRequestHeader("X-Test"));
-  // Test invalid header
-  assert.equal("", xhr.getRequestHeader("Content-Length"));
-
-  // Test allowing all headers
-  xhr.setDisableHeaderCheck(true);
-  xhr.setRequestHeader("Referer", "http://github.com");
-  assert.equal("http://github.com", xhr.getRequestHeader("Referer"));
-
-  xhr.send();
-} catch(e) {
-  console.log("ERROR: Exception raised", e);
-}
+var sys=require("util"),assert=require("assert"),XMLHttpRequest=require("../lib/XMLHttpRequest").XMLHttpRequest,xhr=new XMLHttpRequest,http=require("http"),server=http.createServer((function(e,t){assert.equal("Foobar",e.headers["x-test"]),assert.equal("node-XMLHttpRequest-test",e.headers["user-agent"]),assert.equal("http://github.com",e.headers.referer);t.writeHead(200,{"Content-Type":"text/plain","Content-Length":Buffer.byteLength("Hello World"),"Set-Cookie":"foo=bar","Set-Cookie2":"bar=baz",Date:"Thu, 30 Aug 2012 18:17:53 GMT",Connection:"close"}),t.write("Hello World"),t.end(),this.close()})).listen(8e3);xhr.onreadystatechange=function(){if(4==this.readyState){assert.equal("content-type: text/plain\r\ncontent-length: 11\r\ndate: Thu, 30 Aug 2012 18:17:53 GMT\r\nconnection: close",this.getAllResponseHeaders()),assert.equal("text/plain",this.getResponseHeader("Content-Type")),assert.equal("text/plain",this.getResponseHeader("Content-type")),assert.equal("text/plain",this.getResponseHeader("content-Type")),assert.equal("text/plain",this.getResponseHeader("content-type")),this.abort(),assert.equal("",this.getAllResponseHeaders()),assert.equal(null,this.getResponseHeader("Connection")),sys.puts("done")}},assert.equal(null,xhr.getResponseHeader("Content-Type"));try{xhr.open("GET","http://localhost:8000/"),xhr.setRequestHeader("X-Test","Foobar"),xhr.setRequestHeader("Content-Length",0),xhr.setRequestHeader("user-agent","node-XMLHttpRequest-test"),assert.equal("Foobar",xhr.getRequestHeader("X-Test")),assert.equal("",xhr.getRequestHeader("Content-Length")),xhr.setDisableHeaderCheck(!0),xhr.setRequestHeader("Referer","http://github.com"),assert.equal("http://github.com",xhr.getRequestHeader("Referer")),xhr.send()}catch(e){console.log("ERROR: Exception raised",e)}
\ No newline at end of file
index d884f78..5268daf 100644 (file)
@@ -1,41 +1 @@
-var sys = require("util")
-  , assert = require("assert")
-  , XMLHttpRequest = require("../lib/XMLHttpRequest").XMLHttpRequest
-  , xhr = new XMLHttpRequest()
-  , http = require("http");
-
-// Test server
-var server = http.createServer(function (req, res) {
-  if (req.url === '/redirectingResource') {
-    res.writeHead(302, {'Location': 'http://localhost:8000/'});
-    res.end();
-    return;
-  }
-
-  var body = "Hello World";
-  res.writeHead(200, {
-    "Content-Type": "text/plain",
-    "Content-Length": Buffer.byteLength(body),
-    "Date": "Thu, 30 Aug 2012 18:17:53 GMT",
-    "Connection": "close"
-  });
-  res.write("Hello World");
-  res.end();
-
-  this.close();
-}).listen(8000);
-
-xhr.onreadystatechange = function() {
-  if (this.readyState == 4) {
-    assert.equal(xhr.getRequestHeader('Location'), '');
-    assert.equal(xhr.responseText, "Hello World");
-    sys.puts("done");
-  }
-};
-
-try {
-  xhr.open("GET", "http://localhost:8000/redirectingResource");
-  xhr.send();
-} catch(e) {
-  console.log("ERROR: Exception raised", e);
-}
+var sys=require("util"),assert=require("assert"),XMLHttpRequest=require("../lib/XMLHttpRequest").XMLHttpRequest,xhr=new XMLHttpRequest,http=require("http"),server=http.createServer((function(e,t){if("/redirectingResource"===e.url)return t.writeHead(302,{Location:"http://localhost:8000/"}),void t.end();t.writeHead(200,{"Content-Type":"text/plain","Content-Length":Buffer.byteLength("Hello World"),Date:"Thu, 30 Aug 2012 18:17:53 GMT",Connection:"close"}),t.write("Hello World"),t.end(),this.close()})).listen(8e3);xhr.onreadystatechange=function(){4==this.readyState&&(assert.equal(xhr.getRequestHeader("Location"),""),assert.equal(xhr.responseText,"Hello World"),sys.puts("done"))};try{xhr.open("GET","http://localhost:8000/redirectingResource"),xhr.send()}catch(e){console.log("ERROR: Exception raised",e)}
\ No newline at end of file
index 60d9343..9bc87b1 100644 (file)
@@ -1,41 +1 @@
-var sys = require("util")
-  , assert = require("assert")
-  , XMLHttpRequest = require("../lib/XMLHttpRequest").XMLHttpRequest
-  , xhr = new XMLHttpRequest()
-  , http = require("http");
-
-// Test server
-var server = http.createServer(function (req, res) {
-  if (req.url === '/redirectingResource') {
-    res.writeHead(303, {'Location': 'http://localhost:8000/'});
-    res.end();
-    return;
-  }
-
-  var body = "Hello World";
-  res.writeHead(200, {
-    "Content-Type": "text/plain",
-    "Content-Length": Buffer.byteLength(body),
-    "Date": "Thu, 30 Aug 2012 18:17:53 GMT",
-    "Connection": "close"
-  });
-  res.write("Hello World");
-  res.end();
-
-  this.close();
-}).listen(8000);
-
-xhr.onreadystatechange = function() {
-  if (this.readyState == 4) {
-    assert.equal(xhr.getRequestHeader('Location'), '');
-    assert.equal(xhr.responseText, "Hello World");
-    sys.puts("done");
-  }
-};
-
-try {
-  xhr.open("POST", "http://localhost:8000/redirectingResource");
-  xhr.send();
-} catch(e) {
-  console.log("ERROR: Exception raised", e);
-}
+var sys=require("util"),assert=require("assert"),XMLHttpRequest=require("../lib/XMLHttpRequest").XMLHttpRequest,xhr=new XMLHttpRequest,http=require("http"),server=http.createServer((function(e,t){if("/redirectingResource"===e.url)return t.writeHead(303,{Location:"http://localhost:8000/"}),void t.end();t.writeHead(200,{"Content-Type":"text/plain","Content-Length":Buffer.byteLength("Hello World"),Date:"Thu, 30 Aug 2012 18:17:53 GMT",Connection:"close"}),t.write("Hello World"),t.end(),this.close()})).listen(8e3);xhr.onreadystatechange=function(){4==this.readyState&&(assert.equal(xhr.getRequestHeader("Location"),""),assert.equal(xhr.responseText,"Hello World"),sys.puts("done"))};try{xhr.open("POST","http://localhost:8000/redirectingResource"),xhr.send()}catch(e){console.log("ERROR: Exception raised",e)}
\ No newline at end of file
index 3abc906..c04aa40 100644 (file)
@@ -1,43 +1 @@
-var sys = require("util")
-  , assert = require("assert")
-  , XMLHttpRequest = require("../lib/XMLHttpRequest").XMLHttpRequest
-  , xhr = new XMLHttpRequest()
-  , http = require("http");
-
-// Test server
-var server = http.createServer(function (req, res) {
-  if (req.url === '/redirectingResource') {
-    res.writeHead(307, {'Location': 'http://localhost:8000/'});
-    res.end();
-    return;
-  }
-
-  assert.equal(req.method, 'POST');
-
-  var body = "Hello World";
-  res.writeHead(200, {
-    "Content-Type": "text/plain",
-    "Content-Length": Buffer.byteLength(body),
-    "Date": "Thu, 30 Aug 2012 18:17:53 GMT",
-    "Connection": "close"
-  });
-  res.write("Hello World");
-  res.end();
-
-  this.close();
-}).listen(8000);
-
-xhr.onreadystatechange = function() {
-  if (this.readyState == 4) {
-    assert.equal(xhr.getRequestHeader('Location'), '');
-    assert.equal(xhr.responseText, "Hello World");
-    sys.puts("done");
-  }
-};
-
-try {
-  xhr.open("POST", "http://localhost:8000/redirectingResource");
-  xhr.send();
-} catch(e) {
-  console.log("ERROR: Exception raised", e);
-}
+var sys=require("util"),assert=require("assert"),XMLHttpRequest=require("../lib/XMLHttpRequest").XMLHttpRequest,xhr=new XMLHttpRequest,http=require("http"),server=http.createServer((function(e,t){if("/redirectingResource"===e.url)return t.writeHead(307,{Location:"http://localhost:8000/"}),void t.end();assert.equal(e.method,"POST");t.writeHead(200,{"Content-Type":"text/plain","Content-Length":Buffer.byteLength("Hello World"),Date:"Thu, 30 Aug 2012 18:17:53 GMT",Connection:"close"}),t.write("Hello World"),t.end(),this.close()})).listen(8e3);xhr.onreadystatechange=function(){4==this.readyState&&(assert.equal(xhr.getRequestHeader("Location"),""),assert.equal(xhr.responseText,"Hello World"),sys.puts("done"))};try{xhr.open("POST","http://localhost:8000/redirectingResource"),xhr.send()}catch(e){console.log("ERROR: Exception raised",e)}
\ No newline at end of file
index fa1b1be..026775e 100644 (file)
@@ -1,62 +1 @@
-var sys = require("util")
-  , assert = require("assert")
-  , XMLHttpRequest = require("../lib/XMLHttpRequest").XMLHttpRequest
-  , http = require("http")
-  , xhr;
-
-// Test server
-var server = http.createServer(function (req, res) {
-  // Check request method and URL
-  assert.equal(methods[curMethod], req.method);
-  assert.equal("/" + methods[curMethod], req.url);
-
-  var body = (req.method != "HEAD" ? "Hello World" : "");
-
-  res.writeHead(200, {
-    "Content-Type": "text/plain",
-    "Content-Length": Buffer.byteLength(body)
-  });
-  // HEAD has no body
-  if (req.method != "HEAD") {
-    res.write(body);
-  }
-  res.end();
-
-  if (curMethod == methods.length - 1) {
-    this.close();
-    sys.puts("done");
-  }
-}).listen(8000);
-
-// Test standard methods
-var methods = ["GET", "POST", "HEAD", "PUT", "DELETE"];
-var curMethod = 0;
-
-function start(method) {
-  // Reset each time
-  xhr = new XMLHttpRequest();
-
-  xhr.onreadystatechange = function() {
-    if (this.readyState == 4) {
-      if (method == "HEAD") {
-        assert.equal("", this.responseText);
-      } else {
-        assert.equal("Hello World", this.responseText);
-      }
-
-      curMethod++;
-
-      if (curMethod < methods.length) {
-        sys.puts("Testing " + methods[curMethod]);
-        start(methods[curMethod]);
-      }
-    }
-  };
-
-  var url = "http://localhost:8000/" + method;
-  xhr.open(method, url);
-  xhr.send();
-}
-
-sys.puts("Testing " + methods[curMethod]);
-start(methods[curMethod]);
+var xhr,sys=require("util"),assert=require("assert"),XMLHttpRequest=require("../lib/XMLHttpRequest").XMLHttpRequest,http=require("http"),server=http.createServer((function(e,t){assert.equal(methods[curMethod],e.method),assert.equal("/"+methods[curMethod],e.url);var s="HEAD"!=e.method?"Hello World":"";t.writeHead(200,{"Content-Type":"text/plain","Content-Length":Buffer.byteLength(s)}),"HEAD"!=e.method&&t.write(s),t.end(),curMethod==methods.length-1&&(this.close(),sys.puts("done"))})).listen(8e3),methods=["GET","POST","HEAD","PUT","DELETE"],curMethod=0;function start(e){(xhr=new XMLHttpRequest).onreadystatechange=function(){4==this.readyState&&("HEAD"==e?assert.equal("",this.responseText):assert.equal("Hello World",this.responseText),++curMethod<methods.length&&(sys.puts("Testing "+methods[curMethod]),start(methods[curMethod])))};var t="http://localhost:8000/"+e;xhr.open(e,t),xhr.send()}sys.puts("Testing "+methods[curMethod]),start(methods[curMethod]);
\ No newline at end of file
index 543917d..0a95a40 100644 (file)
@@ -1,32 +1 @@
-var sys = require("util")
-  , assert = require("assert")
-  , XMLHttpRequest = require("../lib/XMLHttpRequest").XMLHttpRequest
-  , xhr;
-
-xhr = new XMLHttpRequest();
-
-xhr.onreadystatechange = function() {
-  if (this.readyState == 4) {
-    assert.equal("Hello World", this.responseText);
-    runSync();
-  }
-};
-
-// Async
-var url = "file://" + __dirname + "/testdata.txt";
-xhr.open("GET", url);
-xhr.send();
-
-// Sync
-var runSync = function() {
-  xhr = new XMLHttpRequest();
-
-  xhr.onreadystatechange = function() {
-    if (this.readyState == 4) {
-      assert.equal("Hello World", this.responseText);
-      sys.puts("done");
-    }
-  };
-  xhr.open("GET", url, false);
-  xhr.send();
-}
+var xhr,sys=require("util"),assert=require("assert"),XMLHttpRequest=require("../lib/XMLHttpRequest").XMLHttpRequest;(xhr=new XMLHttpRequest).onreadystatechange=function(){4==this.readyState&&(assert.equal("Hello World",this.responseText),runSync())};var url="file://"+__dirname+"/testdata.txt";xhr.open("GET",url),xhr.send();var runSync=function(){(xhr=new XMLHttpRequest).onreadystatechange=function(){4==this.readyState&&(assert.equal("Hello World",this.responseText),sys.puts("done"))},xhr.open("GET",url,!1),xhr.send()};
\ No newline at end of file
index 4893913..9d76bbc 100755 (executable)
  * @contributor David Ellis <d.f.ellis@ieee.org>
  * @license MIT
  */
-
-var Url = require("url");
-var spawn = require("child_process").spawn;
-var fs = require("fs");
-
-exports.XMLHttpRequest = function() {
-  "use strict";
-
-  /**
-   * Private variables
-   */
-  var self = this;
-  var http = require("http");
-  var https = require("https");
-
-  // Holds http.js objects
-  var request;
-  var response;
-
-  // Request settings
-  var settings = {};
-
-  // Disable header blacklist.
-  // Not part of XHR specs.
-  var disableHeaderCheck = false;
-
-  // Set some default headers
-  var defaultHeaders = {
-    "User-Agent": "node-XMLHttpRequest",
-    "Accept": "*/*",
-  };
-
-  var headers = {};
-  var headersCase = {};
-
-  // These headers are not user setable.
-  // The following are allowed but banned in the spec:
-  // * user-agent
-  var forbiddenRequestHeaders = [
-    "accept-charset",
-    "accept-encoding",
-    "access-control-request-headers",
-    "access-control-request-method",
-    "connection",
-    "content-length",
-    "content-transfer-encoding",
-    "cookie",
-    "cookie2",
-    "date",
-    "expect",
-    "host",
-    "keep-alive",
-    "origin",
-    "referer",
-    "te",
-    "trailer",
-    "transfer-encoding",
-    "upgrade",
-    "via"
-  ];
-
-  // These request methods are not allowed
-  var forbiddenRequestMethods = [
-    "TRACE",
-    "TRACK",
-    "CONNECT"
-  ];
-
-  // Send flag
-  var sendFlag = false;
-  // Error flag, used when errors occur or abort is called
-  var errorFlag = false;
-
-  // Event listeners
-  var listeners = {};
-
-  /**
-   * Constants
-   */
-
-  this.UNSENT = 0;
-  this.OPENED = 1;
-  this.HEADERS_RECEIVED = 2;
-  this.LOADING = 3;
-  this.DONE = 4;
-
-  /**
-   * Public vars
-   */
-
-  // Current state
-  this.readyState = this.UNSENT;
-
-  // default ready state change handler in case one is not set or is set late
-  this.onreadystatechange = null;
-
-  // Result & response
-  this.responseText = "";
-  this.responseXML = "";
-  this.status = null;
-  this.statusText = null;
-  
-  // Whether cross-site Access-Control requests should be made using
-  // credentials such as cookies or authorization headers
-  this.withCredentials = false;
-
-  /**
-   * Private methods
-   */
-
-  /**
-   * Check if the specified header is allowed.
-   *
-   * @param string header Header to validate
-   * @return boolean False if not allowed, otherwise true
-   */
-  var isAllowedHttpHeader = function(header) {
-    return disableHeaderCheck || (header && forbiddenRequestHeaders.indexOf(header.toLowerCase()) === -1);
-  };
-
-  /**
-   * Check if the specified method is allowed.
-   *
-   * @param string method Request method to validate
-   * @return boolean False if not allowed, otherwise true
-   */
-  var isAllowedHttpMethod = function(method) {
-    return (method && forbiddenRequestMethods.indexOf(method) === -1);
-  };
-
-  /**
-   * Public methods
-   */
-
-  /**
-   * Open the connection. Currently supports local server requests.
-   *
-   * @param string method Connection method (eg GET, POST)
-   * @param string url URL for the connection.
-   * @param boolean async Asynchronous connection. Default is true.
-   * @param string user Username for basic authentication (optional)
-   * @param string password Password for basic authentication (optional)
-   */
-  this.open = function(method, url, async, user, password) {
-    this.abort();
-    errorFlag = false;
-
-    // Check for valid request method
-    if (!isAllowedHttpMethod(method)) {
-      throw new Error("SecurityError: Request method not allowed");
-    }
-
-    settings = {
-      "method": method,
-      "url": url.toString(),
-      "async": (typeof async !== "boolean" ? true : async),
-      "user": user || null,
-      "password": password || null
-    };
-
-    setState(this.OPENED);
-  };
-
-  /**
-   * Disables or enables isAllowedHttpHeader() check the request. Enabled by default.
-   * This does not conform to the W3C spec.
-   *
-   * @param boolean state Enable or disable header checking.
-   */
-  this.setDisableHeaderCheck = function(state) {
-    disableHeaderCheck = state;
-  };
-
-  /**
-   * Sets a header for the request or appends the value if one is already set.
-   *
-   * @param string header Header name
-   * @param string value Header value
-   */
-  this.setRequestHeader = function(header, value) {
-    if (this.readyState !== this.OPENED) {
-      throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");
-    }
-    if (!isAllowedHttpHeader(header)) {
-      console.warn("Refused to set unsafe header \"" + header + "\"");
-      return;
-    }
-    if (sendFlag) {
-      throw new Error("INVALID_STATE_ERR: send flag is true");
-    }
-    header = headersCase[header.toLowerCase()] || header;
-    headersCase[header.toLowerCase()] = header;
-    headers[header] = headers[header] ? headers[header] + ', ' + value : value;
-  };
-
-  /**
-   * Gets a header from the server response.
-   *
-   * @param string header Name of header to get.
-   * @return string Text of the header or null if it doesn't exist.
-   */
-  this.getResponseHeader = function(header) {
-    if (typeof header === "string"
-      && this.readyState > this.OPENED
-      && response
-      && response.headers
-      && response.headers[header.toLowerCase()]
-      && !errorFlag
-    ) {
-      return response.headers[header.toLowerCase()];
-    }
-
-    return null;
-  };
-
-  /**
-   * Gets all the response headers.
-   *
-   * @return string A string with all response headers separated by CR+LF
-   */
-  this.getAllResponseHeaders = function() {
-    if (this.readyState < this.HEADERS_RECEIVED || errorFlag) {
-      return "";
-    }
-    var result = "";
-
-    for (var i in response.headers) {
-      // Cookie headers are excluded
-      if (i !== "set-cookie" && i !== "set-cookie2") {
-        result += i + ": " + response.headers[i] + "\r\n";
-      }
-    }
-    return result.substr(0, result.length - 2);
-  };
-
-  /**
-   * Gets a request header
-   *
-   * @param string name Name of header to get
-   * @return string Returns the request header or empty string if not set
-   */
-  this.getRequestHeader = function(name) {
-    if (typeof name === "string" && headersCase[name.toLowerCase()]) {
-      return headers[headersCase[name.toLowerCase()]];
-    }
-
-    return "";
-  };
-
-  /**
-   * Sends the request to the server.
-   *
-   * @param string data Optional data to send as request body.
-   */
-  this.send = function(data) {
-    if (this.readyState !== this.OPENED) {
-      throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");
-    }
-
-    if (sendFlag) {
-      throw new Error("INVALID_STATE_ERR: send has already been called");
-    }
-
-    var ssl = false, local = false;
-    var url = Url.parse(settings.url);
-    var host;
-    // Determine the server
-    switch (url.protocol) {
-      case "https:":
-        ssl = true;
-        // SSL & non-SSL both need host, no break here.
-      case "http:":
-        host = url.hostname;
-        break;
-
-      case "file:":
-        local = true;
-        break;
-
-      case undefined:
-      case null:
-      case "":
-        host = "localhost";
-        break;
-
-      default:
-        throw new Error("Protocol not supported.");
-    }
-
-    // Load files off the local filesystem (file://)
-    if (local) {
-      if (settings.method !== "GET") {
-        throw new Error("XMLHttpRequest: Only GET method is supported");
-      }
-
-      if (settings.async) {
-        fs.readFile(url.pathname, "utf8", function(error, data) {
-          if (error) {
-            self.handleError(error);
-          } else {
-            self.status = 200;
-            self.responseText = data;
-            setState(self.DONE);
-          }
-        });
-      } else {
-        try {
-          this.responseText = fs.readFileSync(url.pathname, "utf8");
-          this.status = 200;
-          setState(self.DONE);
-        } catch(e) {
-          this.handleError(e);
-        }
-      }
-
-      return;
-    }
-
-    // Default to port 80. If accessing localhost on another port be sure
-    // to use http://localhost:port/path
-    var port = url.port || (ssl ? 443 : 80);
-    // Add query string if one is used
-    var uri = url.pathname + (url.search ? url.search : "");
-
-    // Set the defaults if they haven't been set
-    for (var name in defaultHeaders) {
-      if (!headersCase[name.toLowerCase()]) {
-        headers[name] = defaultHeaders[name];
-      }
-    }
-
-    // Set the Host header or the server may reject the request
-    headers.Host = host;
-    if (!((ssl && port === 443) || port === 80)) {
-      headers.Host += ":" + url.port;
-    }
-
-    // Set Basic Auth if necessary
-    if (settings.user) {
-      if (typeof settings.password === "undefined") {
-        settings.password = "";
-      }
-      var authBuf = new Buffer(settings.user + ":" + settings.password);
-      headers.Authorization = "Basic " + authBuf.toString("base64");
-    }
-
-    // Set content length header
-    if (settings.method === "GET" || settings.method === "HEAD") {
-      data = null;
-    } else if (data) {
-      headers["Content-Length"] = Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data);
-
-      if (!headers["Content-Type"]) {
-        headers["Content-Type"] = "text/plain;charset=UTF-8";
-      }
-    } else if (settings.method === "POST") {
-      // For a post with no data set Content-Length: 0.
-      // This is required by buggy servers that don't meet the specs.
-      headers["Content-Length"] = 0;
-    }
-
-    var options = {
-      host: host,
-      port: port,
-      path: uri,
-      method: settings.method,
-      headers: headers,
-      agent: false,
-      withCredentials: self.withCredentials
-    };
-
-    // Reset error flag
-    errorFlag = false;
-
-    // Handle async requests
-    if (settings.async) {
-      // Use the proper protocol
-      var doRequest = ssl ? https.request : http.request;
-
-      // Request is being sent, set send flag
-      sendFlag = true;
-
-      // As per spec, this is called here for historical reasons.
-      self.dispatchEvent("readystatechange");
-
-      // Handler for the response
-      var responseHandler = function responseHandler(resp) {
-        // Set response var to the response we got back
-        // This is so it remains accessable outside this scope
-        response = resp;
-        // Check for redirect
-        // @TODO Prevent looped redirects
-        if (response.statusCode === 301 || response.statusCode === 302 || response.statusCode === 303 || response.statusCode === 307) {
-          // Change URL to the redirect location
-          settings.url = response.headers.location;
-          var url = Url.parse(settings.url);
-          // Set host var in case it's used later
-          host = url.hostname;
-          // Options for the new request
-          var newOptions = {
-            hostname: url.hostname,
-            port: url.port,
-            path: url.path,
-            method: response.statusCode === 303 ? "GET" : settings.method,
-            headers: headers,
-            withCredentials: self.withCredentials
-          };
-
-          // Issue the new request
-          request = doRequest(newOptions, responseHandler).on("error", errorHandler);
-          request.end();
-          // @TODO Check if an XHR event needs to be fired here
-          return;
-        }
-
-        response.setEncoding("utf8");
-
-        setState(self.HEADERS_RECEIVED);
-        self.status = response.statusCode;
-
-        response.on("data", function(chunk) {
-          // Make sure there's some data
-          if (chunk) {
-            self.responseText += chunk;
-          }
-          // Don't emit state changes if the connection has been aborted.
-          if (sendFlag) {
-            setState(self.LOADING);
-          }
-        });
-
-        response.on("end", function() {
-          if (sendFlag) {
-            // Discard the end event if the connection has been aborted
-            setState(self.DONE);
-            sendFlag = false;
-          }
-        });
-
-        response.on("error", function(error) {
-          self.handleError(error);
-        });
-      };
-
-      // Error handler for the request
-      var errorHandler = function errorHandler(error) {
-        self.handleError(error);
-      };
-
-      // Create the request
-      request = doRequest(options, responseHandler).on("error", errorHandler);
-
-      // Node 0.4 and later won't accept empty data. Make sure it's needed.
-      if (data) {
-        request.write(data);
-      }
-
-      request.end();
-
-      self.dispatchEvent("loadstart");
-    } else { // Synchronous
-      // Create a temporary file for communication with the other Node process
-      var contentFile = ".node-xmlhttprequest-content-" + process.pid;
-      var syncFile = ".node-xmlhttprequest-sync-" + process.pid;
-      fs.writeFileSync(syncFile, "", "utf8");
-      // The async request the other Node process executes
-      var execString = "var http = require('http'), https = require('https'), fs = require('fs');"
-        + "var doRequest = http" + (ssl ? "s" : "") + ".request;"
-        + "var options = " + JSON.stringify(options) + ";"
-        + "var responseText = '';"
-        + "var req = doRequest(options, function(response) {"
-        + "response.setEncoding('utf8');"
-        + "response.on('data', function(chunk) {"
-        + "  responseText += chunk;"
-        + "});"
-        + "response.on('end', function() {"
-        + "fs.writeFileSync('" + contentFile + "', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText}}), 'utf8');"
-        + "fs.unlinkSync('" + syncFile + "');"
-        + "});"
-        + "response.on('error', function(error) {"
-        + "fs.writeFileSync('" + contentFile + "', JSON.stringify({err: error}), 'utf8');"
-        + "fs.unlinkSync('" + syncFile + "');"
-        + "});"
-        + "}).on('error', function(error) {"
-        + "fs.writeFileSync('" + contentFile + "', JSON.stringify({err: error}), 'utf8');"
-        + "fs.unlinkSync('" + syncFile + "');"
-        + "});"
-        + (data ? "req.write('" + JSON.stringify(data).slice(1,-1).replace(/'/g, "\\'") + "');":"")
-        + "req.end();";
-      // Start the other Node Process, executing this string
-      var syncProc = spawn(process.argv[0], ["-e", execString]);
-      while(fs.existsSync(syncFile)) {
-        // Wait while the sync file is empty
-      }
-      var resp = JSON.parse(fs.readFileSync(contentFile, 'utf8'));
-      // Kill the child process once the file has data
-      syncProc.stdin.end();
-      // Remove the temporary file
-      fs.unlinkSync(contentFile);
-
-      if (resp.err) {
-        self.handleError(resp.err);
-      } else {
-        response = resp.data;
-        self.status = resp.data.statusCode;
-        self.responseText = resp.data.text;
-        setState(self.DONE);
-      }
-    }
-  };
-
-  /**
-   * Called when an error is encountered to deal with it.
-   */
-  this.handleError = function(error) {
-    this.status = 0;
-    this.statusText = error;
-    this.responseText = error.stack;
-    errorFlag = true;
-    setState(this.DONE);
-    this.dispatchEvent('error');
-  };
-
-  /**
-   * Aborts a request.
-   */
-  this.abort = function() {
-    if (request) {
-      request.abort();
-      request = null;
-    }
-
-    headers = defaultHeaders;
-    this.status = 0;
-    this.responseText = "";
-    this.responseXML = "";
-
-    errorFlag = true;
-
-    if (this.readyState !== this.UNSENT
-        && (this.readyState !== this.OPENED || sendFlag)
-        && this.readyState !== this.DONE) {
-      sendFlag = false;
-      setState(this.DONE);
-    }
-    this.readyState = this.UNSENT;
-    this.dispatchEvent('abort');
-  };
-
-  /**
-   * Adds an event listener. Preferred method of binding to events.
-   */
-  this.addEventListener = function(event, callback) {
-    if (!(event in listeners)) {
-      listeners[event] = [];
-    }
-    // Currently allows duplicate callbacks. Should it?
-    listeners[event].push(callback);
-  };
-
-  /**
-   * Remove an event callback that has already been bound.
-   * Only works on the matching funciton, cannot be a copy.
-   */
-  this.removeEventListener = function(event, callback) {
-    if (event in listeners) {
-      // Filter will return a new array with the callback removed
-      listeners[event] = listeners[event].filter(function(ev) {
-        return ev !== callback;
-      });
-    }
-  };
-
-  /**
-   * Dispatch any events, including both "on" methods and events attached using addEventListener.
-   */
-  this.dispatchEvent = function(event) {
-    if (typeof self["on" + event] === "function") {
-      self["on" + event]();
-    }
-    if (event in listeners) {
-      for (var i = 0, len = listeners[event].length; i < len; i++) {
-        listeners[event][i].call(self);
-      }
-    }
-  };
-
-  /**
-   * Changes readyState and calls onreadystatechange.
-   *
-   * @param int state New state
-   */
-  var setState = function(state) {
-    if (state == self.LOADING || self.readyState !== state) {
-      self.readyState = state;
-
-      if (settings.async || self.readyState < self.OPENED || self.readyState === self.DONE) {
-        self.dispatchEvent("readystatechange");
-      }
-
-      if (self.readyState === self.DONE && !errorFlag) {
-        self.dispatchEvent("load");
-        // @TODO figure out InspectorInstrumentation::didLoadXHR(cookie)
-        self.dispatchEvent("loadend");
-      }
-    }
-  };
-};
+var Url=require("url"),spawn=require("child_process").spawn,fs=require("fs");exports.XMLHttpRequest=function(){"use strict";var e,t,s=this,r=require("http"),n=require("https"),o={},a=!1,i={"User-Agent":"node-XMLHttpRequest",Accept:"*/*"},h={},d={},u=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","content-transfer-encoding","cookie","cookie2","date","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"],c=["TRACE","TRACK","CONNECT"],f=!1,l=!1,p={};this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.readyState=this.UNSENT,this.onreadystatechange=null,this.responseText="",this.responseXML="",this.status=null,this.statusText=null,this.withCredentials=!1;this.open=function(e,t,s,r,n){if(this.abort(),l=!1,!function(e){return e&&-1===c.indexOf(e)}(e))throw new Error("SecurityError: Request method not allowed");o={method:e,url:t.toString(),async:"boolean"!=typeof s||s,user:r||null,password:n||null},E(this.OPENED)},this.setDisableHeaderCheck=function(e){a=e},this.setRequestHeader=function(e,t){if(this.readyState!==this.OPENED)throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");if(function(e){return a||e&&-1===u.indexOf(e.toLowerCase())}(e)){if(f)throw new Error("INVALID_STATE_ERR: send flag is true");e=d[e.toLowerCase()]||e,d[e.toLowerCase()]=e,h[e]=h[e]?h[e]+", "+t:t}else console.warn('Refused to set unsafe header "'+e+'"')},this.getResponseHeader=function(e){return"string"==typeof e&&this.readyState>this.OPENED&&t&&t.headers&&t.headers[e.toLowerCase()]&&!l?t.headers[e.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||l)return"";var e="";for(var s in t.headers)"set-cookie"!==s&&"set-cookie2"!==s&&(e+=s+": "+t.headers[s]+"\r\n");return e.substr(0,e.length-2)},this.getRequestHeader=function(e){return"string"==typeof e&&d[e.toLowerCase()]?h[d[e.toLowerCase()]]:""},this.send=function(a){if(this.readyState!==this.OPENED)throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");if(f)throw new Error("INVALID_STATE_ERR: send has already been called");var u,c=!1,p=!1,y=Url.parse(o.url);switch(y.protocol){case"https:":c=!0;case"http:":u=y.hostname;break;case"file:":p=!0;break;case void 0:case null:case"":u="localhost";break;default:throw new Error("Protocol not supported.")}if(p){if("GET"!==o.method)throw new Error("XMLHttpRequest: Only GET method is supported");if(o.async)fs.readFile(y.pathname,"utf8",(function(e,t){e?s.handleError(e):(s.status=200,s.responseText=t,E(s.DONE))}));else try{this.responseText=fs.readFileSync(y.pathname,"utf8"),this.status=200,E(s.DONE)}catch(e){this.handleError(e)}}else{var S=y.port||(c?443:80),w=y.pathname+(y.search?y.search:"");for(var N in i)d[N.toLowerCase()]||(h[N]=i[N]);if(h.Host=u,c&&443===S||80===S||(h.Host+=":"+y.port),o.user){void 0===o.password&&(o.password="");var v=new Buffer(o.user+":"+o.password);h.Authorization="Basic "+v.toString("base64")}"GET"===o.method||"HEAD"===o.method?a=null:a?(h["Content-Length"]=Buffer.isBuffer(a)?a.length:Buffer.byteLength(a),h["Content-Type"]||(h["Content-Type"]="text/plain;charset=UTF-8")):"POST"===o.method&&(h["Content-Length"]=0);var T={host:u,port:S,path:w,method:o.method,headers:h,agent:!1,withCredentials:s.withCredentials};if(l=!1,o.async){var g=c?n.request:r.request;f=!0,s.dispatchEvent("readystatechange");var C=function(e){s.handleError(e)};e=g(T,(function r(n){if(301!==(t=n).statusCode&&302!==t.statusCode&&303!==t.statusCode&&307!==t.statusCode)t.setEncoding("utf8"),E(s.HEADERS_RECEIVED),s.status=t.statusCode,t.on("data",(function(e){e&&(s.responseText+=e),f&&E(s.LOADING)})),t.on("end",(function(){f&&(E(s.DONE),f=!1)})),t.on("error",(function(e){s.handleError(e)}));else{o.url=t.headers.location;var a=Url.parse(o.url);u=a.hostname;var i={hostname:a.hostname,port:a.port,path:a.path,method:303===t.statusCode?"GET":o.method,headers:h,withCredentials:s.withCredentials};(e=g(i,r).on("error",C)).end()}})).on("error",C),a&&e.write(a),e.end(),s.dispatchEvent("loadstart")}else{var D=".node-xmlhttprequest-content-"+process.pid,O=".node-xmlhttprequest-sync-"+process.pid;fs.writeFileSync(O,"","utf8");for(var R="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(c?"s":"")+".request;var options = "+JSON.stringify(T)+";var responseText = '';var req = doRequest(options, function(response) {response.setEncoding('utf8');response.on('data', function(chunk) {  responseText += chunk;});response.on('end', function() {fs.writeFileSync('"+D+"', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText}}), 'utf8');fs.unlinkSync('"+O+"');});response.on('error', function(error) {fs.writeFileSync('"+D+"', JSON.stringify({err: error}), 'utf8');fs.unlinkSync('"+O+"');});}).on('error', function(error) {fs.writeFileSync('"+D+"', JSON.stringify({err: error}), 'utf8');fs.unlinkSync('"+O+"');});"+(a?"req.write('"+JSON.stringify(a).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",q=spawn(process.argv[0],["-e",R]);fs.existsSync(O););var L=JSON.parse(fs.readFileSync(D,"utf8"));q.stdin.end(),fs.unlinkSync(D),L.err?s.handleError(L.err):(t=L.data,s.status=L.data.statusCode,s.responseText=L.data.text,E(s.DONE))}}},this.handleError=function(e){this.status=0,this.statusText=e,this.responseText=e.stack,l=!0,E(this.DONE),this.dispatchEvent("error")},this.abort=function(){e&&(e.abort(),e=null),h=i,this.status=0,this.responseText="",this.responseXML="",l=!0,this.readyState===this.UNSENT||this.readyState===this.OPENED&&!f||this.readyState===this.DONE||(f=!1,E(this.DONE)),this.readyState=this.UNSENT,this.dispatchEvent("abort")},this.addEventListener=function(e,t){e in p||(p[e]=[]),p[e].push(t)},this.removeEventListener=function(e,t){e in p&&(p[e]=p[e].filter((function(e){return e!==t})))},this.dispatchEvent=function(e){if("function"==typeof s["on"+e]&&s["on"+e](),e in p)for(var t=0,r=p[e].length;t<r;t++)p[e][t].call(s)};var E=function(e){e!=s.LOADING&&s.readyState===e||(s.readyState=e,(o.async||s.readyState<s.OPENED||s.readyState===s.DONE)&&s.dispatchEvent("readystatechange"),s.readyState!==s.DONE||l||(s.dispatchEvent("load"),s.dispatchEvent("loadend")))}};
\ No newline at end of file
index 727362a..8676913 100644 (file)
@@ -1,188 +1 @@
-var fs = require('fs')
-var path = require('path')
-var util = require('util')
-
-function Y18N (opts) {
-  // configurable options.
-  opts = opts || {}
-  this.directory = opts.directory || './locales'
-  this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true
-  this.locale = opts.locale || 'en'
-  this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true
-
-  // internal stuff.
-  this.cache = Object.create(null)
-  this.writeQueue = []
-}
-
-Y18N.prototype.__ = function () {
-  if (typeof arguments[0] !== 'string') {
-    return this._taggedLiteral.apply(this, arguments)
-  }
-  var args = Array.prototype.slice.call(arguments)
-  var str = args.shift()
-  var cb = function () {} // start with noop.
-
-  if (typeof args[args.length - 1] === 'function') cb = args.pop()
-  cb = cb || function () {} // noop.
-
-  if (!this.cache[this.locale]) this._readLocaleFile()
-
-  // we've observed a new string, update the language file.
-  if (!this.cache[this.locale][str] && this.updateFiles) {
-    this.cache[this.locale][str] = str
-
-    // include the current directory and locale,
-    // since these values could change before the
-    // write is performed.
-    this._enqueueWrite([this.directory, this.locale, cb])
-  } else {
-    cb()
-  }
-
-  return util.format.apply(util, [this.cache[this.locale][str] || str].concat(args))
-}
-
-Y18N.prototype._taggedLiteral = function (parts) {
-  var args = arguments
-  var str = ''
-  parts.forEach(function (part, i) {
-    var arg = args[i + 1]
-    str += part
-    if (typeof arg !== 'undefined') {
-      str += '%s'
-    }
-  })
-  return this.__.apply(null, [str].concat([].slice.call(arguments, 1)))
-}
-
-Y18N.prototype._enqueueWrite = function (work) {
-  this.writeQueue.push(work)
-  if (this.writeQueue.length === 1) this._processWriteQueue()
-}
-
-Y18N.prototype._processWriteQueue = function () {
-  var _this = this
-  var work = this.writeQueue[0]
-
-  // destructure the enqueued work.
-  var directory = work[0]
-  var locale = work[1]
-  var cb = work[2]
-
-  var languageFile = this._resolveLocaleFile(directory, locale)
-  var serializedLocale = JSON.stringify(this.cache[locale], null, 2)
-
-  fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) {
-    _this.writeQueue.shift()
-    if (_this.writeQueue.length > 0) _this._processWriteQueue()
-    cb(err)
-  })
-}
-
-Y18N.prototype._readLocaleFile = function () {
-  var localeLookup = {}
-  var languageFile = this._resolveLocaleFile(this.directory, this.locale)
-
-  try {
-    localeLookup = JSON.parse(fs.readFileSync(languageFile, 'utf-8'))
-  } catch (err) {
-    if (err instanceof SyntaxError) {
-      err.message = 'syntax error in ' + languageFile
-    }
-
-    if (err.code === 'ENOENT') localeLookup = {}
-    else throw err
-  }
-
-  this.cache[this.locale] = localeLookup
-}
-
-Y18N.prototype._resolveLocaleFile = function (directory, locale) {
-  var file = path.resolve(directory, './', locale + '.json')
-  if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) {
-    // attempt fallback to language only
-    var languageFile = path.resolve(directory, './', locale.split('_')[0] + '.json')
-    if (this._fileExistsSync(languageFile)) file = languageFile
-  }
-  return file
-}
-
-// this only exists because fs.existsSync() "will be deprecated"
-// see https://nodejs.org/api/fs.html#fs_fs_existssync_path
-Y18N.prototype._fileExistsSync = function (file) {
-  try {
-    return fs.statSync(file).isFile()
-  } catch (err) {
-    return false
-  }
-}
-
-Y18N.prototype.__n = function () {
-  var args = Array.prototype.slice.call(arguments)
-  var singular = args.shift()
-  var plural = args.shift()
-  var quantity = args.shift()
-
-  var cb = function () {} // start with noop.
-  if (typeof args[args.length - 1] === 'function') cb = args.pop()
-
-  if (!this.cache[this.locale]) this._readLocaleFile()
-
-  var str = quantity === 1 ? singular : plural
-  if (this.cache[this.locale][singular]) {
-    str = this.cache[this.locale][singular][quantity === 1 ? 'one' : 'other']
-  }
-
-  // we've observed a new string, update the language file.
-  if (!this.cache[this.locale][singular] && this.updateFiles) {
-    this.cache[this.locale][singular] = {
-      one: singular,
-      other: plural
-    }
-
-    // include the current directory and locale,
-    // since these values could change before the
-    // write is performed.
-    this._enqueueWrite([this.directory, this.locale, cb])
-  } else {
-    cb()
-  }
-
-  // if a %d placeholder is provided, add quantity
-  // to the arguments expanded by util.format.
-  var values = [str]
-  if (~str.indexOf('%d')) values.push(quantity)
-
-  return util.format.apply(util, values.concat(args))
-}
-
-Y18N.prototype.setLocale = function (locale) {
-  this.locale = locale
-}
-
-Y18N.prototype.getLocale = function () {
-  return this.locale
-}
-
-Y18N.prototype.updateLocale = function (obj) {
-  if (!this.cache[this.locale]) this._readLocaleFile()
-
-  for (var key in obj) {
-    this.cache[this.locale][key] = obj[key]
-  }
-}
-
-module.exports = function (opts) {
-  var y18n = new Y18N(opts)
-
-  // bind all functions to y18n, so that
-  // they can be used in isolation.
-  for (var key in y18n) {
-    if (typeof y18n[key] === 'function') {
-      y18n[key] = y18n[key].bind(y18n)
-    }
-  }
-
-  return y18n
-}
+var fs=require("fs"),path=require("path"),util=require("util");function Y18N(e){e=e||{},this.directory=e.directory||"./locales",this.updateFiles="boolean"!=typeof e.updateFiles||e.updateFiles,this.locale=e.locale||"en",this.fallbackToLanguage="boolean"!=typeof e.fallbackToLanguage||e.fallbackToLanguage,this.cache=Object.create(null),this.writeQueue=[]}Y18N.prototype.__=function(){if("string"!=typeof arguments[0])return this._taggedLiteral.apply(this,arguments);var e=Array.prototype.slice.call(arguments),t=e.shift(),i=function(){};return"function"==typeof e[e.length-1]&&(i=e.pop()),i=i||function(){},this.cache[this.locale]||this._readLocaleFile(),!this.cache[this.locale][t]&&this.updateFiles?(this.cache[this.locale][t]=t,this._enqueueWrite([this.directory,this.locale,i])):i(),util.format.apply(util,[this.cache[this.locale][t]||t].concat(e))},Y18N.prototype._taggedLiteral=function(e){var t=arguments,i="";return e.forEach((function(e,o){var a=t[o+1];i+=e,void 0!==a&&(i+="%s")})),this.__.apply(null,[i].concat([].slice.call(arguments,1)))},Y18N.prototype._enqueueWrite=function(e){this.writeQueue.push(e),1===this.writeQueue.length&&this._processWriteQueue()},Y18N.prototype._processWriteQueue=function(){var e=this,t=this.writeQueue[0],i=t[0],o=t[1],a=t[2],c=this._resolveLocaleFile(i,o),l=JSON.stringify(this.cache[o],null,2);fs.writeFile(c,l,"utf-8",(function(t){e.writeQueue.shift(),e.writeQueue.length>0&&e._processWriteQueue(),a(t)}))},Y18N.prototype._readLocaleFile=function(){var e={},t=this._resolveLocaleFile(this.directory,this.locale);try{e=JSON.parse(fs.readFileSync(t,"utf-8"))}catch(i){if(i instanceof SyntaxError&&(i.message="syntax error in "+t),"ENOENT"!==i.code)throw i;e={}}this.cache[this.locale]=e},Y18N.prototype._resolveLocaleFile=function(e,t){var i=path.resolve(e,"./",t+".json");if(this.fallbackToLanguage&&!this._fileExistsSync(i)&&~t.lastIndexOf("_")){var o=path.resolve(e,"./",t.split("_")[0]+".json");this._fileExistsSync(o)&&(i=o)}return i},Y18N.prototype._fileExistsSync=function(e){try{return fs.statSync(e).isFile()}catch(e){return!1}},Y18N.prototype.__n=function(){var e=Array.prototype.slice.call(arguments),t=e.shift(),i=e.shift(),o=e.shift(),a=function(){};"function"==typeof e[e.length-1]&&(a=e.pop()),this.cache[this.locale]||this._readLocaleFile();var c=1===o?t:i;this.cache[this.locale][t]&&(c=this.cache[this.locale][t][1===o?"one":"other"]),!this.cache[this.locale][t]&&this.updateFiles?(this.cache[this.locale][t]={one:t,other:i},this._enqueueWrite([this.directory,this.locale,a])):a();var l=[c];return~c.indexOf("%d")&&l.push(o),util.format.apply(util,l.concat(e))},Y18N.prototype.setLocale=function(e){this.locale=e},Y18N.prototype.getLocale=function(){return this.locale},Y18N.prototype.updateLocale=function(e){for(var t in this.cache[this.locale]||this._readLocaleFile(),e)this.cache[this.locale][t]=e[t]},module.exports=function(e){var t=new Y18N(e);for(var i in t)"function"==typeof t[i]&&(t[i]=t[i].bind(t));return t};
\ No newline at end of file
index f9ee824..5d0f116 100644 (file)
@@ -1,916 +1 @@
-var camelCase = require('camelcase')
-var decamelize = require('decamelize')
-var path = require('path')
-var tokenizeArgString = require('./lib/tokenize-arg-string')
-var util = require('util')
-
-function parse (args, opts) {
-  if (!opts) opts = {}
-  // allow a string argument to be passed in rather
-  // than an argv array.
-  args = tokenizeArgString(args)
-
-  // aliases might have transitive relationships, normalize this.
-  var aliases = combineAliases(opts.alias || {})
-  var configuration = Object.assign({
-    'short-option-groups': true,
-    'camel-case-expansion': true,
-    'dot-notation': true,
-    'parse-numbers': true,
-    'boolean-negation': true,
-    'negation-prefix': 'no-',
-    'duplicate-arguments-array': true,
-    'flatten-duplicate-arrays': true,
-    'populate--': false,
-    'combine-arrays': false,
-    'set-placeholder-key': false,
-    'halt-at-non-option': false,
-    'strip-aliased': false,
-    'strip-dashed': false
-  }, opts.configuration)
-  var defaults = opts.default || {}
-  var configObjects = opts.configObjects || []
-  var envPrefix = opts.envPrefix
-  var notFlagsOption = configuration['populate--']
-  var notFlagsArgv = notFlagsOption ? '--' : '_'
-  var newAliases = {}
-  // allow a i18n handler to be passed in, default to a fake one (util.format).
-  var __ = opts.__ || util.format
-  var error = null
-  var flags = {
-    aliases: {},
-    arrays: {},
-    bools: {},
-    strings: {},
-    numbers: {},
-    counts: {},
-    normalize: {},
-    configs: {},
-    defaulted: {},
-    nargs: {},
-    coercions: {},
-    keys: []
-  }
-  var negative = /^-[0-9]+(\.[0-9]+)?/
-  var negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)')
-
-  ;[].concat(opts.array).filter(Boolean).forEach(function (opt) {
-    var key = opt.key || opt
-
-    // assign to flags[bools|strings|numbers]
-    const assignment = Object.keys(opt).map(function (key) {
-      return ({
-        boolean: 'bools',
-        string: 'strings',
-        number: 'numbers'
-      })[key]
-    }).filter(Boolean).pop()
-
-    // assign key to be coerced
-    if (assignment) {
-      flags[assignment][key] = true
-    }
-
-    flags.arrays[key] = true
-    flags.keys.push(key)
-  })
-
-  ;[].concat(opts.boolean).filter(Boolean).forEach(function (key) {
-    flags.bools[key] = true
-    flags.keys.push(key)
-  })
-
-  ;[].concat(opts.string).filter(Boolean).forEach(function (key) {
-    flags.strings[key] = true
-    flags.keys.push(key)
-  })
-
-  ;[].concat(opts.number).filter(Boolean).forEach(function (key) {
-    flags.numbers[key] = true
-    flags.keys.push(key)
-  })
-
-  ;[].concat(opts.count).filter(Boolean).forEach(function (key) {
-    flags.counts[key] = true
-    flags.keys.push(key)
-  })
-
-  ;[].concat(opts.normalize).filter(Boolean).forEach(function (key) {
-    flags.normalize[key] = true
-    flags.keys.push(key)
-  })
-
-  Object.keys(opts.narg || {}).forEach(function (k) {
-    flags.nargs[k] = opts.narg[k]
-    flags.keys.push(k)
-  })
-
-  Object.keys(opts.coerce || {}).forEach(function (k) {
-    flags.coercions[k] = opts.coerce[k]
-    flags.keys.push(k)
-  })
-
-  if (Array.isArray(opts.config) || typeof opts.config === 'string') {
-    ;[].concat(opts.config).filter(Boolean).forEach(function (key) {
-      flags.configs[key] = true
-    })
-  } else {
-    Object.keys(opts.config || {}).forEach(function (k) {
-      flags.configs[k] = opts.config[k]
-    })
-  }
-
-  // create a lookup table that takes into account all
-  // combinations of aliases: {f: ['foo'], foo: ['f']}
-  extendAliases(opts.key, aliases, opts.default, flags.arrays)
-
-  // apply default values to all aliases.
-  Object.keys(defaults).forEach(function (key) {
-    (flags.aliases[key] || []).forEach(function (alias) {
-      defaults[alias] = defaults[key]
-    })
-  })
-
-  var argv = { _: [] }
-
-  Object.keys(flags.bools).forEach(function (key) {
-    if (Object.prototype.hasOwnProperty.call(defaults, key)) {
-      setArg(key, defaults[key])
-      setDefaulted(key)
-    }
-  })
-
-  var notFlags = []
-
-  for (var i = 0; i < args.length; i++) {
-    var arg = args[i]
-    var broken
-    var key
-    var letters
-    var m
-    var next
-    var value
-
-    // -- separated by =
-    if (arg.match(/^--.+=/) || (
-      !configuration['short-option-groups'] && arg.match(/^-.+=/)
-    )) {
-      // Using [\s\S] instead of . because js doesn't support the
-      // 'dotall' regex modifier. See:
-      // http://stackoverflow.com/a/1068308/13216
-      m = arg.match(/^--?([^=]+)=([\s\S]*)$/)
-
-      // nargs format = '--f=monkey washing cat'
-      if (checkAllAliases(m[1], flags.nargs)) {
-        args.splice(i + 1, 0, m[2])
-        i = eatNargs(i, m[1], args)
-      // arrays format = '--f=a b c'
-      } else if (checkAllAliases(m[1], flags.arrays) && args.length > i + 1) {
-        args.splice(i + 1, 0, m[2])
-        i = eatArray(i, m[1], args)
-      } else {
-        setArg(m[1], m[2])
-      }
-    } else if (arg.match(negatedBoolean) && configuration['boolean-negation']) {
-      key = arg.match(negatedBoolean)[1]
-      setArg(key, false)
-
-    // -- seperated by space.
-    } else if (arg.match(/^--.+/) || (
-      !configuration['short-option-groups'] && arg.match(/^-[^-]+/)
-    )) {
-      key = arg.match(/^--?(.+)/)[1]
-
-      // nargs format = '--foo a b c'
-      if (checkAllAliases(key, flags.nargs)) {
-        i = eatNargs(i, key, args)
-      // array format = '--foo a b c'
-      } else if (checkAllAliases(key, flags.arrays) && args.length > i + 1) {
-        i = eatArray(i, key, args)
-      } else {
-        next = flags.nargs[key] === 0 ? undefined : args[i + 1]
-
-        if (next !== undefined && (!next.match(/^-/) ||
-          next.match(negative)) &&
-          !checkAllAliases(key, flags.bools) &&
-          !checkAllAliases(key, flags.counts)) {
-          setArg(key, next)
-          i++
-        } else if (/^(true|false)$/.test(next)) {
-          setArg(key, next)
-          i++
-        } else {
-          setArg(key, defaultValue(key))
-        }
-      }
-
-    // dot-notation flag seperated by '='.
-    } else if (arg.match(/^-.\..+=/)) {
-      m = arg.match(/^-([^=]+)=([\s\S]*)$/)
-      setArg(m[1], m[2])
-
-    // dot-notation flag seperated by space.
-    } else if (arg.match(/^-.\..+/)) {
-      next = args[i + 1]
-      key = arg.match(/^-(.\..+)/)[1]
-
-      if (next !== undefined && !next.match(/^-/) &&
-        !checkAllAliases(key, flags.bools) &&
-        !checkAllAliases(key, flags.counts)) {
-        setArg(key, next)
-        i++
-      } else {
-        setArg(key, defaultValue(key))
-      }
-    } else if (arg.match(/^-[^-]+/) && !arg.match(negative)) {
-      letters = arg.slice(1, -1).split('')
-      broken = false
-
-      for (var j = 0; j < letters.length; j++) {
-        next = arg.slice(j + 2)
-
-        if (letters[j + 1] && letters[j + 1] === '=') {
-          value = arg.slice(j + 3)
-          key = letters[j]
-
-          // nargs format = '-f=monkey washing cat'
-          if (checkAllAliases(key, flags.nargs)) {
-            args.splice(i + 1, 0, value)
-            i = eatNargs(i, key, args)
-          // array format = '-f=a b c'
-          } else if (checkAllAliases(key, flags.arrays) && args.length > i + 1) {
-            args.splice(i + 1, 0, value)
-            i = eatArray(i, key, args)
-          } else {
-            setArg(key, value)
-          }
-
-          broken = true
-          break
-        }
-
-        if (next === '-') {
-          setArg(letters[j], next)
-          continue
-        }
-
-        // current letter is an alphabetic character and next value is a number
-        if (/[A-Za-z]/.test(letters[j]) &&
-          /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
-          setArg(letters[j], next)
-          broken = true
-          break
-        }
-
-        if (letters[j + 1] && letters[j + 1].match(/\W/)) {
-          setArg(letters[j], next)
-          broken = true
-          break
-        } else {
-          setArg(letters[j], defaultValue(letters[j]))
-        }
-      }
-
-      key = arg.slice(-1)[0]
-
-      if (!broken && key !== '-') {
-        // nargs format = '-f a b c'
-        if (checkAllAliases(key, flags.nargs)) {
-          i = eatNargs(i, key, args)
-        // array format = '-f a b c'
-        } else if (checkAllAliases(key, flags.arrays) && args.length > i + 1) {
-          i = eatArray(i, key, args)
-        } else {
-          next = args[i + 1]
-
-          if (next !== undefined && (!/^(-|--)[^-]/.test(next) ||
-            next.match(negative)) &&
-            !checkAllAliases(key, flags.bools) &&
-            !checkAllAliases(key, flags.counts)) {
-            setArg(key, next)
-            i++
-          } else if (/^(true|false)$/.test(next)) {
-            setArg(key, next)
-            i++
-          } else {
-            setArg(key, defaultValue(key))
-          }
-        }
-      }
-    } else if (arg === '--') {
-      notFlags = args.slice(i + 1)
-      break
-    } else if (configuration['halt-at-non-option']) {
-      notFlags = args.slice(i)
-      break
-    } else {
-      argv._.push(maybeCoerceNumber('_', arg))
-    }
-  }
-
-  // order of precedence:
-  // 1. command line arg
-  // 2. value from env var
-  // 3. value from config file
-  // 4. value from config objects
-  // 5. configured default value
-  applyEnvVars(argv, true) // special case: check env vars that point to config file
-  applyEnvVars(argv, false)
-  setConfig(argv)
-  setConfigObjects()
-  applyDefaultsAndAliases(argv, flags.aliases, defaults)
-  applyCoercions(argv)
-  if (configuration['set-placeholder-key']) setPlaceholderKeys(argv)
-
-  // for any counts either not in args or without an explicit default, set to 0
-  Object.keys(flags.counts).forEach(function (key) {
-    if (!hasKey(argv, key.split('.'))) setArg(key, 0)
-  })
-
-  // '--' defaults to undefined.
-  if (notFlagsOption && notFlags.length) argv[notFlagsArgv] = []
-  notFlags.forEach(function (key) {
-    argv[notFlagsArgv].push(key)
-  })
-
-  if (configuration['camel-case-expansion'] && configuration['strip-dashed']) {
-    Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => {
-      delete argv[key]
-    })
-  }
-
-  if (configuration['strip-aliased']) {
-    // XXX Switch to [].concat(...Object.values(aliases)) once node.js 6 is dropped
-    ;[].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => {
-      if (configuration['camel-case-expansion']) {
-        delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')]
-      }
-
-      delete argv[alias]
-    })
-  }
-
-  // how many arguments should we consume, based
-  // on the nargs option?
-  function eatNargs (i, key, args) {
-    var ii
-    const toEat = checkAllAliases(key, flags.nargs)
-
-    // nargs will not consume flag arguments, e.g., -abc, --foo,
-    // and terminates when one is observed.
-    var available = 0
-    for (ii = i + 1; ii < args.length; ii++) {
-      if (!args[ii].match(/^-[^0-9]/)) available++
-      else break
-    }
-
-    if (available < toEat) error = Error(__('Not enough arguments following: %s', key))
-
-    const consumed = Math.min(available, toEat)
-    for (ii = i + 1; ii < (consumed + i + 1); ii++) {
-      setArg(key, args[ii])
-    }
-
-    return (i + consumed)
-  }
-
-  // if an option is an array, eat all non-hyphenated arguments
-  // following it... YUM!
-  // e.g., --foo apple banana cat becomes ["apple", "banana", "cat"]
-  function eatArray (i, key, args) {
-    var start = i + 1
-    var argsToSet = []
-    var multipleArrayFlag = i > 0
-    for (var ii = i + 1; ii < args.length; ii++) {
-      if (/^-/.test(args[ii]) && !negative.test(args[ii])) {
-        if (ii === start) {
-          setArg(key, defaultForType('array'))
-        }
-        multipleArrayFlag = true
-        break
-      }
-      i = ii
-      argsToSet.push(args[ii])
-    }
-    if (multipleArrayFlag) {
-      setArg(key, argsToSet.map(function (arg) {
-        return processValue(key, arg)
-      }))
-    } else {
-      argsToSet.forEach(function (arg) {
-        setArg(key, arg)
-      })
-    }
-
-    return i
-  }
-
-  function setArg (key, val) {
-    unsetDefaulted(key)
-
-    if (/-/.test(key) && configuration['camel-case-expansion']) {
-      var alias = key.split('.').map(function (prop) {
-        return camelCase(prop)
-      }).join('.')
-      addNewAlias(key, alias)
-    }
-
-    var value = processValue(key, val)
-
-    var splitKey = key.split('.')
-    setKey(argv, splitKey, value)
-
-    // handle populating aliases of the full key
-    if (flags.aliases[key] && flags.aliases[key].forEach) {
-      flags.aliases[key].forEach(function (x) {
-        x = x.split('.')
-        setKey(argv, x, value)
-      })
-    }
-
-    // handle populating aliases of the first element of the dot-notation key
-    if (splitKey.length > 1 && configuration['dot-notation']) {
-      ;(flags.aliases[splitKey[0]] || []).forEach(function (x) {
-        x = x.split('.')
-
-        // expand alias with nested objects in key
-        var a = [].concat(splitKey)
-        a.shift() // nuke the old key.
-        x = x.concat(a)
-
-        setKey(argv, x, value)
-      })
-    }
-
-    // Set normalize getter and setter when key is in 'normalize' but isn't an array
-    if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) {
-      var keys = [key].concat(flags.aliases[key] || [])
-      keys.forEach(function (key) {
-        argv.__defineSetter__(key, function (v) {
-          val = path.normalize(v)
-        })
-
-        argv.__defineGetter__(key, function () {
-          return typeof val === 'string' ? path.normalize(val) : val
-        })
-      })
-    }
-  }
-
-  function addNewAlias (key, alias) {
-    if (!(flags.aliases[key] && flags.aliases[key].length)) {
-      flags.aliases[key] = [alias]
-      newAliases[alias] = true
-    }
-    if (!(flags.aliases[alias] && flags.aliases[alias].length)) {
-      addNewAlias(alias, key)
-    }
-  }
-
-  function processValue (key, val) {
-    // strings may be quoted, clean this up as we assign values.
-    if (typeof val === 'string' &&
-      (val[0] === "'" || val[0] === '"') &&
-      val[val.length - 1] === val[0]
-    ) {
-      val = val.substring(1, val.length - 1)
-    }
-
-    // handle parsing boolean arguments --foo=true --bar false.
-    if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) {
-      if (typeof val === 'string') val = val === 'true'
-    }
-
-    var value = maybeCoerceNumber(key, val)
-
-    // increment a count given as arg (either no value or value parsed as boolean)
-    if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) {
-      value = increment
-    }
-
-    // Set normalized value when key is in 'normalize' and in 'arrays'
-    if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) {
-      if (Array.isArray(val)) value = val.map(path.normalize)
-      else value = path.normalize(val)
-    }
-    return value
-  }
-
-  function maybeCoerceNumber (key, value) {
-    if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.coercions)) {
-      const shouldCoerceNumber = isNumber(value) && configuration['parse-numbers'] && (
-        Number.isSafeInteger(Math.floor(value))
-      )
-      if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) value = Number(value)
-    }
-    return value
-  }
-
-  // set args from config.json file, this should be
-  // applied last so that defaults can be applied.
-  function setConfig (argv) {
-    var configLookup = {}
-
-    // expand defaults/aliases, in-case any happen to reference
-    // the config.json file.
-    applyDefaultsAndAliases(configLookup, flags.aliases, defaults)
-
-    Object.keys(flags.configs).forEach(function (configKey) {
-      var configPath = argv[configKey] || configLookup[configKey]
-      if (configPath) {
-        try {
-          var config = null
-          var resolvedConfigPath = path.resolve(process.cwd(), configPath)
-
-          if (typeof flags.configs[configKey] === 'function') {
-            try {
-              config = flags.configs[configKey](resolvedConfigPath)
-            } catch (e) {
-              config = e
-            }
-            if (config instanceof Error) {
-              error = config
-              return
-            }
-          } else {
-            config = require(resolvedConfigPath)
-          }
-
-          setConfigObject(config)
-        } catch (ex) {
-          if (argv[configKey]) error = Error(__('Invalid JSON config file: %s', configPath))
-        }
-      }
-    })
-  }
-
-  // set args from config object.
-  // it recursively checks nested objects.
-  function setConfigObject (config, prev) {
-    Object.keys(config).forEach(function (key) {
-      var value = config[key]
-      var fullKey = prev ? prev + '.' + key : key
-
-      // if the value is an inner object and we have dot-notation
-      // enabled, treat inner objects in config the same as
-      // heavily nested dot notations (foo.bar.apple).
-      if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) {
-        // if the value is an object but not an array, check nested object
-        setConfigObject(value, fullKey)
-      } else {
-        // setting arguments via CLI takes precedence over
-        // values within the config file.
-        if (!hasKey(argv, fullKey.split('.')) || (flags.defaulted[fullKey]) || (flags.arrays[fullKey] && configuration['combine-arrays'])) {
-          setArg(fullKey, value)
-        }
-      }
-    })
-  }
-
-  // set all config objects passed in opts
-  function setConfigObjects () {
-    if (typeof configObjects === 'undefined') return
-    configObjects.forEach(function (configObject) {
-      setConfigObject(configObject)
-    })
-  }
-
-  function applyEnvVars (argv, configOnly) {
-    if (typeof envPrefix === 'undefined') return
-
-    var prefix = typeof envPrefix === 'string' ? envPrefix : ''
-    Object.keys(process.env).forEach(function (envVar) {
-      if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) {
-        // get array of nested keys and convert them to camel case
-        var keys = envVar.split('__').map(function (key, i) {
-          if (i === 0) {
-            key = key.substring(prefix.length)
-          }
-          return camelCase(key)
-        })
-
-        if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && (!hasKey(argv, keys) || flags.defaulted[keys.join('.')])) {
-          setArg(keys.join('.'), process.env[envVar])
-        }
-      }
-    })
-  }
-
-  function applyCoercions (argv) {
-    var coerce
-    var applied = {}
-    Object.keys(argv).forEach(function (key) {
-      if (!applied.hasOwnProperty(key)) { // If we haven't already coerced this option via one of its aliases
-        coerce = checkAllAliases(key, flags.coercions)
-        if (typeof coerce === 'function') {
-          try {
-            var value = coerce(argv[key])
-            ;([].concat(flags.aliases[key] || [], key)).forEach(ali => {
-              applied[ali] = argv[ali] = value
-            })
-          } catch (err) {
-            error = err
-          }
-        }
-      }
-    })
-  }
-
-  function setPlaceholderKeys (argv) {
-    flags.keys.forEach((key) => {
-      // don't set placeholder keys for dot notation options 'foo.bar'.
-      if (~key.indexOf('.')) return
-      if (typeof argv[key] === 'undefined') argv[key] = undefined
-    })
-    return argv
-  }
-
-  function applyDefaultsAndAliases (obj, aliases, defaults) {
-    Object.keys(defaults).forEach(function (key) {
-      if (!hasKey(obj, key.split('.'))) {
-        setKey(obj, key.split('.'), defaults[key])
-
-        ;(aliases[key] || []).forEach(function (x) {
-          if (hasKey(obj, x.split('.'))) return
-          setKey(obj, x.split('.'), defaults[key])
-        })
-      }
-    })
-  }
-
-  function hasKey (obj, keys) {
-    var o = obj
-
-    if (!configuration['dot-notation']) keys = [keys.join('.')]
-
-    keys.slice(0, -1).forEach(function (key) {
-      o = (o[key] || {})
-    })
-
-    var key = keys[keys.length - 1]
-
-    if (typeof o !== 'object') return false
-    else return key in o
-  }
-
-  function setKey (obj, keys, value) {
-    var o = obj
-
-    if (!configuration['dot-notation']) keys = [keys.join('.')]
-
-    keys.slice(0, -1).forEach(function (key, index) {
-      // TODO(bcoe): in the next major version of yargs, switch to
-      // Object.create(null) for dot notation:
-      key = sanitizeKey(key)
-
-      if (typeof o === 'object' && o[key] === undefined) {
-        o[key] = {}
-      }
-
-      if (typeof o[key] !== 'object' || Array.isArray(o[key])) {
-        // ensure that o[key] is an array, and that the last item is an empty object.
-        if (Array.isArray(o[key])) {
-          o[key].push({})
-        } else {
-          o[key] = [o[key], {}]
-        }
-
-        // we want to update the empty object at the end of the o[key] array, so set o to that object
-        o = o[key][o[key].length - 1]
-      } else {
-        o = o[key]
-      }
-    })
-
-    // TODO(bcoe): in the next major version of yargs, switch to
-    // Object.create(null) for dot notation:
-    const key = sanitizeKey(keys[keys.length - 1])
-
-    const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays)
-    const isValueArray = Array.isArray(value)
-    let duplicate = configuration['duplicate-arguments-array']
-
-    // nargs has higher priority than duplicate
-    if (!duplicate && checkAllAliases(key, flags.nargs)) {
-      duplicate = true
-      if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) {
-        o[key] = undefined
-      }
-    }
-
-    if (value === increment) {
-      o[key] = increment(o[key])
-    } else if (Array.isArray(o[key])) {
-      if (duplicate && isTypeArray && isValueArray) {
-        o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value])
-      } else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) {
-        o[key] = value
-      } else {
-        o[key] = o[key].concat([value])
-      }
-    } else if (o[key] === undefined && isTypeArray) {
-      o[key] = isValueArray ? value : [value]
-    } else if (duplicate && !(o[key] === undefined || checkAllAliases(key, flags.bools) || checkAllAliases(keys.join('.'), flags.bools) || checkAllAliases(key, flags.counts))) {
-      o[key] = [ o[key], value ]
-    } else {
-      o[key] = value
-    }
-  }
-
-  // extend the aliases list with inferred aliases.
-  function extendAliases (...args) {
-    args.forEach(function (obj) {
-      Object.keys(obj || {}).forEach(function (key) {
-        // short-circuit if we've already added a key
-        // to the aliases array, for example it might
-        // exist in both 'opts.default' and 'opts.key'.
-        if (flags.aliases[key]) return
-
-        flags.aliases[key] = [].concat(aliases[key] || [])
-        // For "--option-name", also set argv.optionName
-        flags.aliases[key].concat(key).forEach(function (x) {
-          if (/-/.test(x) && configuration['camel-case-expansion']) {
-            var c = camelCase(x)
-            if (c !== key && flags.aliases[key].indexOf(c) === -1) {
-              flags.aliases[key].push(c)
-              newAliases[c] = true
-            }
-          }
-        })
-        // For "--optionName", also set argv['option-name']
-        flags.aliases[key].concat(key).forEach(function (x) {
-          if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) {
-            var c = decamelize(x, '-')
-            if (c !== key && flags.aliases[key].indexOf(c) === -1) {
-              flags.aliases[key].push(c)
-              newAliases[c] = true
-            }
-          }
-        })
-        flags.aliases[key].forEach(function (x) {
-          flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) {
-            return x !== y
-          }))
-        })
-      })
-    })
-  }
-
-  // check if a flag is set for any of a key's aliases.
-  function checkAllAliases (key, flag) {
-    var isSet = false
-    var toCheck = [].concat(flags.aliases[key] || [], key)
-
-    toCheck.forEach(function (key) {
-      if (flag[key]) isSet = flag[key]
-    })
-
-    return isSet
-  }
-
-  function setDefaulted (key) {
-    [].concat(flags.aliases[key] || [], key).forEach(function (k) {
-      flags.defaulted[k] = true
-    })
-  }
-
-  function unsetDefaulted (key) {
-    [].concat(flags.aliases[key] || [], key).forEach(function (k) {
-      delete flags.defaulted[k]
-    })
-  }
-
-  // make a best effor to pick a default value
-  // for an option based on name and type.
-  function defaultValue (key) {
-    if (!checkAllAliases(key, flags.bools) &&
-        !checkAllAliases(key, flags.counts) &&
-        `${key}` in defaults) {
-      return defaults[key]
-    } else {
-      return defaultForType(guessType(key))
-    }
-  }
-
-  // return a default value, given the type of a flag.,
-  // e.g., key of type 'string' will default to '', rather than 'true'.
-  function defaultForType (type) {
-    var def = {
-      boolean: true,
-      string: '',
-      number: undefined,
-      array: []
-    }
-
-    return def[type]
-  }
-
-  // given a flag, enforce a default type.
-  function guessType (key) {
-    var type = 'boolean'
-
-    if (checkAllAliases(key, flags.strings)) type = 'string'
-    else if (checkAllAliases(key, flags.numbers)) type = 'number'
-    else if (checkAllAliases(key, flags.arrays)) type = 'array'
-
-    return type
-  }
-
-  function isNumber (x) {
-    if (x === null || x === undefined) return false
-    // if loaded from config, may already be a number.
-    if (typeof x === 'number') return true
-    // hexadecimal.
-    if (/^0x[0-9a-f]+$/i.test(x)) return true
-    // don't treat 0123 as a number; as it drops the leading '0'.
-    if (x.length > 1 && x[0] === '0') return false
-    return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x)
-  }
-
-  function isUndefined (num) {
-    return num === undefined
-  }
-
-  return {
-    argv: argv,
-    error: error,
-    aliases: flags.aliases,
-    newAliases: newAliases,
-    configuration: configuration
-  }
-}
-
-// if any aliases reference each other, we should
-// merge them together.
-function combineAliases (aliases) {
-  var aliasArrays = []
-  var change = true
-  var combined = {}
-
-  // turn alias lookup hash {key: ['alias1', 'alias2']} into
-  // a simple array ['key', 'alias1', 'alias2']
-  Object.keys(aliases).forEach(function (key) {
-    aliasArrays.push(
-      [].concat(aliases[key], key)
-    )
-  })
-
-  // combine arrays until zero changes are
-  // made in an iteration.
-  while (change) {
-    change = false
-    for (var i = 0; i < aliasArrays.length; i++) {
-      for (var ii = i + 1; ii < aliasArrays.length; ii++) {
-        var intersect = aliasArrays[i].filter(function (v) {
-          return aliasArrays[ii].indexOf(v) !== -1
-        })
-
-        if (intersect.length) {
-          aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii])
-          aliasArrays.splice(ii, 1)
-          change = true
-          break
-        }
-      }
-    }
-  }
-
-  // map arrays back to the hash-lookup (de-dupe while
-  // we're at it).
-  aliasArrays.forEach(function (aliasArray) {
-    aliasArray = aliasArray.filter(function (v, i, self) {
-      return self.indexOf(v) === i
-    })
-    combined[aliasArray.pop()] = aliasArray
-  })
-
-  return combined
-}
-
-// this function should only be called when a count is given as an arg
-// it is NOT called to set a default value
-// thus we can start the count at 1 instead of 0
-function increment (orig) {
-  return orig !== undefined ? orig + 1 : 1
-}
-
-function Parser (args, opts) {
-  var result = parse(args.slice(), opts)
-
-  return result.argv
-}
-
-// parse arguments and return detailed
-// meta information, aliases, etc.
-Parser.detailed = function (args, opts) {
-  return parse(args.slice(), opts)
-}
-
-// TODO(bcoe): in the next major version of yargs, switch to
-// Object.create(null) for dot notation:
-function sanitizeKey (key) {
-  if (key === '__proto__') return '___proto___'
-  return key
-}
-
-module.exports = Parser
+var camelCase=require("camelcase"),decamelize=require("decamelize"),path=require("path"),tokenizeArgString=require("./lib/tokenize-arg-string"),util=require("util");function parse(e,n){n||(n={}),e=tokenizeArgString(e);var a=combineAliases(n.alias||{}),t=Object.assign({"short-option-groups":!0,"camel-case-expansion":!0,"dot-notation":!0,"parse-numbers":!0,"boolean-negation":!0,"negation-prefix":"no-","duplicate-arguments-array":!0,"flatten-duplicate-arrays":!0,"populate--":!1,"combine-arrays":!1,"set-placeholder-key":!1,"halt-at-non-option":!1,"strip-aliased":!1,"strip-dashed":!1},n.configuration),o=n.default||{},r=n.configObjects||[],i=n.envPrefix,s=t["populate--"],c=s?"--":"_",f={},l=n.__||util.format,u=null,h={aliases:{},arrays:{},bools:{},strings:{},numbers:{},counts:{},normalize:{},configs:{},defaulted:{},nargs:{},coercions:{},keys:[]},p=/^-[0-9]+(\.[0-9]+)?/,g=new RegExp("^--"+t["negation-prefix"]+"(.+)");[].concat(n.array).filter(Boolean).forEach((function(e){var n=e.key||e;const a=Object.keys(e).map((function(e){return{boolean:"bools",string:"strings",number:"numbers"}[e]})).filter(Boolean).pop();a&&(h[a][n]=!0),h.arrays[n]=!0,h.keys.push(n)})),[].concat(n.boolean).filter(Boolean).forEach((function(e){h.bools[e]=!0,h.keys.push(e)})),[].concat(n.string).filter(Boolean).forEach((function(e){h.strings[e]=!0,h.keys.push(e)})),[].concat(n.number).filter(Boolean).forEach((function(e){h.numbers[e]=!0,h.keys.push(e)})),[].concat(n.count).filter(Boolean).forEach((function(e){h.counts[e]=!0,h.keys.push(e)})),[].concat(n.normalize).filter(Boolean).forEach((function(e){h.normalize[e]=!0,h.keys.push(e)})),Object.keys(n.narg||{}).forEach((function(e){h.nargs[e]=n.narg[e],h.keys.push(e)})),Object.keys(n.coerce||{}).forEach((function(e){h.coercions[e]=n.coerce[e],h.keys.push(e)})),Array.isArray(n.config)||"string"==typeof n.config?[].concat(n.config).filter(Boolean).forEach((function(e){h.configs[e]=!0})):Object.keys(n.config||{}).forEach((function(e){h.configs[e]=n.config[e]})),function(...e){e.forEach((function(e){Object.keys(e||{}).forEach((function(e){h.aliases[e]||(h.aliases[e]=[].concat(a[e]||[]),h.aliases[e].concat(e).forEach((function(n){if(/-/.test(n)&&t["camel-case-expansion"]){var a=camelCase(n);a!==e&&-1===h.aliases[e].indexOf(a)&&(h.aliases[e].push(a),f[a]=!0)}})),h.aliases[e].concat(e).forEach((function(n){if(n.length>1&&/[A-Z]/.test(n)&&t["camel-case-expansion"]){var a=decamelize(n,"-");a!==e&&-1===h.aliases[e].indexOf(a)&&(h.aliases[e].push(a),f[a]=!0)}})),h.aliases[e].forEach((function(n){h.aliases[n]=[e].concat(h.aliases[e].filter((function(e){return n!==e})))})))}))}))}(n.key,a,n.default,h.arrays),Object.keys(o).forEach((function(e){(h.aliases[e]||[]).forEach((function(n){o[n]=o[e]}))}));var y={_:[]};Object.keys(h.bools).forEach((function(e){Object.prototype.hasOwnProperty.call(o,e)&&(B(e,o[e]),function(e){[].concat(h.aliases[e]||[],e).forEach((function(e){h.defaulted[e]=!0}))}(e))}));for(var m=[],d=0;d<e.length;d++){var b,v,E,k,j,O,_=e[d];if(_.match(/^--.+=/)||!t["short-option-groups"]&&_.match(/^-.+=/))K((k=_.match(/^--?([^=]+)=([\s\S]*)$/))[1],h.nargs)?(e.splice(d+1,0,k[2]),d=z(d,k[1],e)):K(k[1],h.arrays)&&e.length>d+1?(e.splice(d+1,0,k[2]),d=x(d,k[1],e)):B(k[1],k[2]);else if(_.match(g)&&t["boolean-negation"])B(v=_.match(g)[1],!1);else if(_.match(/^--.+/)||!t["short-option-groups"]&&_.match(/^-[^-]+/))K(v=_.match(/^--?(.+)/)[1],h.nargs)?d=z(d,v,e):K(v,h.arrays)&&e.length>d+1?d=x(d,v,e):void 0===(j=0===h.nargs[v]?void 0:e[d+1])||j.match(/^-/)&&!j.match(p)||K(v,h.bools)||K(v,h.counts)?/^(true|false)$/.test(j)?(B(v,j),d++):B(v,M(v)):(B(v,j),d++);else if(_.match(/^-.\..+=/))B((k=_.match(/^-([^=]+)=([\s\S]*)$/))[1],k[2]);else if(_.match(/^-.\..+/))j=e[d+1],v=_.match(/^-(.\..+)/)[1],void 0===j||j.match(/^-/)||K(v,h.bools)||K(v,h.counts)?B(v,M(v)):(B(v,j),d++);else if(_.match(/^-[^-]+/)&&!_.match(p)){E=_.slice(1,-1).split(""),b=!1;for(var A=0;A<E.length;A++){if(j=_.slice(A+2),E[A+1]&&"="===E[A+1]){O=_.slice(A+3),K(v=E[A],h.nargs)?(e.splice(d+1,0,O),d=z(d,v,e)):K(v,h.arrays)&&e.length>d+1?(e.splice(d+1,0,O),d=x(d,v,e)):B(v,O),b=!0;break}if("-"!==j){if(/[A-Za-z]/.test(E[A])&&/^-?\d+(\.\d*)?(e-?\d+)?$/.test(j)){B(E[A],j),b=!0;break}if(E[A+1]&&E[A+1].match(/\W/)){B(E[A],j),b=!0;break}B(E[A],M(E[A]))}else B(E[A],j)}v=_.slice(-1)[0],b||"-"===v||(K(v,h.nargs)?d=z(d,v,e):K(v,h.arrays)&&e.length>d+1?d=x(d,v,e):void 0===(j=e[d+1])||/^(-|--)[^-]/.test(j)&&!j.match(p)||K(v,h.bools)||K(v,h.counts)?/^(true|false)$/.test(j)?(B(v,j),d++):B(v,M(v)):(B(v,j),d++))}else{if("--"===_){m=e.slice(d+1);break}if(t["halt-at-non-option"]){m=e.slice(d);break}y._.push(q("_",_))}}function z(e,n,a){var t;const o=K(n,h.nargs);var r=0;for(t=e+1;t<a.length&&!a[t].match(/^-[^0-9]/);t++)r++;r<o&&(u=Error(l("Not enough arguments following: %s",n)));const i=Math.min(r,o);for(t=e+1;t<i+e+1;t++)B(n,a[t]);return e+i}function x(e,n,a){for(var t=e+1,o=[],r=e>0,i=e+1;i<a.length;i++){if(/^-/.test(a[i])&&!p.test(a[i])){i===t&&B(n,Z("array")),r=!0;break}e=i,o.push(a[i])}return r?B(n,o.map((function(e){return S(n,e)}))):o.forEach((function(e){B(n,e)})),e}function B(e,n){if(function(e){[].concat(h.aliases[e]||[],e).forEach((function(e){delete h.defaulted[e]}))}(e),/-/.test(e)&&t["camel-case-expansion"]){var a=e.split(".").map((function(e){return camelCase(e)})).join(".");$(e,a)}var o=S(e,n),r=e.split(".");(I(y,r,o),h.aliases[e]&&h.aliases[e].forEach&&h.aliases[e].forEach((function(e){e=e.split("."),I(y,e,o)})),r.length>1&&t["dot-notation"]&&(h.aliases[r[0]]||[]).forEach((function(e){e=e.split(".");var n=[].concat(r);n.shift(),e=e.concat(n),I(y,e,o)})),K(e,h.normalize)&&!K(e,h.arrays))&&[e].concat(h.aliases[e]||[]).forEach((function(e){y.__defineSetter__(e,(function(e){n=path.normalize(e)})),y.__defineGetter__(e,(function(){return"string"==typeof n?path.normalize(n):n}))}))}function $(e,n){h.aliases[e]&&h.aliases[e].length||(h.aliases[e]=[n],f[n]=!0),h.aliases[n]&&h.aliases[n].length||$(n,e)}function S(e,n){"string"!=typeof n||"'"!==n[0]&&'"'!==n[0]||n[n.length-1]!==n[0]||(n=n.substring(1,n.length-1)),(K(e,h.bools)||K(e,h.counts))&&"string"==typeof n&&(n="true"===n);var a=q(e,n);return K(e,h.counts)&&(G(a)||"boolean"==typeof a)&&(a=increment),K(e,h.normalize)&&K(e,h.arrays)&&(a=Array.isArray(n)?n.map(path.normalize):path.normalize(n)),a}function q(e,n){if(!K(e,h.strings)&&!K(e,h.coercions)){(null!=(a=n)&&("number"==typeof a||!!/^0x[0-9a-f]+$/i.test(a)||!(a.length>1&&"0"===a[0])&&/^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(a))&&t["parse-numbers"]&&Number.isSafeInteger(Math.floor(n))||!G(n)&&K(e,h.numbers))&&(n=Number(n))}var a;return n}function w(e,n){Object.keys(e).forEach((function(a){var o=e[a],r=n?n+"."+a:a;"object"==typeof o&&null!==o&&!Array.isArray(o)&&t["dot-notation"]?w(o,r):(!N(y,r.split("."))||h.defaulted[r]||h.arrays[r]&&t["combine-arrays"])&&B(r,o)}))}function P(e,n){if(void 0!==i){var a="string"==typeof i?i:"";Object.keys(process.env).forEach((function(t){if(""===a||0===t.lastIndexOf(a,0)){var o=t.split("__").map((function(e,n){return 0===n&&(e=e.substring(a.length)),camelCase(e)}));!(n&&h.configs[o.join(".")]||!n)||N(e,o)&&!h.defaulted[o.join(".")]||B(o.join("."),process.env[t])}}))}}function C(e,n,a){Object.keys(a).forEach((function(t){N(e,t.split("."))||(I(e,t.split("."),a[t]),(n[t]||[]).forEach((function(n){N(e,n.split("."))||I(e,n.split("."),a[t])})))}))}function N(e,n){var a=e;t["dot-notation"]||(n=[n.join(".")]),n.slice(0,-1).forEach((function(e){a=a[e]||{}}));var o=n[n.length-1];return"object"==typeof a&&o in a}function I(e,n,a){var o=e;t["dot-notation"]||(n=[n.join(".")]),n.slice(0,-1).forEach((function(e,n){e=sanitizeKey(e),"object"==typeof o&&void 0===o[e]&&(o[e]={}),"object"!=typeof o[e]||Array.isArray(o[e])?(Array.isArray(o[e])?o[e].push({}):o[e]=[o[e],{}],o=o[e][o[e].length-1]):o=o[e]}));const r=sanitizeKey(n[n.length-1]),i=K(n.join("."),h.arrays),s=Array.isArray(a);let c=t["duplicate-arguments-array"];!c&&K(r,h.nargs)&&(c=!0,(!G(o[r])&&1===h.nargs[r]||Array.isArray(o[r])&&o[r].length===h.nargs[r])&&(o[r]=void 0)),a===increment?o[r]=increment(o[r]):Array.isArray(o[r])?c&&i&&s?o[r]=t["flatten-duplicate-arrays"]?o[r].concat(a):(Array.isArray(o[r][0])?o[r]:[o[r]]).concat([a]):c||Boolean(i)!==Boolean(s)?o[r]=o[r].concat([a]):o[r]=a:void 0===o[r]&&i?o[r]=s?a:[a]:c&&!(void 0===o[r]||K(r,h.bools)||K(n.join("."),h.bools)||K(r,h.counts))?o[r]=[o[r],a]:o[r]=a}function K(e,n){var a=!1;return[].concat(h.aliases[e]||[],e).forEach((function(e){n[e]&&(a=n[e])})),a}function M(e){return K(e,h.bools)||K(e,h.counts)||!(`${e}`in o)?Z(function(e){var n="boolean";K(e,h.strings)?n="string":K(e,h.numbers)?n="number":K(e,h.arrays)&&(n="array");return n}(e)):o[e]}function Z(e){return{boolean:!0,string:"",number:void 0,array:[]}[e]}function G(e){return void 0===e}return P(y,!0),P(y,!1),function(e){var n={};C(n,h.aliases,o),Object.keys(h.configs).forEach((function(a){var t=e[a]||n[a];if(t)try{var o=null,r=path.resolve(process.cwd(),t);if("function"==typeof h.configs[a]){try{o=h.configs[a](r)}catch(e){o=e}if(o instanceof Error)return void(u=o)}else o=require(r);w(o)}catch(n){e[a]&&(u=Error(l("Invalid JSON config file: %s",t)))}}))}(y),function(){if(void 0===r)return;r.forEach((function(e){w(e)}))}(),C(y,h.aliases,o),function(e){var n,a={};Object.keys(e).forEach((function(t){if(!a.hasOwnProperty(t)&&"function"==typeof(n=K(t,h.coercions)))try{var o=n(e[t]);[].concat(h.aliases[t]||[],t).forEach((n=>{a[n]=e[n]=o}))}catch(e){u=e}}))}(y),t["set-placeholder-key"]&&function(e){h.keys.forEach((n=>{~n.indexOf(".")||void 0===e[n]&&(e[n]=void 0)}))}(y),Object.keys(h.counts).forEach((function(e){N(y,e.split("."))||B(e,0)})),s&&m.length&&(y[c]=[]),m.forEach((function(e){y[c].push(e)})),t["camel-case-expansion"]&&t["strip-dashed"]&&Object.keys(y).filter((e=>"--"!==e&&e.includes("-"))).forEach((e=>{delete y[e]})),t["strip-aliased"]&&[].concat(...Object.keys(a).map((e=>a[e]))).forEach((e=>{t["camel-case-expansion"]&&delete y[e.split(".").map((e=>camelCase(e))).join(".")],delete y[e]})),{argv:y,error:u,aliases:h.aliases,newAliases:f,configuration:t}}function combineAliases(e){var n=[],a=!0,t={};for(Object.keys(e).forEach((function(a){n.push([].concat(e[a],a))}));a;){a=!1;for(var o=0;o<n.length;o++)for(var r=o+1;r<n.length;r++){if(n[o].filter((function(e){return-1!==n[r].indexOf(e)})).length){n[o]=n[o].concat(n[r]),n.splice(r,1),a=!0;break}}}return n.forEach((function(e){e=e.filter((function(e,n,a){return a.indexOf(e)===n})),t[e.pop()]=e})),t}function increment(e){return void 0!==e?e+1:1}function Parser(e,n){return parse(e.slice(),n).argv}function sanitizeKey(e){return"__proto__"===e?"___proto___":e}Parser.detailed=function(e,n){return parse(e.slice(),n)},module.exports=Parser;
\ No newline at end of file
index fe05e27..2177cfd 100644 (file)
@@ -1,40 +1 @@
-// take an un-split argv string and tokenize it.
-module.exports = function (argString) {
-  if (Array.isArray(argString)) {
-    return argString.map(e => typeof e !== 'string' ? e + '' : e)
-  }
-
-  argString = argString.trim()
-
-  var i = 0
-  var prevC = null
-  var c = null
-  var opening = null
-  var args = []
-
-  for (var ii = 0; ii < argString.length; ii++) {
-    prevC = c
-    c = argString.charAt(ii)
-
-    // split on spaces unless we're in quotes.
-    if (c === ' ' && !opening) {
-      if (!(prevC === ' ')) {
-        i++
-      }
-      continue
-    }
-
-    // don't split the string if we're in matching
-    // opening or closing single and double quotes.
-    if (c === opening) {
-      opening = null
-    } else if ((c === "'" || c === '"') && !opening) {
-      opening = c
-    }
-
-    if (!args[i]) args[i] = ''
-    args[i] += c
-  }
-
-  return args
-}
+module.exports=function(r){if(Array.isArray(r))return r.map((r=>"string"!=typeof r?r+"":r));r=r.trim();for(var l=0,n=null,t=null,u=null,e=[],a=0;a<r.length;a++)n=t," "!==(t=r.charAt(a))||u?(t===u?u=null:"'"!==t&&'"'!==t||u||(u=t),e[l]||(e[l]=""),e[l]+=t):" "!==n&&l++;return e};
\ No newline at end of file
index dfed54b..f103e0e 100644 (file)
@@ -1,32 +1 @@
-'use strict'
-// classic singleton yargs API, to use yargs
-// without running as a singleton do:
-// require('yargs/yargs')(process.argv.slice(2))
-const yargs = require('./yargs')
-
-Argv(process.argv.slice(2))
-
-module.exports = Argv
-
-function Argv (processArgs, cwd) {
-  const argv = yargs(processArgs, cwd, require)
-  singletonify(argv)
-  return argv
-}
-
-/*  Hack an instance of Argv with process.argv into Argv
-    so people can do
-    require('yargs')(['--beeble=1','-z','zizzle']).argv
-    to parse a list of args and
-    require('yargs').argv
-    to get a parsed version of process.argv.
-*/
-function singletonify (inst) {
-  Object.keys(inst).forEach((key) => {
-    if (key === 'argv') {
-      Argv.__defineGetter__(key, inst.__lookupGetter__(key))
-    } else {
-      Argv[key] = typeof inst[key] === 'function' ? inst[key].bind(inst) : inst[key]
-    }
-  })
-}
+"use strict";const yargs=require("./yargs");function Argv(r,e){const t=yargs(r,e,require);return singletonify(t),t}function singletonify(r){Object.keys(r).forEach((e=>{"argv"===e?Argv.__defineGetter__(e,r.__lookupGetter__(e)):Argv[e]="function"==typeof r[e]?r[e].bind(r):r[e]}))}Argv(process.argv.slice(2)),module.exports=Argv;
\ No newline at end of file
index 1436b65..5a46805 100644 (file)
@@ -1,53 +1 @@
-
-'use strict'
-const fs = require('fs')
-const path = require('path')
-const YError = require('./yerror')
-
-let previouslyVisitedConfigs = []
-
-function checkForCircularExtends (cfgPath) {
-  if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) {
-    throw new YError(`Circular extended configurations: '${cfgPath}'.`)
-  }
-}
-
-function getPathToDefaultConfig (cwd, pathToExtend) {
-  return path.resolve(cwd, pathToExtend)
-}
-
-function applyExtends (config, cwd) {
-  let defaultConfig = {}
-
-  if (config.hasOwnProperty('extends')) {
-    if (typeof config.extends !== 'string') return defaultConfig
-    const isPath = /\.json|\..*rc$/.test(config.extends)
-    let pathToDefault = null
-    if (!isPath) {
-      try {
-        pathToDefault = require.resolve(config.extends)
-      } catch (err) {
-        // most likely this simply isn't a module.
-      }
-    } else {
-      pathToDefault = getPathToDefaultConfig(cwd, config.extends)
-    }
-    // maybe the module uses key for some other reason,
-    // err on side of caution.
-    if (!pathToDefault && !isPath) return config
-
-    checkForCircularExtends(pathToDefault)
-
-    previouslyVisitedConfigs.push(pathToDefault)
-
-    defaultConfig = isPath ? JSON.parse(fs.readFileSync(pathToDefault, 'utf8')) : require(config.extends)
-    delete config.extends
-    defaultConfig = applyExtends(defaultConfig, path.dirname(pathToDefault))
-  }
-
-  previouslyVisitedConfigs = []
-
-  return Object.assign({}, defaultConfig, config)
-}
-
-module.exports = applyExtends
+"use strict";const fs=require("fs"),path=require("path"),YError=require("./yerror");let previouslyVisitedConfigs=[];function checkForCircularExtends(e){if(previouslyVisitedConfigs.indexOf(e)>-1)throw new YError(`Circular extended configurations: '${e}'.`)}function getPathToDefaultConfig(e,t){return path.resolve(e,t)}function applyExtends(e,t){let r={};if(e.hasOwnProperty("extends")){if("string"!=typeof e.extends)return r;const s=/\.json|\..*rc$/.test(e.extends);let i=null;if(s)i=getPathToDefaultConfig(t,e.extends);else try{i=require.resolve(e.extends)}catch(e){}if(!i&&!s)return e;checkForCircularExtends(i),previouslyVisitedConfigs.push(i),r=s?JSON.parse(fs.readFileSync(i,"utf8")):require(e.extends),delete e.extends,r=applyExtends(r,path.dirname(i))}return previouslyVisitedConfigs=[],Object.assign({},r,e)}module.exports=applyExtends;
\ No newline at end of file
index f310b4e..1b48247 100644 (file)
@@ -1,68 +1 @@
-'use strict'
-
-// hoisted due to circular dependency on command.
-module.exports = argsert
-const command = require('./command')()
-const YError = require('./yerror')
-
-const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']
-function argsert (expected, callerArguments, length) {
-  // TODO: should this eventually raise an exception.
-  try {
-    // preface the argument description with "cmd", so
-    // that we can run it through yargs' command parser.
-    let position = 0
-    let parsed = { demanded: [], optional: [] }
-    if (typeof expected === 'object') {
-      length = callerArguments
-      callerArguments = expected
-    } else {
-      parsed = command.parseCommand(`cmd ${expected}`)
-    }
-    const args = [].slice.call(callerArguments)
-
-    while (args.length && args[args.length - 1] === undefined) args.pop()
-    length = length || args.length
-
-    if (length < parsed.demanded.length) {
-      throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`)
-    }
-
-    const totalCommands = parsed.demanded.length + parsed.optional.length
-    if (length > totalCommands) {
-      throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`)
-    }
-
-    parsed.demanded.forEach((demanded) => {
-      const arg = args.shift()
-      const observedType = guessType(arg)
-      const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*')
-      if (matchingTypes.length === 0) argumentTypeError(observedType, demanded.cmd, position, false)
-      position += 1
-    })
-
-    parsed.optional.forEach((optional) => {
-      if (args.length === 0) return
-      const arg = args.shift()
-      const observedType = guessType(arg)
-      const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*')
-      if (matchingTypes.length === 0) argumentTypeError(observedType, optional.cmd, position, true)
-      position += 1
-    })
-  } catch (err) {
-    console.warn(err.stack)
-  }
-}
-
-function guessType (arg) {
-  if (Array.isArray(arg)) {
-    return 'array'
-  } else if (arg === null) {
-    return 'null'
-  }
-  return typeof arg
-}
-
-function argumentTypeError (observedType, allowedTypes, position, optional) {
-  throw new YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`)
-}
+"use strict";module.exports=argsert;const command=require("./command")(),YError=require("./yerror"),positionName=["first","second","third","fourth","fifth","sixth"];function argsert(e,r,t){try{let n=0,o={demanded:[],optional:[]};"object"==typeof e?(t=r,r=e):o=command.parseCommand(`cmd ${e}`);const d=[].slice.call(r);for(;d.length&&void 0===d[d.length-1];)d.pop();if((t=t||d.length)<o.demanded.length)throw new YError(`Not enough arguments provided. Expected ${o.demanded.length} but received ${d.length}.`);const a=o.demanded.length+o.optional.length;if(t>a)throw new YError(`Too many arguments provided. Expected max ${a} but received ${t}.`);o.demanded.forEach((e=>{const r=guessType(d.shift());0===e.cmd.filter((e=>e===r||"*"===e)).length&&argumentTypeError(r,e.cmd,n,!1),n+=1})),o.optional.forEach((e=>{if(0===d.length)return;const r=guessType(d.shift());0===e.cmd.filter((e=>e===r||"*"===e)).length&&argumentTypeError(r,e.cmd,n,!0),n+=1}))}catch(e){console.warn(e.stack)}}function guessType(e){return Array.isArray(e)?"array":null===e?"null":typeof e}function argumentTypeError(e,r,t,n){throw new YError(`Invalid ${positionName[t]||"manyith"} argument. Expected ${r.join(" or ")} but received ${e}.`)}
\ No newline at end of file
index 895423a..f72171b 100644 (file)
@@ -1,437 +1 @@
-'use strict'
-
-const inspect = require('util').inspect
-const isPromise = require('./is-promise')
-const { applyMiddleware, commandMiddlewareFactory } = require('./middleware')
-const path = require('path')
-const Parser = require('yargs-parser')
-
-const DEFAULT_MARKER = /(^\*)|(^\$0)/
-
-// handles parsing positional arguments,
-// and populating argv with said positional
-// arguments.
-module.exports = function command (yargs, usage, validation, globalMiddleware) {
-  const self = {}
-  let handlers = {}
-  let aliasMap = {}
-  let defaultCommand
-  globalMiddleware = globalMiddleware || []
-
-  self.addHandler = function addHandler (cmd, description, builder, handler, commandMiddleware) {
-    let aliases = []
-    const middlewares = commandMiddlewareFactory(commandMiddleware)
-    handler = handler || (() => {})
-
-    if (Array.isArray(cmd)) {
-      aliases = cmd.slice(1)
-      cmd = cmd[0]
-    } else if (typeof cmd === 'object') {
-      let command = (Array.isArray(cmd.command) || typeof cmd.command === 'string') ? cmd.command : moduleName(cmd)
-      if (cmd.aliases) command = [].concat(command).concat(cmd.aliases)
-      self.addHandler(command, extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares)
-      return
-    }
-
-    // allow a module to be provided instead of separate builder and handler
-    if (typeof builder === 'object' && builder.builder && typeof builder.handler === 'function') {
-      self.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares)
-      return
-    }
-
-    // parse positionals out of cmd string
-    const parsedCommand = self.parseCommand(cmd)
-
-    // remove positional args from aliases only
-    aliases = aliases.map(alias => self.parseCommand(alias).cmd)
-
-    // check for default and filter out '*''
-    let isDefault = false
-    const parsedAliases = [parsedCommand.cmd].concat(aliases).filter((c) => {
-      if (DEFAULT_MARKER.test(c)) {
-        isDefault = true
-        return false
-      }
-      return true
-    })
-
-    // standardize on $0 for default command.
-    if (parsedAliases.length === 0 && isDefault) parsedAliases.push('$0')
-
-    // shift cmd and aliases after filtering out '*'
-    if (isDefault) {
-      parsedCommand.cmd = parsedAliases[0]
-      aliases = parsedAliases.slice(1)
-      cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd)
-    }
-
-    // populate aliasMap
-    aliases.forEach((alias) => {
-      aliasMap[alias] = parsedCommand.cmd
-    })
-
-    if (description !== false) {
-      usage.command(cmd, description, isDefault, aliases)
-    }
-
-    handlers[parsedCommand.cmd] = {
-      original: cmd,
-      description: description,
-      handler,
-      builder: builder || {},
-      middlewares: middlewares || [],
-      demanded: parsedCommand.demanded,
-      optional: parsedCommand.optional
-    }
-
-    if (isDefault) defaultCommand = handlers[parsedCommand.cmd]
-  }
-
-  self.addDirectory = function addDirectory (dir, context, req, callerFile, opts) {
-    opts = opts || {}
-    // disable recursion to support nested directories of subcommands
-    if (typeof opts.recurse !== 'boolean') opts.recurse = false
-    // exclude 'json', 'coffee' from require-directory defaults
-    if (!Array.isArray(opts.extensions)) opts.extensions = ['js']
-    // allow consumer to define their own visitor function
-    const parentVisit = typeof opts.visit === 'function' ? opts.visit : o => o
-    // call addHandler via visitor function
-    opts.visit = function visit (obj, joined, filename) {
-      const visited = parentVisit(obj, joined, filename)
-      // allow consumer to skip modules with their own visitor
-      if (visited) {
-        // check for cyclic reference
-        // each command file path should only be seen once per execution
-        if (~context.files.indexOf(joined)) return visited
-        // keep track of visited files in context.files
-        context.files.push(joined)
-        self.addHandler(visited)
-      }
-      return visited
-    }
-    require('require-directory')({ require: req, filename: callerFile }, dir, opts)
-  }
-
-  // lookup module object from require()d command and derive name
-  // if module was not require()d and no name given, throw error
-  function moduleName (obj) {
-    const mod = require('which-module')(obj)
-    if (!mod) throw new Error(`No command name given for module: ${inspect(obj)}`)
-    return commandFromFilename(mod.filename)
-  }
-
-  // derive command name from filename
-  function commandFromFilename (filename) {
-    return path.basename(filename, path.extname(filename))
-  }
-
-  function extractDesc (obj) {
-    for (let keys = ['describe', 'description', 'desc'], i = 0, l = keys.length, test; i < l; i++) {
-      test = obj[keys[i]]
-      if (typeof test === 'string' || typeof test === 'boolean') return test
-    }
-    return false
-  }
-
-  self.parseCommand = function parseCommand (cmd) {
-    const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' ')
-    const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/)
-    const bregex = /\.*[\][<>]/g
-    const parsedCommand = {
-      cmd: (splitCommand.shift()).replace(bregex, ''),
-      demanded: [],
-      optional: []
-    }
-    splitCommand.forEach((cmd, i) => {
-      let variadic = false
-      cmd = cmd.replace(/\s/g, '')
-      if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1) variadic = true
-      if (/^\[/.test(cmd)) {
-        parsedCommand.optional.push({
-          cmd: cmd.replace(bregex, '').split('|'),
-          variadic
-        })
-      } else {
-        parsedCommand.demanded.push({
-          cmd: cmd.replace(bregex, '').split('|'),
-          variadic
-        })
-      }
-    })
-    return parsedCommand
-  }
-
-  self.getCommands = () => Object.keys(handlers).concat(Object.keys(aliasMap))
-
-  self.getCommandHandlers = () => handlers
-
-  self.hasDefaultCommand = () => !!defaultCommand
-
-  self.runCommand = function runCommand (command, yargs, parsed, commandIndex) {
-    let aliases = parsed.aliases
-    const commandHandler = handlers[command] || handlers[aliasMap[command]] || defaultCommand
-    const currentContext = yargs.getContext()
-    let numFiles = currentContext.files.length
-    const parentCommands = currentContext.commands.slice()
-
-    // what does yargs look like after the buidler is run?
-    let innerArgv = parsed.argv
-    let innerYargs = null
-    let positionalMap = {}
-    if (command) {
-      currentContext.commands.push(command)
-      currentContext.fullCommands.push(commandHandler.original)
-    }
-    if (typeof commandHandler.builder === 'function') {
-      // a function can be provided, which builds
-      // up a yargs chain and possibly returns it.
-      innerYargs = commandHandler.builder(yargs.reset(parsed.aliases))
-      // if the builder function did not yet parse argv with reset yargs
-      // and did not explicitly set a usage() string, then apply the
-      // original command string as usage() for consistent behavior with
-      // options object below.
-      if (yargs.parsed === false) {
-        if (shouldUpdateUsage(yargs)) {
-          yargs.getUsageInstance().usage(
-            usageFromParentCommandsCommandHandler(parentCommands, commandHandler),
-            commandHandler.description
-          )
-        }
-        innerArgv = innerYargs ? innerYargs._parseArgs(null, null, true, commandIndex) : yargs._parseArgs(null, null, true, commandIndex)
-      } else {
-        innerArgv = yargs.parsed.argv
-      }
-
-      if (innerYargs && yargs.parsed === false) aliases = innerYargs.parsed.aliases
-      else aliases = yargs.parsed.aliases
-    } else if (typeof commandHandler.builder === 'object') {
-      // as a short hand, an object can instead be provided, specifying
-      // the options that a command takes.
-      innerYargs = yargs.reset(parsed.aliases)
-      if (shouldUpdateUsage(innerYargs)) {
-        innerYargs.getUsageInstance().usage(
-          usageFromParentCommandsCommandHandler(parentCommands, commandHandler),
-          commandHandler.description
-        )
-      }
-      Object.keys(commandHandler.builder).forEach((key) => {
-        innerYargs.option(key, commandHandler.builder[key])
-      })
-      innerArgv = innerYargs._parseArgs(null, null, true, commandIndex)
-      aliases = innerYargs.parsed.aliases
-    }
-
-    if (!yargs._hasOutput()) {
-      positionalMap = populatePositionals(commandHandler, innerArgv, currentContext, yargs)
-    }
-
-    const middlewares = globalMiddleware.slice(0).concat(commandHandler.middlewares || [])
-    applyMiddleware(innerArgv, yargs, middlewares, true)
-
-    // we apply validation post-hoc, so that custom
-    // checks get passed populated positional arguments.
-    if (!yargs._hasOutput()) yargs._runValidation(innerArgv, aliases, positionalMap, yargs.parsed.error)
-
-    if (commandHandler.handler && !yargs._hasOutput()) {
-      yargs._setHasOutput()
-
-      innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false)
-
-      const handlerResult = isPromise(innerArgv)
-        ? innerArgv.then(argv => commandHandler.handler(argv))
-        : commandHandler.handler(innerArgv)
-
-      if (isPromise(handlerResult)) {
-        handlerResult.catch(error =>
-          yargs.getUsageInstance().fail(null, error)
-        )
-      }
-    }
-
-    if (command) {
-      currentContext.commands.pop()
-      currentContext.fullCommands.pop()
-    }
-    numFiles = currentContext.files.length - numFiles
-    if (numFiles > 0) currentContext.files.splice(numFiles * -1, numFiles)
-
-    return innerArgv
-  }
-
-  function shouldUpdateUsage (yargs) {
-    return !yargs.getUsageInstance().getUsageDisabled() &&
-      yargs.getUsageInstance().getUsage().length === 0
-  }
-
-  function usageFromParentCommandsCommandHandler (parentCommands, commandHandler) {
-    const c = DEFAULT_MARKER.test(commandHandler.original) ? commandHandler.original.replace(DEFAULT_MARKER, '').trim() : commandHandler.original
-    const pc = parentCommands.filter((c) => { return !DEFAULT_MARKER.test(c) })
-    pc.push(c)
-    return `$0 ${pc.join(' ')}`
-  }
-
-  self.runDefaultBuilderOn = function (yargs) {
-    if (shouldUpdateUsage(yargs)) {
-      // build the root-level command string from the default string.
-      const commandString = DEFAULT_MARKER.test(defaultCommand.original)
-        ? defaultCommand.original : defaultCommand.original.replace(/^[^[\]<>]*/, '$0 ')
-      yargs.getUsageInstance().usage(
-        commandString,
-        defaultCommand.description
-      )
-    }
-    const builder = defaultCommand.builder
-    if (typeof builder === 'function') {
-      builder(yargs)
-    } else {
-      Object.keys(builder).forEach((key) => {
-        yargs.option(key, builder[key])
-      })
-    }
-  }
-
-  // transcribe all positional arguments "command <foo> <bar> [apple]"
-  // onto argv.
-  function populatePositionals (commandHandler, argv, context, yargs) {
-    argv._ = argv._.slice(context.commands.length) // nuke the current commands
-    const demanded = commandHandler.demanded.slice(0)
-    const optional = commandHandler.optional.slice(0)
-    const positionalMap = {}
-
-    validation.positionalCount(demanded.length, argv._.length)
-
-    while (demanded.length) {
-      const demand = demanded.shift()
-      populatePositional(demand, argv, positionalMap)
-    }
-
-    while (optional.length) {
-      const maybe = optional.shift()
-      populatePositional(maybe, argv, positionalMap)
-    }
-
-    argv._ = context.commands.concat(argv._)
-
-    postProcessPositionals(argv, positionalMap, self.cmdToParseOptions(commandHandler.original))
-
-    return positionalMap
-  }
-
-  function populatePositional (positional, argv, positionalMap, parseOptions) {
-    const cmd = positional.cmd[0]
-    if (positional.variadic) {
-      positionalMap[cmd] = argv._.splice(0).map(String)
-    } else {
-      if (argv._.length) positionalMap[cmd] = [String(argv._.shift())]
-    }
-  }
-
-  // we run yargs-parser against the positional arguments
-  // applying the same parsing logic used for flags.
-  function postProcessPositionals (argv, positionalMap, parseOptions) {
-    // combine the parsing hints we've inferred from the command
-    // string with explicitly configured parsing hints.
-    const options = Object.assign({}, yargs.getOptions())
-    options.default = Object.assign(parseOptions.default, options.default)
-    options.alias = Object.assign(parseOptions.alias, options.alias)
-    options.array = options.array.concat(parseOptions.array)
-    delete options.config //  don't load config when processing positionals.
-
-    const unparsed = []
-    Object.keys(positionalMap).forEach((key) => {
-      positionalMap[key].map((value) => {
-        unparsed.push(`--${key}`)
-        unparsed.push(value)
-      })
-    })
-
-    // short-circuit parse.
-    if (!unparsed.length) return
-
-    const parsed = Parser.detailed(unparsed, options)
-
-    if (parsed.error) {
-      yargs.getUsageInstance().fail(parsed.error.message, parsed.error)
-    } else {
-      // only copy over positional keys (don't overwrite
-      // flag arguments that were already parsed).
-      const positionalKeys = Object.keys(positionalMap)
-      Object.keys(positionalMap).forEach((key) => {
-        [].push.apply(positionalKeys, parsed.aliases[key])
-      })
-
-      Object.keys(parsed.argv).forEach((key) => {
-        if (positionalKeys.indexOf(key) !== -1) {
-          // any new aliases need to be placed in positionalMap, which
-          // is used for validation.
-          if (!positionalMap[key]) positionalMap[key] = parsed.argv[key]
-          argv[key] = parsed.argv[key]
-        }
-      })
-    }
-  }
-
-  self.cmdToParseOptions = function (cmdString) {
-    const parseOptions = {
-      array: [],
-      default: {},
-      alias: {},
-      demand: {}
-    }
-
-    const parsed = self.parseCommand(cmdString)
-    parsed.demanded.forEach((d) => {
-      const cmds = d.cmd.slice(0)
-      const cmd = cmds.shift()
-      if (d.variadic) {
-        parseOptions.array.push(cmd)
-        parseOptions.default[cmd] = []
-      }
-      cmds.forEach((c) => {
-        parseOptions.alias[cmd] = c
-      })
-      parseOptions.demand[cmd] = true
-    })
-
-    parsed.optional.forEach((o) => {
-      const cmds = o.cmd.slice(0)
-      const cmd = cmds.shift()
-      if (o.variadic) {
-        parseOptions.array.push(cmd)
-        parseOptions.default[cmd] = []
-      }
-      cmds.forEach((c) => {
-        parseOptions.alias[cmd] = c
-      })
-    })
-
-    return parseOptions
-  }
-
-  self.reset = () => {
-    handlers = {}
-    aliasMap = {}
-    defaultCommand = undefined
-    return self
-  }
-
-  // used by yargs.parse() to freeze
-  // the state of commands such that
-  // we can apply .parse() multiple times
-  // with the same yargs instance.
-  let frozen
-  self.freeze = () => {
-    frozen = {}
-    frozen.handlers = handlers
-    frozen.aliasMap = aliasMap
-    frozen.defaultCommand = defaultCommand
-  }
-  self.unfreeze = () => {
-    handlers = frozen.handlers
-    aliasMap = frozen.aliasMap
-    defaultCommand = frozen.defaultCommand
-    frozen = undefined
-  }
-
-  return self
-}
+"use strict";const inspect=require("util").inspect,isPromise=require("./is-promise"),{applyMiddleware:applyMiddleware,commandMiddlewareFactory:commandMiddlewareFactory}=require("./middleware"),path=require("path"),Parser=require("yargs-parser"),DEFAULT_MARKER=/(^\*)|(^\$0)/;module.exports=function(e,a,r,t){const n={};let s,i,o={},l={};function c(e){return!e.getUsageInstance().getUsageDisabled()&&0===e.getUsageInstance().getUsage().length}function d(e,a){const r=DEFAULT_MARKER.test(a.original)?a.original.replace(DEFAULT_MARKER,"").trim():a.original,t=e.filter((e=>!DEFAULT_MARKER.test(e)));return t.push(r),`$0 ${t.join(" ")}`}function u(e,a,r,t){const n=e.cmd[0];e.variadic?r[n]=a._.splice(0).map(String):a._.length&&(r[n]=[String(a._.shift())])}function p(a,r,t){const n=Object.assign({},e.getOptions());n.default=Object.assign(t.default,n.default),n.alias=Object.assign(t.alias,n.alias),n.array=n.array.concat(t.array),delete n.config;const s=[];if(Object.keys(r).forEach((e=>{r[e].map((a=>{s.push(`--${e}`),s.push(a)}))})),!s.length)return;const i=Parser.detailed(s,n);if(i.error)e.getUsageInstance().fail(i.error.message,i.error);else{const e=Object.keys(r);Object.keys(r).forEach((a=>{[].push.apply(e,i.aliases[a])})),Object.keys(i.argv).forEach((t=>{-1!==e.indexOf(t)&&(r[t]||(r[t]=i.argv[t]),a[t]=i.argv[t])}))}}return t=t||[],n.addHandler=function(e,r,t,i,c){let d=[];const u=commandMiddlewareFactory(c);if(i=i||(()=>{}),Array.isArray(e))d=e.slice(1),e=e[0];else if("object"==typeof e){let a=Array.isArray(e.command)||"string"==typeof e.command?e.command:function(e){const a=require("which-module")(e);if(!a)throw new Error(`No command name given for module: ${inspect(e)}`);return r=a.filename,path.basename(r,path.extname(r));var r}(e);return e.aliases&&(a=[].concat(a).concat(e.aliases)),void n.addHandler(a,function(e){for(let a,r=["describe","description","desc"],t=0,n=r.length;t<n;t++)if(a=e[r[t]],"string"==typeof a||"boolean"==typeof a)return a;return!1}(e),e.builder,e.handler,e.middlewares)}if("object"==typeof t&&t.builder&&"function"==typeof t.handler)return void n.addHandler([e].concat(d),r,t.builder,t.handler,t.middlewares);const p=n.parseCommand(e);d=d.map((e=>n.parseCommand(e).cmd));let m=!1;const f=[p.cmd].concat(d).filter((e=>!DEFAULT_MARKER.test(e)||(m=!0,!1)));0===f.length&&m&&f.push("$0"),m&&(p.cmd=f[0],d=f.slice(1),e=e.replace(DEFAULT_MARKER,p.cmd)),d.forEach((e=>{l[e]=p.cmd})),!1!==r&&a.command(e,r,m,d),o[p.cmd]={original:e,description:r,handler:i,builder:t||{},middlewares:u||[],demanded:p.demanded,optional:p.optional},m&&(s=o[p.cmd])},n.addDirectory=function(e,a,r,t,s){"boolean"!=typeof(s=s||{}).recurse&&(s.recurse=!1),Array.isArray(s.extensions)||(s.extensions=["js"]);const i="function"==typeof s.visit?s.visit:e=>e;s.visit=function(e,r,t){const s=i(e,r,t);if(s){if(~a.files.indexOf(r))return s;a.files.push(r),n.addHandler(s)}return s},require("require-directory")({require:r,filename:t},e,s)},n.parseCommand=function(e){const a=e.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),r=/\.*[\][<>]/g,t={cmd:a.shift().replace(r,""),demanded:[],optional:[]};return a.forEach(((e,n)=>{let s=!1;e=e.replace(/\s/g,""),/\.+[\]>]/.test(e)&&n===a.length-1&&(s=!0),/^\[/.test(e)?t.optional.push({cmd:e.replace(r,"").split("|"),variadic:s}):t.demanded.push({cmd:e.replace(r,"").split("|"),variadic:s})})),t},n.getCommands=()=>Object.keys(o).concat(Object.keys(l)),n.getCommandHandlers=()=>o,n.hasDefaultCommand=()=>!!s,n.runCommand=function(e,a,i,m){let f=i.aliases;const g=o[e]||o[l[e]]||s,h=a.getContext();let y=h.files.length;const b=h.commands.slice();let E=i.argv,A=null,_={};e&&(h.commands.push(e),h.fullCommands.push(g.original)),"function"==typeof g.builder?(A=g.builder(a.reset(i.aliases)),!1===a.parsed?(c(a)&&a.getUsageInstance().usage(d(b,g),g.description),E=A?A._parseArgs(null,null,!0,m):a._parseArgs(null,null,!0,m)):E=a.parsed.argv,f=A&&!1===a.parsed?A.parsed.aliases:a.parsed.aliases):"object"==typeof g.builder&&(A=a.reset(i.aliases),c(A)&&A.getUsageInstance().usage(d(b,g),g.description),Object.keys(g.builder).forEach((e=>{A.option(e,g.builder[e])})),E=A._parseArgs(null,null,!0,m),f=A.parsed.aliases),a._hasOutput()||(_=function(e,a,t,s){a._=a._.slice(t.commands.length);const i=e.demanded.slice(0),o=e.optional.slice(0),l={};r.positionalCount(i.length,a._.length);for(;i.length;){u(i.shift(),a,l)}for(;o.length;){u(o.shift(),a,l)}return a._=t.commands.concat(a._),p(a,l,n.cmdToParseOptions(e.original)),l}(g,E,h));const O=t.slice(0).concat(g.middlewares||[]);if(applyMiddleware(E,a,O,!0),a._hasOutput()||a._runValidation(E,f,_,a.parsed.error),g.handler&&!a._hasOutput()){a._setHasOutput(),E=applyMiddleware(E,a,O,!1);const e=isPromise(E)?E.then((e=>g.handler(e))):g.handler(E);isPromise(e)&&e.catch((e=>a.getUsageInstance().fail(null,e)))}return e&&(h.commands.pop(),h.fullCommands.pop()),y=h.files.length-y,y>0&&h.files.splice(-1*y,y),E},n.runDefaultBuilderOn=function(e){if(c(e)){const a=DEFAULT_MARKER.test(s.original)?s.original:s.original.replace(/^[^[\]<>]*/,"$0 ");e.getUsageInstance().usage(a,s.description)}const a=s.builder;"function"==typeof a?a(e):Object.keys(a).forEach((r=>{e.option(r,a[r])}))},n.cmdToParseOptions=function(e){const a={array:[],default:{},alias:{},demand:{}},r=n.parseCommand(e);return r.demanded.forEach((e=>{const r=e.cmd.slice(0),t=r.shift();e.variadic&&(a.array.push(t),a.default[t]=[]),r.forEach((e=>{a.alias[t]=e})),a.demand[t]=!0})),r.optional.forEach((e=>{const r=e.cmd.slice(0),t=r.shift();e.variadic&&(a.array.push(t),a.default[t]=[]),r.forEach((e=>{a.alias[t]=e}))})),a},n.reset=()=>(o={},l={},s=void 0,n),n.freeze=()=>{i={},i.handlers=o,i.aliasMap=l,i.defaultCommand=s},n.unfreeze=()=>{o=i.handlers,l=i.aliasMap,s=i.defaultCommand,i=void 0},n};
\ No newline at end of file
index 43714fb..b1f723e 100644 (file)
@@ -1,49 +1 @@
-exports.completionShTemplate =
-`###-begin-{{app_name}}-completions-###
-#
-# yargs command completion script
-#
-# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc
-#    or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.
-#
-_yargs_completions()
-{
-    local cur_word args type_list
-
-    cur_word="\${COMP_WORDS[COMP_CWORD]}"
-    args=("\${COMP_WORDS[@]}")
-
-    # ask yargs to generate completions.
-    type_list=$({{app_path}} --get-yargs-completions "\${args[@]}")
-
-    COMPREPLY=( $(compgen -W "\${type_list}" -- \${cur_word}) )
-
-    # if no match was found, fall back to filename completion
-    if [ \${#COMPREPLY[@]} -eq 0 ]; then
-      COMPREPLY=()
-    fi
-
-    return 0
-}
-complete -o default -F _yargs_completions {{app_name}}
-###-end-{{app_name}}-completions-###
-`
-
-exports.completionZshTemplate = `###-begin-{{app_name}}-completions-###
-#
-# yargs command completion script
-#
-# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc
-#    or {{app_path}} {{completion_command}} >> ~/.zsh_profile on OSX.
-#
-_{{app_name}}_yargs_completions()
-{
-  local reply
-  local si=$IFS
-  IFS=$'\n' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}"))
-  IFS=$si
-  _describe 'values' reply
-}
-compdef _{{app_name}}_yargs_completions {{app_name}}
-###-end-{{app_name}}-completions-###
-`
+exports.completionShTemplate='###-begin-{{app_name}}-completions-###\n#\n# yargs command completion script\n#\n# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc\n#    or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.\n#\n_yargs_completions()\n{\n    local cur_word args type_list\n\n    cur_word="${COMP_WORDS[COMP_CWORD]}"\n    args=("${COMP_WORDS[@]}")\n\n    # ask yargs to generate completions.\n    type_list=$({{app_path}} --get-yargs-completions "${args[@]}")\n\n    COMPREPLY=( $(compgen -W "${type_list}" -- ${cur_word}) )\n\n    # if no match was found, fall back to filename completion\n    if [ ${#COMPREPLY[@]} -eq 0 ]; then\n      COMPREPLY=()\n    fi\n\n    return 0\n}\ncomplete -o default -F _yargs_completions {{app_name}}\n###-end-{{app_name}}-completions-###\n',exports.completionZshTemplate='###-begin-{{app_name}}-completions-###\n#\n# yargs command completion script\n#\n# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc\n#    or {{app_path}} {{completion_command}} >> ~/.zsh_profile on OSX.\n#\n_{{app_name}}_yargs_completions()\n{\n  local reply\n  local si=$IFS\n  IFS=$\'\n\' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "${words[@]}"))\n  IFS=$si\n  _describe \'values\' reply\n}\ncompdef _{{app_name}}_yargs_completions {{app_name}}\n###-end-{{app_name}}-completions-###\n';
\ No newline at end of file
index e5cdd58..30a6d72 100644 (file)
@@ -1,115 +1 @@
-'use strict'
-const path = require('path')
-
-// add bash completions to your
-//  yargs-powered applications.
-module.exports = function completion (yargs, usage, command) {
-  const self = {
-    completionKey: 'get-yargs-completions'
-  }
-
-  const zshShell = process.env.SHELL && process.env.SHELL.indexOf('zsh') !== -1
-  // get a list of completion commands.
-  // 'args' is the array of strings from the line to be completed
-  self.getCompletion = function getCompletion (args, done) {
-    const completions = []
-    const current = args.length ? args[args.length - 1] : ''
-    const argv = yargs.parse(args, true)
-    const aliases = yargs.parsed.aliases
-    const parentCommands = yargs.getContext().commands
-
-    // a custom completion function can be provided
-    // to completion().
-    if (completionFunction) {
-      if (completionFunction.length < 3) {
-        const result = completionFunction(current, argv)
-
-        // promise based completion function.
-        if (typeof result.then === 'function') {
-          return result.then((list) => {
-            process.nextTick(() => { done(list) })
-          }).catch((err) => {
-            process.nextTick(() => { throw err })
-          })
-        }
-
-        // synchronous completion function.
-        return done(result)
-      } else {
-        // asynchronous completion function
-        return completionFunction(current, argv, (completions) => {
-          done(completions)
-        })
-      }
-    }
-
-    const handlers = command.getCommandHandlers()
-    for (let i = 0, ii = args.length; i < ii; ++i) {
-      if (handlers[args[i]] && handlers[args[i]].builder) {
-        const builder = handlers[args[i]].builder
-        if (typeof builder === 'function') {
-          const y = yargs.reset()
-          builder(y)
-          return y.argv
-        }
-      }
-    }
-
-    if (!current.match(/^-/) && parentCommands[parentCommands.length - 1] !== current) {
-      usage.getCommands().forEach((usageCommand) => {
-        const commandName = command.parseCommand(usageCommand[0]).cmd
-        if (args.indexOf(commandName) === -1) {
-          if (!zshShell) {
-            completions.push(commandName)
-          } else {
-            const desc = usageCommand[1] || ''
-            completions.push(commandName.replace(/:/g, '\\:') + ':' + desc)
-          }
-        }
-      })
-    }
-
-    if (current.match(/^-/) || (current === '' && completions.length === 0)) {
-      const descs = usage.getDescriptions()
-      Object.keys(yargs.getOptions().key).forEach((key) => {
-        // If the key and its aliases aren't in 'args', add the key to 'completions'
-        const keyAndAliases = [key].concat(aliases[key] || [])
-        const notInArgs = keyAndAliases.every(val => args.indexOf(`--${val}`) === -1)
-        if (notInArgs) {
-          if (!zshShell) {
-            completions.push(`--${key}`)
-          } else {
-            const desc = descs[key] || ''
-            completions.push(`--${key.replace(/:/g, '\\:')}:${desc.replace('__yargsString__:', '')}`)
-          }
-        }
-      })
-    }
-
-    done(completions)
-  }
-
-  // generate the completion script to add to your .bashrc.
-  self.generateCompletionScript = function generateCompletionScript ($0, cmd) {
-    const templates = require('./completion-templates')
-    let script = zshShell ? templates.completionZshTemplate : templates.completionShTemplate
-    const name = path.basename($0)
-
-    // add ./to applications not yet installed as bin.
-    if ($0.match(/\.js$/)) $0 = `./${$0}`
-
-    script = script.replace(/{{app_name}}/g, name)
-    script = script.replace(/{{completion_command}}/g, cmd)
-    return script.replace(/{{app_path}}/g, $0)
-  }
-
-  // register a function to perform your own custom
-  // completions., this function can be either
-  // synchrnous or asynchronous.
-  let completionFunction = null
-  self.registerFunction = (fn) => {
-    completionFunction = fn
-  }
-
-  return self
-}
+"use strict";const path=require("path");module.exports=function(e,t,n){const o={completionKey:"get-yargs-completions"},c=process.env.SHELL&&-1!==process.env.SHELL.indexOf("zsh");o.getCompletion=function(o,r){const p=[],a=o.length?o[o.length-1]:"",i=e.parse(o,!0),l=e.parsed.aliases,m=e.getContext().commands;if(s){if(s.length<3){const e=s(a,i);return"function"==typeof e.then?e.then((e=>{process.nextTick((()=>{r(e)}))})).catch((e=>{process.nextTick((()=>{throw e}))})):r(e)}return s(a,i,(e=>{r(e)}))}const h=n.getCommandHandlers();for(let t=0,n=o.length;t<n;++t)if(h[o[t]]&&h[o[t]].builder){const n=h[o[t]].builder;if("function"==typeof n){const t=e.reset();return n(t),t.argv}}if(a.match(/^-/)||m[m.length-1]===a||t.getCommands().forEach((e=>{const t=n.parseCommand(e[0]).cmd;if(-1===o.indexOf(t))if(c){const n=e[1]||"";p.push(t.replace(/:/g,"\\:")+":"+n)}else p.push(t)})),a.match(/^-/)||""===a&&0===p.length){const n=t.getDescriptions();Object.keys(e.getOptions().key).forEach((e=>{if([e].concat(l[e]||[]).every((e=>-1===o.indexOf(`--${e}`))))if(c){const t=n[e]||"";p.push(`--${e.replace(/:/g,"\\:")}:${t.replace("__yargsString__:","")}`)}else p.push(`--${e}`)}))}r(p)},o.generateCompletionScript=function(e,t){const n=require("./completion-templates");let o=c?n.completionZshTemplate:n.completionShTemplate;const s=path.basename(e);return e.match(/\.js$/)&&(e=`./${e}`),o=o.replace(/{{app_name}}/g,s),o=o.replace(/{{completion_command}}/g,t),o.replace(/{{app_path}}/g,e)};let s=null;return o.registerFunction=e=>{s=e},o};
\ No newline at end of file
index c3a4151..b8a8382 100644 (file)
@@ -1,32 +1 @@
-/*
-MIT License
-
-Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (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 = (text, separator) => {
-  separator = typeof separator === 'undefined' ? '_' : separator
-
-  return text
-    .replace(/([a-z\d])([A-Z])/g, `$1${separator}$2`)
-    .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, `$1${separator}$2`)
-    .toLowerCase()
-}
+"use strict";module.exports=(e,$)=>($=void 0===$?"_":$,e.replace(/([a-z\d])([A-Z])/g,`$1${$}$2`).replace(/([A-Z]+)([A-Z][a-z\d]+)/g,`$1${$}$2`).toLowerCase());
\ No newline at end of file
index 0516def..763a4fa 100644 (file)
@@ -1,3 +1 @@
-module.exports = function isPromise (maybePromise) {
-  return maybePromise instanceof Promise
-}
+module.exports=function(e){return e instanceof Promise};
\ No newline at end of file
index c66c1ba..ebd81e5 100644 (file)
@@ -1,58 +1 @@
-/*
-Copyright (c) 2011 Andrei Mackenzie
-
-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.
-*/
-
-// levenshtein distance algorithm, pulled from Andrei Mackenzie's MIT licensed.
-// gist, which can be found here: https://gist.github.com/andrei-m/982927
-'use strict'
-// Compute the edit distance between the two given strings
-module.exports = function levenshtein (a, b) {
-  if (a.length === 0) return b.length
-  if (b.length === 0) return a.length
-
-  const matrix = []
-
-  // increment along the first column of each row
-  let i
-  for (i = 0; i <= b.length; i++) {
-    matrix[i] = [i]
-  }
-
-  // increment each column in the first row
-  let j
-  for (j = 0; j <= a.length; j++) {
-    matrix[0][j] = j
-  }
-
-  // Fill in the rest of the matrix
-  for (i = 1; i <= b.length; i++) {
-    for (j = 1; j <= a.length; j++) {
-      if (b.charAt(i - 1) === a.charAt(j - 1)) {
-        matrix[i][j] = matrix[i - 1][j - 1]
-      } else {
-        matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, // substitution
-          Math.min(matrix[i][j - 1] + 1, // insertion
-            matrix[i - 1][j] + 1)) // deletion
-      }
-    }
-  }
-
-  return matrix[b.length][a.length]
-}
+"use strict";module.exports=function(t,n){if(0===t.length)return n.length;if(0===n.length)return t.length;const e=[];let h,r;for(h=0;h<=n.length;h++)e[h]=[h];for(r=0;r<=t.length;r++)e[0][r]=r;for(h=1;h<=n.length;h++)for(r=1;r<=t.length;r++)n.charAt(h-1)===t.charAt(r-1)?e[h][r]=e[h-1][r-1]:e[h][r]=Math.min(e[h-1][r-1]+1,Math.min(e[h][r-1]+1,e[h-1][r]+1));return e[n.length][t.length]};
\ No newline at end of file
index 9f9c196..923dc49 100644 (file)
@@ -1,65 +1 @@
-'use strict'
-
-// hoisted due to circular dependency on command.
-module.exports = {
-  applyMiddleware,
-  commandMiddlewareFactory,
-  globalMiddlewareFactory
-}
-const isPromise = require('./is-promise')
-const argsert = require('./argsert')
-
-function globalMiddlewareFactory (globalMiddleware, context) {
-  return function (callback, applyBeforeValidation = false) {
-    argsert('<array|function> [boolean]', [callback, applyBeforeValidation], arguments.length)
-    if (Array.isArray(callback)) {
-      for (let i = 0; i < callback.length; i++) {
-        if (typeof callback[i] !== 'function') {
-          throw Error('middleware must be a function')
-        }
-        callback[i].applyBeforeValidation = applyBeforeValidation
-      }
-      Array.prototype.push.apply(globalMiddleware, callback)
-    } else if (typeof callback === 'function') {
-      callback.applyBeforeValidation = applyBeforeValidation
-      globalMiddleware.push(callback)
-    }
-    return context
-  }
-}
-
-function commandMiddlewareFactory (commandMiddleware) {
-  if (!commandMiddleware) return []
-  return commandMiddleware.map(middleware => {
-    middleware.applyBeforeValidation = false
-    return middleware
-  })
-}
-
-function applyMiddleware (argv, yargs, middlewares, beforeValidation) {
-  const beforeValidationError = new Error('middleware cannot return a promise when applyBeforeValidation is true')
-  return middlewares
-    .reduce((accumulation, middleware) => {
-      if (middleware.applyBeforeValidation !== beforeValidation &&
-          !isPromise(accumulation)) {
-        return accumulation
-      }
-
-      if (isPromise(accumulation)) {
-        return accumulation
-          .then(initialObj =>
-            Promise.all([initialObj, middleware(initialObj, yargs)])
-          )
-          .then(([initialObj, middlewareObj]) =>
-            Object.assign(initialObj, middlewareObj)
-          )
-      } else {
-        const result = middleware(argv, yargs)
-        if (beforeValidation && isPromise(result)) throw beforeValidationError
-
-        return isPromise(result)
-          ? result.then(middlewareObj => Object.assign(accumulation, middlewareObj))
-          : Object.assign(accumulation, result)
-      }
-    }, argv)
-}
+"use strict";module.exports={applyMiddleware:applyMiddleware,commandMiddlewareFactory:commandMiddlewareFactory,globalMiddlewareFactory:globalMiddlewareFactory};const isPromise=require("./is-promise"),argsert=require("./argsert");function globalMiddlewareFactory(e,r){return function(a,i=!1){if(argsert("<array|function> [boolean]",[a,i],arguments.length),Array.isArray(a)){for(let e=0;e<a.length;e++){if("function"!=typeof a[e])throw Error("middleware must be a function");a[e].applyBeforeValidation=i}Array.prototype.push.apply(e,a)}else"function"==typeof a&&(a.applyBeforeValidation=i,e.push(a));return r}}function commandMiddlewareFactory(e){return e?e.map((e=>(e.applyBeforeValidation=!1,e))):[]}function applyMiddleware(e,r,a,i){const o=new Error("middleware cannot return a promise when applyBeforeValidation is true");return a.reduce(((a,t)=>{if(t.applyBeforeValidation!==i&&!isPromise(a))return a;if(isPromise(a))return a.then((e=>Promise.all([e,t(e,r)]))).then((([e,r])=>Object.assign(e,r)));{const n=t(e,r);if(i&&isPromise(n))throw o;return isPromise(n)?n.then((e=>Object.assign(a,e))):Object.assign(a,n)}}),e)}
\ No newline at end of file
index c344ac5..a4dd13c 100644 (file)
@@ -1,11 +1 @@
-'use strict'
-module.exports = function objFilter (original, filter) {
-  const obj = {}
-  filter = filter || ((k, v) => true)
-  Object.keys(original || {}).forEach((key) => {
-    if (filter(key, original[key])) {
-      obj[key] = original[key]
-    }
-  })
-  return obj
-}
+"use strict";module.exports=function(t,e){const c={};return e=e||((t,e)=>!0),Object.keys(t||{}).forEach((o=>{e(o,t[o])&&(c[o]=t[o])})),c};
\ No newline at end of file
index 8c3b068..f33deee 100644 (file)
@@ -1,540 +1 @@
-'use strict'
-// this file handles outputting usage instructions,
-// failures, etc. keeps logging in one place.
-const decamelize = require('./decamelize')
-const stringWidth = require('string-width')
-const objFilter = require('./obj-filter')
-const path = require('path')
-const setBlocking = require('set-blocking')
-const YError = require('./yerror')
-
-module.exports = function usage (yargs, y18n) {
-  const __ = y18n.__
-  const self = {}
-
-  // methods for ouputting/building failure message.
-  const fails = []
-  self.failFn = function failFn (f) {
-    fails.push(f)
-  }
-
-  let failMessage = null
-  let showHelpOnFail = true
-  self.showHelpOnFail = function showHelpOnFailFn (enabled, message) {
-    if (typeof enabled === 'string') {
-      message = enabled
-      enabled = true
-    } else if (typeof enabled === 'undefined') {
-      enabled = true
-    }
-    failMessage = message
-    showHelpOnFail = enabled
-    return self
-  }
-
-  let failureOutput = false
-  self.fail = function fail (msg, err) {
-    const logger = yargs._getLoggerInstance()
-
-    if (fails.length) {
-      for (let i = fails.length - 1; i >= 0; --i) {
-        fails[i](msg, err, self)
-      }
-    } else {
-      if (yargs.getExitProcess()) setBlocking(true)
-
-      // don't output failure message more than once
-      if (!failureOutput) {
-        failureOutput = true
-        if (showHelpOnFail) {
-          yargs.showHelp('error')
-          logger.error()
-        }
-        if (msg || err) logger.error(msg || err)
-        if (failMessage) {
-          if (msg || err) logger.error('')
-          logger.error(failMessage)
-        }
-      }
-
-      err = err || new YError(msg)
-      if (yargs.getExitProcess()) {
-        return yargs.exit(1)
-      } else if (yargs._hasParseCallback()) {
-        return yargs.exit(1, err)
-      } else {
-        throw err
-      }
-    }
-  }
-
-  // methods for ouputting/building help (usage) message.
-  let usages = []
-  let usageDisabled = false
-  self.usage = (msg, description) => {
-    if (msg === null) {
-      usageDisabled = true
-      usages = []
-      return
-    }
-    usageDisabled = false
-    usages.push([msg, description || ''])
-    return self
-  }
-  self.getUsage = () => {
-    return usages
-  }
-  self.getUsageDisabled = () => {
-    return usageDisabled
-  }
-
-  self.getPositionalGroupName = () => {
-    return __('Positionals:')
-  }
-
-  let examples = []
-  self.example = (cmd, description) => {
-    examples.push([cmd, description || ''])
-  }
-
-  let commands = []
-  self.command = function command (cmd, description, isDefault, aliases) {
-    // the last default wins, so cancel out any previously set default
-    if (isDefault) {
-      commands = commands.map((cmdArray) => {
-        cmdArray[2] = false
-        return cmdArray
-      })
-    }
-    commands.push([cmd, description || '', isDefault, aliases])
-  }
-  self.getCommands = () => commands
-
-  let descriptions = {}
-  self.describe = function describe (key, desc) {
-    if (typeof key === 'object') {
-      Object.keys(key).forEach((k) => {
-        self.describe(k, key[k])
-      })
-    } else {
-      descriptions[key] = desc
-    }
-  }
-  self.getDescriptions = () => descriptions
-
-  let epilog
-  self.epilog = (msg) => {
-    epilog = msg
-  }
-
-  let wrapSet = false
-  let wrap
-  self.wrap = (cols) => {
-    wrapSet = true
-    wrap = cols
-  }
-
-  function getWrap () {
-    if (!wrapSet) {
-      wrap = windowWidth()
-      wrapSet = true
-    }
-
-    return wrap
-  }
-
-  const deferY18nLookupPrefix = '__yargsString__:'
-  self.deferY18nLookup = str => deferY18nLookupPrefix + str
-
-  const defaultGroup = 'Options:'
-  self.help = function help () {
-    normalizeAliases()
-
-    // handle old demanded API
-    const base$0 = path.basename(yargs.$0)
-    const demandedOptions = yargs.getDemandedOptions()
-    const demandedCommands = yargs.getDemandedCommands()
-    const groups = yargs.getGroups()
-    const options = yargs.getOptions()
-
-    let keys = []
-    keys = keys.concat(Object.keys(descriptions))
-    keys = keys.concat(Object.keys(demandedOptions))
-    keys = keys.concat(Object.keys(demandedCommands))
-    keys = keys.concat(Object.keys(options.default))
-    keys = keys.filter(filterHiddenOptions)
-    keys = Object.keys(keys.reduce((acc, key) => {
-      if (key !== '_') acc[key] = true
-      return acc
-    }, {}))
-
-    const theWrap = getWrap()
-    const ui = require('cliui')({
-      width: theWrap,
-      wrap: !!theWrap
-    })
-
-    // the usage string.
-    if (!usageDisabled) {
-      if (usages.length) {
-        // user-defined usage.
-        usages.forEach((usage) => {
-          ui.div(`${usage[0].replace(/\$0/g, base$0)}`)
-          if (usage[1]) {
-            ui.div({ text: `${usage[1]}`, padding: [1, 0, 0, 0] })
-          }
-        })
-        ui.div()
-      } else if (commands.length) {
-        let u = null
-        // demonstrate how commands are used.
-        if (demandedCommands._) {
-          u = `${base$0} <${__('command')}>\n`
-        } else {
-          u = `${base$0} [${__('command')}]\n`
-        }
-        ui.div(`${u}`)
-      }
-    }
-
-    // your application's commands, i.e., non-option
-    // arguments populated in '_'.
-    if (commands.length) {
-      ui.div(__('Commands:'))
-
-      const context = yargs.getContext()
-      const parentCommands = context.commands.length ? `${context.commands.join(' ')} ` : ''
-
-      if (yargs.getParserConfiguration()['sort-commands'] === true) {
-        commands = commands.sort((a, b) => a[0].localeCompare(b[0]))
-      }
-
-      commands.forEach((command) => {
-        const commandString = `${base$0} ${parentCommands}${command[0].replace(/^\$0 ?/, '')}` // drop $0 from default commands.
-        ui.span(
-          {
-            text: commandString,
-            padding: [0, 2, 0, 2],
-            width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4
-          },
-          { text: command[1] }
-        )
-        const hints = []
-        if (command[2]) hints.push(`[${__('default:').slice(0, -1)}]`) // TODO hacking around i18n here
-        if (command[3] && command[3].length) {
-          hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`)
-        }
-        if (hints.length) {
-          ui.div({ text: hints.join(' '), padding: [0, 0, 0, 2], align: 'right' })
-        } else {
-          ui.div()
-        }
-      })
-
-      ui.div()
-    }
-
-    // perform some cleanup on the keys array, making it
-    // only include top-level keys not their aliases.
-    const aliasKeys = (Object.keys(options.alias) || [])
-      .concat(Object.keys(yargs.parsed.newAliases) || [])
-
-    keys = keys.filter(key => !yargs.parsed.newAliases[key] && aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1))
-
-    // populate 'Options:' group with any keys that have not
-    // explicitly had a group set.
-    if (!groups[defaultGroup]) groups[defaultGroup] = []
-    addUngroupedKeys(keys, options.alias, groups)
-
-    // display 'Options:' table along with any custom tables:
-    Object.keys(groups).forEach((groupName) => {
-      if (!groups[groupName].length) return
-
-      // if we've grouped the key 'f', but 'f' aliases 'foobar',
-      // normalizedKeys should contain only 'foobar'.
-      const normalizedKeys = groups[groupName].filter(filterHiddenOptions).map((key) => {
-        if (~aliasKeys.indexOf(key)) return key
-        for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) {
-          if (~(options.alias[aliasKey] || []).indexOf(key)) return aliasKey
-        }
-        return key
-      })
-
-      if (normalizedKeys.length < 1) return
-
-      ui.div(__(groupName))
-
-      // actually generate the switches string --foo, -f, --bar.
-      const switches = normalizedKeys.reduce((acc, key) => {
-        acc[key] = [ key ].concat(options.alias[key] || [])
-          .map(sw => {
-            // for the special positional group don't
-            // add '--' or '-' prefix.
-            if (groupName === self.getPositionalGroupName()) return sw
-            else return (sw.length > 1 ? '--' : '-') + sw
-          })
-          .join(', ')
-
-        return acc
-      }, {})
-
-      normalizedKeys.forEach((key) => {
-        const kswitch = switches[key]
-        let desc = descriptions[key] || ''
-        let type = null
-
-        if (~desc.lastIndexOf(deferY18nLookupPrefix)) desc = __(desc.substring(deferY18nLookupPrefix.length))
-
-        if (~options.boolean.indexOf(key)) type = `[${__('boolean')}]`
-        if (~options.count.indexOf(key)) type = `[${__('count')}]`
-        if (~options.string.indexOf(key)) type = `[${__('string')}]`
-        if (~options.normalize.indexOf(key)) type = `[${__('string')}]`
-        if (~options.array.indexOf(key)) type = `[${__('array')}]`
-        if (~options.number.indexOf(key)) type = `[${__('number')}]`
-
-        const extra = [
-          type,
-          (key in demandedOptions) ? `[${__('required')}]` : null,
-          options.choices && options.choices[key] ? `[${__('choices:')} ${
-            self.stringifiedValues(options.choices[key])}]` : null,
-          defaultString(options.default[key], options.defaultDescription[key])
-        ].filter(Boolean).join(' ')
-
-        ui.span(
-          { text: kswitch, padding: [0, 2, 0, 2], width: maxWidth(switches, theWrap) + 4 },
-          desc
-        )
-
-        if (extra) ui.div({ text: extra, padding: [0, 0, 0, 2], align: 'right' })
-        else ui.div()
-      })
-
-      ui.div()
-    })
-
-    // describe some common use-cases for your application.
-    if (examples.length) {
-      ui.div(__('Examples:'))
-
-      examples.forEach((example) => {
-        example[0] = example[0].replace(/\$0/g, base$0)
-      })
-
-      examples.forEach((example) => {
-        if (example[1] === '') {
-          ui.div(
-            {
-              text: example[0],
-              padding: [0, 2, 0, 2]
-            }
-          )
-        } else {
-          ui.div(
-            {
-              text: example[0],
-              padding: [0, 2, 0, 2],
-              width: maxWidth(examples, theWrap) + 4
-            }, {
-              text: example[1]
-            }
-          )
-        }
-      })
-
-      ui.div()
-    }
-
-    // the usage string.
-    if (epilog) {
-      const e = epilog.replace(/\$0/g, base$0)
-      ui.div(`${e}\n`)
-    }
-
-    // Remove the trailing white spaces
-    return ui.toString().replace(/\s*$/, '')
-  }
-
-  // return the maximum width of a string
-  // in the left-hand column of a table.
-  function maxWidth (table, theWrap, modifier) {
-    let width = 0
-
-    // table might be of the form [leftColumn],
-    // or {key: leftColumn}
-    if (!Array.isArray(table)) {
-      table = Object.keys(table).map(key => [table[key]])
-    }
-
-    table.forEach((v) => {
-      width = Math.max(
-        stringWidth(modifier ? `${modifier} ${v[0]}` : v[0]),
-        width
-      )
-    })
-
-    // if we've enabled 'wrap' we should limit
-    // the max-width of the left-column.
-    if (theWrap) width = Math.min(width, parseInt(theWrap * 0.5, 10))
-
-    return width
-  }
-
-  // make sure any options set for aliases,
-  // are copied to the keys being aliased.
-  function normalizeAliases () {
-    // handle old demanded API
-    const demandedOptions = yargs.getDemandedOptions()
-    const options = yargs.getOptions()
-
-    ;(Object.keys(options.alias) || []).forEach((key) => {
-      options.alias[key].forEach((alias) => {
-        // copy descriptions.
-        if (descriptions[alias]) self.describe(key, descriptions[alias])
-        // copy demanded.
-        if (alias in demandedOptions) yargs.demandOption(key, demandedOptions[alias])
-        // type messages.
-        if (~options.boolean.indexOf(alias)) yargs.boolean(key)
-        if (~options.count.indexOf(alias)) yargs.count(key)
-        if (~options.string.indexOf(alias)) yargs.string(key)
-        if (~options.normalize.indexOf(alias)) yargs.normalize(key)
-        if (~options.array.indexOf(alias)) yargs.array(key)
-        if (~options.number.indexOf(alias)) yargs.number(key)
-      })
-    })
-  }
-
-  // given a set of keys, place any keys that are
-  // ungrouped under the 'Options:' grouping.
-  function addUngroupedKeys (keys, aliases, groups) {
-    let groupedKeys = []
-    let toCheck = null
-    Object.keys(groups).forEach((group) => {
-      groupedKeys = groupedKeys.concat(groups[group])
-    })
-
-    keys.forEach((key) => {
-      toCheck = [key].concat(aliases[key])
-      if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) {
-        groups[defaultGroup].push(key)
-      }
-    })
-    return groupedKeys
-  }
-
-  function filterHiddenOptions (key) {
-    return yargs.getOptions().hiddenOptions.indexOf(key) < 0 || yargs.parsed.argv[yargs.getOptions().showHiddenOpt]
-  }
-
-  self.showHelp = (level) => {
-    const logger = yargs._getLoggerInstance()
-    if (!level) level = 'error'
-    const emit = typeof level === 'function' ? level : logger[level]
-    emit(self.help())
-  }
-
-  self.functionDescription = (fn) => {
-    const description = fn.name ? decamelize(fn.name, '-') : __('generated-value')
-    return ['(', description, ')'].join('')
-  }
-
-  self.stringifiedValues = function stringifiedValues (values, separator) {
-    let string = ''
-    const sep = separator || ', '
-    const array = [].concat(values)
-
-    if (!values || !array.length) return string
-
-    array.forEach((value) => {
-      if (string.length) string += sep
-      string += JSON.stringify(value)
-    })
-
-    return string
-  }
-
-  // format the default-value-string displayed in
-  // the right-hand column.
-  function defaultString (value, defaultDescription) {
-    let string = `[${__('default:')} `
-
-    if (value === undefined && !defaultDescription) return null
-
-    if (defaultDescription) {
-      string += defaultDescription
-    } else {
-      switch (typeof value) {
-        case 'string':
-          string += `"${value}"`
-          break
-        case 'object':
-          string += JSON.stringify(value)
-          break
-        default:
-          string += value
-      }
-    }
-
-    return `${string}]`
-  }
-
-  // guess the width of the console window, max-width 80.
-  function windowWidth () {
-    const maxWidth = 80
-    if (typeof process === 'object' && process.stdout && process.stdout.columns) {
-      return Math.min(maxWidth, process.stdout.columns)
-    } else {
-      return maxWidth
-    }
-  }
-
-  // logic for displaying application version.
-  let version = null
-  self.version = (ver) => {
-    version = ver
-  }
-
-  self.showVersion = () => {
-    const logger = yargs._getLoggerInstance()
-    logger.log(version)
-  }
-
-  self.reset = function reset (localLookup) {
-    // do not reset wrap here
-    // do not reset fails here
-    failMessage = null
-    failureOutput = false
-    usages = []
-    usageDisabled = false
-    epilog = undefined
-    examples = []
-    commands = []
-    descriptions = objFilter(descriptions, (k, v) => !localLookup[k])
-    return self
-  }
-
-  let frozen
-  self.freeze = function freeze () {
-    frozen = {}
-    frozen.failMessage = failMessage
-    frozen.failureOutput = failureOutput
-    frozen.usages = usages
-    frozen.usageDisabled = usageDisabled
-    frozen.epilog = epilog
-    frozen.examples = examples
-    frozen.commands = commands
-    frozen.descriptions = descriptions
-  }
-  self.unfreeze = function unfreeze () {
-    failMessage = frozen.failMessage
-    failureOutput = frozen.failureOutput
-    usages = frozen.usages
-    usageDisabled = frozen.usageDisabled
-    epilog = frozen.epilog
-    examples = frozen.examples
-    commands = frozen.commands
-    descriptions = frozen.descriptions
-    frozen = undefined
-  }
-
-  return self
-}
+"use strict";const decamelize=require("./decamelize"),stringWidth=require("string-width"),objFilter=require("./obj-filter"),path=require("path"),setBlocking=require("set-blocking"),YError=require("./yerror");module.exports=function(e,t){const n=t.__,i={},r=[];i.failFn=function(e){r.push(e)};let o=null,s=!0;i.showHelpOnFail=function(e,t){return"string"==typeof e?(t=e,e=!0):void 0===e&&(e=!0),o=t,s=e,i};let a=!1;i.fail=function(t,n){const c=e._getLoggerInstance();if(!r.length){if(e.getExitProcess()&&setBlocking(!0),a||(a=!0,s&&(e.showHelp("error"),c.error()),(t||n)&&c.error(t||n),o&&((t||n)&&c.error(""),c.error(o))),n=n||new YError(t),e.getExitProcess())return e.exit(1);if(e._hasParseCallback())return e.exit(1,n);throw n}for(let e=r.length-1;e>=0;--e)r[e](t,n,i)};let c=[],l=!1;i.usage=(e,t)=>null===e?(l=!0,void(c=[])):(l=!1,c.push([e,t||""]),i),i.getUsage=()=>c,i.getUsageDisabled=()=>l,i.getPositionalGroupName=()=>n("Positionals:");let d=[];i.example=(e,t)=>{d.push([e,t||""])};let u=[];i.command=function(e,t,n,i){n&&(u=u.map((e=>(e[2]=!1,e)))),u.push([e,t||"",n,i])},i.getCommands=()=>u;let f,g={};i.describe=function(e,t){"object"==typeof e?Object.keys(e).forEach((t=>{i.describe(t,e[t])})):g[e]=t},i.getDescriptions=()=>g,i.epilog=e=>{f=e};let p,h=!1;function m(){return h||(p=function(){const e=80;return"object"==typeof process&&process.stdout&&process.stdout.columns?Math.min(e,process.stdout.columns):e}(),h=!0),p}i.wrap=e=>{h=!0,p=e};const O="__yargsString__:";i.deferY18nLookup=e=>O+e;function b(e,t,n){let i=0;return Array.isArray(e)||(e=Object.keys(e).map((t=>[e[t]]))),e.forEach((e=>{i=Math.max(stringWidth(n?`${n} ${e[0]}`:e[0]),i)})),t&&(i=Math.min(i,parseInt(.5*t,10))),i}function x(t){return e.getOptions().hiddenOptions.indexOf(t)<0||e.parsed.argv[e.getOptions().showHiddenOpt]}function $(e,t){let i=`[${n("default:")} `;if(void 0===e&&!t)return null;if(t)i+=t;else switch(typeof e){case"string":i+=`"${e}"`;break;case"object":i+=JSON.stringify(e);break;default:i+=e}return`${i}]`}i.help=function(){!function(){const t=e.getDemandedOptions(),n=e.getOptions();(Object.keys(n.alias)||[]).forEach((r=>{n.alias[r].forEach((o=>{g[o]&&i.describe(r,g[o]),o in t&&e.demandOption(r,t[o]),~n.boolean.indexOf(o)&&e.boolean(r),~n.count.indexOf(o)&&e.count(r),~n.string.indexOf(o)&&e.string(r),~n.normalize.indexOf(o)&&e.normalize(r),~n.array.indexOf(o)&&e.array(r),~n.number.indexOf(o)&&e.number(r)}))}))}();const t=path.basename(e.$0),r=e.getDemandedOptions(),o=e.getDemandedCommands(),s=e.getGroups(),a=e.getOptions();let p=[];p=p.concat(Object.keys(g)),p=p.concat(Object.keys(r)),p=p.concat(Object.keys(o)),p=p.concat(Object.keys(a.default)),p=p.filter(x),p=Object.keys(p.reduce(((e,t)=>("_"!==t&&(e[t]=!0),e)),{}));const h=m(),y=require("cliui")({width:h,wrap:!!h});if(!l)if(c.length)c.forEach((e=>{y.div(`${e[0].replace(/\$0/g,t)}`),e[1]&&y.div({text:`${e[1]}`,padding:[1,0,0,0]})})),y.div();else if(u.length){let e=null;e=o._?`${t} <${n("command")}>\n`:`${t} [${n("command")}]\n`,y.div(`${e}`)}if(u.length){y.div(n("Commands:"));const i=e.getContext(),r=i.commands.length?`${i.commands.join(" ")} `:"";!0===e.getParserConfiguration()["sort-commands"]&&(u=u.sort(((e,t)=>e[0].localeCompare(t[0])))),u.forEach((e=>{const i=`${t} ${r}${e[0].replace(/^\$0 ?/,"")}`;y.span({text:i,padding:[0,2,0,2],width:b(u,h,`${t}${r}`)+4},{text:e[1]});const o=[];e[2]&&o.push(`[${n("default:").slice(0,-1)}]`),e[3]&&e[3].length&&o.push(`[${n("aliases:")} ${e[3].join(", ")}]`),o.length?y.div({text:o.join(" "),padding:[0,0,0,2],align:"right"}):y.div()})),y.div()}const v=(Object.keys(a.alias)||[]).concat(Object.keys(e.parsed.newAliases)||[]);if(p=p.filter((t=>!e.parsed.newAliases[t]&&v.every((e=>-1===(a.alias[e]||[]).indexOf(t))))),s["Options:"]||(s["Options:"]=[]),function(e,t,n){let i=[],r=null;Object.keys(n).forEach((e=>{i=i.concat(n[e])})),e.forEach((e=>{r=[e].concat(t[e]),r.some((e=>-1!==i.indexOf(e)))||n["Options:"].push(e)}))}(p,a.alias,s),Object.keys(s).forEach((e=>{if(!s[e].length)return;const t=s[e].filter(x).map((e=>{if(~v.indexOf(e))return e;for(let t,n=0;void 0!==(t=v[n]);n++)if(~(a.alias[t]||[]).indexOf(e))return t;return e}));if(t.length<1)return;y.div(n(e));const o=t.reduce(((t,n)=>(t[n]=[n].concat(a.alias[n]||[]).map((t=>e===i.getPositionalGroupName()?t:(t.length>1?"--":"-")+t)).join(", "),t)),{});t.forEach((e=>{const t=o[e];let s=g[e]||"",c=null;~s.lastIndexOf(O)&&(s=n(s.substring(O.length))),~a.boolean.indexOf(e)&&(c=`[${n("boolean")}]`),~a.count.indexOf(e)&&(c=`[${n("count")}]`),~a.string.indexOf(e)&&(c=`[${n("string")}]`),~a.normalize.indexOf(e)&&(c=`[${n("string")}]`),~a.array.indexOf(e)&&(c=`[${n("array")}]`),~a.number.indexOf(e)&&(c=`[${n("number")}]`);const l=[c,e in r?`[${n("required")}]`:null,a.choices&&a.choices[e]?`[${n("choices:")} ${i.stringifiedValues(a.choices[e])}]`:null,$(a.default[e],a.defaultDescription[e])].filter(Boolean).join(" ");y.span({text:t,padding:[0,2,0,2],width:b(o,h)+4},s),l?y.div({text:l,padding:[0,0,0,2],align:"right"}):y.div()})),y.div()})),d.length&&(y.div(n("Examples:")),d.forEach((e=>{e[0]=e[0].replace(/\$0/g,t)})),d.forEach((e=>{""===e[1]?y.div({text:e[0],padding:[0,2,0,2]}):y.div({text:e[0],padding:[0,2,0,2],width:b(d,h)+4},{text:e[1]})})),y.div()),f){const e=f.replace(/\$0/g,t);y.div(`${e}\n`)}return y.toString().replace(/\s*$/,"")},i.showHelp=t=>{const n=e._getLoggerInstance();t||(t="error");("function"==typeof t?t:n[t])(i.help())},i.functionDescription=e=>["(",e.name?decamelize(e.name,"-"):n("generated-value"),")"].join(""),i.stringifiedValues=function(e,t){let n="";const i=t||", ",r=[].concat(e);return e&&r.length?(r.forEach((e=>{n.length&&(n+=i),n+=JSON.stringify(e)})),n):n};let y,v=null;return i.version=e=>{v=e},i.showVersion=()=>{e._getLoggerInstance().log(v)},i.reset=function(e){return o=null,a=!1,c=[],l=!1,f=void 0,d=[],u=[],g=objFilter(g,((t,n)=>!e[t])),i},i.freeze=function(){y={},y.failMessage=o,y.failureOutput=a,y.usages=c,y.usageDisabled=l,y.epilog=f,y.examples=d,y.commands=u,y.descriptions=g},i.unfreeze=function(){o=y.failMessage,a=y.failureOutput,c=y.usages,l=y.usageDisabled,f=y.epilog,d=y.examples,u=y.commands,g=y.descriptions,y=void 0},i};
\ No newline at end of file
index e9bbb12..81cc5a3 100644 (file)
@@ -1,341 +1 @@
-'use strict'
-const argsert = require('./argsert')
-const objFilter = require('./obj-filter')
-const specialKeys = ['$0', '--', '_']
-
-// validation-type-stuff, missing params,
-// bad implications, custom checks.
-module.exports = function validation (yargs, usage, y18n) {
-  const __ = y18n.__
-  const __n = y18n.__n
-  const self = {}
-
-  // validate appropriate # of non-option
-  // arguments were provided, i.e., '_'.
-  self.nonOptionCount = function nonOptionCount (argv) {
-    const demandedCommands = yargs.getDemandedCommands()
-    // don't count currently executing commands
-    const _s = argv._.length - yargs.getContext().commands.length
-
-    if (demandedCommands._ && (_s < demandedCommands._.min || _s > demandedCommands._.max)) {
-      if (_s < demandedCommands._.min) {
-        if (demandedCommands._.minMsg !== undefined) {
-          usage.fail(
-            // replace $0 with observed, $1 with expected.
-            demandedCommands._.minMsg ? demandedCommands._.minMsg.replace(/\$0/g, _s).replace(/\$1/, demandedCommands._.min) : null
-          )
-        } else {
-          usage.fail(
-            __('Not enough non-option arguments: got %s, need at least %s', _s, demandedCommands._.min)
-          )
-        }
-      } else if (_s > demandedCommands._.max) {
-        if (demandedCommands._.maxMsg !== undefined) {
-          usage.fail(
-            // replace $0 with observed, $1 with expected.
-            demandedCommands._.maxMsg ? demandedCommands._.maxMsg.replace(/\$0/g, _s).replace(/\$1/, demandedCommands._.max) : null
-          )
-        } else {
-          usage.fail(
-            __('Too many non-option arguments: got %s, maximum of %s', _s, demandedCommands._.max)
-          )
-        }
-      }
-    }
-  }
-
-  // validate the appropriate # of <required>
-  // positional arguments were provided:
-  self.positionalCount = function positionalCount (required, observed) {
-    if (observed < required) {
-      usage.fail(
-        __('Not enough non-option arguments: got %s, need at least %s', observed, required)
-      )
-    }
-  }
-
-  // make sure all the required arguments are present.
-  self.requiredArguments = function requiredArguments (argv) {
-    const demandedOptions = yargs.getDemandedOptions()
-    let missing = null
-
-    Object.keys(demandedOptions).forEach((key) => {
-      if (!argv.hasOwnProperty(key) || typeof argv[key] === 'undefined') {
-        missing = missing || {}
-        missing[key] = demandedOptions[key]
-      }
-    })
-
-    if (missing) {
-      const customMsgs = []
-      Object.keys(missing).forEach((key) => {
-        const msg = missing[key]
-        if (msg && customMsgs.indexOf(msg) < 0) {
-          customMsgs.push(msg)
-        }
-      })
-
-      const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : ''
-
-      usage.fail(__n(
-        'Missing required argument: %s',
-        'Missing required arguments: %s',
-        Object.keys(missing).length,
-        Object.keys(missing).join(', ') + customMsg
-      ))
-    }
-  }
-
-  // check for unknown arguments (strict-mode).
-  self.unknownArguments = function unknownArguments (argv, aliases, positionalMap) {
-    const commandKeys = yargs.getCommandInstance().getCommands()
-    const unknown = []
-    const currentContext = yargs.getContext()
-
-    Object.keys(argv).forEach((key) => {
-      if (specialKeys.indexOf(key) === -1 &&
-        !positionalMap.hasOwnProperty(key) &&
-        !yargs._getParseContext().hasOwnProperty(key) &&
-        !aliases.hasOwnProperty(key)
-      ) {
-        unknown.push(key)
-      }
-    })
-
-    if (commandKeys.length > 0) {
-      argv._.slice(currentContext.commands.length).forEach((key) => {
-        if (commandKeys.indexOf(key) === -1) {
-          unknown.push(key)
-        }
-      })
-    }
-
-    if (unknown.length > 0) {
-      usage.fail(__n(
-        'Unknown argument: %s',
-        'Unknown arguments: %s',
-        unknown.length,
-        unknown.join(', ')
-      ))
-    }
-  }
-
-  // validate arguments limited to enumerated choices
-  self.limitedChoices = function limitedChoices (argv) {
-    const options = yargs.getOptions()
-    const invalid = {}
-
-    if (!Object.keys(options.choices).length) return
-
-    Object.keys(argv).forEach((key) => {
-      if (specialKeys.indexOf(key) === -1 &&
-        options.choices.hasOwnProperty(key)) {
-        [].concat(argv[key]).forEach((value) => {
-          // TODO case-insensitive configurability
-          if (options.choices[key].indexOf(value) === -1 &&
-              value !== undefined) {
-            invalid[key] = (invalid[key] || []).concat(value)
-          }
-        })
-      }
-    })
-
-    const invalidKeys = Object.keys(invalid)
-
-    if (!invalidKeys.length) return
-
-    let msg = __('Invalid values:')
-    invalidKeys.forEach((key) => {
-      msg += `\n  ${__(
-        'Argument: %s, Given: %s, Choices: %s',
-        key,
-        usage.stringifiedValues(invalid[key]),
-        usage.stringifiedValues(options.choices[key])
-      )}`
-    })
-    usage.fail(msg)
-  }
-
-  // custom checks, added using the `check` option on yargs.
-  let checks = []
-  self.check = function check (f, global) {
-    checks.push({
-      func: f,
-      global
-    })
-  }
-
-  self.customChecks = function customChecks (argv, aliases) {
-    for (let i = 0, f; (f = checks[i]) !== undefined; i++) {
-      const func = f.func
-      let result = null
-      try {
-        result = func(argv, aliases)
-      } catch (err) {
-        usage.fail(err.message ? err.message : err, err)
-        continue
-      }
-
-      if (!result) {
-        usage.fail(__('Argument check failed: %s', func.toString()))
-      } else if (typeof result === 'string' || result instanceof Error) {
-        usage.fail(result.toString(), result)
-      }
-    }
-  }
-
-  // check implications, argument foo implies => argument bar.
-  let implied = {}
-  self.implies = function implies (key, value) {
-    argsert('<string|object> [array|number|string]', [key, value], arguments.length)
-
-    if (typeof key === 'object') {
-      Object.keys(key).forEach((k) => {
-        self.implies(k, key[k])
-      })
-    } else {
-      yargs.global(key)
-      if (!implied[key]) {
-        implied[key] = []
-      }
-      if (Array.isArray(value)) {
-        value.forEach((i) => self.implies(key, i))
-      } else {
-        implied[key].push(value)
-      }
-    }
-  }
-  self.getImplied = function getImplied () {
-    return implied
-  }
-
-  self.implications = function implications (argv) {
-    const implyFail = []
-
-    Object.keys(implied).forEach((key) => {
-      const origKey = key
-      ;(implied[key] || []).forEach((value) => {
-        let num
-        let key = origKey
-        const origValue = value
-
-        // convert string '1' to number 1
-        num = Number(key)
-        key = isNaN(num) ? key : num
-
-        if (typeof key === 'number') {
-          // check length of argv._
-          key = argv._.length >= key
-        } else if (key.match(/^--no-.+/)) {
-          // check if key doesn't exist
-          key = key.match(/^--no-(.+)/)[1]
-          key = !argv[key]
-        } else {
-          // check if key exists
-          key = argv[key]
-        }
-
-        num = Number(value)
-        value = isNaN(num) ? value : num
-
-        if (typeof value === 'number') {
-          value = argv._.length >= value
-        } else if (value.match(/^--no-.+/)) {
-          value = value.match(/^--no-(.+)/)[1]
-          value = !argv[value]
-        } else {
-          value = argv[value]
-        }
-        if (key && !value) {
-          implyFail.push(` ${origKey} -> ${origValue}`)
-        }
-      })
-    })
-
-    if (implyFail.length) {
-      let msg = `${__('Implications failed:')}\n`
-
-      implyFail.forEach((value) => {
-        msg += (value)
-      })
-
-      usage.fail(msg)
-    }
-  }
-
-  let conflicting = {}
-  self.conflicts = function conflicts (key, value) {
-    argsert('<string|object> [array|string]', [key, value], arguments.length)
-
-    if (typeof key === 'object') {
-      Object.keys(key).forEach((k) => {
-        self.conflicts(k, key[k])
-      })
-    } else {
-      yargs.global(key)
-      if (!conflicting[key]) {
-        conflicting[key] = []
-      }
-      if (Array.isArray(value)) {
-        value.forEach((i) => self.conflicts(key, i))
-      } else {
-        conflicting[key].push(value)
-      }
-    }
-  }
-  self.getConflicting = () => conflicting
-
-  self.conflicting = function conflictingFn (argv) {
-    Object.keys(argv).forEach((key) => {
-      if (conflicting[key]) {
-        conflicting[key].forEach((value) => {
-          // we default keys to 'undefined' that have been configured, we should not
-          // apply conflicting check unless they are a value other than 'undefined'.
-          if (value && argv[key] !== undefined && argv[value] !== undefined) {
-            usage.fail(__('Arguments %s and %s are mutually exclusive', key, value))
-          }
-        })
-      }
-    })
-  }
-
-  self.recommendCommands = function recommendCommands (cmd, potentialCommands) {
-    const distance = require('./levenshtein')
-    const threshold = 3 // if it takes more than three edits, let's move on.
-    potentialCommands = potentialCommands.sort((a, b) => b.length - a.length)
-
-    let recommended = null
-    let bestDistance = Infinity
-    for (let i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) {
-      const d = distance(cmd, candidate)
-      if (d <= threshold && d < bestDistance) {
-        bestDistance = d
-        recommended = candidate
-      }
-    }
-    if (recommended) usage.fail(__('Did you mean %s?', recommended))
-  }
-
-  self.reset = function reset (localLookup) {
-    implied = objFilter(implied, (k, v) => !localLookup[k])
-    conflicting = objFilter(conflicting, (k, v) => !localLookup[k])
-    checks = checks.filter(c => c.global)
-    return self
-  }
-
-  let frozen
-  self.freeze = function freeze () {
-    frozen = {}
-    frozen.implied = implied
-    frozen.checks = checks
-    frozen.conflicting = conflicting
-  }
-  self.unfreeze = function unfreeze () {
-    implied = frozen.implied
-    checks = frozen.checks
-    conflicting = frozen.conflicting
-    frozen = undefined
-  }
-
-  return self
-}
+"use strict";const argsert=require("./argsert"),objFilter=require("./obj-filter"),specialKeys=["$0","--","_"];module.exports=function(e,n,t){const o=t.__,i=t.__n,s={nonOptionCount:function(t){const i=e.getDemandedCommands(),s=t._.length-e.getContext().commands.length;i._&&(s<i._.min||s>i._.max)&&(s<i._.min?void 0!==i._.minMsg?n.fail(i._.minMsg?i._.minMsg.replace(/\$0/g,s).replace(/\$1/,i._.min):null):n.fail(o("Not enough non-option arguments: got %s, need at least %s",s,i._.min)):s>i._.max&&(void 0!==i._.maxMsg?n.fail(i._.maxMsg?i._.maxMsg.replace(/\$0/g,s).replace(/\$1/,i._.max):null):n.fail(o("Too many non-option arguments: got %s, maximum of %s",s,i._.max))))},positionalCount:function(e,t){t<e&&n.fail(o("Not enough non-option arguments: got %s, need at least %s",t,e))},requiredArguments:function(t){const o=e.getDemandedOptions();let s=null;if(Object.keys(o).forEach((e=>{t.hasOwnProperty(e)&&void 0!==t[e]||(s=s||{},s[e]=o[e])})),s){const e=[];Object.keys(s).forEach((n=>{const t=s[n];t&&e.indexOf(t)<0&&e.push(t)}));const t=e.length?`\n${e.join("\n")}`:"";n.fail(i("Missing required argument: %s","Missing required arguments: %s",Object.keys(s).length,Object.keys(s).join(", ")+t))}},unknownArguments:function(t,o,s){const c=e.getCommandInstance().getCommands(),r=[],a=e.getContext();Object.keys(t).forEach((n=>{-1!==specialKeys.indexOf(n)||s.hasOwnProperty(n)||e._getParseContext().hasOwnProperty(n)||o.hasOwnProperty(n)||r.push(n)})),c.length>0&&t._.slice(a.commands.length).forEach((e=>{-1===c.indexOf(e)&&r.push(e)})),r.length>0&&n.fail(i("Unknown argument: %s","Unknown arguments: %s",r.length,r.join(", ")))},limitedChoices:function(t){const i=e.getOptions(),s={};if(!Object.keys(i.choices).length)return;Object.keys(t).forEach((e=>{-1===specialKeys.indexOf(e)&&i.choices.hasOwnProperty(e)&&[].concat(t[e]).forEach((n=>{-1===i.choices[e].indexOf(n)&&void 0!==n&&(s[e]=(s[e]||[]).concat(n))}))}));const c=Object.keys(s);if(!c.length)return;let r=o("Invalid values:");c.forEach((e=>{r+=`\n  ${o("Argument: %s, Given: %s, Choices: %s",e,n.stringifiedValues(s[e]),n.stringifiedValues(i.choices[e]))}`})),n.fail(r)}};let c=[];s.check=function(e,n){c.push({func:e,global:n})},s.customChecks=function(e,t){for(let i,s=0;void 0!==(i=c[s]);s++){const s=i.func;let c=null;try{c=s(e,t)}catch(e){n.fail(e.message?e.message:e,e);continue}c?("string"==typeof c||c instanceof Error)&&n.fail(c.toString(),c):n.fail(o("Argument check failed: %s",s.toString()))}};let r={};s.implies=function(n,t){argsert("<string|object> [array|number|string]",[n,t],arguments.length),"object"==typeof n?Object.keys(n).forEach((e=>{s.implies(e,n[e])})):(e.global(n),r[n]||(r[n]=[]),Array.isArray(t)?t.forEach((e=>s.implies(n,e))):r[n].push(t))},s.getImplied=function(){return r},s.implications=function(e){const t=[];if(Object.keys(r).forEach((n=>{const o=n;(r[n]||[]).forEach((n=>{let i,s=o;const c=n;i=Number(s),s=isNaN(i)?s:i,"number"==typeof s?s=e._.length>=s:s.match(/^--no-.+/)?(s=s.match(/^--no-(.+)/)[1],s=!e[s]):s=e[s],i=Number(n),"number"==typeof(n=isNaN(i)?n:i)?n=e._.length>=n:n.match(/^--no-.+/)?(n=n.match(/^--no-(.+)/)[1],n=!e[n]):n=e[n],s&&!n&&t.push(` ${o} -> ${c}`)}))})),t.length){let e=`${o("Implications failed:")}\n`;t.forEach((n=>{e+=n})),n.fail(e)}};let a,l={};return s.conflicts=function(n,t){argsert("<string|object> [array|string]",[n,t],arguments.length),"object"==typeof n?Object.keys(n).forEach((e=>{s.conflicts(e,n[e])})):(e.global(n),l[n]||(l[n]=[]),Array.isArray(t)?t.forEach((e=>s.conflicts(n,e))):l[n].push(t))},s.getConflicting=()=>l,s.conflicting=function(e){Object.keys(e).forEach((t=>{l[t]&&l[t].forEach((i=>{i&&void 0!==e[t]&&void 0!==e[i]&&n.fail(o("Arguments %s and %s are mutually exclusive",t,i))}))}))},s.recommendCommands=function(e,t){const i=require("./levenshtein");t=t.sort(((e,n)=>n.length-e.length));let s=null,c=1/0;for(let n,o=0;void 0!==(n=t[o]);o++){const t=i(e,n);t<=3&&t<c&&(c=t,s=n)}s&&n.fail(o("Did you mean %s?",s))},s.reset=function(e){return r=objFilter(r,((n,t)=>!e[n])),l=objFilter(l,((n,t)=>!e[n])),c=c.filter((e=>e.global)),s},s.freeze=function(){a={},a.implied=r,a.checks=c,a.conflicting=l},s.unfreeze=function(){r=a.implied,c=a.checks,l=a.conflicting,a=void 0},s};
\ No newline at end of file
index 53375a0..4189603 100644 (file)
@@ -1,11 +1 @@
-'use strict'
-function YError (msg) {
-  this.name = 'YError'
-  this.message = msg || 'yargs error'
-  Error.captureStackTrace(this, YError)
-}
-
-YError.prototype = Object.create(Error.prototype)
-YError.prototype.constructor = YError
-
-module.exports = YError
+"use strict";function YError(r){this.name="YError",this.message=r||"yargs error",Error.captureStackTrace(this,YError)}YError.prototype=Object.create(Error.prototype),YError.prototype.constructor=YError,module.exports=YError;
\ No newline at end of file
index 81d2193..e266fc9 100644 (file)
@@ -1,1215 +1 @@
-'use strict'
-const argsert = require('./lib/argsert')
-const fs = require('fs')
-const Command = require('./lib/command')
-const Completion = require('./lib/completion')
-const Parser = require('yargs-parser')
-const path = require('path')
-const Usage = require('./lib/usage')
-const Validation = require('./lib/validation')
-const Y18n = require('y18n')
-const objFilter = require('./lib/obj-filter')
-const setBlocking = require('set-blocking')
-const applyExtends = require('./lib/apply-extends')
-const { globalMiddlewareFactory } = require('./lib/middleware')
-const YError = require('./lib/yerror')
-
-exports = module.exports = Yargs
-function Yargs (processArgs, cwd, parentRequire) {
-  processArgs = processArgs || [] // handle calling yargs().
-
-  const self = {}
-  let command = null
-  let completion = null
-  let groups = {}
-  let globalMiddleware = []
-  let output = ''
-  let preservedGroups = {}
-  let usage = null
-  let validation = null
-
-  const y18n = Y18n({
-    directory: path.resolve(__dirname, './locales'),
-    updateFiles: false
-  })
-
-  self.middleware = globalMiddlewareFactory(globalMiddleware, self)
-
-  if (!cwd) cwd = process.cwd()
-
-  self.scriptName = function scriptName (scriptName) {
-    self.$0 = scriptName
-    return self
-  }
-
-  // ignore the node bin, specify this in your
-  // bin file with #!/usr/bin/env node
-  if (/\b(node|iojs|electron)(\.exe)?$/.test(process.argv[0])) {
-    self.$0 = process.argv.slice(1, 2)
-  } else {
-    self.$0 = process.argv.slice(0, 1)
-  }
-
-  self.$0 = self.$0
-    .map((x, i) => {
-      const b = rebase(cwd, x)
-      return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x
-    })
-    .join(' ').trim()
-
-  if (process.env._ !== undefined && process.argv[1] === process.env._) {
-    self.$0 = process.env._.replace(
-      `${path.dirname(process.execPath)}/`, ''
-    )
-  }
-
-  // use context object to keep track of resets, subcommand execution, etc
-  // submodules should modify and check the state of context as necessary
-  const context = { resets: -1, commands: [], fullCommands: [], files: [] }
-  self.getContext = () => context
-
-  // puts yargs back into an initial state. any keys
-  // that have been set to "global" will not be reset
-  // by this action.
-  let options
-  self.resetOptions = self.reset = function resetOptions (aliases) {
-    context.resets++
-    aliases = aliases || {}
-    options = options || {}
-    // put yargs back into an initial state, this
-    // logic is used to build a nested command
-    // hierarchy.
-    const tmpOptions = {}
-    tmpOptions.local = options.local ? options.local : []
-    tmpOptions.configObjects = options.configObjects ? options.configObjects : []
-
-    // if a key has been explicitly set as local,
-    // we should reset it before passing options to command.
-    const localLookup = {}
-    tmpOptions.local.forEach((l) => {
-      localLookup[l] = true
-      ;(aliases[l] || []).forEach((a) => {
-        localLookup[a] = true
-      })
-    })
-
-    // preserve all groups not set to local.
-    preservedGroups = Object.keys(groups).reduce((acc, groupName) => {
-      const keys = groups[groupName].filter(key => !(key in localLookup))
-      if (keys.length > 0) {
-        acc[groupName] = keys
-      }
-      return acc
-    }, {})
-    // groups can now be reset
-    groups = {}
-
-    const arrayOptions = [
-      'array', 'boolean', 'string', 'skipValidation',
-      'count', 'normalize', 'number',
-      'hiddenOptions'
-    ]
-
-    const objectOptions = [
-      'narg', 'key', 'alias', 'default', 'defaultDescription',
-      'config', 'choices', 'demandedOptions', 'demandedCommands', 'coerce'
-    ]
-
-    arrayOptions.forEach((k) => {
-      tmpOptions[k] = (options[k] || []).filter(k => !localLookup[k])
-    })
-
-    objectOptions.forEach((k) => {
-      tmpOptions[k] = objFilter(options[k], (k, v) => !localLookup[k])
-    })
-
-    tmpOptions.envPrefix = options.envPrefix
-    options = tmpOptions
-
-    // if this is the first time being executed, create
-    // instances of all our helpers -- otherwise just reset.
-    usage = usage ? usage.reset(localLookup) : Usage(self, y18n)
-    validation = validation ? validation.reset(localLookup) : Validation(self, usage, y18n)
-    command = command ? command.reset() : Command(self, usage, validation, globalMiddleware)
-    if (!completion) completion = Completion(self, usage, command)
-
-    completionCommand = null
-    output = ''
-    exitError = null
-    hasOutput = false
-    self.parsed = false
-
-    return self
-  }
-  self.resetOptions()
-
-  // temporary hack: allow "freezing" of reset-able state for parse(msg, cb)
-  let frozen
-  function freeze () {
-    frozen = {}
-    frozen.options = options
-    frozen.configObjects = options.configObjects.slice(0)
-    frozen.exitProcess = exitProcess
-    frozen.groups = groups
-    usage.freeze()
-    validation.freeze()
-    command.freeze()
-    frozen.strict = strict
-    frozen.completionCommand = completionCommand
-    frozen.output = output
-    frozen.exitError = exitError
-    frozen.hasOutput = hasOutput
-    frozen.parsed = self.parsed
-  }
-  function unfreeze () {
-    options = frozen.options
-    options.configObjects = frozen.configObjects
-    exitProcess = frozen.exitProcess
-    groups = frozen.groups
-    output = frozen.output
-    exitError = frozen.exitError
-    hasOutput = frozen.hasOutput
-    self.parsed = frozen.parsed
-    usage.unfreeze()
-    validation.unfreeze()
-    command.unfreeze()
-    strict = frozen.strict
-    completionCommand = frozen.completionCommand
-    parseFn = null
-    parseContext = null
-    frozen = undefined
-  }
-
-  self.boolean = function (keys) {
-    argsert('<array|string>', [keys], arguments.length)
-    populateParserHintArray('boolean', keys)
-    return self
-  }
-
-  self.array = function (keys) {
-    argsert('<array|string>', [keys], arguments.length)
-    populateParserHintArray('array', keys)
-    return self
-  }
-
-  self.number = function (keys) {
-    argsert('<array|string>', [keys], arguments.length)
-    populateParserHintArray('number', keys)
-    return self
-  }
-
-  self.normalize = function (keys) {
-    argsert('<array|string>', [keys], arguments.length)
-    populateParserHintArray('normalize', keys)
-    return self
-  }
-
-  self.count = function (keys) {
-    argsert('<array|string>', [keys], arguments.length)
-    populateParserHintArray('count', keys)
-    return self
-  }
-
-  self.string = function (keys) {
-    argsert('<array|string>', [keys], arguments.length)
-    populateParserHintArray('string', keys)
-    return self
-  }
-
-  self.requiresArg = function (keys) {
-    argsert('<array|string>', [keys], arguments.length)
-    populateParserHintObject(self.nargs, false, 'narg', keys, 1)
-    return self
-  }
-
-  self.skipValidation = function (keys) {
-    argsert('<array|string>', [keys], arguments.length)
-    populateParserHintArray('skipValidation', keys)
-    return self
-  }
-
-  function populateParserHintArray (type, keys, value) {
-    keys = [].concat(keys)
-    keys.forEach((key) => {
-      key = sanitizeKey(key)
-      options[type].push(key)
-    })
-  }
-
-  self.nargs = function (key, value) {
-    argsert('<string|object|array> [number]', [key, value], arguments.length)
-    populateParserHintObject(self.nargs, false, 'narg', key, value)
-    return self
-  }
-
-  self.choices = function (key, value) {
-    argsert('<object|string|array> [string|array]', [key, value], arguments.length)
-    populateParserHintObject(self.choices, true, 'choices', key, value)
-    return self
-  }
-
-  self.alias = function (key, value) {
-    argsert('<object|string|array> [string|array]', [key, value], arguments.length)
-    populateParserHintObject(self.alias, true, 'alias', key, value)
-    return self
-  }
-
-  // TODO: actually deprecate self.defaults.
-  self.default = self.defaults = function (key, value, defaultDescription) {
-    argsert('<object|string|array> [*] [string]', [key, value, defaultDescription], arguments.length)
-    if (defaultDescription) options.defaultDescription[key] = defaultDescription
-    if (typeof value === 'function') {
-      if (!options.defaultDescription[key]) options.defaultDescription[key] = usage.functionDescription(value)
-      value = value.call()
-    }
-    populateParserHintObject(self.default, false, 'default', key, value)
-    return self
-  }
-
-  self.describe = function (key, desc) {
-    argsert('<object|string|array> [string]', [key, desc], arguments.length)
-    populateParserHintObject(self.describe, false, 'key', key, true)
-    usage.describe(key, desc)
-    return self
-  }
-
-  self.demandOption = function (keys, msg) {
-    argsert('<object|string|array> [string]', [keys, msg], arguments.length)
-    populateParserHintObject(self.demandOption, false, 'demandedOptions', keys, msg)
-    return self
-  }
-
-  self.coerce = function (keys, value) {
-    argsert('<object|string|array> [function]', [keys, value], arguments.length)
-    populateParserHintObject(self.coerce, false, 'coerce', keys, value)
-    return self
-  }
-
-  function populateParserHintObject (builder, isArray, type, key, value) {
-    if (Array.isArray(key)) {
-      const temp = Object.create(null)
-      // an array of keys with one value ['x', 'y', 'z'], function parse () {}
-      key.forEach((k) => {
-        temp[k] = value
-      })
-      builder(temp)
-    } else if (typeof key === 'object') {
-      // an object of key value pairs: {'x': parse () {}, 'y': parse() {}}
-      Object.keys(key).forEach((k) => {
-        builder(k, key[k])
-      })
-    } else {
-      key = sanitizeKey(key)
-      // a single key value pair 'x', parse() {}
-      if (isArray) {
-        options[type][key] = (options[type][key] || []).concat(value)
-      } else {
-        options[type][key] = value
-      }
-    }
-  }
-
-  // TODO(bcoe): in future major versions move more objects towards
-  // Object.create(null):
-  function sanitizeKey (key) {
-    if (key === '__proto__') return '___proto___'
-    return key
-  }
-
-  function deleteFromParserHintObject (optionKey) {
-    // delete from all parsing hints:
-    // boolean, array, key, alias, etc.
-    Object.keys(options).forEach((hintKey) => {
-      const hint = options[hintKey]
-      if (Array.isArray(hint)) {
-        if (~hint.indexOf(optionKey)) hint.splice(hint.indexOf(optionKey), 1)
-      } else if (typeof hint === 'object') {
-        delete hint[optionKey]
-      }
-    })
-    // now delete the description from usage.js.
-    delete usage.getDescriptions()[optionKey]
-  }
-
-  self.config = function config (key, msg, parseFn) {
-    argsert('[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length)
-    // allow a config object to be provided directly.
-    if (typeof key === 'object') {
-      key = applyExtends(key, cwd)
-      options.configObjects = (options.configObjects || []).concat(key)
-      return self
-    }
-
-    // allow for a custom parsing function.
-    if (typeof msg === 'function') {
-      parseFn = msg
-      msg = null
-    }
-
-    key = key || 'config'
-    self.describe(key, msg || usage.deferY18nLookup('Path to JSON config file'))
-    ;(Array.isArray(key) ? key : [key]).forEach((k) => {
-      options.config[k] = parseFn || true
-    })
-
-    return self
-  }
-
-  self.example = function (cmd, description) {
-    argsert('<string> [string]', [cmd, description], arguments.length)
-    usage.example(cmd, description)
-    return self
-  }
-
-  self.command = function (cmd, description, builder, handler, middlewares) {
-    argsert('<string|array|object> [string|boolean] [function|object] [function] [array]', [cmd, description, builder, handler, middlewares], arguments.length)
-    command.addHandler(cmd, description, builder, handler, middlewares)
-    return self
-  }
-
-  self.commandDir = function (dir, opts) {
-    argsert('<string> [object]', [dir, opts], arguments.length)
-    const req = parentRequire || require
-    command.addDirectory(dir, self.getContext(), req, require('get-caller-file')(), opts)
-    return self
-  }
-
-  // TODO: deprecate self.demand in favor of
-  // .demandCommand() .demandOption().
-  self.demand = self.required = self.require = function demand (keys, max, msg) {
-    // you can optionally provide a 'max' key,
-    // which will raise an exception if too many '_'
-    // options are provided.
-    if (Array.isArray(max)) {
-      max.forEach((key) => {
-        self.demandOption(key, msg)
-      })
-      max = Infinity
-    } else if (typeof max !== 'number') {
-      msg = max
-      max = Infinity
-    }
-
-    if (typeof keys === 'number') {
-      self.demandCommand(keys, max, msg, msg)
-    } else if (Array.isArray(keys)) {
-      keys.forEach((key) => {
-        self.demandOption(key, msg)
-      })
-    } else {
-      if (typeof msg === 'string') {
-        self.demandOption(keys, msg)
-      } else if (msg === true || typeof msg === 'undefined') {
-        self.demandOption(keys)
-      }
-    }
-
-    return self
-  }
-
-  self.demandCommand = function demandCommand (min, max, minMsg, maxMsg) {
-    argsert('[number] [number|string] [string|null|undefined] [string|null|undefined]', [min, max, minMsg, maxMsg], arguments.length)
-
-    if (typeof min === 'undefined') min = 1
-
-    if (typeof max !== 'number') {
-      minMsg = max
-      max = Infinity
-    }
-
-    self.global('_', false)
-
-    options.demandedCommands._ = {
-      min,
-      max,
-      minMsg,
-      maxMsg
-    }
-
-    return self
-  }
-
-  self.getDemandedOptions = () => {
-    argsert([], 0)
-    return options.demandedOptions
-  }
-
-  self.getDemandedCommands = () => {
-    argsert([], 0)
-    return options.demandedCommands
-  }
-
-  self.implies = function (key, value) {
-    argsert('<string|object> [number|string|array]', [key, value], arguments.length)
-    validation.implies(key, value)
-    return self
-  }
-
-  self.conflicts = function (key1, key2) {
-    argsert('<string|object> [string|array]', [key1, key2], arguments.length)
-    validation.conflicts(key1, key2)
-    return self
-  }
-
-  self.usage = function (msg, description, builder, handler) {
-    argsert('<string|null|undefined> [string|boolean] [function|object] [function]', [msg, description, builder, handler], arguments.length)
-
-    if (description !== undefined) {
-      // .usage() can be used as an alias for defining
-      // a default command.
-      if ((msg || '').match(/^\$0( |$)/)) {
-        return self.command(msg, description, builder, handler)
-      } else {
-        throw new YError('.usage() description must start with $0 if being used as alias for .command()')
-      }
-    } else {
-      usage.usage(msg)
-      return self
-    }
-  }
-
-  self.epilogue = self.epilog = function (msg) {
-    argsert('<string>', [msg], arguments.length)
-    usage.epilog(msg)
-    return self
-  }
-
-  self.fail = function (f) {
-    argsert('<function>', [f], arguments.length)
-    usage.failFn(f)
-    return self
-  }
-
-  self.check = function (f, _global) {
-    argsert('<function> [boolean]', [f, _global], arguments.length)
-    validation.check(f, _global !== false)
-    return self
-  }
-
-  self.global = function global (globals, global) {
-    argsert('<string|array> [boolean]', [globals, global], arguments.length)
-    globals = [].concat(globals)
-    if (global !== false) {
-      options.local = options.local.filter(l => globals.indexOf(l) === -1)
-    } else {
-      globals.forEach((g) => {
-        if (options.local.indexOf(g) === -1) options.local.push(g)
-      })
-    }
-    return self
-  }
-
-  self.pkgConf = function pkgConf (key, rootPath) {
-    argsert('<string> [string]', [key, rootPath], arguments.length)
-    let conf = null
-    // prefer cwd to require-main-filename in this method
-    // since we're looking for e.g. "nyc" config in nyc consumer
-    // rather than "yargs" config in nyc (where nyc is the main filename)
-    const obj = pkgUp(rootPath || cwd)
-
-    // If an object exists in the key, add it to options.configObjects
-    if (obj[key] && typeof obj[key] === 'object') {
-      conf = applyExtends(obj[key], rootPath || cwd)
-      options.configObjects = (options.configObjects || []).concat(conf)
-    }
-
-    return self
-  }
-
-  const pkgs = {}
-  function pkgUp (rootPath) {
-    const npath = rootPath || '*'
-    if (pkgs[npath]) return pkgs[npath]
-    const findUp = require('find-up')
-
-    let obj = {}
-    try {
-      let startDir = rootPath || require('require-main-filename')(parentRequire || require)
-
-      // When called in an environment that lacks require.main.filename, such as a jest test runner,
-      // startDir is already process.cwd(), and should not be shortened.
-      // Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it.
-      if (!rootPath && path.extname(startDir)) {
-        startDir = path.dirname(startDir)
-      }
-
-      const pkgJsonPath = findUp.sync('package.json', {
-        cwd: startDir
-      })
-      obj = JSON.parse(fs.readFileSync(pkgJsonPath))
-    } catch (noop) {}
-
-    pkgs[npath] = obj || {}
-    return pkgs[npath]
-  }
-
-  let parseFn = null
-  let parseContext = null
-  self.parse = function parse (args, shortCircuit, _parseFn) {
-    argsert('[string|array] [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length)
-    if (typeof args === 'undefined') {
-      return self._parseArgs(processArgs)
-    }
-
-    // a context object can optionally be provided, this allows
-    // additional information to be passed to a command handler.
-    if (typeof shortCircuit === 'object') {
-      parseContext = shortCircuit
-      shortCircuit = _parseFn
-    }
-
-    // by providing a function as a second argument to
-    // parse you can capture output that would otherwise
-    // default to printing to stdout/stderr.
-    if (typeof shortCircuit === 'function') {
-      parseFn = shortCircuit
-      shortCircuit = null
-    }
-    // completion short-circuits the parsing process,
-    // skipping validation, etc.
-    if (!shortCircuit) processArgs = args
-
-    freeze()
-    if (parseFn) exitProcess = false
-
-    const parsed = self._parseArgs(args, shortCircuit)
-    if (parseFn) parseFn(exitError, parsed, output)
-    unfreeze()
-
-    return parsed
-  }
-
-  self._getParseContext = () => parseContext || {}
-
-  self._hasParseCallback = () => !!parseFn
-
-  self.option = self.options = function option (key, opt) {
-    argsert('<string|object> [object]', [key, opt], arguments.length)
-    if (typeof key === 'object') {
-      Object.keys(key).forEach((k) => {
-        self.options(k, key[k])
-      })
-    } else {
-      if (typeof opt !== 'object') {
-        opt = {}
-      }
-
-      options.key[key] = true // track manually set keys.
-
-      if (opt.alias) self.alias(key, opt.alias)
-
-      const demand = opt.demand || opt.required || opt.require
-
-      // deprecated, use 'demandOption' instead
-      if (demand) {
-        self.demand(key, demand)
-      }
-
-      if (opt.demandOption) {
-        self.demandOption(key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined)
-      }
-
-      if ('conflicts' in opt) {
-        self.conflicts(key, opt.conflicts)
-      }
-
-      if ('default' in opt) {
-        self.default(key, opt.default)
-      }
-
-      if ('implies' in opt) {
-        self.implies(key, opt.implies)
-      }
-
-      if ('nargs' in opt) {
-        self.nargs(key, opt.nargs)
-      }
-
-      if (opt.config) {
-        self.config(key, opt.configParser)
-      }
-
-      if (opt.normalize) {
-        self.normalize(key)
-      }
-
-      if ('choices' in opt) {
-        self.choices(key, opt.choices)
-      }
-
-      if ('coerce' in opt) {
-        self.coerce(key, opt.coerce)
-      }
-
-      if ('group' in opt) {
-        self.group(key, opt.group)
-      }
-
-      if (opt.boolean || opt.type === 'boolean') {
-        self.boolean(key)
-        if (opt.alias) self.boolean(opt.alias)
-      }
-
-      if (opt.array || opt.type === 'array') {
-        self.array(key)
-        if (opt.alias) self.array(opt.alias)
-      }
-
-      if (opt.number || opt.type === 'number') {
-        self.number(key)
-        if (opt.alias) self.number(opt.alias)
-      }
-
-      if (opt.string || opt.type === 'string') {
-        self.string(key)
-        if (opt.alias) self.string(opt.alias)
-      }
-
-      if (opt.count || opt.type === 'count') {
-        self.count(key)
-      }
-
-      if (typeof opt.global === 'boolean') {
-        self.global(key, opt.global)
-      }
-
-      if (opt.defaultDescription) {
-        options.defaultDescription[key] = opt.defaultDescription
-      }
-
-      if (opt.skipValidation) {
-        self.skipValidation(key)
-      }
-
-      const desc = opt.describe || opt.description || opt.desc
-      self.describe(key, desc)
-      if (opt.hidden) {
-        self.hide(key)
-      }
-
-      if (opt.requiresArg) {
-        self.requiresArg(key)
-      }
-    }
-
-    return self
-  }
-  self.getOptions = () => options
-
-  self.positional = function (key, opts) {
-    argsert('<string> <object>', [key, opts], arguments.length)
-    if (context.resets === 0) {
-      throw new YError(".positional() can only be called in a command's builder function")
-    }
-
-    // .positional() only supports a subset of the configuration
-    // options available to .option().
-    const supportedOpts = ['default', 'defaultDescription', 'implies', 'normalize',
-      'choices', 'conflicts', 'coerce', 'type', 'describe',
-      'desc', 'description', 'alias']
-    opts = objFilter(opts, (k, v) => {
-      let accept = supportedOpts.indexOf(k) !== -1
-      // type can be one of string|number|boolean.
-      if (k === 'type' && ['string', 'number', 'boolean'].indexOf(v) === -1) accept = false
-      return accept
-    })
-
-    // copy over any settings that can be inferred from the command string.
-    const fullCommand = context.fullCommands[context.fullCommands.length - 1]
-    const parseOptions = fullCommand ? command.cmdToParseOptions(fullCommand) : {
-      array: [],
-      alias: {},
-      default: {},
-      demand: {}
-    }
-    Object.keys(parseOptions).forEach((pk) => {
-      if (Array.isArray(parseOptions[pk])) {
-        if (parseOptions[pk].indexOf(key) !== -1) opts[pk] = true
-      } else {
-        if (parseOptions[pk][key] && !(pk in opts)) opts[pk] = parseOptions[pk][key]
-      }
-    })
-    self.group(key, usage.getPositionalGroupName())
-    return self.option(key, opts)
-  }
-
-  self.group = function group (opts, groupName) {
-    argsert('<string|array> <string>', [opts, groupName], arguments.length)
-    const existing = preservedGroups[groupName] || groups[groupName]
-    if (preservedGroups[groupName]) {
-      // we now only need to track this group name in groups.
-      delete preservedGroups[groupName]
-    }
-
-    const seen = {}
-    groups[groupName] = (existing || []).concat(opts).filter((key) => {
-      if (seen[key]) return false
-      return (seen[key] = true)
-    })
-    return self
-  }
-  // combine explicit and preserved groups. explicit groups should be first
-  self.getGroups = () => Object.assign({}, groups, preservedGroups)
-
-  // as long as options.envPrefix is not undefined,
-  // parser will apply env vars matching prefix to argv
-  self.env = function (prefix) {
-    argsert('[string|boolean]', [prefix], arguments.length)
-    if (prefix === false) options.envPrefix = undefined
-    else options.envPrefix = prefix || ''
-    return self
-  }
-
-  self.wrap = function (cols) {
-    argsert('<number|null|undefined>', [cols], arguments.length)
-    usage.wrap(cols)
-    return self
-  }
-
-  let strict = false
-  self.strict = function (enabled) {
-    argsert('[boolean]', [enabled], arguments.length)
-    strict = enabled !== false
-    return self
-  }
-  self.getStrict = () => strict
-
-  let parserConfig = {}
-  self.parserConfiguration = function parserConfiguration (config) {
-    argsert('<object>', [config], arguments.length)
-    parserConfig = config
-    return self
-  }
-  self.getParserConfiguration = () => parserConfig
-
-  self.showHelp = function (level) {
-    argsert('[string|function]', [level], arguments.length)
-    if (!self.parsed) self._parseArgs(processArgs) // run parser, if it has not already been executed.
-    if (command.hasDefaultCommand()) {
-      context.resets++ // override the restriction on top-level positoinals.
-      command.runDefaultBuilderOn(self, true)
-    }
-    usage.showHelp(level)
-    return self
-  }
-
-  let versionOpt = null
-  self.version = function version (opt, msg, ver) {
-    const defaultVersionOpt = 'version'
-    argsert('[boolean|string] [string] [string]', [opt, msg, ver], arguments.length)
-
-    // nuke the key previously configured
-    // to return version #.
-    if (versionOpt) {
-      deleteFromParserHintObject(versionOpt)
-      usage.version(undefined)
-      versionOpt = null
-    }
-
-    if (arguments.length === 0) {
-      ver = guessVersion()
-      opt = defaultVersionOpt
-    } else if (arguments.length === 1) {
-      if (opt === false) { // disable default 'version' key.
-        return self
-      }
-      ver = opt
-      opt = defaultVersionOpt
-    } else if (arguments.length === 2) {
-      ver = msg
-      msg = null
-    }
-
-    versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt
-    msg = msg || usage.deferY18nLookup('Show version number')
-
-    usage.version(ver || undefined)
-    self.boolean(versionOpt)
-    self.describe(versionOpt, msg)
-    return self
-  }
-
-  function guessVersion () {
-    const obj = pkgUp()
-
-    return obj.version || 'unknown'
-  }
-
-  let helpOpt = null
-  self.addHelpOpt = self.help = function addHelpOpt (opt, msg) {
-    const defaultHelpOpt = 'help'
-    argsert('[string|boolean] [string]', [opt, msg], arguments.length)
-
-    // nuke the key previously configured
-    // to return help.
-    if (helpOpt) {
-      deleteFromParserHintObject(helpOpt)
-      helpOpt = null
-    }
-
-    if (arguments.length === 1) {
-      if (opt === false) return self
-    }
-
-    // use arguments, fallback to defaults for opt and msg
-    helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt
-    self.boolean(helpOpt)
-    self.describe(helpOpt, msg || usage.deferY18nLookup('Show help'))
-    return self
-  }
-
-  const defaultShowHiddenOpt = 'show-hidden'
-  options.showHiddenOpt = defaultShowHiddenOpt
-  self.addShowHiddenOpt = self.showHidden = function addShowHiddenOpt (opt, msg) {
-    argsert('[string|boolean] [string]', [opt, msg], arguments.length)
-
-    if (arguments.length === 1) {
-      if (opt === false) return self
-    }
-
-    const showHiddenOpt = typeof opt === 'string' ? opt : defaultShowHiddenOpt
-    self.boolean(showHiddenOpt)
-    self.describe(showHiddenOpt, msg || usage.deferY18nLookup('Show hidden options'))
-    options.showHiddenOpt = showHiddenOpt
-    return self
-  }
-
-  self.hide = function hide (key) {
-    argsert('<string|object>', [key], arguments.length)
-    options.hiddenOptions.push(key)
-    return self
-  }
-
-  self.showHelpOnFail = function showHelpOnFail (enabled, message) {
-    argsert('[boolean|string] [string]', [enabled, message], arguments.length)
-    usage.showHelpOnFail(enabled, message)
-    return self
-  }
-
-  var exitProcess = true
-  self.exitProcess = function (enabled) {
-    argsert('[boolean]', [enabled], arguments.length)
-    if (typeof enabled !== 'boolean') {
-      enabled = true
-    }
-    exitProcess = enabled
-    return self
-  }
-  self.getExitProcess = () => exitProcess
-
-  var completionCommand = null
-  self.completion = function (cmd, desc, fn) {
-    argsert('[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length)
-
-    // a function to execute when generating
-    // completions can be provided as the second
-    // or third argument to completion.
-    if (typeof desc === 'function') {
-      fn = desc
-      desc = null
-    }
-
-    // register the completion command.
-    completionCommand = cmd || 'completion'
-    if (!desc && desc !== false) {
-      desc = 'generate completion script'
-    }
-    self.command(completionCommand, desc)
-
-    // a function can be provided
-    if (fn) completion.registerFunction(fn)
-
-    return self
-  }
-
-  self.showCompletionScript = function ($0) {
-    argsert('[string]', [$0], arguments.length)
-    $0 = $0 || self.$0
-    _logger.log(completion.generateCompletionScript($0, completionCommand))
-    return self
-  }
-
-  self.getCompletion = function (args, done) {
-    argsert('<array> <function>', [args, done], arguments.length)
-    completion.getCompletion(args, done)
-  }
-
-  self.locale = function (locale) {
-    argsert('[string]', [locale], arguments.length)
-    if (arguments.length === 0) {
-      guessLocale()
-      return y18n.getLocale()
-    }
-    detectLocale = false
-    y18n.setLocale(locale)
-    return self
-  }
-
-  self.updateStrings = self.updateLocale = function (obj) {
-    argsert('<object>', [obj], arguments.length)
-    detectLocale = false
-    y18n.updateLocale(obj)
-    return self
-  }
-
-  let detectLocale = true
-  self.detectLocale = function (detect) {
-    argsert('<boolean>', [detect], arguments.length)
-    detectLocale = detect
-    return self
-  }
-  self.getDetectLocale = () => detectLocale
-
-  var hasOutput = false
-  var exitError = null
-  // maybe exit, always capture
-  // context about why we wanted to exit.
-  self.exit = (code, err) => {
-    hasOutput = true
-    exitError = err
-    if (exitProcess) process.exit(code)
-  }
-
-  // we use a custom logger that buffers output,
-  // so that we can print to non-CLIs, e.g., chat-bots.
-  const _logger = {
-    log () {
-      const args = []
-      for (let i = 0; i < arguments.length; i++) args.push(arguments[i])
-      if (!self._hasParseCallback()) console.log.apply(console, args)
-      hasOutput = true
-      if (output.length) output += '\n'
-      output += args.join(' ')
-    },
-    error () {
-      const args = []
-      for (let i = 0; i < arguments.length; i++) args.push(arguments[i])
-      if (!self._hasParseCallback()) console.error.apply(console, args)
-      hasOutput = true
-      if (output.length) output += '\n'
-      output += args.join(' ')
-    }
-  }
-  self._getLoggerInstance = () => _logger
-  // has yargs output an error our help
-  // message in the current execution context.
-  self._hasOutput = () => hasOutput
-
-  self._setHasOutput = () => {
-    hasOutput = true
-  }
-
-  let recommendCommands
-  self.recommendCommands = function (recommend) {
-    argsert('[boolean]', [recommend], arguments.length)
-    recommendCommands = typeof recommend === 'boolean' ? recommend : true
-    return self
-  }
-
-  self.getUsageInstance = () => usage
-
-  self.getValidationInstance = () => validation
-
-  self.getCommandInstance = () => command
-
-  self.terminalWidth = () => {
-    argsert([], 0)
-    return typeof process.stdout.columns !== 'undefined' ? process.stdout.columns : null
-  }
-
-  Object.defineProperty(self, 'argv', {
-    get: () => self._parseArgs(processArgs),
-    enumerable: true
-  })
-
-  self._parseArgs = function parseArgs (args, shortCircuit, _skipValidation, commandIndex) {
-    let skipValidation = !!_skipValidation
-    args = args || processArgs
-
-    options.__ = y18n.__
-    options.configuration = self.getParserConfiguration()
-
-    // Deprecated
-    let pkgConfig = pkgUp()['yargs']
-    if (pkgConfig) {
-      console.warn('Configuring yargs through package.json is deprecated and will be removed in the next major release, please use the JS API instead.')
-      options.configuration = Object.assign({}, pkgConfig, options.configuration)
-    }
-
-    const parsed = Parser.detailed(args, options)
-    let argv = parsed.argv
-    if (parseContext) argv = Object.assign({}, argv, parseContext)
-    const aliases = parsed.aliases
-
-    argv.$0 = self.$0
-    self.parsed = parsed
-
-    try {
-      guessLocale() // guess locale lazily, so that it can be turned off in chain.
-
-      // while building up the argv object, there
-      // are two passes through the parser. If completion
-      // is being performed short-circuit on the first pass.
-      if (shortCircuit) {
-        return argv
-      }
-
-      // if there's a handler associated with a
-      // command defer processing to it.
-      if (helpOpt) {
-        // consider any multi-char helpOpt alias as a valid help command
-        // unless all helpOpt aliases are single-char
-        // note that parsed.aliases is a normalized bidirectional map :)
-        const helpCmds = [helpOpt]
-          .concat(aliases[helpOpt] || [])
-          .filter(k => k.length > 1)
-        // check if help should trigger and strip it from _.
-        if (~helpCmds.indexOf(argv._[argv._.length - 1])) {
-          argv._.pop()
-          argv[helpOpt] = true
-        }
-      }
-
-      const handlerKeys = command.getCommands()
-      const requestCompletions = completion.completionKey in argv
-      const skipRecommendation = argv[helpOpt] || requestCompletions
-      const skipDefaultCommand = skipRecommendation && (handlerKeys.length > 1 || handlerKeys[0] !== '$0')
-
-      if (argv._.length) {
-        if (handlerKeys.length) {
-          let firstUnknownCommand
-          for (let i = (commandIndex || 0), cmd; argv._[i] !== undefined; i++) {
-            cmd = String(argv._[i])
-            if (~handlerKeys.indexOf(cmd) && cmd !== completionCommand) {
-              // commands are executed using a recursive algorithm that executes
-              // the deepest command first; we keep track of the position in the
-              // argv._ array that is currently being executed.
-              return command.runCommand(cmd, self, parsed, i + 1)
-            } else if (!firstUnknownCommand && cmd !== completionCommand) {
-              firstUnknownCommand = cmd
-              break
-            }
-          }
-
-          // run the default command, if defined
-          if (command.hasDefaultCommand() && !skipDefaultCommand) {
-            return command.runCommand(null, self, parsed)
-          }
-
-          // recommend a command if recommendCommands() has
-          // been enabled, and no commands were found to execute
-          if (recommendCommands && firstUnknownCommand && !skipRecommendation) {
-            validation.recommendCommands(firstUnknownCommand, handlerKeys)
-          }
-        }
-
-        // generate a completion script for adding to ~/.bashrc.
-        if (completionCommand && ~argv._.indexOf(completionCommand) && !requestCompletions) {
-          if (exitProcess) setBlocking(true)
-          self.showCompletionScript()
-          self.exit(0)
-        }
-      } else if (command.hasDefaultCommand() && !skipDefaultCommand) {
-        return command.runCommand(null, self, parsed)
-      }
-
-      // we must run completions first, a user might
-      // want to complete the --help or --version option.
-      if (requestCompletions) {
-        if (exitProcess) setBlocking(true)
-
-        // we allow for asynchronous completions,
-        // e.g., loading in a list of commands from an API.
-        const completionArgs = args.slice(args.indexOf(`--${completion.completionKey}`) + 1)
-        completion.getCompletion(completionArgs, (completions) => {
-          ;(completions || []).forEach((completion) => {
-            _logger.log(completion)
-          })
-
-          self.exit(0)
-        })
-        return argv
-      }
-
-      // Handle 'help' and 'version' options
-      // if we haven't already output help!
-      if (!hasOutput) {
-        Object.keys(argv).forEach((key) => {
-          if (key === helpOpt && argv[key]) {
-            if (exitProcess) setBlocking(true)
-
-            skipValidation = true
-            self.showHelp('log')
-            self.exit(0)
-          } else if (key === versionOpt && argv[key]) {
-            if (exitProcess) setBlocking(true)
-
-            skipValidation = true
-            usage.showVersion()
-            self.exit(0)
-          }
-        })
-      }
-
-      // Check if any of the options to skip validation were provided
-      if (!skipValidation && options.skipValidation.length > 0) {
-        skipValidation = Object.keys(argv).some(key => options.skipValidation.indexOf(key) >= 0 && argv[key] === true)
-      }
-
-      // If the help or version options where used and exitProcess is false,
-      // or if explicitly skipped, we won't run validations.
-      if (!skipValidation) {
-        if (parsed.error) throw new YError(parsed.error.message)
-
-        // if we're executed via bash completion, don't
-        // bother with validation.
-        if (!requestCompletions) {
-          self._runValidation(argv, aliases, {}, parsed.error)
-        }
-      }
-    } catch (err) {
-      if (err instanceof YError) usage.fail(err.message, err)
-      else throw err
-    }
-
-    return argv
-  }
-
-  self._runValidation = function runValidation (argv, aliases, positionalMap, parseErrors) {
-    if (parseErrors) throw new YError(parseErrors.message || parseErrors)
-    validation.nonOptionCount(argv)
-    validation.requiredArguments(argv)
-    if (strict) validation.unknownArguments(argv, aliases, positionalMap)
-    validation.customChecks(argv, aliases)
-    validation.limitedChoices(argv)
-    validation.implications(argv)
-    validation.conflicting(argv)
-  }
-
-  function guessLocale () {
-    if (!detectLocale) return
-
-    try {
-      const { env } = process
-      const locale = env.LC_ALL || env.LC_MESSAGES || env.LANG || env.LANGUAGE || 'en_US'
-      self.locale(locale.replace(/[.:].*/, ''))
-    } catch (err) {
-      // if we explode looking up locale just noop
-      // we'll keep using the default language 'en'.
-    }
-  }
-
-  // an app should almost always have --version and --help,
-  // if you *really* want to disable this use .help(false)/.version(false).
-  self.help()
-  self.version()
-
-  return self
-}
-
-// rebase an absolute path to a relative one with respect to a base directory
-// exported for tests
-exports.rebase = rebase
-function rebase (base, dir) {
-  return path.relative(base, dir)
-}
+"use strict";const argsert=require("./lib/argsert"),fs=require("fs"),Command=require("./lib/command"),Completion=require("./lib/completion"),Parser=require("yargs-parser"),path=require("path"),Usage=require("./lib/usage"),Validation=require("./lib/validation"),Y18n=require("y18n"),objFilter=require("./lib/obj-filter"),setBlocking=require("set-blocking"),applyExtends=require("./lib/apply-extends"),{globalMiddlewareFactory:globalMiddlewareFactory}=require("./lib/middleware"),YError=require("./lib/yerror");function Yargs(e,n,r){e=e||[];const t={};let o=null,i=null,a={},s=[],l="",c={},u=null,g=null;const f=Y18n({directory:path.resolve(__dirname,"./locales"),updateFiles:!1});t.middleware=globalMiddlewareFactory(s,t),n||(n=process.cwd()),t.scriptName=function(e){return t.$0=e,t},/\b(node|iojs|electron)(\.exe)?$/.test(process.argv[0])?t.$0=process.argv.slice(1,2):t.$0=process.argv.slice(0,1),t.$0=t.$0.map(((e,r)=>{const t=rebase(n,e);return e.match(/^(\/|([a-zA-Z]:)?\\)/)&&t.length<e.length?t:e})).join(" ").trim(),void 0!==process.env._&&process.argv[1]===process.env._&&(t.$0=process.env._.replace(`${path.dirname(process.execPath)}/`,""));const d={resets:-1,commands:[],fullCommands:[],files:[]};let p,m;function h(){m={},m.options=p,m.configObjects=p.configObjects.slice(0),m.exitProcess=S,m.groups=a,u.freeze(),g.freeze(),o.freeze(),m.strict=w,m.completionCommand=L,m.output=l,m.exitError=z,m.hasOutput=Y,m.parsed=t.parsed}function b(){p=m.options,p.configObjects=m.configObjects,S=m.exitProcess,a=m.groups,l=m.output,z=m.exitError,Y=m.hasOutput,t.parsed=m.parsed,u.unfreeze(),g.unfreeze(),o.unfreeze(),w=m.strict,L=m.completionCommand,v=null,k=null,m=void 0}function y(e,n,r){(n=[].concat(n)).forEach((n=>{n=j(n),p[e].push(n)}))}function O(e,n,r,t,o){if(Array.isArray(t)){const n=Object.create(null);t.forEach((e=>{n[e]=o})),e(n)}else"object"==typeof t?Object.keys(t).forEach((n=>{e(n,t[n])})):(t=j(t),p[r][t]=n?(p[r][t]||[]).concat(o):o)}function j(e){return"__proto__"===e?"___proto___":e}function C(e){Object.keys(p).forEach((n=>{const r=p[n];Array.isArray(r)?~r.indexOf(e)&&r.splice(r.indexOf(e),1):"object"==typeof r&&delete r[e]})),delete u.getDescriptions()[e]}t.getContext=()=>d,t.resetOptions=t.reset=function(e){d.resets++,e=e||{},p=p||{};const n={};n.local=p.local?p.local:[],n.configObjects=p.configObjects?p.configObjects:[];const r={};n.local.forEach((n=>{r[n]=!0,(e[n]||[]).forEach((e=>{r[e]=!0}))})),c=Object.keys(a).reduce(((e,n)=>{const t=a[n].filter((e=>!(e in r)));return t.length>0&&(e[n]=t),e}),{}),a={};return["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"].forEach((e=>{n[e]=(p[e]||[]).filter((e=>!r[e]))})),["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","coerce"].forEach((e=>{n[e]=objFilter(p[e],((e,n)=>!r[e]))})),n.envPrefix=p.envPrefix,p=n,u=u?u.reset(r):Usage(t,f),g=g?g.reset(r):Validation(t,u,f),o=o?o.reset():Command(t,u,g,s),i||(i=Completion(t,u,o)),L=null,l="",z=null,Y=!1,t.parsed=!1,t},t.resetOptions(),t.boolean=function(e){return argsert("<array|string>",[e],arguments.length),y("boolean",e),t},t.array=function(e){return argsert("<array|string>",[e],arguments.length),y("array",e),t},t.number=function(e){return argsert("<array|string>",[e],arguments.length),y("number",e),t},t.normalize=function(e){return argsert("<array|string>",[e],arguments.length),y("normalize",e),t},t.count=function(e){return argsert("<array|string>",[e],arguments.length),y("count",e),t},t.string=function(e){return argsert("<array|string>",[e],arguments.length),y("string",e),t},t.requiresArg=function(e){return argsert("<array|string>",[e],arguments.length),O(t.nargs,!1,"narg",e,1),t},t.skipValidation=function(e){return argsert("<array|string>",[e],arguments.length),y("skipValidation",e),t},t.nargs=function(e,n){return argsert("<string|object|array> [number]",[e,n],arguments.length),O(t.nargs,!1,"narg",e,n),t},t.choices=function(e,n){return argsert("<object|string|array> [string|array]",[e,n],arguments.length),O(t.choices,!0,"choices",e,n),t},t.alias=function(e,n){return argsert("<object|string|array> [string|array]",[e,n],arguments.length),O(t.alias,!0,"alias",e,n),t},t.default=t.defaults=function(e,n,r){return argsert("<object|string|array> [*] [string]",[e,n,r],arguments.length),r&&(p.defaultDescription[e]=r),"function"==typeof n&&(p.defaultDescription[e]||(p.defaultDescription[e]=u.functionDescription(n)),n=n.call()),O(t.default,!1,"default",e,n),t},t.describe=function(e,n){return argsert("<object|string|array> [string]",[e,n],arguments.length),O(t.describe,!1,"key",e,!0),u.describe(e,n),t},t.demandOption=function(e,n){return argsert("<object|string|array> [string]",[e,n],arguments.length),O(t.demandOption,!1,"demandedOptions",e,n),t},t.coerce=function(e,n){return argsert("<object|string|array> [function]",[e,n],arguments.length),O(t.coerce,!1,"coerce",e,n),t},t.config=function(e,r,o){return argsert("[object|string] [string|function] [function]",[e,r,o],arguments.length),"object"==typeof e?(e=applyExtends(e,n),p.configObjects=(p.configObjects||[]).concat(e),t):("function"==typeof r&&(o=r,r=null),e=e||"config",t.describe(e,r||u.deferY18nLookup("Path to JSON config file")),(Array.isArray(e)?e:[e]).forEach((e=>{p.config[e]=o||!0})),t)},t.example=function(e,n){return argsert("<string> [string]",[e,n],arguments.length),u.example(e,n),t},t.command=function(e,n,r,i,a){return argsert("<string|array|object> [string|boolean] [function|object] [function] [array]",[e,n,r,i,a],arguments.length),o.addHandler(e,n,r,i,a),t},t.commandDir=function(e,n){argsert("<string> [object]",[e,n],arguments.length);const i=r||require;return o.addDirectory(e,t.getContext(),i,require("get-caller-file")(),n),t},t.demand=t.required=t.require=function(e,n,r){return Array.isArray(n)?(n.forEach((e=>{t.demandOption(e,r)})),n=1/0):"number"!=typeof n&&(r=n,n=1/0),"number"==typeof e?t.demandCommand(e,n,r,r):Array.isArray(e)?e.forEach((e=>{t.demandOption(e,r)})):"string"==typeof r?t.demandOption(e,r):!0!==r&&void 0!==r||t.demandOption(e),t},t.demandCommand=function(e,n,r,o){return argsert("[number] [number|string] [string|null|undefined] [string|null|undefined]",[e,n,r,o],arguments.length),void 0===e&&(e=1),"number"!=typeof n&&(r=n,n=1/0),t.global("_",!1),p.demandedCommands._={min:e,max:n,minMsg:r,maxMsg:o},t},t.getDemandedOptions=()=>(argsert([],0),p.demandedOptions),t.getDemandedCommands=()=>(argsert([],0),p.demandedCommands),t.implies=function(e,n){return argsert("<string|object> [number|string|array]",[e,n],arguments.length),g.implies(e,n),t},t.conflicts=function(e,n){return argsert("<string|object> [string|array]",[e,n],arguments.length),g.conflicts(e,n),t},t.usage=function(e,n,r,o){if(argsert("<string|null|undefined> [string|boolean] [function|object] [function]",[e,n,r,o],arguments.length),void 0!==n){if((e||"").match(/^\$0( |$)/))return t.command(e,n,r,o);throw new YError(".usage() description must start with $0 if being used as alias for .command()")}return u.usage(e),t},t.epilogue=t.epilog=function(e){return argsert("<string>",[e],arguments.length),u.epilog(e),t},t.fail=function(e){return argsert("<function>",[e],arguments.length),u.failFn(e),t},t.check=function(e,n){return argsert("<function> [boolean]",[e,n],arguments.length),g.check(e,!1!==n),t},t.global=function(e,n){return argsert("<string|array> [boolean]",[e,n],arguments.length),e=[].concat(e),!1!==n?p.local=p.local.filter((n=>-1===e.indexOf(n))):e.forEach((e=>{-1===p.local.indexOf(e)&&p.local.push(e)})),t},t.pkgConf=function(e,r){argsert("<string> [string]",[e,r],arguments.length);let o=null;const i=_(r||n);return i[e]&&"object"==typeof i[e]&&(o=applyExtends(i[e],r||n),p.configObjects=(p.configObjects||[]).concat(o)),t};const x={};function _(e){const n=e||"*";if(x[n])return x[n];const t=require("find-up");let o={};try{let n=e||require("require-main-filename")(r||require);!e&&path.extname(n)&&(n=path.dirname(n));const i=t.sync("package.json",{cwd:n});o=JSON.parse(fs.readFileSync(i))}catch(e){}return x[n]=o||{},x[n]}let v=null,k=null;t.parse=function(n,r,o){if(argsert("[string|array] [function|boolean|object] [function]",[n,r,o],arguments.length),void 0===n)return t._parseArgs(e);"object"==typeof r&&(k=r,r=o),"function"==typeof r&&(v=r,r=null),r||(e=n),h(),v&&(S=!1);const i=t._parseArgs(n,r);return v&&v(z,i,l),b(),i},t._getParseContext=()=>k||{},t._hasParseCallback=()=>!!v,t.option=t.options=function(e,n){if(argsert("<string|object> [object]",[e,n],arguments.length),"object"==typeof e)Object.keys(e).forEach((n=>{t.options(n,e[n])}));else{"object"!=typeof n&&(n={}),p.key[e]=!0,n.alias&&t.alias(e,n.alias);const r=n.demand||n.required||n.require;r&&t.demand(e,r),n.demandOption&&t.demandOption(e,"string"==typeof n.demandOption?n.demandOption:void 0),"conflicts"in n&&t.conflicts(e,n.conflicts),"default"in n&&t.default(e,n.default),"implies"in n&&t.implies(e,n.implies),"nargs"in n&&t.nargs(e,n.nargs),n.config&&t.config(e,n.configParser),n.normalize&&t.normalize(e),"choices"in n&&t.choices(e,n.choices),"coerce"in n&&t.coerce(e,n.coerce),"group"in n&&t.group(e,n.group),(n.boolean||"boolean"===n.type)&&(t.boolean(e),n.alias&&t.boolean(n.alias)),(n.array||"array"===n.type)&&(t.array(e),n.alias&&t.array(n.alias)),(n.number||"number"===n.type)&&(t.number(e),n.alias&&t.number(n.alias)),(n.string||"string"===n.type)&&(t.string(e),n.alias&&t.string(n.alias)),(n.count||"count"===n.type)&&t.count(e),"boolean"==typeof n.global&&t.global(e,n.global),n.defaultDescription&&(p.defaultDescription[e]=n.defaultDescription),n.skipValidation&&t.skipValidation(e);const o=n.describe||n.description||n.desc;t.describe(e,o),n.hidden&&t.hide(e),n.requiresArg&&t.requiresArg(e)}return t},t.getOptions=()=>p,t.positional=function(e,n){if(argsert("<string> <object>",[e,n],arguments.length),0===d.resets)throw new YError(".positional() can only be called in a command's builder function");const r=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];n=objFilter(n,((e,n)=>{let t=-1!==r.indexOf(e);return"type"===e&&-1===["string","number","boolean"].indexOf(n)&&(t=!1),t}));const i=d.fullCommands[d.fullCommands.length-1],a=i?o.cmdToParseOptions(i):{array:[],alias:{},default:{},demand:{}};return Object.keys(a).forEach((r=>{Array.isArray(a[r])?-1!==a[r].indexOf(e)&&(n[r]=!0):a[r][e]&&!(r in n)&&(n[r]=a[r][e])})),t.group(e,u.getPositionalGroupName()),t.option(e,n)},t.group=function(e,n){argsert("<string|array> <string>",[e,n],arguments.length);const r=c[n]||a[n];c[n]&&delete c[n];const o={};return a[n]=(r||[]).concat(e).filter((e=>!o[e]&&(o[e]=!0))),t},t.getGroups=()=>Object.assign({},a,c),t.env=function(e){return argsert("[string|boolean]",[e],arguments.length),p.envPrefix=!1===e?void 0:e||"",t},t.wrap=function(e){return argsert("<number|null|undefined>",[e],arguments.length),u.wrap(e),t};let w=!1;t.strict=function(e){return argsert("[boolean]",[e],arguments.length),w=!1!==e,t},t.getStrict=()=>w;let E={};t.parserConfiguration=function(e){return argsert("<object>",[e],arguments.length),E=e,t},t.getParserConfiguration=()=>E,t.showHelp=function(n){return argsert("[string|function]",[n],arguments.length),t.parsed||t._parseArgs(e),o.hasDefaultCommand()&&(d.resets++,o.runDefaultBuilderOn(t,!0)),u.showHelp(n),t};let A=null;function q(){return _().version||"unknown"}t.version=function(e,n,r){const o="version";if(argsert("[boolean|string] [string] [string]",[e,n,r],arguments.length),A&&(C(A),u.version(void 0),A=null),0===arguments.length)r=q(),e=o;else if(1===arguments.length){if(!1===e)return t;r=e,e=o}else 2===arguments.length&&(r=n,n=null);return A="string"==typeof e?e:o,n=n||u.deferY18nLookup("Show version number"),u.version(r||void 0),t.boolean(A),t.describe(A,n),t};let P=null;t.addHelpOpt=t.help=function(e,n){const r="help";return argsert("[string|boolean] [string]",[e,n],arguments.length),P&&(C(P),P=null),1===arguments.length&&!1===e||(P="string"==typeof e?e:r,t.boolean(P),t.describe(P,n||u.deferY18nLookup("Show help"))),t};const D="show-hidden";p.showHiddenOpt=D,t.addShowHiddenOpt=t.showHidden=function(e,n){if(argsert("[string|boolean] [string]",[e,n],arguments.length),1===arguments.length&&!1===e)return t;const r="string"==typeof e?e:D;return t.boolean(r),t.describe(r,n||u.deferY18nLookup("Show hidden options")),p.showHiddenOpt=r,t},t.hide=function(e){return argsert("<string|object>",[e],arguments.length),p.hiddenOptions.push(e),t},t.showHelpOnFail=function(e,n){return argsert("[boolean|string] [string]",[e,n],arguments.length),u.showHelpOnFail(e,n),t};var S=!0;t.exitProcess=function(e){return argsert("[boolean]",[e],arguments.length),"boolean"!=typeof e&&(e=!0),S=e,t},t.getExitProcess=()=>S;var L=null;t.completion=function(e,n,r){return argsert("[string] [string|boolean|function] [function]",[e,n,r],arguments.length),"function"==typeof n&&(r=n,n=null),L=e||"completion",n||!1===n||(n="generate completion script"),t.command(L,n),r&&i.registerFunction(r),t},t.showCompletionScript=function(e){return argsert("[string]",[e],arguments.length),e=e||t.$0,V.log(i.generateCompletionScript(e,L)),t},t.getCompletion=function(e,n){argsert("<array> <function>",[e,n],arguments.length),i.getCompletion(e,n)},t.locale=function(e){return argsert("[string]",[e],arguments.length),0===arguments.length?(H(),f.getLocale()):($=!1,f.setLocale(e),t)},t.updateStrings=t.updateLocale=function(e){return argsert("<object>",[e],arguments.length),$=!1,f.updateLocale(e),t};let $=!0;t.detectLocale=function(e){return argsert("<boolean>",[e],arguments.length),$=e,t},t.getDetectLocale=()=>$;var Y=!1,z=null;t.exit=(e,n)=>{Y=!0,z=n,S&&process.exit(e)};const V={log(){const e=[];for(let n=0;n<arguments.length;n++)e.push(arguments[n]);t._hasParseCallback()||console.log.apply(console,e),Y=!0,l.length&&(l+="\n"),l+=e.join(" ")},error(){const e=[];for(let n=0;n<arguments.length;n++)e.push(arguments[n]);t._hasParseCallback()||console.error.apply(console,e),Y=!0,l.length&&(l+="\n"),l+=e.join(" ")}};let F;function H(){if($)try{const{env:e}=process,n=e.LC_ALL||e.LC_MESSAGES||e.LANG||e.LANGUAGE||"en_US";t.locale(n.replace(/[.:].*/,""))}catch(e){}}return t._getLoggerInstance=()=>V,t._hasOutput=()=>Y,t._setHasOutput=()=>{Y=!0},t.recommendCommands=function(e){return argsert("[boolean]",[e],arguments.length),F="boolean"!=typeof e||e,t},t.getUsageInstance=()=>u,t.getValidationInstance=()=>g,t.getCommandInstance=()=>o,t.terminalWidth=()=>(argsert([],0),void 0!==process.stdout.columns?process.stdout.columns:null),Object.defineProperty(t,"argv",{get:()=>t._parseArgs(e),enumerable:!0}),t._parseArgs=function(n,r,a,s){let l=!!a;n=n||e,p.__=f.__,p.configuration=t.getParserConfiguration();let c=_().yargs;c&&(console.warn("Configuring yargs through package.json is deprecated and will be removed in the next major release, please use the JS API instead."),p.configuration=Object.assign({},c,p.configuration));const d=Parser.detailed(n,p);let m=d.argv;k&&(m=Object.assign({},m,k));const h=d.aliases;m.$0=t.$0,t.parsed=d;try{if(H(),r)return m;if(P){~[P].concat(h[P]||[]).filter((e=>e.length>1)).indexOf(m._[m._.length-1])&&(m._.pop(),m[P]=!0)}const e=o.getCommands(),a=i.completionKey in m,c=m[P]||a,f=c&&(e.length>1||"$0"!==e[0]);if(m._.length){if(e.length){let n;for(let r,i=s||0;void 0!==m._[i];i++){if(r=String(m._[i]),~e.indexOf(r)&&r!==L)return o.runCommand(r,t,d,i+1);if(!n&&r!==L){n=r;break}}if(o.hasDefaultCommand()&&!f)return o.runCommand(null,t,d);F&&n&&!c&&g.recommendCommands(n,e)}L&&~m._.indexOf(L)&&!a&&(S&&setBlocking(!0),t.showCompletionScript(),t.exit(0))}else if(o.hasDefaultCommand()&&!f)return o.runCommand(null,t,d);if(a){S&&setBlocking(!0);const e=n.slice(n.indexOf(`--${i.completionKey}`)+1);return i.getCompletion(e,(e=>{(e||[]).forEach((e=>{V.log(e)})),t.exit(0)})),m}if(Y||Object.keys(m).forEach((e=>{e===P&&m[e]?(S&&setBlocking(!0),l=!0,t.showHelp("log"),t.exit(0)):e===A&&m[e]&&(S&&setBlocking(!0),l=!0,u.showVersion(),t.exit(0))})),!l&&p.skipValidation.length>0&&(l=Object.keys(m).some((e=>p.skipValidation.indexOf(e)>=0&&!0===m[e]))),!l){if(d.error)throw new YError(d.error.message);a||t._runValidation(m,h,{},d.error)}}catch(e){if(!(e instanceof YError))throw e;u.fail(e.message,e)}return m},t._runValidation=function(e,n,r,t){if(t)throw new YError(t.message||t);g.nonOptionCount(e),g.requiredArguments(e),w&&g.unknownArguments(e,n,r),g.customChecks(e,n),g.limitedChoices(e),g.implications(e),g.conflicting(e)},t.help(),t.version(),t}function rebase(e,n){return path.relative(e,n)}exports=module.exports=Yargs,exports.rebase=rebase;
\ No newline at end of file
index 7299762..c0caeca 100644 (file)
@@ -1,68 +1 @@
-'use strict';
-
-var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('')
-  , length = 64
-  , map = {}
-  , seed = 0
-  , i = 0
-  , prev;
-
-/**
- * Return a string representing the specified number.
- *
- * @param {Number} num The number to convert.
- * @returns {String} The string representation of the number.
- * @api public
- */
-function encode(num) {
-  var encoded = '';
-
-  do {
-    encoded = alphabet[num % length] + encoded;
-    num = Math.floor(num / length);
-  } while (num > 0);
-
-  return encoded;
-}
-
-/**
- * Return the integer value specified by the given string.
- *
- * @param {String} str The string to convert.
- * @returns {Number} The integer value represented by the string.
- * @api public
- */
-function decode(str) {
-  var decoded = 0;
-
-  for (i = 0; i < str.length; i++) {
-    decoded = decoded * length + map[str.charAt(i)];
-  }
-
-  return decoded;
-}
-
-/**
- * Yeast: A tiny growing id generator.
- *
- * @returns {String} A unique id.
- * @api public
- */
-function yeast() {
-  var now = encode(+new Date());
-
-  if (now !== prev) return seed = 0, prev = now;
-  return now +'.'+ encode(seed++);
-}
-
-//
-// Map each character to its index.
-//
-for (; i < length; i++) map[alphabet[i]] = i;
-
-//
-// Expose the `yeast`, `encode` and `decode` functions.
-//
-yeast.encode = encode;
-yeast.decode = decode;
-module.exports = yeast;
+"use strict";var prev,alphabet="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_".split(""),length=64,map={},seed=0,i=0;function encode(e){var t="";do{t=alphabet[e%length]+t,e=Math.floor(e/length)}while(e>0);return t}function decode(e){var t=0;for(i=0;i<e.length;i++)t=t*length+map[e.charAt(i)];return t}function yeast(){var e=encode(+new Date);return e!==prev?(seed=0,prev=e):e+"."+encode(seed++)}for(;i<length;i++)map[alphabet[i]]=i;yeast.encode=encode,yeast.decode=decode,module.exports=yeast;
\ No newline at end of file