diff --git a/README.md b/README.md index bedc7c3..c22a076 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,19 @@ In `http` mode this can be anything. This can be any endpoint: a json, csv, txt, A path to a local Deno javascript or typescript file for postprocessing the `downloaded_filename` file. Read more in the ["Postprocessing section"](https://github.com/githubocto/flat#postprocessing). +#### `mask` (optional) + +If your `http_url` string contains secrets, you can choose to mask it from the commit message. You have two options: + +**Option 1**: use a string boolean + +`mask: true # removes the source entirely from the commit message, defaults to false` + +**Option 2**: use a string array with each secret to mask + +`mask: '["${{ secrets.SECRET1 }}", "${{ secrets.SECRET2 }}"]'` + + ### SQL Mode #### `sql_connstring` diff --git a/action.yml b/action.yml index b143715..d47aa30 100644 --- a/action.yml +++ b/action.yml @@ -8,6 +8,9 @@ inputs: http_url: description: 'A URL containing data to fetch.' required: false + mask: + description: 'A string array of secrets to strip from the http_url or a string boolean' + required: false sql_connstring: description: 'A connection string for making a SQL query.' required: false diff --git a/dist/index.js b/dist/index.js index ec20d4e..c71f06f 100644 --- a/dist/index.js +++ b/dist/index.js @@ -233,6 +233,7 @@ const CommonConfigSchema = z.object({ const HTTPConfigSchema = z .object({ http_url: z.string(), + mask: z.string().optional() // string array of secrets or boolean }) .merge(CommonConfigSchema); const SQLConfigSchema = z @@ -247,12 +248,13 @@ function getConfig() { const keys = [ 'downloaded_filename', 'http_url', + 'mask', 'sql_connstring', 'sql_queryfile', 'postprocess', ]; keys.forEach(k => { - const v = core.getInput(k); + const v = core.getInput(k); // getInput always returns a string if (v) { raw[k] = v; } @@ -449,9 +451,30 @@ async function run() { core.startGroup('Fetch data'); let filename = ''; let source; + let shouldMask = false; // by default we don't mask the source + let sourceMasked = ''; if (config_1.isHTTPConfig(config)) { filename = await http_1.default(config); source = config.http_url; + // if including a mask config then we can strip out secrets from the http_url + sourceMasked = source; // if no secrets to mask then this is just source + if (config.mask) { + if (config.mask === 'true' || config.mask === 'false') { // mask param is a string + shouldMask = JSON.parse(config.mask); // convert to boolean + } + else { + try { + const maskArray = JSON.parse(config.mask); + maskArray.forEach((secretToMask) => { + const regex = new RegExp(secretToMask, "g"); + sourceMasked = sourceMasked.replace(regex, "***"); + }); + } + catch (error) { + core.setFailed('Mask param formatted incorrectly. It should be a string array OR a "true" or "false" string.'); + } + } + } } else if (config_1.isSQLConfig(config)) { filename = await sql_1.default(config); @@ -497,8 +520,8 @@ async function run() { core.debug(`git adding ${filename}…`); await exec_1.exec('git', ['add', filename]); const bytes = await git_1.diff(filename); - // core.setOutput('delta_bytes', bytes) - editedFiles.push({ name: filename, deltaBytes: bytes, source }); + const source = shouldMask ? {} : { source: sourceMasked }; + editedFiles.push({ name: filename, deltaBytes: bytes, ...source }); } core.endGroup(); core.startGroup('Committing new data'); diff --git a/dist/index.js.map b/dist/index.js.map index 58b2c17..0d5002a 100644 --- a/dist/index.js.map +++ b/dist/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","sources":["../webpack://flat/./lib/backends/http.js","../webpack://flat/./lib/backends/sql.js","../webpack://flat/./lib/config.js","../webpack://flat/./lib/git.js","../webpack://flat/./lib/main.js","../webpack://flat/./node_modules/@actions/core/lib/command.js","../webpack://flat/./node_modules/@actions/core/lib/core.js","../webpack://flat/./node_modules/@actions/core/lib/file-command.js","../webpack://flat/./node_modules/@actions/core/lib/utils.js","../webpack://flat/./node_modules/@actions/exec/lib/exec.js","../webpack://flat/./node_modules/@actions/exec/lib/toolrunner.js","../webpack://flat/./node_modules/@actions/io/lib/io-util.js","../webpack://flat/./node_modules/@actions/io/lib/io.js","../webpack://flat/./node_modules/@azure/ms-rest-azure-env/dist/msRestAzureEnv.js","../webpack://flat/./node_modules/@azure/ms-rest-js/dist/msRest.node.js","../webpack://flat/./node_modules/@azure/ms-rest-js/node_modules/form-data/lib/form_data.js","../webpack://flat/./node_modules/@azure/ms-rest-js/node_modules/form-data/lib/populate.js","../webpack://flat/./node_modules/@azure/ms-rest-js/node_modules/tslib/tslib.es6.js","../webpack://flat/./node_modules/@azure/ms-rest-nodeauth/dist/lib/credentials/applicationTokenCertificateCredentials.js","../webpack://flat/./node_modules/@azure/ms-rest-nodeauth/dist/lib/credentials/applicationTokenCredentials.js","../webpack://flat/./node_modules/@azure/ms-rest-nodeauth/dist/lib/credentials/applicationTokenCredentialsBase.js","../webpack://flat/./node_modules/@azure/ms-rest-nodeauth/dist/lib/credentials/azureCliCredentials.js","../webpack://flat/./node_modules/@azure/ms-rest-nodeauth/dist/lib/credentials/deviceTokenCredentials.js","../webpack://flat/./node_modules/@azure/ms-rest-nodeauth/dist/lib/credentials/keyVaultFactory.js","../webpack://flat/./node_modules/@azure/ms-rest-nodeauth/dist/lib/credentials/msiAppServiceTokenCredentials.js","../webpack://flat/./node_modules/@azure/ms-rest-nodeauth/dist/lib/credentials/msiTokenCredentials.js","../webpack://flat/./node_modules/@azure/ms-rest-nodeauth/dist/lib/credentials/msiVmTokenCredentials.js","../webpack://flat/./node_modules/@azure/ms-rest-nodeauth/dist/lib/credentials/tokenCredentialsBase.js","../webpack://flat/./node_modules/@azure/ms-rest-nodeauth/dist/lib/credentials/userTokenCredentials.js","../webpack://flat/./node_modules/@azure/ms-rest-nodeauth/dist/lib/login.js","../webpack://flat/./node_modules/@azure/ms-rest-nodeauth/dist/lib/msRestNodeAuth.js","../webpack://flat/./node_modules/@azure/ms-rest-nodeauth/dist/lib/subscriptionManagement/subscriptionUtils.js","../webpack://flat/./node_modules/@azure/ms-rest-nodeauth/dist/lib/util/authConstants.js","../webpack://flat/./node_modules/abbrev/abbrev.js","../webpack://flat/./node_modules/adal-node/lib/adal.js","../webpack://flat/./node_modules/adal-node/lib/argument.js","../webpack://flat/./node_modules/adal-node/lib/authentication-context.js","../webpack://flat/./node_modules/adal-node/lib/authentication-parameters.js","../webpack://flat/./node_modules/adal-node/lib/authority.js","../webpack://flat/./node_modules/adal-node/lib/cache-driver.js","../webpack://flat/./node_modules/adal-node/lib/code-request.js","../webpack://flat/./node_modules/adal-node/lib/constants.js","../webpack://flat/./node_modules/adal-node/lib/log.js","../webpack://flat/./node_modules/adal-node/lib/memory-cache.js","../webpack://flat/./node_modules/adal-node/lib/mex.js","../webpack://flat/./node_modules/adal-node/lib/oauth2client.js","../webpack://flat/./node_modules/adal-node/lib/self-signed-jwt.js","../webpack://flat/./node_modules/adal-node/lib/token-request.js","../webpack://flat/./node_modules/adal-node/lib/user-realm.js","../webpack://flat/./node_modules/adal-node/lib/util.js","../webpack://flat/./node_modules/adal-node/lib/wstrust-request.js","../webpack://flat/./node_modules/adal-node/lib/wstrust-response.js","../webpack://flat/./node_modules/adal-node/lib/xmlutil.js","../webpack://flat/./node_modules/ajv/lib/ajv.js","../webpack://flat/./node_modules/ajv/lib/cache.js","../webpack://flat/./node_modules/ajv/lib/compile/async.js","../webpack://flat/./node_modules/ajv/lib/compile/error_classes.js","../webpack://flat/./node_modules/ajv/lib/compile/formats.js","../webpack://flat/./node_modules/ajv/lib/compile/index.js","../webpack://flat/./node_modules/ajv/lib/compile/resolve.js","../webpack://flat/./node_modules/ajv/lib/compile/rules.js","../webpack://flat/./node_modules/ajv/lib/compile/schema_obj.js","../webpack://flat/./node_modules/ajv/lib/compile/ucs2length.js","../webpack://flat/./node_modules/ajv/lib/compile/util.js","../webpack://flat/./node_modules/ajv/lib/data.js","../webpack://flat/./node_modules/ajv/lib/definition_schema.js","../webpack://flat/./node_modules/ajv/lib/dotjs/_limit.js","../webpack://flat/./node_modules/ajv/lib/dotjs/_limitItems.js","../webpack://flat/./node_modules/ajv/lib/dotjs/_limitLength.js","../webpack://flat/./node_modules/ajv/lib/dotjs/_limitProperties.js","../webpack://flat/./node_modules/ajv/lib/dotjs/allOf.js","../webpack://flat/./node_modules/ajv/lib/dotjs/anyOf.js","../webpack://flat/./node_modules/ajv/lib/dotjs/comment.js","../webpack://flat/./node_modules/ajv/lib/dotjs/const.js","../webpack://flat/./node_modules/ajv/lib/dotjs/contains.js","../webpack://flat/./node_modules/ajv/lib/dotjs/custom.js","../webpack://flat/./node_modules/ajv/lib/dotjs/dependencies.js","../webpack://flat/./node_modules/ajv/lib/dotjs/enum.js","../webpack://flat/./node_modules/ajv/lib/dotjs/format.js","../webpack://flat/./node_modules/ajv/lib/dotjs/if.js","../webpack://flat/./node_modules/ajv/lib/dotjs/index.js","../webpack://flat/./node_modules/ajv/lib/dotjs/items.js","../webpack://flat/./node_modules/ajv/lib/dotjs/multipleOf.js","../webpack://flat/./node_modules/ajv/lib/dotjs/not.js","../webpack://flat/./node_modules/ajv/lib/dotjs/oneOf.js","../webpack://flat/./node_modules/ajv/lib/dotjs/pattern.js","../webpack://flat/./node_modules/ajv/lib/dotjs/properties.js","../webpack://flat/./node_modules/ajv/lib/dotjs/propertyNames.js","../webpack://flat/./node_modules/ajv/lib/dotjs/ref.js","../webpack://flat/./node_modules/ajv/lib/dotjs/required.js","../webpack://flat/./node_modules/ajv/lib/dotjs/uniqueItems.js","../webpack://flat/./node_modules/ajv/lib/dotjs/validate.js","../webpack://flat/./node_modules/ajv/lib/keyword.js","../webpack://flat/./node_modules/ansi-regex/index.js","../webpack://flat/./node_modules/ansi-styles/index.js","../webpack://flat/./node_modules/app-root-path/index.js","../webpack://flat/./node_modules/app-root-path/lib/app-root-path.js","../webpack://flat/./node_modules/app-root-path/lib/resolve.js","../webpack://flat/./node_modules/aproba/index.js","../webpack://flat/./node_modules/are-we-there-yet/index.js","../webpack://flat/./node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_duplex.js","../webpack://flat/./node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_passthrough.js","../webpack://flat/./node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_readable.js","../webpack://flat/./node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_transform.js","../webpack://flat/./node_modules/are-we-there-yet/node_modules/readable-stream/lib/_stream_writable.js","../webpack://flat/./node_modules/are-we-there-yet/node_modules/readable-stream/lib/internal/streams/BufferList.js","../webpack://flat/./node_modules/are-we-there-yet/node_modules/readable-stream/lib/internal/streams/destroy.js","../webpack://flat/./node_modules/are-we-there-yet/node_modules/readable-stream/lib/internal/streams/stream.js","../webpack://flat/./node_modules/are-we-there-yet/node_modules/readable-stream/readable.js","../webpack://flat/./node_modules/are-we-there-yet/node_modules/safe-buffer/index.js","../webpack://flat/./node_modules/are-we-there-yet/node_modules/string_decoder/lib/string_decoder.js","../webpack://flat/./node_modules/are-we-there-yet/tracker-base.js","../webpack://flat/./node_modules/are-we-there-yet/tracker-group.js","../webpack://flat/./node_modules/are-we-there-yet/tracker-stream.js","../webpack://flat/./node_modules/are-we-there-yet/tracker.js","../webpack://flat/./node_modules/asn1/lib/ber/errors.js","../webpack://flat/./node_modules/asn1/lib/ber/index.js","../webpack://flat/./node_modules/asn1/lib/ber/reader.js","../webpack://flat/./node_modules/asn1/lib/ber/types.js","../webpack://flat/./node_modules/asn1/lib/ber/writer.js","../webpack://flat/./node_modules/asn1/lib/index.js","../webpack://flat/./node_modules/assert-plus/assert.js","../webpack://flat/./node_modules/async/dist/async.js","../webpack://flat/./node_modules/asynckit/index.js","../webpack://flat/./node_modules/asynckit/lib/abort.js","../webpack://flat/./node_modules/asynckit/lib/async.js","../webpack://flat/./node_modules/asynckit/lib/defer.js","../webpack://flat/./node_modules/asynckit/lib/iterate.js","../webpack://flat/./node_modules/asynckit/lib/state.js","../webpack://flat/./node_modules/asynckit/lib/terminator.js","../webpack://flat/./node_modules/asynckit/parallel.js","../webpack://flat/./node_modules/asynckit/serial.js","../webpack://flat/./node_modules/asynckit/serialOrdered.js","../webpack://flat/./node_modules/aws-sign2/index.js","../webpack://flat/./node_modules/aws4/aws4.js","../webpack://flat/./node_modules/aws4/lru.js","../webpack://flat/./node_modules/axios/index.js","../webpack://flat/./node_modules/axios/lib/adapters/http.js","../webpack://flat/./node_modules/axios/lib/adapters/xhr.js","../webpack://flat/./node_modules/axios/lib/axios.js","../webpack://flat/./node_modules/axios/lib/cancel/Cancel.js","../webpack://flat/./node_modules/axios/lib/cancel/CancelToken.js","../webpack://flat/./node_modules/axios/lib/cancel/isCancel.js","../webpack://flat/./node_modules/axios/lib/core/Axios.js","../webpack://flat/./node_modules/axios/lib/core/InterceptorManager.js","../webpack://flat/./node_modules/axios/lib/core/buildFullPath.js","../webpack://flat/./node_modules/axios/lib/core/createError.js","../webpack://flat/./node_modules/axios/lib/core/dispatchRequest.js","../webpack://flat/./node_modules/axios/lib/core/enhanceError.js","../webpack://flat/./node_modules/axios/lib/core/mergeConfig.js","../webpack://flat/./node_modules/axios/lib/core/settle.js","../webpack://flat/./node_modules/axios/lib/core/transformData.js","../webpack://flat/./node_modules/axios/lib/defaults.js","../webpack://flat/./node_modules/axios/lib/helpers/bind.js","../webpack://flat/./node_modules/axios/lib/helpers/buildURL.js","../webpack://flat/./node_modules/axios/lib/helpers/combineURLs.js","../webpack://flat/./node_modules/axios/lib/helpers/cookies.js","../webpack://flat/./node_modules/axios/lib/helpers/isAbsoluteURL.js","../webpack://flat/./node_modules/axios/lib/helpers/isAxiosError.js","../webpack://flat/./node_modules/axios/lib/helpers/isURLSameOrigin.js","../webpack://flat/./node_modules/axios/lib/helpers/normalizeHeaderName.js","../webpack://flat/./node_modules/axios/lib/helpers/parseHeaders.js","../webpack://flat/./node_modules/axios/lib/helpers/spread.js","../webpack://flat/./node_modules/axios/lib/utils.js","../webpack://flat/./node_modules/balanced-match/index.js","../webpack://flat/./node_modules/bcrypt-pbkdf/index.js","../webpack://flat/./node_modules/bignumber.js/bignumber.js","../webpack://flat/./node_modules/bl/bl.js","../webpack://flat/./node_modules/brace-expansion/index.js","../webpack://flat/./node_modules/buffer-equal-constant-time/index.js","../webpack://flat/./node_modules/caseless/index.js","../webpack://flat/./node_modules/chalk/source/index.js","../webpack://flat/./node_modules/chalk/source/templates.js","../webpack://flat/./node_modules/chalk/source/util.js","../webpack://flat/./node_modules/cli-highlight/dist/index.js","../webpack://flat/./node_modules/cli-highlight/dist/theme.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/common/doctype.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/common/error-codes.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/common/foreign-content.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/common/html.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/common/unicode.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/extensions/error-reporting/mixin-base.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/extensions/error-reporting/parser-mixin.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/extensions/error-reporting/preprocessor-mixin.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/extensions/error-reporting/tokenizer-mixin.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/extensions/location-info/open-element-stack-mixin.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/extensions/location-info/parser-mixin.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/extensions/location-info/tokenizer-mixin.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/extensions/position-tracking/preprocessor-mixin.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/index.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/parser/formatting-element-list.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/parser/index.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/parser/open-element-stack.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/serializer/index.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/tokenizer/index.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/tokenizer/named-entity-data.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/tokenizer/preprocessor.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/tree-adapters/default.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/utils/merge-options.js","../webpack://flat/./node_modules/cli-highlight/node_modules/parse5/lib/utils/mixin.js","../webpack://flat/./node_modules/code-point-at/index.js","../webpack://flat/./node_modules/color-convert/conversions.js","../webpack://flat/./node_modules/color-convert/index.js","../webpack://flat/./node_modules/color-convert/route.js","../webpack://flat/./node_modules/color-name/index.js","../webpack://flat/./node_modules/combined-stream/lib/combined_stream.js","../webpack://flat/./node_modules/concat-map/index.js","../webpack://flat/./node_modules/connection-string/dist/index.js","../webpack://flat/./node_modules/connection-string/dist/inspect.js","../webpack://flat/./node_modules/connection-string/dist/main.js","../webpack://flat/./node_modules/connection-string/dist/static.js","../webpack://flat/./node_modules/connection-string/dist/types.js","../webpack://flat/./node_modules/console-control-strings/index.js","../webpack://flat/./node_modules/core-util-is/lib/util.js","../webpack://flat/./node_modules/csv-stringify/lib/index.js","../webpack://flat/./node_modules/date-utils/lib/date-utils.js","../webpack://flat/./node_modules/debug/src/browser.js","../webpack://flat/./node_modules/debug/src/common.js","../webpack://flat/./node_modules/debug/src/index.js","../webpack://flat/./node_modules/debug/src/node.js","../webpack://flat/./node_modules/delayed-stream/lib/delayed_stream.js","../webpack://flat/./node_modules/delegates/index.js","../webpack://flat/./node_modules/depd/index.js","../webpack://flat/./node_modules/detect-libc/lib/detect-libc.js","../webpack://flat/./node_modules/dotenv/lib/main.js","../webpack://flat/./node_modules/ecc-jsbn/index.js","../webpack://flat/./node_modules/ecc-jsbn/lib/ec.js","../webpack://flat/./node_modules/ecc-jsbn/lib/sec.js","../webpack://flat/./node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js","../webpack://flat/./node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js","../webpack://flat/./node_modules/extend/index.js","../webpack://flat/./node_modules/extsprintf/lib/extsprintf.js","../webpack://flat/./node_modules/fast-deep-equal/index.js","../webpack://flat/./node_modules/fast-json-stable-stringify/index.js","../webpack://flat/./node_modules/follow-redirects/debug.js","../webpack://flat/./node_modules/follow-redirects/index.js","../webpack://flat/./node_modules/forever-agent/index.js","../webpack://flat/./node_modules/form-data/lib/form_data.js","../webpack://flat/./node_modules/form-data/lib/populate.js","../webpack://flat/./node_modules/fs.realpath/index.js","../webpack://flat/./node_modules/fs.realpath/old.js","../webpack://flat/./node_modules/gauge/base-theme.js","../webpack://flat/./node_modules/gauge/error.js","../webpack://flat/./node_modules/gauge/has-color.js","../webpack://flat/./node_modules/gauge/index.js","../webpack://flat/./node_modules/gauge/node_modules/is-fullwidth-code-point/index.js","../webpack://flat/./node_modules/gauge/node_modules/string-width/index.js","../webpack://flat/./node_modules/gauge/node_modules/strip-ansi/index.js","../webpack://flat/./node_modules/gauge/plumbing.js","../webpack://flat/./node_modules/gauge/process.js","../webpack://flat/./node_modules/gauge/progress-bar.js","../webpack://flat/./node_modules/gauge/render-template.js","../webpack://flat/./node_modules/gauge/set-immediate.js","../webpack://flat/./node_modules/gauge/set-interval.js","../webpack://flat/./node_modules/gauge/spin.js","../webpack://flat/./node_modules/gauge/template-item.js","../webpack://flat/./node_modules/gauge/theme-set.js","../webpack://flat/./node_modules/gauge/themes.js","../webpack://flat/./node_modules/gauge/wide-truncate.js","../webpack://flat/./node_modules/glob/common.js","../webpack://flat/./node_modules/glob/glob.js","../webpack://flat/./node_modules/glob/sync.js","../webpack://flat/./node_modules/har-schema/lib/index.js","../webpack://flat/./node_modules/har-validator/lib/error.js","../webpack://flat/./node_modules/har-validator/lib/promise.js","../webpack://flat/./node_modules/has-flag/index.js","../webpack://flat/./node_modules/has-unicode/index.js","../webpack://flat/./node_modules/highlight.js/lib/core.js","../webpack://flat/./node_modules/highlight.js/lib/index.js","../webpack://flat/./node_modules/highlight.js/lib/languages/1c.js","../webpack://flat/./node_modules/highlight.js/lib/languages/abnf.js","../webpack://flat/./node_modules/highlight.js/lib/languages/accesslog.js","../webpack://flat/./node_modules/highlight.js/lib/languages/actionscript.js","../webpack://flat/./node_modules/highlight.js/lib/languages/ada.js","../webpack://flat/./node_modules/highlight.js/lib/languages/angelscript.js","../webpack://flat/./node_modules/highlight.js/lib/languages/apache.js","../webpack://flat/./node_modules/highlight.js/lib/languages/applescript.js","../webpack://flat/./node_modules/highlight.js/lib/languages/arcade.js","../webpack://flat/./node_modules/highlight.js/lib/languages/arduino.js","../webpack://flat/./node_modules/highlight.js/lib/languages/armasm.js","../webpack://flat/./node_modules/highlight.js/lib/languages/asciidoc.js","../webpack://flat/./node_modules/highlight.js/lib/languages/aspectj.js","../webpack://flat/./node_modules/highlight.js/lib/languages/autohotkey.js","../webpack://flat/./node_modules/highlight.js/lib/languages/autoit.js","../webpack://flat/./node_modules/highlight.js/lib/languages/avrasm.js","../webpack://flat/./node_modules/highlight.js/lib/languages/awk.js","../webpack://flat/./node_modules/highlight.js/lib/languages/axapta.js","../webpack://flat/./node_modules/highlight.js/lib/languages/bash.js","../webpack://flat/./node_modules/highlight.js/lib/languages/basic.js","../webpack://flat/./node_modules/highlight.js/lib/languages/bnf.js","../webpack://flat/./node_modules/highlight.js/lib/languages/brainfuck.js","../webpack://flat/./node_modules/highlight.js/lib/languages/c-like.js","../webpack://flat/./node_modules/highlight.js/lib/languages/c.js","../webpack://flat/./node_modules/highlight.js/lib/languages/cal.js","../webpack://flat/./node_modules/highlight.js/lib/languages/capnproto.js","../webpack://flat/./node_modules/highlight.js/lib/languages/ceylon.js","../webpack://flat/./node_modules/highlight.js/lib/languages/clean.js","../webpack://flat/./node_modules/highlight.js/lib/languages/clojure-repl.js","../webpack://flat/./node_modules/highlight.js/lib/languages/clojure.js","../webpack://flat/./node_modules/highlight.js/lib/languages/cmake.js","../webpack://flat/./node_modules/highlight.js/lib/languages/coffeescript.js","../webpack://flat/./node_modules/highlight.js/lib/languages/coq.js","../webpack://flat/./node_modules/highlight.js/lib/languages/cos.js","../webpack://flat/./node_modules/highlight.js/lib/languages/cpp.js","../webpack://flat/./node_modules/highlight.js/lib/languages/crmsh.js","../webpack://flat/./node_modules/highlight.js/lib/languages/crystal.js","../webpack://flat/./node_modules/highlight.js/lib/languages/csharp.js","../webpack://flat/./node_modules/highlight.js/lib/languages/csp.js","../webpack://flat/./node_modules/highlight.js/lib/languages/css.js","../webpack://flat/./node_modules/highlight.js/lib/languages/d.js","../webpack://flat/./node_modules/highlight.js/lib/languages/dart.js","../webpack://flat/./node_modules/highlight.js/lib/languages/delphi.js","../webpack://flat/./node_modules/highlight.js/lib/languages/diff.js","../webpack://flat/./node_modules/highlight.js/lib/languages/django.js","../webpack://flat/./node_modules/highlight.js/lib/languages/dns.js","../webpack://flat/./node_modules/highlight.js/lib/languages/dockerfile.js","../webpack://flat/./node_modules/highlight.js/lib/languages/dos.js","../webpack://flat/./node_modules/highlight.js/lib/languages/dsconfig.js","../webpack://flat/./node_modules/highlight.js/lib/languages/dts.js","../webpack://flat/./node_modules/highlight.js/lib/languages/dust.js","../webpack://flat/./node_modules/highlight.js/lib/languages/ebnf.js","../webpack://flat/./node_modules/highlight.js/lib/languages/elixir.js","../webpack://flat/./node_modules/highlight.js/lib/languages/elm.js","../webpack://flat/./node_modules/highlight.js/lib/languages/erb.js","../webpack://flat/./node_modules/highlight.js/lib/languages/erlang-repl.js","../webpack://flat/./node_modules/highlight.js/lib/languages/erlang.js","../webpack://flat/./node_modules/highlight.js/lib/languages/excel.js","../webpack://flat/./node_modules/highlight.js/lib/languages/fix.js","../webpack://flat/./node_modules/highlight.js/lib/languages/flix.js","../webpack://flat/./node_modules/highlight.js/lib/languages/fortran.js","../webpack://flat/./node_modules/highlight.js/lib/languages/fsharp.js","../webpack://flat/./node_modules/highlight.js/lib/languages/gams.js","../webpack://flat/./node_modules/highlight.js/lib/languages/gauss.js","../webpack://flat/./node_modules/highlight.js/lib/languages/gcode.js","../webpack://flat/./node_modules/highlight.js/lib/languages/gherkin.js","../webpack://flat/./node_modules/highlight.js/lib/languages/glsl.js","../webpack://flat/./node_modules/highlight.js/lib/languages/gml.js","../webpack://flat/./node_modules/highlight.js/lib/languages/go.js","../webpack://flat/./node_modules/highlight.js/lib/languages/golo.js","../webpack://flat/./node_modules/highlight.js/lib/languages/gradle.js","../webpack://flat/./node_modules/highlight.js/lib/languages/groovy.js","../webpack://flat/./node_modules/highlight.js/lib/languages/haml.js","../webpack://flat/./node_modules/highlight.js/lib/languages/handlebars.js","../webpack://flat/./node_modules/highlight.js/lib/languages/haskell.js","../webpack://flat/./node_modules/highlight.js/lib/languages/haxe.js","../webpack://flat/./node_modules/highlight.js/lib/languages/hsp.js","../webpack://flat/./node_modules/highlight.js/lib/languages/htmlbars.js","../webpack://flat/./node_modules/highlight.js/lib/languages/http.js","../webpack://flat/./node_modules/highlight.js/lib/languages/hy.js","../webpack://flat/./node_modules/highlight.js/lib/languages/inform7.js","../webpack://flat/./node_modules/highlight.js/lib/languages/ini.js","../webpack://flat/./node_modules/highlight.js/lib/languages/irpf90.js","../webpack://flat/./node_modules/highlight.js/lib/languages/isbl.js","../webpack://flat/./node_modules/highlight.js/lib/languages/java.js","../webpack://flat/./node_modules/highlight.js/lib/languages/javascript.js","../webpack://flat/./node_modules/highlight.js/lib/languages/jboss-cli.js","../webpack://flat/./node_modules/highlight.js/lib/languages/json.js","../webpack://flat/./node_modules/highlight.js/lib/languages/julia-repl.js","../webpack://flat/./node_modules/highlight.js/lib/languages/julia.js","../webpack://flat/./node_modules/highlight.js/lib/languages/kotlin.js","../webpack://flat/./node_modules/highlight.js/lib/languages/lasso.js","../webpack://flat/./node_modules/highlight.js/lib/languages/latex.js","../webpack://flat/./node_modules/highlight.js/lib/languages/ldif.js","../webpack://flat/./node_modules/highlight.js/lib/languages/leaf.js","../webpack://flat/./node_modules/highlight.js/lib/languages/less.js","../webpack://flat/./node_modules/highlight.js/lib/languages/lisp.js","../webpack://flat/./node_modules/highlight.js/lib/languages/livecodeserver.js","../webpack://flat/./node_modules/highlight.js/lib/languages/livescript.js","../webpack://flat/./node_modules/highlight.js/lib/languages/llvm.js","../webpack://flat/./node_modules/highlight.js/lib/languages/lsl.js","../webpack://flat/./node_modules/highlight.js/lib/languages/lua.js","../webpack://flat/./node_modules/highlight.js/lib/languages/makefile.js","../webpack://flat/./node_modules/highlight.js/lib/languages/markdown.js","../webpack://flat/./node_modules/highlight.js/lib/languages/mathematica.js","../webpack://flat/./node_modules/highlight.js/lib/languages/matlab.js","../webpack://flat/./node_modules/highlight.js/lib/languages/maxima.js","../webpack://flat/./node_modules/highlight.js/lib/languages/mel.js","../webpack://flat/./node_modules/highlight.js/lib/languages/mercury.js","../webpack://flat/./node_modules/highlight.js/lib/languages/mipsasm.js","../webpack://flat/./node_modules/highlight.js/lib/languages/mizar.js","../webpack://flat/./node_modules/highlight.js/lib/languages/mojolicious.js","../webpack://flat/./node_modules/highlight.js/lib/languages/monkey.js","../webpack://flat/./node_modules/highlight.js/lib/languages/moonscript.js","../webpack://flat/./node_modules/highlight.js/lib/languages/n1ql.js","../webpack://flat/./node_modules/highlight.js/lib/languages/nginx.js","../webpack://flat/./node_modules/highlight.js/lib/languages/nim.js","../webpack://flat/./node_modules/highlight.js/lib/languages/nix.js","../webpack://flat/./node_modules/highlight.js/lib/languages/node-repl.js","../webpack://flat/./node_modules/highlight.js/lib/languages/nsis.js","../webpack://flat/./node_modules/highlight.js/lib/languages/objectivec.js","../webpack://flat/./node_modules/highlight.js/lib/languages/ocaml.js","../webpack://flat/./node_modules/highlight.js/lib/languages/openscad.js","../webpack://flat/./node_modules/highlight.js/lib/languages/oxygene.js","../webpack://flat/./node_modules/highlight.js/lib/languages/parser3.js","../webpack://flat/./node_modules/highlight.js/lib/languages/perl.js","../webpack://flat/./node_modules/highlight.js/lib/languages/pf.js","../webpack://flat/./node_modules/highlight.js/lib/languages/pgsql.js","../webpack://flat/./node_modules/highlight.js/lib/languages/php-template.js","../webpack://flat/./node_modules/highlight.js/lib/languages/php.js","../webpack://flat/./node_modules/highlight.js/lib/languages/plaintext.js","../webpack://flat/./node_modules/highlight.js/lib/languages/pony.js","../webpack://flat/./node_modules/highlight.js/lib/languages/powershell.js","../webpack://flat/./node_modules/highlight.js/lib/languages/processing.js","../webpack://flat/./node_modules/highlight.js/lib/languages/profile.js","../webpack://flat/./node_modules/highlight.js/lib/languages/prolog.js","../webpack://flat/./node_modules/highlight.js/lib/languages/properties.js","../webpack://flat/./node_modules/highlight.js/lib/languages/protobuf.js","../webpack://flat/./node_modules/highlight.js/lib/languages/puppet.js","../webpack://flat/./node_modules/highlight.js/lib/languages/purebasic.js","../webpack://flat/./node_modules/highlight.js/lib/languages/python-repl.js","../webpack://flat/./node_modules/highlight.js/lib/languages/python.js","../webpack://flat/./node_modules/highlight.js/lib/languages/q.js","../webpack://flat/./node_modules/highlight.js/lib/languages/qml.js","../webpack://flat/./node_modules/highlight.js/lib/languages/r.js","../webpack://flat/./node_modules/highlight.js/lib/languages/reasonml.js","../webpack://flat/./node_modules/highlight.js/lib/languages/rib.js","../webpack://flat/./node_modules/highlight.js/lib/languages/roboconf.js","../webpack://flat/./node_modules/highlight.js/lib/languages/routeros.js","../webpack://flat/./node_modules/highlight.js/lib/languages/rsl.js","../webpack://flat/./node_modules/highlight.js/lib/languages/ruby.js","../webpack://flat/./node_modules/highlight.js/lib/languages/ruleslanguage.js","../webpack://flat/./node_modules/highlight.js/lib/languages/rust.js","../webpack://flat/./node_modules/highlight.js/lib/languages/sas.js","../webpack://flat/./node_modules/highlight.js/lib/languages/scala.js","../webpack://flat/./node_modules/highlight.js/lib/languages/scheme.js","../webpack://flat/./node_modules/highlight.js/lib/languages/scilab.js","../webpack://flat/./node_modules/highlight.js/lib/languages/scss.js","../webpack://flat/./node_modules/highlight.js/lib/languages/shell.js","../webpack://flat/./node_modules/highlight.js/lib/languages/smali.js","../webpack://flat/./node_modules/highlight.js/lib/languages/smalltalk.js","../webpack://flat/./node_modules/highlight.js/lib/languages/sml.js","../webpack://flat/./node_modules/highlight.js/lib/languages/sqf.js","../webpack://flat/./node_modules/highlight.js/lib/languages/sql.js","../webpack://flat/./node_modules/highlight.js/lib/languages/sql_more.js","../webpack://flat/./node_modules/highlight.js/lib/languages/stan.js","../webpack://flat/./node_modules/highlight.js/lib/languages/stata.js","../webpack://flat/./node_modules/highlight.js/lib/languages/step21.js","../webpack://flat/./node_modules/highlight.js/lib/languages/stylus.js","../webpack://flat/./node_modules/highlight.js/lib/languages/subunit.js","../webpack://flat/./node_modules/highlight.js/lib/languages/swift.js","../webpack://flat/./node_modules/highlight.js/lib/languages/taggerscript.js","../webpack://flat/./node_modules/highlight.js/lib/languages/tap.js","../webpack://flat/./node_modules/highlight.js/lib/languages/tcl.js","../webpack://flat/./node_modules/highlight.js/lib/languages/thrift.js","../webpack://flat/./node_modules/highlight.js/lib/languages/tp.js","../webpack://flat/./node_modules/highlight.js/lib/languages/twig.js","../webpack://flat/./node_modules/highlight.js/lib/languages/typescript.js","../webpack://flat/./node_modules/highlight.js/lib/languages/vala.js","../webpack://flat/./node_modules/highlight.js/lib/languages/vbnet.js","../webpack://flat/./node_modules/highlight.js/lib/languages/vbscript-html.js","../webpack://flat/./node_modules/highlight.js/lib/languages/vbscript.js","../webpack://flat/./node_modules/highlight.js/lib/languages/verilog.js","../webpack://flat/./node_modules/highlight.js/lib/languages/vhdl.js","../webpack://flat/./node_modules/highlight.js/lib/languages/vim.js","../webpack://flat/./node_modules/highlight.js/lib/languages/x86asm.js","../webpack://flat/./node_modules/highlight.js/lib/languages/xl.js","../webpack://flat/./node_modules/highlight.js/lib/languages/xml.js","../webpack://flat/./node_modules/highlight.js/lib/languages/xquery.js","../webpack://flat/./node_modules/highlight.js/lib/languages/yaml.js","../webpack://flat/./node_modules/highlight.js/lib/languages/zephir.js","../webpack://flat/./node_modules/http-signature/lib/index.js","../webpack://flat/./node_modules/http-signature/lib/parser.js","../webpack://flat/./node_modules/http-signature/lib/signer.js","../webpack://flat/./node_modules/http-signature/lib/utils.js","../webpack://flat/./node_modules/http-signature/lib/verify.js","../webpack://flat/./node_modules/inflight/inflight.js","../webpack://flat/./node_modules/inherits/inherits.js","../webpack://flat/./node_modules/inherits/inherits_browser.js","../webpack://flat/./node_modules/is-typedarray/index.js","../webpack://flat/./node_modules/isarray/index.js","../webpack://flat/./node_modules/isstream/isstream.js","../webpack://flat/./node_modules/js-yaml/index.js","../webpack://flat/./node_modules/js-yaml/lib/common.js","../webpack://flat/./node_modules/js-yaml/lib/dumper.js","../webpack://flat/./node_modules/js-yaml/lib/exception.js","../webpack://flat/./node_modules/js-yaml/lib/loader.js","../webpack://flat/./node_modules/js-yaml/lib/schema.js","../webpack://flat/./node_modules/js-yaml/lib/schema/core.js","../webpack://flat/./node_modules/js-yaml/lib/schema/default.js","../webpack://flat/./node_modules/js-yaml/lib/schema/failsafe.js","../webpack://flat/./node_modules/js-yaml/lib/schema/json.js","../webpack://flat/./node_modules/js-yaml/lib/snippet.js","../webpack://flat/./node_modules/js-yaml/lib/type.js","../webpack://flat/./node_modules/js-yaml/lib/type/binary.js","../webpack://flat/./node_modules/js-yaml/lib/type/bool.js","../webpack://flat/./node_modules/js-yaml/lib/type/float.js","../webpack://flat/./node_modules/js-yaml/lib/type/int.js","../webpack://flat/./node_modules/js-yaml/lib/type/map.js","../webpack://flat/./node_modules/js-yaml/lib/type/merge.js","../webpack://flat/./node_modules/js-yaml/lib/type/null.js","../webpack://flat/./node_modules/js-yaml/lib/type/omap.js","../webpack://flat/./node_modules/js-yaml/lib/type/pairs.js","../webpack://flat/./node_modules/js-yaml/lib/type/seq.js","../webpack://flat/./node_modules/js-yaml/lib/type/set.js","../webpack://flat/./node_modules/js-yaml/lib/type/str.js","../webpack://flat/./node_modules/js-yaml/lib/type/timestamp.js","../webpack://flat/./node_modules/jsbi/dist/jsbi-cjs.js","../webpack://flat/./node_modules/jsbn/index.js","../webpack://flat/./node_modules/json-schema-traverse/index.js","../webpack://flat/./node_modules/json-schema/lib/validate.js","../webpack://flat/./node_modules/json-stringify-safe/stringify.js","../webpack://flat/./node_modules/jsprim/lib/jsprim.js","../webpack://flat/./node_modules/jwa/index.js","../webpack://flat/./node_modules/jws/index.js","../webpack://flat/./node_modules/jws/lib/data-stream.js","../webpack://flat/./node_modules/jws/lib/sign-stream.js","../webpack://flat/./node_modules/jws/lib/tostring.js","../webpack://flat/./node_modules/jws/lib/verify-stream.js","../webpack://flat/./node_modules/mime-db/index.js","../webpack://flat/./node_modules/mime-types/index.js","../webpack://flat/./node_modules/minimatch/minimatch.js","../webpack://flat/./node_modules/ms/index.js","../webpack://flat/./node_modules/mssql/index.js","../webpack://flat/./node_modules/mssql/lib/base/connection-pool.js","../webpack://flat/./node_modules/mssql/lib/base/index.js","../webpack://flat/./node_modules/mssql/lib/base/prepared-statement.js","../webpack://flat/./node_modules/mssql/lib/base/request.js","../webpack://flat/./node_modules/mssql/lib/base/transaction.js","../webpack://flat/./node_modules/mssql/lib/connectionstring.js","../webpack://flat/./node_modules/mssql/lib/datatypes.js","../webpack://flat/./node_modules/mssql/lib/error/connection-error.js","../webpack://flat/./node_modules/mssql/lib/error/index.js","../webpack://flat/./node_modules/mssql/lib/error/mssql-error.js","../webpack://flat/./node_modules/mssql/lib/error/prepared-statement-error.js","../webpack://flat/./node_modules/mssql/lib/error/request-error.js","../webpack://flat/./node_modules/mssql/lib/error/transaction-error.js","../webpack://flat/./node_modules/mssql/lib/global-connection.js","../webpack://flat/./node_modules/mssql/lib/isolationlevel.js","../webpack://flat/./node_modules/mssql/lib/shared.js","../webpack://flat/./node_modules/mssql/lib/table.js","../webpack://flat/./node_modules/mssql/lib/tedious/connection-pool.js","../webpack://flat/./node_modules/mssql/lib/tedious/index.js","../webpack://flat/./node_modules/mssql/lib/tedious/request.js","../webpack://flat/./node_modules/mssql/lib/tedious/transaction.js","../webpack://flat/./node_modules/mssql/lib/udt.js","../webpack://flat/./node_modules/mssql/lib/utils.js","../webpack://flat/./node_modules/mysql/index.js","../webpack://flat/./node_modules/mysql/lib/Connection.js","../webpack://flat/./node_modules/mysql/lib/ConnectionConfig.js","../webpack://flat/./node_modules/mysql/lib/Pool.js","../webpack://flat/./node_modules/mysql/lib/PoolCluster.js","../webpack://flat/./node_modules/mysql/lib/PoolConfig.js","../webpack://flat/./node_modules/mysql/lib/PoolConnection.js","../webpack://flat/./node_modules/mysql/lib/PoolNamespace.js","../webpack://flat/./node_modules/mysql/lib/PoolSelector.js","../webpack://flat/./node_modules/mysql/lib/protocol/Auth.js","../webpack://flat/./node_modules/mysql/lib/protocol/BufferList.js","../webpack://flat/./node_modules/mysql/lib/protocol/PacketHeader.js","../webpack://flat/./node_modules/mysql/lib/protocol/PacketWriter.js","../webpack://flat/./node_modules/mysql/lib/protocol/Parser.js","../webpack://flat/./node_modules/mysql/lib/protocol/Protocol.js","../webpack://flat/./node_modules/mysql/lib/protocol/ResultSet.js","../webpack://flat/./node_modules/mysql/lib/protocol/SqlString.js","../webpack://flat/./node_modules/mysql/lib/protocol/Timer.js","../webpack://flat/./node_modules/mysql/lib/protocol/constants/charsets.js","../webpack://flat/./node_modules/mysql/lib/protocol/constants/client.js","../webpack://flat/./node_modules/mysql/lib/protocol/constants/errors.js","../webpack://flat/./node_modules/mysql/lib/protocol/constants/server_status.js","../webpack://flat/./node_modules/mysql/lib/protocol/constants/ssl_profiles.js","../webpack://flat/./node_modules/mysql/lib/protocol/constants/types.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/AuthSwitchRequestPacket.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/AuthSwitchResponsePacket.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/ClientAuthenticationPacket.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/ComChangeUserPacket.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/ComPingPacket.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/ComQueryPacket.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/ComQuitPacket.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/ComStatisticsPacket.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/EmptyPacket.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/EofPacket.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/ErrorPacket.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/Field.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/FieldPacket.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/HandshakeInitializationPacket.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/LocalDataFilePacket.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/LocalInfileRequestPacket.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/OkPacket.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/OldPasswordPacket.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/ResultSetHeaderPacket.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/RowDataPacket.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/SSLRequestPacket.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/StatisticsPacket.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/UseOldPasswordPacket.js","../webpack://flat/./node_modules/mysql/lib/protocol/packets/index.js","../webpack://flat/./node_modules/mysql/lib/protocol/sequences/ChangeUser.js","../webpack://flat/./node_modules/mysql/lib/protocol/sequences/Handshake.js","../webpack://flat/./node_modules/mysql/lib/protocol/sequences/Ping.js","../webpack://flat/./node_modules/mysql/lib/protocol/sequences/Query.js","../webpack://flat/./node_modules/mysql/lib/protocol/sequences/Quit.js","../webpack://flat/./node_modules/mysql/lib/protocol/sequences/Sequence.js","../webpack://flat/./node_modules/mysql/lib/protocol/sequences/Statistics.js","../webpack://flat/./node_modules/mysql/lib/protocol/sequences/index.js","../webpack://flat/./node_modules/mysql/node_modules/readable-stream/lib/_stream_duplex.js","../webpack://flat/./node_modules/mysql/node_modules/readable-stream/lib/_stream_passthrough.js","../webpack://flat/./node_modules/mysql/node_modules/readable-stream/lib/_stream_readable.js","../webpack://flat/./node_modules/mysql/node_modules/readable-stream/lib/_stream_transform.js","../webpack://flat/./node_modules/mysql/node_modules/readable-stream/lib/_stream_writable.js","../webpack://flat/./node_modules/mysql/node_modules/readable-stream/lib/internal/streams/BufferList.js","../webpack://flat/./node_modules/mysql/node_modules/readable-stream/lib/internal/streams/destroy.js","../webpack://flat/./node_modules/mysql/node_modules/readable-stream/lib/internal/streams/stream.js","../webpack://flat/./node_modules/mysql/node_modules/readable-stream/readable.js","../webpack://flat/./node_modules/mysql/node_modules/safe-buffer/index.js","../webpack://flat/./node_modules/mysql/node_modules/string_decoder/lib/string_decoder.js","../webpack://flat/./node_modules/native-duplexpair/index.js","../webpack://flat/./node_modules/node-pre-gyp/lib/node-pre-gyp.js","../webpack://flat/./node_modules/node-pre-gyp/lib/pre-binding.js","../webpack://flat/./node_modules/node-pre-gyp/lib/util/napi.js","../webpack://flat/./node_modules/node-pre-gyp/lib/util/versioning.js","../webpack://flat/./node_modules/node-pre-gyp/node_modules/nopt/lib/nopt.js","../webpack://flat/./node_modules/node-pre-gyp/node_modules/semver/semver.js","../webpack://flat/./node_modules/npmlog/log.js","../webpack://flat/./node_modules/number-is-nan/index.js","../webpack://flat/./node_modules/oauth-sign/index.js","../webpack://flat/./node_modules/object-assign/index.js","../webpack://flat/./node_modules/once/once.js","../webpack://flat/./node_modules/os-homedir/index.js","../webpack://flat/./node_modules/os-tmpdir/index.js","../webpack://flat/./node_modules/osenv/osenv.js","../webpack://flat/./node_modules/parse5-htmlparser2-tree-adapter/lib/index.js","../webpack://flat/./node_modules/parse5/lib/common/doctype.js","../webpack://flat/./node_modules/parse5/lib/common/html.js","../webpack://flat/./node_modules/path-is-absolute/index.js","../webpack://flat/./node_modules/performance-now/lib/performance-now.js","../webpack://flat/./node_modules/pg-connection-string/index.js","../webpack://flat/./node_modules/pg-int8/index.js","../webpack://flat/./node_modules/pg-pool/index.js","../webpack://flat/./node_modules/pg-protocol/dist/buffer-reader.js","../webpack://flat/./node_modules/pg-protocol/dist/buffer-writer.js","../webpack://flat/./node_modules/pg-protocol/dist/index.js","../webpack://flat/./node_modules/pg-protocol/dist/messages.js","../webpack://flat/./node_modules/pg-protocol/dist/parser.js","../webpack://flat/./node_modules/pg-protocol/dist/serializer.js","../webpack://flat/./node_modules/pg-types/index.js","../webpack://flat/./node_modules/pg-types/lib/arrayParser.js","../webpack://flat/./node_modules/pg-types/lib/binaryParsers.js","../webpack://flat/./node_modules/pg-types/lib/builtins.js","../webpack://flat/./node_modules/pg-types/lib/textParsers.js","../webpack://flat/./node_modules/pg/lib/client.js","../webpack://flat/./node_modules/pg/lib/connection-parameters.js","../webpack://flat/./node_modules/pg/lib/connection.js","../webpack://flat/./node_modules/pg/lib/defaults.js","../webpack://flat/./node_modules/pg/lib/index.js","../webpack://flat/./node_modules/pg/lib/native/client.js","../webpack://flat/./node_modules/pg/lib/native/index.js","../webpack://flat/./node_modules/pg/lib/native/query.js","../webpack://flat/./node_modules/pg/lib/query.js","../webpack://flat/./node_modules/pg/lib/result.js","../webpack://flat/./node_modules/pg/lib/sasl.js","../webpack://flat/./node_modules/pg/lib/type-overrides.js","../webpack://flat/./node_modules/pg/lib/utils.js","../webpack://flat/./node_modules/pgpass/lib/helper.js","../webpack://flat/./node_modules/pgpass/lib/index.js","../webpack://flat/./node_modules/postgres-array/index.js","../webpack://flat/./node_modules/postgres-bytea/index.js","../webpack://flat/./node_modules/postgres-date/index.js","../webpack://flat/./node_modules/postgres-interval/index.js","../webpack://flat/./node_modules/process-nextick-args/index.js","../webpack://flat/./node_modules/psl/index.js","../webpack://flat/./node_modules/qs/lib/formats.js","../webpack://flat/./node_modules/qs/lib/index.js","../webpack://flat/./node_modules/qs/lib/parse.js","../webpack://flat/./node_modules/qs/lib/stringify.js","../webpack://flat/./node_modules/qs/lib/utils.js","../webpack://flat/./node_modules/readable-stream/errors.js","../webpack://flat/./node_modules/readable-stream/lib/_stream_duplex.js","../webpack://flat/./node_modules/readable-stream/lib/_stream_passthrough.js","../webpack://flat/./node_modules/readable-stream/lib/_stream_readable.js","../webpack://flat/./node_modules/readable-stream/lib/_stream_transform.js","../webpack://flat/./node_modules/readable-stream/lib/_stream_writable.js","../webpack://flat/./node_modules/readable-stream/lib/internal/streams/async_iterator.js","../webpack://flat/./node_modules/readable-stream/lib/internal/streams/buffer_list.js","../webpack://flat/./node_modules/readable-stream/lib/internal/streams/destroy.js","../webpack://flat/./node_modules/readable-stream/lib/internal/streams/end-of-stream.js","../webpack://flat/./node_modules/readable-stream/lib/internal/streams/from.js","../webpack://flat/./node_modules/readable-stream/lib/internal/streams/pipeline.js","../webpack://flat/./node_modules/readable-stream/lib/internal/streams/state.js","../webpack://flat/./node_modules/readable-stream/lib/internal/streams/stream.js","../webpack://flat/./node_modules/readable-stream/readable.js","../webpack://flat/./node_modules/reflect-metadata/Reflect.js","../webpack://flat/./node_modules/request/index.js","../webpack://flat/./node_modules/request/lib/auth.js","../webpack://flat/./node_modules/request/lib/cookies.js","../webpack://flat/./node_modules/request/lib/getProxyFromURI.js","../webpack://flat/./node_modules/request/lib/har.js","../webpack://flat/./node_modules/request/lib/hawk.js","../webpack://flat/./node_modules/request/lib/helpers.js","../webpack://flat/./node_modules/request/lib/multipart.js","../webpack://flat/./node_modules/request/lib/oauth.js","../webpack://flat/./node_modules/request/lib/querystring.js","../webpack://flat/./node_modules/request/lib/redirect.js","../webpack://flat/./node_modules/request/lib/tunnel.js","../webpack://flat/./node_modules/request/request.js","../webpack://flat/./node_modules/rimraf/rimraf.js","../webpack://flat/./node_modules/safe-buffer/index.js","../webpack://flat/./node_modules/safer-buffer/safer.js","../webpack://flat/./node_modules/sax/lib/sax.js","../webpack://flat/./node_modules/set-blocking/index.js","../webpack://flat/./node_modules/sha.js/hash.js","../webpack://flat/./node_modules/sha.js/index.js","../webpack://flat/./node_modules/sha.js/sha.js","../webpack://flat/./node_modules/sha.js/sha1.js","../webpack://flat/./node_modules/sha.js/sha224.js","../webpack://flat/./node_modules/sha.js/sha256.js","../webpack://flat/./node_modules/sha.js/sha384.js","../webpack://flat/./node_modules/sha.js/sha512.js","../webpack://flat/./node_modules/signal-exit/index.js","../webpack://flat/./node_modules/signal-exit/signals.js","../webpack://flat/./node_modules/split2/index.js","../webpack://flat/./node_modules/sprintf-js/src/sprintf.js","../webpack://flat/./node_modules/sqlite3/lib/sqlite3-binding.js","../webpack://flat/./node_modules/sqlite3/lib/sqlite3.js","../webpack://flat/./node_modules/sqlite3/lib/trace.js","../webpack://flat/./node_modules/sqlstring/index.js","../webpack://flat/./node_modules/sqlstring/lib/SqlString.js","../webpack://flat/./node_modules/sshpk/lib/algs.js","../webpack://flat/./node_modules/sshpk/lib/certificate.js","../webpack://flat/./node_modules/sshpk/lib/dhe.js","../webpack://flat/./node_modules/sshpk/lib/ed-compat.js","../webpack://flat/./node_modules/sshpk/lib/errors.js","../webpack://flat/./node_modules/sshpk/lib/fingerprint.js","../webpack://flat/./node_modules/sshpk/lib/formats/auto.js","../webpack://flat/./node_modules/sshpk/lib/formats/dnssec.js","../webpack://flat/./node_modules/sshpk/lib/formats/openssh-cert.js","../webpack://flat/./node_modules/sshpk/lib/formats/pem.js","../webpack://flat/./node_modules/sshpk/lib/formats/pkcs1.js","../webpack://flat/./node_modules/sshpk/lib/formats/pkcs8.js","../webpack://flat/./node_modules/sshpk/lib/formats/putty.js","../webpack://flat/./node_modules/sshpk/lib/formats/rfc4253.js","../webpack://flat/./node_modules/sshpk/lib/formats/ssh-private.js","../webpack://flat/./node_modules/sshpk/lib/formats/ssh.js","../webpack://flat/./node_modules/sshpk/lib/formats/x509-pem.js","../webpack://flat/./node_modules/sshpk/lib/formats/x509.js","../webpack://flat/./node_modules/sshpk/lib/identity.js","../webpack://flat/./node_modules/sshpk/lib/index.js","../webpack://flat/./node_modules/sshpk/lib/key.js","../webpack://flat/./node_modules/sshpk/lib/private-key.js","../webpack://flat/./node_modules/sshpk/lib/signature.js","../webpack://flat/./node_modules/sshpk/lib/ssh-buffer.js","../webpack://flat/./node_modules/sshpk/lib/utils.js","../webpack://flat/./node_modules/string_decoder/lib/string_decoder.js","../webpack://flat/./node_modules/supports-color/index.js","../webpack://flat/./node_modules/tarn/lib/PendingOperation.js","../webpack://flat/./node_modules/tarn/lib/Pool.js","../webpack://flat/./node_modules/tarn/lib/PromiseInspection.js","../webpack://flat/./node_modules/tarn/lib/Resource.js","../webpack://flat/./node_modules/tarn/lib/TimeoutError.js","../webpack://flat/./node_modules/tarn/lib/tarn.js","../webpack://flat/./node_modules/tarn/lib/utils.js","../webpack://flat/./node_modules/tedious/lib/all-headers.js","../webpack://flat/./node_modules/tedious/lib/bulk-load.js","../webpack://flat/./node_modules/tedious/lib/collation.js","../webpack://flat/./node_modules/tedious/lib/connection.js","../webpack://flat/./node_modules/tedious/lib/connector.js","../webpack://flat/./node_modules/tedious/lib/data-type.js","../webpack://flat/./node_modules/tedious/lib/data-types/bigint.js","../webpack://flat/./node_modules/tedious/lib/data-types/binary.js","../webpack://flat/./node_modules/tedious/lib/data-types/bit.js","../webpack://flat/./node_modules/tedious/lib/data-types/bitn.js","../webpack://flat/./node_modules/tedious/lib/data-types/char.js","../webpack://flat/./node_modules/tedious/lib/data-types/date.js","../webpack://flat/./node_modules/tedious/lib/data-types/datetime.js","../webpack://flat/./node_modules/tedious/lib/data-types/datetime2.js","../webpack://flat/./node_modules/tedious/lib/data-types/datetimen.js","../webpack://flat/./node_modules/tedious/lib/data-types/datetimeoffset.js","../webpack://flat/./node_modules/tedious/lib/data-types/decimal.js","../webpack://flat/./node_modules/tedious/lib/data-types/decimaln.js","../webpack://flat/./node_modules/tedious/lib/data-types/float.js","../webpack://flat/./node_modules/tedious/lib/data-types/floatn.js","../webpack://flat/./node_modules/tedious/lib/data-types/image.js","../webpack://flat/./node_modules/tedious/lib/data-types/int.js","../webpack://flat/./node_modules/tedious/lib/data-types/intn.js","../webpack://flat/./node_modules/tedious/lib/data-types/money.js","../webpack://flat/./node_modules/tedious/lib/data-types/moneyn.js","../webpack://flat/./node_modules/tedious/lib/data-types/nchar.js","../webpack://flat/./node_modules/tedious/lib/data-types/ntext.js","../webpack://flat/./node_modules/tedious/lib/data-types/null.js","../webpack://flat/./node_modules/tedious/lib/data-types/numeric.js","../webpack://flat/./node_modules/tedious/lib/data-types/numericn.js","../webpack://flat/./node_modules/tedious/lib/data-types/nvarchar.js","../webpack://flat/./node_modules/tedious/lib/data-types/real.js","../webpack://flat/./node_modules/tedious/lib/data-types/smalldatetime.js","../webpack://flat/./node_modules/tedious/lib/data-types/smallint.js","../webpack://flat/./node_modules/tedious/lib/data-types/smallmoney.js","../webpack://flat/./node_modules/tedious/lib/data-types/sql-variant.js","../webpack://flat/./node_modules/tedious/lib/data-types/text.js","../webpack://flat/./node_modules/tedious/lib/data-types/time.js","../webpack://flat/./node_modules/tedious/lib/data-types/tinyint.js","../webpack://flat/./node_modules/tedious/lib/data-types/tvp.js","../webpack://flat/./node_modules/tedious/lib/data-types/udt.js","../webpack://flat/./node_modules/tedious/lib/data-types/uniqueidentifier.js","../webpack://flat/./node_modules/tedious/lib/data-types/varbinary.js","../webpack://flat/./node_modules/tedious/lib/data-types/varchar.js","../webpack://flat/./node_modules/tedious/lib/data-types/xml.js","../webpack://flat/./node_modules/tedious/lib/debug.js","../webpack://flat/./node_modules/tedious/lib/errors.js","../webpack://flat/./node_modules/tedious/lib/guid-parser.js","../webpack://flat/./node_modules/tedious/lib/incoming-message-stream.js","../webpack://flat/./node_modules/tedious/lib/instance-lookup.js","../webpack://flat/./node_modules/tedious/lib/library.js","../webpack://flat/./node_modules/tedious/lib/login7-payload.js","../webpack://flat/./node_modules/tedious/lib/message-io.js","../webpack://flat/./node_modules/tedious/lib/message.js","../webpack://flat/./node_modules/tedious/lib/metadata-parser.js","../webpack://flat/./node_modules/tedious/lib/ntlm-payload.js","../webpack://flat/./node_modules/tedious/lib/ntlm.js","../webpack://flat/./node_modules/tedious/lib/outgoing-message-stream.js","../webpack://flat/./node_modules/tedious/lib/packet.js","../webpack://flat/./node_modules/tedious/lib/prelogin-payload.js","../webpack://flat/./node_modules/tedious/lib/request.js","../webpack://flat/./node_modules/tedious/lib/rpcrequest-payload.js","../webpack://flat/./node_modules/tedious/lib/sender.js","../webpack://flat/./node_modules/tedious/lib/sqlbatch-payload.js","../webpack://flat/./node_modules/tedious/lib/tds-versions.js","../webpack://flat/./node_modules/tedious/lib/tedious.js","../webpack://flat/./node_modules/tedious/lib/token/colmetadata-token-parser.js","../webpack://flat/./node_modules/tedious/lib/token/done-token-parser.js","../webpack://flat/./node_modules/tedious/lib/token/env-change-token-parser.js","../webpack://flat/./node_modules/tedious/lib/token/feature-ext-ack-parser.js","../webpack://flat/./node_modules/tedious/lib/token/fedauth-info-parser.js","../webpack://flat/./node_modules/tedious/lib/token/infoerror-token-parser.js","../webpack://flat/./node_modules/tedious/lib/token/loginack-token-parser.js","../webpack://flat/./node_modules/tedious/lib/token/nbcrow-token-parser.js","../webpack://flat/./node_modules/tedious/lib/token/order-token-parser.js","../webpack://flat/./node_modules/tedious/lib/token/returnstatus-token-parser.js","../webpack://flat/./node_modules/tedious/lib/token/returnvalue-token-parser.js","../webpack://flat/./node_modules/tedious/lib/token/row-token-parser.js","../webpack://flat/./node_modules/tedious/lib/token/sspi-token-parser.js","../webpack://flat/./node_modules/tedious/lib/token/stream-parser.js","../webpack://flat/./node_modules/tedious/lib/token/token-stream-parser.js","../webpack://flat/./node_modules/tedious/lib/token/token.js","../webpack://flat/./node_modules/tedious/lib/tracking-buffer/writable-tracking-buffer.js","../webpack://flat/./node_modules/tedious/lib/transaction.js","../webpack://flat/./node_modules/tedious/lib/transient-error-lookup.js","../webpack://flat/./node_modules/tedious/lib/value-parser.js","../webpack://flat/./node_modules/tedious/node_modules/iconv-lite/encodings/dbcs-codec.js","../webpack://flat/./node_modules/tedious/node_modules/iconv-lite/encodings/dbcs-data.js","../webpack://flat/./node_modules/tedious/node_modules/iconv-lite/encodings/index.js","../webpack://flat/./node_modules/tedious/node_modules/iconv-lite/encodings/internal.js","../webpack://flat/./node_modules/tedious/node_modules/iconv-lite/encodings/sbcs-codec.js","../webpack://flat/./node_modules/tedious/node_modules/iconv-lite/encodings/sbcs-data-generated.js","../webpack://flat/./node_modules/tedious/node_modules/iconv-lite/encodings/sbcs-data.js","../webpack://flat/./node_modules/tedious/node_modules/iconv-lite/encodings/utf16.js","../webpack://flat/./node_modules/tedious/node_modules/iconv-lite/encodings/utf32.js","../webpack://flat/./node_modules/tedious/node_modules/iconv-lite/encodings/utf7.js","../webpack://flat/./node_modules/tedious/node_modules/iconv-lite/lib/bom-handling.js","../webpack://flat/./node_modules/tedious/node_modules/iconv-lite/lib/extend-node.js","../webpack://flat/./node_modules/tedious/node_modules/iconv-lite/lib/index.js","../webpack://flat/./node_modules/tedious/node_modules/iconv-lite/lib/streams.js","../webpack://flat/./node_modules/tough-cookie/lib/cookie.js","../webpack://flat/./node_modules/tough-cookie/lib/memstore.js","../webpack://flat/./node_modules/tough-cookie/lib/pathMatch.js","../webpack://flat/./node_modules/tough-cookie/lib/permuteDomain.js","../webpack://flat/./node_modules/tough-cookie/lib/pubsuffix-psl.js","../webpack://flat/./node_modules/tough-cookie/lib/store.js","../webpack://flat/./node_modules/tough-cookie/lib/version.js","../webpack://flat/./node_modules/tslib/tslib.es6.js","../webpack://flat/./node_modules/tunnel-agent/index.js","../webpack://flat/./node_modules/tunnel/index.js","../webpack://flat/./node_modules/tunnel/lib/tunnel.js","../webpack://flat/./node_modules/tweetnacl/nacl-fast.js","../webpack://flat/./node_modules/typeorm/cache/DbQueryResultCache.js","../webpack://flat/./node_modules/typeorm/cache/QueryResultCacheFactory.js","../webpack://flat/./node_modules/typeorm/cache/RedisQueryResultCache.js","../webpack://flat/./node_modules/typeorm/common/DeepPartial.js","../webpack://flat/./node_modules/typeorm/common/EntityTarget.js","../webpack://flat/./node_modules/typeorm/common/ObjectLiteral.js","../webpack://flat/./node_modules/typeorm/common/ObjectType.js","../webpack://flat/./node_modules/typeorm/connection/Connection.js","../webpack://flat/./node_modules/typeorm/connection/ConnectionManager.js","../webpack://flat/./node_modules/typeorm/connection/ConnectionMetadataBuilder.js","../webpack://flat/./node_modules/typeorm/connection/ConnectionOptionsReader.js","../webpack://flat/./node_modules/typeorm/connection/options-reader/ConnectionOptionsEnvReader.js","../webpack://flat/./node_modules/typeorm/connection/options-reader/ConnectionOptionsXmlReader.js","../webpack://flat/./node_modules/typeorm/connection/options-reader/ConnectionOptionsYmlReader.js","../webpack://flat/./node_modules/typeorm/container.js","../webpack://flat/./node_modules/typeorm/decorator/Check.js","../webpack://flat/./node_modules/typeorm/decorator/EntityRepository.js","../webpack://flat/./node_modules/typeorm/decorator/Exclusion.js","../webpack://flat/./node_modules/typeorm/decorator/Generated.js","../webpack://flat/./node_modules/typeorm/decorator/Index.js","../webpack://flat/./node_modules/typeorm/decorator/Unique.js","../webpack://flat/./node_modules/typeorm/decorator/columns/Column.js","../webpack://flat/./node_modules/typeorm/decorator/columns/CreateDateColumn.js","../webpack://flat/./node_modules/typeorm/decorator/columns/DeleteDateColumn.js","../webpack://flat/./node_modules/typeorm/decorator/columns/ObjectIdColumn.js","../webpack://flat/./node_modules/typeorm/decorator/columns/PrimaryColumn.js","../webpack://flat/./node_modules/typeorm/decorator/columns/PrimaryGeneratedColumn.js","../webpack://flat/./node_modules/typeorm/decorator/columns/UpdateDateColumn.js","../webpack://flat/./node_modules/typeorm/decorator/columns/VersionColumn.js","../webpack://flat/./node_modules/typeorm/decorator/columns/ViewColumn.js","../webpack://flat/./node_modules/typeorm/decorator/entity-view/ViewEntity.js","../webpack://flat/./node_modules/typeorm/decorator/entity/ChildEntity.js","../webpack://flat/./node_modules/typeorm/decorator/entity/Entity.js","../webpack://flat/./node_modules/typeorm/decorator/entity/TableInheritance.js","../webpack://flat/./node_modules/typeorm/decorator/listeners/AfterInsert.js","../webpack://flat/./node_modules/typeorm/decorator/listeners/AfterLoad.js","../webpack://flat/./node_modules/typeorm/decorator/listeners/AfterRemove.js","../webpack://flat/./node_modules/typeorm/decorator/listeners/AfterUpdate.js","../webpack://flat/./node_modules/typeorm/decorator/listeners/BeforeInsert.js","../webpack://flat/./node_modules/typeorm/decorator/listeners/BeforeRemove.js","../webpack://flat/./node_modules/typeorm/decorator/listeners/BeforeUpdate.js","../webpack://flat/./node_modules/typeorm/decorator/listeners/EventSubscriber.js","../webpack://flat/./node_modules/typeorm/decorator/options/ColumnOptions.js","../webpack://flat/./node_modules/typeorm/decorator/options/EntityOptions.js","../webpack://flat/./node_modules/typeorm/decorator/options/IndexOptions.js","../webpack://flat/./node_modules/typeorm/decorator/options/JoinColumnOptions.js","../webpack://flat/./node_modules/typeorm/decorator/options/JoinTableOptions.js","../webpack://flat/./node_modules/typeorm/decorator/options/RelationOptions.js","../webpack://flat/./node_modules/typeorm/decorator/options/ValueTransformer.js","../webpack://flat/./node_modules/typeorm/decorator/relations/JoinColumn.js","../webpack://flat/./node_modules/typeorm/decorator/relations/JoinTable.js","../webpack://flat/./node_modules/typeorm/decorator/relations/ManyToMany.js","../webpack://flat/./node_modules/typeorm/decorator/relations/ManyToOne.js","../webpack://flat/./node_modules/typeorm/decorator/relations/OneToMany.js","../webpack://flat/./node_modules/typeorm/decorator/relations/OneToOne.js","../webpack://flat/./node_modules/typeorm/decorator/relations/RelationCount.js","../webpack://flat/./node_modules/typeorm/decorator/relations/RelationId.js","../webpack://flat/./node_modules/typeorm/decorator/transaction/Transaction.js","../webpack://flat/./node_modules/typeorm/decorator/transaction/TransactionManager.js","../webpack://flat/./node_modules/typeorm/decorator/transaction/TransactionRepository.js","../webpack://flat/./node_modules/typeorm/decorator/tree/Tree.js","../webpack://flat/./node_modules/typeorm/decorator/tree/TreeChildren.js","../webpack://flat/./node_modules/typeorm/decorator/tree/TreeLevelColumn.js","../webpack://flat/./node_modules/typeorm/decorator/tree/TreeParent.js","../webpack://flat/./node_modules/typeorm/driver/DriverFactory.js","../webpack://flat/./node_modules/typeorm/driver/DriverUtils.js","../webpack://flat/./node_modules/typeorm/driver/Query.js","../webpack://flat/./node_modules/typeorm/driver/SqlInMemory.js","../webpack://flat/./node_modules/typeorm/driver/aurora-data-api-pg/AuroraDataApiPostgresDriver.js","../webpack://flat/./node_modules/typeorm/driver/aurora-data-api-pg/AuroraDataApiPostgresQueryRunner.js","../webpack://flat/./node_modules/typeorm/driver/aurora-data-api/AuroraDataApiDriver.js","../webpack://flat/./node_modules/typeorm/driver/aurora-data-api/AuroraDataApiQueryRunner.js","../webpack://flat/./node_modules/typeorm/driver/better-sqlite3/BetterSqlite3Driver.js","../webpack://flat/./node_modules/typeorm/driver/better-sqlite3/BetterSqlite3QueryRunner.js","../webpack://flat/./node_modules/typeorm/driver/cockroachdb/CockroachDriver.js","../webpack://flat/./node_modules/typeorm/driver/cockroachdb/CockroachQueryRunner.js","../webpack://flat/./node_modules/typeorm/driver/cordova/CordovaDriver.js","../webpack://flat/./node_modules/typeorm/driver/cordova/CordovaQueryRunner.js","../webpack://flat/./node_modules/typeorm/driver/expo/ExpoDriver.js","../webpack://flat/./node_modules/typeorm/driver/expo/ExpoQueryRunner.js","../webpack://flat/./node_modules/typeorm/driver/mongodb/MongoDriver.js","../webpack://flat/./node_modules/typeorm/driver/mongodb/MongoQueryRunner.js","../webpack://flat/./node_modules/typeorm/driver/mongodb/typings.js","../webpack://flat/./node_modules/typeorm/driver/mysql/MysqlDriver.js","../webpack://flat/./node_modules/typeorm/driver/mysql/MysqlQueryRunner.js","../webpack://flat/./node_modules/typeorm/driver/nativescript/NativescriptDriver.js","../webpack://flat/./node_modules/typeorm/driver/nativescript/NativescriptQueryRunner.js","../webpack://flat/./node_modules/typeorm/driver/oracle/OracleDriver.js","../webpack://flat/./node_modules/typeorm/driver/oracle/OracleQueryRunner.js","../webpack://flat/./node_modules/typeorm/driver/postgres/PostgresDriver.js","../webpack://flat/./node_modules/typeorm/driver/postgres/PostgresQueryRunner.js","../webpack://flat/./node_modules/typeorm/driver/react-native/ReactNativeDriver.js","../webpack://flat/./node_modules/typeorm/driver/react-native/ReactNativeQueryRunner.js","../webpack://flat/./node_modules/typeorm/driver/sap/SapDriver.js","../webpack://flat/./node_modules/typeorm/driver/sap/SapQueryRunner.js","../webpack://flat/./node_modules/typeorm/driver/sqlite-abstract/AbstractSqliteDriver.js","../webpack://flat/./node_modules/typeorm/driver/sqlite-abstract/AbstractSqliteQueryRunner.js","../webpack://flat/./node_modules/typeorm/driver/sqlite/SqliteDriver.js","../webpack://flat/./node_modules/typeorm/driver/sqlite/SqliteQueryRunner.js","../webpack://flat/./node_modules/typeorm/driver/sqljs/SqljsDriver.js","../webpack://flat/./node_modules/typeorm/driver/sqljs/SqljsQueryRunner.js","../webpack://flat/./node_modules/typeorm/driver/sqlserver/MssqlParameter.js","../webpack://flat/./node_modules/typeorm/driver/sqlserver/SqlServerDriver.js","../webpack://flat/./node_modules/typeorm/driver/sqlserver/SqlServerQueryRunner.js","../webpack://flat/./node_modules/typeorm/driver/types/DatabaseType.js","../webpack://flat/./node_modules/typeorm/driver/types/ReplicationMode.js","../webpack://flat/./node_modules/typeorm/entity-manager/EntityManager.js","../webpack://flat/./node_modules/typeorm/entity-manager/EntityManagerFactory.js","../webpack://flat/./node_modules/typeorm/entity-manager/MongoEntityManager.js","../webpack://flat/./node_modules/typeorm/entity-manager/SqljsEntityManager.js","../webpack://flat/./node_modules/typeorm/entity-schema/EntitySchema.js","../webpack://flat/./node_modules/typeorm/entity-schema/EntitySchemaTransformer.js","../webpack://flat/./node_modules/typeorm/error/AlreadyHasActiveConnectionError.js","../webpack://flat/./node_modules/typeorm/error/CannotAttachTreeChildrenEntityError.js","../webpack://flat/./node_modules/typeorm/error/CannotConnectAlreadyConnectedError.js","../webpack://flat/./node_modules/typeorm/error/CannotCreateEntityIdMapError.js","../webpack://flat/./node_modules/typeorm/error/CannotDetermineEntityError.js","../webpack://flat/./node_modules/typeorm/error/CannotExecuteNotConnectedError.js","../webpack://flat/./node_modules/typeorm/error/CannotGetEntityManagerNotConnectedError.js","../webpack://flat/./node_modules/typeorm/error/CannotReflectMethodParameterTypeError.js","../webpack://flat/./node_modules/typeorm/error/CircularRelationsError.js","../webpack://flat/./node_modules/typeorm/error/ColumnTypeUndefinedError.js","../webpack://flat/./node_modules/typeorm/error/ConnectionIsNotSetError.js","../webpack://flat/./node_modules/typeorm/error/ConnectionNotFoundError.js","../webpack://flat/./node_modules/typeorm/error/CustomRepositoryCannotInheritRepositoryError.js","../webpack://flat/./node_modules/typeorm/error/CustomRepositoryDoesNotHaveEntityError.js","../webpack://flat/./node_modules/typeorm/error/CustomRepositoryNotFoundError.js","../webpack://flat/./node_modules/typeorm/error/DataTypeNotSupportedError.js","../webpack://flat/./node_modules/typeorm/error/DriverOptionNotSetError.js","../webpack://flat/./node_modules/typeorm/error/DriverPackageNotInstalledError.js","../webpack://flat/./node_modules/typeorm/error/EntityColumnNotFound.js","../webpack://flat/./node_modules/typeorm/error/EntityMetadataNotFoundError.js","../webpack://flat/./node_modules/typeorm/error/EntityNotFoundError.js","../webpack://flat/./node_modules/typeorm/error/FindRelationsNotFoundError.js","../webpack://flat/./node_modules/typeorm/error/InitializedRelationError.js","../webpack://flat/./node_modules/typeorm/error/InsertValuesMissingError.js","../webpack://flat/./node_modules/typeorm/error/LimitOnUpdateNotSupportedError.js","../webpack://flat/./node_modules/typeorm/error/LockNotSupportedOnGivenDriverError.js","../webpack://flat/./node_modules/typeorm/error/MetadataAlreadyExistsError.js","../webpack://flat/./node_modules/typeorm/error/MetadataWithSuchNameAlreadyExistsError.js","../webpack://flat/./node_modules/typeorm/error/MissingDeleteDateColumnError.js","../webpack://flat/./node_modules/typeorm/error/MissingDriverError.js","../webpack://flat/./node_modules/typeorm/error/MissingJoinColumnError.js","../webpack://flat/./node_modules/typeorm/error/MissingJoinTableError.js","../webpack://flat/./node_modules/typeorm/error/MissingPrimaryColumnError.js","../webpack://flat/./node_modules/typeorm/error/MustBeEntityError.js","../webpack://flat/./node_modules/typeorm/error/NamingStrategyNotFoundError.js","../webpack://flat/./node_modules/typeorm/error/NoConnectionForRepositoryError.js","../webpack://flat/./node_modules/typeorm/error/NoConnectionOptionError.js","../webpack://flat/./node_modules/typeorm/error/NoNeedToReleaseEntityManagerError.js","../webpack://flat/./node_modules/typeorm/error/NoVersionOrUpdateDateColumnError.js","../webpack://flat/./node_modules/typeorm/error/OffsetWithoutLimitNotSupportedError.js","../webpack://flat/./node_modules/typeorm/error/OptimisticLockCanNotBeUsedError.js","../webpack://flat/./node_modules/typeorm/error/OptimisticLockVersionMismatchError.js","../webpack://flat/./node_modules/typeorm/error/PersistedEntityNotFoundError.js","../webpack://flat/./node_modules/typeorm/error/PessimisticLockTransactionRequiredError.js","../webpack://flat/./node_modules/typeorm/error/PrimaryColumnCannotBeNullableError.js","../webpack://flat/./node_modules/typeorm/error/QueryFailedError.js","../webpack://flat/./node_modules/typeorm/error/QueryRunnerAlreadyReleasedError.js","../webpack://flat/./node_modules/typeorm/error/QueryRunnerProviderAlreadyReleasedError.js","../webpack://flat/./node_modules/typeorm/error/RepositoryNotFoundError.js","../webpack://flat/./node_modules/typeorm/error/RepositoryNotTreeError.js","../webpack://flat/./node_modules/typeorm/error/ReturningStatementNotSupportedError.js","../webpack://flat/./node_modules/typeorm/error/SubjectRemovedAndUpdatedError.js","../webpack://flat/./node_modules/typeorm/error/SubjectWithoutIdentifierError.js","../webpack://flat/./node_modules/typeorm/error/TransactionAlreadyStartedError.js","../webpack://flat/./node_modules/typeorm/error/TransactionNotStartedError.js","../webpack://flat/./node_modules/typeorm/error/TreeRepositoryNotSupportedError.js","../webpack://flat/./node_modules/typeorm/error/UpdateValuesMissingError.js","../webpack://flat/./node_modules/typeorm/error/UsingJoinColumnIsNotAllowedError.js","../webpack://flat/./node_modules/typeorm/error/UsingJoinColumnOnlyOnOneSideAllowedError.js","../webpack://flat/./node_modules/typeorm/error/UsingJoinTableIsNotAllowedError.js","../webpack://flat/./node_modules/typeorm/error/UsingJoinTableOnlyOnOneSideAllowedError.js","../webpack://flat/./node_modules/typeorm/error/index.js","../webpack://flat/./node_modules/typeorm/find-options/FindConditions.js","../webpack://flat/./node_modules/typeorm/find-options/FindManyOptions.js","../webpack://flat/./node_modules/typeorm/find-options/FindOneOptions.js","../webpack://flat/./node_modules/typeorm/find-options/FindOperator.js","../webpack://flat/./node_modules/typeorm/find-options/FindOperatorType.js","../webpack://flat/./node_modules/typeorm/find-options/FindOptionsUtils.js","../webpack://flat/./node_modules/typeorm/find-options/JoinOptions.js","../webpack://flat/./node_modules/typeorm/find-options/OrderByCondition.js","../webpack://flat/./node_modules/typeorm/find-options/operator/Any.js","../webpack://flat/./node_modules/typeorm/find-options/operator/Between.js","../webpack://flat/./node_modules/typeorm/find-options/operator/Equal.js","../webpack://flat/./node_modules/typeorm/find-options/operator/ILike.js","../webpack://flat/./node_modules/typeorm/find-options/operator/In.js","../webpack://flat/./node_modules/typeorm/find-options/operator/IsNull.js","../webpack://flat/./node_modules/typeorm/find-options/operator/LessThan.js","../webpack://flat/./node_modules/typeorm/find-options/operator/LessThanOrEqual.js","../webpack://flat/./node_modules/typeorm/find-options/operator/Like.js","../webpack://flat/./node_modules/typeorm/find-options/operator/MoreThan.js","../webpack://flat/./node_modules/typeorm/find-options/operator/MoreThanOrEqual.js","../webpack://flat/./node_modules/typeorm/find-options/operator/Not.js","../webpack://flat/./node_modules/typeorm/find-options/operator/Raw.js","../webpack://flat/./node_modules/typeorm/index.js","../webpack://flat/./node_modules/typeorm/logger/AdvancedConsoleLogger.js","../webpack://flat/./node_modules/typeorm/logger/DebugLogger.js","../webpack://flat/./node_modules/typeorm/logger/FileLogger.js","../webpack://flat/./node_modules/typeorm/logger/Logger.js","../webpack://flat/./node_modules/typeorm/logger/LoggerFactory.js","../webpack://flat/./node_modules/typeorm/logger/LoggerOptions.js","../webpack://flat/./node_modules/typeorm/logger/SimpleConsoleLogger.js","../webpack://flat/./node_modules/typeorm/metadata-args/MetadataArgsStorage.js","../webpack://flat/./node_modules/typeorm/metadata-builder/ClosureJunctionEntityMetadataBuilder.js","../webpack://flat/./node_modules/typeorm/metadata-builder/EntityMetadataBuilder.js","../webpack://flat/./node_modules/typeorm/metadata-builder/EntityMetadataValidator.js","../webpack://flat/./node_modules/typeorm/metadata-builder/JunctionEntityMetadataBuilder.js","../webpack://flat/./node_modules/typeorm/metadata-builder/MetadataUtils.js","../webpack://flat/./node_modules/typeorm/metadata-builder/RelationJoinColumnBuilder.js","../webpack://flat/./node_modules/typeorm/metadata/CheckMetadata.js","../webpack://flat/./node_modules/typeorm/metadata/ColumnMetadata.js","../webpack://flat/./node_modules/typeorm/metadata/EmbeddedMetadata.js","../webpack://flat/./node_modules/typeorm/metadata/EntityListenerMetadata.js","../webpack://flat/./node_modules/typeorm/metadata/EntityMetadata.js","../webpack://flat/./node_modules/typeorm/metadata/ExclusionMetadata.js","../webpack://flat/./node_modules/typeorm/metadata/ForeignKeyMetadata.js","../webpack://flat/./node_modules/typeorm/metadata/IndexMetadata.js","../webpack://flat/./node_modules/typeorm/metadata/RelationCountMetadata.js","../webpack://flat/./node_modules/typeorm/metadata/RelationIdMetadata.js","../webpack://flat/./node_modules/typeorm/metadata/RelationMetadata.js","../webpack://flat/./node_modules/typeorm/metadata/UniqueMetadata.js","../webpack://flat/./node_modules/typeorm/metadata/types/EventListenerTypes.js","../webpack://flat/./node_modules/typeorm/migration/Migration.js","../webpack://flat/./node_modules/typeorm/migration/MigrationExecutor.js","../webpack://flat/./node_modules/typeorm/naming-strategy/DefaultNamingStrategy.js","../webpack://flat/./node_modules/typeorm/node_modules/mkdirp/index.js","../webpack://flat/./node_modules/typeorm/node_modules/mkdirp/lib/find-made.js","../webpack://flat/./node_modules/typeorm/node_modules/mkdirp/lib/mkdirp-manual.js","../webpack://flat/./node_modules/typeorm/node_modules/mkdirp/lib/mkdirp-native.js","../webpack://flat/./node_modules/typeorm/node_modules/mkdirp/lib/opts-arg.js","../webpack://flat/./node_modules/typeorm/node_modules/mkdirp/lib/path-arg.js","../webpack://flat/./node_modules/typeorm/node_modules/mkdirp/lib/use-native.js","../webpack://flat/./node_modules/typeorm/persistence/EntityPersistExecutor.js","../webpack://flat/./node_modules/typeorm/persistence/Subject.js","../webpack://flat/./node_modules/typeorm/persistence/SubjectChangedColumnsComputer.js","../webpack://flat/./node_modules/typeorm/persistence/SubjectDatabaseEntityLoader.js","../webpack://flat/./node_modules/typeorm/persistence/SubjectExecutor.js","../webpack://flat/./node_modules/typeorm/persistence/SubjectTopoligicalSorter.js","../webpack://flat/./node_modules/typeorm/persistence/subject-builder/CascadesSubjectBuilder.js","../webpack://flat/./node_modules/typeorm/persistence/subject-builder/ManyToManySubjectBuilder.js","../webpack://flat/./node_modules/typeorm/persistence/subject-builder/OneToManySubjectBuilder.js","../webpack://flat/./node_modules/typeorm/persistence/subject-builder/OneToOneInverseSideSubjectBuilder.js","../webpack://flat/./node_modules/typeorm/persistence/tree/ClosureSubjectExecutor.js","../webpack://flat/./node_modules/typeorm/persistence/tree/MaterializedPathSubjectExecutor.js","../webpack://flat/./node_modules/typeorm/persistence/tree/NestedSetSubjectExecutor.js","../webpack://flat/./node_modules/typeorm/platform/PlatformTools.js","../webpack://flat/./node_modules/typeorm/query-builder/Alias.js","../webpack://flat/./node_modules/typeorm/query-builder/Brackets.js","../webpack://flat/./node_modules/typeorm/query-builder/DeleteQueryBuilder.js","../webpack://flat/./node_modules/typeorm/query-builder/InsertQueryBuilder.js","../webpack://flat/./node_modules/typeorm/query-builder/JoinAttribute.js","../webpack://flat/./node_modules/typeorm/query-builder/QueryBuilder.js","../webpack://flat/./node_modules/typeorm/query-builder/QueryBuilderUtils.js","../webpack://flat/./node_modules/typeorm/query-builder/QueryExpressionMap.js","../webpack://flat/./node_modules/typeorm/query-builder/RelationIdLoader.js","../webpack://flat/./node_modules/typeorm/query-builder/RelationLoader.js","../webpack://flat/./node_modules/typeorm/query-builder/RelationQueryBuilder.js","../webpack://flat/./node_modules/typeorm/query-builder/RelationRemover.js","../webpack://flat/./node_modules/typeorm/query-builder/RelationUpdater.js","../webpack://flat/./node_modules/typeorm/query-builder/ReturningResultsEntityUpdator.js","../webpack://flat/./node_modules/typeorm/query-builder/SelectQueryBuilder.js","../webpack://flat/./node_modules/typeorm/query-builder/SoftDeleteQueryBuilder.js","../webpack://flat/./node_modules/typeorm/query-builder/UpdateQueryBuilder.js","../webpack://flat/./node_modules/typeorm/query-builder/relation-count/RelationCountAttribute.js","../webpack://flat/./node_modules/typeorm/query-builder/relation-count/RelationCountLoader.js","../webpack://flat/./node_modules/typeorm/query-builder/relation-count/RelationCountMetadataToAttributeTransformer.js","../webpack://flat/./node_modules/typeorm/query-builder/relation-id/RelationIdAttribute.js","../webpack://flat/./node_modules/typeorm/query-builder/relation-id/RelationIdLoader.js","../webpack://flat/./node_modules/typeorm/query-builder/relation-id/RelationIdMetadataToAttributeTransformer.js","../webpack://flat/./node_modules/typeorm/query-builder/result/DeleteResult.js","../webpack://flat/./node_modules/typeorm/query-builder/result/InsertResult.js","../webpack://flat/./node_modules/typeorm/query-builder/result/UpdateResult.js","../webpack://flat/./node_modules/typeorm/query-builder/transformer/DocumentToEntityTransformer.js","../webpack://flat/./node_modules/typeorm/query-builder/transformer/PlainObjectToDatabaseEntityTransformer.js","../webpack://flat/./node_modules/typeorm/query-builder/transformer/PlainObjectToNewEntityTransformer.js","../webpack://flat/./node_modules/typeorm/query-builder/transformer/RawSqlResultsToEntityTransformer.js","../webpack://flat/./node_modules/typeorm/query-runner/BaseQueryRunner.js","../webpack://flat/./node_modules/typeorm/repository/AbstractRepository.js","../webpack://flat/./node_modules/typeorm/repository/BaseEntity.js","../webpack://flat/./node_modules/typeorm/repository/MongoRepository.js","../webpack://flat/./node_modules/typeorm/repository/RemoveOptions.js","../webpack://flat/./node_modules/typeorm/repository/Repository.js","../webpack://flat/./node_modules/typeorm/repository/RepositoryFactory.js","../webpack://flat/./node_modules/typeorm/repository/SaveOptions.js","../webpack://flat/./node_modules/typeorm/repository/TreeRepository.js","../webpack://flat/./node_modules/typeorm/schema-builder/MongoSchemaBuilder.js","../webpack://flat/./node_modules/typeorm/schema-builder/RdbmsSchemaBuilder.js","../webpack://flat/./node_modules/typeorm/schema-builder/table/Table.js","../webpack://flat/./node_modules/typeorm/schema-builder/table/TableCheck.js","../webpack://flat/./node_modules/typeorm/schema-builder/table/TableColumn.js","../webpack://flat/./node_modules/typeorm/schema-builder/table/TableExclusion.js","../webpack://flat/./node_modules/typeorm/schema-builder/table/TableForeignKey.js","../webpack://flat/./node_modules/typeorm/schema-builder/table/TableIndex.js","../webpack://flat/./node_modules/typeorm/schema-builder/table/TableUnique.js","../webpack://flat/./node_modules/typeorm/schema-builder/util/TableUtils.js","../webpack://flat/./node_modules/typeorm/schema-builder/view/View.js","../webpack://flat/./node_modules/typeorm/subscriber/Broadcaster.js","../webpack://flat/./node_modules/typeorm/subscriber/BroadcasterResult.js","../webpack://flat/./node_modules/typeorm/util/ApplyValueTransformers.js","../webpack://flat/./node_modules/typeorm/util/DateUtils.js","../webpack://flat/./node_modules/typeorm/util/DepGraph.js","../webpack://flat/./node_modules/typeorm/util/DirectoryExportedClassesLoader.js","../webpack://flat/./node_modules/typeorm/util/ObjectUtils.js","../webpack://flat/./node_modules/typeorm/util/OrmUtils.js","../webpack://flat/./node_modules/typeorm/util/RandomGenerator.js","../webpack://flat/./node_modules/typeorm/util/StringUtils.js","../webpack://flat/./node_modules/typeorm/util/VersionUtils.js","../webpack://flat/./node_modules/uri-js/dist/es5/uri.all.js","../webpack://flat/./node_modules/util-deprecate/node.js","../webpack://flat/./node_modules/uuid/index.js","../webpack://flat/./node_modules/uuid/lib/bytesToUuid.js","../webpack://flat/./node_modules/uuid/lib/rng.js","../webpack://flat/./node_modules/uuid/v1.js","../webpack://flat/./node_modules/uuid/v4.js","../webpack://flat/./node_modules/verror/lib/verror.js","../webpack://flat/./node_modules/verror/node_modules/extsprintf/lib/extsprintf.js","../webpack://flat/./node_modules/wide-align/align.js","../webpack://flat/./node_modules/wide-align/node_modules/ansi-regex/index.js","../webpack://flat/./node_modules/wide-align/node_modules/is-fullwidth-code-point/index.js","../webpack://flat/./node_modules/wide-align/node_modules/string-width/index.js","../webpack://flat/./node_modules/wide-align/node_modules/strip-ansi/index.js","../webpack://flat/./node_modules/wrappy/wrappy.js","../webpack://flat/./node_modules/xml2js/lib/bom.js","../webpack://flat/./node_modules/xml2js/lib/builder.js","../webpack://flat/./node_modules/xml2js/lib/defaults.js","../webpack://flat/./node_modules/xml2js/lib/parser.js","../webpack://flat/./node_modules/xml2js/lib/processors.js","../webpack://flat/./node_modules/xml2js/lib/xml2js.js","../webpack://flat/./node_modules/xmlbuilder/lib/DocumentPosition.js","../webpack://flat/./node_modules/xmlbuilder/lib/NodeType.js","../webpack://flat/./node_modules/xmlbuilder/lib/Utility.js","../webpack://flat/./node_modules/xmlbuilder/lib/WriterState.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLAttribute.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLCData.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLCharacterData.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLComment.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLDOMConfiguration.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLDOMErrorHandler.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLDOMImplementation.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLDOMStringList.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLDTDAttList.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLDTDElement.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLDTDEntity.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLDTDNotation.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLDeclaration.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLDocType.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLDocument.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLDocumentCB.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLDummy.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLElement.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLNamedNodeMap.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLNode.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLNodeList.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLProcessingInstruction.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLRaw.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLStreamWriter.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLStringWriter.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLStringifier.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLText.js","../webpack://flat/./node_modules/xmlbuilder/lib/XMLWriterBase.js","../webpack://flat/./node_modules/xmlbuilder/lib/index.js","../webpack://flat/./node_modules/xmldom/lib/dom-parser.js","../webpack://flat/./node_modules/xmldom/lib/dom.js","../webpack://flat/./node_modules/xmldom/lib/entities.js","../webpack://flat/./node_modules/xmldom/lib/sax.js","../webpack://flat/./node_modules/xpath.js/xpath.js","../webpack://flat/./node_modules/xtend/mutable.js","../webpack://flat/./node_modules/zod/lib/PseudoPromise.js","../webpack://flat/./node_modules/zod/lib/ZodError.js","../webpack://flat/./node_modules/zod/lib/external.js","../webpack://flat/./node_modules/zod/lib/helpers/errorUtil.js","../webpack://flat/./node_modules/zod/lib/helpers/parseUtil.js","../webpack://flat/./node_modules/zod/lib/helpers/util.js","../webpack://flat/./node_modules/zod/lib/index.js","../webpack://flat/./node_modules/zod/lib/types.js","../webpack://flat/./node_modules/sqlite3/lib/binding/napi-v3-darwin-x64/node_sqlite3.node","../webpack://flat/./node_modules/@vercel/ncc/dist/ncc/@@notfound.js","../webpack://flat/./node_modules/underscore/underscore-node-f.cjs","../webpack://flat/./node_modules/underscore/underscore-node.cjs","../webpack://flat/external \"assert\"","../webpack://flat/external \"buffer\"","../webpack://flat/external \"child_process\"","../webpack://flat/external \"constants\"","../webpack://flat/external \"crypto\"","../webpack://flat/external \"dgram\"","../webpack://flat/external \"dns\"","../webpack://flat/external \"events\"","../webpack://flat/external \"fs\"","../webpack://flat/external \"http\"","../webpack://flat/external \"https\"","../webpack://flat/external \"module\"","../webpack://flat/external \"net\"","../webpack://flat/external \"os\"","../webpack://flat/external \"path\"","../webpack://flat/external \"punycode\"","../webpack://flat/external \"querystring\"","../webpack://flat/external \"stream\"","../webpack://flat/external \"string_decoder\"","../webpack://flat/external \"timers\"","../webpack://flat/external \"tls\"","../webpack://flat/external \"tty\"","../webpack://flat/external \"url\"","../webpack://flat/external \"util\"","../webpack://flat/external \"zlib\"","../webpack://flat/webpack/bootstrap","../webpack://flat/webpack/runtime/define property getters","../webpack://flat/webpack/runtime/hasOwnProperty shorthand","../webpack://flat/webpack/runtime/make namespace object","../webpack://flat/webpack/runtime/node module decorator","../webpack://flat/webpack/runtime/compat","../webpack://flat/webpack/startup"],"sourcesContent":["\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst core = __importStar(require(\"@actions/core\"));\nconst fs_1 = __importDefault(require(\"fs\"));\nconst axios_1 = __importDefault(require(\"axios\"));\nasync function fetchHTTP(config) {\n core.info('Fetching: HTTP');\n try {\n const response = await axios_1.default.get(config.http_url, {\n method: 'get',\n responseType: 'stream',\n });\n const filename = config.downloaded_filename;\n const writer = fs_1.default.createWriteStream(filename);\n let bytesWritten = 0;\n response.data.pipe(writer);\n await new Promise((resolve, reject) => {\n writer.on('finish', resolve);\n writer.on('error', reject);\n });\n return filename;\n }\n catch (error) {\n core.setFailed(error);\n throw error;\n }\n}\nexports.default = fetchHTTP;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst core = __importStar(require(\"@actions/core\"));\nconst connection_string_1 = require(\"connection-string\");\nconst fs_1 = require(\"fs\");\nconst typeorm_1 = require(\"typeorm\");\nconst csv_stringify_1 = __importDefault(require(\"csv-stringify\"));\n// TODO: wish there was a dynamic way to import this for runtime usage from the DatabaseType type\nconst TYPEORM_PROTOCOLS = [\n 'mysql',\n 'postgres',\n 'cockroachdb',\n 'sap',\n 'mariadb',\n 'sqlite',\n 'cordova',\n 'react-native',\n 'nativescript',\n 'sqljs',\n 'oracle',\n 'mssql',\n 'mongodb',\n 'aurora-data-api',\n 'aurora-data-api-pg',\n 'expo',\n 'better-sqlite3',\n];\nfunction isValidDatabaseType(protocol) {\n return TYPEORM_PROTOCOLS.includes(protocol);\n}\nasync function fetchSQL(config) {\n core.info('Fetching: SQL');\n let connection;\n let query;\n core.debug('Reading query file');\n try {\n core.debug(`SQL Query file path: ${config.sql_queryfile}`);\n query = fs_1.readFileSync(config.sql_queryfile, { encoding: 'utf8' });\n }\n catch (error) {\n core.setFailed(`Unable to read queryfile ${config.sql_queryfile}: ${error.message}`);\n throw error;\n }\n core.debug('Connecting to database');\n const parsed = new connection_string_1.ConnectionString(config.sql_connstring);\n try {\n const protocol = parsed.protocol;\n if (!protocol) {\n throw new Error('Unable to determine the database protocol from the connection string');\n }\n if (!isValidDatabaseType(protocol)) {\n throw new Error(`The '${protocol}' protocol is not supported. Please choose one of: ${TYPEORM_PROTOCOLS.join(', ')}`);\n }\n // @ts-ignore\n connection = await typeorm_1.createConnection({\n type: protocol,\n url: config.sql_connstring,\n });\n }\n catch (error) {\n core.setFailed(`Unable to connect to database: ${error.message}`);\n throw error;\n }\n core.info('Querying database');\n let result;\n try {\n result = await connection.query(query);\n }\n catch (error) {\n core.setFailed(`Unable to query database: ${error.message}`);\n throw error;\n }\n core.info('Closing database');\n try {\n await connection.close();\n }\n catch (error) {\n core.setFailed(`Unable to close database: ${error.message}`);\n throw error;\n }\n const outfile = `${config.downloaded_filename}`;\n const sqlFormat = outfile.split('.').pop(); // should be csv or json\n try {\n switch (sqlFormat) {\n case 'csv':\n core.info('Writing CSV');\n const writer = fs_1.createWriteStream(outfile, { encoding: 'utf8' });\n csv_stringify_1.default(result, {\n header: true,\n }).pipe(writer);\n await new Promise((resolve, reject) => {\n writer.on('finish', resolve);\n writer.on('error', reject);\n });\n break;\n default:\n core.info('Writing JSON');\n await fs_1.writeFileSync(outfile, JSON.stringify(result));\n }\n return outfile;\n }\n catch (error) {\n core.setFailed(`Unable to write results to ${outfile}: ${error.message}`);\n throw error;\n }\n}\nexports.default = fetchSQL;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isSQLConfig = exports.isHTTPConfig = exports.getConfig = void 0;\nconst core = __importStar(require(\"@actions/core\"));\nconst z = __importStar(require(\"zod\"));\nconst FormatEnum = z.enum(['csv', 'json']);\nconst CommonConfigSchema = z.object({\n downloaded_filename: z.string(),\n postprocess: z.string().optional(),\n});\nconst HTTPConfigSchema = z\n .object({\n http_url: z.string(),\n})\n .merge(CommonConfigSchema);\nconst SQLConfigSchema = z\n .object({\n sql_connstring: z.string(),\n sql_queryfile: z.string(),\n})\n .merge(CommonConfigSchema);\nconst ConfigSchema = z.union([HTTPConfigSchema, SQLConfigSchema]);\nfunction getConfig() {\n const raw = {};\n const keys = [\n 'downloaded_filename',\n 'http_url',\n 'sql_connstring',\n 'sql_queryfile',\n 'postprocess',\n ];\n keys.forEach(k => {\n const v = core.getInput(k);\n if (v) {\n raw[k] = v;\n }\n });\n core.debug(`Raw config: ${JSON.stringify(raw)}`);\n try {\n if ('http_url' in raw) {\n return HTTPConfigSchema.parse(raw);\n }\n else if ('sql_connstring' in raw) {\n return SQLConfigSchema.parse(raw);\n }\n else {\n throw new Error('One of `http_url` or `sql_connstring` inputs are required.');\n }\n }\n catch (error) {\n throw new Error(`Invalid configuration!\\nReceived: ${JSON.stringify(raw)}\\nFailure:${error.message}`);\n }\n}\nexports.getConfig = getConfig;\nfunction isHTTPConfig(config) {\n return 'http_url' in config;\n}\nexports.isHTTPConfig = isHTTPConfig;\nfunction isSQLConfig(config) {\n return 'sql_connstring' in config && 'sql_queryfile' in config;\n}\nexports.isSQLConfig = isSQLConfig;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.diff = exports.gitStatus = void 0;\nconst exec_1 = require(\"@actions/exec\");\nconst fs_1 = require(\"fs\");\nconst path_1 = __importDefault(require(\"path\"));\nconst core = __importStar(require(\"@actions/core\"));\nasync function gitStatus() {\n core.debug('Getting gitStatus()');\n let output = '';\n await exec_1.exec('git', ['status', '-s'], {\n listeners: {\n stdout: (data) => {\n output += data.toString();\n },\n },\n });\n core.debug(`=== output was:\\n${output}`);\n return output\n .split('\\n')\n .filter(l => l != '')\n .map(l => {\n const chunks = l.trim().split(/\\s+/);\n return {\n flag: chunks[0],\n path: chunks[1],\n };\n });\n}\nexports.gitStatus = gitStatus;\nasync function getHeadSize(path) {\n let raw = '';\n const exitcode = await exec_1.exec('git', ['cat-file', '-s', `HEAD:${path}`], {\n listeners: {\n stdline: (data) => {\n raw += data;\n },\n },\n });\n core.debug(`raw cat-file output: ${exitcode} '${raw}'`);\n if (exitcode === 0) {\n return parseInt(raw, 10);\n }\n}\nasync function diffSize(file) {\n switch (file.flag) {\n case 'M': {\n const stat = fs_1.statSync(file.path);\n core.debug(`Calculating diff for ${JSON.stringify(file)}, with size ${stat.size}b`);\n // get old size and compare\n const oldSize = await getHeadSize(file.path);\n const delta = oldSize === undefined ? stat.size : stat.size - oldSize;\n core.debug(` ==> ${file.path} modified: old ${oldSize}, new ${stat.size}, delta ${delta}b `);\n return delta;\n }\n case 'A': {\n const stat = fs_1.statSync(file.path);\n core.debug(`Calculating diff for ${JSON.stringify(file)}, with size ${stat.size}b`);\n core.debug(` ==> ${file.path} added: delta ${stat.size}b`);\n return stat.size;\n }\n case 'D': {\n const oldSize = await getHeadSize(file.path);\n const delta = oldSize === undefined ? 0 : oldSize;\n core.debug(` ==> ${file.path} deleted: delta ${delta}b`);\n return delta;\n }\n default: {\n throw new Error(`Encountered an unexpected file status in git: ${file.flag} ${file.path}`);\n }\n }\n}\nasync function diff(filename) {\n const statuses = await gitStatus();\n core.debug(`Parsed statuses: ${statuses.map(s => JSON.stringify(s)).join(', ')}`);\n const status = statuses.find(s => path_1.default.relative(s.path, filename) === '');\n if (typeof status === 'undefined') {\n core.info(`No status found for ${filename}, aborting.`);\n return 0; // there's no change to the specified file\n }\n return await diffSize(status);\n}\nexports.diff = diff;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst core = __importStar(require(\"@actions/core\"));\nconst exec_1 = require(\"@actions/exec\");\nconst child_process_1 = require(\"child_process\");\nconst http_1 = __importDefault(require(\"./backends/http\"));\nconst sql_1 = __importDefault(require(\"./backends/sql\"));\nconst config_1 = require(\"./config\");\nconst git_1 = require(\"./git\");\nasync function run() {\n core.info('[INFO] Usage https://github.com/githubocto/flat#readme');\n core.startGroup('Configuration');\n const config = config_1.getConfig();\n const username = 'flat-data';\n await exec_1.exec('git', ['config', 'user.name', username]);\n await exec_1.exec('git', [\n 'config',\n 'user.email',\n `${username}@users.noreply.github.com`,\n ]);\n core.endGroup();\n core.startGroup('Fetch data');\n let filename = '';\n let source;\n if (config_1.isHTTPConfig(config)) {\n filename = await http_1.default(config);\n source = config.http_url;\n }\n else if (config_1.isSQLConfig(config)) {\n filename = await sql_1.default(config);\n }\n else {\n // typescript should preclude us from ever being here\n // because config is HTTPConfig | SQLConfig\n // But to be on the safe side, blow up if execution\n // has reached this point.\n core.setFailed('Unable to read a coherent action configuration');\n }\n core.endGroup();\n if (config.postprocess) {\n core.startGroup('Postprocess');\n core.debug(`Invoking ${config.postprocess} with ${filename}...`);\n try {\n const raw = child_process_1.execSync(`deno run -q --allow-read --allow-write --allow-run --allow-net --allow-env --unstable ${config.postprocess} ${filename}`).toString();\n core.info(\"Deno output:\");\n core.info(raw);\n }\n catch (error) {\n core.setFailed(error);\n }\n core.endGroup();\n }\n core.startGroup('File changes');\n const newUnstagedFiles = await child_process_1.execSync('git ls-files --others --exclude-standard').toString();\n const modifiedUnstagedFiles = await child_process_1.execSync('git ls-files -m').toString();\n const editedFilenames = [\n ...newUnstagedFiles.split('\\n'),\n ...modifiedUnstagedFiles.split('\\n'),\n ].filter(Boolean);\n core.info('newUnstagedFiles');\n core.info(newUnstagedFiles + '');\n core.info('modifiedUnstagedFiles');\n core.info(modifiedUnstagedFiles + '');\n core.info('editedFilenames');\n core.info(JSON.stringify(editedFilenames));\n core.endGroup();\n core.startGroup('Calculating diffstat');\n const editedFiles = [];\n for (const filename of editedFilenames) {\n core.debug(`git adding ${filename}…`);\n await exec_1.exec('git', ['add', filename]);\n const bytes = await git_1.diff(filename);\n // core.setOutput('delta_bytes', bytes)\n editedFiles.push({ name: filename, deltaBytes: bytes, source });\n }\n core.endGroup();\n core.startGroup('Committing new data');\n const alreadyEditedFiles = JSON.parse(process.env.FILES || '[]');\n core.info('alreadyEditedFiles');\n core.info(JSON.stringify(alreadyEditedFiles));\n core.info('editedFiles');\n core.info(JSON.stringify(editedFiles));\n const files = [...alreadyEditedFiles, ...editedFiles];\n core.exportVariable('FILES', files);\n core.endGroup();\n}\nrun().catch(error => {\n core.setFailed('Workflow failed! ' + error.message);\n});\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.issue = exports.issueCommand = void 0;\nconst os = __importStar(require(\"os\"));\nconst utils_1 = require(\"./utils\");\n/**\n * Commands\n *\n * Command Format:\n * ::name key=value,key=value::message\n *\n * Examples:\n * ::warning::This is the message\n * ::set-env name=MY_VAR::some value\n */\nfunction issueCommand(command, properties, message) {\n const cmd = new Command(command, properties, message);\n process.stdout.write(cmd.toString() + os.EOL);\n}\nexports.issueCommand = issueCommand;\nfunction issue(name, message = '') {\n issueCommand(name, {}, message);\n}\nexports.issue = issue;\nconst CMD_STRING = '::';\nclass Command {\n constructor(command, properties, message) {\n if (!command) {\n command = 'missing.command';\n }\n this.command = command;\n this.properties = properties;\n this.message = message;\n }\n toString() {\n let cmdStr = CMD_STRING + this.command;\n if (this.properties && Object.keys(this.properties).length > 0) {\n cmdStr += ' ';\n let first = true;\n for (const key in this.properties) {\n if (this.properties.hasOwnProperty(key)) {\n const val = this.properties[key];\n if (val) {\n if (first) {\n first = false;\n }\n else {\n cmdStr += ',';\n }\n cmdStr += `${key}=${escapeProperty(val)}`;\n }\n }\n }\n }\n cmdStr += `${CMD_STRING}${escapeData(this.message)}`;\n return cmdStr;\n }\n}\nfunction escapeData(s) {\n return utils_1.toCommandValue(s)\n .replace(/%/g, '%25')\n .replace(/\\r/g, '%0D')\n .replace(/\\n/g, '%0A');\n}\nfunction escapeProperty(s) {\n return utils_1.toCommandValue(s)\n .replace(/%/g, '%25')\n .replace(/\\r/g, '%0D')\n .replace(/\\n/g, '%0A')\n .replace(/:/g, '%3A')\n .replace(/,/g, '%2C');\n}\n//# sourceMappingURL=command.js.map","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0;\nconst command_1 = require(\"./command\");\nconst file_command_1 = require(\"./file-command\");\nconst utils_1 = require(\"./utils\");\nconst os = __importStar(require(\"os\"));\nconst path = __importStar(require(\"path\"));\n/**\n * The code to exit an action\n */\nvar ExitCode;\n(function (ExitCode) {\n /**\n * A code indicating that the action was successful\n */\n ExitCode[ExitCode[\"Success\"] = 0] = \"Success\";\n /**\n * A code indicating that the action was a failure\n */\n ExitCode[ExitCode[\"Failure\"] = 1] = \"Failure\";\n})(ExitCode = exports.ExitCode || (exports.ExitCode = {}));\n//-----------------------------------------------------------------------\n// Variables\n//-----------------------------------------------------------------------\n/**\n * Sets env variable for this action and future actions in the job\n * @param name the name of the variable to set\n * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction exportVariable(name, val) {\n const convertedVal = utils_1.toCommandValue(val);\n process.env[name] = convertedVal;\n const filePath = process.env['GITHUB_ENV'] || '';\n if (filePath) {\n const delimiter = '_GitHubActionsFileCommandDelimeter_';\n const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`;\n file_command_1.issueCommand('ENV', commandValue);\n }\n else {\n command_1.issueCommand('set-env', { name }, convertedVal);\n }\n}\nexports.exportVariable = exportVariable;\n/**\n * Registers a secret which will get masked from logs\n * @param secret value of the secret\n */\nfunction setSecret(secret) {\n command_1.issueCommand('add-mask', {}, secret);\n}\nexports.setSecret = setSecret;\n/**\n * Prepends inputPath to the PATH (for this action and future actions)\n * @param inputPath\n */\nfunction addPath(inputPath) {\n const filePath = process.env['GITHUB_PATH'] || '';\n if (filePath) {\n file_command_1.issueCommand('PATH', inputPath);\n }\n else {\n command_1.issueCommand('add-path', {}, inputPath);\n }\n process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`;\n}\nexports.addPath = addPath;\n/**\n * Gets the value of an input.\n * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed.\n * Returns an empty string if the value is not defined.\n *\n * @param name name of the input to get\n * @param options optional. See InputOptions.\n * @returns string\n */\nfunction getInput(name, options) {\n const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || '';\n if (options && options.required && !val) {\n throw new Error(`Input required and not supplied: ${name}`);\n }\n if (options && options.trimWhitespace === false) {\n return val;\n }\n return val.trim();\n}\nexports.getInput = getInput;\n/**\n * Gets the input value of the boolean type in the YAML 1.2 \"core schema\" specification.\n * Support boolean input list: `true | True | TRUE | false | False | FALSE` .\n * The return value is also in boolean type.\n * ref: https://yaml.org/spec/1.2/spec.html#id2804923\n *\n * @param name name of the input to get\n * @param options optional. See InputOptions.\n * @returns boolean\n */\nfunction getBooleanInput(name, options) {\n const trueValue = ['true', 'True', 'TRUE'];\n const falseValue = ['false', 'False', 'FALSE'];\n const val = getInput(name, options);\n if (trueValue.includes(val))\n return true;\n if (falseValue.includes(val))\n return false;\n throw new TypeError(`Input does not meet YAML 1.2 \"Core Schema\" specification: ${name}\\n` +\n `Support boolean input list: \\`true | True | TRUE | false | False | FALSE\\``);\n}\nexports.getBooleanInput = getBooleanInput;\n/**\n * Sets the value of an output.\n *\n * @param name name of the output to set\n * @param value value to store. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction setOutput(name, value) {\n process.stdout.write(os.EOL);\n command_1.issueCommand('set-output', { name }, value);\n}\nexports.setOutput = setOutput;\n/**\n * Enables or disables the echoing of commands into stdout for the rest of the step.\n * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set.\n *\n */\nfunction setCommandEcho(enabled) {\n command_1.issue('echo', enabled ? 'on' : 'off');\n}\nexports.setCommandEcho = setCommandEcho;\n//-----------------------------------------------------------------------\n// Results\n//-----------------------------------------------------------------------\n/**\n * Sets the action status to failed.\n * When the action exits it will be with an exit code of 1\n * @param message add error issue message\n */\nfunction setFailed(message) {\n process.exitCode = ExitCode.Failure;\n error(message);\n}\nexports.setFailed = setFailed;\n//-----------------------------------------------------------------------\n// Logging Commands\n//-----------------------------------------------------------------------\n/**\n * Gets whether Actions Step Debug is on or not\n */\nfunction isDebug() {\n return process.env['RUNNER_DEBUG'] === '1';\n}\nexports.isDebug = isDebug;\n/**\n * Writes debug message to user log\n * @param message debug message\n */\nfunction debug(message) {\n command_1.issueCommand('debug', {}, message);\n}\nexports.debug = debug;\n/**\n * Adds an error issue\n * @param message error issue message. Errors will be converted to string via toString()\n */\nfunction error(message) {\n command_1.issue('error', message instanceof Error ? message.toString() : message);\n}\nexports.error = error;\n/**\n * Adds an warning issue\n * @param message warning issue message. Errors will be converted to string via toString()\n */\nfunction warning(message) {\n command_1.issue('warning', message instanceof Error ? message.toString() : message);\n}\nexports.warning = warning;\n/**\n * Writes info to log with console.log.\n * @param message info message\n */\nfunction info(message) {\n process.stdout.write(message + os.EOL);\n}\nexports.info = info;\n/**\n * Begin an output group.\n *\n * Output until the next `groupEnd` will be foldable in this group\n *\n * @param name The name of the output group\n */\nfunction startGroup(name) {\n command_1.issue('group', name);\n}\nexports.startGroup = startGroup;\n/**\n * End an output group.\n */\nfunction endGroup() {\n command_1.issue('endgroup');\n}\nexports.endGroup = endGroup;\n/**\n * Wrap an asynchronous function call in a group.\n *\n * Returns the same type as the function itself.\n *\n * @param name The name of the group\n * @param fn The function to wrap in the group\n */\nfunction group(name, fn) {\n return __awaiter(this, void 0, void 0, function* () {\n startGroup(name);\n let result;\n try {\n result = yield fn();\n }\n finally {\n endGroup();\n }\n return result;\n });\n}\nexports.group = group;\n//-----------------------------------------------------------------------\n// Wrapper action state\n//-----------------------------------------------------------------------\n/**\n * Saves state for current action, the state can only be retrieved by this action's post job execution.\n *\n * @param name name of the state to store\n * @param value value to store. Non-string values will be converted to a string via JSON.stringify\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction saveState(name, value) {\n command_1.issueCommand('save-state', { name }, value);\n}\nexports.saveState = saveState;\n/**\n * Gets the value of an state set by this action's main execution.\n *\n * @param name name of the state to get\n * @returns string\n */\nfunction getState(name) {\n return process.env[`STATE_${name}`] || '';\n}\nexports.getState = getState;\n//# sourceMappingURL=core.js.map","\"use strict\";\n// For internal use, subject to change.\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.issueCommand = void 0;\n// We use any as a valid input type\n/* eslint-disable @typescript-eslint/no-explicit-any */\nconst fs = __importStar(require(\"fs\"));\nconst os = __importStar(require(\"os\"));\nconst utils_1 = require(\"./utils\");\nfunction issueCommand(command, message) {\n const filePath = process.env[`GITHUB_${command}`];\n if (!filePath) {\n throw new Error(`Unable to find environment variable for file command ${command}`);\n }\n if (!fs.existsSync(filePath)) {\n throw new Error(`Missing file at path: ${filePath}`);\n }\n fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, {\n encoding: 'utf8'\n });\n}\nexports.issueCommand = issueCommand;\n//# sourceMappingURL=file-command.js.map","\"use strict\";\n// We use any as a valid input type\n/* eslint-disable @typescript-eslint/no-explicit-any */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.toCommandValue = void 0;\n/**\n * Sanitizes an input into a string so it can be passed into issueCommand safely\n * @param input input to sanitize into a string\n */\nfunction toCommandValue(input) {\n if (input === null || input === undefined) {\n return '';\n }\n else if (typeof input === 'string' || input instanceof String) {\n return input;\n }\n return JSON.stringify(input);\n}\nexports.toCommandValue = toCommandValue;\n//# sourceMappingURL=utils.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tr = __importStar(require(\"./toolrunner\"));\n/**\n * Exec a command.\n * Output will be streamed to the live console.\n * Returns promise with return code\n *\n * @param commandLine command to execute (can include additional args). Must be correctly escaped.\n * @param args optional arguments for tool. Escaping is handled by the lib.\n * @param options optional exec options. See ExecOptions\n * @returns Promise exit code\n */\nfunction exec(commandLine, args, options) {\n return __awaiter(this, void 0, void 0, function* () {\n const commandArgs = tr.argStringToArray(commandLine);\n if (commandArgs.length === 0) {\n throw new Error(`Parameter 'commandLine' cannot be null or empty.`);\n }\n // Path to tool to execute should be first arg\n const toolPath = commandArgs[0];\n args = commandArgs.slice(1).concat(args || []);\n const runner = new tr.ToolRunner(toolPath, args, options);\n return runner.exec();\n });\n}\nexports.exec = exec;\n//# sourceMappingURL=exec.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst os = __importStar(require(\"os\"));\nconst events = __importStar(require(\"events\"));\nconst child = __importStar(require(\"child_process\"));\nconst path = __importStar(require(\"path\"));\nconst io = __importStar(require(\"@actions/io\"));\nconst ioUtil = __importStar(require(\"@actions/io/lib/io-util\"));\n/* eslint-disable @typescript-eslint/unbound-method */\nconst IS_WINDOWS = process.platform === 'win32';\n/*\n * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way.\n */\nclass ToolRunner extends events.EventEmitter {\n constructor(toolPath, args, options) {\n super();\n if (!toolPath) {\n throw new Error(\"Parameter 'toolPath' cannot be null or empty.\");\n }\n this.toolPath = toolPath;\n this.args = args || [];\n this.options = options || {};\n }\n _debug(message) {\n if (this.options.listeners && this.options.listeners.debug) {\n this.options.listeners.debug(message);\n }\n }\n _getCommandString(options, noPrefix) {\n const toolPath = this._getSpawnFileName();\n const args = this._getSpawnArgs(options);\n let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool\n if (IS_WINDOWS) {\n // Windows + cmd file\n if (this._isCmdFile()) {\n cmd += toolPath;\n for (const a of args) {\n cmd += ` ${a}`;\n }\n }\n // Windows + verbatim\n else if (options.windowsVerbatimArguments) {\n cmd += `\"${toolPath}\"`;\n for (const a of args) {\n cmd += ` ${a}`;\n }\n }\n // Windows (regular)\n else {\n cmd += this._windowsQuoteCmdArg(toolPath);\n for (const a of args) {\n cmd += ` ${this._windowsQuoteCmdArg(a)}`;\n }\n }\n }\n else {\n // OSX/Linux - this can likely be improved with some form of quoting.\n // creating processes on Unix is fundamentally different than Windows.\n // on Unix, execvp() takes an arg array.\n cmd += toolPath;\n for (const a of args) {\n cmd += ` ${a}`;\n }\n }\n return cmd;\n }\n _processLineBuffer(data, strBuffer, onLine) {\n try {\n let s = strBuffer + data.toString();\n let n = s.indexOf(os.EOL);\n while (n > -1) {\n const line = s.substring(0, n);\n onLine(line);\n // the rest of the string ...\n s = s.substring(n + os.EOL.length);\n n = s.indexOf(os.EOL);\n }\n strBuffer = s;\n }\n catch (err) {\n // streaming lines to console is best effort. Don't fail a build.\n this._debug(`error processing line. Failed with error ${err}`);\n }\n }\n _getSpawnFileName() {\n if (IS_WINDOWS) {\n if (this._isCmdFile()) {\n return process.env['COMSPEC'] || 'cmd.exe';\n }\n }\n return this.toolPath;\n }\n _getSpawnArgs(options) {\n if (IS_WINDOWS) {\n if (this._isCmdFile()) {\n let argline = `/D /S /C \"${this._windowsQuoteCmdArg(this.toolPath)}`;\n for (const a of this.args) {\n argline += ' ';\n argline += options.windowsVerbatimArguments\n ? a\n : this._windowsQuoteCmdArg(a);\n }\n argline += '\"';\n return [argline];\n }\n }\n return this.args;\n }\n _endsWith(str, end) {\n return str.endsWith(end);\n }\n _isCmdFile() {\n const upperToolPath = this.toolPath.toUpperCase();\n return (this._endsWith(upperToolPath, '.CMD') ||\n this._endsWith(upperToolPath, '.BAT'));\n }\n _windowsQuoteCmdArg(arg) {\n // for .exe, apply the normal quoting rules that libuv applies\n if (!this._isCmdFile()) {\n return this._uvQuoteCmdArg(arg);\n }\n // otherwise apply quoting rules specific to the cmd.exe command line parser.\n // the libuv rules are generic and are not designed specifically for cmd.exe\n // command line parser.\n //\n // for a detailed description of the cmd.exe command line parser, refer to\n // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912\n // need quotes for empty arg\n if (!arg) {\n return '\"\"';\n }\n // determine whether the arg needs to be quoted\n const cmdSpecialChars = [\n ' ',\n '\\t',\n '&',\n '(',\n ')',\n '[',\n ']',\n '{',\n '}',\n '^',\n '=',\n ';',\n '!',\n \"'\",\n '+',\n ',',\n '`',\n '~',\n '|',\n '<',\n '>',\n '\"'\n ];\n let needsQuotes = false;\n for (const char of arg) {\n if (cmdSpecialChars.some(x => x === char)) {\n needsQuotes = true;\n break;\n }\n }\n // short-circuit if quotes not needed\n if (!needsQuotes) {\n return arg;\n }\n // the following quoting rules are very similar to the rules that by libuv applies.\n //\n // 1) wrap the string in quotes\n //\n // 2) double-up quotes - i.e. \" => \"\"\n //\n // this is different from the libuv quoting rules. libuv replaces \" with \\\", which unfortunately\n // doesn't work well with a cmd.exe command line.\n //\n // note, replacing \" with \"\" also works well if the arg is passed to a downstream .NET console app.\n // for example, the command line:\n // foo.exe \"myarg:\"\"my val\"\"\"\n // is parsed by a .NET console app into an arg array:\n // [ \"myarg:\\\"my val\\\"\" ]\n // which is the same end result when applying libuv quoting rules. although the actual\n // command line from libuv quoting rules would look like:\n // foo.exe \"myarg:\\\"my val\\\"\"\n //\n // 3) double-up slashes that precede a quote,\n // e.g. hello \\world => \"hello \\world\"\n // hello\\\"world => \"hello\\\\\"\"world\"\n // hello\\\\\"world => \"hello\\\\\\\\\"\"world\"\n // hello world\\ => \"hello world\\\\\"\n //\n // technically this is not required for a cmd.exe command line, or the batch argument parser.\n // the reasons for including this as a .cmd quoting rule are:\n //\n // a) this is optimized for the scenario where the argument is passed from the .cmd file to an\n // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule.\n //\n // b) it's what we've been doing previously (by deferring to node default behavior) and we\n // haven't heard any complaints about that aspect.\n //\n // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be\n // escaped when used on the command line directly - even though within a .cmd file % can be escaped\n // by using %%.\n //\n // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts\n // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing.\n //\n // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would\n // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the\n // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args\n // to an external program.\n //\n // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file.\n // % can be escaped within a .cmd file.\n let reverse = '\"';\n let quoteHit = true;\n for (let i = arg.length; i > 0; i--) {\n // walk the string in reverse\n reverse += arg[i - 1];\n if (quoteHit && arg[i - 1] === '\\\\') {\n reverse += '\\\\'; // double the slash\n }\n else if (arg[i - 1] === '\"') {\n quoteHit = true;\n reverse += '\"'; // double the quote\n }\n else {\n quoteHit = false;\n }\n }\n reverse += '\"';\n return reverse\n .split('')\n .reverse()\n .join('');\n }\n _uvQuoteCmdArg(arg) {\n // Tool runner wraps child_process.spawn() and needs to apply the same quoting as\n // Node in certain cases where the undocumented spawn option windowsVerbatimArguments\n // is used.\n //\n // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV,\n // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details),\n // pasting copyright notice from Node within this function:\n //\n // Copyright Joyent, Inc. and other Node contributors. All rights reserved.\n //\n // Permission is hereby granted, free of charge, to any person obtaining a copy\n // of this software and associated documentation files (the \"Software\"), to\n // deal in the Software without restriction, including without limitation the\n // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n // sell copies of the Software, and to permit persons to whom the Software is\n // furnished to do so, subject to the following conditions:\n //\n // The above copyright notice and this permission notice shall be included in\n // all copies or substantial portions of the Software.\n //\n // THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n // IN THE SOFTWARE.\n if (!arg) {\n // Need double quotation for empty argument\n return '\"\"';\n }\n if (!arg.includes(' ') && !arg.includes('\\t') && !arg.includes('\"')) {\n // No quotation needed\n return arg;\n }\n if (!arg.includes('\"') && !arg.includes('\\\\')) {\n // No embedded double quotes or backslashes, so I can just wrap\n // quote marks around the whole thing.\n return `\"${arg}\"`;\n }\n // Expected input/output:\n // input : hello\"world\n // output: \"hello\\\"world\"\n // input : hello\"\"world\n // output: \"hello\\\"\\\"world\"\n // input : hello\\world\n // output: hello\\world\n // input : hello\\\\world\n // output: hello\\\\world\n // input : hello\\\"world\n // output: \"hello\\\\\\\"world\"\n // input : hello\\\\\"world\n // output: \"hello\\\\\\\\\\\"world\"\n // input : hello world\\\n // output: \"hello world\\\\\" - note the comment in libuv actually reads \"hello world\\\"\n // but it appears the comment is wrong, it should be \"hello world\\\\\"\n let reverse = '\"';\n let quoteHit = true;\n for (let i = arg.length; i > 0; i--) {\n // walk the string in reverse\n reverse += arg[i - 1];\n if (quoteHit && arg[i - 1] === '\\\\') {\n reverse += '\\\\';\n }\n else if (arg[i - 1] === '\"') {\n quoteHit = true;\n reverse += '\\\\';\n }\n else {\n quoteHit = false;\n }\n }\n reverse += '\"';\n return reverse\n .split('')\n .reverse()\n .join('');\n }\n _cloneExecOptions(options) {\n options = options || {};\n const result = {\n cwd: options.cwd || process.cwd(),\n env: options.env || process.env,\n silent: options.silent || false,\n windowsVerbatimArguments: options.windowsVerbatimArguments || false,\n failOnStdErr: options.failOnStdErr || false,\n ignoreReturnCode: options.ignoreReturnCode || false,\n delay: options.delay || 10000\n };\n result.outStream = options.outStream || process.stdout;\n result.errStream = options.errStream || process.stderr;\n return result;\n }\n _getSpawnOptions(options, toolPath) {\n options = options || {};\n const result = {};\n result.cwd = options.cwd;\n result.env = options.env;\n result['windowsVerbatimArguments'] =\n options.windowsVerbatimArguments || this._isCmdFile();\n if (options.windowsVerbatimArguments) {\n result.argv0 = `\"${toolPath}\"`;\n }\n return result;\n }\n /**\n * Exec a tool.\n * Output will be streamed to the live console.\n * Returns promise with return code\n *\n * @param tool path to tool to exec\n * @param options optional exec options. See ExecOptions\n * @returns number\n */\n exec() {\n return __awaiter(this, void 0, void 0, function* () {\n // root the tool path if it is unrooted and contains relative pathing\n if (!ioUtil.isRooted(this.toolPath) &&\n (this.toolPath.includes('/') ||\n (IS_WINDOWS && this.toolPath.includes('\\\\')))) {\n // prefer options.cwd if it is specified, however options.cwd may also need to be rooted\n this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath);\n }\n // if the tool is only a file name, then resolve it from the PATH\n // otherwise verify it exists (add extension on Windows if necessary)\n this.toolPath = yield io.which(this.toolPath, true);\n return new Promise((resolve, reject) => {\n this._debug(`exec tool: ${this.toolPath}`);\n this._debug('arguments:');\n for (const arg of this.args) {\n this._debug(` ${arg}`);\n }\n const optionsNonNull = this._cloneExecOptions(this.options);\n if (!optionsNonNull.silent && optionsNonNull.outStream) {\n optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL);\n }\n const state = new ExecState(optionsNonNull, this.toolPath);\n state.on('debug', (message) => {\n this._debug(message);\n });\n const fileName = this._getSpawnFileName();\n const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName));\n const stdbuffer = '';\n if (cp.stdout) {\n cp.stdout.on('data', (data) => {\n if (this.options.listeners && this.options.listeners.stdout) {\n this.options.listeners.stdout(data);\n }\n if (!optionsNonNull.silent && optionsNonNull.outStream) {\n optionsNonNull.outStream.write(data);\n }\n this._processLineBuffer(data, stdbuffer, (line) => {\n if (this.options.listeners && this.options.listeners.stdline) {\n this.options.listeners.stdline(line);\n }\n });\n });\n }\n const errbuffer = '';\n if (cp.stderr) {\n cp.stderr.on('data', (data) => {\n state.processStderr = true;\n if (this.options.listeners && this.options.listeners.stderr) {\n this.options.listeners.stderr(data);\n }\n if (!optionsNonNull.silent &&\n optionsNonNull.errStream &&\n optionsNonNull.outStream) {\n const s = optionsNonNull.failOnStdErr\n ? optionsNonNull.errStream\n : optionsNonNull.outStream;\n s.write(data);\n }\n this._processLineBuffer(data, errbuffer, (line) => {\n if (this.options.listeners && this.options.listeners.errline) {\n this.options.listeners.errline(line);\n }\n });\n });\n }\n cp.on('error', (err) => {\n state.processError = err.message;\n state.processExited = true;\n state.processClosed = true;\n state.CheckComplete();\n });\n cp.on('exit', (code) => {\n state.processExitCode = code;\n state.processExited = true;\n this._debug(`Exit code ${code} received from tool '${this.toolPath}'`);\n state.CheckComplete();\n });\n cp.on('close', (code) => {\n state.processExitCode = code;\n state.processExited = true;\n state.processClosed = true;\n this._debug(`STDIO streams have closed for tool '${this.toolPath}'`);\n state.CheckComplete();\n });\n state.on('done', (error, exitCode) => {\n if (stdbuffer.length > 0) {\n this.emit('stdline', stdbuffer);\n }\n if (errbuffer.length > 0) {\n this.emit('errline', errbuffer);\n }\n cp.removeAllListeners();\n if (error) {\n reject(error);\n }\n else {\n resolve(exitCode);\n }\n });\n if (this.options.input) {\n if (!cp.stdin) {\n throw new Error('child process missing stdin');\n }\n cp.stdin.end(this.options.input);\n }\n });\n });\n }\n}\nexports.ToolRunner = ToolRunner;\n/**\n * Convert an arg string to an array of args. Handles escaping\n *\n * @param argString string of arguments\n * @returns string[] array of arguments\n */\nfunction argStringToArray(argString) {\n const args = [];\n let inQuotes = false;\n let escaped = false;\n let arg = '';\n function append(c) {\n // we only escape double quotes.\n if (escaped && c !== '\"') {\n arg += '\\\\';\n }\n arg += c;\n escaped = false;\n }\n for (let i = 0; i < argString.length; i++) {\n const c = argString.charAt(i);\n if (c === '\"') {\n if (!escaped) {\n inQuotes = !inQuotes;\n }\n else {\n append(c);\n }\n continue;\n }\n if (c === '\\\\' && escaped) {\n append(c);\n continue;\n }\n if (c === '\\\\' && inQuotes) {\n escaped = true;\n continue;\n }\n if (c === ' ' && !inQuotes) {\n if (arg.length > 0) {\n args.push(arg);\n arg = '';\n }\n continue;\n }\n append(c);\n }\n if (arg.length > 0) {\n args.push(arg.trim());\n }\n return args;\n}\nexports.argStringToArray = argStringToArray;\nclass ExecState extends events.EventEmitter {\n constructor(options, toolPath) {\n super();\n this.processClosed = false; // tracks whether the process has exited and stdio is closed\n this.processError = '';\n this.processExitCode = 0;\n this.processExited = false; // tracks whether the process has exited\n this.processStderr = false; // tracks whether stderr was written to\n this.delay = 10000; // 10 seconds\n this.done = false;\n this.timeout = null;\n if (!toolPath) {\n throw new Error('toolPath must not be empty');\n }\n this.options = options;\n this.toolPath = toolPath;\n if (options.delay) {\n this.delay = options.delay;\n }\n }\n CheckComplete() {\n if (this.done) {\n return;\n }\n if (this.processClosed) {\n this._setResult();\n }\n else if (this.processExited) {\n this.timeout = setTimeout(ExecState.HandleTimeout, this.delay, this);\n }\n }\n _debug(message) {\n this.emit('debug', message);\n }\n _setResult() {\n // determine whether there is an error\n let error;\n if (this.processExited) {\n if (this.processError) {\n error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`);\n }\n else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) {\n error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`);\n }\n else if (this.processStderr && this.options.failOnStdErr) {\n error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`);\n }\n }\n // clear the timeout\n if (this.timeout) {\n clearTimeout(this.timeout);\n this.timeout = null;\n }\n this.done = true;\n this.emit('done', error, this.processExitCode);\n }\n static HandleTimeout(state) {\n if (state.done) {\n return;\n }\n if (!state.processClosed && state.processExited) {\n const message = `The STDIO streams did not close within ${state.delay /\n 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`;\n state._debug(message);\n }\n state._setResult();\n }\n}\n//# sourceMappingURL=toolrunner.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};\nvar _a;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst assert_1 = require(\"assert\");\nconst fs = __importStar(require(\"fs\"));\nconst path = __importStar(require(\"path\"));\n_a = fs.promises, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink;\nexports.IS_WINDOWS = process.platform === 'win32';\nfunction exists(fsPath) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n yield exports.stat(fsPath);\n }\n catch (err) {\n if (err.code === 'ENOENT') {\n return false;\n }\n throw err;\n }\n return true;\n });\n}\nexports.exists = exists;\nfunction isDirectory(fsPath, useStat = false) {\n return __awaiter(this, void 0, void 0, function* () {\n const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath);\n return stats.isDirectory();\n });\n}\nexports.isDirectory = isDirectory;\n/**\n * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like:\n * \\, \\hello, \\\\hello\\share, C:, and C:\\hello (and corresponding alternate separator cases).\n */\nfunction isRooted(p) {\n p = normalizeSeparators(p);\n if (!p) {\n throw new Error('isRooted() parameter \"p\" cannot be empty');\n }\n if (exports.IS_WINDOWS) {\n return (p.startsWith('\\\\') || /^[A-Z]:/i.test(p) // e.g. \\ or \\hello or \\\\hello\n ); // e.g. C: or C:\\hello\n }\n return p.startsWith('/');\n}\nexports.isRooted = isRooted;\n/**\n * Recursively create a directory at `fsPath`.\n *\n * This implementation is optimistic, meaning it attempts to create the full\n * path first, and backs up the path stack from there.\n *\n * @param fsPath The path to create\n * @param maxDepth The maximum recursion depth\n * @param depth The current recursion depth\n */\nfunction mkdirP(fsPath, maxDepth = 1000, depth = 1) {\n return __awaiter(this, void 0, void 0, function* () {\n assert_1.ok(fsPath, 'a path argument must be provided');\n fsPath = path.resolve(fsPath);\n if (depth >= maxDepth)\n return exports.mkdir(fsPath);\n try {\n yield exports.mkdir(fsPath);\n return;\n }\n catch (err) {\n switch (err.code) {\n case 'ENOENT': {\n yield mkdirP(path.dirname(fsPath), maxDepth, depth + 1);\n yield exports.mkdir(fsPath);\n return;\n }\n default: {\n let stats;\n try {\n stats = yield exports.stat(fsPath);\n }\n catch (err2) {\n throw err;\n }\n if (!stats.isDirectory())\n throw err;\n }\n }\n }\n });\n}\nexports.mkdirP = mkdirP;\n/**\n * Best effort attempt to determine whether a file exists and is executable.\n * @param filePath file path to check\n * @param extensions additional file extensions to try\n * @return if file exists and is executable, returns the file path. otherwise empty string.\n */\nfunction tryGetExecutablePath(filePath, extensions) {\n return __awaiter(this, void 0, void 0, function* () {\n let stats = undefined;\n try {\n // test file exists\n stats = yield exports.stat(filePath);\n }\n catch (err) {\n if (err.code !== 'ENOENT') {\n // eslint-disable-next-line no-console\n console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);\n }\n }\n if (stats && stats.isFile()) {\n if (exports.IS_WINDOWS) {\n // on Windows, test for valid extension\n const upperExt = path.extname(filePath).toUpperCase();\n if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) {\n return filePath;\n }\n }\n else {\n if (isUnixExecutable(stats)) {\n return filePath;\n }\n }\n }\n // try each extension\n const originalFilePath = filePath;\n for (const extension of extensions) {\n filePath = originalFilePath + extension;\n stats = undefined;\n try {\n stats = yield exports.stat(filePath);\n }\n catch (err) {\n if (err.code !== 'ENOENT') {\n // eslint-disable-next-line no-console\n console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`);\n }\n }\n if (stats && stats.isFile()) {\n if (exports.IS_WINDOWS) {\n // preserve the case of the actual file (since an extension was appended)\n try {\n const directory = path.dirname(filePath);\n const upperName = path.basename(filePath).toUpperCase();\n for (const actualName of yield exports.readdir(directory)) {\n if (upperName === actualName.toUpperCase()) {\n filePath = path.join(directory, actualName);\n break;\n }\n }\n }\n catch (err) {\n // eslint-disable-next-line no-console\n console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`);\n }\n return filePath;\n }\n else {\n if (isUnixExecutable(stats)) {\n return filePath;\n }\n }\n }\n }\n return '';\n });\n}\nexports.tryGetExecutablePath = tryGetExecutablePath;\nfunction normalizeSeparators(p) {\n p = p || '';\n if (exports.IS_WINDOWS) {\n // convert slashes on Windows\n p = p.replace(/\\//g, '\\\\');\n // remove redundant slashes\n return p.replace(/\\\\\\\\+/g, '\\\\');\n }\n // remove redundant slashes\n return p.replace(/\\/\\/+/g, '/');\n}\n// on Mac/Linux, test the execute bit\n// R W X R W X R W X\n// 256 128 64 32 16 8 4 2 1\nfunction isUnixExecutable(stats) {\n return ((stats.mode & 1) > 0 ||\n ((stats.mode & 8) > 0 && stats.gid === process.getgid()) ||\n ((stats.mode & 64) > 0 && stats.uid === process.getuid()));\n}\n//# sourceMappingURL=io-util.js.map","\"use strict\";\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst childProcess = __importStar(require(\"child_process\"));\nconst path = __importStar(require(\"path\"));\nconst util_1 = require(\"util\");\nconst ioUtil = __importStar(require(\"./io-util\"));\nconst exec = util_1.promisify(childProcess.exec);\n/**\n * Copies a file or folder.\n * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js\n *\n * @param source source path\n * @param dest destination path\n * @param options optional. See CopyOptions.\n */\nfunction cp(source, dest, options = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n const { force, recursive } = readCopyOptions(options);\n const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null;\n // Dest is an existing file, but not forcing\n if (destStat && destStat.isFile() && !force) {\n return;\n }\n // If dest is an existing directory, should copy inside.\n const newDest = destStat && destStat.isDirectory()\n ? path.join(dest, path.basename(source))\n : dest;\n if (!(yield ioUtil.exists(source))) {\n throw new Error(`no such file or directory: ${source}`);\n }\n const sourceStat = yield ioUtil.stat(source);\n if (sourceStat.isDirectory()) {\n if (!recursive) {\n throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`);\n }\n else {\n yield cpDirRecursive(source, newDest, 0, force);\n }\n }\n else {\n if (path.relative(source, newDest) === '') {\n // a file cannot be copied to itself\n throw new Error(`'${newDest}' and '${source}' are the same file`);\n }\n yield copyFile(source, newDest, force);\n }\n });\n}\nexports.cp = cp;\n/**\n * Moves a path.\n *\n * @param source source path\n * @param dest destination path\n * @param options optional. See MoveOptions.\n */\nfunction mv(source, dest, options = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n if (yield ioUtil.exists(dest)) {\n let destExists = true;\n if (yield ioUtil.isDirectory(dest)) {\n // If dest is directory copy src into dest\n dest = path.join(dest, path.basename(source));\n destExists = yield ioUtil.exists(dest);\n }\n if (destExists) {\n if (options.force == null || options.force) {\n yield rmRF(dest);\n }\n else {\n throw new Error('Destination already exists');\n }\n }\n }\n yield mkdirP(path.dirname(dest));\n yield ioUtil.rename(source, dest);\n });\n}\nexports.mv = mv;\n/**\n * Remove a path recursively with force\n *\n * @param inputPath path to remove\n */\nfunction rmRF(inputPath) {\n return __awaiter(this, void 0, void 0, function* () {\n if (ioUtil.IS_WINDOWS) {\n // Node doesn't provide a delete operation, only an unlink function. This means that if the file is being used by another\n // program (e.g. antivirus), it won't be deleted. To address this, we shell out the work to rd/del.\n try {\n if (yield ioUtil.isDirectory(inputPath, true)) {\n yield exec(`rd /s /q \"${inputPath}\"`);\n }\n else {\n yield exec(`del /f /a \"${inputPath}\"`);\n }\n }\n catch (err) {\n // if you try to delete a file that doesn't exist, desired result is achieved\n // other errors are valid\n if (err.code !== 'ENOENT')\n throw err;\n }\n // Shelling out fails to remove a symlink folder with missing source, this unlink catches that\n try {\n yield ioUtil.unlink(inputPath);\n }\n catch (err) {\n // if you try to delete a file that doesn't exist, desired result is achieved\n // other errors are valid\n if (err.code !== 'ENOENT')\n throw err;\n }\n }\n else {\n let isDir = false;\n try {\n isDir = yield ioUtil.isDirectory(inputPath);\n }\n catch (err) {\n // if you try to delete a file that doesn't exist, desired result is achieved\n // other errors are valid\n if (err.code !== 'ENOENT')\n throw err;\n return;\n }\n if (isDir) {\n yield exec(`rm -rf \"${inputPath}\"`);\n }\n else {\n yield ioUtil.unlink(inputPath);\n }\n }\n });\n}\nexports.rmRF = rmRF;\n/**\n * Make a directory. Creates the full path with folders in between\n * Will throw if it fails\n *\n * @param fsPath path to create\n * @returns Promise\n */\nfunction mkdirP(fsPath) {\n return __awaiter(this, void 0, void 0, function* () {\n yield ioUtil.mkdirP(fsPath);\n });\n}\nexports.mkdirP = mkdirP;\n/**\n * Returns path of a tool had the tool actually been invoked. Resolves via paths.\n * If you check and the tool does not exist, it will throw.\n *\n * @param tool name of the tool\n * @param check whether to check if tool exists\n * @returns Promise path to tool\n */\nfunction which(tool, check) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!tool) {\n throw new Error(\"parameter 'tool' is required\");\n }\n // recursive when check=true\n if (check) {\n const result = yield which(tool, false);\n if (!result) {\n if (ioUtil.IS_WINDOWS) {\n throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`);\n }\n else {\n throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`);\n }\n }\n return result;\n }\n const matches = yield findInPath(tool);\n if (matches && matches.length > 0) {\n return matches[0];\n }\n return '';\n });\n}\nexports.which = which;\n/**\n * Returns a list of all occurrences of the given tool on the system path.\n *\n * @returns Promise the paths of the tool\n */\nfunction findInPath(tool) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!tool) {\n throw new Error(\"parameter 'tool' is required\");\n }\n // build the list of extensions to try\n const extensions = [];\n if (ioUtil.IS_WINDOWS && process.env['PATHEXT']) {\n for (const extension of process.env['PATHEXT'].split(path.delimiter)) {\n if (extension) {\n extensions.push(extension);\n }\n }\n }\n // if it's rooted, return it if exists. otherwise return empty.\n if (ioUtil.isRooted(tool)) {\n const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions);\n if (filePath) {\n return [filePath];\n }\n return [];\n }\n // if any path separators, return empty\n if (tool.includes(path.sep)) {\n return [];\n }\n // build the list of directories\n //\n // Note, technically \"where\" checks the current directory on Windows. From a toolkit perspective,\n // it feels like we should not do this. Checking the current directory seems like more of a use\n // case of a shell, and the which() function exposed by the toolkit should strive for consistency\n // across platforms.\n const directories = [];\n if (process.env.PATH) {\n for (const p of process.env.PATH.split(path.delimiter)) {\n if (p) {\n directories.push(p);\n }\n }\n }\n // find all matches\n const matches = [];\n for (const directory of directories) {\n const filePath = yield ioUtil.tryGetExecutablePath(path.join(directory, tool), extensions);\n if (filePath) {\n matches.push(filePath);\n }\n }\n return matches;\n });\n}\nexports.findInPath = findInPath;\nfunction readCopyOptions(options) {\n const force = options.force == null ? true : options.force;\n const recursive = Boolean(options.recursive);\n return { force, recursive };\n}\nfunction cpDirRecursive(sourceDir, destDir, currentDepth, force) {\n return __awaiter(this, void 0, void 0, function* () {\n // Ensure there is not a run away recursive copy\n if (currentDepth >= 255)\n return;\n currentDepth++;\n yield mkdirP(destDir);\n const files = yield ioUtil.readdir(sourceDir);\n for (const fileName of files) {\n const srcFile = `${sourceDir}/${fileName}`;\n const destFile = `${destDir}/${fileName}`;\n const srcFileStat = yield ioUtil.lstat(srcFile);\n if (srcFileStat.isDirectory()) {\n // Recurse\n yield cpDirRecursive(srcFile, destFile, currentDepth, force);\n }\n else {\n yield copyFile(srcFile, destFile, force);\n }\n }\n // Change the mode for the newly created directory\n yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode);\n });\n}\n// Buffered file copy\nfunction copyFile(srcFile, destFile, force) {\n return __awaiter(this, void 0, void 0, function* () {\n if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) {\n // unlink/re-link it\n try {\n yield ioUtil.lstat(destFile);\n yield ioUtil.unlink(destFile);\n }\n catch (e) {\n // Try to override file permission\n if (e.code === 'EPERM') {\n yield ioUtil.chmod(destFile, '0666');\n yield ioUtil.unlink(destFile);\n }\n // other errors = it doesn't exist, no work to do\n }\n // Copy over symlink\n const symlinkFull = yield ioUtil.readlink(srcFile);\n yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null);\n }\n else if (!(yield ioUtil.exists(destFile)) || force) {\n yield ioUtil.copyFile(srcFile, destFile);\n }\n });\n}\n//# sourceMappingURL=io.js.map","/** @license ms-rest-azure-env\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n */\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n typeof define === 'function' && define.amd ? define(['exports'], factory) :\n (factory((global.Azure = {})));\n}(this, (function (exports) { 'use strict';\n\n // Copyright (c) Microsoft Corporation. All rights reserved.\n // Licensed under the MIT License. See License.txt in the project root for license information.\n var Environment = /** @class */ (function () {\n function Environment(parameters) {\n /**\n * Determines whether the authentication endpoint should be validated with Azure AD. Default value is true.\n */\n this.validateAuthority = true;\n if (!parameters || typeof parameters !== \"object\") {\n throw new Error(\"'parameters' is a required parameter and must be of type 'object'.\");\n }\n // Validate required parameters\n var requiredParams = [\"name\", \"portalUrl\", \"managementEndpointUrl\", \"resourceManagerEndpointUrl\",\n \"activeDirectoryEndpointUrl\", \"activeDirectoryResourceId\"];\n requiredParams.forEach(function (param) {\n if (!parameters[param] || typeof parameters[param].valueOf() !== \"string\") {\n throw new Error(\"Please provide \\\"\" + param + \"\\\" for the environment and it must be of type \\\"string\\\".\");\n }\n });\n this.name = parameters.name;\n this.portalUrl = parameters.portalUrl;\n this.managementEndpointUrl = parameters.managementEndpointUrl;\n this.resourceManagerEndpointUrl = parameters.resourceManagerEndpointUrl;\n this.activeDirectoryEndpointUrl = parameters.activeDirectoryEndpointUrl;\n this.activeDirectoryResourceId = parameters.activeDirectoryResourceId;\n if (this.activeDirectoryGraphApiVersion) {\n this.activeDirectoryGraphApiVersion = parameters.activeDirectoryGraphApiVersion;\n }\n if (this.activeDirectoryGraphResourceId) {\n this.activeDirectoryGraphResourceId = parameters.activeDirectoryGraphResourceId;\n }\n if (this.azureDataLakeAnalyticsCatalogAndJobEndpointSuffix) {\n this.azureDataLakeAnalyticsCatalogAndJobEndpointSuffix = parameters.azureDataLakeAnalyticsCatalogAndJobEndpointSuffix;\n }\n if (this.azureDataLakeStoreFileSystemEndpointSuffix) {\n this.azureDataLakeStoreFileSystemEndpointSuffix = parameters.azureDataLakeStoreFileSystemEndpointSuffix;\n }\n if (this.batchResourceId) {\n this.batchResourceId = parameters.batchResourceId;\n }\n if (this.galleryEndpointUrl) {\n this.galleryEndpointUrl = parameters.galleryEndpointUrl;\n }\n if (this.keyVaultDnsSuffix) {\n this.keyVaultDnsSuffix = parameters.keyVaultDnsSuffix;\n }\n if (this.publishingProfileUrl) {\n this.publishingProfileUrl = parameters.publishingProfileUrl;\n }\n if (this.sqlManagementEndpointUrl) {\n this.sqlManagementEndpointUrl = parameters.sqlManagementEndpointUrl;\n }\n if (this.sqlServerHostnameSuffix) {\n this.sqlServerHostnameSuffix = parameters.sqlServerHostnameSuffix;\n }\n if (this.storageEndpointSuffix) {\n this.storageEndpointSuffix = parameters.storageEndpointSuffix;\n }\n }\n Environment.add = function (parameters) {\n var envContainer = {};\n var envObj = new Environment(parameters);\n envContainer[parameters.name] = envObj;\n Object.assign(Environment, envContainer);\n return;\n };\n Environment.get = function (name) {\n if (!name) {\n throw new TypeError(\"name cannot be null or undefined and must be of type string.\");\n }\n return Environment[name];\n };\n Environment.AzureCloud = {\n name: \"AzureCloud\",\n portalUrl: \"https://portal.azure.com\",\n publishingProfileUrl: \"https://go.microsoft.com/fwlink/?LinkId=254432\",\n managementEndpointUrl: \"https://management.core.windows.net\",\n resourceManagerEndpointUrl: \"https://management.azure.com/\",\n sqlManagementEndpointUrl: \"https://management.core.windows.net:8443/\",\n sqlServerHostnameSuffix: \".database.windows.net\",\n galleryEndpointUrl: \"https://gallery.azure.com/\",\n activeDirectoryEndpointUrl: \"https://login.microsoftonline.com/\",\n activeDirectoryResourceId: \"https://management.core.windows.net/\",\n activeDirectoryGraphResourceId: \"https://graph.windows.net/\",\n batchResourceId: \"https://batch.core.windows.net/\",\n activeDirectoryGraphApiVersion: \"2013-04-05\",\n storageEndpointSuffix: \".core.windows.net\",\n keyVaultDnsSuffix: \".vault.azure.net\",\n azureDataLakeStoreFileSystemEndpointSuffix: \"azuredatalakestore.net\",\n azureDataLakeAnalyticsCatalogAndJobEndpointSuffix: \"azuredatalakeanalytics.net\",\n validateAuthority: true\n };\n Environment.ChinaCloud = {\n name: \"AzureChinaCloud\",\n portalUrl: \"https://portal.azure.cn\",\n publishingProfileUrl: \"https://go.microsoft.com/fwlink/?LinkID=301774\",\n managementEndpointUrl: \"https://management.core.chinacloudapi.cn\",\n resourceManagerEndpointUrl: \"https://management.chinacloudapi.cn\",\n sqlManagementEndpointUrl: \"https://management.core.chinacloudapi.cn:8443/\",\n sqlServerHostnameSuffix: \".database.chinacloudapi.cn\",\n galleryEndpointUrl: \"https://gallery.chinacloudapi.cn/\",\n activeDirectoryEndpointUrl: \"https://login.chinacloudapi.cn/\",\n activeDirectoryResourceId: \"https://management.core.chinacloudapi.cn/\",\n activeDirectoryGraphResourceId: \"https://graph.chinacloudapi.cn/\",\n activeDirectoryGraphApiVersion: \"2013-04-05\",\n batchResourceId: \"https://batch.chinacloudapi.cn/\",\n storageEndpointSuffix: \".core.chinacloudapi.cn\",\n keyVaultDnsSuffix: \".vault.azure.cn\",\n // TODO: add dns suffixes for the china cloud for datalake store and datalake analytics once they are defined.\n azureDataLakeStoreFileSystemEndpointSuffix: \"N/A\",\n azureDataLakeAnalyticsCatalogAndJobEndpointSuffix: \"N/A\",\n validateAuthority: true\n };\n Environment.USGovernment = {\n name: \"AzureUSGovernment\",\n portalUrl: \"https://portal.azure.us\",\n publishingProfileUrl: \"https://manage.windowsazure.us/publishsettings/index\",\n managementEndpointUrl: \"https://management.core.usgovcloudapi.net\",\n resourceManagerEndpointUrl: \"https://management.usgovcloudapi.net\",\n sqlManagementEndpointUrl: \"https://management.core.usgovcloudapi.net:8443/\",\n sqlServerHostnameSuffix: \".database.usgovcloudapi.net\",\n galleryEndpointUrl: \"https://gallery.usgovcloudapi.net/\",\n activeDirectoryEndpointUrl: \"https://login.microsoftonline.us/\",\n activeDirectoryResourceId: \"https://management.core.usgovcloudapi.net/\",\n activeDirectoryGraphResourceId: \"https://graph.windows.net/\",\n batchResourceId: \"https://batch.core.usgovcloudapi.net/\",\n activeDirectoryGraphApiVersion: \"2013-04-05\",\n storageEndpointSuffix: \".core.usgovcloudapi.net\",\n keyVaultDnsSuffix: \".vault.usgovcloudapi.net\",\n azureDataLakeStoreFileSystemEndpointSuffix: \"N/A\",\n azureDataLakeAnalyticsCatalogAndJobEndpointSuffix: \"N/A\",\n validateAuthority: true\n };\n Environment.GermanCloud = {\n name: \"AzureGermanCloud\",\n portalUrl: \"https://portal.microsoftazure.de/\",\n publishingProfileUrl: \"https://manage.microsoftazure.de/publishsettings/index\",\n managementEndpointUrl: \"https://management.core.cloudapi.de\",\n resourceManagerEndpointUrl: \"https://management.microsoftazure.de\",\n sqlManagementEndpointUrl: \"https://management.core.cloudapi.de:8443/\",\n sqlServerHostnameSuffix: \".database.cloudapi.de\",\n galleryEndpointUrl: \"https://gallery.cloudapi.de/\",\n activeDirectoryEndpointUrl: \"https://login.microsoftonline.de/\",\n activeDirectoryResourceId: \"https://management.core.cloudapi.de/\",\n activeDirectoryGraphResourceId: \"https://graph.cloudapi.de/\",\n batchResourceId: \"https://batch.microsoftazure.de/\",\n activeDirectoryGraphApiVersion: \"2013-04-05\",\n storageEndpointSuffix: \".core.cloudapi.de\",\n keyVaultDnsSuffix: \".vault.microsoftazure.de\",\n azureDataLakeStoreFileSystemEndpointSuffix: \"N/A\",\n azureDataLakeAnalyticsCatalogAndJobEndpointSuffix: \"N/A\",\n validateAuthority: true\n };\n return Environment;\n }());\n\n exports.Environment = Environment;\n\n Object.defineProperty(exports, '__esModule', { value: true });\n\n})));\n//# sourceMappingURL=msRestAzureEnv.js.map\n","/** @license ms-rest-js\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt and ThirdPartyNotices.txt in the project root for license information.\n */\n'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nfunction _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }\n\nvar uuidv4 = _interopDefault(require('uuid/v4'));\nvar axios = _interopDefault(require('axios'));\nvar stream = require('stream');\nvar FormData = _interopDefault(require('form-data'));\nvar tough = require('tough-cookie');\nvar tunnel = require('tunnel');\nvar http = require('http');\nvar https = require('https');\nvar xml2js = require('xml2js');\nvar os = require('os');\nvar tslib = require('tslib');\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\n/**\n * A collection of HttpHeaders that can be sent with a HTTP request.\n */\nfunction getHeaderKey(headerName) {\n return headerName.toLowerCase();\n}\n/**\n * A collection of HTTP header key/value pairs.\n */\nvar HttpHeaders = /** @class */ (function () {\n function HttpHeaders(rawHeaders) {\n this._headersMap = {};\n if (rawHeaders) {\n for (var headerName in rawHeaders) {\n this.set(headerName, rawHeaders[headerName]);\n }\n }\n }\n /**\n * Set a header in this collection with the provided name and value. The name is\n * case-insensitive.\n * @param headerName The name of the header to set. This value is case-insensitive.\n * @param headerValue The value of the header to set.\n */\n HttpHeaders.prototype.set = function (headerName, headerValue) {\n this._headersMap[getHeaderKey(headerName)] = { name: headerName, value: headerValue.toString() };\n };\n /**\n * Get the header value for the provided header name, or undefined if no header exists in this\n * collection with the provided name.\n * @param headerName The name of the header.\n */\n HttpHeaders.prototype.get = function (headerName) {\n var header = this._headersMap[getHeaderKey(headerName)];\n return !header ? undefined : header.value;\n };\n /**\n * Get whether or not this header collection contains a header entry for the provided header name.\n */\n HttpHeaders.prototype.contains = function (headerName) {\n return !!this._headersMap[getHeaderKey(headerName)];\n };\n /**\n * Remove the header with the provided headerName. Return whether or not the header existed and\n * was removed.\n * @param headerName The name of the header to remove.\n */\n HttpHeaders.prototype.remove = function (headerName) {\n var result = this.contains(headerName);\n delete this._headersMap[getHeaderKey(headerName)];\n return result;\n };\n /**\n * Get the headers that are contained this collection as an object.\n */\n HttpHeaders.prototype.rawHeaders = function () {\n var result = {};\n for (var headerKey in this._headersMap) {\n var header = this._headersMap[headerKey];\n result[header.name.toLowerCase()] = header.value;\n }\n return result;\n };\n /**\n * Get the headers that are contained in this collection as an array.\n */\n HttpHeaders.prototype.headersArray = function () {\n var headers = [];\n for (var headerKey in this._headersMap) {\n headers.push(this._headersMap[headerKey]);\n }\n return headers;\n };\n /**\n * Get the header names that are contained in this collection.\n */\n HttpHeaders.prototype.headerNames = function () {\n var headerNames = [];\n var headers = this.headersArray();\n for (var i = 0; i < headers.length; ++i) {\n headerNames.push(headers[i].name);\n }\n return headerNames;\n };\n /**\n * Get the header names that are contained in this collection.\n */\n HttpHeaders.prototype.headerValues = function () {\n var headerValues = [];\n var headers = this.headersArray();\n for (var i = 0; i < headers.length; ++i) {\n headerValues.push(headers[i].value);\n }\n return headerValues;\n };\n /**\n * Get the JSON object representation of this HTTP header collection.\n */\n HttpHeaders.prototype.toJson = function () {\n return this.rawHeaders();\n };\n /**\n * Get the string representation of this HTTP header collection.\n */\n HttpHeaders.prototype.toString = function () {\n return JSON.stringify(this.toJson());\n };\n /**\n * Create a deep clone/copy of this HttpHeaders collection.\n */\n HttpHeaders.prototype.clone = function () {\n return new HttpHeaders(this.rawHeaders());\n };\n return HttpHeaders;\n}());\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\n/**\n * Encodes a string in base64 format.\n * @param value the string to encode\n */\nfunction encodeString(value) {\n return Buffer.from(value).toString(\"base64\");\n}\n/**\n * Encodes a byte array in base64 format.\n * @param value the Uint8Aray to encode\n */\nfunction encodeByteArray(value) {\n // Buffer.from accepts | -- the TypeScript definition is off here\n // https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length\n var bufferValue = (value instanceof Buffer) ? value : Buffer.from(value.buffer);\n return bufferValue.toString(\"base64\");\n}\n/**\n * Decodes a base64 string into a byte array.\n * @param value the base64 string to decode\n */\nfunction decodeString(value) {\n return Buffer.from(value, \"base64\");\n}\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\nvar Constants = {\n /**\n * The ms-rest version\n * @const\n * @type {string}\n */\n msRestVersion: \"1.11.2\",\n /**\n * Specifies HTTP.\n *\n * @const\n * @type {string}\n */\n HTTP: \"http:\",\n /**\n * Specifies HTTPS.\n *\n * @const\n * @type {string}\n */\n HTTPS: \"https:\",\n /**\n * Specifies HTTP Proxy.\n *\n * @const\n * @type {string}\n */\n HTTP_PROXY: \"HTTP_PROXY\",\n /**\n * Specifies HTTPS Proxy.\n *\n * @const\n * @type {string}\n */\n HTTPS_PROXY: \"HTTPS_PROXY\",\n HttpConstants: {\n /**\n * Http Verbs\n *\n * @const\n * @enum {string}\n */\n HttpVerbs: {\n PUT: \"PUT\",\n GET: \"GET\",\n DELETE: \"DELETE\",\n POST: \"POST\",\n MERGE: \"MERGE\",\n HEAD: \"HEAD\",\n PATCH: \"PATCH\"\n },\n StatusCodes: {\n TooManyRequests: 429\n }\n },\n /**\n * Defines constants for use with HTTP headers.\n */\n HeaderConstants: {\n /**\n * The Authorization header.\n *\n * @const\n * @type {string}\n */\n AUTHORIZATION: \"authorization\",\n AUTHORIZATION_SCHEME: \"Bearer\",\n /**\n * The Retry-After response-header field can be used with a 503 (Service\n * Unavailable) or 349 (Too Many Requests) responses to indicate how long\n * the service is expected to be unavailable to the requesting client.\n *\n * @const\n * @type {string}\n */\n RETRY_AFTER: \"Retry-After\",\n /**\n * The UserAgent header.\n *\n * @const\n * @type {string}\n */\n USER_AGENT: \"User-Agent\"\n }\n};\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n/**\n * A constant that indicates whether the environment is node.js or browser based.\n */\nvar isNode = (typeof process !== \"undefined\") && !!process.version && !!process.versions && !!process.versions.node;\n/**\n * Encodes an URI.\n *\n * @param {string} uri The URI to be encoded.\n * @return {string} The encoded URI.\n */\nfunction encodeUri(uri) {\n return encodeURIComponent(uri)\n .replace(/!/g, \"%21\")\n .replace(/\"/g, \"%27\")\n .replace(/\\(/g, \"%28\")\n .replace(/\\)/g, \"%29\")\n .replace(/\\*/g, \"%2A\");\n}\n/**\n * Returns a stripped version of the Http Response which only contains body,\n * headers and the status.\n *\n * @param {HttpOperationResponse} response The Http Response\n *\n * @return {object} The stripped version of Http Response.\n */\nfunction stripResponse(response) {\n var strippedResponse = {};\n strippedResponse.body = response.bodyAsText;\n strippedResponse.headers = response.headers;\n strippedResponse.status = response.status;\n return strippedResponse;\n}\n/**\n * Returns a stripped version of the Http Request that does not contain the\n * Authorization header.\n *\n * @param {WebResource} request The Http Request object\n *\n * @return {WebResource} The stripped version of Http Request.\n */\nfunction stripRequest(request) {\n var strippedRequest = request.clone();\n if (strippedRequest.headers) {\n strippedRequest.headers.remove(\"authorization\");\n }\n return strippedRequest;\n}\n/**\n * Validates the given uuid as a string\n *\n * @param {string} uuid The uuid as a string that needs to be validated\n *\n * @return {boolean} True if the uuid is valid; false otherwise.\n */\nfunction isValidUuid(uuid) {\n var validUuidRegex = new RegExp(\"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$\", \"ig\");\n return validUuidRegex.test(uuid);\n}\n/**\n * Generated UUID\n *\n * @return {string} RFC4122 v4 UUID.\n */\nfunction generateUuid() {\n return uuidv4();\n}\n/**\n * Executes an array of promises sequentially. Inspiration of this method is here:\n * https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html. An awesome blog on promises!\n *\n * @param {Array} promiseFactories An array of promise factories(A function that return a promise)\n *\n * @param {any} [kickstart] Input to the first promise that is used to kickstart the promise chain.\n * If not provided then the promise chain starts with undefined.\n *\n * @return A chain of resolved or rejected promises\n */\nfunction executePromisesSequentially(promiseFactories, kickstart) {\n var result = Promise.resolve(kickstart);\n promiseFactories.forEach(function (promiseFactory) {\n result = result.then(promiseFactory);\n });\n return result;\n}\n/**\n * A wrapper for setTimeout that resolves a promise after t milliseconds.\n * @param {number} t The number of milliseconds to be delayed.\n * @param {T} value The value to be resolved with after a timeout of t milliseconds.\n * @returns {Promise} Resolved promise\n */\nfunction delay(t, value) {\n return new Promise(function (resolve) { return setTimeout(function () { return resolve(value); }, t); });\n}\n/**\n * Converts a Promise to a callback.\n * @param {Promise} promise The Promise to be converted to a callback\n * @returns {Function} A function that takes the callback (cb: Function): void\n * @deprecated generated code should instead depend on responseToBody\n */\nfunction promiseToCallback(promise) {\n if (typeof promise.then !== \"function\") {\n throw new Error(\"The provided input is not a Promise.\");\n }\n return function (cb) {\n promise.then(function (data) {\n cb(undefined, data);\n }, function (err) {\n cb(err);\n });\n };\n}\n/**\n * Converts a Promise to a service callback.\n * @param {Promise} promise - The Promise of HttpOperationResponse to be converted to a service callback\n * @returns {Function} A function that takes the service callback (cb: ServiceCallback): void\n */\nfunction promiseToServiceCallback(promise) {\n if (typeof promise.then !== \"function\") {\n throw new Error(\"The provided input is not a Promise.\");\n }\n return function (cb) {\n promise.then(function (data) {\n process.nextTick(cb, undefined, data.parsedBody, data.request, data);\n }, function (err) {\n process.nextTick(cb, err);\n });\n };\n}\nfunction prepareXMLRootList(obj, elementName) {\n var _a;\n if (!Array.isArray(obj)) {\n obj = [obj];\n }\n return _a = {}, _a[elementName] = obj, _a;\n}\n/**\n * Applies the properties on the prototype of sourceCtors to the prototype of targetCtor\n * @param {object} targetCtor The target object on which the properties need to be applied.\n * @param {Array} sourceCtors An array of source objects from which the properties need to be taken.\n */\nfunction applyMixins(targetCtor, sourceCtors) {\n sourceCtors.forEach(function (sourceCtors) {\n Object.getOwnPropertyNames(sourceCtors.prototype).forEach(function (name) {\n targetCtor.prototype[name] = sourceCtors.prototype[name];\n });\n });\n}\nvar validateISODuration = /^(-|\\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;\n/**\n * Indicates whether the given string is in ISO 8601 format.\n * @param {string} value The value to be validated for ISO 8601 duration format.\n * @return {boolean} `true` if valid, `false` otherwise.\n */\nfunction isDuration(value) {\n return validateISODuration.test(value);\n}\n/**\n * Replace all of the instances of searchValue in value with the provided replaceValue.\n * @param {string | undefined} value The value to search and replace in.\n * @param {string} searchValue The value to search for in the value argument.\n * @param {string} replaceValue The value to replace searchValue with in the value argument.\n * @returns {string | undefined} The value where each instance of searchValue was replaced with replacedValue.\n */\nfunction replaceAll(value, searchValue, replaceValue) {\n return !value || !searchValue ? value : value.split(searchValue).join(replaceValue || \"\");\n}\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\nvar Serializer = /** @class */ (function () {\n function Serializer(modelMappers, isXML) {\n if (modelMappers === void 0) { modelMappers = {}; }\n this.modelMappers = modelMappers;\n this.isXML = isXML;\n }\n Serializer.prototype.validateConstraints = function (mapper, value, objectName) {\n var failValidation = function (constraintName, constraintValue) {\n throw new Error(\"\\\"\" + objectName + \"\\\" with value \\\"\" + value + \"\\\" should satisfy the constraint \\\"\" + constraintName + \"\\\": \" + constraintValue + \".\");\n };\n if (mapper.constraints && (value != undefined)) {\n var _a = mapper.constraints, ExclusiveMaximum = _a.ExclusiveMaximum, ExclusiveMinimum = _a.ExclusiveMinimum, InclusiveMaximum = _a.InclusiveMaximum, InclusiveMinimum = _a.InclusiveMinimum, MaxItems = _a.MaxItems, MaxLength = _a.MaxLength, MinItems = _a.MinItems, MinLength = _a.MinLength, MultipleOf = _a.MultipleOf, Pattern = _a.Pattern, UniqueItems = _a.UniqueItems;\n if (ExclusiveMaximum != undefined && value >= ExclusiveMaximum) {\n failValidation(\"ExclusiveMaximum\", ExclusiveMaximum);\n }\n if (ExclusiveMinimum != undefined && value <= ExclusiveMinimum) {\n failValidation(\"ExclusiveMinimum\", ExclusiveMinimum);\n }\n if (InclusiveMaximum != undefined && value > InclusiveMaximum) {\n failValidation(\"InclusiveMaximum\", InclusiveMaximum);\n }\n if (InclusiveMinimum != undefined && value < InclusiveMinimum) {\n failValidation(\"InclusiveMinimum\", InclusiveMinimum);\n }\n if (MaxItems != undefined && value.length > MaxItems) {\n failValidation(\"MaxItems\", MaxItems);\n }\n if (MaxLength != undefined && value.length > MaxLength) {\n failValidation(\"MaxLength\", MaxLength);\n }\n if (MinItems != undefined && value.length < MinItems) {\n failValidation(\"MinItems\", MinItems);\n }\n if (MinLength != undefined && value.length < MinLength) {\n failValidation(\"MinLength\", MinLength);\n }\n if (MultipleOf != undefined && value % MultipleOf !== 0) {\n failValidation(\"MultipleOf\", MultipleOf);\n }\n if (Pattern && value.match(Pattern) === null) {\n failValidation(\"Pattern\", Pattern);\n }\n if (UniqueItems && value.some(function (item, i, ar) { return ar.indexOf(item) !== i; })) {\n failValidation(\"UniqueItems\", UniqueItems);\n }\n }\n };\n /**\n * Serialize the given object based on its metadata defined in the mapper\n *\n * @param {Mapper} mapper The mapper which defines the metadata of the serializable object\n *\n * @param {object|string|Array|number|boolean|Date|stream} object A valid Javascript object to be serialized\n *\n * @param {string} objectName Name of the serialized object\n *\n * @returns {object|string|Array|number|boolean|Date|stream} A valid serialized Javascript object\n */\n Serializer.prototype.serialize = function (mapper, object, objectName) {\n var payload = {};\n var mapperType = mapper.type.name;\n if (!objectName) {\n objectName = mapper.serializedName;\n }\n if (mapperType.match(/^Sequence$/ig) !== null) {\n payload = [];\n }\n if (object == undefined && (mapper.defaultValue != undefined || mapper.isConstant)) {\n object = mapper.defaultValue;\n }\n // This table of allowed values should help explain\n // the mapper.required and mapper.nullable properties.\n // X means \"neither undefined or null are allowed\".\n // || required\n // || true | false\n // nullable || ==========================\n // true || null | undefined/null\n // false || X | undefined\n // undefined || X | undefined/null\n var required = mapper.required, nullable = mapper.nullable;\n if (required && nullable && object === undefined) {\n throw new Error(objectName + \" cannot be undefined.\");\n }\n if (required && !nullable && object == undefined) {\n throw new Error(objectName + \" cannot be null or undefined.\");\n }\n if (!required && nullable === false && object === null) {\n throw new Error(objectName + \" cannot be null.\");\n }\n if (object == undefined) {\n payload = object;\n }\n else {\n // Validate Constraints if any\n this.validateConstraints(mapper, object, objectName);\n if (mapperType.match(/^any$/ig) !== null) {\n payload = object;\n }\n else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/ig) !== null) {\n payload = serializeBasicTypes(mapperType, objectName, object);\n }\n else if (mapperType.match(/^Enum$/ig) !== null) {\n var enumMapper = mapper;\n payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object);\n }\n else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/ig) !== null) {\n payload = serializeDateTypes(mapperType, object, objectName);\n }\n else if (mapperType.match(/^ByteArray$/ig) !== null) {\n payload = serializeByteArrayType(objectName, object);\n }\n else if (mapperType.match(/^Base64Url$/ig) !== null) {\n payload = serializeBase64UrlType(objectName, object);\n }\n else if (mapperType.match(/^Sequence$/ig) !== null) {\n payload = serializeSequenceType(this, mapper, object, objectName);\n }\n else if (mapperType.match(/^Dictionary$/ig) !== null) {\n payload = serializeDictionaryType(this, mapper, object, objectName);\n }\n else if (mapperType.match(/^Composite$/ig) !== null) {\n payload = serializeCompositeType(this, mapper, object, objectName);\n }\n }\n return payload;\n };\n /**\n * Deserialize the given object based on its metadata defined in the mapper\n *\n * @param {object} mapper The mapper which defines the metadata of the serializable object\n *\n * @param {object|string|Array|number|boolean|Date|stream} responseBody A valid Javascript entity to be deserialized\n *\n * @param {string} objectName Name of the deserialized object\n *\n * @returns {object|string|Array|number|boolean|Date|stream} A valid deserialized Javascript object\n */\n Serializer.prototype.deserialize = function (mapper, responseBody, objectName) {\n if (responseBody == undefined) {\n if (this.isXML && mapper.type.name === \"Sequence\" && !mapper.xmlIsWrapped) {\n // Edge case for empty XML non-wrapped lists. xml2js can't distinguish\n // between the list being empty versus being missing,\n // so let's do the more user-friendly thing and return an empty list.\n responseBody = [];\n }\n return responseBody;\n }\n var payload;\n var mapperType = mapper.type.name;\n if (!objectName) {\n objectName = mapper.serializedName;\n }\n if (mapperType.match(/^Composite$/ig) !== null) {\n payload = deserializeCompositeType(this, mapper, responseBody, objectName);\n }\n else {\n if (this.isXML) {\n /**\n * If the mapper specifies this as a non-composite type value but the responseBody contains\n * both header (\"$\") and body (\"_\") properties, then just reduce the responseBody value to\n * the body (\"_\") property.\n */\n if (responseBody[\"$\"] != undefined && responseBody[\"_\"] != undefined) {\n responseBody = responseBody[\"_\"];\n }\n }\n if (mapperType.match(/^Number$/ig) !== null) {\n payload = parseFloat(responseBody);\n if (isNaN(payload)) {\n payload = responseBody;\n }\n }\n else if (mapperType.match(/^Boolean$/ig) !== null) {\n if (responseBody === \"true\") {\n payload = true;\n }\n else if (responseBody === \"false\") {\n payload = false;\n }\n else {\n payload = responseBody;\n }\n }\n else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/ig) !== null) {\n payload = responseBody;\n }\n else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/ig) !== null) {\n payload = new Date(responseBody);\n }\n else if (mapperType.match(/^UnixTime$/ig) !== null) {\n payload = unixTimeToDate(responseBody);\n }\n else if (mapperType.match(/^ByteArray$/ig) !== null) {\n payload = decodeString(responseBody);\n }\n else if (mapperType.match(/^Base64Url$/ig) !== null) {\n payload = base64UrlToByteArray(responseBody);\n }\n else if (mapperType.match(/^Sequence$/ig) !== null) {\n payload = deserializeSequenceType(this, mapper, responseBody, objectName);\n }\n else if (mapperType.match(/^Dictionary$/ig) !== null) {\n payload = deserializeDictionaryType(this, mapper, responseBody, objectName);\n }\n }\n if (mapper.isConstant) {\n payload = mapper.defaultValue;\n }\n return payload;\n };\n return Serializer;\n}());\nfunction trimEnd(str, ch) {\n var len = str.length;\n while ((len - 1) >= 0 && str[len - 1] === ch) {\n --len;\n }\n return str.substr(0, len);\n}\nfunction bufferToBase64Url(buffer) {\n if (!buffer) {\n return undefined;\n }\n if (!(buffer instanceof Uint8Array)) {\n throw new Error(\"Please provide an input of type Uint8Array for converting to Base64Url.\");\n }\n // Uint8Array to Base64.\n var str = encodeByteArray(buffer);\n // Base64 to Base64Url.\n return trimEnd(str, \"=\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n}\nfunction base64UrlToByteArray(str) {\n if (!str) {\n return undefined;\n }\n if (str && typeof str.valueOf() !== \"string\") {\n throw new Error(\"Please provide an input of type string for converting to Uint8Array\");\n }\n // Base64Url to Base64.\n str = str.replace(/\\-/g, \"+\").replace(/\\_/g, \"/\");\n // Base64 to Uint8Array.\n return decodeString(str);\n}\nfunction splitSerializeName(prop) {\n var classes = [];\n var partialclass = \"\";\n if (prop) {\n var subwords = prop.split(\".\");\n for (var _i = 0, subwords_1 = subwords; _i < subwords_1.length; _i++) {\n var item = subwords_1[_i];\n if (item.charAt(item.length - 1) === \"\\\\\") {\n partialclass += item.substr(0, item.length - 1) + \".\";\n }\n else {\n partialclass += item;\n classes.push(partialclass);\n partialclass = \"\";\n }\n }\n }\n return classes;\n}\nfunction dateToUnixTime(d) {\n if (!d) {\n return undefined;\n }\n if (typeof d.valueOf() === \"string\") {\n d = new Date(d);\n }\n return Math.floor(d.getTime() / 1000);\n}\nfunction unixTimeToDate(n) {\n if (!n) {\n return undefined;\n }\n return new Date(n * 1000);\n}\nfunction serializeBasicTypes(typeName, objectName, value) {\n if (value !== null && value !== undefined) {\n if (typeName.match(/^Number$/ig) !== null) {\n if (typeof value !== \"number\") {\n throw new Error(objectName + \" with value \" + value + \" must be of type number.\");\n }\n }\n else if (typeName.match(/^String$/ig) !== null) {\n if (typeof value.valueOf() !== \"string\") {\n throw new Error(objectName + \" with value \\\"\" + value + \"\\\" must be of type string.\");\n }\n }\n else if (typeName.match(/^Uuid$/ig) !== null) {\n if (!(typeof value.valueOf() === \"string\" && isValidUuid(value))) {\n throw new Error(objectName + \" with value \\\"\" + value + \"\\\" must be of type string and a valid uuid.\");\n }\n }\n else if (typeName.match(/^Boolean$/ig) !== null) {\n if (typeof value !== \"boolean\") {\n throw new Error(objectName + \" with value \" + value + \" must be of type boolean.\");\n }\n }\n else if (typeName.match(/^Stream$/ig) !== null) {\n var objectType = typeof value;\n if (objectType !== \"string\" &&\n objectType !== \"function\" &&\n !(value instanceof ArrayBuffer) &&\n !ArrayBuffer.isView(value) &&\n !(typeof Blob === \"function\" && value instanceof Blob)) {\n throw new Error(objectName + \" must be a string, Blob, ArrayBuffer, ArrayBufferView, or a function returning NodeJS.ReadableStream.\");\n }\n }\n }\n return value;\n}\nfunction serializeEnumType(objectName, allowedValues, value) {\n if (!allowedValues) {\n throw new Error(\"Please provide a set of allowedValues to validate \" + objectName + \" as an Enum Type.\");\n }\n var isPresent = allowedValues.some(function (item) {\n if (typeof item.valueOf() === \"string\") {\n return item.toLowerCase() === value.toLowerCase();\n }\n return item === value;\n });\n if (!isPresent) {\n throw new Error(value + \" is not a valid value for \" + objectName + \". The valid values are: \" + JSON.stringify(allowedValues) + \".\");\n }\n return value;\n}\nfunction serializeByteArrayType(objectName, value) {\n if (value != undefined) {\n if (!(value instanceof Uint8Array)) {\n throw new Error(objectName + \" must be of type Uint8Array.\");\n }\n value = encodeByteArray(value);\n }\n return value;\n}\nfunction serializeBase64UrlType(objectName, value) {\n if (value != undefined) {\n if (!(value instanceof Uint8Array)) {\n throw new Error(objectName + \" must be of type Uint8Array.\");\n }\n value = bufferToBase64Url(value);\n }\n return value;\n}\nfunction serializeDateTypes(typeName, value, objectName) {\n if (value != undefined) {\n if (typeName.match(/^Date$/ig) !== null) {\n if (!(value instanceof Date ||\n (typeof value.valueOf() === \"string\" && !isNaN(Date.parse(value))))) {\n throw new Error(objectName + \" must be an instanceof Date or a string in ISO8601 format.\");\n }\n value = (value instanceof Date) ? value.toISOString().substring(0, 10) : new Date(value).toISOString().substring(0, 10);\n }\n else if (typeName.match(/^DateTime$/ig) !== null) {\n if (!(value instanceof Date ||\n (typeof value.valueOf() === \"string\" && !isNaN(Date.parse(value))))) {\n throw new Error(objectName + \" must be an instanceof Date or a string in ISO8601 format.\");\n }\n value = (value instanceof Date) ? value.toISOString() : new Date(value).toISOString();\n }\n else if (typeName.match(/^DateTimeRfc1123$/ig) !== null) {\n if (!(value instanceof Date ||\n (typeof value.valueOf() === \"string\" && !isNaN(Date.parse(value))))) {\n throw new Error(objectName + \" must be an instanceof Date or a string in RFC-1123 format.\");\n }\n value = (value instanceof Date) ? value.toUTCString() : new Date(value).toUTCString();\n }\n else if (typeName.match(/^UnixTime$/ig) !== null) {\n if (!(value instanceof Date ||\n (typeof value.valueOf() === \"string\" && !isNaN(Date.parse(value))))) {\n throw new Error(objectName + \" must be an instanceof Date or a string in RFC-1123/ISO8601 format \" +\n \"for it to be serialized in UnixTime/Epoch format.\");\n }\n value = dateToUnixTime(value);\n }\n else if (typeName.match(/^TimeSpan$/ig) !== null) {\n if (!isDuration(value)) {\n throw new Error(objectName + \" must be a string in ISO 8601 format. Instead was \\\"\" + value + \"\\\".\");\n }\n value = value;\n }\n }\n return value;\n}\nfunction serializeSequenceType(serializer, mapper, object, objectName) {\n if (!Array.isArray(object)) {\n throw new Error(objectName + \" must be of type Array.\");\n }\n var elementType = mapper.type.element;\n if (!elementType || typeof elementType !== \"object\") {\n throw new Error(\"element\\\" metadata for an Array must be defined in the \" +\n (\"mapper and it must of type \\\"object\\\" in \" + objectName + \".\"));\n }\n var tempArray = [];\n for (var i = 0; i < object.length; i++) {\n tempArray[i] = serializer.serialize(elementType, object[i], objectName);\n }\n return tempArray;\n}\nfunction serializeDictionaryType(serializer, mapper, object, objectName) {\n if (typeof object !== \"object\") {\n throw new Error(objectName + \" must be of type object.\");\n }\n var valueType = mapper.type.value;\n if (!valueType || typeof valueType !== \"object\") {\n throw new Error(\"\\\"value\\\" metadata for a Dictionary must be defined in the \" +\n (\"mapper and it must of type \\\"object\\\" in \" + objectName + \".\"));\n }\n var tempDictionary = {};\n for (var _i = 0, _a = Object.keys(object); _i < _a.length; _i++) {\n var key = _a[_i];\n tempDictionary[key] = serializer.serialize(valueType, object[key], objectName + \".\" + key);\n }\n return tempDictionary;\n}\n/**\n * Resolves a composite mapper's modelProperties.\n * @param serializer the serializer containing the entire set of mappers\n * @param mapper the composite mapper to resolve\n */\nfunction resolveModelProperties(serializer, mapper, objectName) {\n var modelProps = mapper.type.modelProperties;\n if (!modelProps) {\n var className = mapper.type.className;\n if (!className) {\n throw new Error(\"Class name for model \\\"\" + objectName + \"\\\" is not provided in the mapper \\\"\" + JSON.stringify(mapper, undefined, 2) + \"\\\".\");\n }\n var modelMapper = serializer.modelMappers[className];\n if (!modelMapper) {\n throw new Error(\"mapper() cannot be null or undefined for model \\\"\" + className + \"\\\".\");\n }\n modelProps = modelMapper.type.modelProperties;\n if (!modelProps) {\n throw new Error(\"modelProperties cannot be null or undefined in the \" +\n (\"mapper \\\"\" + JSON.stringify(modelMapper) + \"\\\" of type \\\"\" + className + \"\\\" for object \\\"\" + objectName + \"\\\".\"));\n }\n }\n return modelProps;\n}\nfunction serializeCompositeType(serializer, mapper, object, objectName) {\n var _a;\n if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {\n mapper = getPolymorphicMapper(serializer, mapper, object, \"clientName\");\n }\n if (object != undefined) {\n var payload = {};\n var modelProps = resolveModelProperties(serializer, mapper, objectName);\n for (var _i = 0, _b = Object.keys(modelProps); _i < _b.length; _i++) {\n var key = _b[_i];\n var propertyMapper = modelProps[key];\n if (propertyMapper.readOnly) {\n continue;\n }\n var propName = void 0;\n var parentObject = payload;\n if (serializer.isXML) {\n if (propertyMapper.xmlIsWrapped) {\n propName = propertyMapper.xmlName;\n }\n else {\n propName = propertyMapper.xmlElementName || propertyMapper.xmlName;\n }\n }\n else {\n var paths = splitSerializeName(propertyMapper.serializedName);\n propName = paths.pop();\n for (var _c = 0, paths_1 = paths; _c < paths_1.length; _c++) {\n var pathName = paths_1[_c];\n var childObject = parentObject[pathName];\n if ((childObject == undefined) && (object[key] != undefined)) {\n parentObject[pathName] = {};\n }\n parentObject = parentObject[pathName];\n }\n }\n if (parentObject != undefined) {\n var propertyObjectName = propertyMapper.serializedName !== \"\"\n ? objectName + \".\" + propertyMapper.serializedName\n : objectName;\n var toSerialize = object[key];\n var polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);\n if (polymorphicDiscriminator && polymorphicDiscriminator.clientName === key && toSerialize == undefined) {\n toSerialize = mapper.serializedName;\n }\n var serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName);\n if (serializedValue !== undefined && propName != undefined) {\n if (propertyMapper.xmlIsAttribute) {\n // $ is the key attributes are kept under in xml2js.\n // This keeps things simple while preventing name collision\n // with names in user documents.\n parentObject.$ = parentObject.$ || {};\n parentObject.$[propName] = serializedValue;\n }\n else if (propertyMapper.xmlIsWrapped) {\n parentObject[propName] = (_a = {}, _a[propertyMapper.xmlElementName] = serializedValue, _a);\n }\n else {\n parentObject[propName] = serializedValue;\n }\n }\n }\n }\n var additionalPropertiesMapper = mapper.type.additionalProperties;\n if (additionalPropertiesMapper) {\n var propNames = Object.keys(modelProps);\n var _loop_1 = function (clientPropName) {\n var isAdditionalProperty = propNames.every(function (pn) { return pn !== clientPropName; });\n if (isAdditionalProperty) {\n payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '[\"' + clientPropName + '\"]');\n }\n };\n for (var clientPropName in object) {\n _loop_1(clientPropName);\n }\n }\n return payload;\n }\n return object;\n}\nfunction isSpecialXmlProperty(propertyName) {\n return [\"$\", \"_\"].includes(propertyName);\n}\nfunction deserializeCompositeType(serializer, mapper, responseBody, objectName) {\n if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {\n mapper = getPolymorphicMapper(serializer, mapper, responseBody, \"serializedName\");\n }\n var modelProps = resolveModelProperties(serializer, mapper, objectName);\n var instance = {};\n var handledPropertyNames = [];\n for (var _i = 0, _a = Object.keys(modelProps); _i < _a.length; _i++) {\n var key = _a[_i];\n var propertyMapper = modelProps[key];\n var paths = splitSerializeName(modelProps[key].serializedName);\n handledPropertyNames.push(paths[0]);\n var serializedName = propertyMapper.serializedName, xmlName = propertyMapper.xmlName, xmlElementName = propertyMapper.xmlElementName;\n var propertyObjectName = objectName;\n if (serializedName !== \"\" && serializedName !== undefined) {\n propertyObjectName = objectName + \".\" + serializedName;\n }\n var headerCollectionPrefix = propertyMapper.headerCollectionPrefix;\n if (headerCollectionPrefix) {\n var dictionary = {};\n for (var _b = 0, _c = Object.keys(responseBody); _b < _c.length; _b++) {\n var headerKey = _c[_b];\n if (headerKey.startsWith(headerCollectionPrefix)) {\n dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName);\n }\n handledPropertyNames.push(headerKey);\n }\n instance[key] = dictionary;\n }\n else if (serializer.isXML) {\n if (propertyMapper.xmlIsAttribute && responseBody.$) {\n instance[key] = serializer.deserialize(propertyMapper, responseBody.$[xmlName], propertyObjectName);\n }\n else {\n var propertyName = xmlElementName || xmlName || serializedName;\n var unwrappedProperty = responseBody[propertyName];\n if (propertyMapper.xmlIsWrapped) {\n unwrappedProperty = responseBody[xmlName];\n unwrappedProperty = unwrappedProperty && unwrappedProperty[xmlElementName];\n var isEmptyWrappedList = unwrappedProperty === undefined;\n if (isEmptyWrappedList) {\n unwrappedProperty = [];\n }\n }\n instance[key] = serializer.deserialize(propertyMapper, unwrappedProperty, propertyObjectName);\n }\n }\n else {\n // deserialize the property if it is present in the provided responseBody instance\n var propertyInstance = void 0;\n var res = responseBody;\n // traversing the object step by step.\n for (var _d = 0, paths_2 = paths; _d < paths_2.length; _d++) {\n var item = paths_2[_d];\n if (!res)\n break;\n res = res[item];\n }\n propertyInstance = res;\n var polymorphicDiscriminator = mapper.type.polymorphicDiscriminator;\n if (polymorphicDiscriminator && propertyMapper.serializedName === polymorphicDiscriminator.serializedName && propertyInstance == undefined) {\n propertyInstance = mapper.serializedName;\n }\n var serializedValue = void 0;\n // paging\n if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === \"\") {\n propertyInstance = responseBody[key];\n instance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName);\n }\n else if (propertyInstance !== undefined) {\n serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName);\n instance[key] = serializedValue;\n }\n }\n }\n var additionalPropertiesMapper = mapper.type.additionalProperties;\n if (additionalPropertiesMapper) {\n var isAdditionalProperty = function (responsePropName) {\n for (var clientPropName in modelProps) {\n var paths = splitSerializeName(modelProps[clientPropName].serializedName);\n if (paths[0] === responsePropName) {\n return false;\n }\n }\n return true;\n };\n for (var responsePropName in responseBody) {\n if (isAdditionalProperty(responsePropName)) {\n instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '[\"' + responsePropName + '\"]');\n }\n }\n }\n else if (responseBody) {\n for (var _e = 0, _f = Object.keys(responseBody); _e < _f.length; _e++) {\n var key = _f[_e];\n if (instance[key] === undefined && !handledPropertyNames.includes(key) && !isSpecialXmlProperty(key)) {\n instance[key] = responseBody[key];\n }\n }\n }\n return instance;\n}\nfunction deserializeDictionaryType(serializer, mapper, responseBody, objectName) {\n /*jshint validthis: true */\n var value = mapper.type.value;\n if (!value || typeof value !== \"object\") {\n throw new Error(\"\\\"value\\\" metadata for a Dictionary must be defined in the \" +\n (\"mapper and it must of type \\\"object\\\" in \" + objectName));\n }\n if (responseBody) {\n var tempDictionary = {};\n for (var _i = 0, _a = Object.keys(responseBody); _i < _a.length; _i++) {\n var key = _a[_i];\n tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName);\n }\n return tempDictionary;\n }\n return responseBody;\n}\nfunction deserializeSequenceType(serializer, mapper, responseBody, objectName) {\n /*jshint validthis: true */\n var element = mapper.type.element;\n if (!element || typeof element !== \"object\") {\n throw new Error(\"element\\\" metadata for an Array must be defined in the \" +\n (\"mapper and it must of type \\\"object\\\" in \" + objectName));\n }\n if (responseBody) {\n if (!Array.isArray(responseBody)) {\n // xml2js will interpret a single element array as just the element, so force it to be an array\n responseBody = [responseBody];\n }\n var tempArray = [];\n for (var i = 0; i < responseBody.length; i++) {\n tempArray[i] = serializer.deserialize(element, responseBody[i], objectName + \"[\" + i + \"]\");\n }\n return tempArray;\n }\n return responseBody;\n}\nfunction getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) {\n var polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);\n if (polymorphicDiscriminator) {\n var discriminatorName = polymorphicDiscriminator[polymorphicPropertyName];\n if (discriminatorName != undefined) {\n var discriminatorValue = object[discriminatorName];\n if (discriminatorValue != undefined) {\n var typeName = mapper.type.uberParent || mapper.type.className;\n var indexDiscriminator = discriminatorValue === typeName\n ? discriminatorValue\n : typeName + \".\" + discriminatorValue;\n var polymorphicMapper = serializer.modelMappers.discriminators[indexDiscriminator];\n if (polymorphicMapper) {\n mapper = polymorphicMapper;\n }\n }\n }\n }\n return mapper;\n}\nfunction getPolymorphicDiscriminatorRecursively(serializer, mapper) {\n return mapper.type.polymorphicDiscriminator\n || getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent)\n || getPolymorphicDiscriminatorSafely(serializer, mapper.type.className);\n}\nfunction getPolymorphicDiscriminatorSafely(serializer, typeName) {\n return (typeName && serializer.modelMappers[typeName] && serializer.modelMappers[typeName].type.polymorphicDiscriminator);\n}\n// TODO: why is this here?\nfunction serializeObject(toSerialize) {\n if (toSerialize == undefined)\n return undefined;\n if (toSerialize instanceof Uint8Array) {\n toSerialize = encodeByteArray(toSerialize);\n return toSerialize;\n }\n else if (toSerialize instanceof Date) {\n return toSerialize.toISOString();\n }\n else if (Array.isArray(toSerialize)) {\n var array = [];\n for (var i = 0; i < toSerialize.length; i++) {\n array.push(serializeObject(toSerialize[i]));\n }\n return array;\n }\n else if (typeof toSerialize === \"object\") {\n var dictionary = {};\n for (var property in toSerialize) {\n dictionary[property] = serializeObject(toSerialize[property]);\n }\n return dictionary;\n }\n return toSerialize;\n}\n/**\n * Utility function to create a K:V from a list of strings\n */\nfunction strEnum(o) {\n var result = {};\n for (var _i = 0, o_1 = o; _i < o_1.length; _i++) {\n var key = o_1[_i];\n result[key] = key;\n }\n return result;\n}\nvar MapperType = strEnum([\n \"Base64Url\",\n \"Boolean\",\n \"ByteArray\",\n \"Composite\",\n \"Date\",\n \"DateTime\",\n \"DateTimeRfc1123\",\n \"Dictionary\",\n \"Enum\",\n \"Number\",\n \"Object\",\n \"Sequence\",\n \"String\",\n \"Stream\",\n \"TimeSpan\",\n \"UnixTime\"\n]);\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n/**\n * Creates a new WebResource object.\n *\n * This class provides an abstraction over a REST call by being library / implementation agnostic and wrapping the necessary\n * properties to initiate a request.\n *\n * @constructor\n */\nvar WebResource = /** @class */ (function () {\n function WebResource(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, agentSettings) {\n this.streamResponseBody = streamResponseBody;\n this.url = url || \"\";\n this.method = method || \"GET\";\n this.headers = (headers instanceof HttpHeaders ? headers : new HttpHeaders(headers));\n this.body = body;\n this.query = query;\n this.formData = undefined;\n this.withCredentials = withCredentials || false;\n this.abortSignal = abortSignal;\n this.timeout = timeout || 0;\n this.onUploadProgress = onUploadProgress;\n this.onDownloadProgress = onDownloadProgress;\n this.proxySettings = proxySettings;\n this.keepAlive = keepAlive;\n this.agentSettings = agentSettings;\n }\n /**\n * Validates that the required properties such as method, url, headers[\"Content-Type\"],\n * headers[\"accept-language\"] are defined. It will throw an error if one of the above\n * mentioned properties are not defined.\n */\n WebResource.prototype.validateRequestProperties = function () {\n if (!this.method) {\n throw new Error(\"WebResource.method is required.\");\n }\n if (!this.url) {\n throw new Error(\"WebResource.url is required.\");\n }\n };\n /**\n * Prepares the request.\n * @param {RequestPrepareOptions} options Options to provide for preparing the request.\n * @returns {WebResource} Returns the prepared WebResource (HTTP Request) object that needs to be given to the request pipeline.\n */\n WebResource.prototype.prepare = function (options) {\n if (!options) {\n throw new Error(\"options object is required\");\n }\n if (options.method == undefined || typeof options.method.valueOf() !== \"string\") {\n throw new Error(\"options.method must be a string.\");\n }\n if (options.url && options.pathTemplate) {\n throw new Error(\"options.url and options.pathTemplate are mutually exclusive. Please provide exactly one of them.\");\n }\n if ((options.pathTemplate == undefined || typeof options.pathTemplate.valueOf() !== \"string\") && (options.url == undefined || typeof options.url.valueOf() !== \"string\")) {\n throw new Error(\"Please provide exactly one of options.pathTemplate or options.url.\");\n }\n // set the url if it is provided.\n if (options.url) {\n if (typeof options.url !== \"string\") {\n throw new Error(\"options.url must be of type \\\"string\\\".\");\n }\n this.url = options.url;\n }\n // set the method\n if (options.method) {\n var validMethods = [\"GET\", \"PUT\", \"HEAD\", \"DELETE\", \"OPTIONS\", \"POST\", \"PATCH\", \"TRACE\"];\n if (validMethods.indexOf(options.method.toUpperCase()) === -1) {\n throw new Error(\"The provided method \\\"\" + options.method + \"\\\" is invalid. Supported HTTP methods are: \" + JSON.stringify(validMethods));\n }\n }\n this.method = options.method.toUpperCase();\n // construct the url if path template is provided\n if (options.pathTemplate) {\n var pathTemplate_1 = options.pathTemplate, pathParameters_1 = options.pathParameters;\n if (typeof pathTemplate_1 !== \"string\") {\n throw new Error(\"options.pathTemplate must be of type \\\"string\\\".\");\n }\n if (!options.baseUrl) {\n options.baseUrl = \"https://management.azure.com\";\n }\n var baseUrl = options.baseUrl;\n var url_1 = baseUrl + (baseUrl.endsWith(\"/\") ? \"\" : \"/\") + (pathTemplate_1.startsWith(\"/\") ? pathTemplate_1.slice(1) : pathTemplate_1);\n var segments = url_1.match(/({\\w*\\s*\\w*})/ig);\n if (segments && segments.length) {\n if (!pathParameters_1) {\n throw new Error(\"pathTemplate: \" + pathTemplate_1 + \" has been provided. Hence, options.pathParameters must also be provided.\");\n }\n segments.forEach(function (item) {\n var pathParamName = item.slice(1, -1);\n var pathParam = pathParameters_1[pathParamName];\n if (pathParam === null || pathParam === undefined || !(typeof pathParam === \"string\" || typeof pathParam === \"object\")) {\n throw new Error(\"pathTemplate: \" + pathTemplate_1 + \" contains the path parameter \" + pathParamName +\n (\" however, it is not present in \" + pathParameters_1 + \" - \" + JSON.stringify(pathParameters_1, undefined, 2) + \".\") +\n (\"The value of the path parameter can either be a \\\"string\\\" of the form { \" + pathParamName + \": \\\"some sample value\\\" } or \") +\n (\"it can be an \\\"object\\\" of the form { \\\"\" + pathParamName + \"\\\": { value: \\\"some sample value\\\", skipUrlEncoding: true } }.\"));\n }\n if (typeof pathParam.valueOf() === \"string\") {\n url_1 = url_1.replace(item, encodeURIComponent(pathParam));\n }\n if (typeof pathParam.valueOf() === \"object\") {\n if (!pathParam.value) {\n throw new Error(\"options.pathParameters[\" + pathParamName + \"] is of type \\\"object\\\" but it does not contain a \\\"value\\\" property.\");\n }\n if (pathParam.skipUrlEncoding) {\n url_1 = url_1.replace(item, pathParam.value);\n }\n else {\n url_1 = url_1.replace(item, encodeURIComponent(pathParam.value));\n }\n }\n });\n }\n this.url = url_1;\n }\n // append query parameters to the url if they are provided. They can be provided with pathTemplate or url option.\n if (options.queryParameters) {\n var queryParameters = options.queryParameters;\n if (typeof queryParameters !== \"object\") {\n throw new Error(\"options.queryParameters must be of type object. It should be a JSON object \" +\n \"of \\\"query-parameter-name\\\" as the key and the \\\"query-parameter-value\\\" as the value. \" +\n \"The \\\"query-parameter-value\\\" may be fo type \\\"string\\\" or an \\\"object\\\" of the form { value: \\\"query-parameter-value\\\", skipUrlEncoding: true }.\");\n }\n // append question mark if it is not present in the url\n if (this.url && this.url.indexOf(\"?\") === -1) {\n this.url += \"?\";\n }\n // construct queryString\n var queryParams = [];\n // We need to populate this.query as a dictionary if the request is being used for Sway's validateRequest().\n this.query = {};\n for (var queryParamName in queryParameters) {\n var queryParam = queryParameters[queryParamName];\n if (queryParam) {\n if (typeof queryParam === \"string\") {\n queryParams.push(queryParamName + \"=\" + encodeURIComponent(queryParam));\n this.query[queryParamName] = encodeURIComponent(queryParam);\n }\n else if (typeof queryParam === \"object\") {\n if (!queryParam.value) {\n throw new Error(\"options.queryParameters[\" + queryParamName + \"] is of type \\\"object\\\" but it does not contain a \\\"value\\\" property.\");\n }\n if (queryParam.skipUrlEncoding) {\n queryParams.push(queryParamName + \"=\" + queryParam.value);\n this.query[queryParamName] = queryParam.value;\n }\n else {\n queryParams.push(queryParamName + \"=\" + encodeURIComponent(queryParam.value));\n this.query[queryParamName] = encodeURIComponent(queryParam.value);\n }\n }\n }\n } // end-of-for\n // append the queryString\n this.url += queryParams.join(\"&\");\n }\n // add headers to the request if they are provided\n if (options.headers) {\n var headers = options.headers;\n for (var _i = 0, _a = Object.keys(options.headers); _i < _a.length; _i++) {\n var headerName = _a[_i];\n this.headers.set(headerName, headers[headerName]);\n }\n }\n // ensure accept-language is set correctly\n if (!this.headers.get(\"accept-language\")) {\n this.headers.set(\"accept-language\", \"en-US\");\n }\n // ensure the request-id is set correctly\n if (!this.headers.get(\"x-ms-client-request-id\") && !options.disableClientRequestId) {\n this.headers.set(\"x-ms-client-request-id\", generateUuid());\n }\n // default\n if (!this.headers.get(\"Content-Type\")) {\n this.headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n }\n // set the request body. request.js automatically sets the Content-Length request header, so we need not set it explicilty\n this.body = options.body;\n if (options.body != undefined) {\n // body as a stream special case. set the body as-is and check for some special request headers specific to sending a stream.\n if (options.bodyIsStream) {\n if (!this.headers.get(\"Transfer-Encoding\")) {\n this.headers.set(\"Transfer-Encoding\", \"chunked\");\n }\n if (this.headers.get(\"Content-Type\") !== \"application/octet-stream\") {\n this.headers.set(\"Content-Type\", \"application/octet-stream\");\n }\n }\n else {\n if (options.serializationMapper) {\n this.body = new Serializer(options.mappers).serialize(options.serializationMapper, options.body, \"requestBody\");\n }\n if (!options.disableJsonStringifyOnBody) {\n this.body = JSON.stringify(options.body);\n }\n }\n }\n this.abortSignal = options.abortSignal;\n this.onDownloadProgress = options.onDownloadProgress;\n this.onUploadProgress = options.onUploadProgress;\n return this;\n };\n /**\n * Clone this WebResource HTTP request object.\n * @returns {WebResource} The clone of this WebResource HTTP request object.\n */\n WebResource.prototype.clone = function () {\n var result = new WebResource(this.url, this.method, this.body, this.query, this.headers && this.headers.clone(), this.streamResponseBody, this.withCredentials, this.abortSignal, this.timeout, this.onUploadProgress, this.onDownloadProgress, this.proxySettings, this.keepAlive, this.agentSettings);\n if (this.formData) {\n result.formData = this.formData;\n }\n if (this.operationSpec) {\n result.operationSpec = this.operationSpec;\n }\n if (this.shouldDeserialize) {\n result.shouldDeserialize = this.shouldDeserialize;\n }\n if (this.operationResponseGetter) {\n result.operationResponseGetter = this.operationResponseGetter;\n }\n return result;\n };\n return WebResource;\n}());\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\nvar RestError = /** @class */ (function (_super) {\n tslib.__extends(RestError, _super);\n function RestError(message, code, statusCode, request, response, body) {\n var _this = _super.call(this, message) || this;\n _this.code = code;\n _this.statusCode = statusCode;\n _this.request = request;\n _this.response = response;\n _this.body = body;\n Object.setPrototypeOf(_this, RestError.prototype);\n return _this;\n }\n RestError.REQUEST_SEND_ERROR = \"REQUEST_SEND_ERROR\";\n RestError.REQUEST_ABORTED_ERROR = \"REQUEST_ABORTED_ERROR\";\n RestError.PARSE_ERROR = \"PARSE_ERROR\";\n return RestError;\n}(Error));\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n/**\n * A class that handles the query portion of a URLBuilder.\n */\nvar URLQuery = /** @class */ (function () {\n function URLQuery() {\n this._rawQuery = {};\n }\n /**\n * Get whether or not there any query parameters in this URLQuery.\n */\n URLQuery.prototype.any = function () {\n return Object.keys(this._rawQuery).length > 0;\n };\n /**\n * Set a query parameter with the provided name and value. If the parameterValue is undefined or\n * empty, then this will attempt to remove an existing query parameter with the provided\n * parameterName.\n */\n URLQuery.prototype.set = function (parameterName, parameterValue) {\n if (parameterName) {\n if (parameterValue != undefined) {\n var newValue = Array.isArray(parameterValue) ? parameterValue : parameterValue.toString();\n this._rawQuery[parameterName] = newValue;\n }\n else {\n delete this._rawQuery[parameterName];\n }\n }\n };\n /**\n * Get the value of the query parameter with the provided name. If no parameter exists with the\n * provided parameter name, then undefined will be returned.\n */\n URLQuery.prototype.get = function (parameterName) {\n return parameterName ? this._rawQuery[parameterName] : undefined;\n };\n /**\n * Get the string representation of this query. The return value will not start with a \"?\".\n */\n URLQuery.prototype.toString = function () {\n var result = \"\";\n for (var parameterName in this._rawQuery) {\n if (result) {\n result += \"&\";\n }\n var parameterValue = this._rawQuery[parameterName];\n if (Array.isArray(parameterValue)) {\n var parameterStrings = [];\n for (var _i = 0, parameterValue_1 = parameterValue; _i < parameterValue_1.length; _i++) {\n var parameterValueElement = parameterValue_1[_i];\n parameterStrings.push(parameterName + \"=\" + parameterValueElement);\n }\n result += parameterStrings.join(\"&\");\n }\n else {\n result += parameterName + \"=\" + parameterValue;\n }\n }\n return result;\n };\n /**\n * Parse a URLQuery from the provided text.\n */\n URLQuery.parse = function (text) {\n var result = new URLQuery();\n if (text) {\n if (text.startsWith(\"?\")) {\n text = text.substring(1);\n }\n var currentState = \"ParameterName\";\n var parameterName = \"\";\n var parameterValue = \"\";\n for (var i = 0; i < text.length; ++i) {\n var currentCharacter = text[i];\n switch (currentState) {\n case \"ParameterName\":\n switch (currentCharacter) {\n case \"=\":\n currentState = \"ParameterValue\";\n break;\n case \"&\":\n parameterName = \"\";\n parameterValue = \"\";\n break;\n default:\n parameterName += currentCharacter;\n break;\n }\n break;\n case \"ParameterValue\":\n switch (currentCharacter) {\n case \"=\":\n parameterName = \"\";\n parameterValue = \"\";\n currentState = \"Invalid\";\n break;\n case \"&\":\n result.set(parameterName, parameterValue);\n parameterName = \"\";\n parameterValue = \"\";\n currentState = \"ParameterName\";\n break;\n default:\n parameterValue += currentCharacter;\n break;\n }\n break;\n case \"Invalid\":\n if (currentCharacter === \"&\") {\n currentState = \"ParameterName\";\n }\n break;\n default:\n throw new Error(\"Unrecognized URLQuery parse state: \" + currentState);\n }\n }\n if (currentState === \"ParameterValue\") {\n result.set(parameterName, parameterValue);\n }\n }\n return result;\n };\n return URLQuery;\n}());\n/**\n * A class that handles creating, modifying, and parsing URLs.\n */\nvar URLBuilder = /** @class */ (function () {\n function URLBuilder() {\n }\n /**\n * Set the scheme/protocol for this URL. If the provided scheme contains other parts of a URL\n * (such as a host, port, path, or query), those parts will be added to this URL as well.\n */\n URLBuilder.prototype.setScheme = function (scheme) {\n if (!scheme) {\n this._scheme = undefined;\n }\n else {\n this.set(scheme, \"SCHEME\");\n }\n };\n /**\n * Get the scheme that has been set in this URL.\n */\n URLBuilder.prototype.getScheme = function () {\n return this._scheme;\n };\n /**\n * Set the host for this URL. If the provided host contains other parts of a URL (such as a\n * port, path, or query), those parts will be added to this URL as well.\n */\n URLBuilder.prototype.setHost = function (host) {\n if (!host) {\n this._host = undefined;\n }\n else {\n this.set(host, \"SCHEME_OR_HOST\");\n }\n };\n /**\n * Get the host that has been set in this URL.\n */\n URLBuilder.prototype.getHost = function () {\n return this._host;\n };\n /**\n * Set the port for this URL. If the provided port contains other parts of a URL (such as a\n * path or query), those parts will be added to this URL as well.\n */\n URLBuilder.prototype.setPort = function (port) {\n if (port == undefined || port === \"\") {\n this._port = undefined;\n }\n else {\n this.set(port.toString(), \"PORT\");\n }\n };\n /**\n * Get the port that has been set in this URL.\n */\n URLBuilder.prototype.getPort = function () {\n return this._port;\n };\n /**\n * Set the path for this URL. If the provided path contains a query, then it will be added to\n * this URL as well.\n */\n URLBuilder.prototype.setPath = function (path) {\n if (!path) {\n this._path = undefined;\n }\n else {\n if (path.indexOf(\"://\") !== -1) {\n this.set(path, \"SCHEME\");\n }\n else {\n this.set(path, \"PATH\");\n }\n }\n };\n /**\n * Append the provided path to this URL's existing path. If the provided path contains a query,\n * then it will be added to this URL as well.\n */\n URLBuilder.prototype.appendPath = function (path) {\n if (path) {\n var currentPath = this.getPath();\n if (currentPath) {\n if (!currentPath.endsWith(\"/\")) {\n currentPath += \"/\";\n }\n if (path.startsWith(\"/\")) {\n path = path.substring(1);\n }\n path = currentPath + path;\n }\n this.set(path, \"PATH\");\n }\n };\n /**\n * Get the path that has been set in this URL.\n */\n URLBuilder.prototype.getPath = function () {\n return this._path;\n };\n /**\n * Set the query in this URL.\n */\n URLBuilder.prototype.setQuery = function (query) {\n if (!query) {\n this._query = undefined;\n }\n else {\n this._query = URLQuery.parse(query);\n }\n };\n /**\n * Set a query parameter with the provided name and value in this URL's query. If the provided\n * query parameter value is undefined or empty, then the query parameter will be removed if it\n * existed.\n */\n URLBuilder.prototype.setQueryParameter = function (queryParameterName, queryParameterValue) {\n if (queryParameterName) {\n if (!this._query) {\n this._query = new URLQuery();\n }\n this._query.set(queryParameterName, queryParameterValue);\n }\n };\n /**\n * Get the value of the query parameter with the provided query parameter name. If no query\n * parameter exists with the provided name, then undefined will be returned.\n */\n URLBuilder.prototype.getQueryParameterValue = function (queryParameterName) {\n return this._query ? this._query.get(queryParameterName) : undefined;\n };\n /**\n * Get the query in this URL.\n */\n URLBuilder.prototype.getQuery = function () {\n return this._query ? this._query.toString() : undefined;\n };\n /**\n * Set the parts of this URL by parsing the provided text using the provided startState.\n */\n URLBuilder.prototype.set = function (text, startState) {\n var tokenizer = new URLTokenizer(text, startState);\n while (tokenizer.next()) {\n var token = tokenizer.current();\n if (token) {\n switch (token.type) {\n case \"SCHEME\":\n this._scheme = token.text || undefined;\n break;\n case \"HOST\":\n this._host = token.text || undefined;\n break;\n case \"PORT\":\n this._port = token.text || undefined;\n break;\n case \"PATH\":\n var tokenPath = token.text || undefined;\n if (!this._path || this._path === \"/\" || tokenPath !== \"/\") {\n this._path = tokenPath;\n }\n break;\n case \"QUERY\":\n this._query = URLQuery.parse(token.text);\n break;\n default:\n throw new Error(\"Unrecognized URLTokenType: \" + token.type);\n }\n }\n }\n };\n URLBuilder.prototype.toString = function () {\n var result = \"\";\n if (this._scheme) {\n result += this._scheme + \"://\";\n }\n if (this._host) {\n result += this._host;\n }\n if (this._port) {\n result += \":\" + this._port;\n }\n if (this._path) {\n if (!this._path.startsWith(\"/\")) {\n result += \"/\";\n }\n result += this._path;\n }\n if (this._query && this._query.any()) {\n result += \"?\" + this._query.toString();\n }\n return result;\n };\n /**\n * If the provided searchValue is found in this URLBuilder, then replace it with the provided\n * replaceValue.\n */\n URLBuilder.prototype.replaceAll = function (searchValue, replaceValue) {\n if (searchValue) {\n this.setScheme(replaceAll(this.getScheme(), searchValue, replaceValue));\n this.setHost(replaceAll(this.getHost(), searchValue, replaceValue));\n this.setPort(replaceAll(this.getPort(), searchValue, replaceValue));\n this.setPath(replaceAll(this.getPath(), searchValue, replaceValue));\n this.setQuery(replaceAll(this.getQuery(), searchValue, replaceValue));\n }\n };\n URLBuilder.parse = function (text) {\n var result = new URLBuilder();\n result.set(text, \"SCHEME_OR_HOST\");\n return result;\n };\n return URLBuilder;\n}());\nvar URLToken = /** @class */ (function () {\n function URLToken(text, type) {\n this.text = text;\n this.type = type;\n }\n URLToken.scheme = function (text) {\n return new URLToken(text, \"SCHEME\");\n };\n URLToken.host = function (text) {\n return new URLToken(text, \"HOST\");\n };\n URLToken.port = function (text) {\n return new URLToken(text, \"PORT\");\n };\n URLToken.path = function (text) {\n return new URLToken(text, \"PATH\");\n };\n URLToken.query = function (text) {\n return new URLToken(text, \"QUERY\");\n };\n return URLToken;\n}());\n/**\n * Get whether or not the provided character (single character string) is an alphanumeric (letter or\n * digit) character.\n */\nfunction isAlphaNumericCharacter(character) {\n var characterCode = character.charCodeAt(0);\n return (48 /* '0' */ <= characterCode && characterCode <= 57 /* '9' */) ||\n (65 /* 'A' */ <= characterCode && characterCode <= 90 /* 'Z' */) ||\n (97 /* 'a' */ <= characterCode && characterCode <= 122 /* 'z' */);\n}\n/**\n * A class that tokenizes URL strings.\n */\nvar URLTokenizer = /** @class */ (function () {\n function URLTokenizer(_text, state) {\n this._text = _text;\n this._textLength = _text ? _text.length : 0;\n this._currentState = state != undefined ? state : \"SCHEME_OR_HOST\";\n this._currentIndex = 0;\n }\n /**\n * Get the current URLToken this URLTokenizer is pointing at, or undefined if the URLTokenizer\n * hasn't started or has finished tokenizing.\n */\n URLTokenizer.prototype.current = function () {\n return this._currentToken;\n };\n /**\n * Advance to the next URLToken and return whether or not a URLToken was found.\n */\n URLTokenizer.prototype.next = function () {\n if (!hasCurrentCharacter(this)) {\n this._currentToken = undefined;\n }\n else {\n switch (this._currentState) {\n case \"SCHEME\":\n nextScheme(this);\n break;\n case \"SCHEME_OR_HOST\":\n nextSchemeOrHost(this);\n break;\n case \"HOST\":\n nextHost(this);\n break;\n case \"PORT\":\n nextPort(this);\n break;\n case \"PATH\":\n nextPath(this);\n break;\n case \"QUERY\":\n nextQuery(this);\n break;\n default:\n throw new Error(\"Unrecognized URLTokenizerState: \" + this._currentState);\n }\n }\n return !!this._currentToken;\n };\n return URLTokenizer;\n}());\n/**\n * Read the remaining characters from this Tokenizer's character stream.\n */\nfunction readRemaining(tokenizer) {\n var result = \"\";\n if (tokenizer._currentIndex < tokenizer._textLength) {\n result = tokenizer._text.substring(tokenizer._currentIndex);\n tokenizer._currentIndex = tokenizer._textLength;\n }\n return result;\n}\n/**\n * Whether or not this URLTokenizer has a current character.\n */\nfunction hasCurrentCharacter(tokenizer) {\n return tokenizer._currentIndex < tokenizer._textLength;\n}\n/**\n * Get the character in the text string at the current index.\n */\nfunction getCurrentCharacter(tokenizer) {\n return tokenizer._text[tokenizer._currentIndex];\n}\n/**\n * Advance to the character in text that is \"step\" characters ahead. If no step value is provided,\n * then step will default to 1.\n */\nfunction nextCharacter(tokenizer, step) {\n if (hasCurrentCharacter(tokenizer)) {\n if (!step) {\n step = 1;\n }\n tokenizer._currentIndex += step;\n }\n}\n/**\n * Starting with the current character, peek \"charactersToPeek\" number of characters ahead in this\n * Tokenizer's stream of characters.\n */\nfunction peekCharacters(tokenizer, charactersToPeek) {\n var endIndex = tokenizer._currentIndex + charactersToPeek;\n if (tokenizer._textLength < endIndex) {\n endIndex = tokenizer._textLength;\n }\n return tokenizer._text.substring(tokenizer._currentIndex, endIndex);\n}\n/**\n * Read characters from this Tokenizer until the end of the stream or until the provided condition\n * is false when provided the current character.\n */\nfunction readWhile(tokenizer, condition) {\n var result = \"\";\n while (hasCurrentCharacter(tokenizer)) {\n var currentCharacter = getCurrentCharacter(tokenizer);\n if (!condition(currentCharacter)) {\n break;\n }\n else {\n result += currentCharacter;\n nextCharacter(tokenizer);\n }\n }\n return result;\n}\n/**\n * Read characters from this Tokenizer until a non-alphanumeric character or the end of the\n * character stream is reached.\n */\nfunction readWhileLetterOrDigit(tokenizer) {\n return readWhile(tokenizer, function (character) { return isAlphaNumericCharacter(character); });\n}\n/**\n * Read characters from this Tokenizer until one of the provided terminating characters is read or\n * the end of the character stream is reached.\n */\nfunction readUntilCharacter(tokenizer) {\n var terminatingCharacters = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n terminatingCharacters[_i - 1] = arguments[_i];\n }\n return readWhile(tokenizer, function (character) { return terminatingCharacters.indexOf(character) === -1; });\n}\nfunction nextScheme(tokenizer) {\n var scheme = readWhileLetterOrDigit(tokenizer);\n tokenizer._currentToken = URLToken.scheme(scheme);\n if (!hasCurrentCharacter(tokenizer)) {\n tokenizer._currentState = \"DONE\";\n }\n else {\n tokenizer._currentState = \"HOST\";\n }\n}\nfunction nextSchemeOrHost(tokenizer) {\n var schemeOrHost = readUntilCharacter(tokenizer, \":\", \"/\", \"?\");\n if (!hasCurrentCharacter(tokenizer)) {\n tokenizer._currentToken = URLToken.host(schemeOrHost);\n tokenizer._currentState = \"DONE\";\n }\n else if (getCurrentCharacter(tokenizer) === \":\") {\n if (peekCharacters(tokenizer, 3) === \"://\") {\n tokenizer._currentToken = URLToken.scheme(schemeOrHost);\n tokenizer._currentState = \"HOST\";\n }\n else {\n tokenizer._currentToken = URLToken.host(schemeOrHost);\n tokenizer._currentState = \"PORT\";\n }\n }\n else {\n tokenizer._currentToken = URLToken.host(schemeOrHost);\n if (getCurrentCharacter(tokenizer) === \"/\") {\n tokenizer._currentState = \"PATH\";\n }\n else {\n tokenizer._currentState = \"QUERY\";\n }\n }\n}\nfunction nextHost(tokenizer) {\n if (peekCharacters(tokenizer, 3) === \"://\") {\n nextCharacter(tokenizer, 3);\n }\n var host = readUntilCharacter(tokenizer, \":\", \"/\", \"?\");\n tokenizer._currentToken = URLToken.host(host);\n if (!hasCurrentCharacter(tokenizer)) {\n tokenizer._currentState = \"DONE\";\n }\n else if (getCurrentCharacter(tokenizer) === \":\") {\n tokenizer._currentState = \"PORT\";\n }\n else if (getCurrentCharacter(tokenizer) === \"/\") {\n tokenizer._currentState = \"PATH\";\n }\n else {\n tokenizer._currentState = \"QUERY\";\n }\n}\nfunction nextPort(tokenizer) {\n if (getCurrentCharacter(tokenizer) === \":\") {\n nextCharacter(tokenizer);\n }\n var port = readUntilCharacter(tokenizer, \"/\", \"?\");\n tokenizer._currentToken = URLToken.port(port);\n if (!hasCurrentCharacter(tokenizer)) {\n tokenizer._currentState = \"DONE\";\n }\n else if (getCurrentCharacter(tokenizer) === \"/\") {\n tokenizer._currentState = \"PATH\";\n }\n else {\n tokenizer._currentState = \"QUERY\";\n }\n}\nfunction nextPath(tokenizer) {\n var path = readUntilCharacter(tokenizer, \"?\");\n tokenizer._currentToken = URLToken.path(path);\n if (!hasCurrentCharacter(tokenizer)) {\n tokenizer._currentState = \"DONE\";\n }\n else {\n tokenizer._currentState = \"QUERY\";\n }\n}\nfunction nextQuery(tokenizer) {\n if (getCurrentCharacter(tokenizer) === \"?\") {\n nextCharacter(tokenizer);\n }\n var query = readRemaining(tokenizer);\n tokenizer._currentToken = URLToken.query(query);\n tokenizer._currentState = \"DONE\";\n}\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\nvar axiosInstance = axios.create();\n// This hack is still required with 0.19.0 version of axios since axios tries to merge the\n// Content-Type header from it's config[\"\"] where the method name is lower-case,\n// into the request header. It could be possible that the Content-Type header is not present\n// in the original request and this would create problems while creating the signature for\n// storage data plane sdks.\naxiosInstance.interceptors.request.use(function (config) { return (tslib.__assign(tslib.__assign({}, config), { method: config.method && config.method.toUpperCase() })); });\n// keepalive agents are reused across instances to provide maximum socket reuse for\n// outbound requests\nvar keepaliveAgents = {\n http: new http.Agent({ keepAlive: true }),\n https: new https.Agent({ keepAlive: true }),\n};\n/**\n * A HttpClient implementation that uses axios to send HTTP requests.\n */\nvar AxiosHttpClient = /** @class */ (function () {\n function AxiosHttpClient() {\n this.cookieJar = new tough.CookieJar();\n }\n AxiosHttpClient.prototype.sendRequest = function (httpRequest) {\n return tslib.__awaiter(this, void 0, void 0, function () {\n var formData, requestForm_1, appendFormValue, _i, _a, formKey, formValue, j, contentType, cookieString, abortSignal, abortListener, cancelToken, rawHeaders, httpRequestBody, axiosBody, onUploadProgress, loadedBytes_1, uploadReportStream, res, config, _b, httpAgent, httpsAgent, agent, err_1, axiosErr, headers, onDownloadProgress, responseBody, loadedBytes_2, downloadReportStream, length_1, operationResponse, setCookieHeader_1;\n var _this = this;\n return tslib.__generator(this, function (_c) {\n switch (_c.label) {\n case 0:\n if (typeof httpRequest !== \"object\") {\n throw new Error(\"httpRequest (WebResource) cannot be null or undefined and must be of type object.\");\n }\n if (httpRequest.formData) {\n formData = httpRequest.formData;\n requestForm_1 = new FormData();\n appendFormValue = function (key, value) {\n // value function probably returns a stream so we can provide a fresh stream on each retry\n if (typeof value === \"function\") {\n value = value();\n }\n if (value && value.hasOwnProperty(\"value\") && value.hasOwnProperty(\"options\")) {\n requestForm_1.append(key, value.value, value.options);\n }\n else {\n requestForm_1.append(key, value);\n }\n };\n for (_i = 0, _a = Object.keys(formData); _i < _a.length; _i++) {\n formKey = _a[_i];\n formValue = formData[formKey];\n if (Array.isArray(formValue)) {\n for (j = 0; j < formValue.length; j++) {\n appendFormValue(formKey, formValue[j]);\n }\n }\n else {\n appendFormValue(formKey, formValue);\n }\n }\n httpRequest.body = requestForm_1;\n httpRequest.formData = undefined;\n contentType = httpRequest.headers.get(\"Content-Type\");\n if (contentType && contentType.indexOf(\"multipart/form-data\") !== -1) {\n if (typeof requestForm_1.getBoundary === \"function\") {\n httpRequest.headers.set(\"Content-Type\", \"multipart/form-data; boundary=\" + requestForm_1.getBoundary());\n }\n else {\n // browser will automatically apply a suitable content-type header\n httpRequest.headers.remove(\"Content-Type\");\n }\n }\n }\n if (!(this.cookieJar && !httpRequest.headers.get(\"Cookie\"))) return [3 /*break*/, 2];\n return [4 /*yield*/, new Promise(function (resolve, reject) {\n _this.cookieJar.getCookieString(httpRequest.url, function (err, cookie) {\n if (err) {\n reject(err);\n }\n else {\n resolve(cookie);\n }\n });\n })];\n case 1:\n cookieString = _c.sent();\n httpRequest.headers.set(\"Cookie\", cookieString);\n _c.label = 2;\n case 2:\n abortSignal = httpRequest.abortSignal;\n if (abortSignal && abortSignal.aborted) {\n throw new RestError(\"The request was aborted\", RestError.REQUEST_ABORTED_ERROR, undefined, httpRequest);\n }\n cancelToken = abortSignal && new axios.CancelToken(function (canceler) {\n abortListener = function () { return canceler(); };\n abortSignal.addEventListener(\"abort\", abortListener);\n });\n rawHeaders = httpRequest.headers.rawHeaders();\n httpRequestBody = httpRequest.body;\n axiosBody = \n // Workaround for https://github.com/axios/axios/issues/755\n // tslint:disable-next-line:no-null-keyword\n typeof httpRequestBody === \"undefined\" ? null :\n typeof httpRequestBody === \"function\" ? httpRequestBody() :\n httpRequestBody;\n onUploadProgress = httpRequest.onUploadProgress;\n if (onUploadProgress && axiosBody) {\n loadedBytes_1 = 0;\n uploadReportStream = new stream.Transform({\n transform: function (chunk, _encoding, callback) {\n loadedBytes_1 += chunk.length;\n onUploadProgress({ loadedBytes: loadedBytes_1 });\n callback(undefined, chunk);\n }\n });\n if (isReadableStream(axiosBody)) {\n axiosBody.pipe(uploadReportStream);\n }\n else {\n uploadReportStream.end(axiosBody);\n }\n axiosBody = uploadReportStream;\n }\n _c.label = 3;\n case 3:\n _c.trys.push([3, 5, 6, 7]);\n config = {\n method: httpRequest.method,\n url: httpRequest.url,\n headers: rawHeaders,\n data: axiosBody,\n transformResponse: function (data) { return data; },\n validateStatus: function () { return true; },\n // Workaround for https://github.com/axios/axios/issues/1362\n maxContentLength: Infinity,\n responseType: httpRequest.streamResponseBody ? \"stream\" : \"text\",\n cancelToken: cancelToken,\n timeout: httpRequest.timeout,\n proxy: false\n };\n if (httpRequest.agentSettings) {\n _b = httpRequest.agentSettings, httpAgent = _b.http, httpsAgent = _b.https;\n if (httpsAgent) {\n config.httpsAgent = httpsAgent;\n }\n if (httpAgent) {\n config.httpAgent = httpAgent;\n }\n }\n else if (httpRequest.proxySettings) {\n agent = createProxyAgent(httpRequest.url, httpRequest.proxySettings, httpRequest.headers);\n if (agent.isHttps) {\n config.httpsAgent = agent.agent;\n }\n else {\n config.httpAgent = agent.agent;\n }\n }\n if (httpRequest.keepAlive === true) {\n if (config.httpAgent) {\n config.httpAgent.keepAlive = true;\n }\n else {\n config.httpAgent = keepaliveAgents.http;\n }\n if (config.httpsAgent) {\n config.httpsAgent.keepAlive = true;\n }\n else {\n config.httpsAgent = keepaliveAgents.https;\n }\n }\n return [4 /*yield*/, axiosInstance.request(config)];\n case 4:\n res = _c.sent();\n return [3 /*break*/, 7];\n case 5:\n err_1 = _c.sent();\n if (err_1 instanceof axios.Cancel) {\n throw new RestError(err_1.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest);\n }\n else {\n axiosErr = err_1;\n throw new RestError(axiosErr.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest);\n }\n return [3 /*break*/, 7];\n case 6:\n if (abortSignal && abortListener) {\n abortSignal.removeEventListener(\"abort\", abortListener);\n }\n return [7 /*endfinally*/];\n case 7:\n headers = new HttpHeaders(res.headers);\n onDownloadProgress = httpRequest.onDownloadProgress;\n responseBody = res.data;\n if (onDownloadProgress) {\n if (isReadableStream(responseBody)) {\n loadedBytes_2 = 0;\n downloadReportStream = new stream.Transform({\n transform: function (chunk, _encoding, callback) {\n loadedBytes_2 += chunk.length;\n onDownloadProgress({ loadedBytes: loadedBytes_2 });\n callback(undefined, chunk);\n }\n });\n responseBody.pipe(downloadReportStream);\n responseBody = downloadReportStream;\n }\n else {\n length_1 = parseInt(headers.get(\"Content-Length\")) || responseBody.length || undefined;\n if (length_1) {\n // Calling callback for non-stream response for consistency with browser\n onDownloadProgress({ loadedBytes: length_1 });\n }\n }\n }\n operationResponse = {\n request: httpRequest,\n status: res.status,\n headers: headers,\n readableStreamBody: httpRequest.streamResponseBody ? responseBody : undefined,\n bodyAsText: httpRequest.streamResponseBody ? undefined : responseBody\n };\n if (!this.cookieJar) return [3 /*break*/, 9];\n setCookieHeader_1 = operationResponse.headers.get(\"Set-Cookie\");\n if (!(setCookieHeader_1 != undefined)) return [3 /*break*/, 9];\n return [4 /*yield*/, new Promise(function (resolve, reject) {\n _this.cookieJar.setCookie(setCookieHeader_1, httpRequest.url, function (err) {\n if (err) {\n reject(err);\n }\n else {\n resolve();\n }\n });\n })];\n case 8:\n _c.sent();\n _c.label = 9;\n case 9: return [2 /*return*/, operationResponse];\n }\n });\n });\n };\n return AxiosHttpClient;\n}());\nfunction isReadableStream(body) {\n return typeof body.pipe === \"function\";\n}\nfunction createProxyAgent(requestUrl, proxySettings, headers) {\n var tunnelOptions = {\n proxy: {\n host: URLBuilder.parse(proxySettings.host).getHost(),\n port: proxySettings.port,\n headers: (headers && headers.rawHeaders()) || {}\n }\n };\n if ((proxySettings.username && proxySettings.password)) {\n tunnelOptions.proxy.proxyAuth = proxySettings.username + \":\" + proxySettings.password;\n }\n var requestScheme = URLBuilder.parse(requestUrl).getScheme() || \"\";\n var isRequestHttps = requestScheme.toLowerCase() === \"https\";\n var proxyScheme = URLBuilder.parse(proxySettings.host).getScheme() || \"\";\n var isProxyHttps = proxyScheme.toLowerCase() === \"https\";\n var proxyAgent = {\n isHttps: isRequestHttps,\n agent: createTunnel(isRequestHttps, isProxyHttps, tunnelOptions)\n };\n return proxyAgent;\n}\nfunction createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) {\n if (isRequestHttps && isProxyHttps) {\n return tunnel.httpsOverHttps(tunnelOptions);\n }\n else if (isRequestHttps && !isProxyHttps) {\n return tunnel.httpsOverHttp(tunnelOptions);\n }\n else if (!isRequestHttps && isProxyHttps) {\n return tunnel.httpOverHttps(tunnelOptions);\n }\n else {\n return tunnel.httpOverHttp(tunnelOptions);\n }\n}\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n(function (HttpPipelineLogLevel) {\n /**\n * A log level that indicates that no logs will be logged.\n */\n HttpPipelineLogLevel[HttpPipelineLogLevel[\"OFF\"] = 0] = \"OFF\";\n /**\n * An error log.\n */\n HttpPipelineLogLevel[HttpPipelineLogLevel[\"ERROR\"] = 1] = \"ERROR\";\n /**\n * A warning log.\n */\n HttpPipelineLogLevel[HttpPipelineLogLevel[\"WARNING\"] = 2] = \"WARNING\";\n /**\n * An information log.\n */\n HttpPipelineLogLevel[HttpPipelineLogLevel[\"INFO\"] = 3] = \"INFO\";\n})(exports.HttpPipelineLogLevel || (exports.HttpPipelineLogLevel = {}));\n\n// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n/**\n * A static-key-based credential that supports updating\n * the underlying key value.\n */\nvar AzureKeyCredential = /** @class */ (function () {\n /**\n * Create an instance of an AzureKeyCredential for use\n * with a service client.\n *\n * @param key - The initial value of the key to use in authentication\n */\n function AzureKeyCredential(key) {\n if (!key) {\n throw new Error(\"key must be a non-empty string\");\n }\n this._key = key;\n }\n Object.defineProperty(AzureKeyCredential.prototype, \"key\", {\n /**\n * The value of the key to be used in authentication\n */\n get: function () {\n return this._key;\n },\n enumerable: false,\n configurable: true\n });\n /**\n * Change the value of the key.\n *\n * Updates will take effect upon the next request after\n * updating the key value.\n *\n * @param newKey - The new key value to be used\n */\n AzureKeyCredential.prototype.update = function (newKey) {\n this._key = newKey;\n };\n return AzureKeyCredential;\n}());\n\n// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n/**\n * Tests an object to determine whether it implements TokenCredential.\n *\n * @param credential - The assumed TokenCredential to be tested.\n */\nfunction isTokenCredential(credential) {\n // Check for an object with a 'getToken' function and possibly with\n // a 'signRequest' function. We do this check to make sure that\n // a ServiceClientCredentials implementor (like TokenClientCredentials\n // in ms-rest-nodeauth) doesn't get mistaken for a TokenCredential if\n // it doesn't actually implement TokenCredential also.\n var castCredential = credential;\n return (castCredential &&\n typeof castCredential.getToken === \"function\" &&\n (castCredential.signRequest === undefined || castCredential.getToken.length > 0));\n}\n\n// Copyright (c) Microsoft Corporation.\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\n/**\n * Get the path to this parameter's value as a dotted string (a.b.c).\n * @param parameter The parameter to get the path string for.\n * @returns The path to this parameter's value as a dotted string.\n */\nfunction getPathStringFromParameter(parameter) {\n return getPathStringFromParameterPath(parameter.parameterPath, parameter.mapper);\n}\nfunction getPathStringFromParameterPath(parameterPath, mapper) {\n var result;\n if (typeof parameterPath === \"string\") {\n result = parameterPath;\n }\n else if (Array.isArray(parameterPath)) {\n result = parameterPath.join(\".\");\n }\n else {\n result = mapper.serializedName;\n }\n return result;\n}\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\nfunction isStreamOperation(operationSpec) {\n var result = false;\n for (var statusCode in operationSpec.responses) {\n var operationResponse = operationSpec.responses[statusCode];\n if (operationResponse.bodyMapper && operationResponse.bodyMapper.type.name === MapperType.Stream) {\n result = true;\n break;\n }\n }\n return result;\n}\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\nfunction stringifyXML(obj, opts) {\n var builder = new xml2js.Builder({\n explicitArray: false,\n explicitCharkey: false,\n rootName: (opts || {}).rootName,\n renderOpts: {\n pretty: false\n }\n });\n return builder.buildObject(obj);\n}\nfunction parseXML(str) {\n var xmlParser = new xml2js.Parser({\n explicitArray: false,\n explicitCharkey: false,\n explicitRoot: false\n });\n return new Promise(function (resolve, reject) {\n if (!str) {\n reject(new Error(\"Document is empty\"));\n }\n else {\n xmlParser.parseString(str, function (err, res) {\n if (err) {\n reject(err);\n }\n else {\n resolve(res);\n }\n });\n }\n });\n}\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\nvar BaseRequestPolicy = /** @class */ (function () {\n function BaseRequestPolicy(_nextPolicy, _options) {\n this._nextPolicy = _nextPolicy;\n this._options = _options;\n }\n /**\n * Get whether or not a log with the provided log level should be logged.\n * @param logLevel The log level of the log that will be logged.\n * @returns Whether or not a log with the provided log level should be logged.\n */\n BaseRequestPolicy.prototype.shouldLog = function (logLevel) {\n return this._options.shouldLog(logLevel);\n };\n /**\n * Attempt to log the provided message to the provided logger. If no logger was provided or if\n * the log level does not meat the logger's threshold, then nothing will be logged.\n * @param logLevel The log level of this log.\n * @param message The message of this log.\n */\n BaseRequestPolicy.prototype.log = function (logLevel, message) {\n this._options.log(logLevel, message);\n };\n return BaseRequestPolicy;\n}());\n/**\n * Optional properties that can be used when creating a RequestPolicy.\n */\nvar RequestPolicyOptions = /** @class */ (function () {\n function RequestPolicyOptions(_logger) {\n this._logger = _logger;\n }\n /**\n * Get whether or not a log with the provided log level should be logged.\n * @param logLevel The log level of the log that will be logged.\n * @returns Whether or not a log with the provided log level should be logged.\n */\n RequestPolicyOptions.prototype.shouldLog = function (logLevel) {\n return !!this._logger &&\n logLevel !== exports.HttpPipelineLogLevel.OFF &&\n logLevel <= this._logger.minimumLogLevel;\n };\n /**\n * Attempt to log the provided message to the provided logger. If no logger was provided or if\n * the log level does not meat the logger's threshold, then nothing will be logged.\n * @param logLevel The log level of this log.\n * @param message The message of this log.\n */\n RequestPolicyOptions.prototype.log = function (logLevel, message) {\n if (this._logger && this.shouldLog(logLevel)) {\n this._logger.log(logLevel, message);\n }\n };\n return RequestPolicyOptions;\n}());\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n/**\n * Create a new serialization RequestPolicyCreator that will serialized HTTP request bodies as they\n * pass through the HTTP pipeline.\n */\nfunction deserializationPolicy(deserializationContentTypes) {\n return {\n create: function (nextPolicy, options) {\n return new DeserializationPolicy(nextPolicy, deserializationContentTypes, options);\n }\n };\n}\nvar defaultJsonContentTypes = [\"application/json\", \"text/json\"];\nvar defaultXmlContentTypes = [\"application/xml\", \"application/atom+xml\"];\n/**\n * A RequestPolicy that will deserialize HTTP response bodies and headers as they pass through the\n * HTTP pipeline.\n */\nvar DeserializationPolicy = /** @class */ (function (_super) {\n tslib.__extends(DeserializationPolicy, _super);\n function DeserializationPolicy(nextPolicy, deserializationContentTypes, options) {\n var _this = _super.call(this, nextPolicy, options) || this;\n _this.jsonContentTypes = deserializationContentTypes && deserializationContentTypes.json || defaultJsonContentTypes;\n _this.xmlContentTypes = deserializationContentTypes && deserializationContentTypes.xml || defaultXmlContentTypes;\n return _this;\n }\n DeserializationPolicy.prototype.sendRequest = function (request) {\n return tslib.__awaiter(this, void 0, void 0, function () {\n var _this = this;\n return tslib.__generator(this, function (_a) {\n return [2 /*return*/, this._nextPolicy.sendRequest(request).then(function (response) { return deserializeResponseBody(_this.jsonContentTypes, _this.xmlContentTypes, response); })];\n });\n });\n };\n return DeserializationPolicy;\n}(BaseRequestPolicy));\nfunction getOperationResponse(parsedResponse) {\n var result;\n var request = parsedResponse.request;\n var operationSpec = request.operationSpec;\n if (operationSpec) {\n var operationResponseGetter = request.operationResponseGetter;\n if (!operationResponseGetter) {\n result = operationSpec.responses[parsedResponse.status];\n }\n else {\n result = operationResponseGetter(operationSpec, parsedResponse);\n }\n }\n return result;\n}\nfunction shouldDeserializeResponse(parsedResponse) {\n var shouldDeserialize = parsedResponse.request.shouldDeserialize;\n var result;\n if (shouldDeserialize === undefined) {\n result = true;\n }\n else if (typeof shouldDeserialize === \"boolean\") {\n result = shouldDeserialize;\n }\n else {\n result = shouldDeserialize(parsedResponse);\n }\n return result;\n}\nfunction deserializeResponseBody(jsonContentTypes, xmlContentTypes, response) {\n return parse(jsonContentTypes, xmlContentTypes, response).then(function (parsedResponse) {\n var shouldDeserialize = shouldDeserializeResponse(parsedResponse);\n if (shouldDeserialize) {\n var operationSpec = parsedResponse.request.operationSpec;\n if (operationSpec && operationSpec.responses) {\n var statusCode = parsedResponse.status;\n var expectedStatusCodes = Object.keys(operationSpec.responses);\n var hasNoExpectedStatusCodes = (expectedStatusCodes.length === 0 || (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === \"default\"));\n var responseSpec = getOperationResponse(parsedResponse);\n var isExpectedStatusCode = hasNoExpectedStatusCodes ? (200 <= statusCode && statusCode < 300) : !!responseSpec;\n if (!isExpectedStatusCode) {\n var defaultResponseSpec = operationSpec.responses.default;\n if (defaultResponseSpec) {\n var initialErrorMessage = isStreamOperation(operationSpec)\n ? \"Unexpected status code: \" + statusCode\n : parsedResponse.bodyAsText;\n var error = new RestError(initialErrorMessage);\n error.statusCode = statusCode;\n error.request = stripRequest(parsedResponse.request);\n error.response = stripResponse(parsedResponse);\n var parsedErrorResponse = parsedResponse.parsedBody;\n try {\n if (parsedErrorResponse) {\n var defaultResponseBodyMapper = defaultResponseSpec.bodyMapper;\n if (defaultResponseBodyMapper && defaultResponseBodyMapper.serializedName === \"CloudError\") {\n if (parsedErrorResponse.error) {\n parsedErrorResponse = parsedErrorResponse.error;\n }\n if (parsedErrorResponse.code) {\n error.code = parsedErrorResponse.code;\n }\n if (parsedErrorResponse.message) {\n error.message = parsedErrorResponse.message;\n }\n }\n else {\n var internalError = parsedErrorResponse;\n if (parsedErrorResponse.error) {\n internalError = parsedErrorResponse.error;\n }\n error.code = internalError.code;\n if (internalError.message) {\n error.message = internalError.message;\n }\n }\n if (defaultResponseBodyMapper) {\n var valueToDeserialize = parsedErrorResponse;\n if (operationSpec.isXML && defaultResponseBodyMapper.type.name === MapperType.Sequence) {\n valueToDeserialize = typeof parsedErrorResponse === \"object\"\n ? parsedErrorResponse[defaultResponseBodyMapper.xmlElementName]\n : [];\n }\n error.body = operationSpec.serializer.deserialize(defaultResponseBodyMapper, valueToDeserialize, \"error.body\");\n }\n }\n }\n catch (defaultError) {\n error.message = \"Error \\\"\" + defaultError.message + \"\\\" occurred in deserializing the responseBody - \\\"\" + parsedResponse.bodyAsText + \"\\\" for the default response.\";\n }\n return Promise.reject(error);\n }\n }\n else if (responseSpec) {\n if (responseSpec.bodyMapper) {\n var valueToDeserialize = parsedResponse.parsedBody;\n if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperType.Sequence) {\n valueToDeserialize = typeof valueToDeserialize === \"object\" ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName] : [];\n }\n try {\n parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, \"operationRes.parsedBody\");\n }\n catch (error) {\n var restError = new RestError(\"Error \" + error + \" occurred in deserializing the responseBody - \" + parsedResponse.bodyAsText);\n restError.request = stripRequest(parsedResponse.request);\n restError.response = stripResponse(parsedResponse);\n return Promise.reject(restError);\n }\n }\n else if (operationSpec.httpMethod === \"HEAD\") {\n // head methods never have a body, but we return a boolean to indicate presence/absence of the resource\n parsedResponse.parsedBody = response.status >= 200 && response.status < 300;\n }\n if (responseSpec.headersMapper) {\n parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.rawHeaders(), \"operationRes.parsedHeaders\");\n }\n }\n }\n }\n return Promise.resolve(parsedResponse);\n });\n}\nfunction parse(jsonContentTypes, xmlContentTypes, operationResponse) {\n var errorHandler = function (err) {\n var msg = \"Error \\\"\" + err + \"\\\" occurred while parsing the response body - \" + operationResponse.bodyAsText + \".\";\n var errCode = err.code || RestError.PARSE_ERROR;\n var e = new RestError(msg, errCode, operationResponse.status, operationResponse.request, operationResponse, operationResponse.bodyAsText);\n return Promise.reject(e);\n };\n if (!operationResponse.request.streamResponseBody && operationResponse.bodyAsText) {\n var text_1 = operationResponse.bodyAsText;\n var contentType = operationResponse.headers.get(\"Content-Type\") || \"\";\n var contentComponents = !contentType ? [] : contentType.split(\";\").map(function (component) { return component.toLowerCase(); });\n if (contentComponents.length === 0 || contentComponents.some(function (component) { return jsonContentTypes.indexOf(component) !== -1; })) {\n return new Promise(function (resolve) {\n operationResponse.parsedBody = JSON.parse(text_1);\n resolve(operationResponse);\n }).catch(errorHandler);\n }\n else if (contentComponents.some(function (component) { return xmlContentTypes.indexOf(component) !== -1; })) {\n return parseXML(text_1)\n .then(function (body) {\n operationResponse.parsedBody = body;\n return operationResponse;\n })\n .catch(errorHandler);\n }\n }\n return Promise.resolve(operationResponse);\n}\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\nfunction exponentialRetryPolicy(retryCount, retryInterval, minRetryInterval, maxRetryInterval) {\n return {\n create: function (nextPolicy, options) {\n return new ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval);\n }\n };\n}\nvar DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30;\nvar DEFAULT_CLIENT_RETRY_COUNT = 3;\nvar DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90;\nvar DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3;\n/**\n * @class\n * Instantiates a new \"ExponentialRetryPolicyFilter\" instance.\n */\nvar ExponentialRetryPolicy = /** @class */ (function (_super) {\n tslib.__extends(ExponentialRetryPolicy, _super);\n /**\n * @constructor\n * @param {RequestPolicy} nextPolicy The next RequestPolicy in the pipeline chain.\n * @param {RequestPolicyOptions} options The options for this RequestPolicy.\n * @param {number} [retryCount] The client retry count.\n * @param {number} [retryInterval] The client retry interval, in milliseconds.\n * @param {number} [minRetryInterval] The minimum retry interval, in milliseconds.\n * @param {number} [maxRetryInterval] The maximum retry interval, in milliseconds.\n */\n function ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) {\n var _this = _super.call(this, nextPolicy, options) || this;\n function isNumber(n) { return typeof n === \"number\"; }\n _this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT;\n _this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL;\n _this.minRetryInterval = isNumber(minRetryInterval) ? minRetryInterval : DEFAULT_CLIENT_MIN_RETRY_INTERVAL;\n _this.maxRetryInterval = isNumber(maxRetryInterval) ? maxRetryInterval : DEFAULT_CLIENT_MAX_RETRY_INTERVAL;\n return _this;\n }\n ExponentialRetryPolicy.prototype.sendRequest = function (request) {\n var _this = this;\n return this._nextPolicy.sendRequest(request.clone())\n .then(function (response) { return retry(_this, request, response); })\n .catch(function (error) { return retry(_this, request, error.response, undefined, error); });\n };\n return ExponentialRetryPolicy;\n}(BaseRequestPolicy));\n/**\n * Determines if the operation should be retried and how long to wait until the next retry.\n *\n * @param {ExponentialRetryPolicy} policy The ExponentialRetryPolicy that this function is being called against.\n * @param {number} statusCode The HTTP status code.\n * @param {RetryData} retryData The retry data.\n * @return {boolean} True if the operation qualifies for a retry; false otherwise.\n */\nfunction shouldRetry(policy, statusCode, retryData) {\n if (statusCode == undefined || (statusCode < 500 && statusCode !== 408) || statusCode === 501 || statusCode === 505) {\n return false;\n }\n var currentCount;\n if (!retryData) {\n throw new Error(\"retryData for the ExponentialRetryPolicyFilter cannot be null.\");\n }\n else {\n currentCount = (retryData && retryData.retryCount);\n }\n return (currentCount < policy.retryCount);\n}\n/**\n * Updates the retry data for the next attempt.\n *\n * @param {ExponentialRetryPolicy} policy The ExponentialRetryPolicy that this function is being called against.\n * @param {RetryData} retryData The retry data.\n * @param {RetryError} [err] The operation\"s error, if any.\n */\nfunction updateRetryData(policy, retryData, err) {\n if (!retryData) {\n retryData = {\n retryCount: 0,\n retryInterval: 0\n };\n }\n if (err) {\n if (retryData.error) {\n err.innerError = retryData.error;\n }\n retryData.error = err;\n }\n // Adjust retry count\n retryData.retryCount++;\n // Adjust retry interval\n var incrementDelta = Math.pow(2, retryData.retryCount) - 1;\n var boundedRandDelta = policy.retryInterval * 0.8 +\n Math.floor(Math.random() * (policy.retryInterval * 1.2 - policy.retryInterval * 0.8));\n incrementDelta *= boundedRandDelta;\n retryData.retryInterval = Math.min(policy.minRetryInterval + incrementDelta, policy.maxRetryInterval);\n return retryData;\n}\nfunction retry(policy, request, response, retryData, requestError) {\n retryData = updateRetryData(policy, retryData, requestError);\n var isAborted = request.abortSignal && request.abortSignal.aborted;\n if (!isAborted && shouldRetry(policy, response && response.status, retryData)) {\n return delay(retryData.retryInterval)\n .then(function () { return policy._nextPolicy.sendRequest(request.clone()); })\n .then(function (res) { return retry(policy, request, res, retryData, undefined); })\n .catch(function (err) { return retry(policy, request, response, retryData, err); });\n }\n else if (isAborted || requestError || !response) {\n // If the operation failed in the end, return all errors instead of just the last one\n var err = retryData.error ||\n new RestError(\"Failed to send the request.\", RestError.REQUEST_SEND_ERROR, response && response.status, response && response.request, response);\n return Promise.reject(err);\n }\n else {\n return Promise.resolve(response);\n }\n}\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\nfunction generateClientRequestIdPolicy(requestIdHeaderName) {\n if (requestIdHeaderName === void 0) { requestIdHeaderName = \"x-ms-client-request-id\"; }\n return {\n create: function (nextPolicy, options) {\n return new GenerateClientRequestIdPolicy(nextPolicy, options, requestIdHeaderName);\n }\n };\n}\nvar GenerateClientRequestIdPolicy = /** @class */ (function (_super) {\n tslib.__extends(GenerateClientRequestIdPolicy, _super);\n function GenerateClientRequestIdPolicy(nextPolicy, options, _requestIdHeaderName) {\n var _this = _super.call(this, nextPolicy, options) || this;\n _this._requestIdHeaderName = _requestIdHeaderName;\n return _this;\n }\n GenerateClientRequestIdPolicy.prototype.sendRequest = function (request) {\n if (!request.headers.contains(this._requestIdHeaderName)) {\n request.headers.set(this._requestIdHeaderName, generateUuid());\n }\n return this._nextPolicy.sendRequest(request);\n };\n return GenerateClientRequestIdPolicy;\n}(BaseRequestPolicy));\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\nfunction getDefaultUserAgentKey() {\n return Constants.HeaderConstants.USER_AGENT;\n}\nfunction getPlatformSpecificData() {\n var runtimeInfo = {\n key: \"Node\",\n value: process.version\n };\n var osInfo = {\n key: \"OS\",\n value: \"(\" + os.arch() + \"-\" + os.type() + \"-\" + os.release() + \")\"\n };\n return [runtimeInfo, osInfo];\n}\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\nfunction getRuntimeInfo() {\n var msRestRuntime = {\n key: \"ms-rest-js\",\n value: Constants.msRestVersion\n };\n return [msRestRuntime];\n}\nfunction getUserAgentString(telemetryInfo, keySeparator, valueSeparator) {\n if (keySeparator === void 0) { keySeparator = \" \"; }\n if (valueSeparator === void 0) { valueSeparator = \"/\"; }\n return telemetryInfo.map(function (info) {\n var value = info.value ? \"\" + valueSeparator + info.value : \"\";\n return \"\" + info.key + value;\n }).join(keySeparator);\n}\nvar getDefaultUserAgentHeaderName = getDefaultUserAgentKey;\nfunction getDefaultUserAgentValue() {\n var runtimeInfo = getRuntimeInfo();\n var platformSpecificData = getPlatformSpecificData();\n var userAgent = getUserAgentString(runtimeInfo.concat(platformSpecificData));\n return userAgent;\n}\nfunction userAgentPolicy(userAgentData) {\n var key = (!userAgentData || userAgentData.key == undefined) ? getDefaultUserAgentKey() : userAgentData.key;\n var value = (!userAgentData || userAgentData.value == undefined) ? getDefaultUserAgentValue() : userAgentData.value;\n return {\n create: function (nextPolicy, options) {\n return new UserAgentPolicy(nextPolicy, options, key, value);\n }\n };\n}\nvar UserAgentPolicy = /** @class */ (function (_super) {\n tslib.__extends(UserAgentPolicy, _super);\n function UserAgentPolicy(_nextPolicy, _options, headerKey, headerValue) {\n var _this = _super.call(this, _nextPolicy, _options) || this;\n _this._nextPolicy = _nextPolicy;\n _this._options = _options;\n _this.headerKey = headerKey;\n _this.headerValue = headerValue;\n return _this;\n }\n UserAgentPolicy.prototype.sendRequest = function (request) {\n this.addUserAgentHeader(request);\n return this._nextPolicy.sendRequest(request);\n };\n UserAgentPolicy.prototype.addUserAgentHeader = function (request) {\n if (!request.headers) {\n request.headers = new HttpHeaders();\n }\n if (!request.headers.get(this.headerKey) && this.headerValue) {\n request.headers.set(this.headerKey, this.headerValue);\n }\n };\n return UserAgentPolicy;\n}(BaseRequestPolicy));\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\nfunction redirectPolicy(maximumRetries) {\n if (maximumRetries === void 0) { maximumRetries = 20; }\n return {\n create: function (nextPolicy, options) {\n return new RedirectPolicy(nextPolicy, options, maximumRetries);\n }\n };\n}\nvar RedirectPolicy = /** @class */ (function (_super) {\n tslib.__extends(RedirectPolicy, _super);\n function RedirectPolicy(nextPolicy, options, maxRetries) {\n if (maxRetries === void 0) { maxRetries = 20; }\n var _this = _super.call(this, nextPolicy, options) || this;\n _this.maxRetries = maxRetries;\n return _this;\n }\n RedirectPolicy.prototype.sendRequest = function (request) {\n var _this = this;\n return this._nextPolicy.sendRequest(request).then(function (response) { return handleRedirect(_this, response, 0); });\n };\n return RedirectPolicy;\n}(BaseRequestPolicy));\nfunction handleRedirect(policy, response, currentRetries) {\n var request = response.request, status = response.status;\n var locationHeader = response.headers.get(\"location\");\n if (locationHeader &&\n (status === 300 || status === 307 || (status === 303 && request.method === \"POST\")) &&\n (!policy.maxRetries || currentRetries < policy.maxRetries)) {\n var builder = URLBuilder.parse(request.url);\n builder.setPath(locationHeader);\n request.url = builder.toString();\n // POST request with Status code 303 should be converted into a\n // redirected GET request if the redirect url is present in the location header\n if (status === 303) {\n request.method = \"GET\";\n }\n return policy._nextPolicy.sendRequest(request)\n .then(function (res) { return handleRedirect(policy, res, currentRetries + 1); });\n }\n return Promise.resolve(response);\n}\n\nfunction rpRegistrationPolicy(retryTimeout) {\n if (retryTimeout === void 0) { retryTimeout = 30; }\n return {\n create: function (nextPolicy, options) {\n return new RPRegistrationPolicy(nextPolicy, options, retryTimeout);\n }\n };\n}\nvar RPRegistrationPolicy = /** @class */ (function (_super) {\n tslib.__extends(RPRegistrationPolicy, _super);\n function RPRegistrationPolicy(nextPolicy, options, _retryTimeout) {\n if (_retryTimeout === void 0) { _retryTimeout = 30; }\n var _this = _super.call(this, nextPolicy, options) || this;\n _this._retryTimeout = _retryTimeout;\n return _this;\n }\n RPRegistrationPolicy.prototype.sendRequest = function (request) {\n var _this = this;\n return this._nextPolicy.sendRequest(request.clone())\n .then(function (response) { return registerIfNeeded(_this, request, response); });\n };\n return RPRegistrationPolicy;\n}(BaseRequestPolicy));\nfunction registerIfNeeded(policy, request, response) {\n if (response.status === 409) {\n var rpName = checkRPNotRegisteredError(response.bodyAsText);\n if (rpName) {\n var urlPrefix = extractSubscriptionUrl(request.url);\n return registerRP(policy, urlPrefix, rpName, request)\n // Autoregistration of ${provider} failed for some reason. We will not return this error\n // instead will return the initial response with 409 status code back to the user.\n // do nothing here as we are returning the original response at the end of this method.\n .catch(function () { return false; })\n .then(function (registrationStatus) {\n if (registrationStatus) {\n // Retry the original request. We have to change the x-ms-client-request-id\n // otherwise Azure endpoint will return the initial 409 (cached) response.\n request.headers.set(\"x-ms-client-request-id\", generateUuid());\n return policy._nextPolicy.sendRequest(request.clone());\n }\n return response;\n });\n }\n }\n return Promise.resolve(response);\n}\n/**\n * Reuses the headers of the original request and url (if specified).\n * @param {WebResource} originalRequest The original request\n * @param {boolean} reuseUrlToo Should the url from the original request be reused as well. Default false.\n * @returns {object} A new request object with desired headers.\n */\nfunction getRequestEssentials(originalRequest, reuseUrlToo) {\n if (reuseUrlToo === void 0) { reuseUrlToo = false; }\n var reqOptions = originalRequest.clone();\n if (reuseUrlToo) {\n reqOptions.url = originalRequest.url;\n }\n // We have to change the x-ms-client-request-id otherwise Azure endpoint\n // will return the initial 409 (cached) response.\n reqOptions.headers.set(\"x-ms-client-request-id\", generateUuid());\n // Set content-type to application/json\n reqOptions.headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n return reqOptions;\n}\n/**\n * Validates the error code and message associated with 409 response status code. If it matches to that of\n * RP not registered then it returns the name of the RP else returns undefined.\n * @param {string} body The response body received after making the original request.\n * @returns {string} The name of the RP if condition is satisfied else undefined.\n */\nfunction checkRPNotRegisteredError(body) {\n var result, responseBody;\n if (body) {\n try {\n responseBody = JSON.parse(body);\n }\n catch (err) {\n // do nothing;\n }\n if (responseBody && responseBody.error && responseBody.error.message &&\n responseBody.error.code && responseBody.error.code === \"MissingSubscriptionRegistration\") {\n var matchRes = responseBody.error.message.match(/.*'(.*)'/i);\n if (matchRes) {\n result = matchRes.pop();\n }\n }\n }\n return result;\n}\n/**\n * Extracts the first part of the URL, just after subscription:\n * https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/\n * @param {string} url The original request url\n * @returns {string} The url prefix as explained above.\n */\nfunction extractSubscriptionUrl(url) {\n var result;\n var matchRes = url.match(/.*\\/subscriptions\\/[a-f0-9-]+\\//ig);\n if (matchRes && matchRes[0]) {\n result = matchRes[0];\n }\n else {\n throw new Error(\"Unable to extract subscriptionId from the given url - \" + url + \".\");\n }\n return result;\n}\n/**\n * Registers the given provider.\n * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against.\n * @param {string} urlPrefix https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/\n * @param {string} provider The provider name to be registered.\n * @param {WebResource} originalRequest The original request sent by the user that returned a 409 response\n * with a message that the provider is not registered.\n * @param {registrationCallback} callback The callback that handles the RP registration\n */\nfunction registerRP(policy, urlPrefix, provider, originalRequest) {\n var postUrl = urlPrefix + \"providers/\" + provider + \"/register?api-version=2016-02-01\";\n var getUrl = urlPrefix + \"providers/\" + provider + \"?api-version=2016-02-01\";\n var reqOptions = getRequestEssentials(originalRequest);\n reqOptions.method = \"POST\";\n reqOptions.url = postUrl;\n return policy._nextPolicy.sendRequest(reqOptions)\n .then(function (response) {\n if (response.status !== 200) {\n throw new Error(\"Autoregistration of \" + provider + \" failed. Please try registering manually.\");\n }\n return getRegistrationStatus(policy, getUrl, originalRequest);\n });\n}\n/**\n * Polls the registration status of the provider that was registered. Polling happens at an interval of 30 seconds.\n * Polling will happen till the registrationState property of the response body is \"Registered\".\n * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against.\n * @param {string} url The request url for polling\n * @param {WebResource} originalRequest The original request sent by the user that returned a 409 response\n * with a message that the provider is not registered.\n * @returns {Promise} True if RP Registration is successful.\n */\nfunction getRegistrationStatus(policy, url, originalRequest) {\n var reqOptions = getRequestEssentials(originalRequest);\n reqOptions.url = url;\n reqOptions.method = \"GET\";\n return policy._nextPolicy.sendRequest(reqOptions).then(function (res) {\n var obj = res.parsedBody;\n if (res.parsedBody && obj.registrationState && obj.registrationState === \"Registered\") {\n return true;\n }\n else {\n return delay(policy._retryTimeout * 1000).then(function () { return getRegistrationStatus(policy, url, originalRequest); });\n }\n });\n}\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\nfunction signingPolicy(authenticationProvider) {\n return {\n create: function (nextPolicy, options) {\n return new SigningPolicy(nextPolicy, options, authenticationProvider);\n }\n };\n}\nvar SigningPolicy = /** @class */ (function (_super) {\n tslib.__extends(SigningPolicy, _super);\n function SigningPolicy(nextPolicy, options, authenticationProvider) {\n var _this = _super.call(this, nextPolicy, options) || this;\n _this.authenticationProvider = authenticationProvider;\n return _this;\n }\n SigningPolicy.prototype.signRequest = function (request) {\n return this.authenticationProvider.signRequest(request);\n };\n SigningPolicy.prototype.sendRequest = function (request) {\n var _this = this;\n return this.signRequest(request).then(function (nextRequest) { return _this._nextPolicy.sendRequest(nextRequest); });\n };\n return SigningPolicy;\n}(BaseRequestPolicy));\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\nfunction systemErrorRetryPolicy(retryCount, retryInterval, minRetryInterval, maxRetryInterval) {\n return {\n create: function (nextPolicy, options) {\n return new SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval);\n }\n };\n}\n/**\n * @class\n * Instantiates a new \"ExponentialRetryPolicyFilter\" instance.\n *\n * @constructor\n * @param {number} retryCount The client retry count.\n * @param {number} retryInterval The client retry interval, in milliseconds.\n * @param {number} minRetryInterval The minimum retry interval, in milliseconds.\n * @param {number} maxRetryInterval The maximum retry interval, in milliseconds.\n */\nvar SystemErrorRetryPolicy = /** @class */ (function (_super) {\n tslib.__extends(SystemErrorRetryPolicy, _super);\n function SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) {\n var _this = _super.call(this, nextPolicy, options) || this;\n _this.DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30;\n _this.DEFAULT_CLIENT_RETRY_COUNT = 3;\n _this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90;\n _this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3;\n _this.retryCount = typeof retryCount === \"number\" ? retryCount : _this.DEFAULT_CLIENT_RETRY_COUNT;\n _this.retryInterval = typeof retryInterval === \"number\" ? retryInterval : _this.DEFAULT_CLIENT_RETRY_INTERVAL;\n _this.minRetryInterval = typeof minRetryInterval === \"number\" ? minRetryInterval : _this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL;\n _this.maxRetryInterval = typeof maxRetryInterval === \"number\" ? maxRetryInterval : _this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL;\n return _this;\n }\n SystemErrorRetryPolicy.prototype.sendRequest = function (request) {\n var _this = this;\n return this._nextPolicy.sendRequest(request.clone()).then(function (response) { return retry$1(_this, request, response); });\n };\n return SystemErrorRetryPolicy;\n}(BaseRequestPolicy));\n/**\n * Determines if the operation should be retried and how long to wait until the next retry.\n *\n * @param {number} statusCode The HTTP status code.\n * @param {RetryData} retryData The retry data.\n * @return {boolean} True if the operation qualifies for a retry; false otherwise.\n */\nfunction shouldRetry$1(policy, retryData) {\n var currentCount;\n if (!retryData) {\n throw new Error(\"retryData for the SystemErrorRetryPolicyFilter cannot be null.\");\n }\n else {\n currentCount = (retryData && retryData.retryCount);\n }\n return (currentCount < policy.retryCount);\n}\n/**\n * Updates the retry data for the next attempt.\n *\n * @param {RetryData} retryData The retry data.\n * @param {object} err The operation\"s error, if any.\n */\nfunction updateRetryData$1(policy, retryData, err) {\n if (!retryData) {\n retryData = {\n retryCount: 0,\n retryInterval: 0\n };\n }\n if (err) {\n if (retryData.error) {\n err.innerError = retryData.error;\n }\n retryData.error = err;\n }\n // Adjust retry count\n retryData.retryCount++;\n // Adjust retry interval\n var incrementDelta = Math.pow(2, retryData.retryCount) - 1;\n var boundedRandDelta = policy.retryInterval * 0.8 +\n Math.floor(Math.random() * (policy.retryInterval * 1.2 - policy.retryInterval * 0.8));\n incrementDelta *= boundedRandDelta;\n retryData.retryInterval = Math.min(policy.minRetryInterval + incrementDelta, policy.maxRetryInterval);\n return retryData;\n}\nfunction retry$1(policy, request, operationResponse, retryData, err) {\n retryData = updateRetryData$1(policy, retryData, err);\n if (err && err.code && shouldRetry$1(policy, retryData) &&\n (err.code === \"ETIMEDOUT\" || err.code === \"ESOCKETTIMEDOUT\" || err.code === \"ECONNREFUSED\" ||\n err.code === \"ECONNRESET\" || err.code === \"ENOENT\")) {\n // If previous operation ended with an error and the policy allows a retry, do that\n return delay(retryData.retryInterval)\n .then(function () { return policy._nextPolicy.sendRequest(request.clone()); })\n .then(function (res) { return retry$1(policy, request, res, retryData, err); })\n .catch(function (err) { return retry$1(policy, request, operationResponse, retryData, err); });\n }\n else {\n if (err != undefined) {\n // If the operation failed in the end, return all errors instead of just the last one\n err = retryData.error;\n return Promise.reject(err);\n }\n return Promise.resolve(operationResponse);\n }\n}\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n(function (QueryCollectionFormat) {\n QueryCollectionFormat[\"Csv\"] = \",\";\n QueryCollectionFormat[\"Ssv\"] = \" \";\n QueryCollectionFormat[\"Tsv\"] = \"\\t\";\n QueryCollectionFormat[\"Pipes\"] = \"|\";\n QueryCollectionFormat[\"Multi\"] = \"Multi\";\n})(exports.QueryCollectionFormat || (exports.QueryCollectionFormat = {}));\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\nfunction agentPolicy(agentSettings) {\n return {\n create: function (nextPolicy, options) {\n return new AgentPolicy(nextPolicy, options, agentSettings);\n }\n };\n}\nvar AgentPolicy = /** @class */ (function (_super) {\n tslib.__extends(AgentPolicy, _super);\n function AgentPolicy(nextPolicy, options, agentSettings) {\n var _this = _super.call(this, nextPolicy, options) || this;\n _this.agentSettings = agentSettings;\n return _this;\n }\n AgentPolicy.prototype.sendRequest = function (request) {\n if (!request.agentSettings) {\n request.agentSettings = this.agentSettings;\n }\n return this._nextPolicy.sendRequest(request);\n };\n return AgentPolicy;\n}(BaseRequestPolicy));\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\nfunction loadEnvironmentProxyValue() {\n if (!process) {\n return undefined;\n }\n if (process.env[Constants.HTTPS_PROXY]) {\n return process.env[Constants.HTTPS_PROXY];\n }\n else if (process.env[Constants.HTTPS_PROXY.toLowerCase()]) {\n return process.env[Constants.HTTPS_PROXY.toLowerCase()];\n }\n else if (process.env[Constants.HTTP_PROXY]) {\n return process.env[Constants.HTTP_PROXY];\n }\n else if (process.env[Constants.HTTP_PROXY.toLowerCase()]) {\n return process.env[Constants.HTTP_PROXY.toLowerCase()];\n }\n return undefined;\n}\nfunction getDefaultProxySettings(proxyUrl) {\n if (!proxyUrl) {\n proxyUrl = loadEnvironmentProxyValue();\n if (!proxyUrl) {\n return undefined;\n }\n }\n var parsedUrl = URLBuilder.parse(proxyUrl);\n return {\n host: parsedUrl.getScheme() + \"://\" + parsedUrl.getHost(),\n port: Number.parseInt(parsedUrl.getPort() || \"80\")\n };\n}\nfunction proxyPolicy(proxySettings) {\n return {\n create: function (nextPolicy, options) {\n return new ProxyPolicy(nextPolicy, options, proxySettings);\n }\n };\n}\nvar ProxyPolicy = /** @class */ (function (_super) {\n tslib.__extends(ProxyPolicy, _super);\n function ProxyPolicy(nextPolicy, options, proxySettings) {\n var _this = _super.call(this, nextPolicy, options) || this;\n _this.proxySettings = proxySettings;\n return _this;\n }\n ProxyPolicy.prototype.sendRequest = function (request) {\n if (!request.proxySettings) {\n request.proxySettings = this.proxySettings;\n }\n return this._nextPolicy.sendRequest(request);\n };\n return ProxyPolicy;\n}(BaseRequestPolicy));\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\nvar StatusCodes = Constants.HttpConstants.StatusCodes;\nfunction throttlingRetryPolicy() {\n return {\n create: function (nextPolicy, options) {\n return new ThrottlingRetryPolicy(nextPolicy, options);\n }\n };\n}\n/**\n * To learn more, please refer to\n * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits,\n * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and\n * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors\n */\nvar ThrottlingRetryPolicy = /** @class */ (function (_super) {\n tslib.__extends(ThrottlingRetryPolicy, _super);\n function ThrottlingRetryPolicy(nextPolicy, options, _handleResponse) {\n var _this = _super.call(this, nextPolicy, options) || this;\n _this._handleResponse = _handleResponse || _this._defaultResponseHandler;\n return _this;\n }\n ThrottlingRetryPolicy.prototype.sendRequest = function (httpRequest) {\n return tslib.__awaiter(this, void 0, void 0, function () {\n var _this = this;\n return tslib.__generator(this, function (_a) {\n return [2 /*return*/, this._nextPolicy.sendRequest(httpRequest.clone()).then(function (response) {\n if (response.status !== StatusCodes.TooManyRequests) {\n return response;\n }\n else {\n return _this._handleResponse(httpRequest, response);\n }\n })];\n });\n });\n };\n ThrottlingRetryPolicy.prototype._defaultResponseHandler = function (httpRequest, httpResponse) {\n return tslib.__awaiter(this, void 0, void 0, function () {\n var retryAfterHeader, delayInMs;\n var _this = this;\n return tslib.__generator(this, function (_a) {\n retryAfterHeader = httpResponse.headers.get(Constants.HeaderConstants.RETRY_AFTER);\n if (retryAfterHeader) {\n delayInMs = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader);\n if (delayInMs) {\n return [2 /*return*/, delay(delayInMs).then(function (_) { return _this._nextPolicy.sendRequest(httpRequest); })];\n }\n }\n return [2 /*return*/, httpResponse];\n });\n });\n };\n ThrottlingRetryPolicy.parseRetryAfterHeader = function (headerValue) {\n var retryAfterInSeconds = Number(headerValue);\n if (Number.isNaN(retryAfterInSeconds)) {\n return ThrottlingRetryPolicy.parseDateRetryAfterHeader(headerValue);\n }\n else {\n return retryAfterInSeconds * 1000;\n }\n };\n ThrottlingRetryPolicy.parseDateRetryAfterHeader = function (headerValue) {\n try {\n var now = Date.now();\n var date = Date.parse(headerValue);\n var diff = date - now;\n return Number.isNaN(diff) ? undefined : diff;\n }\n catch (error) {\n return undefined;\n }\n };\n return ThrottlingRetryPolicy;\n}(BaseRequestPolicy));\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\nvar DEFAULT_AUTHORIZATION_SCHEME = \"Bearer\";\n/**\n * This class provides a simple extension to use {@link TokenCredential} from `@azure/identity` library to\n * use with legacy Azure SDKs that accept {@link ServiceClientCredentials} family of credentials for authentication.\n */\nvar AzureIdentityCredentialAdapter = /** @class */ (function () {\n function AzureIdentityCredentialAdapter(azureTokenCredential, scopes) {\n if (scopes === void 0) { scopes = \"https://management.azure.com/.default\"; }\n this.azureTokenCredential = azureTokenCredential;\n this.scopes = scopes;\n }\n AzureIdentityCredentialAdapter.prototype.getToken = function () {\n return tslib.__awaiter(this, void 0, void 0, function () {\n var accessToken, result;\n return tslib.__generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, this.azureTokenCredential.getToken(this.scopes)];\n case 1:\n accessToken = _a.sent();\n if (accessToken !== null) {\n result = {\n accessToken: accessToken.token,\n tokenType: DEFAULT_AUTHORIZATION_SCHEME,\n expiresOn: accessToken.expiresOnTimestamp,\n };\n return [2 /*return*/, result];\n }\n else {\n throw new Error(\"Could find token for scope\");\n }\n return [2 /*return*/];\n }\n });\n });\n };\n AzureIdentityCredentialAdapter.prototype.signRequest = function (webResource) {\n return tslib.__awaiter(this, void 0, void 0, function () {\n var tokenResponse;\n return tslib.__generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, this.getToken()];\n case 1:\n tokenResponse = _a.sent();\n webResource.headers.set(Constants.HeaderConstants.AUTHORIZATION, tokenResponse.tokenType + \" \" + tokenResponse.accessToken);\n return [2 /*return*/, Promise.resolve(webResource)];\n }\n });\n });\n };\n return AzureIdentityCredentialAdapter;\n}());\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n/**\n * @class\n * Initializes a new instance of the ServiceClient.\n */\nvar ServiceClient = /** @class */ (function () {\n /**\n * The ServiceClient constructor\n * @constructor\n * @param {ServiceClientCredentials} [credentials] The credentials object used for authentication.\n * @param {ServiceClientOptions} [options] The service client options that govern the behavior of the client.\n */\n function ServiceClient(credentials, options) {\n if (!options) {\n options = {};\n }\n var serviceClientCredentials;\n if (isTokenCredential(credentials)) {\n serviceClientCredentials = new AzureIdentityCredentialAdapter(credentials);\n }\n else {\n serviceClientCredentials = credentials;\n }\n if (serviceClientCredentials && !serviceClientCredentials.signRequest) {\n throw new Error(\"credentials argument needs to implement signRequest method\");\n }\n this._withCredentials = options.withCredentials || false;\n this._httpClient = options.httpClient || new AxiosHttpClient();\n this._requestPolicyOptions = new RequestPolicyOptions(options.httpPipelineLogger);\n var requestPolicyFactories;\n if (Array.isArray(options.requestPolicyFactories)) {\n requestPolicyFactories = options.requestPolicyFactories;\n }\n else {\n requestPolicyFactories = createDefaultRequestPolicyFactories(serviceClientCredentials, options);\n if (options.requestPolicyFactories) {\n var newRequestPolicyFactories = options.requestPolicyFactories(requestPolicyFactories);\n if (newRequestPolicyFactories) {\n requestPolicyFactories = newRequestPolicyFactories;\n }\n }\n }\n this._requestPolicyFactories = requestPolicyFactories;\n }\n /**\n * Send the provided httpRequest.\n */\n ServiceClient.prototype.sendRequest = function (options) {\n if (options === null || options === undefined || typeof options !== \"object\") {\n throw new Error(\"options cannot be null or undefined and it must be of type object.\");\n }\n var httpRequest;\n try {\n if (options instanceof WebResource) {\n options.validateRequestProperties();\n httpRequest = options;\n }\n else {\n httpRequest = new WebResource();\n httpRequest = httpRequest.prepare(options);\n }\n }\n catch (error) {\n return Promise.reject(error);\n }\n var httpPipeline = this._httpClient;\n if (this._requestPolicyFactories && this._requestPolicyFactories.length > 0) {\n for (var i = this._requestPolicyFactories.length - 1; i >= 0; --i) {\n httpPipeline = this._requestPolicyFactories[i].create(httpPipeline, this._requestPolicyOptions);\n }\n }\n return httpPipeline.sendRequest(httpRequest);\n };\n /**\n * Send an HTTP request that is populated using the provided OperationSpec.\n * @param {OperationArguments} operationArguments The arguments that the HTTP request's templated values will be populated from.\n * @param {OperationSpec} operationSpec The OperationSpec to use to populate the httpRequest.\n * @param {ServiceCallback} callback The callback to call when the response is received.\n */\n ServiceClient.prototype.sendOperationRequest = function (operationArguments, operationSpec, callback) {\n if (typeof operationArguments.options === \"function\") {\n callback = operationArguments.options;\n operationArguments.options = undefined;\n }\n var httpRequest = new WebResource();\n var result;\n try {\n var baseUri = operationSpec.baseUrl || this.baseUri;\n if (!baseUri) {\n throw new Error(\"If operationSpec.baseUrl is not specified, then the ServiceClient must have a baseUri string property that contains the base URL to use.\");\n }\n httpRequest.method = operationSpec.httpMethod;\n httpRequest.operationSpec = operationSpec;\n var requestUrl = URLBuilder.parse(baseUri);\n if (operationSpec.path) {\n requestUrl.appendPath(operationSpec.path);\n }\n if (operationSpec.urlParameters && operationSpec.urlParameters.length > 0) {\n for (var _i = 0, _a = operationSpec.urlParameters; _i < _a.length; _i++) {\n var urlParameter = _a[_i];\n var urlParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, urlParameter, operationSpec.serializer);\n urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, getPathStringFromParameter(urlParameter));\n if (!urlParameter.skipEncoding) {\n urlParameterValue = encodeURIComponent(urlParameterValue);\n }\n requestUrl.replaceAll(\"{\" + (urlParameter.mapper.serializedName || getPathStringFromParameter(urlParameter)) + \"}\", urlParameterValue);\n }\n }\n if (operationSpec.queryParameters && operationSpec.queryParameters.length > 0) {\n for (var _b = 0, _c = operationSpec.queryParameters; _b < _c.length; _b++) {\n var queryParameter = _c[_b];\n var queryParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, queryParameter, operationSpec.serializer);\n if (queryParameterValue != undefined) {\n queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter));\n if (queryParameter.collectionFormat != undefined) {\n if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Multi) {\n if (queryParameterValue.length === 0) {\n queryParameterValue = \"\";\n }\n else {\n for (var index in queryParameterValue) {\n var item = queryParameterValue[index];\n queryParameterValue[index] = item == undefined ? \"\" : item.toString();\n }\n }\n }\n else {\n queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat);\n }\n }\n if (!queryParameter.skipEncoding) {\n if (Array.isArray(queryParameterValue)) {\n for (var index in queryParameterValue) {\n queryParameterValue[index] = encodeURIComponent(queryParameterValue[index]);\n }\n }\n else {\n queryParameterValue = encodeURIComponent(queryParameterValue);\n }\n }\n requestUrl.setQueryParameter(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue);\n }\n }\n }\n httpRequest.url = requestUrl.toString();\n var contentType = operationSpec.contentType || this.requestContentType;\n if (contentType) {\n httpRequest.headers.set(\"Content-Type\", contentType);\n }\n if (operationSpec.headerParameters) {\n for (var _d = 0, _e = operationSpec.headerParameters; _d < _e.length; _d++) {\n var headerParameter = _e[_d];\n var headerValue = getOperationArgumentValueFromParameter(this, operationArguments, headerParameter, operationSpec.serializer);\n if (headerValue != undefined) {\n headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter));\n var headerCollectionPrefix = headerParameter.mapper.headerCollectionPrefix;\n if (headerCollectionPrefix) {\n for (var _f = 0, _g = Object.keys(headerValue); _f < _g.length; _f++) {\n var key = _g[_f];\n httpRequest.headers.set(headerCollectionPrefix + key, headerValue[key]);\n }\n }\n else {\n httpRequest.headers.set(headerParameter.mapper.serializedName || getPathStringFromParameter(headerParameter), headerValue);\n }\n }\n }\n }\n var options = operationArguments.options;\n if (options) {\n if (options.customHeaders) {\n for (var customHeaderName in options.customHeaders) {\n httpRequest.headers.set(customHeaderName, options.customHeaders[customHeaderName]);\n }\n }\n if (options.abortSignal) {\n httpRequest.abortSignal = options.abortSignal;\n }\n if (options.timeout) {\n httpRequest.timeout = options.timeout;\n }\n if (options.onUploadProgress) {\n httpRequest.onUploadProgress = options.onUploadProgress;\n }\n if (options.onDownloadProgress) {\n httpRequest.onDownloadProgress = options.onDownloadProgress;\n }\n }\n httpRequest.withCredentials = this._withCredentials;\n serializeRequestBody(this, httpRequest, operationArguments, operationSpec);\n if (httpRequest.streamResponseBody == undefined) {\n httpRequest.streamResponseBody = isStreamOperation(operationSpec);\n }\n result = this.sendRequest(httpRequest)\n .then(function (res) { return flattenResponse(res, operationSpec.responses[res.status]); });\n }\n catch (error) {\n result = Promise.reject(error);\n }\n var cb = callback;\n if (cb) {\n result\n // tslint:disable-next-line:no-null-keyword\n .then(function (res) { return cb(null, res._response.parsedBody, res._response.request, res._response); })\n .catch(function (err) { return cb(err); });\n }\n return result;\n };\n return ServiceClient;\n}());\nfunction serializeRequestBody(serviceClient, httpRequest, operationArguments, operationSpec) {\n if (operationSpec.requestBody && operationSpec.requestBody.mapper) {\n httpRequest.body = getOperationArgumentValueFromParameter(serviceClient, operationArguments, operationSpec.requestBody, operationSpec.serializer);\n var bodyMapper = operationSpec.requestBody.mapper;\n var required = bodyMapper.required, xmlName = bodyMapper.xmlName, xmlElementName = bodyMapper.xmlElementName, serializedName = bodyMapper.serializedName;\n var typeName = bodyMapper.type.name;\n try {\n if (httpRequest.body != undefined || required) {\n var requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody);\n httpRequest.body = operationSpec.serializer.serialize(bodyMapper, httpRequest.body, requestBodyParameterPathString);\n var isStream = typeName === MapperType.Stream;\n if (operationSpec.isXML) {\n if (typeName === MapperType.Sequence) {\n httpRequest.body = stringifyXML(prepareXMLRootList(httpRequest.body, xmlElementName || xmlName || serializedName), { rootName: xmlName || serializedName });\n }\n else if (!isStream) {\n httpRequest.body = stringifyXML(httpRequest.body, { rootName: xmlName || serializedName });\n }\n }\n else if (!isStream) {\n httpRequest.body = JSON.stringify(httpRequest.body);\n }\n }\n }\n catch (error) {\n throw new Error(\"Error \\\"\" + error.message + \"\\\" occurred in serializing the payload - \" + JSON.stringify(serializedName, undefined, \" \") + \".\");\n }\n }\n else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) {\n httpRequest.formData = {};\n for (var _i = 0, _a = operationSpec.formDataParameters; _i < _a.length; _i++) {\n var formDataParameter = _a[_i];\n var formDataParameterValue = getOperationArgumentValueFromParameter(serviceClient, operationArguments, formDataParameter, operationSpec.serializer);\n if (formDataParameterValue != undefined) {\n var formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter);\n httpRequest.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter));\n }\n }\n }\n}\nfunction isRequestPolicyFactory(instance) {\n return typeof instance.create === \"function\";\n}\nfunction getValueOrFunctionResult(value, defaultValueCreator) {\n var result;\n if (typeof value === \"string\") {\n result = value;\n }\n else {\n result = defaultValueCreator();\n if (typeof value === \"function\") {\n result = value(result);\n }\n }\n return result;\n}\nfunction createDefaultRequestPolicyFactories(credentials, options) {\n var factories = [];\n if (options.generateClientRequestIdHeader) {\n factories.push(generateClientRequestIdPolicy(options.clientRequestIdHeaderName));\n }\n if (credentials) {\n if (isRequestPolicyFactory(credentials)) {\n factories.push(credentials);\n }\n else {\n factories.push(signingPolicy(credentials));\n }\n }\n var userAgentHeaderName = getValueOrFunctionResult(options.userAgentHeaderName, getDefaultUserAgentHeaderName);\n var userAgentHeaderValue = getValueOrFunctionResult(options.userAgent, getDefaultUserAgentValue);\n if (userAgentHeaderName && userAgentHeaderValue) {\n factories.push(userAgentPolicy({ key: userAgentHeaderName, value: userAgentHeaderValue }));\n }\n factories.push(redirectPolicy());\n factories.push(rpRegistrationPolicy(options.rpRegistrationRetryTimeout));\n if (!options.noRetryPolicy) {\n factories.push(exponentialRetryPolicy());\n factories.push(systemErrorRetryPolicy());\n factories.push(throttlingRetryPolicy());\n }\n factories.push(deserializationPolicy(options.deserializationContentTypes));\n var proxySettings = options.proxySettings || getDefaultProxySettings();\n if (proxySettings) {\n factories.push(proxyPolicy(proxySettings));\n }\n if (options.agentSettings) {\n factories.push(agentPolicy(options.agentSettings));\n }\n return factories;\n}\nfunction getOperationArgumentValueFromParameter(serviceClient, operationArguments, parameter, serializer) {\n return getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameter.parameterPath, parameter.mapper, serializer);\n}\nfunction getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, serializer) {\n var value;\n if (typeof parameterPath === \"string\") {\n parameterPath = [parameterPath];\n }\n if (Array.isArray(parameterPath)) {\n if (parameterPath.length > 0) {\n if (parameterMapper.isConstant) {\n value = parameterMapper.defaultValue;\n }\n else {\n var propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath);\n if (!propertySearchResult.propertyFound) {\n propertySearchResult = getPropertyFromParameterPath(serviceClient, parameterPath);\n }\n var useDefaultValue = false;\n if (!propertySearchResult.propertyFound) {\n useDefaultValue = parameterMapper.required || (parameterPath[0] === \"options\" && parameterPath.length === 2);\n }\n value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue;\n }\n // Serialize just for validation purposes.\n var parameterPathString = getPathStringFromParameterPath(parameterPath, parameterMapper);\n serializer.serialize(parameterMapper, value, parameterPathString);\n }\n }\n else {\n if (parameterMapper.required) {\n value = {};\n }\n for (var propertyName in parameterPath) {\n var propertyMapper = parameterMapper.type.modelProperties[propertyName];\n var propertyPath = parameterPath[propertyName];\n var propertyValue = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, propertyPath, propertyMapper, serializer);\n // Serialize just for validation purposes.\n var propertyPathString = getPathStringFromParameterPath(propertyPath, propertyMapper);\n serializer.serialize(propertyMapper, propertyValue, propertyPathString);\n if (propertyValue !== undefined) {\n if (!value) {\n value = {};\n }\n value[propertyName] = propertyValue;\n }\n }\n }\n return value;\n}\nfunction getPropertyFromParameterPath(parent, parameterPath) {\n var result = { propertyFound: false };\n var i = 0;\n for (; i < parameterPath.length; ++i) {\n var parameterPathPart = parameterPath[i];\n // Make sure to check inherited properties too, so don't use hasOwnProperty().\n if (parent != undefined && parameterPathPart in parent) {\n parent = parent[parameterPathPart];\n }\n else {\n break;\n }\n }\n if (i === parameterPath.length) {\n result.propertyValue = parent;\n result.propertyFound = true;\n }\n return result;\n}\nfunction flattenResponse(_response, responseSpec) {\n var parsedHeaders = _response.parsedHeaders;\n var bodyMapper = responseSpec && responseSpec.bodyMapper;\n var addOperationResponse = function (obj) {\n return Object.defineProperty(obj, \"_response\", {\n value: _response\n });\n };\n if (bodyMapper) {\n var typeName = bodyMapper.type.name;\n if (typeName === \"Stream\") {\n return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), { blobBody: _response.blobBody, readableStreamBody: _response.readableStreamBody }));\n }\n var modelProperties_1 = typeName === \"Composite\" && bodyMapper.type.modelProperties || {};\n var isPageableResponse = Object.keys(modelProperties_1).some(function (k) { return modelProperties_1[k].serializedName === \"\"; });\n if (typeName === \"Sequence\" || isPageableResponse) {\n // We're expecting a sequence(array) make sure that the response body is in the\n // correct format, if not make it an empty array []\n var parsedBody = Array.isArray(_response.parsedBody)\n ? _response.parsedBody\n : [];\n var arrayResponse = tslib.__spreadArrays(parsedBody);\n for (var _i = 0, _a = Object.keys(modelProperties_1); _i < _a.length; _i++) {\n var key = _a[_i];\n if (modelProperties_1[key].serializedName) {\n arrayResponse[key] = _response.parsedBody[key];\n }\n }\n if (parsedHeaders) {\n for (var _b = 0, _c = Object.keys(parsedHeaders); _b < _c.length; _b++) {\n var key = _c[_b];\n arrayResponse[key] = parsedHeaders[key];\n }\n }\n addOperationResponse(arrayResponse);\n return arrayResponse;\n }\n if (typeName === \"Composite\" || typeName === \"Dictionary\") {\n return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), _response.parsedBody));\n }\n }\n if (bodyMapper || _response.request.method === \"HEAD\") {\n // primitive body types and HEAD booleans\n return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), { body: _response.parsedBody }));\n }\n return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), _response.parsedBody));\n}\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\nfunction logPolicy(logger) {\n if (logger === void 0) { logger = console.log; }\n return {\n create: function (nextPolicy, options) {\n return new LogPolicy(nextPolicy, options, logger);\n }\n };\n}\nvar LogPolicy = /** @class */ (function (_super) {\n tslib.__extends(LogPolicy, _super);\n function LogPolicy(nextPolicy, options, logger) {\n if (logger === void 0) { logger = console.log; }\n var _this = _super.call(this, nextPolicy, options) || this;\n _this.logger = logger;\n return _this;\n }\n LogPolicy.prototype.sendRequest = function (request) {\n var _this = this;\n return this._nextPolicy.sendRequest(request).then(function (response) { return logResponse(_this, response); });\n };\n return LogPolicy;\n}(BaseRequestPolicy));\nfunction logResponse(policy, response) {\n policy.logger(\">> Request: \" + JSON.stringify(response.request, undefined, 2));\n policy.logger(\">> Response status code: \" + response.status);\n var responseBody = response.bodyAsText;\n policy.logger(\">> Body: \" + responseBody);\n return Promise.resolve(response);\n}\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\nvar HeaderConstants = Constants.HeaderConstants;\nvar DEFAULT_AUTHORIZATION_SCHEME$1 = \"Bearer\";\n/**\n * A credentials object that uses a token string and a authorzation scheme to authenticate.\n */\nvar TokenCredentials = /** @class */ (function () {\n /**\n * Creates a new TokenCredentials object.\n *\n * @constructor\n * @param {string} token The token.\n * @param {string} [authorizationScheme] The authorization scheme.\n */\n function TokenCredentials(token, authorizationScheme) {\n if (authorizationScheme === void 0) { authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$1; }\n this.authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$1;\n if (!token) {\n throw new Error(\"token cannot be null or undefined.\");\n }\n this.token = token;\n this.authorizationScheme = authorizationScheme;\n }\n /**\n * Signs a request with the Authentication header.\n *\n * @param {WebResource} webResource The WebResource to be signed.\n * @return {Promise} The signed request object.\n */\n TokenCredentials.prototype.signRequest = function (webResource) {\n if (!webResource.headers)\n webResource.headers = new HttpHeaders();\n webResource.headers.set(HeaderConstants.AUTHORIZATION, this.authorizationScheme + \" \" + this.token);\n return Promise.resolve(webResource);\n };\n return TokenCredentials;\n}());\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\nvar HeaderConstants$1 = Constants.HeaderConstants;\nvar DEFAULT_AUTHORIZATION_SCHEME$2 = \"Basic\";\nvar BasicAuthenticationCredentials = /** @class */ (function () {\n /**\n * Creates a new BasicAuthenticationCredentials object.\n *\n * @constructor\n * @param {string} userName User name.\n * @param {string} password Password.\n * @param {string} [authorizationScheme] The authorization scheme.\n */\n function BasicAuthenticationCredentials(userName, password, authorizationScheme) {\n if (authorizationScheme === void 0) { authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$2; }\n this.authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$2;\n if (userName === null || userName === undefined || typeof userName.valueOf() !== \"string\") {\n throw new Error(\"userName cannot be null or undefined and must be of type string.\");\n }\n if (password === null || password === undefined || typeof password.valueOf() !== \"string\") {\n throw new Error(\"password cannot be null or undefined and must be of type string.\");\n }\n this.userName = userName;\n this.password = password;\n this.authorizationScheme = authorizationScheme;\n }\n /**\n * Signs a request with the Authentication header.\n *\n * @param {WebResource} webResource The WebResource to be signed.\n * @returns {Promise} The signed request object.\n */\n BasicAuthenticationCredentials.prototype.signRequest = function (webResource) {\n var credentials = this.userName + \":\" + this.password;\n var encodedCredentials = this.authorizationScheme + \" \" + encodeString(credentials);\n if (!webResource.headers)\n webResource.headers = new HttpHeaders();\n webResource.headers.set(HeaderConstants$1.AUTHORIZATION, encodedCredentials);\n return Promise.resolve(webResource);\n };\n return BasicAuthenticationCredentials;\n}());\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n/**\n * Authenticates to a service using an API key.\n */\nvar ApiKeyCredentials = /** @class */ (function () {\n /**\n * @constructor\n * @param {object} options Specifies the options to be provided for auth. Either header or query needs to be provided.\n */\n function ApiKeyCredentials(options) {\n if (!options || (options && !options.inHeader && !options.inQuery)) {\n throw new Error(\"options cannot be null or undefined. Either \\\"inHeader\\\" or \\\"inQuery\\\" property of the options object needs to be provided.\");\n }\n this.inHeader = options.inHeader;\n this.inQuery = options.inQuery;\n }\n /**\n * Signs a request with the values provided in the inHeader and inQuery parameter.\n *\n * @param {WebResource} webResource The WebResource to be signed.\n * @returns {Promise} The signed request object.\n */\n ApiKeyCredentials.prototype.signRequest = function (webResource) {\n if (!webResource) {\n return Promise.reject(new Error(\"webResource cannot be null or undefined and must be of type \\\"object\\\".\"));\n }\n if (this.inHeader) {\n if (!webResource.headers) {\n webResource.headers = new HttpHeaders();\n }\n for (var headerName in this.inHeader) {\n webResource.headers.set(headerName, this.inHeader[headerName]);\n }\n }\n if (this.inQuery) {\n if (!webResource.url) {\n return Promise.reject(new Error(\"url cannot be null in the request object.\"));\n }\n if (webResource.url.indexOf(\"?\") < 0) {\n webResource.url += \"?\";\n }\n for (var key in this.inQuery) {\n if (!webResource.url.endsWith(\"?\")) {\n webResource.url += \"&\";\n }\n webResource.url += key + \"=\" + this.inQuery[key];\n }\n }\n return Promise.resolve(webResource);\n };\n return ApiKeyCredentials;\n}());\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\nvar TopicCredentials = /** @class */ (function (_super) {\n tslib.__extends(TopicCredentials, _super);\n /**\n * Creates a new EventGrid TopicCredentials object.\n *\n * @constructor\n * @param {string} topicKey The EventGrid topic key\n */\n function TopicCredentials(topicKey) {\n var _this = this;\n if (!topicKey || (topicKey && typeof topicKey !== \"string\")) {\n throw new Error(\"topicKey cannot be null or undefined and must be of type string.\");\n }\n var options = {\n inHeader: {\n \"aeg-sas-key\": topicKey\n }\n };\n _this = _super.call(this, options) || this;\n return _this;\n }\n return TopicCredentials;\n}(ApiKeyCredentials));\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\nvar DomainCredentials = /** @class */ (function (_super) {\n tslib.__extends(DomainCredentials, _super);\n /**\n * Creates a new EventGrid DomainCredentials object.\n *\n * @constructor\n * @param {string} domainKey The EventGrid domain key\n */\n function DomainCredentials(domainKey) {\n var _this = this;\n if (!domainKey || (domainKey && typeof domainKey !== \"string\")) {\n throw new Error(\"domainKey cannot be null or undefined and must be of type string.\");\n }\n var options = {\n inHeader: {\n \"aeg-sas-key\": domainKey\n }\n };\n _this = _super.call(this, options) || this;\n return _this;\n }\n return DomainCredentials;\n}(ApiKeyCredentials));\n\n// Copyright (c) Microsoft Corporation. All rights reserved.\n\nexports.WebResource = WebResource;\nexports.DefaultHttpClient = AxiosHttpClient;\nexports.HttpHeaders = HttpHeaders;\nexports.RestError = RestError;\nexports.ServiceClient = ServiceClient;\nexports.flattenResponse = flattenResponse;\nexports.Constants = Constants;\nexports.logPolicy = logPolicy;\nexports.BaseRequestPolicy = BaseRequestPolicy;\nexports.RequestPolicyOptions = RequestPolicyOptions;\nexports.generateClientRequestIdPolicy = generateClientRequestIdPolicy;\nexports.exponentialRetryPolicy = exponentialRetryPolicy;\nexports.systemErrorRetryPolicy = systemErrorRetryPolicy;\nexports.throttlingRetryPolicy = throttlingRetryPolicy;\nexports.getDefaultProxySettings = getDefaultProxySettings;\nexports.proxyPolicy = proxyPolicy;\nexports.redirectPolicy = redirectPolicy;\nexports.signingPolicy = signingPolicy;\nexports.userAgentPolicy = userAgentPolicy;\nexports.getDefaultUserAgentValue = getDefaultUserAgentValue;\nexports.deserializationPolicy = deserializationPolicy;\nexports.deserializeResponseBody = deserializeResponseBody;\nexports.MapperType = MapperType;\nexports.Serializer = Serializer;\nexports.serializeObject = serializeObject;\nexports.stripRequest = stripRequest;\nexports.stripResponse = stripResponse;\nexports.delay = delay;\nexports.executePromisesSequentially = executePromisesSequentially;\nexports.generateUuid = generateUuid;\nexports.encodeUri = encodeUri;\nexports.promiseToCallback = promiseToCallback;\nexports.promiseToServiceCallback = promiseToServiceCallback;\nexports.isValidUuid = isValidUuid;\nexports.applyMixins = applyMixins;\nexports.isNode = isNode;\nexports.isDuration = isDuration;\nexports.URLBuilder = URLBuilder;\nexports.URLQuery = URLQuery;\nexports.TokenCredentials = TokenCredentials;\nexports.BasicAuthenticationCredentials = BasicAuthenticationCredentials;\nexports.ApiKeyCredentials = ApiKeyCredentials;\nexports.TopicCredentials = TopicCredentials;\nexports.DomainCredentials = DomainCredentials;\n//# sourceMappingURL=msRest.node.js.map\n","var CombinedStream = require('combined-stream');\nvar util = require('util');\nvar path = require('path');\nvar http = require('http');\nvar https = require('https');\nvar parseUrl = require('url').parse;\nvar fs = require('fs');\nvar mime = require('mime-types');\nvar asynckit = require('asynckit');\nvar populate = require('./populate.js');\n\n// Public API\nmodule.exports = FormData;\n\n// make it a Stream\nutil.inherits(FormData, CombinedStream);\n\n/**\n * Create readable \"multipart/form-data\" streams.\n * Can be used to submit forms\n * and file uploads to other web applications.\n *\n * @constructor\n * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream\n */\nfunction FormData(options) {\n if (!(this instanceof FormData)) {\n return new FormData();\n }\n\n this._overheadLength = 0;\n this._valueLength = 0;\n this._valuesToMeasure = [];\n\n CombinedStream.call(this);\n\n options = options || {};\n for (var option in options) {\n this[option] = options[option];\n }\n}\n\nFormData.LINE_BREAK = '\\r\\n';\nFormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream';\n\nFormData.prototype.append = function(field, value, options) {\n\n options = options || {};\n\n // allow filename as single option\n if (typeof options == 'string') {\n options = {filename: options};\n }\n\n var append = CombinedStream.prototype.append.bind(this);\n\n // all that streamy business can't handle numbers\n if (typeof value == 'number') {\n value = '' + value;\n }\n\n // https://github.com/felixge/node-form-data/issues/38\n if (util.isArray(value)) {\n // Please convert your array into string\n // the way web server expects it\n this._error(new Error('Arrays are not supported.'));\n return;\n }\n\n var header = this._multiPartHeader(field, value, options);\n var footer = this._multiPartFooter();\n\n append(header);\n append(value);\n append(footer);\n\n // pass along options.knownLength\n this._trackLength(header, value, options);\n};\n\nFormData.prototype._trackLength = function(header, value, options) {\n var valueLength = 0;\n\n // used w/ getLengthSync(), when length is known.\n // e.g. for streaming directly from a remote server,\n // w/ a known file a size, and not wanting to wait for\n // incoming file to finish to get its size.\n if (options.knownLength != null) {\n valueLength += +options.knownLength;\n } else if (Buffer.isBuffer(value)) {\n valueLength = value.length;\n } else if (typeof value === 'string') {\n valueLength = Buffer.byteLength(value);\n }\n\n this._valueLength += valueLength;\n\n // @check why add CRLF? does this account for custom/multiple CRLFs?\n this._overheadLength +=\n Buffer.byteLength(header) +\n FormData.LINE_BREAK.length;\n\n // empty or either doesn't have path or not an http response\n if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) )) {\n return;\n }\n\n // no need to bother with the length\n if (!options.knownLength) {\n this._valuesToMeasure.push(value);\n }\n};\n\nFormData.prototype._lengthRetriever = function(value, callback) {\n\n if (value.hasOwnProperty('fd')) {\n\n // take read range into a account\n // `end` = Infinity –> read file till the end\n //\n // TODO: Looks like there is bug in Node fs.createReadStream\n // it doesn't respect `end` options without `start` options\n // Fix it when node fixes it.\n // https://github.com/joyent/node/issues/7819\n if (value.end != undefined && value.end != Infinity && value.start != undefined) {\n\n // when end specified\n // no need to calculate range\n // inclusive, starts with 0\n callback(null, value.end + 1 - (value.start ? value.start : 0));\n\n // not that fast snoopy\n } else {\n // still need to fetch file size from fs\n fs.stat(value.path, function(err, stat) {\n\n var fileSize;\n\n if (err) {\n callback(err);\n return;\n }\n\n // update final size based on the range options\n fileSize = stat.size - (value.start ? value.start : 0);\n callback(null, fileSize);\n });\n }\n\n // or http response\n } else if (value.hasOwnProperty('httpVersion')) {\n callback(null, +value.headers['content-length']);\n\n // or request stream http://github.com/mikeal/request\n } else if (value.hasOwnProperty('httpModule')) {\n // wait till response come back\n value.on('response', function(response) {\n value.pause();\n callback(null, +response.headers['content-length']);\n });\n value.resume();\n\n // something else\n } else {\n callback('Unknown stream');\n }\n};\n\nFormData.prototype._multiPartHeader = function(field, value, options) {\n // custom header specified (as string)?\n // it becomes responsible for boundary\n // (e.g. to handle extra CRLFs on .NET servers)\n if (typeof options.header == 'string') {\n return options.header;\n }\n\n var contentDisposition = this._getContentDisposition(value, options);\n var contentType = this._getContentType(value, options);\n\n var contents = '';\n var headers = {\n // add custom disposition as third element or keep it two elements if not\n 'Content-Disposition': ['form-data', 'name=\"' + field + '\"'].concat(contentDisposition || []),\n // if no content type. allow it to be empty array\n 'Content-Type': [].concat(contentType || [])\n };\n\n // allow custom headers.\n if (typeof options.header == 'object') {\n populate(headers, options.header);\n }\n\n var header;\n for (var prop in headers) {\n if (!headers.hasOwnProperty(prop)) continue;\n header = headers[prop];\n\n // skip nullish headers.\n if (header == null) {\n continue;\n }\n\n // convert all headers to arrays.\n if (!Array.isArray(header)) {\n header = [header];\n }\n\n // add non-empty headers.\n if (header.length) {\n contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK;\n }\n }\n\n return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK;\n};\n\nFormData.prototype._getContentDisposition = function(value, options) {\n\n var filename\n , contentDisposition\n ;\n\n if (typeof options.filepath === 'string') {\n // custom filepath for relative paths\n filename = path.normalize(options.filepath).replace(/\\\\/g, '/');\n } else if (options.filename || value.name || value.path) {\n // custom filename take precedence\n // formidable and the browser add a name property\n // fs- and request- streams have path property\n filename = path.basename(options.filename || value.name || value.path);\n } else if (value.readable && value.hasOwnProperty('httpVersion')) {\n // or try http response\n filename = path.basename(value.client._httpMessage.path || '');\n }\n\n if (filename) {\n contentDisposition = 'filename=\"' + filename + '\"';\n }\n\n return contentDisposition;\n};\n\nFormData.prototype._getContentType = function(value, options) {\n\n // use custom content-type above all\n var contentType = options.contentType;\n\n // or try `name` from formidable, browser\n if (!contentType && value.name) {\n contentType = mime.lookup(value.name);\n }\n\n // or try `path` from fs-, request- streams\n if (!contentType && value.path) {\n contentType = mime.lookup(value.path);\n }\n\n // or if it's http-reponse\n if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) {\n contentType = value.headers['content-type'];\n }\n\n // or guess it from the filepath or filename\n if (!contentType && (options.filepath || options.filename)) {\n contentType = mime.lookup(options.filepath || options.filename);\n }\n\n // fallback to the default content type if `value` is not simple value\n if (!contentType && typeof value == 'object') {\n contentType = FormData.DEFAULT_CONTENT_TYPE;\n }\n\n return contentType;\n};\n\nFormData.prototype._multiPartFooter = function() {\n return function(next) {\n var footer = FormData.LINE_BREAK;\n\n var lastPart = (this._streams.length === 0);\n if (lastPart) {\n footer += this._lastBoundary();\n }\n\n next(footer);\n }.bind(this);\n};\n\nFormData.prototype._lastBoundary = function() {\n return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK;\n};\n\nFormData.prototype.getHeaders = function(userHeaders) {\n var header;\n var formHeaders = {\n 'content-type': 'multipart/form-data; boundary=' + this.getBoundary()\n };\n\n for (header in userHeaders) {\n if (userHeaders.hasOwnProperty(header)) {\n formHeaders[header.toLowerCase()] = userHeaders[header];\n }\n }\n\n return formHeaders;\n};\n\nFormData.prototype.getBoundary = function() {\n if (!this._boundary) {\n this._generateBoundary();\n }\n\n return this._boundary;\n};\n\nFormData.prototype.getBuffer = function() {\n var dataBuffer = new Buffer.alloc( 0 );\n var boundary = this.getBoundary();\n\n // Create the form content. Add Line breaks to the end of data.\n for (var i = 0, len = this._streams.length; i < len; i++) {\n if (typeof this._streams[i] !== 'function') {\n\n // Add content to the buffer.\n if(Buffer.isBuffer(this._streams[i])) {\n dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]);\n }else {\n dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]);\n }\n\n // Add break after content.\n if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) {\n dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] );\n }\n }\n }\n\n // Add the footer and return the Buffer object.\n return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] );\n};\n\nFormData.prototype._generateBoundary = function() {\n // This generates a 50 character boundary similar to those used by Firefox.\n // They are optimized for boyer-moore parsing.\n var boundary = '--------------------------';\n for (var i = 0; i < 24; i++) {\n boundary += Math.floor(Math.random() * 10).toString(16);\n }\n\n this._boundary = boundary;\n};\n\n// Note: getLengthSync DOESN'T calculate streams length\n// As workaround one can calculate file size manually\n// and add it as knownLength option\nFormData.prototype.getLengthSync = function() {\n var knownLength = this._overheadLength + this._valueLength;\n\n // Don't get confused, there are 3 \"internal\" streams for each keyval pair\n // so it basically checks if there is any value added to the form\n if (this._streams.length) {\n knownLength += this._lastBoundary().length;\n }\n\n // https://github.com/form-data/form-data/issues/40\n if (!this.hasKnownLength()) {\n // Some async length retrievers are present\n // therefore synchronous length calculation is false.\n // Please use getLength(callback) to get proper length\n this._error(new Error('Cannot calculate proper length in synchronous way.'));\n }\n\n return knownLength;\n};\n\n// Public API to check if length of added values is known\n// https://github.com/form-data/form-data/issues/196\n// https://github.com/form-data/form-data/issues/262\nFormData.prototype.hasKnownLength = function() {\n var hasKnownLength = true;\n\n if (this._valuesToMeasure.length) {\n hasKnownLength = false;\n }\n\n return hasKnownLength;\n};\n\nFormData.prototype.getLength = function(cb) {\n var knownLength = this._overheadLength + this._valueLength;\n\n if (this._streams.length) {\n knownLength += this._lastBoundary().length;\n }\n\n if (!this._valuesToMeasure.length) {\n process.nextTick(cb.bind(this, null, knownLength));\n return;\n }\n\n asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) {\n if (err) {\n cb(err);\n return;\n }\n\n values.forEach(function(length) {\n knownLength += length;\n });\n\n cb(null, knownLength);\n });\n};\n\nFormData.prototype.submit = function(params, cb) {\n var request\n , options\n , defaults = {method: 'post'}\n ;\n\n // parse provided url if it's string\n // or treat it as options object\n if (typeof params == 'string') {\n\n params = parseUrl(params);\n options = populate({\n port: params.port,\n path: params.pathname,\n host: params.hostname,\n protocol: params.protocol\n }, defaults);\n\n // use custom params\n } else {\n\n options = populate(params, defaults);\n // if no port provided use default one\n if (!options.port) {\n options.port = options.protocol == 'https:' ? 443 : 80;\n }\n }\n\n // put that good code in getHeaders to some use\n options.headers = this.getHeaders(params.headers);\n\n // https if specified, fallback to http in any other case\n if (options.protocol == 'https:') {\n request = https.request(options);\n } else {\n request = http.request(options);\n }\n\n // get content length and fire away\n this.getLength(function(err, length) {\n if (err) {\n this._error(err);\n return;\n }\n\n // add content length\n request.setHeader('Content-Length', length);\n\n this.pipe(request);\n if (cb) {\n request.on('error', cb);\n request.on('response', cb.bind(this, null));\n }\n }.bind(this));\n\n return request;\n};\n\nFormData.prototype._error = function(err) {\n if (!this.error) {\n this.error = err;\n this.pause();\n this.emit('error', err);\n }\n};\n\nFormData.prototype.toString = function () {\n return '[object FormData]';\n};\n","// populates missing values\nmodule.exports = function(dst, src) {\n\n Object.keys(src).forEach(function(prop)\n {\n dst[prop] = dst[prop] || src[prop];\n });\n\n return dst;\n};\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","\"use strict\";\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst fs_1 = require(\"fs\");\nconst crypto_1 = require(\"crypto\");\nconst applicationTokenCredentialsBase_1 = require(\"./applicationTokenCredentialsBase\");\nconst authConstants_1 = require(\"../util/authConstants\");\nclass ApplicationTokenCertificateCredentials extends applicationTokenCredentialsBase_1.ApplicationTokenCredentialsBase {\n /**\n * Creates a new ApplicationTokenCredentials object.\n * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}\n * for detailed instructions on creating an Azure Active Directory application.\n * @constructor\n * @param {string} clientId The active directory application client id.\n * @param {string} domain The domain or tenant id containing this application.\n * @param {string} certificate A PEM encoded certificate private key.\n * @param {string} thumbprint A hex encoded thumbprint of the certificate.\n * @param {string} [tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'.\n * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).\n * @param {Environment} [environment] The azure environment to authenticate with.\n * @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal.\n */\n constructor(clientId, domain, certificate, thumbprint, tokenAudience, environment, tokenCache) {\n if (!certificate || typeof certificate.valueOf() !== \"string\") {\n throw new Error(\"certificate must be a non empty string.\");\n }\n if (!thumbprint || typeof thumbprint.valueOf() !== \"string\") {\n throw new Error(\"thumbprint must be a non empty string.\");\n }\n super(clientId, domain, tokenAudience, environment, tokenCache);\n this.certificate = certificate;\n this.thumbprint = thumbprint;\n }\n /**\n * Tries to get the token from cache initially. If that is unsuccessfull then it tries to get the token from ADAL.\n * @returns {Promise} A promise that resolves to TokenResponse and rejects with an Error.\n */\n getToken() {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const tokenResponse = yield this.getTokenFromCache();\n return tokenResponse;\n }\n catch (error) {\n if (error.message.startsWith(authConstants_1.AuthConstants.SDK_INTERNAL_ERROR)) {\n return Promise.reject(error);\n }\n return new Promise((resolve, reject) => {\n const resource = this.getActiveDirectoryResourceId();\n this.authContext.acquireTokenWithClientCertificate(resource, this.clientId, this.certificate, this.thumbprint, (error, tokenResponse) => {\n if (error) {\n return reject(error);\n }\n if (tokenResponse.error || tokenResponse.errorDescription) {\n return reject(tokenResponse);\n }\n return resolve(tokenResponse);\n });\n });\n }\n });\n }\n /**\n * Creates a new instance of ApplicationTokenCertificateCredentials.\n *\n * @param clientId The active directory application client id also known as the SPN (ServicePrincipal Name).\n * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}\n * for an example.\n * @param {string} certificateStringOrFilePath A PEM encoded certificate and private key OR an absolute filepath to the .pem file containing that information. For example:\n * - CertificateString: \"-----BEGIN PRIVATE KEY-----\\n\\n-----END PRIVATE KEY-----\\n-----BEGIN CERTIFICATE-----\\n\\n-----END CERTIFICATE-----\\n\"\n * - CertificateFilePath: **Absolute** file path of the .pem file.\n * @param domain The domain or tenant id containing this application.\n * @param options AzureTokenCredentialsOptions - Object representing optional parameters.\n *\n * @returns ApplicationTokenCertificateCredentials\n */\n static create(clientId, certificateStringOrFilePath, domain, options) {\n if (!certificateStringOrFilePath ||\n typeof certificateStringOrFilePath.valueOf() !== \"string\") {\n throw new Error(\"'certificateStringOrFilePath' must be a non empty string.\");\n }\n if (!certificateStringOrFilePath.startsWith(\"-----BEGIN\")) {\n certificateStringOrFilePath = fs_1.readFileSync(certificateStringOrFilePath, \"utf8\");\n }\n const certificatePattern = /(-+BEGIN CERTIFICATE-+)(\\n\\r?|\\r\\n?)([A-Za-z0-9\\+\\/\\n\\r]+\\=*)(\\n\\r?|\\r\\n?)(-+END CERTIFICATE-+)/;\n const matchCert = certificateStringOrFilePath.match(certificatePattern);\n const rawCertificate = matchCert ? matchCert[3] : \"\";\n if (!rawCertificate) {\n throw new Error(\"Unable to correctly parse the certificate from the value provided in 'certificateStringOrFilePath' \");\n }\n const thumbprint = crypto_1.createHash(\"sha1\")\n .update(Buffer.from(rawCertificate, \"base64\"))\n .digest(\"hex\");\n return new ApplicationTokenCertificateCredentials(clientId, domain, certificateStringOrFilePath, thumbprint, options.tokenAudience, options.environment, options.tokenCache);\n }\n}\nexports.ApplicationTokenCertificateCredentials = ApplicationTokenCertificateCredentials;\n//# sourceMappingURL=applicationTokenCertificateCredentials.js.map","\"use strict\";\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst applicationTokenCredentialsBase_1 = require(\"./applicationTokenCredentialsBase\");\nconst authConstants_1 = require(\"../util/authConstants\");\nclass ApplicationTokenCredentials extends applicationTokenCredentialsBase_1.ApplicationTokenCredentialsBase {\n /**\n * Creates a new ApplicationTokenCredentials object.\n * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}\n * for detailed instructions on creating an Azure Active Directory application.\n * @constructor\n * @param {string} clientId The active directory application client id.\n * @param {string} domain The domain or tenant id containing this application.\n * @param {string} secret The authentication secret for the application.\n * @param {string} [tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'.\n * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).\n * @param {Environment} [environment] The azure environment to authenticate with.\n * @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal.\n */\n constructor(clientId, domain, secret, tokenAudience, environment, tokenCache) {\n if (!secret || typeof secret.valueOf() !== \"string\") {\n throw new Error(\"secret must be a non empty string.\");\n }\n super(clientId, domain, tokenAudience, environment, tokenCache);\n this.secret = secret;\n }\n /**\n * Tries to get the token from cache initially. If that is unsuccessfull then it tries to get the token from ADAL.\n * @returns {Promise} A promise that resolves to TokenResponse and rejects with an Error.\n */\n getToken() {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n const tokenResponse = yield this.getTokenFromCache();\n return tokenResponse;\n }\n catch (error) {\n if (error.message &&\n error.message.startsWith(authConstants_1.AuthConstants.SDK_INTERNAL_ERROR)) {\n return Promise.reject(error);\n }\n const resource = this.getActiveDirectoryResourceId();\n return new Promise((resolve, reject) => {\n this.authContext.acquireTokenWithClientCredentials(resource, this.clientId, this.secret, (error, tokenResponse) => {\n if (error) {\n return reject(error);\n }\n if (tokenResponse.error || tokenResponse.errorDescription) {\n return reject(tokenResponse);\n }\n return resolve(tokenResponse);\n });\n });\n }\n });\n }\n}\nexports.ApplicationTokenCredentials = ApplicationTokenCredentials;\n//# sourceMappingURL=applicationTokenCredentials.js.map","\"use strict\";\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tokenCredentialsBase_1 = require(\"./tokenCredentialsBase\");\nconst authConstants_1 = require(\"../util/authConstants\");\nclass ApplicationTokenCredentialsBase extends tokenCredentialsBase_1.TokenCredentialsBase {\n /**\n * Creates a new ApplicationTokenCredentials object.\n * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}\n * for detailed instructions on creating an Azure Active Directory application.\n * @constructor\n * @param {string} clientId The active directory application client id.\n * @param {string} domain The domain or tenant id containing this application.\n * @param {string} [tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'.\n * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).\n * @param {Environment} [environment] The azure environment to authenticate with.\n * @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal.\n */\n constructor(clientId, domain, tokenAudience, environment, tokenCache) {\n super(clientId, domain, tokenAudience, environment, tokenCache);\n }\n getTokenFromCache() {\n const _super = Object.create(null, {\n getTokenFromCache: { get: () => super.getTokenFromCache }\n });\n return __awaiter(this, void 0, void 0, function* () {\n const self = this;\n // a thin wrapper over the base implementation. try get token from cache, additionaly clean up cache if required.\n try {\n const tokenResponse = yield _super.getTokenFromCache.call(this, undefined);\n return Promise.resolve(tokenResponse);\n }\n catch (error) {\n // Remove the stale token from the tokencache. ADAL gives the same error message \"Entry not found in cache.\"\n // for entry not being present in the cache and for accessToken being expired in the cache. We do not want the token cache\n // to contain the expired token, we clean it up here.\n const status = yield self.removeInvalidItemsFromCache({\n _clientId: self.clientId\n });\n if (status.result) {\n return Promise.reject(error);\n }\n const message = status && status.details && status.details.message\n ? status.details.message\n : status.details;\n return Promise.reject(new Error(authConstants_1.AuthConstants.SDK_INTERNAL_ERROR +\n \" : \" +\n \"critical failure while removing expired token for service principal from token cache. \" +\n message));\n }\n });\n }\n /**\n * Removes invalid items from token cache. This method is different. Here we never reject in case of error.\n * Rather we resolve with an object that says the result is false and error information is provided in\n * the details property of the resolved object. This is done to do better error handling in the above function\n * where removeInvalidItemsFromCache() is called.\n * @param {object} query The query to be used for finding the token for service principal from the cache\n * @returns {result: boolean, details?: Error} resultObject with more info.\n */\n removeInvalidItemsFromCache(query) {\n const self = this;\n return new Promise(resolve => {\n self.tokenCache.find(query, (error, entries) => {\n if (error) {\n return resolve({ result: false, details: error });\n }\n if (entries && entries.length > 0) {\n return new Promise(resolve => {\n return self.tokenCache.remove(entries, (err) => {\n if (err) {\n return resolve({ result: false, details: err });\n }\n return resolve({ result: true });\n });\n });\n }\n else {\n return resolve({ result: true });\n }\n });\n });\n }\n}\nexports.ApplicationTokenCredentialsBase = ApplicationTokenCredentialsBase;\n//# sourceMappingURL=applicationTokenCredentialsBase.js.map","\"use strict\";\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst ms_rest_js_1 = require(\"@azure/ms-rest-js\");\nconst login_1 = require(\"../login\");\n/**\n * Describes the credentials by retrieving token via Azure CLI.\n */\nclass AzureCliCredentials {\n constructor(subscriptionInfo, tokenInfo, \n // tslint:disable-next-line: no-inferrable-types\n resource = \"https://management.azure.com\") {\n /**\n * Azure resource endpoints.\n * - Defaults to Azure Resource Manager from environment: AzureCloud. \"https://management.azure.com\"\n * - For Azure KeyVault: \"https://vault.azure.net\"\n * - For Azure Batch: \"https://batch.core.windows.net\"\n * - For Azure Active Directory Graph: \"https://graph.windows.net\"\n *\n * To get the resource for other clouds:\n * - `az cloud list`\n */\n // tslint:disable-next-line: no-inferrable-types\n this.resource = \"https://management.azure.com\";\n /**\n * The number of seconds within which it is good to renew the token.\n * A constant set to 270 seconds (4.5 minutes).\n */\n this._tokenRenewalMarginInSeconds = 270;\n this.subscriptionInfo = subscriptionInfo;\n this.tokenInfo = tokenInfo;\n this.resource = resource;\n }\n /**\n * Tries to get the new token from Azure CLI, if the token has expired or the subscription has\n * changed else uses the cached accessToken.\n * @return The tokenResponse (tokenType and accessToken are the two important properties).\n */\n getToken() {\n return __awaiter(this, void 0, void 0, function* () {\n if (this._hasTokenExpired() || this._hasSubscriptionChanged() || this._hasResourceChanged()) {\n try {\n // refresh the access token\n this.tokenInfo = yield AzureCliCredentials.getAccessToken({\n subscriptionIdOrName: this.subscriptionInfo.id,\n resource: this.resource\n });\n }\n catch (err) {\n throw new Error(`An error occurred while refreshing the new access ` +\n `token:${err.stderr ? err.stderr : err.message}`);\n }\n }\n const result = {\n accessToken: this.tokenInfo.accessToken,\n tokenType: this.tokenInfo.tokenType,\n expiresOn: this.tokenInfo.expiresOn,\n tenantId: this.tokenInfo.tenant\n };\n return result;\n });\n }\n /**\n * Signs a request with the Authentication header.\n * @param The request to be signed.\n */\n signRequest(webResource) {\n return __awaiter(this, void 0, void 0, function* () {\n const tokenResponse = yield this.getToken();\n webResource.headers.set(ms_rest_js_1.Constants.HeaderConstants.AUTHORIZATION, `${tokenResponse.tokenType} ${tokenResponse.accessToken}`);\n return Promise.resolve(webResource);\n });\n }\n _hasTokenExpired() {\n let result = true;\n const now = Math.floor(Date.now() / 1000);\n if (this.tokenInfo.expiresOn &&\n this.tokenInfo.expiresOn instanceof Date &&\n Math.floor(this.tokenInfo.expiresOn.getTime() / 1000) - now > this._tokenRenewalMarginInSeconds) {\n result = false;\n }\n return result;\n }\n _hasSubscriptionChanged() {\n return this.subscriptionInfo.id !== this.tokenInfo.subscription;\n }\n _parseToken() {\n try {\n const base64Url = this.tokenInfo.accessToken.split(\".\")[1];\n const base64 = decodeURIComponent(Buffer.from(base64Url, \"base64\").toString(\"binary\").split(\"\").map((c) => {\n return \"%\" + (\"00\" + c.charCodeAt(0).toString(16)).slice(-2);\n }).join(\"\"));\n return JSON.parse(base64);\n }\n catch (err) {\n const msg = `An error occurred while parsing the access token: ${err.stack}`;\n throw new Error(msg);\n }\n }\n _isAzureResourceManagerEndpoint(newResource, currentResource) {\n if (newResource.endsWith(\"/\"))\n newResource = newResource.slice(0, -1);\n if (currentResource.endsWith(\"/\"))\n currentResource = currentResource.slice(0, -1);\n return (newResource === \"https://management.core.windows.net\" &&\n currentResource === \"https://management.azure.com\") ||\n (newResource === \"https://management.azure.com\" &&\n currentResource === \"https://management.core.windows.net\");\n }\n _hasResourceChanged() {\n const parsedToken = this._parseToken();\n // normalize the resource string, since it is possible to\n // provide a resource without a trailing slash\n const currentResource = parsedToken.aud && parsedToken.aud.endsWith(\"/\")\n ? parsedToken.aud.slice(0, -1)\n : parsedToken.aud;\n const newResource = this.resource.endsWith(\"/\")\n ? this.resource.slice(0, -1)\n : this.resource;\n const result = this._isAzureResourceManagerEndpoint(newResource, currentResource)\n ? false\n : currentResource !== newResource;\n return result;\n }\n /**\n * Gets the access token for the default or specified subscription.\n * @param options Optional parameters that can be provided to get the access token.\n */\n static getAccessToken(options = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n let cmd = \"account get-access-token\";\n if (options.subscriptionIdOrName) {\n cmd += ` -s \"${options.subscriptionIdOrName}\"`;\n }\n if (options.resource) {\n cmd += ` --resource ${options.resource}`;\n }\n const result = yield login_1.execAz(cmd);\n result.expiresOn = new Date(result.expiresOn);\n return result;\n }\n catch (err) {\n const message = `An error occurred while getting credentials from ` +\n `Azure CLI: ${err.stack}`;\n throw new Error(message);\n }\n });\n }\n /**\n * Gets the subscription from Azure CLI.\n * @param subscriptionIdOrName - The name or id of the subscription for which the information is\n * required.\n */\n static getSubscription(subscriptionIdOrName) {\n return __awaiter(this, void 0, void 0, function* () {\n if (subscriptionIdOrName && (typeof subscriptionIdOrName !== \"string\" || !subscriptionIdOrName.length)) {\n throw new Error(\"'subscriptionIdOrName' must be a non-empty string.\");\n }\n try {\n let cmd = \"account show\";\n if (subscriptionIdOrName) {\n cmd += ` -s \"${subscriptionIdOrName}\"`;\n }\n const result = yield login_1.execAz(cmd);\n return result;\n }\n catch (err) {\n const message = `An error occurred while getting information about the current subscription from ` +\n `Azure CLI: ${err.stack}`;\n throw new Error(message);\n }\n });\n }\n /**\n * Sets the specified subscription as the default subscription for Azure CLI.\n * @param subscriptionIdOrName The name or id of the subsciption that needs to be set as the\n * default subscription.\n */\n static setDefaultSubscription(subscriptionIdOrName) {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n yield login_1.execAz(`account set -s ${subscriptionIdOrName}`);\n }\n catch (err) {\n const message = `An error occurred while setting the current subscription from ` +\n `Azure CLI: ${err.stack}`;\n throw new Error(message);\n }\n });\n }\n /**\n * Returns a list of all the subscriptions from Azure CLI.\n * @param options Optional parameters that can be provided while listing all the subcriptions.\n */\n static listAllSubscriptions(options = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n let subscriptionList = [];\n try {\n let cmd = \"account list\";\n if (options.all) {\n cmd += \" --all\";\n }\n if (options.refresh) {\n cmd += \"--refresh\";\n }\n subscriptionList = yield login_1.execAz(cmd);\n if (subscriptionList && subscriptionList.length) {\n for (const sub of subscriptionList) {\n if (sub.cloudName) {\n sub.environmentName = sub.cloudName;\n delete sub.cloudName;\n }\n }\n }\n return subscriptionList;\n }\n catch (err) {\n const message = `An error occurred while getting a list of all the subscription from ` +\n `Azure CLI: ${err.stack}`;\n throw new Error(message);\n }\n });\n }\n /**\n * Provides credentials that can be used by the JS SDK to interact with Azure via azure cli.\n * **Pre-requisite**\n * - **install azure-cli** . For more information see\n * {@link https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest Install Azure CLI}\n * - **login via `az login`**\n * @param options - Optional parameters that can be provided while creating AzureCliCredentials.\n */\n static create(options = {}) {\n return __awaiter(this, void 0, void 0, function* () {\n const [subscriptinInfo, accessToken] = yield Promise.all([\n AzureCliCredentials.getSubscription(options.subscriptionIdOrName),\n AzureCliCredentials.getAccessToken(options)\n ]);\n return new AzureCliCredentials(subscriptinInfo, accessToken, options.resource);\n });\n }\n}\nexports.AzureCliCredentials = AzureCliCredentials;\n//# sourceMappingURL=azureCliCredentials.js.map","\"use strict\";\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tokenCredentialsBase_1 = require(\"./tokenCredentialsBase\");\nconst authConstants_1 = require(\"../util/authConstants\");\nclass DeviceTokenCredentials extends tokenCredentialsBase_1.TokenCredentialsBase {\n /**\n * Creates a new DeviceTokenCredentials object that gets a new access token using userCodeInfo (contains user_code, device_code)\n * for authenticating user on device.\n *\n * When this credential is used, the script will provide a url and code. The user needs to copy the url and the code, paste it\n * in a browser and authenticate over there. If successful, the script will get the access token.\n *\n * @constructor\n * @param {string} [clientId] The active directory application client id.\n * @param {string} [domain] The domain or tenant id containing this application. Default value is \"common\"\n * @param {string} [username] The user name for account in the form: \"user@example.com\".\n * @param {string} [tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'.\n * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).\n * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}\n * for an example.\n * @param {Environment} [environment] The azure environment to authenticate with. Default environment is \"Azure\" popularly known as \"Public Azure Cloud\".\n * @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal.\n */\n constructor(clientId, domain, username, tokenAudience, environment, tokenCache) {\n if (!username) {\n username = \"user@example.com\";\n }\n if (!domain) {\n domain = authConstants_1.AuthConstants.AAD_COMMON_TENANT;\n }\n if (!clientId) {\n clientId = authConstants_1.AuthConstants.DEFAULT_ADAL_CLIENT_ID;\n }\n super(clientId, domain, tokenAudience, environment, tokenCache);\n this.username = username;\n }\n getToken() {\n // For device auth, this is just getTokenFromCache.\n return this.getTokenFromCache(this.username);\n }\n}\nexports.DeviceTokenCredentials = DeviceTokenCredentials;\n//# sourceMappingURL=deviceTokenCredentials.js.map","\"use strict\";\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst applicationTokenCredentials_1 = require(\"./applicationTokenCredentials\");\nconst applicationTokenCertificateCredentials_1 = require(\"./applicationTokenCertificateCredentials\");\nconst deviceTokenCredentials_1 = require(\"./deviceTokenCredentials\");\nconst msiAppServiceTokenCredentials_1 = require(\"./msiAppServiceTokenCredentials\");\nconst msiTokenCredentials_1 = require(\"./msiTokenCredentials\");\nconst msiVmTokenCredentials_1 = require(\"./msiVmTokenCredentials\");\nconst tokenCredentialsBase_1 = require(\"./tokenCredentialsBase\");\nconst userTokenCredentials_1 = require(\"./userTokenCredentials\");\nconst adal_node_1 = require(\"adal-node\");\nfunction createAuthenticator(credentials) {\n const convertedCredentials = _convert(credentials);\n const authenticator = _createAuthenticatorMapper(convertedCredentials);\n return authenticator;\n}\nexports.createAuthenticator = createAuthenticator;\nfunction _convert(credentials) {\n if (credentials instanceof msiAppServiceTokenCredentials_1.MSIAppServiceTokenCredentials) {\n return new msiAppServiceTokenCredentials_1.MSIAppServiceTokenCredentials({\n msiEndpoint: credentials.msiEndpoint,\n msiSecret: credentials.msiSecret,\n msiApiVersion: credentials.msiApiVersion,\n resource: credentials.resource\n });\n }\n else if (credentials instanceof msiVmTokenCredentials_1.MSIVmTokenCredentials) {\n return new msiVmTokenCredentials_1.MSIVmTokenCredentials({\n resource: credentials.resource,\n msiEndpoint: credentials.msiEndpoint\n });\n }\n else if (credentials instanceof msiTokenCredentials_1.MSITokenCredentials) {\n throw new Error(\"MSI-credentials not one of: MSIVmTokenCredentials, MSIAppServiceTokenCredentials\");\n }\n else {\n return credentials;\n }\n}\nfunction _createAuthenticatorMapper(credentials) {\n return (challenge) => new Promise((resolve, reject) => {\n // Function to take token Response and format a authorization value\n const _formAuthorizationValue = (err, tokenResponse) => {\n if (err) {\n return reject(err);\n }\n if (tokenResponse.error) {\n return reject(tokenResponse.error);\n }\n tokenResponse = tokenResponse;\n // Calculate the value to be set in the request's Authorization header and resume the call.\n const authorizationValue = tokenResponse.tokenType + \" \" + tokenResponse.accessToken;\n return resolve(authorizationValue);\n };\n // Create a new authentication context.\n if (credentials instanceof tokenCredentialsBase_1.TokenCredentialsBase) {\n const context = new adal_node_1.AuthenticationContext(challenge.authorization, true, credentials.authContext && credentials.authContext.cache);\n if (credentials instanceof applicationTokenCredentials_1.ApplicationTokenCredentials) {\n return context.acquireTokenWithClientCredentials(challenge.resource, credentials.clientId, credentials.secret, _formAuthorizationValue);\n }\n else if (credentials instanceof applicationTokenCertificateCredentials_1.ApplicationTokenCertificateCredentials) {\n return context.acquireTokenWithClientCertificate(challenge.resource, credentials.clientId, credentials.certificate, credentials.thumbprint, _formAuthorizationValue);\n }\n else if (credentials instanceof userTokenCredentials_1.UserTokenCredentials) {\n return context.acquireTokenWithUsernamePassword(challenge.resource, credentials.username, credentials.password, credentials.clientId, _formAuthorizationValue);\n }\n else if (credentials instanceof deviceTokenCredentials_1.DeviceTokenCredentials) {\n return context.acquireToken(challenge.resource, credentials.username, credentials.clientId, _formAuthorizationValue);\n }\n }\n else if (credentials instanceof msiTokenCredentials_1.MSITokenCredentials) {\n return credentials.getToken();\n }\n else {\n return reject(new Error(\"credentials must be one of: ApplicationTokenCredentials, UserTokenCredentials, \" +\n \"DeviceTokenCredentials, MSITokenCredentials\"));\n }\n });\n}\n//# sourceMappingURL=keyVaultFactory.js.map","\"use strict\";\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst msiTokenCredentials_1 = require(\"./msiTokenCredentials\");\nconst ms_rest_js_1 = require(\"@azure/ms-rest-js\");\n/**\n * @class MSIAppServiceTokenCredentials\n */\nclass MSIAppServiceTokenCredentials extends msiTokenCredentials_1.MSITokenCredentials {\n /**\n * Creates an instance of MSIAppServiceTokenCredentials.\n * @param {string} [options.msiEndpoint] - The local URL from which your app can request tokens.\n * Either provide this parameter or set the environment variable `MSI_ENDPOINT`.\n * For example: `MSI_ENDPOINT=\"http://127.0.0.1:41741/MSI/token/\"`\n * @param {string} [options.msiSecret] - The secret used in communication between your code and the local MSI agent.\n * Either provide this parameter or set the environment variable `MSI_SECRET`.\n * For example: `MSI_SECRET=\"69418689F1E342DD946CB82994CDA3CB\"`\n * @param {string} [options.resource] - The resource uri or token audience for which the token is needed.\n * For e.g. it can be:\n * - resource management endpoint \"https://management.azure.com/\" (default)\n * - management endpoint \"https://management.core.windows.net/\"\n * @param {string} [options.msiApiVersion] - The api-version of the local MSI agent. Default value is \"2017-09-01\".\n */\n constructor(options) {\n if (!options)\n options = {};\n super(options);\n options.msiEndpoint = options.msiEndpoint || process.env[\"MSI_ENDPOINT\"];\n options.msiSecret = options.msiSecret || process.env[\"MSI_SECRET\"];\n if (!options.msiEndpoint || (options.msiEndpoint && typeof options.msiEndpoint.valueOf() !== \"string\")) {\n throw new Error('Either provide \"msiEndpoint\" as a property of the \"options\" object ' +\n 'or set the environment variable \"MSI_ENDPOINT\" and it must be of type \"string\".');\n }\n if (!options.msiSecret || (options.msiSecret && typeof options.msiSecret.valueOf() !== \"string\")) {\n throw new Error('Either provide \"msiSecret\" as a property of the \"options\" object ' +\n 'or set the environment variable \"MSI_SECRET\" and it must be of type \"string\".');\n }\n if (!options.msiApiVersion) {\n options.msiApiVersion = \"2017-09-01\";\n }\n else if (typeof options.msiApiVersion.valueOf() !== \"string\") {\n throw new Error(\"msiApiVersion must be a uri.\");\n }\n this.msiEndpoint = options.msiEndpoint;\n this.msiSecret = options.msiSecret;\n this.msiApiVersion = options.msiApiVersion;\n }\n /**\n * Prepares and sends a GET request to a service endpoint indicated by the app service, which responds with the access token.\n * @return {Promise} Promise with the tokenResponse (tokenType and accessToken are the two important properties).\n */\n getToken() {\n return __awaiter(this, void 0, void 0, function* () {\n const reqOptions = this.prepareRequestOptions();\n let opRes;\n let result;\n opRes = yield this._httpClient.sendRequest(reqOptions);\n if (opRes.bodyAsText === undefined || opRes.bodyAsText.indexOf(\"ExceptionMessage\") !== -1) {\n throw new Error(`MSI: Failed to retrieve a token from \"${reqOptions.url}\" with an error: ${opRes.bodyAsText}`);\n }\n result = this.parseTokenResponse(opRes.bodyAsText);\n if (!result.tokenType) {\n throw new Error(`Invalid token response, did not find tokenType. Response body is: ${opRes.bodyAsText}`);\n }\n else if (!result.accessToken) {\n throw new Error(`Invalid token response, did not find accessToken. Response body is: ${opRes.bodyAsText}`);\n }\n return result;\n });\n }\n prepareRequestOptions() {\n const endpoint = this.msiEndpoint.endsWith(\"/\") ? this.msiEndpoint : `${this.msiEndpoint}/`;\n const resource = encodeURIComponent(this.resource);\n const getUrl = `${endpoint}?resource=${resource}&api-version=${this.msiApiVersion}`;\n const reqOptions = {\n url: getUrl,\n headers: {\n \"secret\": this.msiSecret\n },\n method: \"GET\"\n };\n const webResource = new ms_rest_js_1.WebResource();\n return webResource.prepare(reqOptions);\n }\n}\nexports.MSIAppServiceTokenCredentials = MSIAppServiceTokenCredentials;\n//# sourceMappingURL=msiAppServiceTokenCredentials.js.map","\"use strict\";\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst ms_rest_js_1 = require(\"@azure/ms-rest-js\");\nconst authConstants_1 = require(\"../util/authConstants\");\n/**\n * @class MSITokenCredentials - Provides information about managed service identity token credentials.\n * This object can only be used to acquire token on a virtual machine provisioned in Azure with managed service identity.\n */\nclass MSITokenCredentials {\n /**\n * Creates an instance of MSITokenCredentials.\n * @param {object} [options] - Optional parameters\n * @param {string} [options.resource] - The resource uri or token audience for which the token is needed.\n * For e.g. it can be:\n * - resource management endpoint \"https://management.azure.com/\"(default)\n * - management endpoint \"https://management.core.windows.net/\"\n */\n constructor(options) {\n if (!options)\n options = {};\n if (!options.resource) {\n options.resource = authConstants_1.AuthConstants.RESOURCE_MANAGER_ENDPOINT;\n }\n else if (typeof options.resource.valueOf() !== \"string\") {\n throw new Error(\"resource must be a uri.\");\n }\n this.resource = options.resource;\n this._httpClient = options.httpClient || new ms_rest_js_1.DefaultHttpClient();\n }\n /**\n * Parses a tokenResponse json string into a object, and converts properties on the first level to camelCase.\n * This method tries to standardize the tokenResponse\n * @param {string} body A json string\n * @return {object} [tokenResponse] The tokenResponse (tokenType and accessToken are the two important properties).\n */\n parseTokenResponse(body) {\n // Docs show different examples of possible MSI responses for different services. https://docs.microsoft.com/en-us/azure/active-directory/managed-service-identity/overview\n // expires_on - is a Date like string in this doc\n // - https://docs.microsoft.com/en-us/azure/app-service/app-service-managed-service-identity#rest-protocol-examples\n // In other doc it is stringified number.\n // - https://docs.microsoft.com/en-us/azure/active-directory/managed-service-identity/tutorial-linux-vm-access-arm#get-an-access-token-using-the-vms-identity-and-use-it-to-call-resource-manager\n const parsedBody = JSON.parse(body);\n parsedBody.accessToken = parsedBody[\"access_token\"];\n delete parsedBody[\"access_token\"];\n parsedBody.tokenType = parsedBody[\"token_type\"];\n delete parsedBody[\"token_type\"];\n if (parsedBody[\"refresh_token\"]) {\n parsedBody.refreshToken = parsedBody[\"refresh_token\"];\n delete parsedBody[\"refresh_token\"];\n }\n if (parsedBody[\"expires_in\"]) {\n parsedBody.expiresIn = parsedBody[\"expires_in\"];\n if (typeof parsedBody[\"expires_in\"] === \"string\") {\n // normal number as a string '1504130527'\n parsedBody.expiresIn = parseInt(parsedBody[\"expires_in\"], 10);\n }\n delete parsedBody[\"expires_in\"];\n }\n if (parsedBody[\"not_before\"]) {\n parsedBody.notBefore = parsedBody[\"not_before\"];\n if (typeof parsedBody[\"not_before\"] === \"string\") {\n // normal number as a string '1504130527'\n parsedBody.notBefore = parseInt(parsedBody[\"not_before\"], 10);\n }\n delete parsedBody[\"not_before\"];\n }\n if (parsedBody[\"expires_on\"]) {\n parsedBody.expiresOn = parsedBody[\"expires_on\"];\n if (typeof parsedBody[\"expires_on\"] === \"string\") {\n // possibly a Date string '09/14/2017 00:00:00 PM +00:00'\n if (parsedBody[\"expires_on\"].includes(\":\") || parsedBody[\"expires_on\"].includes(\"/\")) {\n parsedBody.expiresOn = new Date(parsedBody[\"expires_on\"], 10);\n }\n else {\n // normal number as a string '1504130527'\n parsedBody.expiresOn = new Date(parseInt(parsedBody[\"expires_on\"], 10));\n }\n }\n delete parsedBody[\"expires_on\"];\n }\n return parsedBody;\n }\n /**\n * Signs a request with the Authentication header.\n *\n * @param {webResource} The WebResource to be signed.\n * @return {Promise} Promise with signed WebResource.\n */\n signRequest(webResource) {\n return __awaiter(this, void 0, void 0, function* () {\n const tokenResponse = yield this.getToken();\n webResource.headers.set(ms_rest_js_1.Constants.HeaderConstants.AUTHORIZATION, `${tokenResponse.tokenType} ${tokenResponse.accessToken}`);\n return Promise.resolve(webResource);\n });\n }\n}\nexports.MSITokenCredentials = MSITokenCredentials;\n//# sourceMappingURL=msiTokenCredentials.js.map","\"use strict\";\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst msiTokenCredentials_1 = require(\"./msiTokenCredentials\");\nconst ms_rest_js_1 = require(\"@azure/ms-rest-js\");\n/**\n * @class MSIVmTokenCredentials\n */\nclass MSIVmTokenCredentials extends msiTokenCredentials_1.MSITokenCredentials {\n constructor(options) {\n if (!options)\n options = {};\n super(options);\n if (!options.msiEndpoint) {\n options.msiEndpoint = \"http://169.254.169.254/metadata/identity/oauth2/token\";\n }\n else if (typeof options.msiEndpoint !== \"string\") {\n throw new Error(\"msiEndpoint must be a string.\");\n }\n const urlBuilder = ms_rest_js_1.URLBuilder.parse(options.msiEndpoint);\n if (!urlBuilder.getScheme()) {\n options.msiEndpoint = `http://${options.msiEndpoint}`;\n }\n if (!options.apiVersion) {\n options.apiVersion = \"2018-02-01\";\n }\n else if (typeof options.apiVersion !== \"string\") {\n throw new Error(\"apiVersion must be a string.\");\n }\n if (!options.httpMethod) {\n options.httpMethod = \"GET\";\n }\n this.apiVersion = options.apiVersion;\n this.msiEndpoint = options.msiEndpoint;\n this.httpMethod = options.httpMethod;\n this.objectId = options.objectId;\n this.clientId = options.clientId;\n this.identityId = options.identityId;\n }\n /**\n * Prepares and sends a POST request to a service endpoint hosted on the Azure VM, which responds with the access token.\n * @return {Promise} Promise with the tokenResponse (tokenType and accessToken are the two important properties).\n */\n getToken() {\n return __awaiter(this, void 0, void 0, function* () {\n const reqOptions = this.prepareRequestOptions();\n let opRes;\n let result;\n opRes = yield this._httpClient.sendRequest(reqOptions);\n result = this.parseTokenResponse(opRes.bodyAsText);\n if (!result.tokenType) {\n throw new Error(`Invalid token response, did not find tokenType. Response body is: ${opRes.bodyAsText}`);\n }\n else if (!result.accessToken) {\n throw new Error(`Invalid token response, did not find accessToken. Response body is: ${opRes.bodyAsText}`);\n }\n return result;\n });\n }\n prepareRequestOptions() {\n const reqOptions = {\n url: this.msiEndpoint,\n headers: {\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n \"Metadata\": \"true\"\n },\n method: this.httpMethod,\n queryParameters: {\n \"api-version\": this.apiVersion,\n \"resource\": this.resource,\n \"object_id\": this.objectId,\n \"client_id\": this.clientId,\n \"mi_res_id\": this.identityId\n }\n };\n const webResource = new ms_rest_js_1.WebResource();\n return webResource.prepare(reqOptions);\n }\n}\nexports.MSIVmTokenCredentials = MSIVmTokenCredentials;\n//# sourceMappingURL=msiVmTokenCredentials.js.map","\"use strict\";\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst ms_rest_js_1 = require(\"@azure/ms-rest-js\");\nconst ms_rest_azure_env_1 = require(\"@azure/ms-rest-azure-env\");\nconst adal_node_1 = require(\"adal-node\");\nclass TokenCredentialsBase {\n constructor(clientId, domain, tokenAudience, environment = ms_rest_azure_env_1.Environment.AzureCloud, tokenCache = new adal_node_1.MemoryCache()) {\n this.clientId = clientId;\n this.domain = domain;\n this.tokenAudience = tokenAudience;\n this.environment = environment;\n this.tokenCache = tokenCache;\n if (!clientId || typeof clientId.valueOf() !== \"string\") {\n throw new Error(\"clientId must be a non empty string.\");\n }\n if (!domain || typeof domain.valueOf() !== \"string\") {\n throw new Error(\"domain must be a non empty string.\");\n }\n if (this.tokenAudience === \"graph\" && this.domain.toLowerCase() === \"common\") {\n throw new Error(`${\"If the tokenAudience is specified as \\\"graph\\\" then \\\"domain\\\" cannot be defaulted to \\\"commmon\\\" tenant.\\\n It must be the actual tenant (preferrably a string in a guid format).\"}`);\n }\n const authorityUrl = this.environment.activeDirectoryEndpointUrl + this.domain;\n this.authContext = new adal_node_1.AuthenticationContext(authorityUrl, this.environment.validateAuthority, this.tokenCache);\n }\n getActiveDirectoryResourceId() {\n let resource = this.environment.activeDirectoryResourceId;\n if (this.tokenAudience) {\n resource = this.tokenAudience;\n if (this.tokenAudience.toLowerCase() === \"graph\") {\n resource = this.environment.activeDirectoryGraphResourceId;\n }\n else if (this.tokenAudience.toLowerCase() === \"batch\") {\n resource = this.environment.batchResourceId;\n }\n }\n return resource;\n }\n getTokenFromCache(username) {\n const self = this;\n const resource = this.getActiveDirectoryResourceId();\n return new Promise((resolve, reject) => {\n self.authContext.acquireToken(resource, username, self.clientId, (error, tokenResponse) => {\n if (error) {\n return reject(error);\n }\n if (tokenResponse.error || tokenResponse.errorDescription) {\n return reject(tokenResponse);\n }\n return resolve(tokenResponse);\n });\n });\n }\n /**\n * Signs a request with the Authentication header.\n *\n * @param {webResource} The WebResource to be signed.\n * @param {function(error)} callback The callback function.\n * @return {undefined}\n */\n signRequest(webResource) {\n return __awaiter(this, void 0, void 0, function* () {\n const tokenResponse = yield this.getToken();\n webResource.headers.set(ms_rest_js_1.Constants.HeaderConstants.AUTHORIZATION, `${tokenResponse.tokenType} ${tokenResponse.accessToken}`);\n return Promise.resolve(webResource);\n });\n }\n}\nexports.TokenCredentialsBase = TokenCredentialsBase;\n//# sourceMappingURL=tokenCredentialsBase.js.map","\"use strict\";\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst tokenCredentialsBase_1 = require(\"./tokenCredentialsBase\");\nclass UserTokenCredentials extends tokenCredentialsBase_1.TokenCredentialsBase {\n /**\n * Creates a new UserTokenCredentials object.\n *\n * @constructor\n * @param {string} clientId The active directory application client id.\n * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}\n * for an example.\n * @param {string} domain The domain or tenant id containing this application.\n * @param {string} username The user name for the Organization Id account.\n * @param {string} password The password for the Organization Id account.\n * @param {string} [tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'.\n * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).\n * @param {Environment} [environment] The azure environment to authenticate with.\n * @param {object} [tokenCache] The token cache. Default value is the MemoryCache object from adal.\n */\n constructor(clientId, domain, username, password, tokenAudience, environment, tokenCache) {\n if (!clientId || typeof clientId.valueOf() !== \"string\") {\n throw new Error(\"clientId must be a non empty string.\");\n }\n if (!domain || typeof domain.valueOf() !== \"string\") {\n throw new Error(\"domain must be a non empty string.\");\n }\n if (!username || typeof username.valueOf() !== \"string\") {\n throw new Error(\"username must be a non empty string.\");\n }\n if (!password || typeof password.valueOf() !== \"string\") {\n throw new Error(\"password must be a non empty string.\");\n }\n super(clientId, domain, tokenAudience, environment, tokenCache);\n this.username = username;\n this.password = password;\n }\n crossCheckUserNameWithToken(username, userIdFromToken) {\n // to maintain the casing consistency between \"azureprofile.json\" and token cache. (RD 1996587)\n // use the \"userId\" here, which should be the same with \"username\" except the casing.\n return (username.toLowerCase() === userIdFromToken.toLowerCase());\n }\n /**\n * Tries to get the token from cache initially. If that is unsuccessful then it tries to get the token from ADAL.\n * @returns {Promise}\n * {object} [tokenResponse] The tokenResponse (tokenType and accessToken are the two important properties).\n * @memberof UserTokenCredentials\n */\n getToken() {\n return __awaiter(this, void 0, void 0, function* () {\n try {\n return yield this.getTokenFromCache(this.username);\n }\n catch (error) {\n const self = this;\n const resource = this.getActiveDirectoryResourceId();\n return new Promise((resolve, reject) => {\n self.authContext.acquireTokenWithUsernamePassword(resource, self.username, self.password, self.clientId, (error, tokenResponse) => {\n if (error) {\n return reject(error);\n }\n if (tokenResponse.error || tokenResponse.errorDescription) {\n return reject(tokenResponse);\n }\n tokenResponse = tokenResponse;\n if (self.crossCheckUserNameWithToken(self.username, tokenResponse.userId)) {\n return resolve(tokenResponse);\n }\n else {\n return reject(`The userId \"${tokenResponse.userId}\" in access token doesn\"t match the username \"${self.username}\" provided during authentication.`);\n }\n });\n });\n }\n });\n }\n}\nexports.UserTokenCredentials = UserTokenCredentials;\n//# sourceMappingURL=userTokenCredentials.js.map","\"use strict\";\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst adal = require(\"adal-node\");\nconst msRest = require(\"@azure/ms-rest-js\");\nconst child_process_1 = require(\"child_process\");\nconst fs_1 = require(\"fs\");\nconst ms_rest_azure_env_1 = require(\"@azure/ms-rest-azure-env\");\nconst applicationTokenCredentials_1 = require(\"./credentials/applicationTokenCredentials\");\nconst applicationTokenCertificateCredentials_1 = require(\"./credentials/applicationTokenCertificateCredentials\");\nconst deviceTokenCredentials_1 = require(\"./credentials/deviceTokenCredentials\");\nconst userTokenCredentials_1 = require(\"./credentials/userTokenCredentials\");\nconst authConstants_1 = require(\"./util/authConstants\");\nconst subscriptionUtils_1 = require(\"./subscriptionManagement/subscriptionUtils\");\nconst msiVmTokenCredentials_1 = require(\"./credentials/msiVmTokenCredentials\");\nconst msiAppServiceTokenCredentials_1 = require(\"./credentials/msiAppServiceTokenCredentials\");\n/**\n * @constant {Array} managementPlaneTokenAudiences - Urls for management plane token\n * audience across different azure environments.\n */\nconst managementPlaneTokenAudiences = [\n \"https://management.core.windows.net/\",\n \"https://management.core.chinacloudapi.cn/\",\n \"https://management.core.usgovcloudapi.net/\",\n \"https://management.core.cloudapi.de/\",\n \"https://management.azure.com/\",\n \"https://management.core.windows.net\",\n \"https://management.core.chinacloudapi.cn\",\n \"https://management.core.usgovcloudapi.net\",\n \"https://management.core.cloudapi.de\",\n \"https://management.azure.com\"\n];\nfunction turnOnLogging() {\n const log = adal.Logging;\n log.setLoggingOptions({\n level: 3,\n log: function (level, message, error) {\n level;\n console.info(message);\n if (error) {\n console.error(error);\n }\n }\n });\n}\nif (process.env[\"AZURE_ADAL_LOGGING_ENABLED\"]) {\n turnOnLogging();\n}\n/**\n * Provides a UserTokenCredentials object and the list of subscriptions associated with that userId across all the applicable tenants.\n * This method is applicable only for organizational ids that are not 2FA enabled otherwise please use interactive login.\n *\n * @param {string} username The user name for the Organization Id account.\n * @param {string} password The password for the Organization Id account.\n * @param {object} [options] Object representing optional parameters.\n * @param {string} [options.clientId] The active directory application client id.\n * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}\n * for an example.\n * @param {string} [options.tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'.\n * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).\n * @param {string} [options.domain] The domain or tenant id containing this application. Default value \"common\".\n * @param {Environment} [options.environment] The azure environment to authenticate with.\n * @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal.\n *\n * @returns {Promise} A Promise that resolves to AuthResponse that contains \"credentials\" and optional \"subscriptions\" array and rejects with an Error.\n */\nfunction withUsernamePasswordWithAuthResponse(username, password, options) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!options) {\n options = {};\n }\n if (!options.clientId) {\n options.clientId = authConstants_1.AuthConstants.DEFAULT_ADAL_CLIENT_ID;\n }\n if (!options.domain) {\n options.domain = authConstants_1.AuthConstants.AAD_COMMON_TENANT;\n }\n if (!options.environment) {\n options.environment = ms_rest_azure_env_1.Environment.AzureCloud;\n }\n let creds;\n let tenantList = [];\n let subscriptionList = [];\n try {\n creds = new userTokenCredentials_1.UserTokenCredentials(options.clientId, options.domain, username, password, options.tokenAudience, options.environment);\n yield creds.getToken();\n // The token cache gets propulated for all the tenants as a part of building the tenantList.\n tenantList = yield subscriptionUtils_1.buildTenantList(creds);\n subscriptionList = yield _getSubscriptions(creds, tenantList, options.tokenAudience);\n }\n catch (err) {\n return Promise.reject(err);\n }\n return Promise.resolve({ credentials: creds, subscriptions: subscriptionList });\n });\n}\nexports.withUsernamePasswordWithAuthResponse = withUsernamePasswordWithAuthResponse;\n/**\n * Provides an ApplicationTokenCredentials object and the list of subscriptions associated with that servicePrinicpalId/clientId across all the applicable tenants.\n *\n * @param {string} clientId The active directory application client id also known as the SPN (ServicePrincipal Name).\n * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}\n * for an example.\n * @param {string} secret The application secret for the service principal.\n * @param {string} domain The domain or tenant id containing this application.\n * @param {object} [options] Object representing optional parameters.\n * @param {string} [options.tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'.\n * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).\n * @param {Environment} [options.environment] The azure environment to authenticate with.\n * @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal.\n *\n * @returns {Promise} A Promise that resolves to AuthResponse that contains \"credentials\" and optional \"subscriptions\" array and rejects with an Error.\n */\nfunction withServicePrincipalSecretWithAuthResponse(clientId, secret, domain, options) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!options) {\n options = {};\n }\n if (!options.environment) {\n options.environment = ms_rest_azure_env_1.Environment.AzureCloud;\n }\n let creds;\n let subscriptionList = [];\n try {\n creds = new applicationTokenCredentials_1.ApplicationTokenCredentials(clientId, domain, secret, options.tokenAudience, options.environment);\n yield creds.getToken();\n subscriptionList = yield _getSubscriptions(creds, [domain], options.tokenAudience);\n }\n catch (err) {\n return Promise.reject(err);\n }\n return Promise.resolve({ credentials: creds, subscriptions: subscriptionList });\n });\n}\nexports.withServicePrincipalSecretWithAuthResponse = withServicePrincipalSecretWithAuthResponse;\n/**\n * Provides an ApplicationTokenCertificateCredentials object and the list of subscriptions associated with that servicePrinicpalId/clientId across all the applicable tenants.\n *\n * @param {string} clientId The active directory application client id also known as the SPN (ServicePrincipal Name).\n * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}\n * for an example.\n * @param {string} certificateStringOrFilePath A PEM encoded certificate and private key OR an absolute filepath to the .pem file containing that information. For example:\n * - CertificateString: \"-----BEGIN PRIVATE KEY-----\\n\\n-----END PRIVATE KEY-----\\n-----BEGIN CERTIFICATE-----\\n\\n-----END CERTIFICATE-----\\n\"\n * - CertificateFilePath: **Absolute** file path of the .pem file.\n * @param {string} domain The domain or tenant id containing this application.\n * @param {object} [options] Object representing optional parameters.\n * @param {string} [options.tokenAudience] The audience for which the token is requested. Valid values are 'graph', 'batch', or any other resource like 'https://vault.azure.net/'.\n * If tokenAudience is 'graph' then domain should also be provided and its value should not be the default 'common' tenant. It must be a string (preferrably in a guid format).\n * @param {Environment} [options.environment] The azure environment to authenticate with.\n * @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal.\n *\n * @returns {Promise} A Promise that resolves to AuthResponse that contains \"credentials\" and optional \"subscriptions\" array and rejects with an Error.\n */\nfunction withServicePrincipalCertificateWithAuthResponse(clientId, certificateStringOrFilePath, domain, options) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!options) {\n options = {};\n }\n if (!options.environment) {\n options.environment = ms_rest_azure_env_1.Environment.AzureCloud;\n }\n let creds;\n let subscriptionList = [];\n try {\n creds = applicationTokenCertificateCredentials_1.ApplicationTokenCertificateCredentials.create(clientId, certificateStringOrFilePath, domain, options);\n yield creds.getToken();\n subscriptionList = yield _getSubscriptions(creds, [domain], options.tokenAudience);\n }\n catch (err) {\n return Promise.reject(err);\n }\n return Promise.resolve({ credentials: creds, subscriptions: subscriptionList });\n });\n}\nexports.withServicePrincipalCertificateWithAuthResponse = withServicePrincipalCertificateWithAuthResponse;\nfunction validateAuthFileContent(credsObj, filePath) {\n if (!credsObj) {\n throw new Error(\"Please provide a credsObj to validate.\");\n }\n if (!filePath) {\n throw new Error(\"Please provide a filePath.\");\n }\n if (!credsObj.clientId) {\n throw new Error(`\"clientId\" is missing from the auth file: ${filePath}.`);\n }\n if (!credsObj.clientSecret && !credsObj.clientCertificate) {\n throw new Error(`Either \"clientSecret\" or \"clientCertificate\" must be present in the auth file: ${filePath}.`);\n }\n if (!credsObj.subscriptionId) {\n throw new Error(`\"subscriptionId\" is missing from the auth file: ${filePath}.`);\n }\n if (!credsObj.tenantId) {\n throw new Error(`\"tenantId\" is missing from the auth file: ${filePath}.`);\n }\n if (!credsObj.activeDirectoryEndpointUrl) {\n throw new Error(`\"activeDirectoryEndpointUrl\" is missing from the auth file: ${filePath}.`);\n }\n if (!credsObj.resourceManagerEndpointUrl) {\n throw new Error(`\"resourceManagerEndpointUrl\" is missing from the auth file: ${filePath}.`);\n }\n if (!credsObj.activeDirectoryGraphResourceId) {\n throw new Error(`\"activeDirectoryGraphResourceId\" is missing from the auth file: ${filePath}.`);\n }\n if (!credsObj.sqlManagementEndpointUrl) {\n throw new Error(`\"sqlManagementEndpointUrl\" is missing from the auth file: ${filePath}.`);\n }\n}\nfunction foundManagementEndpointUrl(authFileUrl, envUrl) {\n if (!authFileUrl || (authFileUrl && typeof authFileUrl.valueOf() !== \"string\")) {\n throw new Error(\"authFileUrl cannot be null or undefined and must be of type string.\");\n }\n if (!envUrl || (envUrl && typeof envUrl.valueOf() !== \"string\")) {\n throw new Error(\"envUrl cannot be null or undefined and must be of type string.\");\n }\n authFileUrl = authFileUrl.endsWith(\"/\") ? authFileUrl.slice(0, -1) : authFileUrl;\n envUrl = envUrl.endsWith(\"/\") ? envUrl.slice(0, -1) : envUrl;\n return (authFileUrl.toLowerCase() === envUrl.toLowerCase());\n}\n/**\n * Before using this method please install az cli from https://github.com/Azure/azure-cli/releases. Then execute `az ad sp create-for-rbac --sdk-auth > ${yourFilename.json}`.\n * If you want to create the sp for a different cloud/environment then please execute:\n * 1. az cloud list\n * 2. az cloud set –n \n * 3. az ad sp create-for-rbac --sdk-auth > auth.json // create sp with secret\n * **OR**\n * 3. az ad sp create-for-rbac --create-cert --sdk-auth > auth.json // create sp with certificate\n * If the service principal is already created then login with service principal info:\n * 4. az login --service-principal -u -p -t \n * 5. az account show --sdk-auth > auth.json\n *\n * Authenticates using the service principal information provided in the auth file. This method will set\n * the subscriptionId from the auth file to the user provided environment variable in the options\n * parameter or the default \"AZURE_SUBSCRIPTION_ID\".\n *\n * @param {object} [options] - Optional parameters\n * @param {string} [options.filePath] - Absolute file path to the auth file. If not provided\n * then please set the environment variable AZURE_AUTH_LOCATION.\n * @param {string} [options.subscriptionEnvVariableName] - The subscriptionId environment variable\n * name. Default is \"AZURE_SUBSCRIPTION_ID\".\n * @param {function} [optionalCallback] The optional callback.\n *\n * @returns {Promise} A Promise that resolves to AuthResponse that contains \"credentials\" and optional \"subscriptions\" array and rejects with an Error.\n */\nfunction withAuthFileWithAuthResponse(options) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!options)\n options = { filePath: \"\" };\n const filePath = options.filePath || process.env[authConstants_1.AuthConstants.AZURE_AUTH_LOCATION];\n const subscriptionEnvVariableName = options.subscriptionEnvVariableName || \"AZURE_SUBSCRIPTION_ID\";\n if (!filePath) {\n const msg = `Either provide an absolute file path to the auth file or set/export the environment variable - ${authConstants_1.AuthConstants.AZURE_AUTH_LOCATION}.`;\n return Promise.reject(new Error(msg));\n }\n let content, credsObj = {};\n const optionsForSp = {};\n try {\n content = fs_1.readFileSync(filePath, { encoding: \"utf8\" });\n credsObj = JSON.parse(content);\n validateAuthFileContent(credsObj, filePath);\n }\n catch (err) {\n return Promise.reject(err);\n }\n if (!credsObj.managementEndpointUrl) {\n credsObj.managementEndpointUrl = credsObj.resourceManagerEndpointUrl;\n }\n // setting the subscriptionId from auth file to the environment variable\n process.env[subscriptionEnvVariableName] = credsObj.subscriptionId;\n // get the AzureEnvironment or create a new AzureEnvironment based on the info provided in the auth file\n const envFound = {\n name: \"\"\n };\n const envNames = Object.keys(ms_rest_azure_env_1.Environment);\n for (let i = 0; i < envNames.length; i++) {\n const env = envNames[i];\n const environmentObj = ms_rest_azure_env_1.Environment[env];\n if (environmentObj &&\n environmentObj.managementEndpointUrl &&\n foundManagementEndpointUrl(credsObj.managementEndpointUrl, environmentObj.managementEndpointUrl)) {\n envFound.name = environmentObj.name;\n break;\n }\n }\n if (envFound.name) {\n optionsForSp.environment = ms_rest_azure_env_1.Environment[envFound.name];\n }\n else {\n // create a new environment with provided info.\n const envParams = {\n // try to find a logical name or set the filepath as the env name.\n name: credsObj.managementEndpointUrl.match(/.*management\\.core\\.(.*)\\..*/i)[1] || filePath\n };\n const keys = Object.keys(credsObj);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n if (key.match(/^(clientId|clientSecret|clientCertificate|subscriptionId|tenantId)$/ig) === null) {\n if (key === \"activeDirectoryEndpointUrl\" && !key.endsWith(\"/\")) {\n envParams[key] = credsObj[key] + \"/\";\n }\n else {\n envParams[key] = credsObj[key];\n }\n }\n }\n if (!envParams.activeDirectoryResourceId) {\n envParams.activeDirectoryResourceId = credsObj.managementEndpointUrl;\n }\n if (!envParams.portalUrl) {\n envParams.portalUrl = \"https://portal.azure.com\";\n }\n optionsForSp.environment = ms_rest_azure_env_1.Environment.add(envParams);\n }\n if (credsObj.clientSecret) {\n return withServicePrincipalSecretWithAuthResponse(credsObj.clientId, credsObj.clientSecret, credsObj.tenantId, optionsForSp);\n }\n return withServicePrincipalCertificateWithAuthResponse(credsObj.clientId, credsObj.clientCertificate, credsObj.tenantId, optionsForSp);\n });\n}\nexports.withAuthFileWithAuthResponse = withAuthFileWithAuthResponse;\n/**\n * Provides a url and code that needs to be copy and pasted in a browser and authenticated over there. If successful, the user will get a\n * DeviceTokenCredentials object and the list of subscriptions associated with that userId across all the applicable tenants.\n *\n * @param {object} [options] Object representing optional parameters.\n *\n * @param {string} [options.clientId] The active directory application client id.\n * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net}\n * for an example.\n *\n * @param {string} [options.tokenAudience] The audience for which the token is requested. Valid value is \"graph\".If tokenAudience is provided\n * then domain should also be provided its value should not be the default \"common\" tenant. It must be a string (preferrably in a guid format).\n *\n * @param {string} [options.domain] The domain or tenant id containing this application. Default value is \"common\".\n *\n * @param {Environment} [options.environment] The azure environment to authenticate with. Default environment is \"Public Azure\".\n *\n * @param {object} [options.tokenCache] The token cache. Default value is the MemoryCache object from adal.\n *\n * @param {object} [options.language] The language code specifying how the message should be localized to. Default value \"en-us\".\n *\n * @param {object|function} [options.userCodeResponseLogger] A logger that logs the user code response message required for interactive login. When\n * this option is specified the usercode response message will not be logged to console.\n *\n * @param {function} [optionalCallback] The optional callback.\n *\n * @returns {Promise} A Promise that resolves to AuthResponse that contains \"credentials\" and optional \"subscriptions\" array and rejects with an Error.\n */\nfunction withInteractiveWithAuthResponse(options) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!options) {\n options = {};\n }\n if (!options) {\n options = {};\n }\n if (!options.environment) {\n options.environment = ms_rest_azure_env_1.Environment.AzureCloud;\n }\n if (!options.domain) {\n options.domain = authConstants_1.AuthConstants.AAD_COMMON_TENANT;\n }\n if (!options.clientId) {\n options.clientId = authConstants_1.AuthConstants.DEFAULT_ADAL_CLIENT_ID;\n }\n if (!options.tokenCache) {\n options.tokenCache = new adal.MemoryCache();\n }\n if (!options.language) {\n options.language = authConstants_1.AuthConstants.DEFAULT_LANGUAGE;\n }\n if (!options.tokenAudience) {\n options.tokenAudience = options.environment.activeDirectoryResourceId;\n }\n const interactiveOptions = {};\n interactiveOptions.tokenAudience = options.tokenAudience;\n interactiveOptions.environment = options.environment;\n interactiveOptions.domain = options.domain;\n interactiveOptions.clientId = options.clientId;\n interactiveOptions.tokenCache = options.tokenCache;\n interactiveOptions.language = options.language;\n interactiveOptions.userCodeResponseLogger = options.userCodeResponseLogger;\n const authorityUrl = interactiveOptions.environment.activeDirectoryEndpointUrl + interactiveOptions.domain;\n const authContext = new adal.AuthenticationContext(authorityUrl, interactiveOptions.environment.validateAuthority, interactiveOptions.tokenCache);\n interactiveOptions.context = authContext;\n let userCodeResponse;\n let creds;\n function tryAcquireToken(interactiveOptions, resolve, reject) {\n authContext.acquireUserCode(interactiveOptions.tokenAudience, interactiveOptions.clientId, interactiveOptions.language, (err, userCodeRes) => {\n if (err) {\n if (err.error === \"authorization_pending\") {\n setTimeout(() => {\n tryAcquireToken(interactiveOptions, resolve, reject);\n }, 1000);\n }\n else {\n return reject(err);\n }\n }\n userCodeResponse = userCodeRes;\n if (interactiveOptions.userCodeResponseLogger) {\n interactiveOptions.userCodeResponseLogger(userCodeResponse.message);\n }\n else {\n console.log(userCodeResponse.message);\n }\n return resolve(userCodeResponse);\n });\n }\n const getUserCode = new Promise((resolve, reject) => {\n return tryAcquireToken(interactiveOptions, resolve, reject);\n });\n return getUserCode.then(() => {\n return new Promise((resolve, reject) => {\n return authContext.acquireTokenWithDeviceCode(interactiveOptions.tokenAudience, interactiveOptions.clientId, userCodeResponse, (error, tokenResponse) => {\n if (error) {\n return reject(error);\n }\n interactiveOptions.userName = tokenResponse.userId;\n interactiveOptions.authorizationScheme = tokenResponse.tokenType;\n try {\n creds = new deviceTokenCredentials_1.DeviceTokenCredentials(interactiveOptions.clientId, interactiveOptions.domain, interactiveOptions.userName, interactiveOptions.tokenAudience, interactiveOptions.environment, interactiveOptions.tokenCache);\n }\n catch (err) {\n return reject(err);\n }\n return resolve(creds);\n });\n });\n }).then((creds) => {\n return subscriptionUtils_1.buildTenantList(creds);\n }).then((tenants) => {\n return _getSubscriptions(creds, tenants, interactiveOptions.tokenAudience);\n }).then((subscriptions) => {\n return Promise.resolve({ credentials: creds, subscriptions: subscriptions });\n });\n });\n}\nexports.withInteractiveWithAuthResponse = withInteractiveWithAuthResponse;\nfunction withAuthFile(options, callback) {\n if (!callback && typeof options === \"function\") {\n callback = options;\n options = undefined;\n }\n const cb = callback;\n if (!callback) {\n return withAuthFileWithAuthResponse(options).then((authRes) => {\n return Promise.resolve(authRes.credentials);\n }).catch((err) => {\n return Promise.reject(err);\n });\n }\n else {\n msRest.promiseToCallback(withAuthFileWithAuthResponse(options))((err, authRes) => {\n if (err) {\n return cb(err);\n }\n return cb(undefined, authRes.credentials, authRes.subscriptions);\n });\n }\n}\nexports.withAuthFile = withAuthFile;\nfunction interactive(options, callback) {\n if (!callback && typeof options === \"function\") {\n callback = options;\n options = undefined;\n }\n const cb = callback;\n if (!callback) {\n return withInteractiveWithAuthResponse(options).then((authRes) => {\n return Promise.resolve(authRes.credentials);\n }).catch((err) => {\n return Promise.reject(err);\n });\n }\n else {\n msRest.promiseToCallback(withInteractiveWithAuthResponse(options))((err, authRes) => {\n if (err) {\n return cb(err);\n }\n return cb(undefined, authRes.credentials, authRes.subscriptions);\n });\n }\n}\nexports.interactive = interactive;\nfunction withServicePrincipalSecret(clientId, secret, domain, options, callback) {\n if (!callback && typeof options === \"function\") {\n callback = options;\n options = undefined;\n }\n const cb = callback;\n if (!callback) {\n return withServicePrincipalSecretWithAuthResponse(clientId, secret, domain, options).then((authRes) => {\n return Promise.resolve(authRes.credentials);\n }).catch((err) => {\n return Promise.reject(err);\n });\n }\n else {\n msRest.promiseToCallback(withServicePrincipalSecretWithAuthResponse(clientId, secret, domain, options))((err, authRes) => {\n if (err) {\n return cb(err);\n }\n return cb(undefined, authRes.credentials, authRes.subscriptions);\n });\n }\n}\nexports.withServicePrincipalSecret = withServicePrincipalSecret;\nfunction withServicePrincipalCertificate(clientId, certificateStringOrFilePath, domain, options, callback) {\n if (!callback && typeof options === \"function\") {\n callback = options;\n options = undefined;\n }\n const cb = callback;\n if (!callback) {\n return withServicePrincipalCertificateWithAuthResponse(clientId, certificateStringOrFilePath, domain, options).then((authRes) => {\n return Promise.resolve(authRes.credentials);\n }).catch((err) => {\n return Promise.reject(err);\n });\n }\n else {\n msRest.promiseToCallback(withServicePrincipalCertificateWithAuthResponse(clientId, certificateStringOrFilePath, domain, options))((err, authRes) => {\n if (err) {\n return cb(err);\n }\n return cb(undefined, authRes.credentials, authRes.subscriptions);\n });\n }\n}\nexports.withServicePrincipalCertificate = withServicePrincipalCertificate;\nfunction withUsernamePassword(username, password, options, callback) {\n if (!callback && typeof options === \"function\") {\n callback = options;\n options = undefined;\n }\n const cb = callback;\n if (!callback) {\n return withUsernamePasswordWithAuthResponse(username, password, options).then((authRes) => {\n return Promise.resolve(authRes.credentials);\n }).catch((err) => {\n return Promise.reject(err);\n });\n }\n else {\n msRest.promiseToCallback(withUsernamePasswordWithAuthResponse(username, password, options))((err, authRes) => {\n if (err) {\n return cb(err);\n }\n return cb(undefined, authRes.credentials, authRes.subscriptions);\n });\n }\n}\nexports.withUsernamePassword = withUsernamePassword;\n/**\n * We only need to get the subscription list if the tokenAudience is for a management client.\n */\nfunction _getSubscriptions(creds, tenants, tokenAudience) {\n if (tokenAudience &&\n !managementPlaneTokenAudiences.some((item) => { return item === tokenAudience.toLowerCase(); })) {\n return Promise.resolve(([]));\n }\n return subscriptionUtils_1.getSubscriptionsFromTenants(creds, tenants);\n}\n/**\n * Initializes MSITokenCredentials class and calls getToken and returns a token response.\n *\n * @param {string} domain - required. The tenant id.\n * @param {object} options - Optional parameters\n * @param {string} [options.port] - port on which the MSI service is running on the host VM. Default port is 50342\n * @param {string} [options.resource] - The resource uri or token audience for which the token is needed. Default - \"https://management.azure.com/\"\n * @param {string} [options.aadEndpoint] - The add endpoint for authentication. default - \"https://login.microsoftonline.com\"\n * @param {any} callback - the callback function.\n */\nfunction _withMSI(options) {\n if (!options) {\n options = {};\n }\n return new Promise((resolve, reject) => {\n const creds = new msiVmTokenCredentials_1.MSIVmTokenCredentials(options);\n creds.getToken().then((_tokenResponse) => {\n // We ignore the token response, it's put in the cache.\n return resolve(creds);\n }).catch(error => {\n reject(error);\n });\n });\n}\nfunction loginWithVmMSI(options, callback) {\n if (!callback && typeof options === \"function\") {\n callback = options;\n options = {};\n }\n const cb = callback;\n if (!callback) {\n return _withMSI(options);\n }\n else {\n msRest.promiseToCallback(_withMSI(options))((err, tokenRes) => {\n if (err) {\n return cb(err);\n }\n return cb(undefined, tokenRes);\n });\n }\n}\nexports.loginWithVmMSI = loginWithVmMSI;\n/**\n * Private method\n */\nfunction _withAppServiceMSI(options) {\n if (!options) {\n options = {};\n }\n return new Promise((resolve, reject) => {\n const creds = new msiAppServiceTokenCredentials_1.MSIAppServiceTokenCredentials(options);\n creds.getToken().then((_tokenResponse) => {\n // We ignore the token response, it's put in the cache.\n return resolve(creds);\n }).catch(error => {\n reject(error);\n });\n });\n}\nfunction loginWithAppServiceMSI(options, callback) {\n if (!callback && typeof options === \"function\") {\n callback = options;\n options = {};\n }\n const cb = callback;\n if (!callback) {\n return _withAppServiceMSI(options);\n }\n else {\n msRest.promiseToCallback(_withAppServiceMSI(options))((err, tokenRes) => {\n if (err) {\n return cb(err);\n }\n return cb(undefined, tokenRes);\n });\n }\n}\nexports.loginWithAppServiceMSI = loginWithAppServiceMSI;\n/**\n * Executes the azure cli command and returns the result. It will be `undefined` if the command did\n * not return anything or a `JSON object` if the command did return something.\n * @param cmd The az cli command to execute.\n */\nfunction execAz(cmd) {\n return __awaiter(this, void 0, void 0, function* () {\n return new Promise((resolve, reject) => {\n child_process_1.exec(`az ${cmd} --out json`, { encoding: \"utf8\" }, (error, stdout) => {\n if (error) {\n return reject(error);\n }\n if (stdout) {\n try {\n return resolve(JSON.parse(stdout));\n }\n catch (err) {\n const msg = `An error occured while parsing the output \"${stdout}\", of ` +\n `the cmd \"${cmd}\": ${err.stack}.`;\n return reject(new Error(msg));\n }\n }\n return resolve();\n });\n });\n });\n}\nexports.execAz = execAz;\n//# sourceMappingURL=login.js.map","\"use strict\";\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nvar applicationTokenCredentials_1 = require(\"./credentials/applicationTokenCredentials\");\nexports.ApplicationTokenCredentials = applicationTokenCredentials_1.ApplicationTokenCredentials;\nvar applicationTokenCertificateCredentials_1 = require(\"./credentials/applicationTokenCertificateCredentials\");\nexports.ApplicationTokenCertificateCredentials = applicationTokenCertificateCredentials_1.ApplicationTokenCertificateCredentials;\nvar deviceTokenCredentials_1 = require(\"./credentials/deviceTokenCredentials\");\nexports.DeviceTokenCredentials = deviceTokenCredentials_1.DeviceTokenCredentials;\nvar keyVaultFactory_1 = require(\"./credentials/keyVaultFactory\");\nexports.createAuthenticator = keyVaultFactory_1.createAuthenticator;\nvar msiAppServiceTokenCredentials_1 = require(\"./credentials/msiAppServiceTokenCredentials\");\nexports.MSIAppServiceTokenCredentials = msiAppServiceTokenCredentials_1.MSIAppServiceTokenCredentials;\nvar msiTokenCredentials_1 = require(\"./credentials/msiTokenCredentials\");\nexports.MSITokenCredentials = msiTokenCredentials_1.MSITokenCredentials;\nvar msiVmTokenCredentials_1 = require(\"./credentials/msiVmTokenCredentials\");\nexports.MSIVmTokenCredentials = msiVmTokenCredentials_1.MSIVmTokenCredentials;\nvar tokenCredentialsBase_1 = require(\"./credentials/tokenCredentialsBase\");\nexports.TokenCredentialsBase = tokenCredentialsBase_1.TokenCredentialsBase;\nvar userTokenCredentials_1 = require(\"./credentials/userTokenCredentials\");\nexports.UserTokenCredentials = userTokenCredentials_1.UserTokenCredentials;\nvar authConstants_1 = require(\"./util/authConstants\");\nexports.AuthConstants = authConstants_1.AuthConstants;\nvar azureCliCredentials_1 = require(\"./credentials/azureCliCredentials\");\nexports.AzureCliCredentials = azureCliCredentials_1.AzureCliCredentials;\nvar login_1 = require(\"./login\");\nexports.interactiveLogin = login_1.interactive;\nexports.interactiveLoginWithAuthResponse = login_1.withInteractiveWithAuthResponse;\nexports.loginWithUsernamePassword = login_1.withUsernamePassword;\nexports.loginWithUsernamePasswordWithAuthResponse = login_1.withUsernamePasswordWithAuthResponse;\nexports.loginWithServicePrincipalSecret = login_1.withServicePrincipalSecret;\nexports.loginWithServicePrincipalSecretWithAuthResponse = login_1.withServicePrincipalSecretWithAuthResponse;\nexports.loginWithAuthFile = login_1.withAuthFile;\nexports.loginWithAuthFileWithAuthResponse = login_1.withAuthFileWithAuthResponse;\nexports.loginWithVmMSI = login_1.loginWithVmMSI;\nexports.loginWithAppServiceMSI = login_1.loginWithAppServiceMSI;\nexports.loginWithServicePrincipalCertificate = login_1.withServicePrincipalCertificate;\nexports.loginWithServicePrincipalCertificateWithAuthResponse = login_1.withServicePrincipalCertificateWithAuthResponse;\n//# sourceMappingURL=msRestNodeAuth.js.map","\"use strict\";\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst msRest = require(\"@azure/ms-rest-js\");\nconst applicationTokenCredentialsBase_1 = require(\"../credentials/applicationTokenCredentialsBase\");\nconst authConstants_1 = require(\"../util/authConstants\");\n/**\n * Builds an array of tenantIds.\n * @param {TokenCredentialsBase} credentials The credentials.\n * @param {string} apiVersion default value 2016-06-01\n * @returns {Promise} resolves to an array of tenantIds and rejects with an error.\n */\nfunction buildTenantList(credentials, apiVersion = \"2016-06-01\") {\n return __awaiter(this, void 0, void 0, function* () {\n if (credentials.domain && credentials.domain !== authConstants_1.AuthConstants.AAD_COMMON_TENANT) {\n return Promise.resolve([credentials.domain]);\n }\n const client = new msRest.ServiceClient(credentials);\n const baseUrl = credentials.environment.resourceManagerEndpointUrl;\n const reqUrl = `${baseUrl}${baseUrl.endsWith(\"/\") ? \"\" : \"/\"}tenants?api-version=${apiVersion}`;\n const req = {\n url: reqUrl,\n method: \"GET\",\n };\n let res;\n try {\n res = yield client.sendRequest(req);\n }\n catch (err) {\n return Promise.reject(err);\n }\n const result = [];\n const tenants = res.parsedBody;\n for (const tenant in tenants.value) {\n result.push(tenant.tenantId);\n }\n return Promise.resolve(result);\n });\n}\nexports.buildTenantList = buildTenantList;\nfunction getSubscriptionsFromTenants(credentials, tenantList, apiVersion = \"2016-06-01\") {\n return __awaiter(this, void 0, void 0, function* () {\n let subscriptions = [];\n let userType = \"user\";\n let username;\n const originalDomain = credentials.domain;\n if (credentials instanceof applicationTokenCredentialsBase_1.ApplicationTokenCredentialsBase) {\n userType = \"servicePrincipal\";\n username = credentials.clientId;\n }\n else {\n username = credentials.username;\n }\n for (const tenant of tenantList) {\n credentials.domain = tenant;\n const client = new msRest.ServiceClient(credentials);\n const baseUrl = credentials.environment.resourceManagerEndpointUrl;\n const reqUrl = `${baseUrl}${baseUrl.endsWith(\"/\") ? \"\" : \"/\"}subscriptions?api-version=${apiVersion}`;\n const req = {\n url: reqUrl,\n method: \"GET\",\n };\n let res;\n try {\n res = yield client.sendRequest(req);\n }\n catch (err) {\n return Promise.reject(err);\n }\n const subscriptionList = res.parsedBody.value;\n subscriptions = subscriptions.concat(subscriptionList.map((s) => {\n s.tenantId = tenant;\n s.user = { name: username, type: userType };\n s.environmentName = credentials.environment.name;\n s.name = s.displayName;\n s.id = s.subscriptionId;\n delete s.displayName;\n delete s.subscriptionId;\n delete s.subscriptionPolicies;\n return s;\n }));\n }\n // Reset the original domain.\n credentials.domain = originalDomain;\n return Promise.resolve(subscriptions);\n });\n}\nexports.getSubscriptionsFromTenants = getSubscriptionsFromTenants;\n//# sourceMappingURL=subscriptionUtils.js.map","\"use strict\";\n// Copyright (c) Microsoft Corporation. All rights reserved.\n// Licensed under the MIT License. See License.txt in the project root for license information.\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.AuthConstants = {\n \"AAD_COMMON_TENANT\": \"common\",\n \"DEFAULT_ADAL_CLIENT_ID\": \"04b07795-8ddb-461a-bbee-02f9e1bf7b46\",\n \"SDK_INTERNAL_ERROR\": \"SDK_INTERNAL_ERROR\",\n \"DEFAULT_LANGUAGE\": \"en-us\",\n \"AZURE_AUTH_LOCATION\": \"AZURE_AUTH_LOCATION\",\n \"RESOURCE_MANAGER_ENDPOINT\": \"https://management.azure.com/\"\n};\n//# sourceMappingURL=authConstants.js.map","module.exports = exports = abbrev.abbrev = abbrev\n\nabbrev.monkeyPatch = monkeyPatch\n\nfunction monkeyPatch () {\n Object.defineProperty(Array.prototype, 'abbrev', {\n value: function () { return abbrev(this) },\n enumerable: false, configurable: true, writable: true\n })\n\n Object.defineProperty(Object.prototype, 'abbrev', {\n value: function () { return abbrev(Object.keys(this)) },\n enumerable: false, configurable: true, writable: true\n })\n}\n\nfunction abbrev (list) {\n if (arguments.length !== 1 || !Array.isArray(list)) {\n list = Array.prototype.slice.call(arguments, 0)\n }\n for (var i = 0, l = list.length, args = [] ; i < l ; i ++) {\n args[i] = typeof list[i] === \"string\" ? list[i] : String(list[i])\n }\n\n // sort them lexicographically, so that they're next to their nearest kin\n args = args.sort(lexSort)\n\n // walk through each, seeing how much it has in common with the next and previous\n var abbrevs = {}\n , prev = \"\"\n for (var i = 0, l = args.length ; i < l ; i ++) {\n var current = args[i]\n , next = args[i + 1] || \"\"\n , nextMatches = true\n , prevMatches = true\n if (current === next) continue\n for (var j = 0, cl = current.length ; j < cl ; j ++) {\n var curChar = current.charAt(j)\n nextMatches = nextMatches && curChar === next.charAt(j)\n prevMatches = prevMatches && curChar === prev.charAt(j)\n if (!nextMatches && !prevMatches) {\n j ++\n break\n }\n }\n prev = current\n if (j === cl) {\n abbrevs[current] = current\n continue\n }\n for (var a = current.substr(0, j) ; j <= cl ; j ++) {\n abbrevs[a] = current\n a += current.charAt(j)\n }\n }\n return abbrevs\n}\n\nfunction lexSort (a, b) {\n return a === b ? 0 : a > b ? 1 : -1\n}\n","/*\r\n * @copyright\r\n * Copyright © Microsoft Open Technologies, Inc.\r\n *\r\n * All Rights Reserved\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http: *www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\r\n * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\r\n * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A\r\n * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.\r\n *\r\n * See the Apache License, Version 2.0 for the specific language\r\n * governing permissions and limitations under the License.\r\n */\r\n'use strict';\r\n\r\nvar _ = require('underscore');\r\n\r\nvar ac = require('./authentication-context');\r\nvar authParams = require('./authentication-parameters');\r\nvar logging = require('./log');\r\nvar MemoryCache = require('./memory-cache');\r\n\r\nexports = {};\r\n\r\nexports.Logging = logging.Logging;\r\nexports.AuthenticationContext = ac.AuthenticationContext;\r\nexports.setGlobalADALOptions = ac.setGlobalADALOptions;\r\nexports.getGlobalADALOptions = ac.getGlobalADALOptions;\r\nexports.MemoryCache = MemoryCache;\r\n_.extend(exports, authParams);\r\n\r\n/**\r\n * Creates a new AuthenticationContext object. By default the authority will be checked against\r\n * a list of known Azure Active Directory authorities. If the authority is not recognized as\r\n * one of these well known authorities then token acquisition will fail. This behavior can be\r\n * turned off via the validateAuthority parameter below.\r\n * @function\r\n * @param {string} authority A URL that identifies a token authority.\r\n * @param {bool} [validateAuthority] Turns authority validation on or off. This parameter default to true.\r\n * @returns {AuthenticationContext} A new authentication context.\r\n */\r\nexports.createAuthenticationContext = function(authority, validateAuthority) {\r\n return new ac.AuthenticationContext(authority, validateAuthority);\r\n};\r\n\r\nmodule.exports = exports;\r\n","/*\r\n * @copyright\r\n * Copyright © Microsoft Open Technologies, Inc.\r\n *\r\n * All Rights Reserved\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http: *www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\r\n * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\r\n * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A\r\n * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.\r\n *\r\n * See the Apache License, Version 2.0 for the specific language\r\n * governing permissions and limitations under the License.\r\n */\r\n'use strict';\r\n\r\nvar _ = require('underscore');\r\nvar constants = require('./constants');\r\n\r\nvar UserCodeResponseFields = constants.UserCodeResponseFields;\r\n\r\nvar argumentValidation = {\r\n /**\r\n * Throws if the passed in parameter is not a string.\r\n * @param {string} param The parameter to validate.\r\n * @param {string} name The name of the parameter being validated.\r\n * @throws {Error} If the parameter is not a valid string.\r\n */\r\n validateStringParameter : function(param, name) {\r\n if (!param) {\r\n throw new Error('The ' + name + ' parameter is required.');\r\n }\r\n if (!_.isString(param)) {\r\n throw new Error('The ' + name + ' parameter must be of type String.');\r\n }\r\n },\r\n\r\n /**\r\n * Validates that the callback passed in {@link AuthenticationContext.acquireToken} is a function\r\n * @param {AcquireTokenCallback} callback\r\n * @throws {Error} If the callback parameter is not a function\r\n */\r\n validateCallbackType : function(callback) {\r\n if (!callback || !_.isFunction(callback)) {\r\n throw new Error('acquireToken requires a function callback parameter.');\r\n }\r\n }, \r\n\r\n validateUserCodeInfo : function(userCodeInfo) {\r\n if (!userCodeInfo){\r\n throw new Error('The userCodeInfo parameter is required');\r\n }\r\n\r\n if (!userCodeInfo.hasOwnProperty(UserCodeResponseFields.DEVICE_CODE)){\r\n throw new Error('The userCodeInfo is missing device_code');\r\n }\r\n\r\n if (!userCodeInfo.hasOwnProperty(UserCodeResponseFields.INTERVAL)){\r\n throw new Error('The userCodeInfo is missing interval');\r\n }\r\n\r\n if (!userCodeInfo.hasOwnProperty(UserCodeResponseFields.EXPIRES_IN)){\r\n throw new Error('The userCodeInfo is missing expires_in');\r\n }\r\n }\r\n};\r\n\r\nmodule.exports = argumentValidation;\r\n","/*\r\n * @copyright\r\n * Copyright © Microsoft Open Technologies, Inc.\r\n *\r\n * All Rights Reserved\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http: *www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\r\n * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\r\n * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A\r\n * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.\r\n *\r\n * See the Apache License, Version 2.0 for the specific language\r\n * governing permissions and limitations under the License.\r\n */\r\n'use strict';\r\n\r\nvar argument = require('./argument');\r\nvar Authority = require('./authority').Authority;\r\nvar TokenRequest = require('./token-request');\r\nvar CodeRequest = require('./code-request');\r\nvar createLogContext = require('./log').createLogContext;\r\nvar MemoryCache = require('./memory-cache');\r\nvar util = require('./util');\r\nvar constants = require('./constants');\r\n\r\nvar globalADALOptions = {};\r\nvar globalCache = new MemoryCache();\r\n\r\n\r\n/**\r\n * This function is used to add or remove entries from a TokenCache\r\n * @typedef {function} ModifyCacheFunction\r\n * @param {Array} entries An array of entries to either add or remove from the TokenCache\r\n * @param {function} callback A callback function to call when the add or remove operation is complete.\r\n * This function can take a single error argument.\r\n */\r\n\r\n/**\r\n * This function is called by a TokenCache when a find operation completes.\r\n * @callback TokenCacheFindCallback\r\n * @param {Error} [err] If an error occurred during the find operation then it should be passed here.\r\n * @param {Array} [entries] If the find operation was succesful then the matched entries should be returned here.\r\n */\r\n\r\n/**\r\n * This function is called by ADAL to query a TokenCache. The query parameter is\r\n * a flat object which must be compared against entries in the cache. An entry\r\n * matches if it has all of the fields in the query and the values of those fields match\r\n * the values in the query. A matched object may have more fields than the query object.\r\n * @typedef {function} FindCacheFunction\r\n * @param {object} query This object should be compared to cache entries and matches should be returned.\r\n * @param {TokenCacheFindCallback} callback This callback should be called when the find operation is complete.\r\n */\r\n\r\n/**\r\n * This is an interface that can be implemented to provide custom token cache persistence.\r\n * @public\r\n * @class TokenCache\r\n * @property {ModifyCacheFunction} add Called by ADAL when entries should be added to the cache.\r\n * @property {ModifyCacheFunction} remove Called by ADAL when entries should be removed from the cache.\r\n * @property {FindCacheFunction} find Called when ADAL needs to find entries in the cache.\r\n */\r\n\r\n\r\n/**\r\n * Creates a new AuthenticationContext object. By default the authority will be checked against\r\n * a list of known Azure Active Directory authorities. If the authority is not recognized as\r\n * one of these well known authorities then token acquisition will fail. This behavior can be\r\n * turned off via the validateAuthority parameter below.\r\n * @constructor\r\n * @param {string} authority A URL that identifies a token authority.\r\n * @param {bool} [validateAuthority] Turns authority validation on or off. This parameter default to true.\r\n * @param {TokenCache} [cache] Sets the token cache used by this AuthenticationContext instance. If this parameter is not set\r\n * then a default, in memory cache is used. The default in memory cache is global to the process and is\r\n * shared by all AuthenticationContexts that are created with an empty cache parameter. To control the\r\n * scope and lifetime of a cache you can either create a {@link MemoryCache} instance and pass it when\r\n * constructing an AuthenticationContext or implement a custom {@link TokenCache} and pass that. Cache\r\n * instances passed at AuthenticationContext construction time are only used by that instance of\r\n * the AuthenticationContext and are not shared unless it has been manually passed during the\r\n * construction of other AuthenticationContexts.\r\n *\r\n */\r\nfunction AuthenticationContext(authority, validateAuthority, cache) {\r\n var validate = (validateAuthority === undefined || validateAuthority === null || validateAuthority);\r\n\r\n this._authority = new Authority(authority, validate);\r\n this._oauth2client = null;\r\n this._correlationId = null;\r\n this._callContext = { options : globalADALOptions };\r\n this._cache = cache || globalCache;\r\n this._tokenRequestWithUserCode = {};\r\n}\r\n\r\n/**\r\n * Gets the authority url this AuthenticationContext was constructed with.\r\n * @instance\r\n * @memberOf AuthenticationContext\r\n * @type {string}\r\n * @name authority\r\n */\r\nObject.defineProperty(AuthenticationContext.prototype, 'authority', {\r\n get: function () {\r\n return this._authority.url;\r\n }\r\n});\r\n\r\n/**\r\n * Gets/Sets the correlation id that will be used for the next acquireToken request.\r\n * @instance\r\n * @memberOf AuthenticationContext\r\n * @type {string}\r\n * @name correlationId\r\n */\r\nObject.defineProperty(AuthenticationContext.prototype, 'correlationId', {\r\n get: function () {\r\n return this._correlationId;\r\n },\r\n set: function (id) {\r\n this._correlationId = id;\r\n }\r\n});\r\n\r\n/**\r\n * Get/Sets options that are applied to requests generated by this AuthenticationContext instance.\r\n * @instance\r\n * @memberOf AuthenticationContext\r\n * @type {object}\r\n * @name options\r\n */\r\nObject.defineProperty(AuthenticationContext.prototype, 'options', {\r\n get: function() {\r\n return this._callContext.options;\r\n },\r\n set: function (value) {\r\n this._callContext.options = value;\r\n }\r\n});\r\n\r\n/**\r\n * Get the token cache used by this AuthenticationContext instance.\r\n * @instance\r\n * @memberOf AuthenticationContext\r\n * @type {object}\r\n * @name cache\r\n */\r\nObject.defineProperty(AuthenticationContext.prototype, 'cache', {\r\n get: function() {\r\n return this._cache;\r\n },\r\n});\r\n\r\n/**\r\n * This will be returned in case the OAuth 2 service returns an error.\r\n * @typedef ErrorResponse\r\n * @property {string} [error] A server error.\r\n * @property {string} [errorDescription] A description of the error returned.\r\n */\r\n\r\n/**\r\n * Contains tokens and metadata upon successful completion of an acquireToken call.\r\n * @typedef TokenResponse\r\n * @property {string} tokenType The type of token returned.\r\n * @property {string} accessToken The returned access token.\r\n * @property {string} [refreshToken] A refresh token.\r\n * @property {Date} [createdOn] The date on which the access token was created.\r\n * @property {Date} expiresOn The Date on which the access token expires.\r\n * @property {int} expiresIn The amount of time, in seconds, for which the token is valid.\r\n * @property {string} [userId] An id for the user. May be a displayable value if is_user_id_displayable is true.\r\n * @property {bool} [isUserIdDisplayable] Indicates whether the user_id property will be meaningful if displayed to a user.\r\n * @property {string} [tenantId] The identifier of the tenant under which the access token was issued.\r\n * @property {string} [givenName] The given name of the principal represented by the access token.\r\n * @property {string} [familyName] The family name of the principal represented by the access token.\r\n * @property {string} [identityProvider] Identifies the identity provider that issued the access token.\r\n */\r\n\r\n/**\r\n * This is the callback that is passed to all acquireToken variants below.\r\n * @callback AcquireTokenCallback\r\n * @param {Error} [error] If the request fails this parameter will contain an Error object.\r\n * @param {TokenResponse|ErrorResponse} [response] On a succesful request returns a {@link TokenResposne}.\r\n */\r\n\r\n/**\r\n * This function implements code that is common to all acquireToken flows.\r\n * @private\r\n * @param {AcquireTokenCallback} callback\r\n * @param {Function} tokenFunction This is the function to call to actually acquire the token after common flow has completed.\r\n */\r\nAuthenticationContext.prototype._acquireToken = function(callback, tokenFunction) {\r\n var self = this;\r\n this._callContext._logContext = createLogContext(this.correlationId);\r\n this._authority.validate(this._callContext, function(err) {\r\n if (err) {\r\n callback(err);\r\n return;\r\n }\r\n tokenFunction.call(self);\r\n });\r\n};\r\n\r\nAuthenticationContext.prototype._acquireUserCode = function (callback, codeFunction) { \r\n var self = this;\r\n this._callContext._logContext = createLogContext(this.correlationId);\r\n this._authority.validate(this._callContext, function (err) { \r\n if (err) { \r\n callback(err);\r\n return;\r\n } \r\n\r\n codeFunction.call(self);\r\n });\r\n};\r\n\r\n/**\r\n * Gets a token for a given resource.\r\n * @param {string} resource A URI that identifies the resource for which the token is valid.\r\n * @param {string} [userId] The username of the user on behalf this application is authenticating.\r\n * @param {string} [clientId] The OAuth client id of the calling application.\r\n * @param {AcquireTokenCallback} callback The callback function.\r\n */\r\nAuthenticationContext.prototype.acquireToken = function(resource, userId, clientId, callback) {\r\n argument.validateCallbackType(callback);\r\n try {\r\n argument.validateStringParameter(resource, 'resource');\r\n argument.validateStringParameter(clientId, 'clientId');\r\n } catch(err) {\r\n callback(err);\r\n return;\r\n }\r\n\r\n this._acquireToken(callback, function() {\r\n var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource);\r\n tokenRequest.getTokenFromCacheWithRefresh(userId, callback);\r\n });\r\n};\r\n\r\n/**\r\n * Gets a token for a given resource.\r\n * @param {string} resource A URI that identifies the resource for which the token is valid.\r\n * @param {string} username The username of the user on behalf this application is authenticating.\r\n * @param {string} password The password of the user named in the username parameter.\r\n * @param {string} clientId The OAuth client id of the calling application.\r\n * @param {AcquireTokenCallback} callback The callback function.\r\n */\r\nAuthenticationContext.prototype.acquireTokenWithUsernamePassword = function(resource, username, password, clientId, callback) {\r\n argument.validateCallbackType(callback);\r\n try {\r\n argument.validateStringParameter(resource, 'resource');\r\n argument.validateStringParameter(username, 'username');\r\n argument.validateStringParameter(password, 'password');\r\n argument.validateStringParameter(clientId, 'clientId');\r\n } catch(err) {\r\n callback(err);\r\n return;\r\n }\r\n\r\n this._acquireToken(callback, function() {\r\n var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource);\r\n tokenRequest.getTokenWithUsernamePassword(username, password, callback);\r\n });\r\n};\r\n\r\n/**\r\n * Gets a token for a given resource.\r\n * @param {string} resource A URI that identifies the resource for which the token is valid.\r\n * @param {string} clientId The OAuth client id of the calling application.\r\n * @param {string} clientSecret The OAuth client secret of the calling application.\r\n * @param {AcquireTokenCallback} callback The callback function.\r\n */\r\nAuthenticationContext.prototype.acquireTokenWithClientCredentials = function(resource, clientId, clientSecret, callback) {\r\n argument.validateCallbackType(callback);\r\n try {\r\n argument.validateStringParameter(resource, 'resource');\r\n argument.validateStringParameter(clientId, 'clientId');\r\n argument.validateStringParameter(clientSecret, 'clientSecret');\r\n } catch (err) {\r\n callback(err);\r\n return;\r\n }\r\n\r\n this._acquireToken(callback, function() {\r\n var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource);\r\n tokenRequest.getTokenWithClientCredentials(clientSecret, callback);\r\n });\r\n};\r\n\r\n/**\r\n * Gets a token for a given resource.\r\n * @param {string} authorizationCode An authorization code returned from a client.\r\n * @param {string} redirectUri The redirect uri that was used in the authorize call.\r\n * @param {string} resource A URI that identifies the resource for which the token is valid.\r\n * @param {string} clientId The OAuth client id of the calling application.\r\n * @param {string} clientSecret The OAuth client secret of the calling application.\r\n * @param {AcquireTokenCallback} callback The callback function.\r\n */\r\nAuthenticationContext.prototype.acquireTokenWithAuthorizationCode = function(authorizationCode, redirectUri, resource, clientId, clientSecret, callback) {\r\n argument.validateCallbackType(callback);\r\n try {\r\n argument.validateStringParameter(resource, 'resource');\r\n argument.validateStringParameter(authorizationCode, 'authorizationCode');\r\n argument.validateStringParameter(redirectUri, 'redirectUri');\r\n argument.validateStringParameter(clientId, 'clientId');\r\n } catch(err) {\r\n callback(err);\r\n return;\r\n }\r\n\r\n this._acquireToken(callback, function() {\r\n var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource, redirectUri);\r\n tokenRequest.getTokenWithAuthorizationCode(authorizationCode, clientSecret, callback);\r\n });\r\n};\r\n\r\n/**\r\n * Gets a new access token via a previously issued refresh token.\r\n * @param {string} refreshToken A refresh token returned in a tokne response from a previous invocation of acquireToken.\r\n * @param {string} clientId The OAuth client id of the calling application.\r\n * @param {string} [clientSecret] The OAuth client secret of the calling application. (Note: this parameter is a late addition.\r\n * This parameter may be ommitted entirely so that applications built before this change will continue\r\n * to work unchanged.)\r\n * @param {string} resource The OAuth resource for which a token is being request. This parameter is optional and can be set to null.\r\n * @param {AcquireTokenCallback} callback The callback function.\r\n */\r\nAuthenticationContext.prototype.acquireTokenWithRefreshToken = function(refreshToken, clientId, clientSecret, resource, callback) {\r\n // Fix up the arguments. Older clients may pass fewer arguments as the clientSecret paramter did not always exist.\r\n // The code needs to make adjustments for those clients.\r\n var clientSecretPresent = (5 === arguments.length);\r\n var actualClientSecret = clientSecretPresent ? clientSecret : null;\r\n var actualCallback = clientSecretPresent ? arguments[4] : arguments[3];\r\n var actualResource = clientSecretPresent ? arguments[3] : arguments[2];\r\n\r\n argument.validateCallbackType(actualCallback);\r\n try {\r\n argument.validateStringParameter(refreshToken, 'refreshToken');\r\n argument.validateStringParameter(clientId, 'clientId');\r\n } catch(err) {\r\n callback(err);\r\n return;\r\n }\r\n\r\n this._acquireToken(callback, function() {\r\n var tokenRequest = new TokenRequest(this._callContext, this, clientId, actualResource);\r\n tokenRequest.getTokenWithRefreshToken(refreshToken, actualClientSecret, actualCallback);\r\n });\r\n};\r\n\r\n/**\r\n * Gets a new access token using via a certificate credential.\r\n * @param {string} resource A URI that identifies the resource for which the token is valid.\r\n * @param {string} clientId The OAuth client id of the calling application.\r\n * @param {string} certificate A PEM encoded certificate private key.\r\n * @param {string} thumbprint A hex encoded thumbprint of the certificate.\r\n * @param {AcquireTokenCallback} callback The callback function.\r\n */\r\nAuthenticationContext.prototype.acquireTokenWithClientCertificate = function(resource, clientId, certificate, thumbprint, callback) {\r\n argument.validateCallbackType(callback);\r\n try {\r\n argument.validateStringParameter(resource, 'resource');\r\n argument.validateStringParameter(certificate, 'certificate');\r\n argument.validateStringParameter(thumbprint, 'thumbprint');\r\n } catch(err) {\r\n callback(err);\r\n return;\r\n }\r\n\r\n this._acquireToken(callback, function() {\r\n var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource);\r\n tokenRequest.getTokenWithCertificate(certificate, thumbprint, callback);\r\n });\r\n};\r\n\r\n/**\r\n * Gets the userCodeInfo which contains user_code, device_code for authenticating user on device. \r\n * @param {string} resource A URI that identifies the resource for which the device_code and user_code is valid for.\r\n * @param {string} clientId The OAuth client id of the calling application.\r\n * @param {string} language The language code specifying how the message should be localized to. \r\n * @param {AcquireTokenCallback} callback The callback function.\r\n */\r\nAuthenticationContext.prototype.acquireUserCode = function(resource, clientId, language, callback) { \r\n argument.validateCallbackType(callback);\r\n \r\n try { \r\n argument.validateStringParameter(resource, 'resource');\r\n argument.validateStringParameter(clientId, 'clientId');\r\n } catch (err) { \r\n callback(err);\r\n return;\r\n } \r\n\r\n this._acquireUserCode(callback, function () { \r\n var codeRequest = new CodeRequest(this._callContext, this, clientId, resource);\r\n codeRequest.getUserCodeInfo(language, callback); \r\n });\r\n};\r\n\r\n/**\r\n * Gets a new access token using via a device code.\r\n * @note This method doesn't look up the cache, it only stores the returned token into cache. To look up cache before making a new request, \r\n * please use acquireToken. \r\n * @param {string} clientId The OAuth client id of the calling application.\r\n * @param {object} userCodeInfo Contains device_code, retry interval, and expire time for the request for get the token. \r\n * @param {AcquireTokenCallback} callback The callback function.\r\n */\r\nAuthenticationContext.prototype.acquireTokenWithDeviceCode = function(resource, clientId, userCodeInfo, callback){\r\n argument.validateCallbackType(callback);\r\n\r\n try{\r\n argument.validateUserCodeInfo(userCodeInfo);\r\n } catch (err) {\r\n callback(err);\r\n return;\r\n }\r\n\r\n var self = this;\r\n this._acquireToken(callback, function() {\r\n var tokenRequest = new TokenRequest(this._callContext, this, clientId, resource, null);\r\n self._tokenRequestWithUserCode[userCodeInfo[constants.UserCodeResponseFields.DEVICE_CODE]] = tokenRequest;\r\n tokenRequest.getTokenWithDeviceCode(userCodeInfo, callback); \r\n })\r\n};\r\n\r\n/**\r\n * Cancels the polling request to get token with device code. \r\n * @param {object} userCodeInfo Contains device_code, retry interval, and expire time for the request for get the token. \r\n * @param {AcquireTokenCallback} callback The callback function.\r\n */\r\nAuthenticationContext.prototype.cancelRequestToGetTokenWithDeviceCode = function (userCodeInfo, callback) {\r\n argument.validateCallbackType(callback);\r\n\r\n try {\r\n argument.validateUserCodeInfo(userCodeInfo);\r\n } catch (err) {\r\n callback(err);\r\n return;\r\n }\r\n\r\n if (!this._tokenRequestWithUserCode || !this._tokenRequestWithUserCode[userCodeInfo[constants.UserCodeResponseFields.DEVICE_CODE]]) {\r\n callback(new Error('No acquireTokenWithDeviceCodeRequest existed to be cancelled')); \r\n return;\r\n }\r\n\r\n var tokenRequestToBeCancelled = this._tokenRequestWithUserCode[userCodeInfo[constants.UserCodeResponseFields.DEVICE_CODE]];\r\n tokenRequestToBeCancelled.cancelTokenRequestWithDeviceCode();\r\n\r\n delete this._tokenRequestWithUserCode[constants.UserCodeResponseFields.DEVICE_CODE];\r\n};\r\n\r\nvar exports = {\r\n AuthenticationContext : AuthenticationContext,\r\n setGlobalADALOptions : function(options) {\r\n globalADALOptions = options;\r\n },\r\n getGlobalADALOptions : function() {\r\n return globalADALOptions;\r\n }\r\n};\r\n\r\nutil.adalInit();\r\nmodule.exports = exports;\r\n","/*\r\n * @copyright\r\n * Copyright © Microsoft Open Technologies, Inc.\r\n *\r\n * All Rights Reserved\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http: *www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\r\n * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\r\n * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A\r\n * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.\r\n *\r\n * See the Apache License, Version 2.0 for the specific language\r\n * governing permissions and limitations under the License.\r\n */\r\n\r\n'use strict';\r\n\r\nvar request = require('request');\r\n\r\nvar argument = require('./argument');\r\nvar log = require('./log');\r\nvar util = require('./util');\r\nvar HttpErrorCode = require('./constants').HttpError;\r\n\r\n/*\r\n * Constants\r\n */\r\nvar consts = {\r\n AUTHORIZATION_URI : 'authorization_uri',\r\n RESOURCE : 'resource',\r\n WWW_AUTHENTICATE_HEADER : 'www-authenticate'\r\n};\r\n\r\n/**\r\n * The AuthenticationParameters class holds the parameters that are parsed from an OAuth challenge\r\n * in the www-authenticate header.\r\n * @constructor\r\n * @param {string} authorizationUri The URI of an authority that can issues tokens for the\r\n * resource that issued the challenge.\r\n * @param {string} resource The resource for a which a token should be requested from the authority.\r\n */\r\nfunction AuthenticationParameters(authorizationUri, resource) {\r\n this._authorizationUri = authorizationUri;\r\n this._resource = resource;\r\n}\r\n\r\n/**\r\n * The URI of an authority that can issues tokens for the resource that issued the challenge.\r\n * @instance\r\n * @memberOf AuthenticationParameters\r\n * @type {string}\r\n * @name authorizationUri\r\n */\r\nObject.defineProperty(AuthenticationParameters.prototype, 'authorizationUri', {\r\n get : function() {\r\n return this._authorizationUri;\r\n }\r\n});\r\n\r\n/**\r\n * The resource for a which a token should be requested from the authority.\r\n * This property may be undefined if the resource was not returned in the challenge.\r\n * @instance\r\n * @memberOf AuthenticationParameters\r\n * @type {string}\r\n * @name authorizationUri\r\n */\r\nObject.defineProperty(AuthenticationParameters.prototype, 'resource', {\r\n get : function() {\r\n return this._resource;\r\n }\r\n});\r\n\r\nvar exports = {};\r\n\r\n// The 401 challenge is a standard defined in RFC6750, which is based in part on RFC2617.\r\n// The challenge has the following form.\r\n// WWW-Authenticate : Bearer authorization_uri=\"https://login.windows.net/mytenant.com/oauth2/authorize\",Resource_id=\"00000002-0000-0000-c000-000000000000\"\r\n\r\n// This regex is used to validate the structure of the challenge header.\r\n// Match whole structure: ^\\s*Bearer\\s+([^,\\s=\"]+?)=\"([^\"]*?)\"\\s*(,\\s*([^,\\s=\"]+?)=\"([^\"]*?)\"\\s*)*$\r\n// ^ Start at the beginning of the string.\r\n// \\s*Bearer\\s+ Match 'Bearer' surrounded by one or more amount of whitespace.\r\n// ([^,\\s=\"]+?) This cpatures the key which is composed of any characters except comma, whitespace or a quotes.\r\n// = Match the = sign.\r\n// \"([^\"]*?)\" Captures the value can be any number of non quote characters. At this point only the first key value pair as been captured.\r\n// \\s* There can be any amount of white space after the first key value pair.\r\n// ( Start a capture group to retrieve the rest of the key value pairs that are separated by commas.\r\n// \\s* There can be any amount of whitespace before the comma.\r\n// , There must be a comma.\r\n// \\s* There can be any amount of whitespace after the comma.\r\n// (([^,\\s=\"]+?) This will capture the key that comes after the comma. It's made of a series of any character excpet comma, whitespace or quotes.\r\n// = Match the equal sign between the key and value.\r\n// \" Match the opening quote of the value.\r\n// ([^\"]*?) This will capture the value which can be any number of non quote characters.\r\n// \" Match the values closing quote.\r\n// \\s* There can be any amount of whitespace before the next comma.\r\n// )* Close the capture group for key value pairs. There can be any number of these.\r\n// $ The rest of the string can be whitespace but nothing else up to the end of the string.\r\n//\r\n//\r\n// In other some other languages the regex above would be all that was needed. However, in JavaScript the RegExp object does not\r\n// return all of the captures in one go. So the regex above needs to be broken up so that captures can be retrieved\r\n// iteratively.\r\n//\r\n\r\nfunction parseChallenge(challenge) {\r\n // This regex checks the structure of the whole challenge header. The complete\r\n // header needs to be checked for validity before we can be certain that\r\n // we will succeed in pulling out the individual parts.\r\n var bearerChallengeStructureValidation = /^\\s*Bearer\\s+([^,\\s=\"]+?)=\"([^\"]*?)\"\\s*(,\\s*([^,\\s=\"]+?)=\"([^\"]*?)\"\\s*)*$/;\r\n\r\n // This regex pulls out the key and value from the very first pair.\r\n var firstKeyValuePairRegex = /^\\s*Bearer\\s+([^,\\s=\"]+?)=\"([^\"]*?)\"\\s*/;\r\n\r\n // This regex is used to pull out all of the key value pairs after the first one.\r\n // All of these begin with a comma.\r\n var allOtherKeyValuePairRegex = /(?:,\\s*([^,\\s=\"]+?)=\"([^\"]*?)\"\\s*)/g;\r\n\r\n\r\n if (!bearerChallengeStructureValidation.test(challenge)) {\r\n throw new Error('The challenge is not parseable as an RFC6750 OAuth2 challenge');\r\n }\r\n\r\n var challengeParameters = {};\r\n for(var match = firstKeyValuePairRegex.exec(challenge);\r\n match;\r\n match = allOtherKeyValuePairRegex.exec(challenge)) {\r\n\r\n challengeParameters[match[1]] = match[2];\r\n }\r\n\r\n return challengeParameters;\r\n}\r\n\r\nexports.AuthenticationParameters = AuthenticationParameters;\r\n\r\n/**\r\n * Creates an {@link AuthenticationParameters} object from the contents of a\r\n * www-authenticate header received from a HTTP 401 response from a resource server.\r\n * @param {string} challenge The content fo the www-authenticate header.\r\n * @return {AuthenticationParameters} An AuthenticationParameters object containing the parsed values from the header.\r\n */\r\nexports.createAuthenticationParametersFromHeader = function(challenge) {\r\n argument.validateStringParameter(challenge, 'challenge');\r\n\r\n var challengeParameters = parseChallenge(challenge);\r\n\r\n var authorizationUri = challengeParameters[consts.AUTHORIZATION_URI];\r\n if (!authorizationUri) {\r\n throw new Error('Could not find \\'authorization_uri\\' in challenge header.');\r\n }\r\n\r\n var resource = challengeParameters[consts.RESOURCE];\r\n\r\n return new AuthenticationParameters(authorizationUri, resource);\r\n};\r\n\r\n/**\r\n * Create an {@link AuthenticationParameters} object from a node http.IncomingMessage\r\n * object that was created as a result of a request to a resource server. This function\r\n * expects the response to contain a HTTP 401 error code with a www-authenticate\r\n * header.\r\n * @param {http.IncomingMessage} response A response from a http request to a resource server.\r\n * @return {AuthenticationParameters}\r\n */\r\nexports.createAuthenticationParametersFromResponse = function(response) {\r\n if (!response) {\r\n throw new Error('Mising required parameter: response');\r\n }\r\n\r\n if (!response.statusCode) {\r\n throw new Error('The response parameter does not have the expected HTTP statusCode field');\r\n }\r\n\r\n if (HttpErrorCode.UNAUTHORIZED !== response.statusCode) {\r\n throw new Error('The response status code does not correspond to an OAuth challenge. ' +\r\n 'The statusCode is expected to be 401 but is: ' + response.statusCode);\r\n }\r\n\r\n if (!response.headers) {\r\n throw new Error('There were no headers found in the response.');\r\n }\r\n\r\n var challenge = response.headers[consts.WWW_AUTHENTICATE_HEADER];\r\n if (!challenge) {\r\n throw new Error('The response does not contain a WWW-Authenticate header that can be used to determine the authority_uri and resource.');\r\n }\r\n\r\n return exports.createAuthenticationParametersFromHeader(challenge);\r\n};\r\n\r\nfunction validateUrlObject(url) {\r\n if (!url || !url.href) {\r\n throw new Error('Parameter is of wrong type: url');\r\n }\r\n}\r\n\r\n/**\r\n * This is the callback that is passed to all acquireToken variants below.\r\n * @callback CreateAuthenticationParametersCallback\r\n * @memberOf AuthenticationContext\r\n * @param {Error} [error] If the request fails this parameter will contain an Error object.\r\n * @param {AuthenticationParameters} [parameters] On a succesful request returns a {@link AuthenticationParameters}.\r\n */\r\n\r\n/**\r\n * Creates an {@link AuthenticationParameters} object by sending a get request\r\n * to the url passed to this function, and parsing the resulting http 401\r\n * response.\r\n * @param {string|url} url The url of a resource server.\r\n * @param {AuthenticationParameters} callback Called on error or request completion.\r\n * @param {string} [correlationId] An optional correlationId to pass along with the request and to include in any logs.\r\n */\r\nexports.createAuthenticationParametersFromUrl = function(url, callback, correlationId) {\r\n argument.validateCallbackType(callback);\r\n try {\r\n if (!url) {\r\n callback(new Error('Missing required parameter: url'));\r\n return;\r\n }\r\n var challengeUrl;\r\n if ('string' === typeof(url)) {\r\n challengeUrl = url;\r\n } else {\r\n validateUrlObject(url);\r\n challengeUrl = url.href;\r\n }\r\n\r\n var logContext = log.createLogContext(correlationId);\r\n var logger = new log.Logger('AuthenticationParameters', logContext);\r\n\r\n logger.verbose('Attempting to retrieve authentication parameters');\r\n logger.verbose('Attempting to retrieve authentication parameters from: ' + challengeUrl, true);\r\n var options = util.createRequestOptions( { _callContext : { _logContext: logContext } } );\r\n request.get(challengeUrl, options, function(err, response) {\r\n if (err) {\r\n logger.error('Authentication parameters http get failed.', err, true);\r\n callback(err);\r\n return;\r\n }\r\n var parameters;\r\n try {\r\n parameters = exports.createAuthenticationParametersFromResponse(response);\r\n } catch(creationErr) {\r\n logger.error('Unable to parse response in to authentication paramaters.', creationErr, true);\r\n callback(creationErr);\r\n return;\r\n }\r\n callback(null, parameters);\r\n });\r\n } catch(err) {\r\n callback(err);\r\n return;\r\n }\r\n};\r\n\r\nmodule.exports = exports;","/*\r\n * @copyright\r\n * Copyright © Microsoft Open Technologies, Inc.\r\n *\r\n * All Rights Reserved\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http: *www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\r\n * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\r\n * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A\r\n * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.\r\n *\r\n * See the Apache License, Version 2.0 for the specific language\r\n * governing permissions and limitations under the License.\r\n */\r\n'use strict';\r\n\r\nvar request = require('request');\r\nvar url = require('url');\r\nvar _ = require('underscore');\r\n\r\nvar AADConstants = require('./constants').AADConstants;\r\nvar Logger = require('./log').Logger;\r\nvar util = require('./util');\r\n\r\n/**\r\n* Constructs an Authority object with a specific authority URL.\r\n* @private\r\n* @constructor\r\n* @param {string} authorityUrl A URL that identifies a token authority.\r\n* @param {bool} validateAuthority Indicates whether the Authority url should be validated as an actual AAD\r\n* authority. The default is true.\r\n*/\r\nfunction Authority(authorityUrl, validateAuthority) {\r\n this._log = null;\r\n this._url = url.parse(authorityUrl);\r\n this._validateAuthorityUrl();\r\n\r\n this._validated = !validateAuthority;\r\n this._host = null;\r\n this._tenant = null;\r\n this._parseAuthority();\r\n\r\n this._authorizationEndpoint = null;\r\n this._tokenEndpoint = null;\r\n this._deviceCodeEndpoint = null;\r\n this._isAdfsAuthority = (this._tenant.toLowerCase() === \"adfs\");\r\n}\r\n\r\n/**\r\n * The URL of the authority\r\n * @instance\r\n * @type {string}\r\n * @memberOf Authority\r\n * @name url\r\n */\r\nObject.defineProperty(Authority.prototype, 'url', {\r\n get: function() {\r\n return url.format(this._url);\r\n }\r\n});\r\n\r\n/**\r\n * The token endpoint that the authority uses as discovered by instance discovery.\r\n * @instance\r\n * @type {string}\r\n * @memberOf Authority\r\n * @name tokenEndpoint\r\n */\r\nObject.defineProperty(Authority.prototype, 'tokenEndpoint', {\r\n get: function() {\r\n return this._tokenEndpoint;\r\n }\r\n});\r\n\r\nObject.defineProperty(Authority.prototype, 'deviceCodeEndpoint', {\r\n get: function() {\r\n return this._deviceCodeEndpoint;\r\n }\r\n});\r\n\r\n/**\r\n * Checks the authority url to ensure that it meets basic requirements such as being over SSL. If it does not then\r\n * this method will throw if any of the checks fail.\r\n * @private\r\n * @throws {Error} If the authority url fails to pass any validation checks.\r\n */\r\nAuthority.prototype._validateAuthorityUrl = function() {\r\n if (this._url.protocol !== 'https:') {\r\n throw new Error('The authority url must be an https endpoint.');\r\n }\r\n\r\n if (this._url.query) {\r\n throw new Error('The authority url must not have a query string.');\r\n }\r\n};\r\n\r\n/**\r\n * Parse the authority to get the tenant name. The rest of the\r\n * URL is thrown away in favor of one of the endpoints from the validation doc.\r\n * @private\r\n */\r\nAuthority.prototype._parseAuthority = function() {\r\n this._host = this._url.host;\r\n\r\n var pathParts = this._url.pathname.split('/');\r\n this._tenant = pathParts[1];\r\n\r\n if (!this._tenant) {\r\n throw new Error('Could not determine tenant.');\r\n }\r\n};\r\n\r\n/**\r\n * Performs instance discovery based on a simple match against well known authorities.\r\n * @private\r\n * @return {bool} Returns true if the authority is recognized.\r\n */\r\nAuthority.prototype._performStaticInstanceDiscovery = function() {\r\n this._log.verbose('Performing static instance discovery');\r\n\r\n var hostIndex = _.indexOf(AADConstants.WELL_KNOWN_AUTHORITY_HOSTS, this._url.hostname);\r\n var found = hostIndex > -1;\r\n\r\n if (found) {\r\n this._log.verbose('Authority validated via static instance discovery.');\r\n }\r\n\r\n return found;\r\n};\r\n\r\nAuthority.prototype._createAuthorityUrl = function() {\r\n return 'https://' + this._url.host + '/' + encodeURIComponent(this._tenant) + AADConstants.AUTHORIZE_ENDPOINT_PATH;\r\n};\r\n\r\n/**\r\n * Creates an instance discovery endpoint url for the specific authority that this object represents.\r\n * @private\r\n * @param {string} authorityHost The host name of a well known authority.\r\n * @return {URL} The constructed endpoint url.\r\n */\r\nAuthority.prototype._createInstanceDiscoveryEndpointFromTemplate = function(authorityHost) {\r\n var discoveryEndpoint = AADConstants.INSTANCE_DISCOVERY_ENDPOINT_TEMPLATE;\r\n discoveryEndpoint = discoveryEndpoint.replace('{authorize_host}', authorityHost);\r\n discoveryEndpoint = discoveryEndpoint.replace('{authorize_endpoint}', encodeURIComponent(this._createAuthorityUrl()));\r\n return url.parse(discoveryEndpoint);\r\n};\r\n\r\n/**\r\n * Performs instance discovery via a network call to well known authorities.\r\n * @private\r\n * @param {Authority.InstanceDiscoveryCallback} callback The callback function. If succesful,\r\n * this function calls the callback with the\r\n * tenantDiscoveryEndpoint returned by the\r\n * server.\r\n */\r\nAuthority.prototype._performDynamicInstanceDiscovery = function(callback) {\r\n try {\r\n var self = this;\r\n var discoveryEndpoint = this._createInstanceDiscoveryEndpointFromTemplate(AADConstants.WORLD_WIDE_AUTHORITY);\r\n\r\n var getOptions = util.createRequestOptions(self);\r\n\r\n this._log.verbose('Attempting instance discover');\r\n this._log.verbose('Attempting instance discover at: ' + url.format(discoveryEndpoint), true);\r\n request.get(discoveryEndpoint, getOptions, util.createRequestHandler('Instance Discovery', this._log, callback,\r\n function(response, body) {\r\n var discoveryResponse = JSON.parse(body);\r\n\r\n if (discoveryResponse['tenant_discovery_endpoint']) {\r\n callback(null, discoveryResponse['tenant_discovery_endpoint']);\r\n } else {\r\n callback(self._log.createError('Failed to parse instance discovery response'));\r\n }\r\n })\r\n );\r\n } catch(e) {\r\n callback(e);\r\n }\r\n};\r\n\r\n/**\r\n * @callback InstanceDiscoveryCallback\r\n * @private\r\n * @memberOf Authority\r\n * @param {Error} err If an error occurs during instance discovery then it will be returned here.\r\n * @param {string} tenantDiscoveryEndpoint If instance discovery is successful then this will contain the\r\n * tenantDiscoveryEndpoint associated with the authority.\r\n */\r\n\r\n/**\r\n * Determines whether the authority is recognized as a trusted AAD authority.\r\n * @private\r\n * @param {Authority.InstanceDiscoveryCallback} callback The callback function.\r\n */\r\nAuthority.prototype._validateViaInstanceDiscovery = function(callback) {\r\n if (this._performStaticInstanceDiscovery()) {\r\n callback();\r\n } else {\r\n this._performDynamicInstanceDiscovery(callback);\r\n }\r\n};\r\n\r\n/**\r\n * @callback GetOauthEndpointsCallback\r\n * @private\r\n * @memberOf Authority\r\n * @param {Error} error An error if one occurred.\r\n */\r\n\r\n/**\r\n * Given a tenant discovery endpoint this method will attempt to discover the token endpoint. If the\r\n * tenant discovery endpoint is unreachable for some reason then it will fall back to a algorithmic generation of the\r\n * token endpoint url.\r\n * @private\r\n * @param {string} tenantDiscoveryEndpoint The url of the tenant discovery endpoint for this authority.\r\n * @param {Authority.GetOauthEndpointsCallback} callback The callback function.\r\n */\r\nAuthority.prototype._getOAuthEndpoints = function(tenantDiscoveryEndpoint, callback) {\r\n if (this._tokenEndpoint && this._deviceCodeEndpoint) {\r\n callback();\r\n return;\r\n } else {\r\n // fallback to the well known token endpoint path.\r\n if (!this._tokenEndpoint){\r\n this._tokenEndpoint = url.format('https://' + this._url.host + '/' + encodeURIComponent(this._tenant)) + AADConstants.TOKEN_ENDPOINT_PATH;\r\n }\r\n\r\n if (!this._deviceCodeEndpoint){\r\n this._deviceCodeEndpoint = url.format('https://' + this._url.host + '/' + encodeURIComponent(this._tenant)) + AADConstants.DEVICE_ENDPOINT_PATH;\r\n }\r\n\r\n callback();\r\n return;\r\n }\r\n};\r\n\r\n/**\r\n * @callback ValidateCallback\r\n * @memberOf Authority\r\n */\r\n\r\n/**\r\n * Perform validation on the authority represented by this object. In addition to simple validation\r\n * the oauth token endpoint will be retrieved.\r\n * @param {Authority.ValidateCallback} callback The callback function.\r\n */\r\nAuthority.prototype.validate = function(callContext, callback) {\r\n this._log = new Logger('Authority', callContext._logContext);\r\n this._callContext = callContext;\r\n var self = this;\r\n\r\n if (!this._validated) {\r\n this._log.verbose('Performing instance discovery');\r\n this._log.verbose('Performing instance discovery: ' + url.format(this._url), true);\r\n this._validateViaInstanceDiscovery(function(err, tenantDiscoveryEndpoint) {\r\n if (err)\r\n {\r\n callback(err);\r\n } else {\r\n self._validated = true;\r\n self._getOAuthEndpoints(tenantDiscoveryEndpoint, callback);\r\n return;\r\n }\r\n });\r\n } else {\r\n this._log.verbose('Instance discovery/validation has either already been completed or is turned off');\r\n this._log.verbose('Instance discovery/validation has either already been completed or is turned off: ' + url.format(this._url), true);\r\n this._getOAuthEndpoints(null, callback);\r\n return;\r\n }\r\n};\r\n\r\nmodule.exports.Authority = Authority;\r\n","/*\r\n * @copyright\r\n * Copyright © Microsoft Open Technologies, Inc.\r\n *\r\n * All Rights Reserved\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http: *www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\r\n * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\r\n * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A\r\n * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.\r\n *\r\n * See the Apache License, Version 2.0 for the specific language\r\n * governing permissions and limitations under the License.\r\n */\r\n\r\n'use strict';\r\n\r\nvar _ = require('underscore');\r\nvar crypto = require('crypto');\r\nrequire('date-utils'); // Adds a number of convenience methods to the builtin Date object.\r\n\r\nvar Logger = require('./log').Logger;\r\nvar constants = require('./constants');\r\nvar cacheConstants = constants.Cache;\r\nvar TokenResponseFields = constants.TokenResponseFields;\r\n\r\n// TODO: remove this.\r\n// There is a PM requirement that developers be able to look in to the cache and manipulate the cache based on\r\n// the parameters (authority, resource, clientId, userId), in any combination. They must be able find, add, and remove\r\n// tokens based on those parameters. Any default cache that the API supplies must allow for this query pattern.\r\n// This has the following implications:\r\n// The developer must not be required to calculate any special fields, such as hashes or unique keys.\r\n//\r\n// The default cache implementation can not include optimizations that break the previous requirement.\r\n// This means that we can only do complete scans of the data and equality can only be calculated based on\r\n// equality of all of the individual fields.\r\n//\r\n// The cache interface can not make any assumption about the query efficency of the cache nor can\r\n// it help in optimizing those queries.\r\n//\r\n// There is no simple sorting optimization, rather a series of indexes, and index intersection would\r\n// be necessary.\r\n//\r\n// If for some reason the developer tries to update the cache with a new entry that may be a refresh\r\n// token, they will not know that they need to update all of the refresh tokens or they may get strange\r\n// behavior.\r\n//\r\n// Related to the above, there is no definition of a coherent cache. And if there was there would be\r\n// no way for our API to enforce it. What about duplicates?\r\n//\r\n// there be a single cache entry per (authority, resource, clientId)\r\n// tuple, with no special tokens (i.e. MRRT tokens)\r\n// Required cache operations\r\n//\r\n\r\n// Constants\r\nvar METADATA_CLIENTID = '_clientId';\r\nvar METADATA_AUTHORITY = '_authority';\r\n\r\nfunction nop(placeHolder, callback) {\r\n callback();\r\n}\r\n\r\n/*\r\n * This is a place holder cache that does nothing.\r\n */\r\nvar nopCache = {\r\n add : nop,\r\n addMany : nop,\r\n remove : nop,\r\n removeMany : nop,\r\n find : nop\r\n};\r\n\r\nfunction createTokenHash(token) {\r\n var hashAlg = crypto.createHash(cacheConstants.HASH_ALGORITHM);\r\n hashAlg.update(token, 'utf8');\r\n return hashAlg.digest('base64');\r\n}\r\n\r\nfunction createTokenIdMessage(entry) {\r\n var accessTokenHash = createTokenHash(entry[TokenResponseFields.ACCESS_TOKEN]);\r\n var message = 'AccessTokenId: ' + accessTokenHash;\r\n if (entry[TokenResponseFields.REFRESH_TOKEN]) {\r\n var refreshTokenHash = createTokenHash(entry[TokenResponseFields.REFRESH_TOKEN]);\r\n message += ', RefreshTokenId: ' + refreshTokenHash;\r\n }\r\n return message;\r\n}\r\n\r\n/**\r\n * This is the callback that is passed to all acquireToken variants below.\r\n * @callback RefreshEntryFunction\r\n * @memberOf CacheDriver\r\n * @param {object} tokenResponse A token response to refresh.\r\n * @param {string} [resource] The resource for which to obtain the token if it is different from the original token.\r\n * @param {AcquireTokenCallback} callback Called on completion with an error or a new entry to add to the cache.\r\n */\r\n\r\n/**\r\n * Constructs a new CacheDriver object.\r\n * @constructor\r\n * @private\r\n * @param {object} callContext Contains any context information that applies to the request.\r\n * @param {string} authority\r\n * @param {TokenCache} [cache] A token cache to use. If none is passed then the CacheDriver instance\r\n * will not cache.\r\n * @param {RefreshEntryFunction} refreshFunction\r\n */\r\nfunction CacheDriver(callContext, authority, resource, clientId, cache, refreshFunction) {\r\n this._callContext = callContext;\r\n this._log = new Logger('CacheDriver', callContext._logContext);\r\n this._authority = authority;\r\n this._resource = resource;\r\n this._clientId = clientId;\r\n this._cache = cache || nopCache;\r\n this._refreshFunction = refreshFunction;\r\n}\r\n\r\n/**\r\n * This is the callback that is passed to all acquireToken variants below.\r\n * @callback QueryCallback\r\n * @memberOf CacheDriver\r\n * @param {Error} [error] If the request fails this parameter will contain an Error object.\r\n * @param {Array} [response] On a succesful request returns an array of matched entries.\r\n */\r\n\r\n/**\r\n * The cache driver query function. Ensures that all queries are authority specific.\r\n * @param {object} query A query object. Can contain a clientId or userId or both.\r\n * @param {QueryCallback} callback\r\n */\r\nCacheDriver.prototype._find = function(query, callback) {\r\n this._cache.find(query, callback);\r\n};\r\n\r\n/**\r\n * Queries for all entries that might satisfy a request for a cached token.\r\n * @param {object} query A query object. Can contain a clientId or userId or both.\r\n * @param {QueryCallback} callback\r\n */\r\nCacheDriver.prototype._getPotentialEntries = function(query, callback) {\r\n var self = this;\r\n var potentialEntriesQuery = {};\r\n\r\n if (query.clientId) {\r\n potentialEntriesQuery[METADATA_CLIENTID] = query.clientId;\r\n }\r\n if (query.userId) {\r\n potentialEntriesQuery[TokenResponseFields.USER_ID] = query.userId;\r\n }\r\n\r\n this._log.verbose('Looking for potential cache entries:');\r\n this._log.verbose(JSON.stringify(potentialEntriesQuery), true);\r\n this._find(potentialEntriesQuery, function(err, entries) {\r\n self._log.verbose('Found ' + entries.length + ' potential entries.');\r\n callback(err, entries);\r\n return;\r\n });\r\n};\r\n\r\n/**\r\n * Finds all multi resource refresh tokens in the cache.\r\n * Refresh token is bound to userId, clientId. \r\n * @param {QueryCallback} callback\r\n */\r\nCacheDriver.prototype._findMRRTTokensForUser = function(user, callback) {\r\n this._find({ isMRRT : true, userId : user, _clientId : this._clientId}, callback);\r\n};\r\n\r\n/**\r\n * This is the callback that is passed to all acquireToken variants below.\r\n * @callback SingleEntryCallback\r\n * @memberOf CacheDriver\r\n * @param {Error} [error] If the request fails this parameter will contain an Error object.\r\n * @param {object} [response] On a succesful request returns a single cache entry.\r\n */\r\n\r\n\r\n/**\r\n * Finds a single entry that matches the query. If multiple entries are found that satisfy the query\r\n * then an error will be returned.\r\n * @param {object} query A query object.\r\n * @param {SingleEntryCallback} callback\r\n */\r\nCacheDriver.prototype._loadSingleEntryFromCache = function(query, callback) {\r\n var self = this;\r\n this._getPotentialEntries(query, function(err, potentialEntries) {\r\n if (err) {\r\n callback(err);\r\n return;\r\n }\r\n\r\n var returnVal;\r\n var isResourceTenantSpecific;\r\n\r\n if (potentialEntries && 0 < potentialEntries.length) {\r\n var resourceTenantSpecificEntries = _.where(potentialEntries, { resource : self._resource, _authority : self._authority });\r\n\r\n if (!resourceTenantSpecificEntries || 0 === resourceTenantSpecificEntries.length) {\r\n self._log.verbose('No resource specific cache entries found.');\r\n\r\n // There are no resource specific entries. Find an MRRT token.\r\n var mrrtTokens = _.where(potentialEntries, { isMRRT : true });\r\n if (mrrtTokens && mrrtTokens.length > 0) {\r\n self._log.verbose('Found an MRRT token.');\r\n returnVal = mrrtTokens[0];\r\n } else {\r\n self._log.verbose('No MRRT tokens found.');\r\n }\r\n\r\n } else if (resourceTenantSpecificEntries.length === 1) {\r\n self._log.verbose('Resource specific token found.');\r\n returnVal = resourceTenantSpecificEntries[0];\r\n isResourceTenantSpecific = true;\r\n }else {\r\n callback(self._log.createError('More than one token matches the criteria. The result is ambiguous.'));\r\n return;\r\n }\r\n }\r\n if (returnVal) {\r\n self._log.verbose('Returning token from cache lookup');\r\n self._log.verbose('Returning token from cache lookup, ' + createTokenIdMessage(returnVal), true);\r\n }\r\n callback(null, returnVal, isResourceTenantSpecific);\r\n });\r\n};\r\n\r\n/**\r\n * The response from a token refresh request never contains an id_token and therefore no\r\n * userInfo can be created from the response. This function creates a new cache entry\r\n * combining the id_token based info and cache metadata from the cache entry that was refreshed with the\r\n * new tokens in the refresh response.\r\n * @param {object} entry A cache entry corresponding to the resfreshResponse.\r\n * @param {object} refreshResponse The response from a token refresh request for the entry parameter.\r\n * @return {object} A new cache entry.\r\n */\r\nCacheDriver.prototype._createEntryFromRefresh = function(entry, refreshResponse) {\r\n var newEntry = _.clone(entry);\r\n newEntry = _.extend(newEntry, refreshResponse);\r\n\r\n if (entry.isMRRT && this._authority !== entry[METADATA_AUTHORITY]) {\r\n newEntry[METADATA_AUTHORITY] = this._authority;\r\n }\r\n\r\n this._log.verbose('Created new cache entry from refresh response.');\r\n return newEntry;\r\n};\r\n\r\nCacheDriver.prototype._replaceEntry = function(entryToReplace, newEntry, callback) {\r\n var self = this;\r\n this.remove(entryToReplace, function(err) {\r\n if (err) {\r\n callback(err);\r\n return;\r\n }\r\n self.add(newEntry, callback);\r\n });\r\n};\r\n\r\n/**\r\n * Given an expired cache entry refreshes it and updates the cache.\r\n * @param {object} entry A cache entry with an MRRT to refresh for another resource.\r\n * @param {SingleEntryCallback} callback\r\n */\r\nCacheDriver.prototype._refreshExpiredEntry = function(entry, callback) {\r\n var self = this;\r\n this._refreshFunction(entry, null, function(err, tokenResponse) {\r\n if (err) {\r\n callback(err);\r\n return;\r\n }\r\n\r\n var newEntry = self._createEntryFromRefresh(entry, tokenResponse);\r\n self._replaceEntry(entry, newEntry, function(err) {\r\n if (err) {\r\n self._log.error('error refreshing expired token', err, true);\r\n } else {\r\n self._log.info('Returning token refreshed after expiry.');\r\n }\r\n callback(err, newEntry);\r\n });\r\n });\r\n};\r\n\r\n/**\r\n * Given a cache entry with an MRRT will acquire a new token for a new resource via the MRRT, and cache it.\r\n * @param {object} entry A cache entry with an MRRT to refresh for another resource.\r\n * @param {SingleEntryCallback} callback\r\n */\r\nCacheDriver.prototype._acquireNewTokenFromMrrt = function(entry, callback) {\r\n var self = this;\r\n this._refreshFunction(entry, this._resource, function(err, tokenResponse) {\r\n if (err) {\r\n callback(err);\r\n return;\r\n }\r\n\r\n var newEntry = self._createEntryFromRefresh(entry, tokenResponse);\r\n self.add(newEntry, function(err) {\r\n if (err) {\r\n self._log.error('error refreshing mrrt', err, true);\r\n } else {\r\n self._log.info('Returning token derived from mrrt refresh.');\r\n }\r\n callback(err, newEntry);\r\n });\r\n });\r\n};\r\n\r\n/**\r\n * Given a token this function will refresh it if it is either expired, or an MRRT.\r\n * @param {object} entry A cache entry to refresh if necessary.\r\n * @param {Boolean} isResourceSpecific Indicates whether this token is appropriate for the resource for which\r\n * it was requested or whether it is possibly an MRRT token for which\r\n * a resource specific access token should be acquired.\r\n * @param {SingleEntryCallback} callback\r\n */\r\nCacheDriver.prototype._refreshEntryIfNecessary = function(entry, isResourceSpecific, callback) {\r\n var expiryDate = entry[TokenResponseFields.EXPIRES_ON];\r\n\r\n // Add some buffer in to the time comparison to account for clock skew or latency.\r\n var nowPlusBuffer = (new Date()).addMinutes(constants.Misc.CLOCK_BUFFER);\r\n\r\n if (isResourceSpecific && nowPlusBuffer.isAfter(expiryDate)) {\r\n this._log.info('Cached token is expired. Refreshing: ' + expiryDate);\r\n this._refreshExpiredEntry(entry, callback);\r\n return;\r\n } else if (!isResourceSpecific && entry.isMRRT) {\r\n this._log.info('Acquiring new access token from MRRT token.');\r\n this._acquireNewTokenFromMrrt(entry, callback);\r\n return;\r\n } else {\r\n callback(null, entry);\r\n }\r\n};\r\n\r\n/**\r\n * Finds a single entry in the cache that matches the query or fails if more than one match is found.\r\n * @param {object} query A query object\r\n * @param {SingleEntryCallback} callback\r\n */\r\nCacheDriver.prototype.find = function(query, callback) {\r\n var self = this;\r\n query = query || {};\r\n this._log.verbose('finding using query');\r\n this._log.verbose('finding with query:' + JSON.stringify(query), true);\r\n this._loadSingleEntryFromCache(query, function(err, entry, isResourceTenantSpecific) {\r\n if (err) {\r\n callback(err);\r\n return;\r\n }\r\n\r\n if (!entry) {\r\n callback();\r\n return;\r\n }\r\n\r\n self._refreshEntryIfNecessary(entry, isResourceTenantSpecific, function(err, newEntry) {\r\n callback(err, newEntry);\r\n return;\r\n });\r\n });\r\n};\r\n\r\n/**\r\n * Removes a single entry from the cache.\r\n * @param {object} entry The entry to remove.\r\n * @param {Function} callback Called on completion. The first parameter may contain an error.\r\n */\r\nCacheDriver.prototype.remove = function(entry, callback) {\r\n this._log.verbose('Removing entry.');\r\n return this._cache.remove([entry], function(err) {\r\n callback(err);\r\n return;\r\n });\r\n};\r\n\r\n/**\r\n * Removes a collection of entries from the cache in a single batch operation.\r\n * @param {Array} entries An array of cache entries to remove.\r\n * @param {Function} callback This function is called when the operation is complete. Any error is provided as the\r\n * first parameter.\r\n */\r\nCacheDriver.prototype._removeMany = function(entries, callback) {\r\n this._log.verbose('Remove many: ' + entries.length);\r\n this._cache.remove(entries, function(err) {\r\n callback(err);\r\n return;\r\n });\r\n};\r\n\r\n/**\r\n * Adds a collection of entries to the cache in a single batch operation.\r\n * @param {Array} entries An array of entries to add to the cache.\r\n * @param {Function} callback This function is called when the operation is complete. Any error is provided as the\r\n * first parameter.\r\n */\r\nCacheDriver.prototype._addMany = function(entries, callback) {\r\n this._log.verbose('Add many: ' + entries.length);\r\n this._cache.add(entries, function(err) {\r\n callback(err);\r\n return;\r\n });\r\n};\r\n\r\n/*\r\n * Tests whether the passed entry is a multi resource refresh token.\r\n * Somewhat mysteriously the presense of a resource field in a returned\r\n * token response indicates that the response is an MRRT.\r\n * @param {object} entry\r\n * @return {Boolean} true if the entry is an MRRT.\r\n */\r\nfunction isMRRT(entry) {\r\n return entry.resource ? true : false;\r\n}\r\n\r\n/**\r\n * Given an cache entry this function finds all of the MRRT tokens already in the cache\r\n * and updates them with the refresh_token of the passed in entry.\r\n * @param {object} entry The entry from which to get an updated refresh_token\r\n * @param {Function} callback Called back on completion. The first parameter may contain an error.\r\n */\r\nCacheDriver.prototype._updateRefreshTokens = function(entry, callback) {\r\n var self = this;\r\n if (isMRRT(entry)) {\r\n this._findMRRTTokensForUser(entry.userId, function(err, mrrtTokens) {\r\n if (err) {\r\n callback(err);\r\n return;\r\n }\r\n\r\n if (!mrrtTokens || 0 === mrrtTokens.length) {\r\n callback();\r\n return;\r\n }\r\n\r\n self._log.verbose('Updating ' + mrrtTokens.length + ' cached refresh tokens.');\r\n self._removeMany(mrrtTokens, function(err) {\r\n if (err) {\r\n callback(err);\r\n return;\r\n }\r\n\r\n for (var i = 0; i < mrrtTokens.length; i++) {\r\n mrrtTokens[i][TokenResponseFields.REFRESH_TOKEN] = entry[TokenResponseFields.REFRESH_TOKEN];\r\n }\r\n\r\n self._addMany(mrrtTokens, function(err) {\r\n callback(err);\r\n return;\r\n });\r\n });\r\n });\r\n } else {\r\n callback();\r\n return;\r\n }\r\n};\r\n\r\n/**\r\n * Checks to see if the entry has cache metadata already. If it does\r\n * then it probably came from a refresh operation and the metadata\r\n * was copied from the originating entry.\r\n * @param {object} entry The entry to check\r\n * @return {bool} Returns true if the entry has already been augmented\r\n * with cache metadata.\r\n */\r\nCacheDriver.prototype._entryHasMetadata = function(entry) {\r\n return (_.has(entry, METADATA_CLIENTID) && _.has(entry, METADATA_AUTHORITY));\r\n};\r\n\r\nCacheDriver.prototype._augmentEntryWithCacheMetadata = function(entry) {\r\n if (this._entryHasMetadata(entry)) {\r\n return;\r\n }\r\n\r\n if (isMRRT(entry)) {\r\n this._log.verbose('Added entry is MRRT');\r\n entry.isMRRT = true;\r\n } else {\r\n entry.resource = this._resource;\r\n }\r\n\r\n entry[METADATA_CLIENTID] = this._clientId;\r\n entry[METADATA_AUTHORITY] = this._authority;\r\n};\r\n\r\n/**\r\n * Adds a single entry to the cache.\r\n * @param {object} entry The entry to add.\r\n * @param {string} clientId The id of this client app.\r\n * @param {string} resource The id of the resource for which the cached token was obtained.\r\n * @param {Function} callback Called back on completion. The first parameter may contain an error.\r\n */\r\nCacheDriver.prototype.add = function(entry, callback) {\r\n var self = this;\r\n this._log.verbose('Adding entry');\r\n this._log.verbose('Adding entry, ' + createTokenIdMessage(entry));\r\n\r\n this._augmentEntryWithCacheMetadata(entry);\r\n\r\n this._updateRefreshTokens(entry, function(err) {\r\n if (err) {\r\n callback(err);\r\n return;\r\n }\r\n\r\n self._cache.add([entry], function(err) {\r\n callback(err);\r\n return;\r\n });\r\n });\r\n};\r\n\r\nmodule.exports = CacheDriver;","/*\r\n * @copyright\r\n * Copyright © Microsoft Open Technologies, Inc.\r\n *\r\n * All Rights Reserved\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http: *www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\r\n * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\r\n * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A\r\n * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.\r\n *\r\n * See the Apache License, Version 2.0 for the specific language\r\n * governing permissions and limitations under the License.\r\n */\r\n'use strict';\r\n\r\nvar constants = require('./constants');\r\nvar Logger = require('./log').Logger;\r\nvar Mex = require('./mex');\r\nvar OAuth2Client = require('./oauth2client');\r\n\r\nvar OAuth2Parameters = constants.OAuth2.Parameters;\r\nvar TokenResponseFields = constants.TokenResponseFields;\r\nvar OAuth2GrantType = constants.OAuth2.GrantType;\r\nvar OAuth2Scope = constants.OAuth2.Scope;\r\n\r\n/**\r\n * Constructs a new CodeRequest object.\r\n * @constructor\r\n * @private\r\n * @param {object} callContext Contains any context information that applies to the request.\r\n * @param {AuthenticationContext} authenticationContext\r\n * @param {string} resource\r\n * @param {string} clientId\r\n */\r\n// TODO: probably need to modify the parameter list. \r\nfunction CodeRequest(callContext, authenticationContext, clientId, resource) {\r\n this._log = new Logger('DeviceCodeRequest', callContext._logContext);\r\n this._callContext = callContext;\r\n this._authenticationContext = authenticationContext;\r\n this._resource = resource;\r\n this._clientId = clientId;\r\n \r\n // This should be set at the beginning of getToken\r\n // functions that have a userId.\r\n this._userId = null;\r\n};\r\n\r\n/**\r\n * Get user code info. \r\n * @private\r\n * @param {object} oauthParameters containing all the parameters needed to get the user code info. \r\n * @param {callback} callback\r\n */\r\nCodeRequest.prototype._getUserCodeInfo = function (oauthParameters, callback) {\r\n var oauth2Client = this._createOAuth2Client();\r\n oauth2Client.getUserCodeInfo(oauthParameters, callback);\r\n};\r\n\r\nCodeRequest.prototype._createOAuth2Client = function () {\r\n return new OAuth2Client(this._callContext, this._authenticationContext._authority);\r\n};\r\n\r\n/**\r\n * Creates a set of basic, common, OAuthParameters based on values that the CodeRequest was created with.\r\n * @private\r\n * @return {object} containing all the basic parameters. \r\n */\r\nCodeRequest.prototype._createOAuthParameters = function () {\r\n var oauthParameters = {};\r\n \r\n oauthParameters[OAuth2Parameters.CLIENT_ID] = this._clientId;\r\n oauthParameters[OAuth2Parameters.RESOURCE] = this._resource;\r\n\r\n return oauthParameters;\r\n};\r\n\r\n/**\r\n * Get the user code information. \r\n * @param {string} language optional parameter used to get the user code info. \r\n * @param {callback} callback\r\n */\r\nCodeRequest.prototype.getUserCodeInfo = function(language, callback) {\r\n this._log.info('Getting user code info.');\r\n\r\n var oauthParameters = this._createOAuthParameters();\r\n if (language){\r\n oauthParameters[OAuth2Parameters.LANGUAGE] = language;\r\n }\r\n\r\n this._getUserCodeInfo(oauthParameters, callback);\r\n};\r\nmodule.exports = CodeRequest;","/*\r\n * @copyright\r\n * Copyright © Microsoft Open Technologies, Inc.\r\n *\r\n * All Rights Reserved\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http: *www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\r\n * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\r\n * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A\r\n * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.\r\n *\r\n * See the Apache License, Version 2.0 for the specific language\r\n * governing permissions and limitations under the License.\r\n */\r\n'use strict';\r\n\r\nvar Constants = {\r\n OAuth2 : {\r\n Parameters : {\r\n GRANT_TYPE : 'grant_type',\r\n CLIENT_ASSERTION : 'client_assertion',\r\n CLIENT_ASSERTION_TYPE : 'client_assertion_type',\r\n CLIENT_ID : 'client_id',\r\n CLIENT_SECRET : 'client_secret',\r\n REDIRECT_URI : 'redirect_uri',\r\n RESOURCE : 'resource',\r\n CODE : 'code',\r\n SCOPE : 'scope',\r\n ASSERTION : 'assertion',\r\n AAD_API_VERSION : 'api-version',\r\n USERNAME : 'username',\r\n PASSWORD : 'password',\r\n REFRESH_TOKEN : 'refresh_token', \r\n LANGUAGE : 'mkt', \r\n DEVICE_CODE : 'device_code', \r\n },\r\n\r\n GrantType : {\r\n AUTHORIZATION_CODE : 'authorization_code',\r\n REFRESH_TOKEN : 'refresh_token',\r\n CLIENT_CREDENTIALS : 'client_credentials',\r\n JWT_BEARER : 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',\r\n PASSWORD : 'password',\r\n SAML1 : 'urn:ietf:params:oauth:grant-type:saml1_1-bearer',\r\n SAML2 : 'urn:ietf:params:oauth:grant-type:saml2-bearer',\r\n DEVICE_CODE: 'device_code'\r\n },\r\n\r\n ResponseParameters : {\r\n CODE : 'code',\r\n TOKEN_TYPE : 'token_type',\r\n ACCESS_TOKEN : 'access_token',\r\n ID_TOKEN : 'id_token',\r\n REFRESH_TOKEN : 'refresh_token',\r\n CREATED_ON : 'created_on',\r\n EXPIRES_ON : 'expires_on',\r\n EXPIRES_IN : 'expires_in',\r\n RESOURCE : 'resource',\r\n ERROR : 'error',\r\n ERROR_DESCRIPTION : 'error_description'\r\n },\r\n\r\n DeviceCodeResponseParameters : {\r\n USER_CODE : 'user_code', \r\n DEVICE_CODE : 'device_code', \r\n VERIFICATION_URL : 'verification_url',\r\n EXPIRES_IN : 'expires_in', \r\n INTERVAL: 'interval', \r\n MESSAGE: 'message', \r\n ERROR: 'error', \r\n ERROR_DESCRIPTION: 'error_description'\r\n },\r\n\r\n Scope : {\r\n OPENID : 'openid'\r\n },\r\n\r\n IdTokenMap : {\r\n 'tid' : 'tenantId',\r\n 'given_name' : 'givenName',\r\n 'family_name' : 'familyName',\r\n 'idp' : 'identityProvider',\r\n 'oid': 'oid'\r\n }\r\n },\r\n\r\n TokenResponseFields : {\r\n TOKEN_TYPE : 'tokenType',\r\n ACCESS_TOKEN : 'accessToken',\r\n REFRESH_TOKEN : 'refreshToken',\r\n CREATED_ON : 'createdOn',\r\n EXPIRES_ON : 'expiresOn',\r\n EXPIRES_IN : 'expiresIn',\r\n RESOURCE : 'resource',\r\n USER_ID : 'userId',\r\n ERROR : 'error',\r\n ERROR_DESCRIPTION : 'errorDescription'\r\n },\r\n\r\n UserCodeResponseFields : {\r\n USER_CODE : 'userCode', \r\n DEVICE_CODE: 'deviceCode', \r\n VERIFICATION_URL: 'verificationUrl',\r\n EXPIRES_IN: 'expiresIn', \r\n INTERVAL: 'interval', \r\n MESSAGE: 'message', \r\n ERROR: 'error', \r\n ERROR_DESCRIPTION: 'errorDescription'\r\n },\r\n\r\n IdTokenFields : {\r\n USER_ID : 'userId',\r\n IS_USER_ID_DISPLAYABLE : 'isUserIdDisplayable',\r\n TENANT_ID : 'tenantId',\r\n GIVE_NAME : 'givenName',\r\n FAMILY_NAME : 'familyName',\r\n IDENTITY_PROVIDER : 'identityProvider'\r\n },\r\n\r\n Misc : {\r\n MAX_DATE : 0xffffffff,\r\n CLOCK_BUFFER : 5 // In minutes.\r\n },\r\n\r\n Jwt : {\r\n SELF_SIGNED_JWT_LIFETIME : 10, // 10 mins in mins\r\n AUDIENCE : 'aud',\r\n ISSUER : 'iss',\r\n SUBJECT : 'sub',\r\n NOT_BEFORE : 'nbf',\r\n EXPIRES_ON : 'exp',\r\n JWT_ID : 'jti'\r\n },\r\n\r\n AADConstants : {\r\n WORLD_WIDE_AUTHORITY : 'login.windows.net',\r\n WELL_KNOWN_AUTHORITY_HOSTS : ['login.windows.net', 'login.microsoftonline.com', 'login.chinacloudapi.cn', 'login-us.microsoftonline.com', 'login.microsoftonline.de', 'login.microsoftonline.us'],\r\n INSTANCE_DISCOVERY_ENDPOINT_TEMPLATE : 'https://{authorize_host}/common/discovery/instance?authorization_endpoint={authorize_endpoint}&api-version=1.0',\r\n AUTHORIZE_ENDPOINT_PATH : '/oauth2/authorize',\r\n TOKEN_ENDPOINT_PATH : '/oauth2/token', \r\n DEVICE_ENDPOINT_PATH : '/oauth2/devicecode'\r\n },\r\n\r\n UserRealm : {\r\n FederationProtocolType : {\r\n WSFederation : 'wstrust',\r\n SAML2 : 'saml20',\r\n Unknown : 'unknown'\r\n },\r\n\r\n AccountType : {\r\n Federated : 'federated',\r\n Managed : 'managed',\r\n Unknown : 'unknown'\r\n }\r\n },\r\n\r\n Saml : {\r\n TokenTypeV1 : 'urn:oasis:names:tc:SAML:1.0:assertion',\r\n TokenTypeV2 : 'urn:oasis:names:tc:SAML:2.0:assertion'\r\n },\r\n\r\n XmlNamespaces : {\r\n wsdl : 'http://schemas.xmlsoap.org/wsdl/',\r\n sp : 'http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702',\r\n sp2005 : 'http://schemas.xmlsoap.org/ws/2005/07/securitypolicy',\r\n wsu : 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd',\r\n wsa10 : 'http://www.w3.org/2005/08/addressing',\r\n http : 'http://schemas.microsoft.com/ws/06/2004/policy/http',\r\n soap12 : 'http://schemas.xmlsoap.org/wsdl/soap12/',\r\n wsp : 'http://schemas.xmlsoap.org/ws/2004/09/policy',\r\n s : 'http://www.w3.org/2003/05/soap-envelope',\r\n wsa : 'http://www.w3.org/2005/08/addressing',\r\n wst : 'http://docs.oasis-open.org/ws-sx/ws-trust/200512', \r\n t : 'http://schemas.xmlsoap.org/ws/2005/02/trust'\r\n },\r\n\r\n Cache : {\r\n HASH_ALGORITHM : 'sha256'\r\n },\r\n\r\n HttpError : {\r\n UNAUTHORIZED : 401\r\n },\r\n\r\n AdalIdParameters : {\r\n SKU : 'x-client-SKU',\r\n VERSION : 'x-client-Ver',\r\n OS : 'x-client-OS',\r\n CPU : 'x-client-CPU',\r\n NODE_SKU : 'Node'\r\n },\r\n\r\n WSTrustVersion : {\r\n UNDEFINED : 'undefined', \r\n WSTRUST13 : 'wstrust13', \r\n WSTRUST2005 : 'wstrust2005'\r\n } \r\n };\r\n\r\nmodule.exports = Constants;\r\n","/*\r\n * @copyright\r\n * Copyright © Microsoft Open Technologies, Inc.\r\n *\r\n * All Rights Reserved\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http: *www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\r\n * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\r\n * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A\r\n * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.\r\n *\r\n * See the Apache License, Version 2.0 for the specific language\r\n * governing permissions and limitations under the License.\r\n */\r\n'use strict';\r\n\r\nvar _ = require('underscore');\r\nvar uuid = require('uuid'); // want to replace with this in the future: https://gist.github.com/jed/982883\r\n\r\n\r\n\r\nvar LEVEL_STRING_MAP = {\r\n 0 : 'ERROR:',\r\n 1 : 'WARNING:',\r\n 2 : 'INFO:',\r\n 3 : 'VERBOSE:'\r\n};\r\n\r\n/**\r\n * Methods for controling global logging options for ADAL\r\n * @namespace\r\n */\r\nvar Logging = {\r\n\r\n /**\r\n * @callback LoggingCallback\r\n * @memberOf Logging\r\n * @param {Logging.LOGGING_LEVEL} level The level of this log entry.\r\n * @param {string} message The text content of the log entry.\r\n * @param {Error} [error] An Error object if this is an {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry.\r\n */\r\n\r\n /**\r\n * @typedef LoggingOptions\r\n * @memberOf Logging\r\n * @property {LoggingCallback} [log] The function to call when ADAL generates a log entry.\r\n * @property {Logging.LOGGING_LEVEL} [level] The maximum level of log entries to generate.\r\n */\r\n\r\n /**\r\n * Describes the available logging levels.\r\n * @enum\r\n * @type {Number}\r\n */\r\n LOGGING_LEVEL : {\r\n ERROR : 0,\r\n WARN : 1,\r\n INFO : 2,\r\n VERBOSE : 3\r\n },\r\n\r\n /**\r\n * Sets global logging options for ADAL.\r\n * @param {LoggingOptions} options\r\n */\r\n setLoggingOptions : function(options) {\r\n if (!options) {\r\n options = {};\r\n }\r\n\r\n if (options.log) {\r\n if (!_.isFunction(options.log)) {\r\n throw new Error('setLogOptions expects the log key in the options parameter to be a function');\r\n }\r\n } else {\r\n // if no log function was passed set it to a default no op function.\r\n options.log = function() {};\r\n }\r\n\r\n if (options.level) {\r\n var level = options.level;\r\n if (level < 0 || level > 3) {\r\n throw new Error('setLogOptions expects the level key to be in the range 0 to 3 inclusive');\r\n }\r\n } else {\r\n options.level = this.LOGGING_LEVEL.ERROR;\r\n }\r\n\r\n if (options.loggingWithPII != true) {\r\n options.loggingWithPII = false;\r\n }\r\n \r\n this.LogOptions = options;\r\n },\r\n\r\n /**\r\n * Get's the current global logging options.\r\n * @return {LoggingOptions}\r\n */\r\n getLoggingOptions : function() {\r\n return this.LogOptions;\r\n },\r\n\r\n /**\r\n * Stores the current global logging options.\r\n * @private\r\n * @type {LoggingOptions}\r\n */\r\n LogOptions : {\r\n log : function() {},\r\n level : 0,\r\n loggingWithPII: false\r\n }\r\n};\r\n\r\n/**\r\n * An internal logging object.\r\n * @class\r\n * @private\r\n * @param {string} componentName The name of the component that created this instance. This name will be\r\n * prepended to the beginning of all log entries generated by this instance.\r\n */\r\nfunction Logger(componentName, logContext) {\r\n if (!logContext) {\r\n throw new Error('Logger: logContext is a required parameter');\r\n }\r\n this._componentName = componentName;\r\n this._logContext = logContext;\r\n}\r\n\r\nObject.defineProperty(Logger.prototype, 'context', {\r\n get: function () {\r\n return this._logContext;\r\n }\r\n});\r\n\r\n/**\r\n * Generates a log entry\r\n * @param {Logging.LOGGING_LEVEL} level The level of this log entry\r\n * @param {string|function} message A message string, or a function that returns a message string, to log.\r\n * @param {Error} [error] If this is a {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry then the caller\r\n * should pass an error object in this parameter.\r\n * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false.\r\n */\r\nLogger.prototype.log = function (level, message, error, containsPII) {\r\n if (containsPII == true && !Logging.LogOptions.loggingWithPII) {\r\n return;\r\n }\r\n\r\n if (level <= Logging.LogOptions.level) {\r\n if (_.isFunction(message)) {\r\n message = message();\r\n }\r\n\r\n var correlationId = this._logContext.correlationId || '';\r\n var timeStamp = new Date().toUTCString();\r\n\r\n var formattedMessage = timeStamp + ':' + correlationId + ' - ' + this._componentName + ': ' + LEVEL_STRING_MAP[level] + ' ' + message;\r\n if (error) {\r\n formattedMessage += '\\nStack:\\n' + error.stack;\r\n }\r\n Logging.LogOptions.log(level, formattedMessage, error);\r\n }\r\n};\r\n\r\n/**\r\n * Generate an {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry.\r\n * @param {string} message A message to log\r\n * @param {Error} error The Error object associated with this log entry\r\n * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false.\r\n */\r\nLogger.prototype.error = function (message, error, containsPII) {\r\n this.log(Logging.LOGGING_LEVEL.ERROR, message, error, containsPII);\r\n};\r\n\r\n/**\r\n * Generate an {@link Logging.LOGGING_LEVEL.WARN|WARN} level log entry.\r\n * @param {string} message A message to log\r\n * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false.\r\n */\r\nLogger.prototype.warn = function (message, containsPII) {\r\n this.log(Logging.LOGGING_LEVEL.WARN, message, null, containsPII);\r\n};\r\n\r\n/**\r\n * Generate an {@link Logging.LOGGING_LEVEL.INFO|INFO} level log entry.\r\n * @param {string} message A message to log\r\n * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false.\r\n */\r\nLogger.prototype.info = function (message, containsPII) {\r\n this.log(Logging.LOGGING_LEVEL.INFO, message, null, containsPII);\r\n};\r\n\r\n/**\r\n * Generate an {@link Logging.LOGGING_LEVEL.VERBOSE|VERBOSE} level log entry.\r\n * @param {string} message A message to log\r\n * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false.\r\n */\r\nLogger.prototype.verbose = function (message, containsPII) {\r\n this.log(Logging.LOGGING_LEVEL.VERBOSE, message, null, containsPII);\r\n};\r\n\r\n/**\r\n * Generate a {@link Logging.LOGGING_LEVEL.ERROR|ERROR} level log entry, as well as an\r\n * Error object to go with it. This is a convenience method for throwing logged errors.\r\n * @param {string} message A message to log\r\n * @param {boolean} [containsPII] Determines if the log message contains personal information. Default value is false.\r\n */\r\nLogger.prototype.createError = function(message, containsPII) {\r\n var err = new Error(message);\r\n this.error(message, err, containsPII);\r\n return err;\r\n};\r\n\r\n/**\r\n * Creates a new log context based on the correlationId passed in. If no correlationId is passed in\r\n * then one is generated, by the function uuid.v4()\r\n * @private\r\n */\r\nfunction createLogContext(correlationId) {\r\n var id = correlationId || uuid.v4();\r\n return { correlationId : id };\r\n}\r\n\r\nvar exports = {\r\n Logging : Logging,\r\n Logger : Logger,\r\n createLogContext : createLogContext\r\n};\r\n\r\nmodule.exports = exports;","/*\r\n * @copyright\r\n * Copyright © Microsoft Open Technologies, Inc.\r\n *\r\n * All Rights Reserved\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http: *www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\r\n * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\r\n * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A\r\n * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.\r\n *\r\n * See the Apache License, Version 2.0 for the specific language\r\n * governing permissions and limitations under the License.\r\n */\r\n\r\n'use strict';\r\n\r\nvar _ = require('underscore');\r\n\r\n/**\r\n * Constructs a new in memory token cache.\r\n * @constructor\r\n */\r\nfunction MemoryCache() {\r\n this._entries = [];\r\n}\r\n\r\n/**\r\n * Removes a collection of entries from the cache in a single batch operation.\r\n * @param {Array} entries An array of cache entries to remove.\r\n * @param {Function} callback This function is called when the operation is complete. Any error is provided as the\r\n * first parameter.\r\n */\r\nMemoryCache.prototype.remove = function(entries, callback) {\r\n var updatedEntries = _.filter(this._entries, function(element) {\r\n if (_.findWhere(entries, element)) {\r\n return false;\r\n }\r\n return true;\r\n });\r\n\r\n this._entries = updatedEntries;\r\n callback();\r\n};\r\n\r\n/**\r\n * Adds a collection of entries to the cache in a single batch operation.\r\n * @param {Array} entries An array of entries to add to the cache.\r\n * @param {Function} callback This function is called when the operation is complete. Any error is provided as the\r\n * first parameter.\r\n */\r\nMemoryCache.prototype.add = function(entries, callback) {\r\n // Remove any entries that are duplicates of the existing\r\n // cache elements.\r\n _.each(this._entries, function(element) {\r\n _.each(entries, function(addElement, index) {\r\n if (_.isEqual(element, addElement)) {\r\n entries[index] = null;\r\n }\r\n });\r\n });\r\n\r\n // Add the new entries to the end of the cache.\r\n entries = _.compact(entries);\r\n for (var i = 0; i < entries.length; i++) {\r\n this._entries.push(entries[i]);\r\n }\r\n\r\n callback(null, true);\r\n};\r\n\r\n/**\r\n * Finds all entries in the cache that match all of the passed in values.\r\n * @param {object} query This object will be compared to each entry in the cache. Any entries that\r\n * match all of the values in this object will be returned. All the values\r\n * in the passed in object must match values in a potentialy returned object\r\n * exactly. The returned object may have more values than the passed in query\r\n * object.\r\n * @param {TokenCacheFindCallback} callback\r\n */\r\nMemoryCache.prototype.find = function(query, callback) {\r\n var results = _.where(this._entries, query);\r\n callback(null, results);\r\n};\r\n\r\nmodule.exports = MemoryCache;","/*\r\n * @copyright\r\n * Copyright © Microsoft Open Technologies, Inc.\r\n *\r\n * All Rights Reserved\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http: *www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\r\n * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\r\n * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A\r\n * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.\r\n *\r\n * See the Apache License, Version 2.0 for the specific language\r\n * governing permissions and limitations under the License.\r\n */\r\n'use strict';\r\nvar request = require('request');\r\nvar url = require('url');\r\nvar DOMParser = require('xmldom').DOMParser;\r\nvar _ = require('underscore');\r\nvar Logger = require('./log').Logger;\r\nvar util = require('./util');\r\n\r\nvar xmlutil = require('./xmlutil');\r\nvar select = xmlutil.xpathSelect;\r\n\r\nvar Namespaces = require('./constants').XmlNamespaces;\r\n\r\nvar WSTrustVersion = require('./constants').WSTrustVersion;\r\n\r\n/**\r\n * Create a new Mex object.\r\n * @private\r\n * @constructor\r\n * @param {object} callContext Contains any context information that applies to the request.\r\n * @param {string} url The url of the mex endpoint.\r\n */\r\nfunction Mex(callContext, url) {\r\n this._log = new Logger('MEX', callContext._logContext);\r\n this._callContext = callContext;\r\n this._url = url;\r\n this._dom = null;\r\n this._mexDoc = null;\r\n this._usernamePasswordPolicy = {};\r\n this._log.verbose('Mex created');\r\n this._log.verbose('Mex created with url: ' + url, true);\r\n}\r\n\r\n/**\r\n* Returns the policy containing IDP url and wstrust version from which a username passwowrd can be exchanged for a token.\r\n* @instance\r\n* @memberOf Mex\r\n* @name usernamePasswordPolicy\r\n*/\r\nObject.defineProperty(Mex.prototype, 'usernamePasswordPolicy', {\r\n get: function() {\r\n return this._usernamePasswordPolicy;\r\n }\r\n});\r\n\r\n/**\r\n* @callback DiscoverCallback\r\n* @memberOf Mex\r\n* @param {object} error\r\n*/\r\n\r\n/**\r\n* Performs Mex discovery. This method will retrieve the mex document, parse it, and extract\r\n* the username password ws-trust endpoint.\r\n* @private\r\n* @param {Mex.DiscoverCallback} callback Called when discover is complete.\r\n*/\r\nMex.prototype.discover = function (callback) {\r\n this._log.verbose('Retrieving mex');\r\n this._log.verbose('Retrieving mex at: ' + this._url);\r\n var self = this;\r\n var options = util.createRequestOptions(self, { headers : { 'Content-Type' : 'application/soap+xml'} });\r\n request.get(this._url, options, util.createRequestHandler('Mex Get', this._log, callback,\r\n function(response, body) {\r\n try {\r\n self._mexDoc = body;\r\n var options = {\r\n errorHandler : self._log.error\r\n };\r\n self._dom = new DOMParser(options).parseFromString(self._mexDoc);\r\n self._parse(callback);\r\n return;\r\n } catch (err) {\r\n self._log.error('Failed to parse mex response in to DOM', err, true);\r\n callback(err);\r\n }\r\n })\r\n );\r\n};\r\n\r\nvar TRANSPORT_BINDING_XPATH = 'wsp:ExactlyOne/wsp:All/sp:TransportBinding';\r\nvar TRANSPORT_BINDING_2005_XPATH = 'wsp:ExactlyOne/wsp:All/sp2005:TransportBinding';\r\n/**\r\n* Checks a DOM policy node that is a potentialy appplicable username password policy\r\n* to ensure that it has the correct transport.\r\n* @private\r\n* @param {object} policyNode The policy node to check.\r\n* @returns {string} If the policy matches the desired transport then the id of the policy is returned.\r\n* If not then null is returned.\r\n*/\r\nMex.prototype._checkPolicy = function(policyNode) {\r\n var policyId = null;\r\n var id = policyNode.getAttributeNS(Namespaces.wsu, 'Id');\r\n var transportBindingNodes = select(policyNode, TRANSPORT_BINDING_XPATH);\r\n if (0 === transportBindingNodes.length) {\r\n transportBindingNodes = select(policyNode, TRANSPORT_BINDING_2005_XPATH);\r\n }\r\n if (0 !== transportBindingNodes.length) {\r\n if (id) {\r\n policyId = id;\r\n }\r\n }\r\n if (policyId) {\r\n this._log.verbose('found matching policy id');\r\n this._log.verbose('found matching policy id: ' + policyId, true);\r\n } else {\r\n if (!id) {\r\n id = '';\r\n }\r\n this._log.verbose('potential policy did not match required transport binding');\r\n this._log.verbose('potential policy did not match required transport binding: ' + id, true);\r\n }\r\n return policyId;\r\n};\r\n\r\n/**\r\n* Finds all username password policies within the mex document.\r\n* @private\r\n* @param xpath The xpath expression for selecting username token nodes. \r\n* @returns {object} A map object that contains objects containing the id of username password polices.\r\n*/\r\nMex.prototype._selectUsernamePasswordPolicies = function(xpath) {\r\n var policies = {};\r\n var usernameTokenNodes = select(this._dom, xpath);\r\n if (!usernameTokenNodes.length) {\r\n this._log.warn('no username token policy nodes found');\r\n return;\r\n }\r\n for (var i=0; i < usernameTokenNodes.length; i++) {\r\n var policyNode = usernameTokenNodes[i].parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;\r\n var id = this._checkPolicy(policyNode);\r\n if (id) {\r\n var idRef = '#' + id;\r\n policies[idRef] = { id : idRef };\r\n }\r\n }\r\n return _.isEmpty(policies) ? null : policies;\r\n};\r\n\r\nvar SOAP_ACTION_XPATH = 'wsdl:operation/soap12:operation/@soapAction';\r\nvar RST_SOAP_ACTION_13 = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue';\r\nvar RST_SOAP_ACTION_2005 = 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue';\r\nvar SOAP_TRANSPORT_XPATH = 'soap12:binding/@transport';\r\nvar SOAP_HTTP_TRANSPORT_VALUE = 'http://schemas.xmlsoap.org/soap/http';\r\n/**\r\n* Given a DOM binding node determines whether it matches the correct soap action and transport.\r\n* @private\r\n* @param {object} bindingNode The DOM node to check.\r\n* @returns {bool}\r\n*/\r\nMex.prototype._checkSoapActionAndTransport = function(bindingNode) {\r\n var soapTransportAttributes;\r\n var soapAction;\r\n var soapTransport;\r\n var bindingName = bindingNode.getAttribute('name');\r\n var soapActionAttributes = select(bindingNode, SOAP_ACTION_XPATH);\r\n if (soapActionAttributes.length) {\r\n soapAction = soapActionAttributes[0].value;\r\n soapTransportAttributes = select(bindingNode, SOAP_TRANSPORT_XPATH);\r\n }\r\n if (soapTransportAttributes.length) {\r\n soapTransport = soapTransportAttributes[0].value;\r\n }\r\n\r\n if (soapTransport === SOAP_HTTP_TRANSPORT_VALUE) {\r\n if (soapAction === RST_SOAP_ACTION_13) {\r\n this._log.verbose('foud binding matching Action and Transport: ' + bindingName);\r\n return WSTrustVersion.WSTRUST13;\r\n }\r\n else if (soapAction === RST_SOAP_ACTION_2005) {\r\n this._log.verbose('found binding matching Action and Transport: ' + bindingName);\r\n return WSTrustVersion.WSTRUST2005;\r\n }\r\n }\r\n\r\n this._log.verbose('binding node did not match soap Action or Transport: ' + bindingName);\r\n return WSTrustVersion.UNDEFINED;\r\n};\r\n\r\n/**\r\n* Given a map with policy id keys, finds the bindings in the mex document that are linked to thos policies.\r\n* @private\r\n* @param {object} policies A map with policy id keys.\r\n* @returns {object} a map of bindings id's to policy id's.\r\n*/\r\nMex.prototype._getMatchingBindings = function(policies) {\r\n var bindings = {};\r\n var bindingPolicyRefNodes = select(this._dom, '//wsdl:definitions/wsdl:binding/wsp:PolicyReference');\r\n for (var i=0; i < bindingPolicyRefNodes.length; i++) {\r\n var node = bindingPolicyRefNodes[i];\r\n var uri = node.getAttribute('URI');\r\n var policy = policies[uri];\r\n if (policy) {\r\n var bindingNode = node.parentNode;\r\n var bindingName = bindingNode.getAttribute('name');\r\n var version = this._checkSoapActionAndTransport(bindingNode);\r\n if (version !== WSTrustVersion.UNDEFINED) {\r\n var bindingPolicy = {};\r\n bindingPolicy.url = uri;\r\n bindingPolicy.version = version;\r\n\r\n bindings[bindingName] = bindingPolicy;\r\n }\r\n }\r\n }\r\n return _.isEmpty(bindings) ? null : bindings;\r\n};\r\n\r\n/**\r\n* Ensures that a url points to an SSL endpoint.\r\n* @private\r\n* @param {string} endpointUrl The url to check.\r\n* @returns {bool}\r\n*/\r\nMex.prototype._urlIsSecure = function(endpointUrl) {\r\n var parsedUrl = url.parse(endpointUrl);\r\n return parsedUrl.protocol === 'https:';\r\n};\r\n\r\nvar PORT_XPATH = '//wsdl:definitions/wsdl:service/wsdl:port';\r\nvar ADDRESS_XPATH = 'wsa10:EndpointReference/wsa10:Address';\r\n/**\r\n* Finds all of the wsdl ports in the mex document that are associated with username password policies. Augments\r\n* the passed in bindings with the endpoint url of the correct port.\r\n* @private\r\n* @param {object} bindings A map of binding id's to policy id's.\r\n*/\r\nMex.prototype._getPortsForPolicyBindings = function(bindings, policies) {\r\n var portNodes = select(this._dom, PORT_XPATH);\r\n if (0 === portNodes.length) {\r\n this._log.warning('no ports found');\r\n }\r\n for (var i=0; i < portNodes.length; i++) {\r\n var portNode = portNodes[i];\r\n var bindingId = portNode.getAttribute('binding');\r\n\r\n // Clear any prefix\r\n var bindingIdParts = bindingId.split(':');\r\n bindingId = bindingIdParts[bindingIdParts.length - 1];\r\n\r\n var trustPolicy = bindings[bindingId];\r\n if (trustPolicy) {\r\n var bindingPolicy = policies[trustPolicy.url];\r\n\r\n if (bindingPolicy && !bindingPolicy.url) {\r\n bindingPolicy.version = trustPolicy.version;\r\n var addressNode = select(portNode, ADDRESS_XPATH);\r\n if (0 === addressNode) {\r\n throw this._log.createError('no address nodes on port.');\r\n }\r\n var address = xmlutil.findElementText(addressNode[0]);\r\n if (this._urlIsSecure(address)) {\r\n bindingPolicy.url = address;\r\n } else {\r\n this._log.warn('skipping insecure endpoint: ' + address);\r\n }\r\n }\r\n }\r\n }\r\n};\r\n\r\n/**\r\n* Given a list of username password policies chooses one of them at random as the policy chosen by this Mex instance.\r\n* @private\r\n* @param {object} policies A map of policy id's to an object containing username password ws-trust endpoint addresses.\r\n*/\r\nMex.prototype._selectSingleMatchingPolicy = function(policies) {\r\n // if both wstrust13 and wstrust2005 policy exists, then choose wstrust13, otherwise choose whatever exists.\r\n var matchingPolicies = _.filter(policies, function(policy) { return policy.url ? true : false; });\r\n if (!matchingPolicies) {\r\n this._log.warn('no policies found with an url');\r\n return;\r\n }\r\n\r\n var wstrust13Policy = null, wstrust2005Policy = null;\r\n for(var i = 0; i < matchingPolicies.length; ++i) {\r\n var matchingPolicy = matchingPolicies[i];\r\n if (WSTrustVersion.WSTRUST13 === matchingPolicy.version) {\r\n wstrust13Policy = matchingPolicy;\r\n }\r\n else if (WSTrustVersion.WSTRUST2005 === matchingPolicy.version) {\r\n wstrust2005Policy = matchingPolicy;\r\n }\r\n }\r\n\r\n if (!wstrust13Policy && !wstrust2005Policy) {\r\n this._log.warn('no policies found with an url');\r\n this._usernamePasswordPolicy = null;\r\n return;\r\n }\r\n\r\n this._usernamePasswordPolicy = wstrust13Policy ? wstrust13Policy : wstrust2005Policy;\r\n};\r\n\r\n/**\r\n* Parses the mex document previously retrieved.\r\n* @private\r\n* @param {Mex.DiscoverCallback} callback\r\n*/\r\nMex.prototype._parse = function(callback) {\r\n var self = this;\r\n var xpathExpression = '//wsdl:definitions/wsp:Policy/wsp:ExactlyOne/wsp:All/sp:SignedEncryptedSupportingTokens/wsp:Policy/sp:UsernameToken/wsp:Policy/sp:WssUsernameToken10'; \r\n var policies = self._selectUsernamePasswordPolicies(xpathExpression);\r\n\r\n xpathExpression = '//wsdl:definitions/wsp:Policy/wsp:ExactlyOne/wsp:All/sp2005:SignedSupportingTokens/wsp:Policy/sp2005:UsernameToken/wsp:Policy/sp2005:WssUsernameToken10';\r\n\r\n if (policies) {\r\n _.extend(policies, self._selectUsernamePasswordPolicies(xpathExpression));\r\n }\r\n else {\r\n policies = self._selectUsernamePasswordPolicies(xpathExpression);\r\n }\r\n\r\n if (!policies) {\r\n callback(self._log.createError('No matching policies'));\r\n return;\r\n }\r\n var bindings = self._getMatchingBindings(policies);\r\n if (!bindings) {\r\n callback(self._log.createError('No matching bindings'));\r\n return;\r\n }\r\n self._getPortsForPolicyBindings(bindings, policies);\r\n self._selectSingleMatchingPolicy(policies);\r\n var err = this._url ? undefined : this._log.createError('No ws-trust endpoints match requirements.');\r\n callback(err);\r\n};\r\n\r\nmodule.exports = Mex;","/*\r\n * @copyright\r\n * Copyright © Microsoft Open Technologies, Inc.\r\n *\r\n * All Rights Reserved\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http: *www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\r\n * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\r\n * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A\r\n * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.\r\n *\r\n * See the Apache License, Version 2.0 for the specific language\r\n * governing permissions and limitations under the License.\r\n */\r\n'use strict';\r\n\r\nvar _ = require('underscore');\r\nrequire('date-utils'); // Adds a number of convenience methods to the builtin Date object.\r\nvar querystring = require('querystring');\r\nvar uuid = require('uuid');\r\nvar request = require('request');\r\nvar url = require('url');\r\nvar async = require('async');\r\n\r\nvar constants = require('./constants');\r\nvar Logger = require('./log').Logger;\r\nvar util = require('./util');\r\n\r\nvar OAuth2Parameters = constants.OAuth2.Parameters;\r\nvar OAuth2ResponseParameters = constants.OAuth2.ResponseParameters;\r\nvar DeviceCodeResponseParameters = constants.OAuth2.DeviceCodeResponseParameters;\r\nvar IdTokenMap = constants.OAuth2.IdTokenMap;\r\nvar TokenResponseFields = constants.TokenResponseFields;\r\nvar UserCodeResponseFields = constants.UserCodeResponseFields;\r\nvar IdTokenFields = constants.IdTokenFields;\r\n\r\nvar TOKEN_RESPONSE_MAP = {};\r\nTOKEN_RESPONSE_MAP[OAuth2ResponseParameters.TOKEN_TYPE] = TokenResponseFields.TOKEN_TYPE;\r\nTOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ACCESS_TOKEN] = TokenResponseFields.ACCESS_TOKEN;\r\nTOKEN_RESPONSE_MAP[OAuth2ResponseParameters.REFRESH_TOKEN] = TokenResponseFields.REFRESH_TOKEN;\r\nTOKEN_RESPONSE_MAP[OAuth2ResponseParameters.CREATED_ON] = TokenResponseFields.CREATED_ON;\r\nTOKEN_RESPONSE_MAP[OAuth2ResponseParameters.EXPIRES_ON] = TokenResponseFields.EXPIRES_ON;\r\nTOKEN_RESPONSE_MAP[OAuth2ResponseParameters.EXPIRES_IN] = TokenResponseFields.EXPIRES_IN;\r\nTOKEN_RESPONSE_MAP[OAuth2ResponseParameters.RESOURCE] = TokenResponseFields.RESOURCE;\r\nTOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ERROR] = TokenResponseFields.ERROR;\r\nTOKEN_RESPONSE_MAP[OAuth2ResponseParameters.ERROR_DESCRIPTION] = TokenResponseFields.ERROR_DESCRIPTION;\r\n\r\n\r\nvar DEVICE_CODE_RESPONSE_MAP = {};\r\nDEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.DEVICE_CODE] = UserCodeResponseFields.DEVICE_CODE;\r\nDEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.USER_CODE] = UserCodeResponseFields.USER_CODE;\r\nDEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.VERIFICATION_URL] = UserCodeResponseFields.VERIFICATION_URL;\r\nDEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.INTERVAL] = UserCodeResponseFields.INTERVAL;\r\nDEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.EXPIRES_IN] = UserCodeResponseFields.EXPIRES_IN;\r\nDEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.MESSAGE] = UserCodeResponseFields.MESSAGE;\r\nDEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.ERROR] = UserCodeResponseFields.ERROR;\r\nDEVICE_CODE_RESPONSE_MAP[DeviceCodeResponseParameters.ERROR_DESCRIPTION] = UserCodeResponseFields.ERROR_DESCRIPTION;\r\n\r\n/**\r\n * Constructs an instances of OAuth2Client\r\n * @constructor\r\n * @private\r\n * @param {object} callContext Contains any context information that applies to the request.\r\n * @param {string|url} authority An url that points to an authority.\r\n */\r\nfunction OAuth2Client(callContext, authority) {\r\n this._tokenEndpoint = authority.tokenEndpoint;\r\n this._deviceCodeEndpoint = authority.deviceCodeEndpoint;\r\n\r\n this._log = new Logger('OAuth2Client', callContext._logContext);\r\n this._callContext = callContext;\r\n this._cancelPollingRequest = false;\r\n}\r\n\r\n/**\r\n * Constructs an OAuth 2.0 token request url.\r\n * @private\r\n * @return {URL}\r\n */\r\nOAuth2Client.prototype._createTokenUrl = function () {\r\n var tokenUrl = url.parse(this._tokenEndpoint);\r\n\r\n var parameters = {};\r\n parameters[OAuth2Parameters.AAD_API_VERSION] = '1.0';\r\n\r\n tokenUrl.search = querystring.stringify(parameters);\r\n return tokenUrl;\r\n};\r\n\r\n/**\r\n * Constructs the user code info request url. \r\n * @private \r\n * @return {URL}\r\n */\r\nOAuth2Client.prototype._createDeviceCodeUrl = function () {\r\n var deviceCodeUrl = url.parse(this._deviceCodeEndpoint);\r\n\r\n var parameters = {};\r\n parameters[OAuth2Parameters.AAD_API_VERSION] = '1.0';\r\n\r\n deviceCodeUrl.search = querystring.stringify(parameters);\r\n\r\n return deviceCodeUrl;\r\n};\r\n\r\n/**\r\n * @private\r\n * @param {object} obj An object in which integer values may reside.\r\n * @param {array} keys An array of strings that specify keys in which integers may need parsing.\r\n */\r\nOAuth2Client.prototype._parseOptionalInts = function (obj, keys) {\r\n var self = this;\r\n keys.forEach(function(element) {\r\n if (_.has(obj, element)) {\r\n obj[element] = parseInt(obj[element], 10);\r\n if (isNaN(obj[element])) {\r\n throw self._log.createError(element + ' could not be parsed as an int.');\r\n }\r\n }\r\n });\r\n};\r\n\r\n/**\r\n * Parses a JWS encoded JWT into it's three parts.\r\n * @param {string} jwtToken The token to parse.\r\n * @return {object} The three JWS parts, header, JWSPayload, and JWSSig, or undefined.\r\n */\r\nOAuth2Client.prototype._crackJwt = function(jwtToken) {\r\n var idTokenPartsRegex = /^([^\\.\\s]*)\\.([^\\.\\s]+)\\.([^\\.\\s]*)$/;\r\n\r\n var matches = idTokenPartsRegex.exec(jwtToken);\r\n if (!matches || matches.length < 4) {\r\n this._log.warn('The returned id_token is not parseable.');\r\n return;\r\n }\r\n\r\n var crackedToken = {\r\n header : matches[1],\r\n JWSPayload : matches[2],\r\n JWSSig : matches[3]\r\n };\r\n\r\n return crackedToken;\r\n};\r\n\r\n/**\r\n * Finds the value that should be used as the userId value.\r\n * @param {object} idToken The id token that parsed.\r\n * @returns {object} An object with a userId field and maybe a userIdIsDisplayable field.\r\n */\r\nOAuth2Client.prototype._getUserId = function(idToken) {\r\n var userId;\r\n var isDisplayable;\r\n\r\n if (idToken.upn) {\r\n userId = idToken.upn;\r\n isDisplayable = true;\r\n } else if (idToken.email) {\r\n userId = idToken.email;\r\n isDisplayable = true;\r\n } else if (idToken.sub) {\r\n userId = idToken.sub;\r\n }\r\n\r\n if (!userId) {\r\n // generate a random GUID.\r\n userId = uuid.v4();\r\n }\r\n\r\n var userIdVals = {};\r\n userIdVals[IdTokenFields.USER_ID] = userId;\r\n if (isDisplayable) {\r\n userIdVals[IdTokenFields.IS_USER_ID_DISPLAYABLE] = true;\r\n }\r\n\r\n return userIdVals;\r\n};\r\n\r\nfunction mapFields(inObj, outObj, map) {\r\n for (var key in inObj) {\r\n if (map[key]) {\r\n var mappedKey = map[key];\r\n outObj[mappedKey] = inObj[key];\r\n }\r\n }\r\n}\r\n\r\n/**\r\n * Given a decoded id token off the wire, this function extracts the values that\r\n * ADAL commonly returns to callers and translates the names to more user\r\n * friendly names.\r\n * @param {Object} idToken A decoded id token.\r\n * @return {Object} The set of extracted values with their new names.\r\n */\r\nOAuth2Client.prototype._extractIdTokenValues = function(idToken) {\r\n var extractedValues = {};\r\n _.extend(extractedValues, this._getUserId(idToken));\r\n\r\n mapFields(idToken, extractedValues, IdTokenMap);\r\n\r\n return extractedValues;\r\n};\r\n\r\n/**\r\n * Parses the value of the id_token OAuth 2 Reponse.\r\n * @param {string} encodedIdToken An unencrypted JWT token.\r\n * @return {object} returns the decoded id_token or undefined.\r\n */\r\nOAuth2Client.prototype._parseIdToken = function(encodedIdToken) {\r\n var crackedToken = this._crackJwt(encodedIdToken);\r\n if (!crackedToken) {\r\n return;\r\n }\r\n\r\n var idToken;\r\n try {\r\n var base64IdToken = crackedToken.JWSPayload;\r\n var base64Decoded = util.base64DecodeStringUrlSafe(base64IdToken);\r\n if (!base64Decoded) {\r\n this._log.warn('The returned id_token could not be base64 url safe decoded.');\r\n return;\r\n }\r\n\r\n idToken = JSON.parse(base64Decoded);\r\n } catch (err) {\r\n this._log.warn('the returned id_token could not be decoded');\r\n this._log.warn('The returned id_token could not be decoded: ' + err.stack, true);\r\n return;\r\n }\r\n\r\n return this._extractIdTokenValues(idToken);\r\n};\r\n\r\n/**\r\n * Validates the response returned from an OAuth 2.0 token request.\r\n * @private\r\n * @param {string} body The response as a string encoded JSON object.\r\n * @return {object} The parsed response.\r\n */\r\nOAuth2Client.prototype._validateTokenResponse = function(body) {\r\n var wireResponse;\r\n var tokenResponse = {};\r\n\r\n try {\r\n wireResponse = JSON.parse(body);\r\n } catch(e) {\r\n throw new Error('The token response returned from the server is unparseable as JSON');\r\n }\r\n\r\n var intKeys = [\r\n OAuth2ResponseParameters.EXPIRES_ON,\r\n OAuth2ResponseParameters.EXPIRES_IN,\r\n OAuth2ResponseParameters.CREATED_ON\r\n ];\r\n\r\n this._parseOptionalInts(wireResponse, intKeys);\r\n\r\n if (wireResponse[OAuth2ResponseParameters.EXPIRES_IN]) {\r\n var expiresIn = wireResponse[OAuth2ResponseParameters.EXPIRES_IN];\r\n var now = new Date();\r\n wireResponse[OAuth2ResponseParameters.EXPIRES_ON] = now.add( { seconds : expiresIn });\r\n }\r\n\r\n if (wireResponse[OAuth2ResponseParameters.CREATED_ON]) {\r\n var tempDate = new Date();\r\n var createdOn = wireResponse[OAuth2ResponseParameters.CREATED_ON];\r\n tempDate.setTime(createdOn);\r\n wireResponse[OAuth2ResponseParameters.CREATED_ON] = tempDate;\r\n }\r\n\r\n if (!wireResponse[OAuth2ResponseParameters.TOKEN_TYPE]) {\r\n throw this._log.createError('wireResponse is missing token_type');\r\n }\r\n if (!wireResponse[OAuth2ResponseParameters.ACCESS_TOKEN]) {\r\n throw this._log.createError('wireResponse missing access_token');\r\n }\r\n \r\n mapFields(wireResponse, tokenResponse, TOKEN_RESPONSE_MAP);\r\n\r\n if (wireResponse[OAuth2ResponseParameters.ID_TOKEN]) {\r\n var idToken = this._parseIdToken(wireResponse[OAuth2ResponseParameters.ID_TOKEN]);\r\n if (idToken) {\r\n _.extend(tokenResponse, idToken);\r\n }\r\n }\r\n\r\n return tokenResponse;\r\n};\r\n\r\n/**\r\n * Validates the response returned from an OAuth 2.0 device code request.\r\n * @private\r\n * @param {string} body The response as a string encoded JSON object.\r\n * @return {object} The parsed response.\r\n */\r\nOAuth2Client.prototype._validateDeviceCodeResponse = function(body) {\r\n var wireResponse;\r\n var deviceCodeResponse = {};\r\n\r\n try {\r\n wireResponse = JSON.parse(body);\r\n } catch(e) {\r\n throw new Error('The device code response returned from the server is unparseable as JSON.');\r\n }\r\n\r\n var intKeys = [\r\n DeviceCodeResponseParameters.EXPIRES_IN, \r\n DeviceCodeResponseParameters.INTERVAL\r\n ];\r\n\r\n this._parseOptionalInts(wireResponse, intKeys);\r\n \r\n if (!wireResponse[DeviceCodeResponseParameters.EXPIRES_IN]){\r\n throw this._log.createError('wireResponse is missing expires_in');\r\n }\r\n\r\n if (!wireResponse[DeviceCodeResponseParameters.DEVICE_CODE]) {\r\n throw this._log.createError('wireResponse is missing device code');\r\n }\r\n\r\n if (!wireResponse[DeviceCodeResponseParameters.USER_CODE]) {\r\n throw this._log.createError('wireResponse is missing user code');\r\n }\r\n\r\n mapFields(wireResponse, deviceCodeResponse, DEVICE_CODE_RESPONSE_MAP);\r\n\r\n return deviceCodeResponse;\r\n};\r\n\r\n/**\r\n * @private\r\n * @param {string} body The body of a http token response.\r\n */\r\nOAuth2Client.prototype._handlePollingResponse = function(body) {\r\n //handle token error response\r\n var tokenResponse = this._handlePollingRequestErrorResponse(body);\r\n if (_.isEmpty(tokenResponse)){\r\n tokenResponse = this._validateTokenResponse(body);\r\n }\r\n\r\n return tokenResponse;\r\n};\r\n\r\n/**\r\n * @private\r\n * @param {string} body The body of a http token response.\r\n */\r\nOAuth2Client.prototype._handlePollingRequestErrorResponse = function(body) {\r\n var wireResponse;\r\n var tokenResponse = {};\r\n\r\n try {\r\n wireResponse = JSON.parse(body);\r\n } catch (e) {\r\n throw new Error ('The token response returned from the server is unparsable as JSON');\r\n }\r\n\r\n if (wireResponse[OAuth2ResponseParameters.ERROR]) {\r\n mapFields(wireResponse, tokenResponse, TOKEN_RESPONSE_MAP);\r\n }\r\n\r\n return tokenResponse;\r\n};\r\n\r\n/**\r\n * @private\r\n * @param {object} response An http response object.\r\n * @param {string} body The body of a http token response.\r\n * @param {OAuth2Client.GetTokenCallback} callback A call back function. The body parameter is the body parameter passed\r\n * into this function.\r\n */\r\nOAuth2Client.prototype._handleGetTokenResponse = function(response, body, callback) {\r\n var tokenResponse;\r\n try {\r\n tokenResponse = this._validateTokenResponse(body);\r\n } catch (e) {\r\n this._log.error('Error validating get token response', e, true);\r\n callback(e);\r\n return;\r\n }\r\n callback(null, tokenResponse);\r\n};\r\n\r\nOAuth2Client.prototype._handleGetDeviceCodeResponse = function(response, body, callback) {\r\n var deviceCodeResponse;\r\n try {\r\n deviceCodeResponse = this._validateDeviceCodeResponse(body);\r\n } catch (e) {\r\n this._log.error('Error validating get user code response', e, true);\r\n callback(e);\r\n return;\r\n }\r\n\r\n callback(null, deviceCodeResponse);\r\n};\r\n\r\nOAuth2Client.prototype._getTokenWithPolling = function (postOptions, callback) {\r\n var self = this;\r\n if (self._cancelPollingRequest === true) {\r\n callback(null, new Error('Polling_Request_Cancelled'));\r\n return;\r\n }\r\n \r\n request.post(postOptions, util.createRequestHandler('Get Token', this._log, function(response, body) {\r\n //error response callback, for error response, it's already parsed as Json. \r\n if (body && body.hasOwnProperty(TokenResponseFields.ERROR) && body[TokenResponseFields.ERROR] === 'authorization_pending') {\r\n callback(new Error(body[TokenResponseFields.ERROR]), body);\r\n }\r\n else {\r\n callback(null, body);\r\n }\r\n }, \r\n // success response callback\r\n function (response, body) {\r\n var tokenResponse;\r\n try {\r\n tokenResponse = self._handlePollingResponse(body);\r\n } catch (e) {\r\n self._log.error('Error validating get token response', e, true);\r\n callback(null, e);\r\n return;\r\n }\r\n \r\n callback(null, tokenResponse);\r\n })\r\n );\r\n};\r\n\r\nOAuth2Client.prototype._createPostOption = function (postUrl, urlEncodedRequestForm) {\r\n var postOptions = util.createRequestOptions(\r\n this,\r\n {\r\n 'url' : url.format(postUrl),\r\n body : urlEncodedRequestForm,\r\n headers: {\r\n 'Content-Type': 'application/x-www-form-urlencoded'\r\n },\r\n followRedirect : false,\r\n encoding : 'utf8'\r\n }\r\n );\r\n \r\n return postOptions;\r\n};\r\n\r\n/**\r\n * @callback GetTokenCallback\r\n * @memberOf OAuth2Client\r\n * @param {Error} [error] In case of an error this will hold the associated Error object.\r\n * @param {TokenResponse} tokenResponse Contains the parsed result of a get token request.\r\n */\r\n\r\n/**\r\n* @param {object} oauthParameters An object whose keys come from\r\n* Constants.OAuth2.Parameters\r\n* @param {OAuth2Client.GetTokenCallback} callback The callback function.\r\n*/\r\nOAuth2Client.prototype.getToken = function(oauthParameters, callback) {\r\n var self = this;\r\n var tokenUrl = self._createTokenUrl();\r\n\r\n var urlEncodedTokenRequestForm = querystring.stringify(oauthParameters);\r\n\r\n var postOptions = self._createPostOption(tokenUrl, urlEncodedTokenRequestForm);\r\n\r\n request.post(postOptions, util.createRequestHandler('Get Token', this._log, callback,\r\n function (response, body) {\r\n self._handleGetTokenResponse(response, body, callback);\r\n })\r\n );\r\n};\r\n\r\n/**\r\n * @param {object} oauthParameters An object whose keys come from\r\n * Constants.OAuth2.Parameters\r\n * @param {integer} refresh_interval The interval for polling request. \r\n * @param {integer} exipres_in The timeout for polling request. \r\n * @param {OAuth2Client.GetTokenCallback} callback The callback function.\r\n */\r\nOAuth2Client.prototype.getTokenWithPolling = function(oauthParameters, refresh_interval, expires_in, callback){\r\n var self = this; \r\n var maxTimesForRetry = Math.floor(expires_in / refresh_interval);\r\n \r\n var tokenUrl = self._createTokenUrl();\r\n var urlEncodedTokenRequestForm = querystring.stringify(oauthParameters);\r\n var postOptions = self._createPostOption(tokenUrl, urlEncodedTokenRequestForm);\r\n\r\n var optionsForRetry = {times: maxTimesForRetry, interval: refresh_interval * 1000};\r\n\r\n async.retry(optionsForRetry, function(retryCallback, response) {\r\n self._getTokenWithPolling(postOptions, retryCallback);\r\n }, function(err, response) {\r\n if (response && response instanceof Error) {\r\n callback(response);\r\n return;\r\n }\r\n else if (response && response.hasOwnProperty(DeviceCodeResponseParameters.ERROR)) {\r\n callback(response);\r\n return;\r\n }\r\n callback(err, response);\r\n });\r\n};\r\n\r\nOAuth2Client.prototype.getUserCodeInfo = function(oauthParameters, callback) {\r\n // for now make it as a post request\r\n var self = this;\r\n var deviceCodeUrl = self._createDeviceCodeUrl();\r\n\r\n var urlEncodedDeviceCodeRequestForm = querystring.stringify(oauthParameters);\r\n \r\n var postOptions = self._createPostOption(deviceCodeUrl, urlEncodedDeviceCodeRequestForm);\r\n\r\n request.post(postOptions, util.createRequestHandler('Get Device Code ', this._log, callback,\r\n function (response, body) {\r\n self._handleGetDeviceCodeResponse(response, body, callback);\r\n })\r\n );\r\n};\r\n\r\n/**\r\n * Cancel the polling request made for acquiring token by device code. \r\n */\r\nOAuth2Client.prototype.cancelPollingRequest = function() {\r\n this._cancelPollingRequest = true;\r\n};\r\n\r\nmodule.exports = OAuth2Client;\r\n","/*\r\n * @copyright\r\n * Copyright © Microsoft Open Technologies, Inc.\r\n *\r\n * All Rights Reserved\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http: *www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\r\n * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\r\n * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A\r\n * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.\r\n *\r\n * See the Apache License, Version 2.0 for the specific language\r\n * governing permissions and limitations under the License.\r\n */\r\n'use strict';\r\n\r\nvar jwtConstants = require('./constants').Jwt;\r\nvar Logger = require('./log').Logger;\r\nvar util = require('./util');\r\n\r\nrequire('date-utils');\r\nvar jws = require('jws');\r\nvar uuid = require('uuid');\r\n\r\n/**\r\n * JavaScript dates are in milliseconds, but JWT dates are in seconds.\r\n * This function does the conversion.\r\n * @param {Date} date\r\n * @return {string}\r\n */\r\nfunction dateGetTimeInSeconds(date) {\r\n return Math.floor(date.getTime()/1000);\r\n}\r\n\r\n/**\r\n * Constructs a new SelfSignedJwt object.\r\n * @param {object} callContext Context specific to this token request.\r\n * @param {Authority} authority The authority to be used as the JWT audience.\r\n * @param {string} clientId The client id of the calling app.\r\n */\r\nfunction SelfSignedJwt(callContext, authority, clientId) {\r\n this._log = new Logger('SelfSignedJwt', callContext._logContext);\r\n this._callContext = callContext;\r\n\r\n this._authority = authority;\r\n this._tokenEndpoint = authority.tokenEndpoint;\r\n this._clientId = clientId;\r\n}\r\n\r\n/**\r\n * This wraps date creation in order to make unit testing easier.\r\n * @return {Date}\r\n */\r\nSelfSignedJwt.prototype._getDateNow = function() {\r\n return new Date();\r\n};\r\n\r\nSelfSignedJwt.prototype._getNewJwtId = function() {\r\n return uuid.v4();\r\n};\r\n\r\n/**\r\n * A regular certificate thumbprint is a hex encode string of the binary certificate\r\n * hash. For some reason teh x5t value in a JWT is a url save base64 encoded string\r\n * instead. This function does the conversion.\r\n * @param {string} thumbprint A hex encoded certificate thumbprint.\r\n * @return {string} A url safe base64 encoded certificate thumbprint.\r\n */\r\nSelfSignedJwt.prototype._createx5tValue = function(thumbprint) {\r\n var hexString = thumbprint.replace(/:/g, '').replace(/ /g, '');\r\n var base64 = (new Buffer(hexString, 'hex')).toString('base64');\r\n return util.convertRegularToUrlSafeBase64EncodedString(base64);\r\n};\r\n\r\n/**\r\n * Creates the JWT header.\r\n * @param {string} thumbprint A hex encoded certificate thumbprint.\r\n * @return {object}\r\n */\r\nSelfSignedJwt.prototype._createHeader = function(thumbprint) {\r\n var x5t = this._createx5tValue(thumbprint);\r\n var header = { typ: 'JWT', alg: 'RS256', x5t : x5t };\r\n\r\n this._log.verbose('Creating self signed JWT header');\r\n this._log.verbose('Creating self signed JWT header. x5t: ' + x5t, true);\r\n\r\n return header;\r\n};\r\n\r\n/**\r\n * Creates the JWT payload.\r\n * @return {object}\r\n */\r\nSelfSignedJwt.prototype._createPayload = function() {\r\n var now = this._getDateNow();\r\n var expires = (new Date(now.getTime())).addMinutes(jwtConstants.SELF_SIGNED_JWT_LIFETIME);\r\n\r\n this._log.verbose('Creating self signed JWT payload. Expires: ' + expires + ' NotBefore: ' + now);\r\n\r\n var jwtPayload = {};\r\n jwtPayload[jwtConstants.AUDIENCE] = this._tokenEndpoint;\r\n jwtPayload[jwtConstants.ISSUER] = this._clientId;\r\n jwtPayload[jwtConstants.SUBJECT] = this._clientId;\r\n jwtPayload[jwtConstants.NOT_BEFORE] = dateGetTimeInSeconds(now);\r\n jwtPayload[jwtConstants.EXPIRES_ON] = dateGetTimeInSeconds(expires);\r\n jwtPayload[jwtConstants.JWT_ID] = this._getNewJwtId();\r\n\r\n return jwtPayload;\r\n};\r\n\r\nSelfSignedJwt.prototype._throwOnInvalidJwtSignature = function(jwt) {\r\n var jwtSegments = jwt.split('.');\r\n\r\n if (3 > jwtSegments.length || !jwtSegments[2]) {\r\n throw this._log.createError('Failed to sign JWT. This is most likely due to an invalid certificate.');\r\n }\r\n\r\n return;\r\n};\r\n\r\nSelfSignedJwt.prototype._signJwt = function(header, payload, certificate) {\r\n var jwt;\r\n try {\r\n jwt = jws.sign({ header : header, payload : payload, secret : certificate });\r\n }\r\n catch (err) {\r\n this._log.error(err, true);\r\n throw this._log.createError('Failed to sign JWT.This is most likely due to an invalid certificate.'); \r\n }\r\n \r\n this._throwOnInvalidJwtSignature(jwt);\r\n return jwt;\r\n};\r\n\r\nSelfSignedJwt.prototype._reduceThumbprint = function(thumbprint) {\r\n var canonical = thumbprint.toLowerCase().replace(/ /g, '').replace(/:/g, '');\r\n this._throwOnInvalidThumbprint(canonical);\r\n return canonical;\r\n};\r\n\r\nvar numCharIn128BitHexString = 128/8*2;\r\nvar numCharIn160BitHexString = 160/8*2;\r\nvar thumbprintSizes = {};\r\nthumbprintSizes[numCharIn128BitHexString] = true;\r\nthumbprintSizes[numCharIn160BitHexString] = true;\r\nvar thumbprintRegExp = /^[a-f\\d]*$/;\r\n\r\nSelfSignedJwt.prototype._throwOnInvalidThumbprint = function(thumbprint) {\r\n if (!thumbprintSizes[thumbprint.length] || !thumbprintRegExp.test(thumbprint)) {\r\n throw this._log.createError('The thumbprint does not match a known format');\r\n }\r\n};\r\n\r\n/**\r\n * Creates a self signed JWT that can be used as a client_assertion.\r\n * @param {string} certificate A PEM encoded certificate private key.\r\n * @param {string} thumbprint A hex encoded thumbprint of the certificate.\r\n * @return {string} A self signed JWT token.\r\n */\r\nSelfSignedJwt.prototype.create = function(certificate, thumbprint) {\r\n thumbprint = this._reduceThumbprint(thumbprint);\r\n var header = this._createHeader(thumbprint);\r\n\r\n var payload = this._createPayload();\r\n\r\n var jwt = this._signJwt(header, payload, certificate);\r\n return jwt;\r\n};\r\n\r\nmodule.exports = SelfSignedJwt;","/*\r\n * @copyright\r\n * Copyright © Microsoft Open Technologies, Inc.\r\n *\r\n * All Rights Reserved\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http: *www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\r\n * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\r\n * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A\r\n * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.\r\n *\r\n * See the Apache License, Version 2.0 for the specific language\r\n * governing permissions and limitations under the License.\r\n */\r\n'use strict';\r\n\r\nvar constants = require('./constants');\r\nvar CacheDriver = require('./cache-driver');\r\nvar Logger = require('./log').Logger;\r\nvar Mex = require('./mex');\r\nvar OAuth2Client = require('./oauth2client');\r\nvar SelfSignedJwt = require('./self-signed-jwt');\r\nvar UserRealm = require('./user-realm');\r\nvar WSTrustRequest = require('./wstrust-request');\r\n\r\nvar OAuth2Parameters = constants.OAuth2.Parameters;\r\nvar TokenResponseFields = constants.TokenResponseFields;\r\nvar OAuth2GrantType = constants.OAuth2.GrantType;\r\nvar OAuth2Scope = constants.OAuth2.Scope;\r\nvar Saml = constants.Saml;\r\nvar AccountType = constants.UserRealm.AccountType;\r\nvar WSTrustVersion = constants.WSTrustVersion;\r\nvar DeviceCodeResponseParameters = constants.UserCodeResponseFields;\r\n\r\n/**\r\n * Constructs a new TokenRequest object.\r\n * @constructor\r\n * @private\r\n * @param {object} callContext Contains any context information that applies to the request.\r\n * @param {AuthenticationContext} authenticationContext\r\n * @param {string} resource\r\n * @param {string} clientId\r\n * @param {string} redirectUri\r\n */\r\nfunction TokenRequest(callContext, authenticationContext, clientId, resource, redirectUri) {\r\n this._log = new Logger('TokenRequest', callContext._logContext);\r\n this._callContext = callContext;\r\n this._authenticationContext = authenticationContext;\r\n this._resource = resource;\r\n this._clientId = clientId;\r\n this._redirectUri = redirectUri;\r\n\r\n // This should be set at the beginning of getToken\r\n // functions that have a userId.\r\n this._userId = null;\r\n\r\n this._userRealm = null;\r\n this._pollingClient = {};\r\n}\r\n\r\nTokenRequest.prototype._createUserRealmRequest = function(username) {\r\n return new UserRealm(this._callContext, username, this._authenticationContext.authority);\r\n};\r\n\r\nTokenRequest.prototype._createMex = function(mexEndpoint) {\r\n return new Mex(this._callContext, mexEndpoint);\r\n};\r\n\r\nTokenRequest.prototype._createWSTrustRequest = function(wstrustEndpoint, appliesTo, wstrustEndpointVersion) {\r\n return new WSTrustRequest(this._callContext, wstrustEndpoint, appliesTo, wstrustEndpointVersion);\r\n};\r\n\r\nTokenRequest.prototype._createOAuth2Client = function() {\r\n return new OAuth2Client(this._callContext, this._authenticationContext._authority);\r\n};\r\n\r\nTokenRequest.prototype._createSelfSignedJwt = function() {\r\n return new SelfSignedJwt(this._callContext, this._authenticationContext._authority, this._clientId);\r\n};\r\n\r\nTokenRequest.prototype._oauthGetToken = function(oauthParameters, callback) {\r\n var client = this._createOAuth2Client();\r\n client.getToken(oauthParameters, callback);\r\n};\r\n\r\nTokenRequest.prototype._oauthGetTokenByPolling = function(oauthParameters, refresh_interval, expires_in, callback){\r\n var client = this._createOAuth2Client();\r\n client.getTokenWithPolling(oauthParameters, refresh_interval, expires_in, callback);\r\n this._pollingClient = client;\r\n}\r\n\r\nTokenRequest.prototype._createCacheDriver = function() {\r\n return new CacheDriver(\r\n this._callContext,\r\n this._authenticationContext.authority,\r\n this._resource,\r\n this._clientId,\r\n this._authenticationContext.cache,\r\n this._getTokenWithTokenResponse.bind(this)\r\n );\r\n};\r\n\r\n/**\r\n * Used by the cache driver to refresh tokens.\r\n * @param {TokenResponse} entry A token response to refresh.\r\n * @param {string} resource The resource for which to get the token.\r\n * @param {AcquireTokenCallback} callback\r\n */\r\nTokenRequest.prototype._getTokenWithTokenResponse = function(entry, resource, callback) {\r\n this._log.verbose('Called to refresh a token from the cache.');\r\n var refreshToken = entry[TokenResponseFields.REFRESH_TOKEN];\r\n this._getTokenWithRefreshToken(refreshToken, resource, null, callback);\r\n};\r\n\r\nTokenRequest.prototype._createCacheQuery = function() {\r\n var query = {\r\n clientId : this._clientId\r\n };\r\n\r\n if (this._userId) {\r\n query.userId = this._userId;\r\n } else {\r\n this._log.verbose('No userId passed for cache query.');\r\n }\r\n\r\n return query;\r\n};\r\n\r\n\r\nTokenRequest.prototype._getTokenWithCacheWrapper = function(callback, getTokenFunc) {\r\n var self = this;\r\n this._cacheDriver = this._createCacheDriver();\r\n var cacheQuery = this._createCacheQuery();\r\n this._cacheDriver.find(cacheQuery, function(err, token) {\r\n if (err) {\r\n self._log.warn('Attempt to look for token in cahce resulted in Error');\r\n self._log.warn('Attempt to look for token in cache resulted in Error: ' + err.stack, true);\r\n }\r\n\r\n if (!token) {\r\n self._log.verbose('No appropriate cached token found.');\r\n getTokenFunc.call(self, function(err, tokenResponse) {\r\n if (err) {\r\n self._log.verbose('getTokenFunc returned with err');\r\n callback(err, tokenResponse);\r\n return;\r\n }\r\n\r\n self._log.verbose('Successfully retrieved token from authority');\r\n self._cacheDriver.add(tokenResponse, function() {\r\n callback(null, tokenResponse);\r\n });\r\n });\r\n } else {\r\n self._log.info('Returning cached token.');\r\n callback(err, token);\r\n }\r\n });\r\n};\r\n\r\n/**\r\n * Store token into cache.\r\n * @param {object} tokenResponse Token response to be added into the cache.\r\n */\r\nTokenRequest.prototype._addTokenIntoCache = function(tokenResponse, callback) {\r\n this._cacheDriver = this._createCacheDriver();\r\n this._log.verbose('Storing retrieved token into cache');\r\n this._cacheDriver.add(tokenResponse, function(err) {\r\n callback(err, tokenResponse);\r\n });\r\n};\r\n\r\n/**\r\n * Adds an OAuth parameter to the paramters object if the parameter is\r\n * not null or undefined.\r\n * @private\r\n * @param {object} parameters OAuth parameters object.\r\n * @param {string} key A member of the OAuth2Parameters constants.\r\n * @param {object} value\r\n */\r\nfunction _addParameterIfAvailable(parameters, key, value) {\r\n if (value) {\r\n parameters[key] = value;\r\n }\r\n}\r\n\r\n/**\r\n * Creates a set of basic, common, OAuthParameters based on values that the TokenRequest\r\n * was created with.\r\n * @private\r\n * @param {string} grantType A member of the OAuth2GrantType constants.\r\n * @return {object}\r\n */\r\nTokenRequest.prototype._createOAuthParameters = function(grantType) {\r\n var oauthParameters = {};\r\n oauthParameters[OAuth2Parameters.GRANT_TYPE] = grantType;\r\n\r\n if (OAuth2GrantType.AUTHORIZATION_CODE !== grantType &&\r\n OAuth2GrantType.CLIENT_CREDENTIALS !== grantType &&\r\n OAuth2GrantType.DEVICE_CODE != grantType) {\r\n oauthParameters[OAuth2Parameters.SCOPE] = OAuth2Scope.OPENID;\r\n }\r\n\r\n _addParameterIfAvailable(oauthParameters, OAuth2Parameters.CLIENT_ID, this._clientId);\r\n _addParameterIfAvailable(oauthParameters, OAuth2Parameters.RESOURCE, this._resource);\r\n _addParameterIfAvailable(oauthParameters, OAuth2Parameters.REDIRECT_URI, this._redirectUri);\r\n\r\n return oauthParameters;\r\n};\r\n\r\n/**\r\n * Get's a token from AAD using a username and password\r\n * @private\r\n * @param {string} username\r\n * @param {string} password\r\n * @param {AcquireTokenCallback} callback\r\n */\r\nTokenRequest.prototype._getTokenUsernamePasswordManaged = function(username, password, callback) {\r\n this._log.verbose('Acquiring token with username password for managed user');\r\n\r\n var oauthParameters = this._createOAuthParameters(OAuth2GrantType.PASSWORD);\r\n\r\n oauthParameters[OAuth2Parameters.PASSWORD] = password;\r\n oauthParameters[OAuth2Parameters.USERNAME] = username;\r\n\r\n this._oauthGetToken(oauthParameters, callback);\r\n};\r\n\r\n/**\r\n * Determines the OAuth SAML grant type to use based on the passed in TokenType\r\n * that was returned from a RSTR.\r\n * @param {string} wstrustResponse RSTR token type.\r\n * @return {string} An OAuth grant type.\r\n */\r\nTokenRequest.prototype._getSamlGrantType = function(wstrustResponse) {\r\n var tokenType = wstrustResponse.tokenType;\r\n switch (tokenType) {\r\n case Saml.TokenTypeV1:\r\n return OAuth2GrantType.SAML1;\r\n case Saml.TokenTypeV2:\r\n return OAuth2GrantType.SAML2;\r\n default:\r\n throw this._log.createError('RSTR returned unknown token type: ' + tokenType);\r\n }\r\n};\r\n\r\n/**\r\n * Performs an OAuth SAML Assertion grant type exchange. Uses a SAML token as the credential for getting\r\n * an OAuth access token.\r\n * @param {WSTrustResponse} wstrustResponse A response from a WSTrustRequest\r\n * @param {AcquireTokenCallback} callback callback\r\n */\r\nTokenRequest.prototype._performWSTrustAssertionOAuthExchange = function(wstrustResponse, callback) {\r\n this._log.verbose('Performing OAuth assertion grant type exchange.');\r\n\r\n var oauthParameters;\r\n try {\r\n var grantType = this._getSamlGrantType(wstrustResponse);\r\n var assertion = new Buffer(wstrustResponse.token).toString('base64');\r\n oauthParameters = this._createOAuthParameters(grantType);\r\n oauthParameters[OAuth2Parameters.ASSERTION] = assertion;\r\n } catch (err) {\r\n callback(err);\r\n return;\r\n }\r\n\r\n this._oauthGetToken(oauthParameters, callback);\r\n};\r\n\r\n/**\r\n * Exchange a username and password for a SAML token from an ADFS instance via WSTrust.\r\n * @param {string} wstrustEndpoint An url of an ADFS WSTrust endpoint.\r\n * @param {string} wstrustEndpointVersion The version of the wstrust endpoint.\r\n * @param {string} username username\r\n * @param {string} password password\r\n * @param {AcquireTokenCallback} callback callback\r\n */\r\nTokenRequest.prototype._performWSTrustExchange = function(wstrustEndpoint, wstrustEndpointVersion, username, password, callback) {\r\n var self = this;\r\n var wstrust = this._createWSTrustRequest(wstrustEndpoint, 'urn:federation:MicrosoftOnline', wstrustEndpointVersion);\r\n wstrust.acquireToken(username, password, function(rstErr, response) {\r\n if (rstErr) {\r\n callback(rstErr);\r\n return;\r\n }\r\n\r\n if (!response.token) {\r\n var rstrErr = self._log.createError('Unsucessful RSTR.\\n\\terror code: ' + response.errorCode + '\\n\\tfaultMessage: ' + response.faultMessage, true);\r\n callback(rstrErr);\r\n return;\r\n }\r\n\r\n callback(null, response);\r\n });\r\n};\r\n\r\n/**\r\n * Given a username and password this method invokes a WSTrust and OAuth exchange to get an access token.\r\n * @param {string} wstrustEndpoint An url of an ADFS WSTrust endpoint.\r\n * @param {string} username username\r\n * @param {string} password password\r\n * @param {AcquireTokenCallback} callback callback\r\n */\r\nTokenRequest.prototype._performUsernamePasswordForAccessTokenExchange = function(wstrustEndpoint, wstrustEndpointVersion, username, password, callback) {\r\n var self = this;\r\n this._performWSTrustExchange(wstrustEndpoint, wstrustEndpointVersion, username, password, function(err, wstrustResponse) {\r\n if (err) {\r\n callback(err);\r\n return;\r\n }\r\n\r\n self._performWSTrustAssertionOAuthExchange(wstrustResponse, callback);\r\n });\r\n};\r\n\r\n/**\r\n * Returns an Error object indicating that AAD did not return a WSTrust endpoint.\r\n * @return {Error}\r\n */\r\nTokenRequest.prototype._createADWSTrustEndpointError = function() {\r\n return this._log.createError('AAD did not return a WSTrust endpoint. Unable to proceed.');\r\n};\r\n\r\n/**\r\n * Gets an OAuth access token using a username and password via a federated ADFS instance.\r\n * @param {string} username username\r\n * @param {string} password password\r\n * @param {AcquireTokenCallback} callback callback\r\n */\r\nTokenRequest.prototype._getTokenUsernamePasswordFederated = function(username, password, callback) {\r\n this._log.verbose('Acquiring token with username password for federated user');\r\n\r\n var self = this;\r\n if (!this._userRealm.federationMetadataUrl) {\r\n this._log.warn('Unable to retrieve federationMetadataUrl from AAD. Attempting fallback to AAD supplied endpoint.');\r\n\r\n if (!this._userRealm.federationActiveAuthUrl) {\r\n callback(this._createADWSTrustEndpointError());\r\n return;\r\n }\r\n\r\n var wstrustVersion = this._parseWStrustVersionFromFederationActiveAuthUrl(this._userRealm.federationActiveAuthUrl);\r\n this._log.verbose('Wstrust endpoint version is: ' + wstrustVersion);\r\n this._performUsernamePasswordForAccessTokenExchange(this._userRealm.federationActiveAuthUrl, wstrustVersion, username, password, callback);\r\n return;\r\n } else {\r\n var mexEndpoint = this._userRealm.federationMetadataUrl;\r\n this._log.verbose('Attempting mex');\r\n this._log.verbose('Attempting mex at: ' + mexEndpoint, true);\r\n var mex = this._createMex(mexEndpoint);\r\n mex.discover(function(mexErr) {\r\n var wstrustEndpoint;\r\n wstrustVersion = WSTrustVersion.UNDEFINED;\r\n if (mexErr) {\r\n self._log.warn('MEX exchange failed. Attempting fallback to AAD supplied endpoint.');\r\n\r\n wstrustEndpoint = self._userRealm.federationActiveAuthUrl;\r\n wstrustVersion = self._parseWStrustVersionFromFederationActiveAuthUrl(self._userRealm.federationActiveAuthUrl);\r\n if (!wstrustEndpoint) {\r\n callback(self._createADWSTrustEndpointError());\r\n return;\r\n }\r\n } else {\r\n wstrustEndpoint = mex.usernamePasswordPolicy.url;\r\n wstrustVersion = mex.usernamePasswordPolicy.version;\r\n }\r\n\r\n self._performUsernamePasswordForAccessTokenExchange(wstrustEndpoint, wstrustVersion, username, password, callback);\r\n return;\r\n });\r\n }\r\n};\r\n\r\n/**\r\n * Gets wstrust endpoint version from the federation active auth url.\r\n * @private\r\n * @param {string} federationActiveAuthUrl federationActiveAuthUrl\r\n * @return {object} The wstrust endpoint version.\r\n */\r\nTokenRequest.prototype._parseWStrustVersionFromFederationActiveAuthUrl = function(federationActiveAuthUrl) {\r\n var wstrust2005Regex = /[/trust]?[2005][/usernamemixed]?/;\r\n var wstrust13Regex = /[/trust]?[13][/usernamemixed]?/;\r\n\r\n if (wstrust2005Regex.exec(federationActiveAuthUrl)) {\r\n return WSTrustVersion.WSTRUST2005;\r\n }\r\n else if (wstrust13Regex.exec(federationActiveAuthUrl)) {\r\n return WSTrustVersion.WSTRUST13;\r\n }\r\n\r\n return WSTrustVersion.UNDEFINED;\r\n};\r\n\r\n/**\r\n * Decides whether the username represents a managed or a federated user and then\r\n * obtains a token using the appropriate protocol flow.\r\n * @private\r\n * @param {string} username\r\n * @param {string} password\r\n * @param {AcquireTokenCallback} callback\r\n */\r\nTokenRequest.prototype.getTokenWithUsernamePassword = function(username, password, callback) {\r\n this._log.info('Acquiring token with username password');\r\n this._userId = username;\r\n\r\n this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) {\r\n var self = this;\r\n\r\n if(this._authenticationContext._authority._isAdfsAuthority) {\r\n this._log.info('Skipping user realm discovery for ADFS authority');\r\n\r\n self._getTokenUsernamePasswordManaged(username, password, getTokenCompleteCallback);\r\n return;\r\n }\r\n\r\n this._userRealm = this._createUserRealmRequest(username);\r\n this._userRealm.discover(function(err) {\r\n if (err) {\r\n getTokenCompleteCallback(err);\r\n return;\r\n }\r\n\r\n switch(self._userRealm.accountType) {\r\n case AccountType.Managed:\r\n self._getTokenUsernamePasswordManaged(username, password, getTokenCompleteCallback);\r\n return;\r\n case AccountType.Federated:\r\n self._getTokenUsernamePasswordFederated(username, password, getTokenCompleteCallback);\r\n return;\r\n default:\r\n getTokenCompleteCallback(self._log.createError('Server returned an unknown AccountType: ' + self._userRealm.AccountType));\r\n }\r\n });\r\n });\r\n};\r\n\r\n/**\r\n * Obtains a token using client credentials\r\n * @private\r\n * @param {string} clientSecret\r\n * @param {AcquireTokenCallback} callback\r\n */\r\nTokenRequest.prototype.getTokenWithClientCredentials = function(clientSecret, callback) {\r\n this._log.info('Getting token with client credentials.');\r\n\r\n this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) {\r\n var oauthParameters = this._createOAuthParameters(OAuth2GrantType.CLIENT_CREDENTIALS);\r\n\r\n oauthParameters[OAuth2Parameters.CLIENT_SECRET] = clientSecret;\r\n\r\n this._oauthGetToken(oauthParameters, getTokenCompleteCallback);\r\n });\r\n};\r\n\r\n/**\r\n * Obtains a token using an authorization code.\r\n * @private\r\n * @param {string} authorizationCode\r\n * @param {string} clientSecret\r\n * @param {AcquireTokenCallback} callback\r\n */\r\nTokenRequest.prototype.getTokenWithAuthorizationCode = function(authorizationCode, clientSecret, callback) {\r\n this._log.info('Getting token with auth code.');\r\n var oauthParameters = this._createOAuthParameters(OAuth2GrantType.AUTHORIZATION_CODE);\r\n\r\n oauthParameters[OAuth2Parameters.CODE] = authorizationCode;\r\n oauthParameters[OAuth2Parameters.CLIENT_SECRET] = clientSecret;\r\n\r\n this._oauthGetToken(oauthParameters, callback);\r\n};\r\n\r\n/**\r\n * Obtains a token using a refresh token.\r\n * @param {string} refreshToken\r\n * @param {string} resource\r\n * @param {string} [clientSecret]\r\n * @param {AcquireTokenCallback} callback\r\n */\r\nTokenRequest.prototype._getTokenWithRefreshToken = function(refreshToken, resource, clientSecret, callback) {\r\n this._log.info('Getting a new token from a refresh token.');\r\n var oauthParameters = this._createOAuthParameters(OAuth2GrantType.REFRESH_TOKEN);\r\n\r\n if (resource) {\r\n oauthParameters[OAuth2Parameters.RESOURCE] = resource;\r\n }\r\n\r\n if (clientSecret) {\r\n oauthParameters[OAuth2Parameters.CLIENT_SECRET] = clientSecret;\r\n }\r\n\r\n oauthParameters[OAuth2Parameters.REFRESH_TOKEN] = refreshToken;\r\n\r\n this._oauthGetToken(oauthParameters, callback);\r\n};\r\n\r\n/**\r\n * Obtains a token using a refresh token.\r\n * @param {string} refreshToken\r\n * @param {string} [clientSecret]\r\n * @param {AcquireTokenCallback} callback\r\n */\r\nTokenRequest.prototype.getTokenWithRefreshToken = function(refreshToken, clientSecret, callback) {\r\n this._getTokenWithRefreshToken(refreshToken, null, clientSecret, callback);\r\n};\r\n\r\n/**\r\n * Obtains a token from the cache, refreshing it or using a MRRT if necessary.\r\n * @param {string} [userId] The user associated with the cached token.\r\n * @param {AcquireTokenCallback} callback\r\n */\r\nTokenRequest.prototype.getTokenFromCacheWithRefresh = function(userId, callback) {\r\n var self = this;\r\n this._log.info('Getting token from cache with refresh if necessary.');\r\n\r\n this._userId = userId;\r\n this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) {\r\n // If this method was called then no cached entry was found. Since\r\n // this particular version of acquireToken can only retrieve tokens\r\n // from the cache, return an error.\r\n getTokenCompleteCallback(self._log.createError('Entry not found in cache.'));\r\n });\r\n};\r\n\r\n/**\r\n * Creates a self signed jwt.\r\n * @param {string} authorityUrl\r\n * @param {string} certificate A PEM encoded certificate private key.\r\n * @param {string} thumbprint\r\n * @return {string} A self signed JWT\r\n */\r\nTokenRequest.prototype._createJwt = function(authorityUrl, certificate, thumbprint) {\r\n var jwt;\r\n var ssj = this._createSelfSignedJwt();\r\n jwt = ssj.create(certificate, thumbprint);\r\n if (!jwt) {\r\n throw this._log.createError('Failed to create JWT');\r\n }\r\n\r\n return jwt;\r\n};\r\n\r\n/**\r\n * Obtains a token via a certificate. The certificate is used to generate a self signed\r\n * JWT token that is passed as a client_assertion.\r\n * @param {string} certificate A PEM encoded certificate private key.\r\n * @param {string} thumbprint A hex encoded thumbprint of the certificate.\r\n * @param {AcquireTokenCallback} callback\r\n */\r\nTokenRequest.prototype.getTokenWithCertificate = function(certificate, thumbprint, callback) {\r\n\r\n this._log.info('Getting a token via certificate.');\r\n\r\n var authorityUrl = this._authenticationContext._authority;\r\n\r\n var jwt;\r\n try {\r\n jwt = this._createJwt(authorityUrl, certificate, thumbprint);\r\n } catch (err) {\r\n callback(err);\r\n return;\r\n }\r\n\r\n var oauthParameters = this._createOAuthParameters(OAuth2GrantType.CLIENT_CREDENTIALS);\r\n oauthParameters[OAuth2Parameters.CLIENT_ASSERTION_TYPE] = OAuth2GrantType.JWT_BEARER;\r\n oauthParameters[OAuth2Parameters.CLIENT_ASSERTION] = jwt;\r\n\r\n this._getTokenWithCacheWrapper(callback, function(getTokenCompleteCallback) {\r\n this._oauthGetToken(oauthParameters, getTokenCompleteCallback);\r\n });\r\n};\r\n\r\nTokenRequest.prototype.getTokenWithDeviceCode = function(userCodeInfo, callback) {\r\n this._log.info('Getting a token via device code');\r\n var self = this;\r\n\r\n var oauthParameters = this._createOAuthParameters(OAuth2GrantType.DEVICE_CODE);\r\n oauthParameters[OAuth2Parameters.CODE] = userCodeInfo[DeviceCodeResponseParameters.DEVICE_CODE];\r\n\r\n var interval = userCodeInfo[DeviceCodeResponseParameters.INTERVAL];\r\n var expires_in = userCodeInfo[DeviceCodeResponseParameters.EXPIRES_IN];\r\n\r\n if (interval <= 0) {\r\n callback(new Error('invalid refresh interval'));\r\n }\r\n\r\n this._oauthGetTokenByPolling(oauthParameters, interval, expires_in, function(err, tokenResponse) {\r\n if (err) {\r\n self._log.verbose('Token polling request returend with err.');\r\n callback(err, tokenResponse);\r\n }\r\n else {\r\n self._addTokenIntoCache(tokenResponse, callback);\r\n }\r\n });\r\n};\r\n\r\nTokenRequest.prototype.cancelTokenRequestWithDeviceCode = function() {\r\n this._pollingClient.cancelPollingRequest();\r\n};\r\n\r\nmodule.exports = TokenRequest;\r\n","/*\r\n * @copyright\r\n * Copyright © Microsoft Open Technologies, Inc.\r\n *\r\n * All Rights Reserved\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http: *www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\r\n * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\r\n * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A\r\n * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.\r\n *\r\n * See the Apache License, Version 2.0 for the specific language\r\n * governing permissions and limitations under the License.\r\n */\r\n'use strict';\r\n\r\nvar querystring = require('querystring');\r\nvar request = require('request');\r\nvar _ = require('underscore');\r\nvar url = require('url');\r\n\r\nvar constants = require('./constants');\r\nvar Logger = require('./log').Logger;\r\nvar util = require('./util');\r\n\r\nvar AccountType = constants.UserRealm.AccountType;\r\nvar FederationProtocolType = constants.UserRealm.FederationProtocolType;\r\n\r\nvar USER_REALM_PATH_TEMPLATE = 'common/UserRealm/';\r\n\r\n/**\r\n * Create a new UserRealm object\r\n * @private\r\n * @constructor\r\n * @param {object} callContext Contains any context information that applies to the request.\r\n * @param {string} userPrinciple The username for which a realm needs to be discovered.\r\n * @param {string} authority The string url of the authority that owns the userPrinciple.\r\n */\r\nfunction UserRealm(callContext, userPrinciple, authority) {\r\n this._log = new Logger('UserRealm', callContext._logContext);\r\n this._callContext = callContext;\r\n this._apiVersion = '1.0';\r\n this._federationProtocol = null;\r\n this._accountType = null;\r\n this._federationMetadataUrl = null;\r\n this._federationActiveAuthUrl = null;\r\n this._userPrinciple = userPrinciple;\r\n this._authority = authority;\r\n}\r\n\r\n/**\r\n* The API version requested by UserRealm.\r\n* @type {string}\r\n* @instance\r\n* @memberOf UserRealm\r\n* @name apiVersion\r\n*/\r\nObject.defineProperty(UserRealm.prototype, 'apiVersion', {\r\n get : function() {\r\n return this._apiVersion;\r\n }\r\n});\r\n\r\n/**\r\n* The federation protocol used by the users realm.\r\n* @type {string}\r\n* @instance\r\n* @memberOf UserRealm\r\n* @name federationProtocol\r\n*/\r\nObject.defineProperty(UserRealm.prototype, 'federationProtocol', {\r\n get : function() {\r\n return this._federationProtocol;\r\n }\r\n});\r\n\r\n/**\r\n* The Type of account. Either managed or federated.\r\n* @type {string}\r\n* @instance\r\n* @memberOf UserRealm\r\n* @name accountType\r\n*/\r\nObject.defineProperty(UserRealm.prototype, 'accountType', {\r\n get : function() {\r\n return this._accountType;\r\n }\r\n});\r\n\r\n/**\r\n* If this is a federated account then this property will contain the mex url.\r\n* @type {string}\r\n* @instance\r\n* @memberOf UserRealm\r\n* @name federationsMetadataUrl\r\n*/\r\nObject.defineProperty(UserRealm.prototype, 'federationMetadataUrl', {\r\n get : function() {\r\n return this._federationMetadataUrl;\r\n }\r\n});\r\n\r\n/**\r\n* If the account is federated this will contain the authentication endpoint.\r\n* @type {string}\r\n* @instance\r\n* @memberOf UserRealm\r\n* @name federationActiveAuthUrl\r\n*/\r\nObject.defineProperty(UserRealm.prototype, 'federationActiveAuthUrl', {\r\n get : function() {\r\n return this._federationActiveAuthUrl;\r\n }\r\n});\r\n\r\n/**\r\n* Given the authority url this method constructs a full user realm discovery url.\r\n* @private\r\n* @returns A full user realm discovery url including path and query string.\r\n*/\r\nUserRealm.prototype._getUserRealmUrl = function() {\r\n var userRealmUrl = util.copyUrl(this._authority);\r\n var urlEncodedUser = encodeURIComponent(this._userPrinciple);\r\n userRealmUrl.pathname = USER_REALM_PATH_TEMPLATE.replace('', urlEncodedUser);\r\n\r\n var userRealmQuery = {\r\n 'api-version' : this._apiVersion\r\n };\r\n\r\n userRealmUrl.search = querystring.stringify(userRealmQuery);\r\n\r\n userRealmUrl = util.copyUrl(userRealmUrl);\r\n\r\n return userRealmUrl;\r\n};\r\n\r\n/**\r\n* Given a constants object and a value, validates that the value is a key in the constants object.\r\n* @private\r\n* @param {object} constants An object containing constant key value pairs.\r\n* @param {string} value A value to check against the constants\r\n* @param {bool} caseSensitive set to true if comparisons should be made as case sensitive. Defaults to false.\r\n* @returns {bool|string} If value passed in matches one of the constants then the return value is the matched constant.\r\n* If a non case sensitive match was done, then the value returned may be different than the value\r\n* passed in. If there is no match then the method returns false.\r\n*/\r\nUserRealm.prototype._validateConstantValue = function(constants, value, caseSensitive) {\r\n if (!value) {\r\n return false;\r\n }\r\n if (!caseSensitive) {\r\n value = value.toLowerCase();\r\n }\r\n return _.contains(_.values(constants), value) ? value : false;\r\n};\r\n\r\n/**\r\n* Checks whether an account type string is valid.\r\n* @private\r\n* @param {string} type An account type string.\r\n* @returns {bool}\r\n*/\r\nUserRealm.prototype._validateAccountType = function(type) {\r\n return this._validateConstantValue(AccountType, type);\r\n};\r\n\r\n/**\r\n* Checks whether a federation protocol string is valid.\r\n* @private\r\n* @param {string} protocol A federation protocol string.\r\n* @returns {bool}\r\n*/\r\nUserRealm.prototype._validateFederationProtocol = function(protocol) {\r\n return this._validateConstantValue(FederationProtocolType, protocol);\r\n};\r\n\r\n/**\r\n* Logs the values parsed as part of user realm discovery.\r\n* @private\r\n*/\r\nUserRealm.prototype._logParsedResponse = function() {\r\n this._log.verbose('UserRealm response:');\r\n this._log.verbose(' AccountType: ' + this.accountType);\r\n this._log.verbose(' FederationProtocol: ' + this.federationProtocol);\r\n this._log.verbose(' FederationMetatdataUrl: ' + this.federationMetadataUrl, true);\r\n this._log.verbose(' FederationActiveAuthUrl: ' + this.federationActiveAuthUrl, true);\r\n};\r\n\r\n/**\r\n* Parses the response from a user realm discovery request.\r\n* @private\r\n* @param {string} body The body returned as part of the http user realm discovery request.\r\n* @param {UserRealm.DiscoverCallback} callback Called when parsing is complete.\r\n*/\r\nUserRealm.prototype._parseDiscoveryResponse = function(body, callback) {\r\n this._log.verbose('Discovery response:\\n' + body, true);\r\n\r\n var response;\r\n try {\r\n response = JSON.parse(body);\r\n } catch (err) {\r\n callback(this._log.createError('Parsing realm discovery respone JSON failed: ' + body, true));\r\n return;\r\n }\r\n\r\n var accountType = this._validateAccountType(response['account_type']);\r\n if (!accountType) {\r\n callback(this._log.createError('Cannot parse account_type: ' + accountType));\r\n return;\r\n }\r\n\r\n this._accountType = accountType;\r\n\r\n if (this._accountType === AccountType.Federated) {\r\n var protocol = this._validateFederationProtocol(response['federation_protocol']);\r\n\r\n if (!protocol) {\r\n callback(this._log.createError('Cannot parse federation protocol: ' + protocol));\r\n return;\r\n }\r\n\r\n this._federationProtocol = protocol;\r\n this._federationMetadataUrl = response['federation_metadata_url'];\r\n this._federationActiveAuthUrl = response['federation_active_auth_url'];\r\n }\r\n\r\n this._logParsedResponse();\r\n callback();\r\n};\r\n\r\n/**\r\n* @callback DiscoverCallback\r\n* @memberOf UserRealm\r\n* @param {Error} error If an error occurs during discovery then this parameter will be used to return the error.\r\n*/\r\n\r\n/**\r\n* Performs user realm discovery and fills in the properties on this object.\r\n* @private\r\n* @param {UserRealm.DiscoverCallback} callback Called when discovery is complete.\r\n*/\r\nUserRealm.prototype.discover = function(callback) {\r\n var self = this;\r\n var options = util.createRequestOptions(\r\n this,\r\n {\r\n headers : {\r\n Accept : 'application/json'\r\n }\r\n }\r\n );\r\n\r\n var userRealmUrl = this._getUserRealmUrl();\r\n this._log.verbose('Performing user realm discovery at: ' + url.format(userRealmUrl), true);\r\n request.get(userRealmUrl, options, util.createRequestHandler('User Realm Discovery', this._log, callback,\r\n function(response, body) {\r\n self._parseDiscoveryResponse(body, callback);\r\n })\r\n );\r\n};\r\n\r\nmodule.exports = UserRealm;","/*\r\n * @copyright\r\n * Copyright © Microsoft Open Technologies, Inc.\r\n *\r\n * All Rights Reserved\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http: *www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\r\n * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\r\n * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A\r\n * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.\r\n *\r\n * See the Apache License, Version 2.0 for the specific language\r\n * governing permissions and limitations under the License.\r\n */\r\n'use strict';\r\n\r\nvar _ = require('underscore');\r\nvar adalIdConstants = require('./constants').AdalIdParameters;\r\nvar os = require('os');\r\nvar url = require('url');\r\n\r\nvar ADAL_VERSION;\r\n\r\n/**\r\n * @namespace Util\r\n * @private\r\n */\r\n\r\nfunction loadAdalVersion() {\r\n ADAL_VERSION = require('../package.json').version;\r\n}\r\n\r\nfunction adalInit() {\r\n loadAdalVersion();\r\n}\r\n\r\n/**\r\n * @static\r\n * @memberOf Util\r\n * @param {string|int} statusCode An HTTP status code.\r\n */\r\nfunction isHttpSuccess(statusCode) {\r\n return statusCode >= 200 && statusCode < 300;\r\n}\r\n\r\nfunction addDefaultRequestHeaders (self, options) {\r\n if (!options.headers) {\r\n options.headers = {};\r\n }\r\n var headers = options.headers;\r\n if (!headers['Accept-Charset']) {\r\n headers['Accept-Charset'] = 'utf-8';\r\n }\r\n headers['client-request-id'] = self._callContext._logContext.correlationId;\r\n headers['return-client-request-id'] = 'true';\r\n\r\n // ADAL Id headers\r\n headers[adalIdConstants.SKU] = adalIdConstants.NODE_SKU;\r\n headers[adalIdConstants.VERSION] = ADAL_VERSION;\r\n headers[adalIdConstants.OS] = os.platform();\r\n headers[adalIdConstants.CPU] = os.arch();\r\n}\r\n\r\n/**\r\n* Central place for housing default request options. This is a place holder\r\n* for when SSL validation is implemented an all requests are subject to that\r\n* policy.\r\n* @static\r\n* @memberOf Util\r\n* @param {object} options A set of options that will be merged with teh default options\r\n* These will override any default options.\r\n* @returns {object} Returns the merged options.\r\n*/\r\nfunction createRequestOptions(self, options) {\r\n var defaultOptions = {}; //{ strictSSL : true };\r\n var mergedOptions = defaultOptions;\r\n if (options) {\r\n _.extend(mergedOptions, options);\r\n }\r\n if (self._callContext.options && self._callContext.options.http) {\r\n _.extend(mergedOptions, self._callContext.options.http);\r\n }\r\n\r\n addDefaultRequestHeaders(self, mergedOptions);\r\n return mergedOptions;\r\n}\r\n\r\nfunction logReturnCorrelationId(log, operationMessage, response) {\r\n if (response && response.headers && response.headers['client-request-id']) {\r\n log.info(operationMessage + 'Server returned this correlationId: ' + response.headers['client-request-id'], true);\r\n }\r\n}\r\n\r\n/**\r\n* Creates a function that can be used as the callback for http request operations. This is meant\r\n* to centralize error handling in one place.\r\n* @static\r\n* @memberOf Util\r\n* @param {string} operationMessage A message to be prepended to logged error strings. This should be something like 'Mex Request'\r\n* and summarize the purpose of the http request.\r\n* @param {object} log A Logger object being used by the calling component.\r\n* @param {Util.CreateRequestHandlerErrorCallback} errorCallback Called in the event of an error.\r\n* @param {Util.CreateRequestHandlerSuccessCallabck} successCallback Called on successfull completion of the request.\r\n*/\r\nfunction createRequestHandler(operationMessage, log, errorCallback, successCallback) {\r\n return function(err, response, body) {\r\n logReturnCorrelationId(log, operationMessage, response);\r\n if (err) {\r\n log.error(operationMessage + ' request failed with', err, true);\r\n errorCallback(err);\r\n return;\r\n }\r\n if (!isHttpSuccess(response.statusCode)) {\r\n var returnErrorString = operationMessage + ' request returned http error: ' + response.statusCode;\r\n var errorResponse;\r\n if (body) {\r\n returnErrorString += ' and server response: ' + body;\r\n try {\r\n errorResponse = JSON.parse(body);\r\n } catch (e) {\r\n // No problem if it doesn't parse.\r\n }\r\n }\r\n errorCallback(log.createError(returnErrorString, true), errorResponse);\r\n return;\r\n }\r\n\r\n successCallback(response, body);\r\n };\r\n}\r\n\r\n/**\r\n* @callback CreateRequestHandlerErrorCallback\r\n* @memberOf Util\r\n* @param {Error} error An error object.\r\n*/\r\n\r\n/**\r\n* @callback CreateRequestHandlerSuccessCallabck\r\n* @memberOf Util\r\n* @param {object} response The response object returned from request.\r\n* @param {string} body The body of the http response.\r\n*/\r\n\r\n/**\r\n* Deep copies a url object.\r\n* @static\r\n* @memberOf Util\r\n* @param {URL} urlSource The source url object to copy.\r\n* @returns {URL} A deep copy of sourceUrl.\r\n*/\r\nfunction copyUrl(urlSource) {\r\n return url.parse(url.format(urlSource));\r\n}\r\n\r\nfunction convertUrlSafeToRegularBase64EncodedString(str) {\r\n return str.replace(/-/g, '+').replace(/_/g, '/');\r\n}\r\n\r\nfunction convertRegularToUrlSafeBase64EncodedString(str) {\r\n return str.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '');\r\n}\r\n\r\nfunction base64DecodeStringUrlSafe(str) {\r\n var base64 = convertUrlSafeToRegularBase64EncodedString(str);\r\n return (new Buffer(base64, 'base64')).toString('utf8');\r\n}\r\n\r\nfunction base64EncodeStringUrlSafe(str) {\r\n var base64 = (new Buffer(str, 'utf8').toString('base64'));\r\n var converted = convertRegularToUrlSafeBase64EncodedString(base64);\r\n return converted;\r\n}\r\n\r\nmodule.exports.adalInit = adalInit;\r\nmodule.exports.isHttpSuccess = isHttpSuccess;\r\nmodule.exports.createRequestHandler = createRequestHandler;\r\nmodule.exports.createRequestOptions = createRequestOptions;\r\nmodule.exports.copyUrl = copyUrl;\r\nmodule.exports.base64DecodeStringUrlSafe = base64DecodeStringUrlSafe;\r\nmodule.exports.base64EncodeStringUrlSafe = base64EncodeStringUrlSafe;\r\nmodule.exports.convertRegularToUrlSafeBase64EncodedString = convertRegularToUrlSafeBase64EncodedString;","/*\r\n * @copyright\r\n * Copyright © Microsoft Open Technologies, Inc.\r\n *\r\n * All Rights Reserved\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http: *www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\r\n * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\r\n * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A\r\n * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.\r\n *\r\n * See the Apache License, Version 2.0 for the specific language\r\n * governing permissions and limitations under the License.\r\n */\r\n'use strict';\r\n\r\nvar request = require('request');\r\nvar uuid = require('uuid');\r\n\r\nvar Logger = require('./log').Logger;\r\nvar util = require('./util');\r\nvar WSTrustResponse = require('./wstrust-response');\r\nvar WSTrustVersion = require('./constants').WSTrustVersion;\r\n\r\nvar USERNAME_PLACEHOLDER = '{UsernamePlaceHolder}';\r\nvar PASSWORD_PLACEHOLDER = '{PasswordPlaceHolder}';\r\n\r\n/**\r\n * Creates a new instance of WSTrustRequest\r\n * @constructor\r\n * @private\r\n * @param {object} callContext Contains any context information that applies to the request.\r\n * @param {string} wstrustEndpointUrl An STS WS-Trust soap endpoint.\r\n * @param {string} appliesTo A URI that identifies a service for which the a token is to be obtained.\r\n */\r\nfunction WSTrustRequest(callContext, wstrustEndpointUrl, appliesTo, wstrustEndpointVersion) {\r\n this._log = new Logger('WSTrustRequest', callContext._logContext);\r\n this._callContext = callContext;\r\n this._wstrustEndpointUrl = wstrustEndpointUrl;\r\n this._appliesTo = appliesTo;\r\n this._wstrustEndpointVersion = wstrustEndpointVersion;\r\n}\r\n\r\n/**\r\n* Given a Date object adds the minutes parameter and returns a new Date object.\r\n* @private\r\n* @static\r\n* @memberOf WSTrustRequest\r\n* @param {Date} date A Date object.\r\n* @param {Number} minutes The number of minutes to add to the date parameter.\r\n* @returns {Date} Returns a Date object.\r\n*/\r\nfunction _datePlusMinutes(date, minutes) {\r\n var minutesInMilliSeconds = minutes * 60 * 1000;\r\n var epochTime = date.getTime() + minutesInMilliSeconds;\r\n return new Date(epochTime);\r\n}\r\n\r\n/**\r\n * Builds the soap security header for the RST message.\r\n * @private\r\n * @param {string} username A username\r\n * @param {string} password The passowrd that corresponds to the username parameter.\r\n * @returns {string} A string that contains the soap security header.\r\n */\r\nWSTrustRequest.prototype._buildSecurityHeader = function() {\r\n var timeNow = new Date();\r\n var expireTime = _datePlusMinutes(timeNow, 10);\r\n var timeNowString = timeNow.toISOString();\r\n var expireTimeString = expireTime.toISOString();\r\n\r\n var securityHeaderXml = \r\n '\\\r\n \\\r\n ' + timeNowString + '\\\r\n ' + expireTimeString + '\\\r\n \\\r\n \\\r\n ' + USERNAME_PLACEHOLDER + '\\\r\n ' + PASSWORD_PLACEHOLDER + '\\\r\n \\\r\n ';\r\n\r\n return securityHeaderXml;\r\n};\r\n\r\n/**\r\n * Replaces the placeholders in the RST template with the actual username and password values.\r\n * @private\r\n * @param {string} RSTTemplate An RST with placeholders for username and password.\r\n * @param {string} username A username\r\n * @param {string} password The passowrd that corresponds to the username parameter.\r\n * @returns {string} A string containing a complete RST soap message.\r\n */\r\n\r\nWSTrustRequest.prototype._populateRSTUsernamePassword = function(RSTTemplate, username, password) {\r\n var RST = RSTTemplate.replace(USERNAME_PLACEHOLDER, username).replace(PASSWORD_PLACEHOLDER, this._populatedEscapedPassword(password));\r\n return RST;\r\n};\r\n\r\n/**\r\n * Escape xml characters in password. \r\n * @private\r\n * @param {string} password The password to be excaped with xml charaters. \r\n */\r\nWSTrustRequest.prototype._populatedEscapedPassword = function (password) { \r\n var escapedPassword = password;\r\n return escapedPassword.replace(/&/g, '&')\r\n .replace(/\"/g, '"')\r\n .replace(/'/g, ''')\r\n .replace(//g, '>');\r\n}\r\n\r\n/**\r\n * Builds a WS-Trust RequestSecurityToken (RST) message using username password authentication.\r\n * @private\r\n * @param {string} username A username\r\n * @param {string} password The passowrd that corresponds to the username parameter.\r\n * @returns {string} A string containing a complete RST soap message.\r\n */\r\nWSTrustRequest.prototype._buildRST = function(username, password) {\r\n var messageID = uuid.v4();\r\n\r\n // Create a template RST with placeholders for the username and password so the\r\n // the RST can be logged without the sensitive information.\r\n var schemaLocation = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd';\r\n var soapAction = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue';\r\n var rstTrustNamespace = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512';\r\n var keyType = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer';\r\n var requestType = 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue';\r\n\r\n if (this._wstrustEndpointVersion === WSTrustVersion.WSTRUST2005) {\r\n soapAction = 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue';\r\n rstTrustNamespace = 'http://schemas.xmlsoap.org/ws/2005/02/trust';\r\n keyType = 'http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey';\r\n requestType = 'http://schemas.xmlsoap.org/ws/2005/02/trust/Issue'; \r\n }\r\n\r\n var RSTTemplate =\r\n '\\\r\n \\\r\n ' + soapAction + '\\\r\n urn:uuid:' + messageID + '\\\r\n \\\r\n http://www.w3.org/2005/08/addressing/anonymous\\\r\n \\\r\n ' + this._wstrustEndpointUrl + '\\\r\n ' + this._buildSecurityHeader() + '\\\r\n \\\r\n \\\r\n \\\r\n \\\r\n \\\r\n ' + this._appliesTo + '\\\r\n \\\r\n \\\r\n ' + keyType + '\\\r\n ' + requestType + '\\\r\n \\\r\n \\\r\n ';\r\n\r\n this._log.verbose('Created RST: \\n' + RSTTemplate, true);\r\n\r\n var RST = this._populateRSTUsernamePassword(RSTTemplate, username, password);\r\n return RST;\r\n};\r\n\r\n/**\r\n * Handles the processing of a RSTR\r\n * @private\r\n * @param {string} body\r\n * @param {WSTrustRequest.AcquireTokenCallback} callback\r\n */\r\nWSTrustRequest.prototype._handleRSTR = function(body, callback) {\r\n var err;\r\n\r\n var wstrustResponse = new WSTrustResponse(this._callContext, body, this._wstrustEndpointVersion);\r\n try {\r\n wstrustResponse.parse();\r\n } catch (error) {\r\n err = error;\r\n }\r\n\r\n callback(err, wstrustResponse);\r\n};\r\n\r\n/**\r\n * Performs a WS-Trust RequestSecurityToken request to obtain a federated token in exchange for a username password.\r\n * @param {string} username A username\r\n * @param {string} password The passowrd that corresponds to the username parameter.\r\n * @param {WSTrustRequest.AcquireTokenCallback} callback Called once the federated token has been retrieved or on error.\r\n*/\r\nWSTrustRequest.prototype.acquireToken = function(username, password, callback) {\r\n if (this._wstrustEndpointVersion === WSTrustVersion.UNDEFINED) {\r\n var err = this._log.createError('Unsupported wstrust endpoint version. Current support version is wstrust2005 or wstrust13.');\r\n callback(err);\r\n return; \r\n }\r\n\r\n var self = this;\r\n var RST = this._buildRST(username, password);\r\n\r\n var soapAction = this._wstrustEndpointVersion === WSTrustVersion.WSTRUST2005 ? 'http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue' : 'http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue';\r\n\r\n var options = util.createRequestOptions(\r\n this,\r\n {\r\n headers : {\r\n 'Content-Type' : 'application/soap+xml; charset=utf-8',\r\n 'SOAPAction' : soapAction\r\n },\r\n body : RST\r\n }\r\n );\r\n\r\n this._log.verbose('Sending RST to: ' + this._wstrustEndpointUrl, true);\r\n\r\n request.post(this._wstrustEndpointUrl, options, util.createRequestHandler('WS-Trust RST', this._log, callback,\r\n function(response, body) {\r\n self._handleRSTR(body, callback);\r\n }\r\n ));\r\n};\r\n\r\n/**\r\n* @callback AcquireTokenCallback\r\n* @memberOf WSTrustRequest\r\n* @param {Error} err Contains an error object if acquireToken fails.\r\n* @param {WSTrustResponse} A successful response to the RST.\r\n*/\r\n\r\nmodule.exports = WSTrustRequest;\r\n","/*\r\n * @copyright\r\n * Copyright © Microsoft Open Technologies, Inc.\r\n *\r\n * All Rights Reserved\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http: *www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\r\n * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\r\n * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A\r\n * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.\r\n *\r\n * See the Apache License, Version 2.0 for the specific language\r\n * governing permissions and limitations under the License.\r\n */\r\n'use strict';\r\n\r\nvar xmldom = require('xmldom');\r\n\r\nvar xmlutil = require('./xmlutil');\r\n\r\nvar Logger = require('./log').Logger;\r\n\r\nvar WSTrustVersion = require('./constants').WSTrustVersion;\r\n\r\nvar select = xmlutil.xpathSelect;\r\nvar DOMParser = xmldom.DOMParser;\r\n\r\n// A regular expression for finding the SAML Assertion in an RSTR. Used to remove the SAML\r\n// assertion when logging the RSTR.\r\nvar assertionRegEx = /RequestedSecurityToken.*?((<.*?:Assertion.*?>).*<\\/.*?Assertion>).*?/;\r\n\r\n/**\r\n * Creates a log message that contains the RSTR scrubbed of the actual SAML assertion.\r\n * @private\r\n * @return {string} A log message.\r\n */\r\nfunction scrubRSTRLogMessage(RSTR) {\r\n var scrubbedRSTR = null;\r\n\r\n var singleLineRSTR = RSTR.replace(/(\\r\\n|\\n|\\r)/gm,'');\r\n\r\n var matchResult = assertionRegEx.exec(singleLineRSTR);\r\n if (null === matchResult) {\r\n // No Assertion was matched so just return the RSTR as is.\r\n scrubbedRSTR = singleLineRSTR;\r\n } else {\r\n var samlAssertion = matchResult[1];\r\n var samlAssertionStartTag = matchResult[2];\r\n\r\n scrubbedRSTR = singleLineRSTR.replace(samlAssertion, samlAssertionStartTag + 'ASSERTION CONTENTS REDACTED');\r\n }\r\n\r\n return 'RSTR Response: ' + scrubbedRSTR;\r\n}\r\n\r\n/**\r\n * Creates a new WSTrustResponse instance.\r\n * @constructor\r\n * @private\r\n * @param {object} callContext Contains any context information that applies to the request.\r\n * @param {string} response A soap response from a WS-Trust request.\r\n * @param {sting} wstrustVersion The version for the WS-Trust request. \r\n */\r\nfunction WSTrustResponse(callContext, response, wstrustVersion) {\r\n this._log = new Logger('WSTrustResponse', callContext._logContext);\r\n this._callContext = callContext;\r\n this._response = response;\r\n this._dom = null;\r\n this._errorCode = null;\r\n this._faultMessage = null;\r\n this._tokenType = null;\r\n this._token = null;\r\n this._wstrustVersion = wstrustVersion;\r\n\r\n this._log.verbose(function(){return scrubRSTRLogMessage(response);});\r\n}\r\n\r\n/**\r\n * If the soap response contained a soap fault then this property will contain the fault\r\n * error code. Otherwise it will return null\r\n * @instance\r\n * @type {string}\r\n * @memberOf WSTrustResponse\r\n * @name errorCode\r\n */\r\nObject.defineProperty(WSTrustResponse.prototype, 'errorCode', {\r\n get: function() {\r\n return this._errorCode;\r\n }\r\n});\r\n\r\n/**\r\n * @property {string} FaultMessage If the soap resopnse contained a soap fault with a fault message then it will\r\n * be returned by this property.\r\n * @instance\r\n * @type {string}\r\n * @memberOf WSTrustResponse\r\n * @name faultMessage\r\n */\r\nObject.defineProperty(WSTrustResponse.prototype, 'faultMessage', {\r\n get: function() {\r\n return this._faultMessage;\r\n }\r\n});\r\n\r\n/**\r\n * @property {string} TokenType If the soap resonse contained a token then this property will contain\r\n * the token type uri\r\n * @instance\r\n * @type {string}\r\n * @memberOf WSTrustResponse\r\n * @name tokenType\r\n */\r\nObject.defineProperty(WSTrustResponse.prototype, 'tokenType', {\r\n get: function() {\r\n return this._tokenType;\r\n }\r\n});\r\n\r\n/**\r\n * @property {string} Token If the soap response contained a token then this property will hold that token.\r\n * @instance\r\n * @type {string}\r\n * @memberOf WSTrustResponse\r\n * @name token\r\n */\r\nObject.defineProperty(WSTrustResponse.prototype, 'token', {\r\n get: function() {\r\n return this._token;\r\n }\r\n});\r\n\r\n // Sample error message\r\n //\r\n // \r\n // http://www.w3.org/2005/08/addressing/soap/fault\r\n // - \r\n // \r\n // 2013-07-30T00:32:21.989Z\r\n // 2013-07-30T00:37:21.989Z\r\n // \r\n // \r\n // \r\n // \r\n // \r\n // \r\n // s:Sender\r\n // \r\n // a:RequestFailed\r\n // \r\n // \r\n // \r\n // MSIS3127: The specified request failed.\r\n // \r\n // \r\n // \r\n //\r\n\r\n/**\r\n * Attempts to parse an error from the soap response. If there is one then it\r\n * will fill in the error related properties. Otherwsie it will do nothing.\r\n * @private\r\n * @returns {bool} true if an error was found and parsed in the response.\r\n */\r\nWSTrustResponse.prototype._parseError = function() {\r\n var errorFound = false;\r\n\r\n var faultNode = select(this._dom, '//s:Envelope/s:Body/s:Fault/s:Reason');\r\n if (faultNode.length) {\r\n this._faultMessage = xmlutil.serializeNodeChildren(faultNode[0]);\r\n\r\n if (this._faultMessage) {\r\n errorFound = true;\r\n }\r\n }\r\n\r\n // Subcode has minoccurs=0 and maxoccurs=1(default) according to the http://www.w3.org/2003/05/soap-envelope\r\n // Subcode may have another subcode as well. This is only targetting at top level subcode.\r\n // Subcode value may have different messages not always uses http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd.\r\n // text inside the value is not possible to select without prefix, so substring is necessary\r\n var subcodeNode = select(this._dom, '//s:Envelope/s:Body/s:Fault/s:Code/s:Subcode/s:Value');\r\n if (1 < subcodeNode.length) {\r\n throw this._log.createError('Found too many fault code values:' + subcodeNode.length);\r\n }\r\n\r\n if (subcodeNode.length) {\r\n var errorCode = subcodeNode[0].firstChild.data;\r\n this._errorCode = (errorCode.split(':'))[1];\r\n errorFound = true;\r\n }\r\n\r\n return errorFound;\r\n};\r\n\r\n/**\r\n * Attempts to parse a token from the soap response. If there is one then it will fill in the\r\n * token related properties. Otherwise it does nothing.\r\n * @private\r\n * @throws {Error} If the response is not parseable, or too many tokens are found.\r\n */\r\nWSTrustResponse.prototype._parseToken = function() {\r\n var xPath = this._wstrustVersion === WSTrustVersion.WSTRUST2005 ? '//s:Envelope/s:Body/t:RequestSecurityTokenResponse/t:TokenType' : '//s:Envelope/s:Body/wst:RequestSecurityTokenResponseCollection/wst:RequestSecurityTokenResponse/wst:TokenType';\r\n\r\n var tokenTypeNodes = select(this._dom, xPath);\r\n if (!tokenTypeNodes.length) {\r\n this._log.warn('No TokenType elements found in RSTR');\r\n }\r\n\r\n for (var i = 0, length = tokenTypeNodes.length; i < length; i++) {\r\n if (this._token) {\r\n this._log.warn('Found more than one returned token. Using the first.');\r\n break;\r\n }\r\n\r\n var tokenTypeNode = tokenTypeNodes[i];\r\n var tokenType = xmlutil.findElementText(tokenTypeNode);\r\n if (!tokenType) {\r\n this._log.warn('Could not find token type in RSTR token');\r\n }\r\n\r\n var securityTokenPath = this._wstrustVersion === WSTrustVersion.WSTRUST2005 ? 't:RequestedSecurityToken' : 'wst:RequestedSecurityToken';\r\n var requestedTokenNode = select(tokenTypeNode.parentNode, securityTokenPath);\r\n if (1 < requestedTokenNode) {\r\n throw this._log.createError('Found too many RequestedSecurityToken nodes for token type: ' + tokenType);\r\n }\r\n if (!requestedTokenNode.length) {\r\n this._log.warn('Unable to find RequestsSecurityToken element associated with TokenType element: ' + tokenType);\r\n continue;\r\n }\r\n\r\n var token = xmlutil.serializeNodeChildren(requestedTokenNode[0]);\r\n if (!token) {\r\n this._log.warn('Unable to find token associated with TokenType element: ' + tokenType);\r\n continue;\r\n }\r\n\r\n this._token = token;\r\n this._tokenType = tokenType;\r\n\r\n this._log.info('Found token of type: ' + this._tokenType);\r\n }\r\n\r\n if (!this._token) {\r\n throw this._log.createError('Unable to find any tokens in RSTR.');\r\n }\r\n};\r\n\r\n/**\r\n * This method parses the soap response that was passed in at construction.\r\n * @throws {Error} If the server returned an error, or there was any failure to parse the response.\r\n */\r\nWSTrustResponse.prototype.parse = function() {\r\n if (!this._response) {\r\n throw this._log.createError('Received empty RSTR response body.');\r\n }\r\n\r\n try {\r\n try {\r\n var options = {\r\n errorHandler : this._log.error\r\n };\r\n this._dom = new DOMParser(options).parseFromString(this._response);\r\n } catch (err) {\r\n throw this._log.createError('Failed to parse RSTR in to DOM', err, true);\r\n }\r\n\r\n var errorFound = this._parseError();\r\n\r\n if (errorFound) {\r\n var stringErrorCode = this.ErrorCode || 'NONE';\r\n var stringFaultMessage = this.FaultMessage || 'NONE';\r\n throw this._log.createError('Server returned error in RSTR - ErrorCode: ' + stringErrorCode + ' : FaultMessage: ' + stringFaultMessage, true);\r\n }\r\n\r\n this._parseToken();\r\n } catch (err) {\r\n delete this._dom;\r\n throw err;\r\n }\r\n};\r\n\r\nmodule.exports = WSTrustResponse;","/*\r\n * @copyright\r\n * Copyright © Microsoft Open Technologies, Inc.\r\n *\r\n * All Rights Reserved\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http: *www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\r\n * OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\r\n * ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A\r\n * PARTICULAR PURPOSE, MERCHANTABILITY OR NON-INFRINGEMENT.\r\n *\r\n * See the Apache License, Version 2.0 for the specific language\r\n * governing permissions and limitations under the License.\r\n */\r\n'use strict';\r\n\r\nvar _ = require('underscore');\r\nvar select = require('xpath.js');\r\nvar XMLSerializer = require('xmldom').XMLSerializer;\r\n\r\nvar constants = require('./constants');\r\n\r\n/**\r\n * @namespace XmlUtil\r\n * @private\r\n */\r\n\r\nvar XPATH_PATH_TEMPLATE = '*[local-name() = \\'LOCAL_NAME\\' and namespace-uri() = \\'NAMESPACE\\']';\r\n/**\r\n* The xpath implementation being used does not have a way of matching expanded namespace.\r\n* This method takes an xpath query and expands all of the namespaces involved. It then\r\n* re-writes the query in to a longer form that directory matches the correct namespaces.\r\n* @private\r\n* @static\r\n* @memberOf XmlUtil\r\n* @param {string} xpath The expath query string to expand.\r\n* @returns {string} An expanded xpath query.\r\n*/\r\nfunction expandQNames(xpath) {\r\n var namespaces = constants.XmlNamespaces;\r\n var pathParts = xpath.split('/');\r\n for (var i=0; i < pathParts.length; i++) {\r\n if (pathParts[i].indexOf(':') !== -1) {\r\n var QNameParts = pathParts[i].split(':');\r\n if (QNameParts.length !== 2) {\r\n throw new Error('Unable to parse XPath string : ' + xpath + ' : with QName : ' + pathParts[i]);\r\n }\r\n var expandedPath = XPATH_PATH_TEMPLATE.replace('LOCAL_NAME', QNameParts[1]);\r\n expandedPath = expandedPath.replace('NAMESPACE', namespaces[QNameParts[0]]);\r\n pathParts[i] = expandedPath;\r\n }\r\n }\r\n return pathParts.join('/');\r\n}\r\n\r\nvar exports = {\r\n\r\n /**\r\n * Performs an xpath select that does appropriate namespace matching since the imported\r\n * xpath module does not properly handle namespaces.\r\n * @static\r\n * @memberOf XmlUtil\r\n * @param {object} dom A dom object created by the xmldom module\r\n * @param {string} xpath An xpath expression\r\n * @return {array} An array of matching dom nodes.\r\n */\r\n xpathSelect : function (dom, xpath) {\r\n return select(dom, expandQNames(xpath));\r\n },\r\n\r\n /**\r\n * Given a dom node serializes all immediate children that are xml elements.\r\n * @static\r\n * @memberOf XmlUtil\r\n * @param {object} node An xml dom node.\r\n * @return {string} Serialized xml.\r\n */\r\n serializeNodeChildren : function(node) {\r\n var doc = '';\r\n var sibling = node.firstChild;\r\n var serializer = new XMLSerializer();\r\n\r\n while (sibling) {\r\n if (this.isElementNode(sibling)) {\r\n doc += serializer.serializeToString(sibling);\r\n }\r\n sibling = sibling.nextSibling;\r\n }\r\n\r\n return doc !== '' ? doc : null;\r\n },\r\n\r\n /**\r\n * Detects whether the passed in dom node represents an xml element.\r\n * @static\r\n * @memberOf XmlUtil\r\n * @param {object} node An xml dom node.\r\n * @return {Boolean} true if the node represents an element.\r\n */\r\n isElementNode : function(node) {\r\n return _.has(node, 'tagName');\r\n },\r\n\r\n /**\r\n * Given an xmldom node this function returns any text data contained within.\r\n * @static\r\n * @memberOf XmlUtil\r\n * @param {object} node An xmldom node from which the data should be extracted.\r\n * @return {string} Any data found within the element or null if none is found.\r\n */\r\n findElementText : function(node) {\r\n var sibling = node.firstChild;\r\n while (sibling && !sibling.data) {\r\n sibling = sibling.nextSibling;\r\n }\r\n\r\n return sibling.data ? sibling.data : null;\r\n }\r\n};\r\n\r\nmodule.exports = exports;","'use strict';\n\nvar compileSchema = require('./compile')\n , resolve = require('./compile/resolve')\n , Cache = require('./cache')\n , SchemaObject = require('./compile/schema_obj')\n , stableStringify = require('fast-json-stable-stringify')\n , formats = require('./compile/formats')\n , rules = require('./compile/rules')\n , $dataMetaSchema = require('./data')\n , util = require('./compile/util');\n\nmodule.exports = Ajv;\n\nAjv.prototype.validate = validate;\nAjv.prototype.compile = compile;\nAjv.prototype.addSchema = addSchema;\nAjv.prototype.addMetaSchema = addMetaSchema;\nAjv.prototype.validateSchema = validateSchema;\nAjv.prototype.getSchema = getSchema;\nAjv.prototype.removeSchema = removeSchema;\nAjv.prototype.addFormat = addFormat;\nAjv.prototype.errorsText = errorsText;\n\nAjv.prototype._addSchema = _addSchema;\nAjv.prototype._compile = _compile;\n\nAjv.prototype.compileAsync = require('./compile/async');\nvar customKeyword = require('./keyword');\nAjv.prototype.addKeyword = customKeyword.add;\nAjv.prototype.getKeyword = customKeyword.get;\nAjv.prototype.removeKeyword = customKeyword.remove;\nAjv.prototype.validateKeyword = customKeyword.validate;\n\nvar errorClasses = require('./compile/error_classes');\nAjv.ValidationError = errorClasses.Validation;\nAjv.MissingRefError = errorClasses.MissingRef;\nAjv.$dataMetaSchema = $dataMetaSchema;\n\nvar META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema';\n\nvar META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ];\nvar META_SUPPORT_DATA = ['/properties'];\n\n/**\n * Creates validator instance.\n * Usage: `Ajv(opts)`\n * @param {Object} opts optional options\n * @return {Object} ajv instance\n */\nfunction Ajv(opts) {\n if (!(this instanceof Ajv)) return new Ajv(opts);\n opts = this._opts = util.copy(opts) || {};\n setLogger(this);\n this._schemas = {};\n this._refs = {};\n this._fragments = {};\n this._formats = formats(opts.format);\n\n this._cache = opts.cache || new Cache;\n this._loadingSchemas = {};\n this._compilations = [];\n this.RULES = rules();\n this._getId = chooseGetId(opts);\n\n opts.loopRequired = opts.loopRequired || Infinity;\n if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true;\n if (opts.serialize === undefined) opts.serialize = stableStringify;\n this._metaOpts = getMetaSchemaOptions(this);\n\n if (opts.formats) addInitialFormats(this);\n if (opts.keywords) addInitialKeywords(this);\n addDefaultMetaSchema(this);\n if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);\n if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}});\n addInitialSchemas(this);\n}\n\n\n\n/**\n * Validate data using schema\n * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize.\n * @this Ajv\n * @param {String|Object} schemaKeyRef key, ref or schema object\n * @param {Any} data to be validated\n * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).\n */\nfunction validate(schemaKeyRef, data) {\n var v;\n if (typeof schemaKeyRef == 'string') {\n v = this.getSchema(schemaKeyRef);\n if (!v) throw new Error('no schema with key or ref \"' + schemaKeyRef + '\"');\n } else {\n var schemaObj = this._addSchema(schemaKeyRef);\n v = schemaObj.validate || this._compile(schemaObj);\n }\n\n var valid = v(data);\n if (v.$async !== true) this.errors = v.errors;\n return valid;\n}\n\n\n/**\n * Create validating function for passed schema.\n * @this Ajv\n * @param {Object} schema schema object\n * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.\n * @return {Function} validating function\n */\nfunction compile(schema, _meta) {\n var schemaObj = this._addSchema(schema, undefined, _meta);\n return schemaObj.validate || this._compile(schemaObj);\n}\n\n\n/**\n * Adds schema to the instance.\n * @this Ajv\n * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.\n * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.\n * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.\n * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.\n * @return {Ajv} this for method chaining\n */\nfunction addSchema(schema, key, _skipValidation, _meta) {\n if (Array.isArray(schema)){\n for (var i=0; i} errors optional array of validation errors, if not passed errors from the instance are used.\n * @param {Object} options optional options with properties `separator` and `dataVar`.\n * @return {String} human readable string with all errors descriptions\n */\nfunction errorsText(errors, options) {\n errors = errors || this.errors;\n if (!errors) return 'No errors';\n options = options || {};\n var separator = options.separator === undefined ? ', ' : options.separator;\n var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;\n\n var text = '';\n for (var i=0; i%\\\\^`{|}]|%[0-9a-f]{2})|\\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\\*)?)*\\})*$/i;\n// For the source: https://gist.github.com/dperini/729294\n// For test cases: https://mathiasbynens.be/demo/url-regex\n// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983.\n// var URL = /^(?:(?:https?|ftp):\\/\\/)(?:\\S+(?::\\S*)?@)?(?:(?!10(?:\\.\\d{1,3}){3})(?!127(?:\\.\\d{1,3}){3})(?!169\\.254(?:\\.\\d{1,3}){2})(?!192\\.168(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u{00a1}-\\u{ffff}0-9]+-)*[a-z\\u{00a1}-\\u{ffff}0-9]+)(?:\\.(?:[a-z\\u{00a1}-\\u{ffff}0-9]+-)*[a-z\\u{00a1}-\\u{ffff}0-9]+)*(?:\\.(?:[a-z\\u{00a1}-\\u{ffff}]{2,})))(?::\\d{2,5})?(?:\\/[^\\s]*)?$/iu;\nvar URL = /^(?:(?:http[s\\u017F]?|ftp):\\/\\/)(?:(?:[\\0-\\x08\\x0E-\\x1F!-\\x9F\\xA1-\\u167F\\u1681-\\u1FFF\\u200B-\\u2027\\u202A-\\u202E\\u2030-\\u205E\\u2060-\\u2FFF\\u3001-\\uD7FF\\uE000-\\uFEFE\\uFF00-\\uFFFF]|[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF])+(?::(?:[\\0-\\x08\\x0E-\\x1F!-\\x9F\\xA1-\\u167F\\u1681-\\u1FFF\\u200B-\\u2027\\u202A-\\u202E\\u2030-\\u205E\\u2060-\\u2FFF\\u3001-\\uD7FF\\uE000-\\uFEFE\\uFF00-\\uFFFF]|[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF])*)?@)?(?:(?!10(?:\\.[0-9]{1,3}){3})(?!127(?:\\.[0-9]{1,3}){3})(?!169\\.254(?:\\.[0-9]{1,3}){2})(?!192\\.168(?:\\.[0-9]{1,3}){2})(?!172\\.(?:1[6-9]|2[0-9]|3[01])(?:\\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\\xA1-\\uD7FF\\uE000-\\uFFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF])+-)*(?:[0-9a-z\\xA1-\\uD7FF\\uE000-\\uFFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF])+)(?:\\.(?:(?:[0-9a-z\\xA1-\\uD7FF\\uE000-\\uFFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF])+-)*(?:[0-9a-z\\xA1-\\uD7FF\\uE000-\\uFFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF])+)*(?:\\.(?:(?:[a-z\\xA1-\\uD7FF\\uE000-\\uFFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\\/(?:[\\0-\\x08\\x0E-\\x1F!-\\x9F\\xA1-\\u167F\\u1681-\\u1FFF\\u200B-\\u2027\\u202A-\\u202E\\u2030-\\u205E\\u2060-\\u2FFF\\u3001-\\uD7FF\\uE000-\\uFEFE\\uFF00-\\uFFFF]|[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF])*)?$/i;\nvar UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;\nvar JSON_POINTER = /^(?:\\/(?:[^~/]|~0|~1)*)*$/;\nvar JSON_POINTER_URI_FRAGMENT = /^#(?:\\/(?:[a-z0-9_\\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;\nvar RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\\/(?:[^~/]|~0|~1)*)*)$/;\n\n\nmodule.exports = formats;\n\nfunction formats(mode) {\n mode = mode == 'full' ? 'full' : 'fast';\n return util.copy(formats[mode]);\n}\n\n\nformats.fast = {\n // date: http://tools.ietf.org/html/rfc3339#section-5.6\n date: /^\\d\\d\\d\\d-[0-1]\\d-[0-3]\\d$/,\n // date-time: http://tools.ietf.org/html/rfc3339#section-5.6\n time: /^(?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)?$/i,\n 'date-time': /^\\d\\d\\d\\d-[0-1]\\d-[0-3]\\d[t\\s](?:[0-2]\\d:[0-5]\\d:[0-5]\\d|23:59:60)(?:\\.\\d+)?(?:z|[+-]\\d\\d(?::?\\d\\d)?)$/i,\n // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js\n uri: /^(?:[a-z][a-z0-9+\\-.]*:)(?:\\/?\\/)?[^\\s]*$/i,\n 'uri-reference': /^(?:(?:[a-z][a-z0-9+\\-.]*:)?\\/?\\/)?(?:[^\\\\\\s#][^\\s#]*)?(?:#[^\\\\\\s]*)?$/i,\n 'uri-template': URITEMPLATE,\n url: URL,\n // email (sources from jsen validator):\n // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363\n // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation')\n email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,\n hostname: HOSTNAME,\n // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html\n ipv4: /^(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$/,\n // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses\n ipv6: /^\\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(?:%.+)?\\s*$/i,\n regex: regex,\n // uuid: http://tools.ietf.org/html/rfc4122\n uuid: UUID,\n // JSON-pointer: https://tools.ietf.org/html/rfc6901\n // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A\n 'json-pointer': JSON_POINTER,\n 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,\n // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00\n 'relative-json-pointer': RELATIVE_JSON_POINTER\n};\n\n\nformats.full = {\n date: date,\n time: time,\n 'date-time': date_time,\n uri: uri,\n 'uri-reference': URIREF,\n 'uri-template': URITEMPLATE,\n url: URL,\n email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,\n hostname: HOSTNAME,\n ipv4: /^(?:(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$/,\n ipv6: /^\\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(?:%.+)?\\s*$/i,\n regex: regex,\n uuid: UUID,\n 'json-pointer': JSON_POINTER,\n 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,\n 'relative-json-pointer': RELATIVE_JSON_POINTER\n};\n\n\nfunction isLeapYear(year) {\n // https://tools.ietf.org/html/rfc3339#appendix-C\n return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);\n}\n\n\nfunction date(str) {\n // full-date from http://tools.ietf.org/html/rfc3339#section-5.6\n var matches = str.match(DATE);\n if (!matches) return false;\n\n var year = +matches[1];\n var month = +matches[2];\n var day = +matches[3];\n\n return month >= 1 && month <= 12 && day >= 1 &&\n day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]);\n}\n\n\nfunction time(str, full) {\n var matches = str.match(TIME);\n if (!matches) return false;\n\n var hour = matches[1];\n var minute = matches[2];\n var second = matches[3];\n var timeZone = matches[5];\n return ((hour <= 23 && minute <= 59 && second <= 59) ||\n (hour == 23 && minute == 59 && second == 60)) &&\n (!full || timeZone);\n}\n\n\nvar DATE_TIME_SEPARATOR = /t|\\s/i;\nfunction date_time(str) {\n // http://tools.ietf.org/html/rfc3339#section-5.6\n var dateTime = str.split(DATE_TIME_SEPARATOR);\n return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true);\n}\n\n\nvar NOT_URI_FRAGMENT = /\\/|:/;\nfunction uri(str) {\n // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required \".\"\n return NOT_URI_FRAGMENT.test(str) && URI.test(str);\n}\n\n\nvar Z_ANCHOR = /[^\\\\]\\\\Z/;\nfunction regex(str) {\n if (Z_ANCHOR.test(str)) return false;\n try {\n new RegExp(str);\n return true;\n } catch(e) {\n return false;\n }\n}\n","'use strict';\n\nvar resolve = require('./resolve')\n , util = require('./util')\n , errorClasses = require('./error_classes')\n , stableStringify = require('fast-json-stable-stringify');\n\nvar validateGenerator = require('../dotjs/validate');\n\n/**\n * Functions below are used inside compiled validations function\n */\n\nvar ucs2length = util.ucs2length;\nvar equal = require('fast-deep-equal');\n\n// this error is thrown by async schemas to return validation errors via exception\nvar ValidationError = errorClasses.Validation;\n\nmodule.exports = compile;\n\n\n/**\n * Compiles schema to validation function\n * @this Ajv\n * @param {Object} schema schema object\n * @param {Object} root object with information about the root schema for this schema\n * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution\n * @param {String} baseId base ID for IDs in the schema\n * @return {Function} validation function\n */\nfunction compile(schema, root, localRefs, baseId) {\n /* jshint validthis: true, evil: true */\n /* eslint no-shadow: 0 */\n var self = this\n , opts = this._opts\n , refVal = [ undefined ]\n , refs = {}\n , patterns = []\n , patternsHash = {}\n , defaults = []\n , defaultsHash = {}\n , customRules = [];\n\n root = root || { schema: schema, refVal: refVal, refs: refs };\n\n var c = checkCompiling.call(this, schema, root, baseId);\n var compilation = this._compilations[c.index];\n if (c.compiling) return (compilation.callValidate = callValidate);\n\n var formats = this._formats;\n var RULES = this.RULES;\n\n try {\n var v = localCompile(schema, root, localRefs, baseId);\n compilation.validate = v;\n var cv = compilation.callValidate;\n if (cv) {\n cv.schema = v.schema;\n cv.errors = null;\n cv.refs = v.refs;\n cv.refVal = v.refVal;\n cv.root = v.root;\n cv.$async = v.$async;\n if (opts.sourceCode) cv.source = v.source;\n }\n return v;\n } finally {\n endCompiling.call(this, schema, root, baseId);\n }\n\n /* @this {*} - custom context, see passContext option */\n function callValidate() {\n /* jshint validthis: true */\n var validate = compilation.validate;\n var result = validate.apply(this, arguments);\n callValidate.errors = validate.errors;\n return result;\n }\n\n function localCompile(_schema, _root, localRefs, baseId) {\n var isRoot = !_root || (_root && _root.schema == _schema);\n if (_root.schema != root.schema)\n return compile.call(self, _schema, _root, localRefs, baseId);\n\n var $async = _schema.$async === true;\n\n var sourceCode = validateGenerator({\n isTop: true,\n schema: _schema,\n isRoot: isRoot,\n baseId: baseId,\n root: _root,\n schemaPath: '',\n errSchemaPath: '#',\n errorPath: '\"\"',\n MissingRefError: errorClasses.MissingRef,\n RULES: RULES,\n validate: validateGenerator,\n util: util,\n resolve: resolve,\n resolveRef: resolveRef,\n usePattern: usePattern,\n useDefault: useDefault,\n useCustomRule: useCustomRule,\n opts: opts,\n formats: formats,\n logger: self.logger,\n self: self\n });\n\n sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode)\n + vars(defaults, defaultCode) + vars(customRules, customRuleCode)\n + sourceCode;\n\n if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema);\n // console.log('\\n\\n\\n *** \\n', JSON.stringify(sourceCode));\n var validate;\n try {\n var makeValidate = new Function(\n 'self',\n 'RULES',\n 'formats',\n 'root',\n 'refVal',\n 'defaults',\n 'customRules',\n 'equal',\n 'ucs2length',\n 'ValidationError',\n sourceCode\n );\n\n validate = makeValidate(\n self,\n RULES,\n formats,\n root,\n refVal,\n defaults,\n customRules,\n equal,\n ucs2length,\n ValidationError\n );\n\n refVal[0] = validate;\n } catch(e) {\n self.logger.error('Error compiling schema, function code:', sourceCode);\n throw e;\n }\n\n validate.schema = _schema;\n validate.errors = null;\n validate.refs = refs;\n validate.refVal = refVal;\n validate.root = isRoot ? validate : _root;\n if ($async) validate.$async = true;\n if (opts.sourceCode === true) {\n validate.source = {\n code: sourceCode,\n patterns: patterns,\n defaults: defaults\n };\n }\n\n return validate;\n }\n\n function resolveRef(baseId, ref, isRoot) {\n ref = resolve.url(baseId, ref);\n var refIndex = refs[ref];\n var _refVal, refCode;\n if (refIndex !== undefined) {\n _refVal = refVal[refIndex];\n refCode = 'refVal[' + refIndex + ']';\n return resolvedRef(_refVal, refCode);\n }\n if (!isRoot && root.refs) {\n var rootRefId = root.refs[ref];\n if (rootRefId !== undefined) {\n _refVal = root.refVal[rootRefId];\n refCode = addLocalRef(ref, _refVal);\n return resolvedRef(_refVal, refCode);\n }\n }\n\n refCode = addLocalRef(ref);\n var v = resolve.call(self, localCompile, root, ref);\n if (v === undefined) {\n var localSchema = localRefs && localRefs[ref];\n if (localSchema) {\n v = resolve.inlineRef(localSchema, opts.inlineRefs)\n ? localSchema\n : compile.call(self, localSchema, root, localRefs, baseId);\n }\n }\n\n if (v === undefined) {\n removeLocalRef(ref);\n } else {\n replaceLocalRef(ref, v);\n return resolvedRef(v, refCode);\n }\n }\n\n function addLocalRef(ref, v) {\n var refId = refVal.length;\n refVal[refId] = v;\n refs[ref] = refId;\n return 'refVal' + refId;\n }\n\n function removeLocalRef(ref) {\n delete refs[ref];\n }\n\n function replaceLocalRef(ref, v) {\n var refId = refs[ref];\n refVal[refId] = v;\n }\n\n function resolvedRef(refVal, code) {\n return typeof refVal == 'object' || typeof refVal == 'boolean'\n ? { code: code, schema: refVal, inline: true }\n : { code: code, $async: refVal && !!refVal.$async };\n }\n\n function usePattern(regexStr) {\n var index = patternsHash[regexStr];\n if (index === undefined) {\n index = patternsHash[regexStr] = patterns.length;\n patterns[index] = regexStr;\n }\n return 'pattern' + index;\n }\n\n function useDefault(value) {\n switch (typeof value) {\n case 'boolean':\n case 'number':\n return '' + value;\n case 'string':\n return util.toQuotedString(value);\n case 'object':\n if (value === null) return 'null';\n var valueStr = stableStringify(value);\n var index = defaultsHash[valueStr];\n if (index === undefined) {\n index = defaultsHash[valueStr] = defaults.length;\n defaults[index] = value;\n }\n return 'default' + index;\n }\n }\n\n function useCustomRule(rule, schema, parentSchema, it) {\n if (self._opts.validateSchema !== false) {\n var deps = rule.definition.dependencies;\n if (deps && !deps.every(function(keyword) {\n return Object.prototype.hasOwnProperty.call(parentSchema, keyword);\n }))\n throw new Error('parent schema must have all required keywords: ' + deps.join(','));\n\n var validateSchema = rule.definition.validateSchema;\n if (validateSchema) {\n var valid = validateSchema(schema);\n if (!valid) {\n var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);\n if (self._opts.validateSchema == 'log') self.logger.error(message);\n else throw new Error(message);\n }\n }\n }\n\n var compile = rule.definition.compile\n , inline = rule.definition.inline\n , macro = rule.definition.macro;\n\n var validate;\n if (compile) {\n validate = compile.call(self, schema, parentSchema, it);\n } else if (macro) {\n validate = macro.call(self, schema, parentSchema, it);\n if (opts.validateSchema !== false) self.validateSchema(validate, true);\n } else if (inline) {\n validate = inline.call(self, it, rule.keyword, schema, parentSchema);\n } else {\n validate = rule.definition.validate;\n if (!validate) return;\n }\n\n if (validate === undefined)\n throw new Error('custom keyword \"' + rule.keyword + '\"failed to compile');\n\n var index = customRules.length;\n customRules[index] = validate;\n\n return {\n code: 'customRule' + index,\n validate: validate\n };\n }\n}\n\n\n/**\n * Checks if the schema is currently compiled\n * @this Ajv\n * @param {Object} schema schema to compile\n * @param {Object} root root object\n * @param {String} baseId base schema ID\n * @return {Object} object with properties \"index\" (compilation index) and \"compiling\" (boolean)\n */\nfunction checkCompiling(schema, root, baseId) {\n /* jshint validthis: true */\n var index = compIndex.call(this, schema, root, baseId);\n if (index >= 0) return { index: index, compiling: true };\n index = this._compilations.length;\n this._compilations[index] = {\n schema: schema,\n root: root,\n baseId: baseId\n };\n return { index: index, compiling: false };\n}\n\n\n/**\n * Removes the schema from the currently compiled list\n * @this Ajv\n * @param {Object} schema schema to compile\n * @param {Object} root root object\n * @param {String} baseId base schema ID\n */\nfunction endCompiling(schema, root, baseId) {\n /* jshint validthis: true */\n var i = compIndex.call(this, schema, root, baseId);\n if (i >= 0) this._compilations.splice(i, 1);\n}\n\n\n/**\n * Index of schema compilation in the currently compiled list\n * @this Ajv\n * @param {Object} schema schema to compile\n * @param {Object} root root object\n * @param {String} baseId base schema ID\n * @return {Integer} compilation index\n */\nfunction compIndex(schema, root, baseId) {\n /* jshint validthis: true */\n for (var i=0; i= 0xD800 && value <= 0xDBFF && pos < len) {\n // high surrogate, and there is a next character\n value = str.charCodeAt(pos);\n if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate\n }\n }\n return length;\n};\n","'use strict';\n\n\nmodule.exports = {\n copy: copy,\n checkDataType: checkDataType,\n checkDataTypes: checkDataTypes,\n coerceToTypes: coerceToTypes,\n toHash: toHash,\n getProperty: getProperty,\n escapeQuotes: escapeQuotes,\n equal: require('fast-deep-equal'),\n ucs2length: require('./ucs2length'),\n varOccurences: varOccurences,\n varReplace: varReplace,\n schemaHasRules: schemaHasRules,\n schemaHasRulesExcept: schemaHasRulesExcept,\n schemaUnknownRules: schemaUnknownRules,\n toQuotedString: toQuotedString,\n getPathExpr: getPathExpr,\n getPath: getPath,\n getData: getData,\n unescapeFragment: unescapeFragment,\n unescapeJsonPointer: unescapeJsonPointer,\n escapeFragment: escapeFragment,\n escapeJsonPointer: escapeJsonPointer\n};\n\n\nfunction copy(o, to) {\n to = to || {};\n for (var key in o) to[key] = o[key];\n return to;\n}\n\n\nfunction checkDataType(dataType, data, strictNumbers, negate) {\n var EQUAL = negate ? ' !== ' : ' === '\n , AND = negate ? ' || ' : ' && '\n , OK = negate ? '!' : ''\n , NOT = negate ? '' : '!';\n switch (dataType) {\n case 'null': return data + EQUAL + 'null';\n case 'array': return OK + 'Array.isArray(' + data + ')';\n case 'object': return '(' + OK + data + AND +\n 'typeof ' + data + EQUAL + '\"object\"' + AND +\n NOT + 'Array.isArray(' + data + '))';\n case 'integer': return '(typeof ' + data + EQUAL + '\"number\"' + AND +\n NOT + '(' + data + ' % 1)' +\n AND + data + EQUAL + data +\n (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')';\n case 'number': return '(typeof ' + data + EQUAL + '\"' + dataType + '\"' +\n (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')';\n default: return 'typeof ' + data + EQUAL + '\"' + dataType + '\"';\n }\n}\n\n\nfunction checkDataTypes(dataTypes, data, strictNumbers) {\n switch (dataTypes.length) {\n case 1: return checkDataType(dataTypes[0], data, strictNumbers, true);\n default:\n var code = '';\n var types = toHash(dataTypes);\n if (types.array && types.object) {\n code = types.null ? '(': '(!' + data + ' || ';\n code += 'typeof ' + data + ' !== \"object\")';\n delete types.null;\n delete types.array;\n delete types.object;\n }\n if (types.number) delete types.integer;\n for (var t in types)\n code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true);\n\n return code;\n }\n}\n\n\nvar COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]);\nfunction coerceToTypes(optionCoerceTypes, dataTypes) {\n if (Array.isArray(dataTypes)) {\n var types = [];\n for (var i=0; i= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl);\n return paths[lvl - up];\n }\n\n if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl);\n data = 'data' + ((lvl - up) || '');\n if (!jsonPointer) return data;\n }\n\n var expr = data;\n var segments = jsonPointer.split('/');\n for (var i=0; i',\n $notOp = $isMax ? '>' : '<',\n $errorKeyword = undefined;\n if (!($isData || typeof $schema == 'number' || $schema === undefined)) {\n throw new Error($keyword + ' must be number');\n }\n if (!($isDataExcl || $schemaExcl === undefined || typeof $schemaExcl == 'number' || typeof $schemaExcl == 'boolean')) {\n throw new Error($exclusiveKeyword + ' must be number or boolean');\n }\n if ($isDataExcl) {\n var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr),\n $exclusive = 'exclusive' + $lvl,\n $exclType = 'exclType' + $lvl,\n $exclIsNumber = 'exclIsNumber' + $lvl,\n $opExpr = 'op' + $lvl,\n $opStr = '\\' + ' + $opExpr + ' + \\'';\n out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; ';\n $schemaValueExcl = 'schemaExcl' + $lvl;\n out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \\'boolean\\' && ' + ($exclType) + ' != \\'undefined\\' && ' + ($exclType) + ' != \\'number\\') { ';\n var $errorKeyword = $exclusiveKeyword;\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = ''; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ($errorKeyword || '_exclusiveLimit') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'' + ($exclusiveKeyword) + ' should be boolean\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n var __err = out;\n out = $$outStack.pop();\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError([' + (__err) + ']); ';\n } else {\n out += ' validate.errors = [' + (__err) + ']; return false; ';\n }\n } else {\n out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n }\n out += ' } else if ( ';\n if ($isData) {\n out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \\'number\\') || ';\n }\n out += ' ' + ($exclType) + ' == \\'number\\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \\'' + ($op) + '\\' : \\'' + ($op) + '=\\'; ';\n if ($schema === undefined) {\n $errorKeyword = $exclusiveKeyword;\n $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;\n $schemaValue = $schemaValueExcl;\n $isData = $isDataExcl;\n }\n } else {\n var $exclIsNumber = typeof $schemaExcl == 'number',\n $opStr = $op;\n if ($exclIsNumber && $isData) {\n var $opExpr = '\\'' + $opStr + '\\'';\n out += ' if ( ';\n if ($isData) {\n out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \\'number\\') || ';\n }\n out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { ';\n } else {\n if ($exclIsNumber && $schema === undefined) {\n $exclusive = true;\n $errorKeyword = $exclusiveKeyword;\n $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;\n $schemaValue = $schemaExcl;\n $notOp += '=';\n } else {\n if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema);\n if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) {\n $exclusive = true;\n $errorKeyword = $exclusiveKeyword;\n $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;\n $notOp += '=';\n } else {\n $exclusive = false;\n $opStr += '=';\n }\n }\n var $opExpr = '\\'' + $opStr + '\\'';\n out += ' if ( ';\n if ($isData) {\n out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \\'number\\') || ';\n }\n out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { ';\n }\n }\n $errorKeyword = $errorKeyword || $keyword;\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = ''; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ($errorKeyword || '_limit') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'should be ' + ($opStr) + ' ';\n if ($isData) {\n out += '\\' + ' + ($schemaValue);\n } else {\n out += '' + ($schemaValue) + '\\'';\n }\n }\n if (it.opts.verbose) {\n out += ' , schema: ';\n if ($isData) {\n out += 'validate.schema' + ($schemaPath);\n } else {\n out += '' + ($schema);\n }\n out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n var __err = out;\n out = $$outStack.pop();\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError([' + (__err) + ']); ';\n } else {\n out += ' validate.errors = [' + (__err) + ']; return false; ';\n }\n } else {\n out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n }\n out += ' } ';\n if ($breakOnError) {\n out += ' else { ';\n }\n return out;\n}\n","'use strict';\nmodule.exports = function generate__limitItems(it, $keyword, $ruleType) {\n var out = ' ';\n var $lvl = it.level;\n var $dataLvl = it.dataLevel;\n var $schema = it.schema[$keyword];\n var $schemaPath = it.schemaPath + it.util.getProperty($keyword);\n var $errSchemaPath = it.errSchemaPath + '/' + $keyword;\n var $breakOnError = !it.opts.allErrors;\n var $errorKeyword;\n var $data = 'data' + ($dataLvl || '');\n var $isData = it.opts.$data && $schema && $schema.$data,\n $schemaValue;\n if ($isData) {\n out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';\n $schemaValue = 'schema' + $lvl;\n } else {\n $schemaValue = $schema;\n }\n if (!($isData || typeof $schema == 'number')) {\n throw new Error($keyword + ' must be number');\n }\n var $op = $keyword == 'maxItems' ? '>' : '<';\n out += 'if ( ';\n if ($isData) {\n out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \\'number\\') || ';\n }\n out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { ';\n var $errorKeyword = $keyword;\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = ''; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ($errorKeyword || '_limitItems') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'should NOT have ';\n if ($keyword == 'maxItems') {\n out += 'more';\n } else {\n out += 'fewer';\n }\n out += ' than ';\n if ($isData) {\n out += '\\' + ' + ($schemaValue) + ' + \\'';\n } else {\n out += '' + ($schema);\n }\n out += ' items\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: ';\n if ($isData) {\n out += 'validate.schema' + ($schemaPath);\n } else {\n out += '' + ($schema);\n }\n out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n var __err = out;\n out = $$outStack.pop();\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError([' + (__err) + ']); ';\n } else {\n out += ' validate.errors = [' + (__err) + ']; return false; ';\n }\n } else {\n out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n }\n out += '} ';\n if ($breakOnError) {\n out += ' else { ';\n }\n return out;\n}\n","'use strict';\nmodule.exports = function generate__limitLength(it, $keyword, $ruleType) {\n var out = ' ';\n var $lvl = it.level;\n var $dataLvl = it.dataLevel;\n var $schema = it.schema[$keyword];\n var $schemaPath = it.schemaPath + it.util.getProperty($keyword);\n var $errSchemaPath = it.errSchemaPath + '/' + $keyword;\n var $breakOnError = !it.opts.allErrors;\n var $errorKeyword;\n var $data = 'data' + ($dataLvl || '');\n var $isData = it.opts.$data && $schema && $schema.$data,\n $schemaValue;\n if ($isData) {\n out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';\n $schemaValue = 'schema' + $lvl;\n } else {\n $schemaValue = $schema;\n }\n if (!($isData || typeof $schema == 'number')) {\n throw new Error($keyword + ' must be number');\n }\n var $op = $keyword == 'maxLength' ? '>' : '<';\n out += 'if ( ';\n if ($isData) {\n out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \\'number\\') || ';\n }\n if (it.opts.unicode === false) {\n out += ' ' + ($data) + '.length ';\n } else {\n out += ' ucs2length(' + ($data) + ') ';\n }\n out += ' ' + ($op) + ' ' + ($schemaValue) + ') { ';\n var $errorKeyword = $keyword;\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = ''; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ($errorKeyword || '_limitLength') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'should NOT be ';\n if ($keyword == 'maxLength') {\n out += 'longer';\n } else {\n out += 'shorter';\n }\n out += ' than ';\n if ($isData) {\n out += '\\' + ' + ($schemaValue) + ' + \\'';\n } else {\n out += '' + ($schema);\n }\n out += ' characters\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: ';\n if ($isData) {\n out += 'validate.schema' + ($schemaPath);\n } else {\n out += '' + ($schema);\n }\n out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n var __err = out;\n out = $$outStack.pop();\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError([' + (__err) + ']); ';\n } else {\n out += ' validate.errors = [' + (__err) + ']; return false; ';\n }\n } else {\n out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n }\n out += '} ';\n if ($breakOnError) {\n out += ' else { ';\n }\n return out;\n}\n","'use strict';\nmodule.exports = function generate__limitProperties(it, $keyword, $ruleType) {\n var out = ' ';\n var $lvl = it.level;\n var $dataLvl = it.dataLevel;\n var $schema = it.schema[$keyword];\n var $schemaPath = it.schemaPath + it.util.getProperty($keyword);\n var $errSchemaPath = it.errSchemaPath + '/' + $keyword;\n var $breakOnError = !it.opts.allErrors;\n var $errorKeyword;\n var $data = 'data' + ($dataLvl || '');\n var $isData = it.opts.$data && $schema && $schema.$data,\n $schemaValue;\n if ($isData) {\n out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';\n $schemaValue = 'schema' + $lvl;\n } else {\n $schemaValue = $schema;\n }\n if (!($isData || typeof $schema == 'number')) {\n throw new Error($keyword + ' must be number');\n }\n var $op = $keyword == 'maxProperties' ? '>' : '<';\n out += 'if ( ';\n if ($isData) {\n out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \\'number\\') || ';\n }\n out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { ';\n var $errorKeyword = $keyword;\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = ''; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ($errorKeyword || '_limitProperties') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'should NOT have ';\n if ($keyword == 'maxProperties') {\n out += 'more';\n } else {\n out += 'fewer';\n }\n out += ' than ';\n if ($isData) {\n out += '\\' + ' + ($schemaValue) + ' + \\'';\n } else {\n out += '' + ($schema);\n }\n out += ' properties\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: ';\n if ($isData) {\n out += 'validate.schema' + ($schemaPath);\n } else {\n out += '' + ($schema);\n }\n out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n var __err = out;\n out = $$outStack.pop();\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError([' + (__err) + ']); ';\n } else {\n out += ' validate.errors = [' + (__err) + ']; return false; ';\n }\n } else {\n out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n }\n out += '} ';\n if ($breakOnError) {\n out += ' else { ';\n }\n return out;\n}\n","'use strict';\nmodule.exports = function generate_allOf(it, $keyword, $ruleType) {\n var out = ' ';\n var $schema = it.schema[$keyword];\n var $schemaPath = it.schemaPath + it.util.getProperty($keyword);\n var $errSchemaPath = it.errSchemaPath + '/' + $keyword;\n var $breakOnError = !it.opts.allErrors;\n var $it = it.util.copy(it);\n var $closingBraces = '';\n $it.level++;\n var $nextValid = 'valid' + $it.level;\n var $currentBaseId = $it.baseId,\n $allSchemasEmpty = true;\n var arr1 = $schema;\n if (arr1) {\n var $sch, $i = -1,\n l1 = arr1.length - 1;\n while ($i < l1) {\n $sch = arr1[$i += 1];\n if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {\n $allSchemasEmpty = false;\n $it.schema = $sch;\n $it.schemaPath = $schemaPath + '[' + $i + ']';\n $it.errSchemaPath = $errSchemaPath + '/' + $i;\n out += ' ' + (it.validate($it)) + ' ';\n $it.baseId = $currentBaseId;\n if ($breakOnError) {\n out += ' if (' + ($nextValid) + ') { ';\n $closingBraces += '}';\n }\n }\n }\n }\n if ($breakOnError) {\n if ($allSchemasEmpty) {\n out += ' if (true) { ';\n } else {\n out += ' ' + ($closingBraces.slice(0, -1)) + ' ';\n }\n }\n return out;\n}\n","'use strict';\nmodule.exports = function generate_anyOf(it, $keyword, $ruleType) {\n var out = ' ';\n var $lvl = it.level;\n var $dataLvl = it.dataLevel;\n var $schema = it.schema[$keyword];\n var $schemaPath = it.schemaPath + it.util.getProperty($keyword);\n var $errSchemaPath = it.errSchemaPath + '/' + $keyword;\n var $breakOnError = !it.opts.allErrors;\n var $data = 'data' + ($dataLvl || '');\n var $valid = 'valid' + $lvl;\n var $errs = 'errs__' + $lvl;\n var $it = it.util.copy(it);\n var $closingBraces = '';\n $it.level++;\n var $nextValid = 'valid' + $it.level;\n var $noEmptySchema = $schema.every(function($sch) {\n return (it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all));\n });\n if ($noEmptySchema) {\n var $currentBaseId = $it.baseId;\n out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; ';\n var $wasComposite = it.compositeRule;\n it.compositeRule = $it.compositeRule = true;\n var arr1 = $schema;\n if (arr1) {\n var $sch, $i = -1,\n l1 = arr1.length - 1;\n while ($i < l1) {\n $sch = arr1[$i += 1];\n $it.schema = $sch;\n $it.schemaPath = $schemaPath + '[' + $i + ']';\n $it.errSchemaPath = $errSchemaPath + '/' + $i;\n out += ' ' + (it.validate($it)) + ' ';\n $it.baseId = $currentBaseId;\n out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { ';\n $closingBraces += '}';\n }\n }\n it.compositeRule = $it.compositeRule = $wasComposite;\n out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ('anyOf') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'should match some schema in anyOf\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError(vErrors); ';\n } else {\n out += ' validate.errors = vErrors; return false; ';\n }\n }\n out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';\n if (it.opts.allErrors) {\n out += ' } ';\n }\n } else {\n if ($breakOnError) {\n out += ' if (true) { ';\n }\n }\n return out;\n}\n","'use strict';\nmodule.exports = function generate_comment(it, $keyword, $ruleType) {\n var out = ' ';\n var $schema = it.schema[$keyword];\n var $errSchemaPath = it.errSchemaPath + '/' + $keyword;\n var $breakOnError = !it.opts.allErrors;\n var $comment = it.util.toQuotedString($schema);\n if (it.opts.$comment === true) {\n out += ' console.log(' + ($comment) + ');';\n } else if (typeof it.opts.$comment == 'function') {\n out += ' self._opts.$comment(' + ($comment) + ', ' + (it.util.toQuotedString($errSchemaPath)) + ', validate.root.schema);';\n }\n return out;\n}\n","'use strict';\nmodule.exports = function generate_const(it, $keyword, $ruleType) {\n var out = ' ';\n var $lvl = it.level;\n var $dataLvl = it.dataLevel;\n var $schema = it.schema[$keyword];\n var $schemaPath = it.schemaPath + it.util.getProperty($keyword);\n var $errSchemaPath = it.errSchemaPath + '/' + $keyword;\n var $breakOnError = !it.opts.allErrors;\n var $data = 'data' + ($dataLvl || '');\n var $valid = 'valid' + $lvl;\n var $isData = it.opts.$data && $schema && $schema.$data,\n $schemaValue;\n if ($isData) {\n out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';\n $schemaValue = 'schema' + $lvl;\n } else {\n $schemaValue = $schema;\n }\n if (!$isData) {\n out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';';\n }\n out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { ';\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = ''; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ('const') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'should be equal to constant\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n var __err = out;\n out = $$outStack.pop();\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError([' + (__err) + ']); ';\n } else {\n out += ' validate.errors = [' + (__err) + ']; return false; ';\n }\n } else {\n out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n }\n out += ' }';\n if ($breakOnError) {\n out += ' else { ';\n }\n return out;\n}\n","'use strict';\nmodule.exports = function generate_contains(it, $keyword, $ruleType) {\n var out = ' ';\n var $lvl = it.level;\n var $dataLvl = it.dataLevel;\n var $schema = it.schema[$keyword];\n var $schemaPath = it.schemaPath + it.util.getProperty($keyword);\n var $errSchemaPath = it.errSchemaPath + '/' + $keyword;\n var $breakOnError = !it.opts.allErrors;\n var $data = 'data' + ($dataLvl || '');\n var $valid = 'valid' + $lvl;\n var $errs = 'errs__' + $lvl;\n var $it = it.util.copy(it);\n var $closingBraces = '';\n $it.level++;\n var $nextValid = 'valid' + $it.level;\n var $idx = 'i' + $lvl,\n $dataNxt = $it.dataLevel = it.dataLevel + 1,\n $nextData = 'data' + $dataNxt,\n $currentBaseId = it.baseId,\n $nonEmptySchema = (it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all));\n out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';\n if ($nonEmptySchema) {\n var $wasComposite = it.compositeRule;\n it.compositeRule = $it.compositeRule = true;\n $it.schema = $schema;\n $it.schemaPath = $schemaPath;\n $it.errSchemaPath = $errSchemaPath;\n out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';\n $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);\n var $passData = $data + '[' + $idx + ']';\n $it.dataPathArr[$dataNxt] = $idx;\n var $code = it.validate($it);\n $it.baseId = $currentBaseId;\n if (it.util.varOccurences($code, $nextData) < 2) {\n out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';\n } else {\n out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';\n }\n out += ' if (' + ($nextValid) + ') break; } ';\n it.compositeRule = $it.compositeRule = $wasComposite;\n out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {';\n } else {\n out += ' if (' + ($data) + '.length == 0) {';\n }\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = ''; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ('contains') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'should contain a valid item\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n var __err = out;\n out = $$outStack.pop();\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError([' + (__err) + ']); ';\n } else {\n out += ' validate.errors = [' + (__err) + ']; return false; ';\n }\n } else {\n out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n }\n out += ' } else { ';\n if ($nonEmptySchema) {\n out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';\n }\n if (it.opts.allErrors) {\n out += ' } ';\n }\n return out;\n}\n","'use strict';\nmodule.exports = function generate_custom(it, $keyword, $ruleType) {\n var out = ' ';\n var $lvl = it.level;\n var $dataLvl = it.dataLevel;\n var $schema = it.schema[$keyword];\n var $schemaPath = it.schemaPath + it.util.getProperty($keyword);\n var $errSchemaPath = it.errSchemaPath + '/' + $keyword;\n var $breakOnError = !it.opts.allErrors;\n var $errorKeyword;\n var $data = 'data' + ($dataLvl || '');\n var $valid = 'valid' + $lvl;\n var $errs = 'errs__' + $lvl;\n var $isData = it.opts.$data && $schema && $schema.$data,\n $schemaValue;\n if ($isData) {\n out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';\n $schemaValue = 'schema' + $lvl;\n } else {\n $schemaValue = $schema;\n }\n var $rule = this,\n $definition = 'definition' + $lvl,\n $rDef = $rule.definition,\n $closingBraces = '';\n var $compile, $inline, $macro, $ruleValidate, $validateCode;\n if ($isData && $rDef.$data) {\n $validateCode = 'keywordValidate' + $lvl;\n var $validateSchema = $rDef.validateSchema;\n out += ' var ' + ($definition) + ' = RULES.custom[\\'' + ($keyword) + '\\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;';\n } else {\n $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it);\n if (!$ruleValidate) return;\n $schemaValue = 'validate.schema' + $schemaPath;\n $validateCode = $ruleValidate.code;\n $compile = $rDef.compile;\n $inline = $rDef.inline;\n $macro = $rDef.macro;\n }\n var $ruleErrs = $validateCode + '.errors',\n $i = 'i' + $lvl,\n $ruleErr = 'ruleErr' + $lvl,\n $asyncKeyword = $rDef.async;\n if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema');\n if (!($inline || $macro)) {\n out += '' + ($ruleErrs) + ' = null;';\n }\n out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';\n if ($isData && $rDef.$data) {\n $closingBraces += '}';\n out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { ';\n if ($validateSchema) {\n $closingBraces += '}';\n out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { ';\n }\n }\n if ($inline) {\n if ($rDef.statements) {\n out += ' ' + ($ruleValidate.validate) + ' ';\n } else {\n out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; ';\n }\n } else if ($macro) {\n var $it = it.util.copy(it);\n var $closingBraces = '';\n $it.level++;\n var $nextValid = 'valid' + $it.level;\n $it.schema = $ruleValidate.validate;\n $it.schemaPath = '';\n var $wasComposite = it.compositeRule;\n it.compositeRule = $it.compositeRule = true;\n var $code = it.validate($it).replace(/validate\\.schema/g, $validateCode);\n it.compositeRule = $it.compositeRule = $wasComposite;\n out += ' ' + ($code);\n } else {\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = '';\n out += ' ' + ($validateCode) + '.call( ';\n if (it.opts.passContext) {\n out += 'this';\n } else {\n out += 'self';\n }\n if ($compile || $rDef.schema === false) {\n out += ' , ' + ($data) + ' ';\n } else {\n out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' ';\n }\n out += ' , (dataPath || \\'\\')';\n if (it.errorPath != '\"\"') {\n out += ' + ' + (it.errorPath);\n }\n var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',\n $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';\n out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) ';\n var def_callRuleValidate = out;\n out = $$outStack.pop();\n if ($rDef.errors === false) {\n out += ' ' + ($valid) + ' = ';\n if ($asyncKeyword) {\n out += 'await ';\n }\n out += '' + (def_callRuleValidate) + '; ';\n } else {\n if ($asyncKeyword) {\n $ruleErrs = 'customErrors' + $lvl;\n out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = await ' + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } ';\n } else {\n out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; ';\n }\n }\n }\n if ($rDef.modifying) {\n out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];';\n }\n out += '' + ($closingBraces);\n if ($rDef.valid) {\n if ($breakOnError) {\n out += ' if (true) { ';\n }\n } else {\n out += ' if ( ';\n if ($rDef.valid === undefined) {\n out += ' !';\n if ($macro) {\n out += '' + ($nextValid);\n } else {\n out += '' + ($valid);\n }\n } else {\n out += ' ' + (!$rDef.valid) + ' ';\n }\n out += ') { ';\n $errorKeyword = $rule.keyword;\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = '';\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = ''; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ($errorKeyword || 'custom') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \\'' + ($rule.keyword) + '\\' } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'should pass \"' + ($rule.keyword) + '\" keyword validation\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n var __err = out;\n out = $$outStack.pop();\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError([' + (__err) + ']); ';\n } else {\n out += ' validate.errors = [' + (__err) + ']; return false; ';\n }\n } else {\n out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n }\n var def_customError = out;\n out = $$outStack.pop();\n if ($inline) {\n if ($rDef.errors) {\n if ($rDef.errors != 'full') {\n out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + ' 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {\n out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';\n if ($ownProperties) {\n out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \\'' + (it.util.escapeQuotes($property)) + '\\') ';\n }\n out += ') { ';\n $it.schema = $sch;\n $it.schemaPath = $schemaPath + it.util.getProperty($property);\n $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property);\n out += ' ' + (it.validate($it)) + ' ';\n $it.baseId = $currentBaseId;\n out += ' } ';\n if ($breakOnError) {\n out += ' if (' + ($nextValid) + ') { ';\n $closingBraces += '}';\n }\n }\n }\n if ($breakOnError) {\n out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';\n }\n return out;\n}\n","'use strict';\nmodule.exports = function generate_enum(it, $keyword, $ruleType) {\n var out = ' ';\n var $lvl = it.level;\n var $dataLvl = it.dataLevel;\n var $schema = it.schema[$keyword];\n var $schemaPath = it.schemaPath + it.util.getProperty($keyword);\n var $errSchemaPath = it.errSchemaPath + '/' + $keyword;\n var $breakOnError = !it.opts.allErrors;\n var $data = 'data' + ($dataLvl || '');\n var $valid = 'valid' + $lvl;\n var $isData = it.opts.$data && $schema && $schema.$data,\n $schemaValue;\n if ($isData) {\n out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';\n $schemaValue = 'schema' + $lvl;\n } else {\n $schemaValue = $schema;\n }\n var $i = 'i' + $lvl,\n $vSchema = 'schema' + $lvl;\n if (!$isData) {\n out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';';\n }\n out += 'var ' + ($valid) + ';';\n if ($isData) {\n out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';\n }\n out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }';\n if ($isData) {\n out += ' } ';\n }\n out += ' if (!' + ($valid) + ') { ';\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = ''; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ('enum') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'should be equal to one of the allowed values\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n var __err = out;\n out = $$outStack.pop();\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError([' + (__err) + ']); ';\n } else {\n out += ' validate.errors = [' + (__err) + ']; return false; ';\n }\n } else {\n out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n }\n out += ' }';\n if ($breakOnError) {\n out += ' else { ';\n }\n return out;\n}\n","'use strict';\nmodule.exports = function generate_format(it, $keyword, $ruleType) {\n var out = ' ';\n var $lvl = it.level;\n var $dataLvl = it.dataLevel;\n var $schema = it.schema[$keyword];\n var $schemaPath = it.schemaPath + it.util.getProperty($keyword);\n var $errSchemaPath = it.errSchemaPath + '/' + $keyword;\n var $breakOnError = !it.opts.allErrors;\n var $data = 'data' + ($dataLvl || '');\n if (it.opts.format === false) {\n if ($breakOnError) {\n out += ' if (true) { ';\n }\n return out;\n }\n var $isData = it.opts.$data && $schema && $schema.$data,\n $schemaValue;\n if ($isData) {\n out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';\n $schemaValue = 'schema' + $lvl;\n } else {\n $schemaValue = $schema;\n }\n var $unknownFormats = it.opts.unknownFormats,\n $allowUnknown = Array.isArray($unknownFormats);\n if ($isData) {\n var $format = 'format' + $lvl,\n $isObject = 'isObject' + $lvl,\n $formatType = 'formatType' + $lvl;\n out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \\'object\\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \\'string\\'; if (' + ($isObject) + ') { ';\n if (it.async) {\n out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; ';\n }\n out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( ';\n if ($isData) {\n out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \\'string\\') || ';\n }\n out += ' (';\n if ($unknownFormats != 'ignore') {\n out += ' (' + ($schemaValue) + ' && !' + ($format) + ' ';\n if ($allowUnknown) {\n out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 ';\n }\n out += ') || ';\n }\n out += ' (' + ($format) + ' && ' + ($formatType) + ' == \\'' + ($ruleType) + '\\' && !(typeof ' + ($format) + ' == \\'function\\' ? ';\n if (it.async) {\n out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) ';\n } else {\n out += ' ' + ($format) + '(' + ($data) + ') ';\n }\n out += ' : ' + ($format) + '.test(' + ($data) + '))))) {';\n } else {\n var $format = it.formats[$schema];\n if (!$format) {\n if ($unknownFormats == 'ignore') {\n it.logger.warn('unknown format \"' + $schema + '\" ignored in schema at path \"' + it.errSchemaPath + '\"');\n if ($breakOnError) {\n out += ' if (true) { ';\n }\n return out;\n } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) {\n if ($breakOnError) {\n out += ' if (true) { ';\n }\n return out;\n } else {\n throw new Error('unknown format \"' + $schema + '\" is used in schema at path \"' + it.errSchemaPath + '\"');\n }\n }\n var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate;\n var $formatType = $isObject && $format.type || 'string';\n if ($isObject) {\n var $async = $format.async === true;\n $format = $format.validate;\n }\n if ($formatType != $ruleType) {\n if ($breakOnError) {\n out += ' if (true) { ';\n }\n return out;\n }\n if ($async) {\n if (!it.async) throw new Error('async format in sync schema');\n var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';\n out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { ';\n } else {\n out += ' if (! ';\n var $formatRef = 'formats' + it.util.getProperty($schema);\n if ($isObject) $formatRef += '.validate';\n if (typeof $format == 'function') {\n out += ' ' + ($formatRef) + '(' + ($data) + ') ';\n } else {\n out += ' ' + ($formatRef) + '.test(' + ($data) + ') ';\n }\n out += ') { ';\n }\n }\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = ''; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ('format') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: ';\n if ($isData) {\n out += '' + ($schemaValue);\n } else {\n out += '' + (it.util.toQuotedString($schema));\n }\n out += ' } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'should match format \"';\n if ($isData) {\n out += '\\' + ' + ($schemaValue) + ' + \\'';\n } else {\n out += '' + (it.util.escapeQuotes($schema));\n }\n out += '\"\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: ';\n if ($isData) {\n out += 'validate.schema' + ($schemaPath);\n } else {\n out += '' + (it.util.toQuotedString($schema));\n }\n out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n var __err = out;\n out = $$outStack.pop();\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError([' + (__err) + ']); ';\n } else {\n out += ' validate.errors = [' + (__err) + ']; return false; ';\n }\n } else {\n out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n }\n out += ' } ';\n if ($breakOnError) {\n out += ' else { ';\n }\n return out;\n}\n","'use strict';\nmodule.exports = function generate_if(it, $keyword, $ruleType) {\n var out = ' ';\n var $lvl = it.level;\n var $dataLvl = it.dataLevel;\n var $schema = it.schema[$keyword];\n var $schemaPath = it.schemaPath + it.util.getProperty($keyword);\n var $errSchemaPath = it.errSchemaPath + '/' + $keyword;\n var $breakOnError = !it.opts.allErrors;\n var $data = 'data' + ($dataLvl || '');\n var $valid = 'valid' + $lvl;\n var $errs = 'errs__' + $lvl;\n var $it = it.util.copy(it);\n $it.level++;\n var $nextValid = 'valid' + $it.level;\n var $thenSch = it.schema['then'],\n $elseSch = it.schema['else'],\n $thenPresent = $thenSch !== undefined && (it.opts.strictKeywords ? (typeof $thenSch == 'object' && Object.keys($thenSch).length > 0) || $thenSch === false : it.util.schemaHasRules($thenSch, it.RULES.all)),\n $elsePresent = $elseSch !== undefined && (it.opts.strictKeywords ? (typeof $elseSch == 'object' && Object.keys($elseSch).length > 0) || $elseSch === false : it.util.schemaHasRules($elseSch, it.RULES.all)),\n $currentBaseId = $it.baseId;\n if ($thenPresent || $elsePresent) {\n var $ifClause;\n $it.createErrors = false;\n $it.schema = $schema;\n $it.schemaPath = $schemaPath;\n $it.errSchemaPath = $errSchemaPath;\n out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = true; ';\n var $wasComposite = it.compositeRule;\n it.compositeRule = $it.compositeRule = true;\n out += ' ' + (it.validate($it)) + ' ';\n $it.baseId = $currentBaseId;\n $it.createErrors = true;\n out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';\n it.compositeRule = $it.compositeRule = $wasComposite;\n if ($thenPresent) {\n out += ' if (' + ($nextValid) + ') { ';\n $it.schema = it.schema['then'];\n $it.schemaPath = it.schemaPath + '.then';\n $it.errSchemaPath = it.errSchemaPath + '/then';\n out += ' ' + (it.validate($it)) + ' ';\n $it.baseId = $currentBaseId;\n out += ' ' + ($valid) + ' = ' + ($nextValid) + '; ';\n if ($thenPresent && $elsePresent) {\n $ifClause = 'ifClause' + $lvl;\n out += ' var ' + ($ifClause) + ' = \\'then\\'; ';\n } else {\n $ifClause = '\\'then\\'';\n }\n out += ' } ';\n if ($elsePresent) {\n out += ' else { ';\n }\n } else {\n out += ' if (!' + ($nextValid) + ') { ';\n }\n if ($elsePresent) {\n $it.schema = it.schema['else'];\n $it.schemaPath = it.schemaPath + '.else';\n $it.errSchemaPath = it.errSchemaPath + '/else';\n out += ' ' + (it.validate($it)) + ' ';\n $it.baseId = $currentBaseId;\n out += ' ' + ($valid) + ' = ' + ($nextValid) + '; ';\n if ($thenPresent && $elsePresent) {\n $ifClause = 'ifClause' + $lvl;\n out += ' var ' + ($ifClause) + ' = \\'else\\'; ';\n } else {\n $ifClause = '\\'else\\'';\n }\n out += ' } ';\n }\n out += ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ('if') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'should match \"\\' + ' + ($ifClause) + ' + \\'\" schema\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError(vErrors); ';\n } else {\n out += ' validate.errors = vErrors; return false; ';\n }\n }\n out += ' } ';\n if ($breakOnError) {\n out += ' else { ';\n }\n } else {\n if ($breakOnError) {\n out += ' if (true) { ';\n }\n }\n return out;\n}\n","'use strict';\n\n//all requires must be explicit because browserify won't work with dynamic requires\nmodule.exports = {\n '$ref': require('./ref'),\n allOf: require('./allOf'),\n anyOf: require('./anyOf'),\n '$comment': require('./comment'),\n const: require('./const'),\n contains: require('./contains'),\n dependencies: require('./dependencies'),\n 'enum': require('./enum'),\n format: require('./format'),\n 'if': require('./if'),\n items: require('./items'),\n maximum: require('./_limit'),\n minimum: require('./_limit'),\n maxItems: require('./_limitItems'),\n minItems: require('./_limitItems'),\n maxLength: require('./_limitLength'),\n minLength: require('./_limitLength'),\n maxProperties: require('./_limitProperties'),\n minProperties: require('./_limitProperties'),\n multipleOf: require('./multipleOf'),\n not: require('./not'),\n oneOf: require('./oneOf'),\n pattern: require('./pattern'),\n properties: require('./properties'),\n propertyNames: require('./propertyNames'),\n required: require('./required'),\n uniqueItems: require('./uniqueItems'),\n validate: require('./validate')\n};\n","'use strict';\nmodule.exports = function generate_items(it, $keyword, $ruleType) {\n var out = ' ';\n var $lvl = it.level;\n var $dataLvl = it.dataLevel;\n var $schema = it.schema[$keyword];\n var $schemaPath = it.schemaPath + it.util.getProperty($keyword);\n var $errSchemaPath = it.errSchemaPath + '/' + $keyword;\n var $breakOnError = !it.opts.allErrors;\n var $data = 'data' + ($dataLvl || '');\n var $valid = 'valid' + $lvl;\n var $errs = 'errs__' + $lvl;\n var $it = it.util.copy(it);\n var $closingBraces = '';\n $it.level++;\n var $nextValid = 'valid' + $it.level;\n var $idx = 'i' + $lvl,\n $dataNxt = $it.dataLevel = it.dataLevel + 1,\n $nextData = 'data' + $dataNxt,\n $currentBaseId = it.baseId;\n out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';\n if (Array.isArray($schema)) {\n var $additionalItems = it.schema.additionalItems;\n if ($additionalItems === false) {\n out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; ';\n var $currErrSchemaPath = $errSchemaPath;\n $errSchemaPath = it.errSchemaPath + '/additionalItems';\n out += ' if (!' + ($valid) + ') { ';\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = ''; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ('additionalItems') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'should NOT have more than ' + ($schema.length) + ' items\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n var __err = out;\n out = $$outStack.pop();\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError([' + (__err) + ']); ';\n } else {\n out += ' validate.errors = [' + (__err) + ']; return false; ';\n }\n } else {\n out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n }\n out += ' } ';\n $errSchemaPath = $currErrSchemaPath;\n if ($breakOnError) {\n $closingBraces += '}';\n out += ' else { ';\n }\n }\n var arr1 = $schema;\n if (arr1) {\n var $sch, $i = -1,\n l1 = arr1.length - 1;\n while ($i < l1) {\n $sch = arr1[$i += 1];\n if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {\n out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { ';\n var $passData = $data + '[' + $i + ']';\n $it.schema = $sch;\n $it.schemaPath = $schemaPath + '[' + $i + ']';\n $it.errSchemaPath = $errSchemaPath + '/' + $i;\n $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);\n $it.dataPathArr[$dataNxt] = $i;\n var $code = it.validate($it);\n $it.baseId = $currentBaseId;\n if (it.util.varOccurences($code, $nextData) < 2) {\n out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';\n } else {\n out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';\n }\n out += ' } ';\n if ($breakOnError) {\n out += ' if (' + ($nextValid) + ') { ';\n $closingBraces += '}';\n }\n }\n }\n }\n if (typeof $additionalItems == 'object' && (it.opts.strictKeywords ? (typeof $additionalItems == 'object' && Object.keys($additionalItems).length > 0) || $additionalItems === false : it.util.schemaHasRules($additionalItems, it.RULES.all))) {\n $it.schema = $additionalItems;\n $it.schemaPath = it.schemaPath + '.additionalItems';\n $it.errSchemaPath = it.errSchemaPath + '/additionalItems';\n out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';\n $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);\n var $passData = $data + '[' + $idx + ']';\n $it.dataPathArr[$dataNxt] = $idx;\n var $code = it.validate($it);\n $it.baseId = $currentBaseId;\n if (it.util.varOccurences($code, $nextData) < 2) {\n out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';\n } else {\n out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';\n }\n if ($breakOnError) {\n out += ' if (!' + ($nextValid) + ') break; ';\n }\n out += ' } } ';\n if ($breakOnError) {\n out += ' if (' + ($nextValid) + ') { ';\n $closingBraces += '}';\n }\n }\n } else if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) {\n $it.schema = $schema;\n $it.schemaPath = $schemaPath;\n $it.errSchemaPath = $errSchemaPath;\n out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';\n $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);\n var $passData = $data + '[' + $idx + ']';\n $it.dataPathArr[$dataNxt] = $idx;\n var $code = it.validate($it);\n $it.baseId = $currentBaseId;\n if (it.util.varOccurences($code, $nextData) < 2) {\n out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';\n } else {\n out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';\n }\n if ($breakOnError) {\n out += ' if (!' + ($nextValid) + ') break; ';\n }\n out += ' }';\n }\n if ($breakOnError) {\n out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';\n }\n return out;\n}\n","'use strict';\nmodule.exports = function generate_multipleOf(it, $keyword, $ruleType) {\n var out = ' ';\n var $lvl = it.level;\n var $dataLvl = it.dataLevel;\n var $schema = it.schema[$keyword];\n var $schemaPath = it.schemaPath + it.util.getProperty($keyword);\n var $errSchemaPath = it.errSchemaPath + '/' + $keyword;\n var $breakOnError = !it.opts.allErrors;\n var $data = 'data' + ($dataLvl || '');\n var $isData = it.opts.$data && $schema && $schema.$data,\n $schemaValue;\n if ($isData) {\n out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';\n $schemaValue = 'schema' + $lvl;\n } else {\n $schemaValue = $schema;\n }\n if (!($isData || typeof $schema == 'number')) {\n throw new Error($keyword + ' must be number');\n }\n out += 'var division' + ($lvl) + ';if (';\n if ($isData) {\n out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \\'number\\' || ';\n }\n out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', ';\n if (it.opts.multipleOfPrecision) {\n out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' ';\n } else {\n out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') ';\n }\n out += ' ) ';\n if ($isData) {\n out += ' ) ';\n }\n out += ' ) { ';\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = ''; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ('multipleOf') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'should be multiple of ';\n if ($isData) {\n out += '\\' + ' + ($schemaValue);\n } else {\n out += '' + ($schemaValue) + '\\'';\n }\n }\n if (it.opts.verbose) {\n out += ' , schema: ';\n if ($isData) {\n out += 'validate.schema' + ($schemaPath);\n } else {\n out += '' + ($schema);\n }\n out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n var __err = out;\n out = $$outStack.pop();\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError([' + (__err) + ']); ';\n } else {\n out += ' validate.errors = [' + (__err) + ']; return false; ';\n }\n } else {\n out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n }\n out += '} ';\n if ($breakOnError) {\n out += ' else { ';\n }\n return out;\n}\n","'use strict';\nmodule.exports = function generate_not(it, $keyword, $ruleType) {\n var out = ' ';\n var $lvl = it.level;\n var $dataLvl = it.dataLevel;\n var $schema = it.schema[$keyword];\n var $schemaPath = it.schemaPath + it.util.getProperty($keyword);\n var $errSchemaPath = it.errSchemaPath + '/' + $keyword;\n var $breakOnError = !it.opts.allErrors;\n var $data = 'data' + ($dataLvl || '');\n var $errs = 'errs__' + $lvl;\n var $it = it.util.copy(it);\n $it.level++;\n var $nextValid = 'valid' + $it.level;\n if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) {\n $it.schema = $schema;\n $it.schemaPath = $schemaPath;\n $it.errSchemaPath = $errSchemaPath;\n out += ' var ' + ($errs) + ' = errors; ';\n var $wasComposite = it.compositeRule;\n it.compositeRule = $it.compositeRule = true;\n $it.createErrors = false;\n var $allErrorsOption;\n if ($it.opts.allErrors) {\n $allErrorsOption = $it.opts.allErrors;\n $it.opts.allErrors = false;\n }\n out += ' ' + (it.validate($it)) + ' ';\n $it.createErrors = true;\n if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption;\n it.compositeRule = $it.compositeRule = $wasComposite;\n out += ' if (' + ($nextValid) + ') { ';\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = ''; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ('not') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'should NOT be valid\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n var __err = out;\n out = $$outStack.pop();\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError([' + (__err) + ']); ';\n } else {\n out += ' validate.errors = [' + (__err) + ']; return false; ';\n }\n } else {\n out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n }\n out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';\n if (it.opts.allErrors) {\n out += ' } ';\n }\n } else {\n out += ' var err = '; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ('not') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'should NOT be valid\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n if ($breakOnError) {\n out += ' if (false) { ';\n }\n }\n return out;\n}\n","'use strict';\nmodule.exports = function generate_oneOf(it, $keyword, $ruleType) {\n var out = ' ';\n var $lvl = it.level;\n var $dataLvl = it.dataLevel;\n var $schema = it.schema[$keyword];\n var $schemaPath = it.schemaPath + it.util.getProperty($keyword);\n var $errSchemaPath = it.errSchemaPath + '/' + $keyword;\n var $breakOnError = !it.opts.allErrors;\n var $data = 'data' + ($dataLvl || '');\n var $valid = 'valid' + $lvl;\n var $errs = 'errs__' + $lvl;\n var $it = it.util.copy(it);\n var $closingBraces = '';\n $it.level++;\n var $nextValid = 'valid' + $it.level;\n var $currentBaseId = $it.baseId,\n $prevValid = 'prevValid' + $lvl,\n $passingSchemas = 'passingSchemas' + $lvl;\n out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; ';\n var $wasComposite = it.compositeRule;\n it.compositeRule = $it.compositeRule = true;\n var arr1 = $schema;\n if (arr1) {\n var $sch, $i = -1,\n l1 = arr1.length - 1;\n while ($i < l1) {\n $sch = arr1[$i += 1];\n if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {\n $it.schema = $sch;\n $it.schemaPath = $schemaPath + '[' + $i + ']';\n $it.errSchemaPath = $errSchemaPath + '/' + $i;\n out += ' ' + (it.validate($it)) + ' ';\n $it.baseId = $currentBaseId;\n } else {\n out += ' var ' + ($nextValid) + ' = true; ';\n }\n if ($i) {\n out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { ';\n $closingBraces += '}';\n }\n out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }';\n }\n }\n it.compositeRule = $it.compositeRule = $wasComposite;\n out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ('oneOf') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'should match exactly one schema in oneOf\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError(vErrors); ';\n } else {\n out += ' validate.errors = vErrors; return false; ';\n }\n }\n out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }';\n if (it.opts.allErrors) {\n out += ' } ';\n }\n return out;\n}\n","'use strict';\nmodule.exports = function generate_pattern(it, $keyword, $ruleType) {\n var out = ' ';\n var $lvl = it.level;\n var $dataLvl = it.dataLevel;\n var $schema = it.schema[$keyword];\n var $schemaPath = it.schemaPath + it.util.getProperty($keyword);\n var $errSchemaPath = it.errSchemaPath + '/' + $keyword;\n var $breakOnError = !it.opts.allErrors;\n var $data = 'data' + ($dataLvl || '');\n var $isData = it.opts.$data && $schema && $schema.$data,\n $schemaValue;\n if ($isData) {\n out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';\n $schemaValue = 'schema' + $lvl;\n } else {\n $schemaValue = $schema;\n }\n var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema);\n out += 'if ( ';\n if ($isData) {\n out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \\'string\\') || ';\n }\n out += ' !' + ($regexp) + '.test(' + ($data) + ') ) { ';\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = ''; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ('pattern') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: ';\n if ($isData) {\n out += '' + ($schemaValue);\n } else {\n out += '' + (it.util.toQuotedString($schema));\n }\n out += ' } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'should match pattern \"';\n if ($isData) {\n out += '\\' + ' + ($schemaValue) + ' + \\'';\n } else {\n out += '' + (it.util.escapeQuotes($schema));\n }\n out += '\"\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: ';\n if ($isData) {\n out += 'validate.schema' + ($schemaPath);\n } else {\n out += '' + (it.util.toQuotedString($schema));\n }\n out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n var __err = out;\n out = $$outStack.pop();\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError([' + (__err) + ']); ';\n } else {\n out += ' validate.errors = [' + (__err) + ']; return false; ';\n }\n } else {\n out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n }\n out += '} ';\n if ($breakOnError) {\n out += ' else { ';\n }\n return out;\n}\n","'use strict';\nmodule.exports = function generate_properties(it, $keyword, $ruleType) {\n var out = ' ';\n var $lvl = it.level;\n var $dataLvl = it.dataLevel;\n var $schema = it.schema[$keyword];\n var $schemaPath = it.schemaPath + it.util.getProperty($keyword);\n var $errSchemaPath = it.errSchemaPath + '/' + $keyword;\n var $breakOnError = !it.opts.allErrors;\n var $data = 'data' + ($dataLvl || '');\n var $errs = 'errs__' + $lvl;\n var $it = it.util.copy(it);\n var $closingBraces = '';\n $it.level++;\n var $nextValid = 'valid' + $it.level;\n var $key = 'key' + $lvl,\n $idx = 'idx' + $lvl,\n $dataNxt = $it.dataLevel = it.dataLevel + 1,\n $nextData = 'data' + $dataNxt,\n $dataProperties = 'dataProperties' + $lvl;\n var $schemaKeys = Object.keys($schema || {}).filter(notProto),\n $pProperties = it.schema.patternProperties || {},\n $pPropertyKeys = Object.keys($pProperties).filter(notProto),\n $aProperties = it.schema.additionalProperties,\n $someProperties = $schemaKeys.length || $pPropertyKeys.length,\n $noAdditional = $aProperties === false,\n $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length,\n $removeAdditional = it.opts.removeAdditional,\n $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional,\n $ownProperties = it.opts.ownProperties,\n $currentBaseId = it.baseId;\n var $required = it.schema.required;\n if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) {\n var $requiredHash = it.util.toHash($required);\n }\n\n function notProto(p) {\n return p !== '__proto__';\n }\n out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;';\n if ($ownProperties) {\n out += ' var ' + ($dataProperties) + ' = undefined;';\n }\n if ($checkAdditional) {\n if ($ownProperties) {\n out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';\n } else {\n out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';\n }\n if ($someProperties) {\n out += ' var isAdditional' + ($lvl) + ' = !(false ';\n if ($schemaKeys.length) {\n if ($schemaKeys.length > 8) {\n out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') ';\n } else {\n var arr1 = $schemaKeys;\n if (arr1) {\n var $propertyKey, i1 = -1,\n l1 = arr1.length - 1;\n while (i1 < l1) {\n $propertyKey = arr1[i1 += 1];\n out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' ';\n }\n }\n }\n }\n if ($pPropertyKeys.length) {\n var arr2 = $pPropertyKeys;\n if (arr2) {\n var $pProperty, $i = -1,\n l2 = arr2.length - 1;\n while ($i < l2) {\n $pProperty = arr2[$i += 1];\n out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') ';\n }\n }\n }\n out += ' ); if (isAdditional' + ($lvl) + ') { ';\n }\n if ($removeAdditional == 'all') {\n out += ' delete ' + ($data) + '[' + ($key) + ']; ';\n } else {\n var $currentErrorPath = it.errorPath;\n var $additionalProperty = '\\' + ' + $key + ' + \\'';\n if (it.opts._errorDataPathProperty) {\n it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);\n }\n if ($noAdditional) {\n if ($removeAdditional) {\n out += ' delete ' + ($data) + '[' + ($key) + ']; ';\n } else {\n out += ' ' + ($nextValid) + ' = false; ';\n var $currErrSchemaPath = $errSchemaPath;\n $errSchemaPath = it.errSchemaPath + '/additionalProperties';\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = ''; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ('additionalProperties') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \\'' + ($additionalProperty) + '\\' } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'';\n if (it.opts._errorDataPathProperty) {\n out += 'is an invalid additional property';\n } else {\n out += 'should NOT have additional properties';\n }\n out += '\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n var __err = out;\n out = $$outStack.pop();\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError([' + (__err) + ']); ';\n } else {\n out += ' validate.errors = [' + (__err) + ']; return false; ';\n }\n } else {\n out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n }\n $errSchemaPath = $currErrSchemaPath;\n if ($breakOnError) {\n out += ' break; ';\n }\n }\n } else if ($additionalIsSchema) {\n if ($removeAdditional == 'failing') {\n out += ' var ' + ($errs) + ' = errors; ';\n var $wasComposite = it.compositeRule;\n it.compositeRule = $it.compositeRule = true;\n $it.schema = $aProperties;\n $it.schemaPath = it.schemaPath + '.additionalProperties';\n $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';\n $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);\n var $passData = $data + '[' + $key + ']';\n $it.dataPathArr[$dataNxt] = $key;\n var $code = it.validate($it);\n $it.baseId = $currentBaseId;\n if (it.util.varOccurences($code, $nextData) < 2) {\n out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';\n } else {\n out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';\n }\n out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } ';\n it.compositeRule = $it.compositeRule = $wasComposite;\n } else {\n $it.schema = $aProperties;\n $it.schemaPath = it.schemaPath + '.additionalProperties';\n $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';\n $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);\n var $passData = $data + '[' + $key + ']';\n $it.dataPathArr[$dataNxt] = $key;\n var $code = it.validate($it);\n $it.baseId = $currentBaseId;\n if (it.util.varOccurences($code, $nextData) < 2) {\n out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';\n } else {\n out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';\n }\n if ($breakOnError) {\n out += ' if (!' + ($nextValid) + ') break; ';\n }\n }\n }\n it.errorPath = $currentErrorPath;\n }\n if ($someProperties) {\n out += ' } ';\n }\n out += ' } ';\n if ($breakOnError) {\n out += ' if (' + ($nextValid) + ') { ';\n $closingBraces += '}';\n }\n }\n var $useDefaults = it.opts.useDefaults && !it.compositeRule;\n if ($schemaKeys.length) {\n var arr3 = $schemaKeys;\n if (arr3) {\n var $propertyKey, i3 = -1,\n l3 = arr3.length - 1;\n while (i3 < l3) {\n $propertyKey = arr3[i3 += 1];\n var $sch = $schema[$propertyKey];\n if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {\n var $prop = it.util.getProperty($propertyKey),\n $passData = $data + $prop,\n $hasDefault = $useDefaults && $sch.default !== undefined;\n $it.schema = $sch;\n $it.schemaPath = $schemaPath + $prop;\n $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey);\n $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers);\n $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey);\n var $code = it.validate($it);\n $it.baseId = $currentBaseId;\n if (it.util.varOccurences($code, $nextData) < 2) {\n $code = it.util.varReplace($code, $nextData, $passData);\n var $useData = $passData;\n } else {\n var $useData = $nextData;\n out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ';\n }\n if ($hasDefault) {\n out += ' ' + ($code) + ' ';\n } else {\n if ($requiredHash && $requiredHash[$propertyKey]) {\n out += ' if ( ' + ($useData) + ' === undefined ';\n if ($ownProperties) {\n out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \\'' + (it.util.escapeQuotes($propertyKey)) + '\\') ';\n }\n out += ') { ' + ($nextValid) + ' = false; ';\n var $currentErrorPath = it.errorPath,\n $currErrSchemaPath = $errSchemaPath,\n $missingProperty = it.util.escapeQuotes($propertyKey);\n if (it.opts._errorDataPathProperty) {\n it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);\n }\n $errSchemaPath = it.errSchemaPath + '/required';\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = ''; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ('required') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \\'' + ($missingProperty) + '\\' } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'';\n if (it.opts._errorDataPathProperty) {\n out += 'is a required property';\n } else {\n out += 'should have required property \\\\\\'' + ($missingProperty) + '\\\\\\'';\n }\n out += '\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n var __err = out;\n out = $$outStack.pop();\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError([' + (__err) + ']); ';\n } else {\n out += ' validate.errors = [' + (__err) + ']; return false; ';\n }\n } else {\n out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n }\n $errSchemaPath = $currErrSchemaPath;\n it.errorPath = $currentErrorPath;\n out += ' } else { ';\n } else {\n if ($breakOnError) {\n out += ' if ( ' + ($useData) + ' === undefined ';\n if ($ownProperties) {\n out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \\'' + (it.util.escapeQuotes($propertyKey)) + '\\') ';\n }\n out += ') { ' + ($nextValid) + ' = true; } else { ';\n } else {\n out += ' if (' + ($useData) + ' !== undefined ';\n if ($ownProperties) {\n out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \\'' + (it.util.escapeQuotes($propertyKey)) + '\\') ';\n }\n out += ' ) { ';\n }\n }\n out += ' ' + ($code) + ' } ';\n }\n }\n if ($breakOnError) {\n out += ' if (' + ($nextValid) + ') { ';\n $closingBraces += '}';\n }\n }\n }\n }\n if ($pPropertyKeys.length) {\n var arr4 = $pPropertyKeys;\n if (arr4) {\n var $pProperty, i4 = -1,\n l4 = arr4.length - 1;\n while (i4 < l4) {\n $pProperty = arr4[i4 += 1];\n var $sch = $pProperties[$pProperty];\n if ((it.opts.strictKeywords ? (typeof $sch == 'object' && Object.keys($sch).length > 0) || $sch === false : it.util.schemaHasRules($sch, it.RULES.all))) {\n $it.schema = $sch;\n $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty);\n $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty);\n if ($ownProperties) {\n out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';\n } else {\n out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';\n }\n out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { ';\n $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);\n var $passData = $data + '[' + $key + ']';\n $it.dataPathArr[$dataNxt] = $key;\n var $code = it.validate($it);\n $it.baseId = $currentBaseId;\n if (it.util.varOccurences($code, $nextData) < 2) {\n out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';\n } else {\n out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';\n }\n if ($breakOnError) {\n out += ' if (!' + ($nextValid) + ') break; ';\n }\n out += ' } ';\n if ($breakOnError) {\n out += ' else ' + ($nextValid) + ' = true; ';\n }\n out += ' } ';\n if ($breakOnError) {\n out += ' if (' + ($nextValid) + ') { ';\n $closingBraces += '}';\n }\n }\n }\n }\n }\n if ($breakOnError) {\n out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';\n }\n return out;\n}\n","'use strict';\nmodule.exports = function generate_propertyNames(it, $keyword, $ruleType) {\n var out = ' ';\n var $lvl = it.level;\n var $dataLvl = it.dataLevel;\n var $schema = it.schema[$keyword];\n var $schemaPath = it.schemaPath + it.util.getProperty($keyword);\n var $errSchemaPath = it.errSchemaPath + '/' + $keyword;\n var $breakOnError = !it.opts.allErrors;\n var $data = 'data' + ($dataLvl || '');\n var $errs = 'errs__' + $lvl;\n var $it = it.util.copy(it);\n var $closingBraces = '';\n $it.level++;\n var $nextValid = 'valid' + $it.level;\n out += 'var ' + ($errs) + ' = errors;';\n if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) {\n $it.schema = $schema;\n $it.schemaPath = $schemaPath;\n $it.errSchemaPath = $errSchemaPath;\n var $key = 'key' + $lvl,\n $idx = 'idx' + $lvl,\n $i = 'i' + $lvl,\n $invalidName = '\\' + ' + $key + ' + \\'',\n $dataNxt = $it.dataLevel = it.dataLevel + 1,\n $nextData = 'data' + $dataNxt,\n $dataProperties = 'dataProperties' + $lvl,\n $ownProperties = it.opts.ownProperties,\n $currentBaseId = it.baseId;\n if ($ownProperties) {\n out += ' var ' + ($dataProperties) + ' = undefined; ';\n }\n if ($ownProperties) {\n out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';\n } else {\n out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';\n }\n out += ' var startErrs' + ($lvl) + ' = errors; ';\n var $passData = $key;\n var $wasComposite = it.compositeRule;\n it.compositeRule = $it.compositeRule = true;\n var $code = it.validate($it);\n $it.baseId = $currentBaseId;\n if (it.util.varOccurences($code, $nextData) < 2) {\n out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';\n } else {\n out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';\n }\n it.compositeRule = $it.compositeRule = $wasComposite;\n out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + ' 0) || $propertySch === false : it.util.schemaHasRules($propertySch, it.RULES.all)))) {\n $required[$required.length] = $property;\n }\n }\n }\n } else {\n var $required = $schema;\n }\n }\n if ($isData || $required.length) {\n var $currentErrorPath = it.errorPath,\n $loopRequired = $isData || $required.length >= it.opts.loopRequired,\n $ownProperties = it.opts.ownProperties;\n if ($breakOnError) {\n out += ' var missing' + ($lvl) + '; ';\n if ($loopRequired) {\n if (!$isData) {\n out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';\n }\n var $i = 'i' + $lvl,\n $propertyPath = 'schema' + $lvl + '[' + $i + ']',\n $missingProperty = '\\' + ' + $propertyPath + ' + \\'';\n if (it.opts._errorDataPathProperty) {\n it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);\n }\n out += ' var ' + ($valid) + ' = true; ';\n if ($isData) {\n out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';\n }\n out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined ';\n if ($ownProperties) {\n out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) ';\n }\n out += '; if (!' + ($valid) + ') break; } ';\n if ($isData) {\n out += ' } ';\n }\n out += ' if (!' + ($valid) + ') { ';\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = ''; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ('required') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \\'' + ($missingProperty) + '\\' } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'';\n if (it.opts._errorDataPathProperty) {\n out += 'is a required property';\n } else {\n out += 'should have required property \\\\\\'' + ($missingProperty) + '\\\\\\'';\n }\n out += '\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n var __err = out;\n out = $$outStack.pop();\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError([' + (__err) + ']); ';\n } else {\n out += ' validate.errors = [' + (__err) + ']; return false; ';\n }\n } else {\n out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n }\n out += ' } else { ';\n } else {\n out += ' if ( ';\n var arr2 = $required;\n if (arr2) {\n var $propertyKey, $i = -1,\n l2 = arr2.length - 1;\n while ($i < l2) {\n $propertyKey = arr2[$i += 1];\n if ($i) {\n out += ' || ';\n }\n var $prop = it.util.getProperty($propertyKey),\n $useData = $data + $prop;\n out += ' ( ( ' + ($useData) + ' === undefined ';\n if ($ownProperties) {\n out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \\'' + (it.util.escapeQuotes($propertyKey)) + '\\') ';\n }\n out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) ';\n }\n }\n out += ') { ';\n var $propertyPath = 'missing' + $lvl,\n $missingProperty = '\\' + ' + $propertyPath + ' + \\'';\n if (it.opts._errorDataPathProperty) {\n it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;\n }\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = ''; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ('required') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \\'' + ($missingProperty) + '\\' } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'';\n if (it.opts._errorDataPathProperty) {\n out += 'is a required property';\n } else {\n out += 'should have required property \\\\\\'' + ($missingProperty) + '\\\\\\'';\n }\n out += '\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n var __err = out;\n out = $$outStack.pop();\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError([' + (__err) + ']); ';\n } else {\n out += ' validate.errors = [' + (__err) + ']; return false; ';\n }\n } else {\n out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n }\n out += ' } else { ';\n }\n } else {\n if ($loopRequired) {\n if (!$isData) {\n out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';\n }\n var $i = 'i' + $lvl,\n $propertyPath = 'schema' + $lvl + '[' + $i + ']',\n $missingProperty = '\\' + ' + $propertyPath + ' + \\'';\n if (it.opts._errorDataPathProperty) {\n it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);\n }\n if ($isData) {\n out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ('required') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \\'' + ($missingProperty) + '\\' } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'';\n if (it.opts._errorDataPathProperty) {\n out += 'is a required property';\n } else {\n out += 'should have required property \\\\\\'' + ($missingProperty) + '\\\\\\'';\n }\n out += '\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { ';\n }\n out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined ';\n if ($ownProperties) {\n out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) ';\n }\n out += ') { var err = '; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ('required') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \\'' + ($missingProperty) + '\\' } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'';\n if (it.opts._errorDataPathProperty) {\n out += 'is a required property';\n } else {\n out += 'should have required property \\\\\\'' + ($missingProperty) + '\\\\\\'';\n }\n out += '\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ';\n if ($isData) {\n out += ' } ';\n }\n } else {\n var arr3 = $required;\n if (arr3) {\n var $propertyKey, i3 = -1,\n l3 = arr3.length - 1;\n while (i3 < l3) {\n $propertyKey = arr3[i3 += 1];\n var $prop = it.util.getProperty($propertyKey),\n $missingProperty = it.util.escapeQuotes($propertyKey),\n $useData = $data + $prop;\n if (it.opts._errorDataPathProperty) {\n it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);\n }\n out += ' if ( ' + ($useData) + ' === undefined ';\n if ($ownProperties) {\n out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \\'' + (it.util.escapeQuotes($propertyKey)) + '\\') ';\n }\n out += ') { var err = '; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ('required') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \\'' + ($missingProperty) + '\\' } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'';\n if (it.opts._errorDataPathProperty) {\n out += 'is a required property';\n } else {\n out += 'should have required property \\\\\\'' + ($missingProperty) + '\\\\\\'';\n }\n out += '\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';\n }\n }\n }\n }\n it.errorPath = $currentErrorPath;\n } else if ($breakOnError) {\n out += ' if (true) {';\n }\n return out;\n}\n","'use strict';\nmodule.exports = function generate_uniqueItems(it, $keyword, $ruleType) {\n var out = ' ';\n var $lvl = it.level;\n var $dataLvl = it.dataLevel;\n var $schema = it.schema[$keyword];\n var $schemaPath = it.schemaPath + it.util.getProperty($keyword);\n var $errSchemaPath = it.errSchemaPath + '/' + $keyword;\n var $breakOnError = !it.opts.allErrors;\n var $data = 'data' + ($dataLvl || '');\n var $valid = 'valid' + $lvl;\n var $isData = it.opts.$data && $schema && $schema.$data,\n $schemaValue;\n if ($isData) {\n out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';\n $schemaValue = 'schema' + $lvl;\n } else {\n $schemaValue = $schema;\n }\n if (($schema || $isData) && it.opts.uniqueItems !== false) {\n if ($isData) {\n out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \\'boolean\\') ' + ($valid) + ' = false; else { ';\n }\n out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { ';\n var $itemType = it.schema.items && it.schema.items.type,\n $typeIsArray = Array.isArray($itemType);\n if (!$itemType || $itemType == 'object' || $itemType == 'array' || ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0))) {\n out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } ';\n } else {\n out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; ';\n var $method = 'checkDataType' + ($typeIsArray ? 's' : '');\n out += ' if (' + (it.util[$method]($itemType, 'item', it.opts.strictNumbers, true)) + ') continue; ';\n if ($typeIsArray) {\n out += ' if (typeof item == \\'string\\') item = \\'\"\\' + item; ';\n }\n out += ' if (typeof itemIndices[item] == \\'number\\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } ';\n }\n out += ' } ';\n if ($isData) {\n out += ' } ';\n }\n out += ' if (!' + ($valid) + ') { ';\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = ''; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ('uniqueItems') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'should NOT have duplicate items (items ## \\' + j + \\' and \\' + i + \\' are identical)\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: ';\n if ($isData) {\n out += 'validate.schema' + ($schemaPath);\n } else {\n out += '' + ($schema);\n }\n out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n var __err = out;\n out = $$outStack.pop();\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError([' + (__err) + ']); ';\n } else {\n out += ' validate.errors = [' + (__err) + ']; return false; ';\n }\n } else {\n out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n }\n out += ' } ';\n if ($breakOnError) {\n out += ' else { ';\n }\n } else {\n if ($breakOnError) {\n out += ' if (true) { ';\n }\n }\n return out;\n}\n","'use strict';\nmodule.exports = function generate_validate(it, $keyword, $ruleType) {\n var out = '';\n var $async = it.schema.$async === true,\n $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'),\n $id = it.self._getId(it.schema);\n if (it.opts.strictKeywords) {\n var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords);\n if ($unknownKwd) {\n var $keywordsMsg = 'unknown keyword: ' + $unknownKwd;\n if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg);\n else throw new Error($keywordsMsg);\n }\n }\n if (it.isTop) {\n out += ' var validate = ';\n if ($async) {\n it.async = true;\n out += 'async ';\n }\n out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \\'use strict\\'; ';\n if ($id && (it.opts.sourceCode || it.opts.processCode)) {\n out += ' ' + ('/\\*# sourceURL=' + $id + ' */') + ' ';\n }\n }\n if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) {\n var $keyword = 'false schema';\n var $lvl = it.level;\n var $dataLvl = it.dataLevel;\n var $schema = it.schema[$keyword];\n var $schemaPath = it.schemaPath + it.util.getProperty($keyword);\n var $errSchemaPath = it.errSchemaPath + '/' + $keyword;\n var $breakOnError = !it.opts.allErrors;\n var $errorKeyword;\n var $data = 'data' + ($dataLvl || '');\n var $valid = 'valid' + $lvl;\n if (it.schema === false) {\n if (it.isTop) {\n $breakOnError = true;\n } else {\n out += ' var ' + ($valid) + ' = false; ';\n }\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = ''; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ($errorKeyword || 'false schema') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'boolean schema is false\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n var __err = out;\n out = $$outStack.pop();\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError([' + (__err) + ']); ';\n } else {\n out += ' validate.errors = [' + (__err) + ']; return false; ';\n }\n } else {\n out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n }\n } else {\n if (it.isTop) {\n if ($async) {\n out += ' return data; ';\n } else {\n out += ' validate.errors = null; return true; ';\n }\n } else {\n out += ' var ' + ($valid) + ' = true; ';\n }\n }\n if (it.isTop) {\n out += ' }; return validate; ';\n }\n return out;\n }\n if (it.isTop) {\n var $top = it.isTop,\n $lvl = it.level = 0,\n $dataLvl = it.dataLevel = 0,\n $data = 'data';\n it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema));\n it.baseId = it.baseId || it.rootId;\n delete it.isTop;\n it.dataPathArr = [\"\"];\n if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) {\n var $defaultMsg = 'default is ignored in the schema root';\n if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);\n else throw new Error($defaultMsg);\n }\n out += ' var vErrors = null; ';\n out += ' var errors = 0; ';\n out += ' if (rootData === undefined) rootData = data; ';\n } else {\n var $lvl = it.level,\n $dataLvl = it.dataLevel,\n $data = 'data' + ($dataLvl || '');\n if ($id) it.baseId = it.resolve.url(it.baseId, $id);\n if ($async && !it.async) throw new Error('async schema in sync schema');\n out += ' var errs_' + ($lvl) + ' = errors;';\n }\n var $valid = 'valid' + $lvl,\n $breakOnError = !it.opts.allErrors,\n $closingBraces1 = '',\n $closingBraces2 = '';\n var $errorKeyword;\n var $typeSchema = it.schema.type,\n $typeIsArray = Array.isArray($typeSchema);\n if ($typeSchema && it.opts.nullable && it.schema.nullable === true) {\n if ($typeIsArray) {\n if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null');\n } else if ($typeSchema != 'null') {\n $typeSchema = [$typeSchema, 'null'];\n $typeIsArray = true;\n }\n }\n if ($typeIsArray && $typeSchema.length == 1) {\n $typeSchema = $typeSchema[0];\n $typeIsArray = false;\n }\n if (it.schema.$ref && $refKeywords) {\n if (it.opts.extendRefs == 'fail') {\n throw new Error('$ref: validation keywords used in schema at path \"' + it.errSchemaPath + '\" (see option extendRefs)');\n } else if (it.opts.extendRefs !== true) {\n $refKeywords = false;\n it.logger.warn('$ref: keywords ignored in schema at path \"' + it.errSchemaPath + '\"');\n }\n }\n if (it.schema.$comment && it.opts.$comment) {\n out += ' ' + (it.RULES.all.$comment.code(it, '$comment'));\n }\n if ($typeSchema) {\n if (it.opts.coerceTypes) {\n var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema);\n }\n var $rulesGroup = it.RULES.types[$typeSchema];\n if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) {\n var $schemaPath = it.schemaPath + '.type',\n $errSchemaPath = it.errSchemaPath + '/type';\n var $schemaPath = it.schemaPath + '.type',\n $errSchemaPath = it.errSchemaPath + '/type',\n $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';\n out += ' if (' + (it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true)) + ') { ';\n if ($coerceToTypes) {\n var $dataType = 'dataType' + $lvl,\n $coerced = 'coerced' + $lvl;\n out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; var ' + ($coerced) + ' = undefined; ';\n if (it.opts.coerceTypes == 'array') {\n out += ' if (' + ($dataType) + ' == \\'object\\' && Array.isArray(' + ($data) + ') && ' + ($data) + '.length == 1) { ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; if (' + (it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers)) + ') ' + ($coerced) + ' = ' + ($data) + '; } ';\n }\n out += ' if (' + ($coerced) + ' !== undefined) ; ';\n var arr1 = $coerceToTypes;\n if (arr1) {\n var $type, $i = -1,\n l1 = arr1.length - 1;\n while ($i < l1) {\n $type = arr1[$i += 1];\n if ($type == 'string') {\n out += ' else if (' + ($dataType) + ' == \\'number\\' || ' + ($dataType) + ' == \\'boolean\\') ' + ($coerced) + ' = \\'\\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \\'\\'; ';\n } else if ($type == 'number' || $type == 'integer') {\n out += ' else if (' + ($dataType) + ' == \\'boolean\\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \\'string\\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' ';\n if ($type == 'integer') {\n out += ' && !(' + ($data) + ' % 1)';\n }\n out += ')) ' + ($coerced) + ' = +' + ($data) + '; ';\n } else if ($type == 'boolean') {\n out += ' else if (' + ($data) + ' === \\'false\\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \\'true\\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; ';\n } else if ($type == 'null') {\n out += ' else if (' + ($data) + ' === \\'\\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; ';\n } else if (it.opts.coerceTypes == 'array' && $type == 'array') {\n out += ' else if (' + ($dataType) + ' == \\'string\\' || ' + ($dataType) + ' == \\'number\\' || ' + ($dataType) + ' == \\'boolean\\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; ';\n }\n }\n }\n out += ' else { ';\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = ''; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ($errorKeyword || 'type') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \\'';\n if ($typeIsArray) {\n out += '' + ($typeSchema.join(\",\"));\n } else {\n out += '' + ($typeSchema);\n }\n out += '\\' } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'should be ';\n if ($typeIsArray) {\n out += '' + ($typeSchema.join(\",\"));\n } else {\n out += '' + ($typeSchema);\n }\n out += '\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n var __err = out;\n out = $$outStack.pop();\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError([' + (__err) + ']); ';\n } else {\n out += ' validate.errors = [' + (__err) + ']; return false; ';\n }\n } else {\n out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n }\n out += ' } if (' + ($coerced) + ' !== undefined) { ';\n var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',\n $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';\n out += ' ' + ($data) + ' = ' + ($coerced) + '; ';\n if (!$dataLvl) {\n out += 'if (' + ($parentData) + ' !== undefined)';\n }\n out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } ';\n } else {\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = ''; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ($errorKeyword || 'type') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \\'';\n if ($typeIsArray) {\n out += '' + ($typeSchema.join(\",\"));\n } else {\n out += '' + ($typeSchema);\n }\n out += '\\' } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'should be ';\n if ($typeIsArray) {\n out += '' + ($typeSchema.join(\",\"));\n } else {\n out += '' + ($typeSchema);\n }\n out += '\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n var __err = out;\n out = $$outStack.pop();\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError([' + (__err) + ']); ';\n } else {\n out += ' validate.errors = [' + (__err) + ']; return false; ';\n }\n } else {\n out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n }\n }\n out += ' } ';\n }\n }\n if (it.schema.$ref && !$refKeywords) {\n out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' ';\n if ($breakOnError) {\n out += ' } if (errors === ';\n if ($top) {\n out += '0';\n } else {\n out += 'errs_' + ($lvl);\n }\n out += ') { ';\n $closingBraces2 += '}';\n }\n } else {\n var arr2 = it.RULES;\n if (arr2) {\n var $rulesGroup, i2 = -1,\n l2 = arr2.length - 1;\n while (i2 < l2) {\n $rulesGroup = arr2[i2 += 1];\n if ($shouldUseGroup($rulesGroup)) {\n if ($rulesGroup.type) {\n out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers)) + ') { ';\n }\n if (it.opts.useDefaults) {\n if ($rulesGroup.type == 'object' && it.schema.properties) {\n var $schema = it.schema.properties,\n $schemaKeys = Object.keys($schema);\n var arr3 = $schemaKeys;\n if (arr3) {\n var $propertyKey, i3 = -1,\n l3 = arr3.length - 1;\n while (i3 < l3) {\n $propertyKey = arr3[i3 += 1];\n var $sch = $schema[$propertyKey];\n if ($sch.default !== undefined) {\n var $passData = $data + it.util.getProperty($propertyKey);\n if (it.compositeRule) {\n if (it.opts.strictDefaults) {\n var $defaultMsg = 'default is ignored for: ' + $passData;\n if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);\n else throw new Error($defaultMsg);\n }\n } else {\n out += ' if (' + ($passData) + ' === undefined ';\n if (it.opts.useDefaults == 'empty') {\n out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \\'\\' ';\n }\n out += ' ) ' + ($passData) + ' = ';\n if (it.opts.useDefaults == 'shared') {\n out += ' ' + (it.useDefault($sch.default)) + ' ';\n } else {\n out += ' ' + (JSON.stringify($sch.default)) + ' ';\n }\n out += '; ';\n }\n }\n }\n }\n } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) {\n var arr4 = it.schema.items;\n if (arr4) {\n var $sch, $i = -1,\n l4 = arr4.length - 1;\n while ($i < l4) {\n $sch = arr4[$i += 1];\n if ($sch.default !== undefined) {\n var $passData = $data + '[' + $i + ']';\n if (it.compositeRule) {\n if (it.opts.strictDefaults) {\n var $defaultMsg = 'default is ignored for: ' + $passData;\n if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);\n else throw new Error($defaultMsg);\n }\n } else {\n out += ' if (' + ($passData) + ' === undefined ';\n if (it.opts.useDefaults == 'empty') {\n out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \\'\\' ';\n }\n out += ' ) ' + ($passData) + ' = ';\n if (it.opts.useDefaults == 'shared') {\n out += ' ' + (it.useDefault($sch.default)) + ' ';\n } else {\n out += ' ' + (JSON.stringify($sch.default)) + ' ';\n }\n out += '; ';\n }\n }\n }\n }\n }\n }\n var arr5 = $rulesGroup.rules;\n if (arr5) {\n var $rule, i5 = -1,\n l5 = arr5.length - 1;\n while (i5 < l5) {\n $rule = arr5[i5 += 1];\n if ($shouldUseRule($rule)) {\n var $code = $rule.code(it, $rule.keyword, $rulesGroup.type);\n if ($code) {\n out += ' ' + ($code) + ' ';\n if ($breakOnError) {\n $closingBraces1 += '}';\n }\n }\n }\n }\n }\n if ($breakOnError) {\n out += ' ' + ($closingBraces1) + ' ';\n $closingBraces1 = '';\n }\n if ($rulesGroup.type) {\n out += ' } ';\n if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) {\n out += ' else { ';\n var $schemaPath = it.schemaPath + '.type',\n $errSchemaPath = it.errSchemaPath + '/type';\n var $$outStack = $$outStack || [];\n $$outStack.push(out);\n out = ''; /* istanbul ignore else */\n if (it.createErrors !== false) {\n out += ' { keyword: \\'' + ($errorKeyword || 'type') + '\\' , dataPath: (dataPath || \\'\\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \\'';\n if ($typeIsArray) {\n out += '' + ($typeSchema.join(\",\"));\n } else {\n out += '' + ($typeSchema);\n }\n out += '\\' } ';\n if (it.opts.messages !== false) {\n out += ' , message: \\'should be ';\n if ($typeIsArray) {\n out += '' + ($typeSchema.join(\",\"));\n } else {\n out += '' + ($typeSchema);\n }\n out += '\\' ';\n }\n if (it.opts.verbose) {\n out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';\n }\n out += ' } ';\n } else {\n out += ' {} ';\n }\n var __err = out;\n out = $$outStack.pop();\n if (!it.compositeRule && $breakOnError) {\n /* istanbul ignore if */\n if (it.async) {\n out += ' throw new ValidationError([' + (__err) + ']); ';\n } else {\n out += ' validate.errors = [' + (__err) + ']; return false; ';\n }\n } else {\n out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';\n }\n out += ' } ';\n }\n }\n if ($breakOnError) {\n out += ' if (errors === ';\n if ($top) {\n out += '0';\n } else {\n out += 'errs_' + ($lvl);\n }\n out += ') { ';\n $closingBraces2 += '}';\n }\n }\n }\n }\n }\n if ($breakOnError) {\n out += ' ' + ($closingBraces2) + ' ';\n }\n if ($top) {\n if ($async) {\n out += ' if (errors === 0) return data; ';\n out += ' else throw new ValidationError(vErrors); ';\n } else {\n out += ' validate.errors = vErrors; ';\n out += ' return errors === 0; ';\n }\n out += ' }; return validate;';\n } else {\n out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';';\n }\n\n function $shouldUseGroup($rulesGroup) {\n var rules = $rulesGroup.rules;\n for (var i = 0; i < rules.length; i++)\n if ($shouldUseRule(rules[i])) return true;\n }\n\n function $shouldUseRule($rule) {\n return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule));\n }\n\n function $ruleImplementsSomeKeyword($rule) {\n var impl = $rule.implements;\n for (var i = 0; i < impl.length; i++)\n if (it.schema[impl[i]] !== undefined) return true;\n }\n return out;\n}\n","'use strict';\n\nvar IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i;\nvar customRuleCode = require('./dotjs/custom');\nvar definitionSchema = require('./definition_schema');\n\nmodule.exports = {\n add: addKeyword,\n get: getKeyword,\n remove: removeKeyword,\n validate: validateKeyword\n};\n\n\n/**\n * Define custom keyword\n * @this Ajv\n * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords).\n * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`.\n * @return {Ajv} this for method chaining\n */\nfunction addKeyword(keyword, definition) {\n /* jshint validthis: true */\n /* eslint no-shadow: 0 */\n var RULES = this.RULES;\n if (RULES.keywords[keyword])\n throw new Error('Keyword ' + keyword + ' is already defined');\n\n if (!IDENTIFIER.test(keyword))\n throw new Error('Keyword ' + keyword + ' is not a valid identifier');\n\n if (definition) {\n this.validateKeyword(definition, true);\n\n var dataType = definition.type;\n if (Array.isArray(dataType)) {\n for (var i=0; i<]/g;\n};\n","'use strict';\n\nconst wrapAnsi16 = (fn, offset) => (...args) => {\n\tconst code = fn(...args);\n\treturn `\\u001B[${code + offset}m`;\n};\n\nconst wrapAnsi256 = (fn, offset) => (...args) => {\n\tconst code = fn(...args);\n\treturn `\\u001B[${38 + offset};5;${code}m`;\n};\n\nconst wrapAnsi16m = (fn, offset) => (...args) => {\n\tconst rgb = fn(...args);\n\treturn `\\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;\n};\n\nconst ansi2ansi = n => n;\nconst rgb2rgb = (r, g, b) => [r, g, b];\n\nconst setLazyProperty = (object, property, get) => {\n\tObject.defineProperty(object, property, {\n\t\tget: () => {\n\t\t\tconst value = get();\n\n\t\t\tObject.defineProperty(object, property, {\n\t\t\t\tvalue,\n\t\t\t\tenumerable: true,\n\t\t\t\tconfigurable: true\n\t\t\t});\n\n\t\t\treturn value;\n\t\t},\n\t\tenumerable: true,\n\t\tconfigurable: true\n\t});\n};\n\n/** @type {typeof import('color-convert')} */\nlet colorConvert;\nconst makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {\n\tif (colorConvert === undefined) {\n\t\tcolorConvert = require('color-convert');\n\t}\n\n\tconst offset = isBackground ? 10 : 0;\n\tconst styles = {};\n\n\tfor (const [sourceSpace, suite] of Object.entries(colorConvert)) {\n\t\tconst name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;\n\t\tif (sourceSpace === targetSpace) {\n\t\t\tstyles[name] = wrap(identity, offset);\n\t\t} else if (typeof suite === 'object') {\n\t\t\tstyles[name] = wrap(suite[targetSpace], offset);\n\t\t}\n\t}\n\n\treturn styles;\n};\n\nfunction assembleStyles() {\n\tconst codes = new Map();\n\tconst styles = {\n\t\tmodifier: {\n\t\t\treset: [0, 0],\n\t\t\t// 21 isn't widely supported and 22 does the same thing\n\t\t\tbold: [1, 22],\n\t\t\tdim: [2, 22],\n\t\t\titalic: [3, 23],\n\t\t\tunderline: [4, 24],\n\t\t\tinverse: [7, 27],\n\t\t\thidden: [8, 28],\n\t\t\tstrikethrough: [9, 29]\n\t\t},\n\t\tcolor: {\n\t\t\tblack: [30, 39],\n\t\t\tred: [31, 39],\n\t\t\tgreen: [32, 39],\n\t\t\tyellow: [33, 39],\n\t\t\tblue: [34, 39],\n\t\t\tmagenta: [35, 39],\n\t\t\tcyan: [36, 39],\n\t\t\twhite: [37, 39],\n\n\t\t\t// Bright color\n\t\t\tblackBright: [90, 39],\n\t\t\tredBright: [91, 39],\n\t\t\tgreenBright: [92, 39],\n\t\t\tyellowBright: [93, 39],\n\t\t\tblueBright: [94, 39],\n\t\t\tmagentaBright: [95, 39],\n\t\t\tcyanBright: [96, 39],\n\t\t\twhiteBright: [97, 39]\n\t\t},\n\t\tbgColor: {\n\t\t\tbgBlack: [40, 49],\n\t\t\tbgRed: [41, 49],\n\t\t\tbgGreen: [42, 49],\n\t\t\tbgYellow: [43, 49],\n\t\t\tbgBlue: [44, 49],\n\t\t\tbgMagenta: [45, 49],\n\t\t\tbgCyan: [46, 49],\n\t\t\tbgWhite: [47, 49],\n\n\t\t\t// Bright color\n\t\t\tbgBlackBright: [100, 49],\n\t\t\tbgRedBright: [101, 49],\n\t\t\tbgGreenBright: [102, 49],\n\t\t\tbgYellowBright: [103, 49],\n\t\t\tbgBlueBright: [104, 49],\n\t\t\tbgMagentaBright: [105, 49],\n\t\t\tbgCyanBright: [106, 49],\n\t\t\tbgWhiteBright: [107, 49]\n\t\t}\n\t};\n\n\t// Alias bright black as gray (and grey)\n\tstyles.color.gray = styles.color.blackBright;\n\tstyles.bgColor.bgGray = styles.bgColor.bgBlackBright;\n\tstyles.color.grey = styles.color.blackBright;\n\tstyles.bgColor.bgGrey = styles.bgColor.bgBlackBright;\n\n\tfor (const [groupName, group] of Object.entries(styles)) {\n\t\tfor (const [styleName, style] of Object.entries(group)) {\n\t\t\tstyles[styleName] = {\n\t\t\t\topen: `\\u001B[${style[0]}m`,\n\t\t\t\tclose: `\\u001B[${style[1]}m`\n\t\t\t};\n\n\t\t\tgroup[styleName] = styles[styleName];\n\n\t\t\tcodes.set(style[0], style[1]);\n\t\t}\n\n\t\tObject.defineProperty(styles, groupName, {\n\t\t\tvalue: group,\n\t\t\tenumerable: false\n\t\t});\n\t}\n\n\tObject.defineProperty(styles, 'codes', {\n\t\tvalue: codes,\n\t\tenumerable: false\n\t});\n\n\tstyles.color.close = '\\u001B[39m';\n\tstyles.bgColor.close = '\\u001B[49m';\n\n\tsetLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));\n\tsetLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));\n\tsetLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));\n\tsetLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));\n\tsetLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));\n\tsetLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));\n\n\treturn styles;\n}\n\n// Make the export immutable\nObject.defineProperty(module, 'exports', {\n\tenumerable: true,\n\tget: assembleStyles\n});\n","'use strict';\n\nvar lib = require('./lib/app-root-path.js');\nmodule.exports = lib(__dirname);",null,null,"'use strict'\n\nfunction isArguments (thingy) {\n return thingy != null && typeof thingy === 'object' && thingy.hasOwnProperty('callee')\n}\n\nvar types = {\n '*': {label: 'any', check: function () { return true }},\n A: {label: 'array', check: function (thingy) { return Array.isArray(thingy) || isArguments(thingy) }},\n S: {label: 'string', check: function (thingy) { return typeof thingy === 'string' }},\n N: {label: 'number', check: function (thingy) { return typeof thingy === 'number' }},\n F: {label: 'function', check: function (thingy) { return typeof thingy === 'function' }},\n O: {label: 'object', check: function (thingy) { return typeof thingy === 'object' && thingy != null && !types.A.check(thingy) && !types.E.check(thingy) }},\n B: {label: 'boolean', check: function (thingy) { return typeof thingy === 'boolean' }},\n E: {label: 'error', check: function (thingy) { return thingy instanceof Error }},\n Z: {label: 'null', check: function (thingy) { return thingy == null }}\n}\n\nfunction addSchema (schema, arity) {\n var group = arity[schema.length] = arity[schema.length] || []\n if (group.indexOf(schema) === -1) group.push(schema)\n}\n\nvar validate = module.exports = function (rawSchemas, args) {\n if (arguments.length !== 2) throw wrongNumberOfArgs(['SA'], arguments.length)\n if (!rawSchemas) throw missingRequiredArg(0, 'rawSchemas')\n if (!args) throw missingRequiredArg(1, 'args')\n if (!types.S.check(rawSchemas)) throw invalidType(0, ['string'], rawSchemas)\n if (!types.A.check(args)) throw invalidType(1, ['array'], args)\n var schemas = rawSchemas.split('|')\n var arity = {}\n\n schemas.forEach(function (schema) {\n for (var ii = 0; ii < schema.length; ++ii) {\n var type = schema[ii]\n if (!types[type]) throw unknownType(ii, type)\n }\n if (/E.*E/.test(schema)) throw moreThanOneError(schema)\n addSchema(schema, arity)\n if (/E/.test(schema)) {\n addSchema(schema.replace(/E.*$/, 'E'), arity)\n addSchema(schema.replace(/E/, 'Z'), arity)\n if (schema.length === 1) addSchema('', arity)\n }\n })\n var matching = arity[args.length]\n if (!matching) {\n throw wrongNumberOfArgs(Object.keys(arity), args.length)\n }\n for (var ii = 0; ii < args.length; ++ii) {\n var newMatching = matching.filter(function (schema) {\n var type = schema[ii]\n var typeCheck = types[type].check\n return typeCheck(args[ii])\n })\n if (!newMatching.length) {\n var labels = matching.map(function (schema) {\n return types[schema[ii]].label\n }).filter(function (schema) { return schema != null })\n throw invalidType(ii, labels, args[ii])\n }\n matching = newMatching\n }\n}\n\nfunction missingRequiredArg (num) {\n return newException('EMISSINGARG', 'Missing required argument #' + (num + 1))\n}\n\nfunction unknownType (num, type) {\n return newException('EUNKNOWNTYPE', 'Unknown type ' + type + ' in argument #' + (num + 1))\n}\n\nfunction invalidType (num, expectedTypes, value) {\n var valueType\n Object.keys(types).forEach(function (typeCode) {\n if (types[typeCode].check(value)) valueType = types[typeCode].label\n })\n return newException('EINVALIDTYPE', 'Argument #' + (num + 1) + ': Expected ' +\n englishList(expectedTypes) + ' but got ' + valueType)\n}\n\nfunction englishList (list) {\n return list.join(', ').replace(/, ([^,]+)$/, ' or $1')\n}\n\nfunction wrongNumberOfArgs (expected, got) {\n var english = englishList(expected)\n var args = expected.every(function (ex) { return ex.length === 1 })\n ? 'argument'\n : 'arguments'\n return newException('EWRONGARGCOUNT', 'Expected ' + english + ' ' + args + ' but got ' + got)\n}\n\nfunction moreThanOneError (schema) {\n return newException('ETOOMANYERRORTYPES',\n 'Only one error type per argument signature is allowed, more than one found in \"' + schema + '\"')\n}\n\nfunction newException (code, msg) {\n var e = new Error(msg)\n e.code = code\n if (Error.captureStackTrace) Error.captureStackTrace(e, validate)\n return e\n}\n","'use strict'\nexports.TrackerGroup = require('./tracker-group.js')\nexports.Tracker = require('./tracker.js')\nexports.TrackerStream = require('./tracker-stream.js')\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a duplex stream is just a stream that is both readable and writable.\n// Since JS doesn't have multiple prototypal inheritance, this class\n// prototypally inherits from Readable, and then parasitically from\n// Writable.\n\n'use strict';\n\n/**/\n\nvar pna = require('process-nextick-args');\n/**/\n\n/**/\nvar objectKeys = Object.keys || function (obj) {\n var keys = [];\n for (var key in obj) {\n keys.push(key);\n }return keys;\n};\n/**/\n\nmodule.exports = Duplex;\n\n/**/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/**/\n\nvar Readable = require('./_stream_readable');\nvar Writable = require('./_stream_writable');\n\nutil.inherits(Duplex, Readable);\n\n{\n // avoid scope creep, the keys array can then be collected\n var keys = objectKeys(Writable.prototype);\n for (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n }\n}\n\nfunction Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n\n Readable.call(this, options);\n Writable.call(this, options);\n\n if (options && options.readable === false) this.readable = false;\n\n if (options && options.writable === false) this.writable = false;\n\n this.allowHalfOpen = true;\n if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;\n\n this.once('end', onend);\n}\n\nObject.defineProperty(Duplex.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// the no-half-open enforcer\nfunction onend() {\n // if we allow half-open state, or if the writable side ended,\n // then we're ok.\n if (this.allowHalfOpen || this._writableState.ended) return;\n\n // no more data can be written.\n // But allow more writes to happen in this tick.\n pna.nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n\nObject.defineProperty(Duplex.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined || this._writableState === undefined) {\n return false;\n }\n return this._readableState.destroyed && this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (this._readableState === undefined || this._writableState === undefined) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n this._writableState.destroyed = value;\n }\n});\n\nDuplex.prototype._destroy = function (err, cb) {\n this.push(null);\n this.end();\n\n pna.nextTick(cb, err);\n};","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a passthrough stream.\n// basically just the most minimal sort of Transform stream.\n// Every written chunk gets output as-is.\n\n'use strict';\n\nmodule.exports = PassThrough;\n\nvar Transform = require('./_stream_transform');\n\n/**/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/**/\n\nutil.inherits(PassThrough, Transform);\n\nfunction PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar pna = require('process-nextick-args');\n/**/\n\nmodule.exports = Readable;\n\n/**/\nvar isArray = require('isarray');\n/**/\n\n/**/\nvar Duplex;\n/**/\n\nReadable.ReadableState = ReadableState;\n\n/**/\nvar EE = require('events').EventEmitter;\n\nvar EElistenerCount = function (emitter, type) {\n return emitter.listeners(type).length;\n};\n/**/\n\n/**/\nvar Stream = require('./internal/streams/stream');\n/**/\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\nvar OurUint8Array = global.Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/**/\n\n/**/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/**/\n\n/**/\nvar debugUtil = require('util');\nvar debug = void 0;\nif (debugUtil && debugUtil.debuglog) {\n debug = debugUtil.debuglog('stream');\n} else {\n debug = function () {};\n}\n/**/\n\nvar BufferList = require('./internal/streams/BufferList');\nvar destroyImpl = require('./internal/streams/destroy');\nvar StringDecoder;\n\nutil.inherits(Readable, Stream);\n\nvar kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);\n\n // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n 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]];\n}\n\nfunction ReadableState(options, stream) {\n Duplex = Duplex || require('./_stream_duplex');\n\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n this.objectMode = !!options.objectMode;\n\n if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;\n\n // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n var hwm = options.highWaterMark;\n var readableHwm = options.readableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false;\n\n // a flag to be able to tell if the event 'readable'/'data' is emitted\n // immediately, or on a later tick. We set this to true at first, because\n // any actions that shouldn't happen until \"later\" should generally also\n // not happen before the first read call.\n this.sync = true;\n\n // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // the number of writers that are awaiting a drain event in .pipe()s\n this.awaitDrain = 0;\n\n // if true, a maybeReadMore has been scheduled\n this.readingMore = false;\n\n this.decoder = null;\n this.encoding = null;\n if (options.encoding) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\n\nfunction Readable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n\n if (!(this instanceof Readable)) return new Readable(options);\n\n this._readableState = new ReadableState(options, this);\n\n // legacy\n this.readable = true;\n\n if (options) {\n if (typeof options.read === 'function') this._read = options.read;\n\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n }\n\n Stream.call(this);\n}\n\nObject.defineProperty(Readable.prototype, 'destroyed', {\n get: function () {\n if (this._readableState === undefined) {\n return false;\n }\n return this._readableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._readableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._readableState.destroyed = value;\n }\n});\n\nReadable.prototype.destroy = destroyImpl.destroy;\nReadable.prototype._undestroy = destroyImpl.undestroy;\nReadable.prototype._destroy = function (err, cb) {\n this.push(null);\n cb(err);\n};\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n var skipChunkCheck;\n\n if (!state.objectMode) {\n if (typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n skipChunkCheck = true;\n }\n } else {\n skipChunkCheck = true;\n }\n\n return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);\n};\n\n// Unshift should *always* be something directly out of read()\nReadable.prototype.unshift = function (chunk) {\n return readableAddChunk(this, chunk, null, true, false);\n};\n\nfunction readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {\n var state = stream._readableState;\n if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else {\n var er;\n if (!skipChunkCheck) er = chunkInvalid(state, chunk);\n if (er) {\n stream.emit('error', er);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (addToFront) {\n if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);\n } else if (state.ended) {\n stream.emit('error', new Error('stream.push() after EOF'));\n } else {\n state.reading = false;\n if (state.decoder && !encoding) {\n chunk = state.decoder.write(chunk);\n if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);\n } else {\n addChunk(stream, state, chunk, false);\n }\n }\n } else if (!addToFront) {\n state.reading = false;\n }\n }\n\n return needMoreData(state);\n}\n\nfunction addChunk(stream, state, chunk, addToFront) {\n if (state.flowing && state.length === 0 && !state.sync) {\n stream.emit('data', chunk);\n stream.read(0);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n\n if (state.needReadable) emitReadable(stream);\n }\n maybeReadMore(stream, state);\n}\n\nfunction chunkInvalid(state, chunk) {\n var er;\n if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n return er;\n}\n\n// if it's past the high water mark, we can push in some more.\n// Also, if we have no data yet, we can stand some\n// more bytes. This is to work around cases where hwm=0,\n// such as the repl. Also, if the push() triggered a\n// readable event, and the user called read(largeNumber) such that\n// needReadable was set, then we ought to push more, so that another\n// 'readable' event will be triggered.\nfunction needMoreData(state) {\n return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);\n}\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n};\n\n// backwards compatibility.\nReadable.prototype.setEncoding = function (enc) {\n if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;\n this._readableState.decoder = new StringDecoder(enc);\n this._readableState.encoding = enc;\n return this;\n};\n\n// Don't raise the hwm > 8MB\nvar MAX_HWM = 0x800000;\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n return n;\n}\n\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n }\n // If we're asking for more than the current hwm, then raise the hwm.\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n;\n // Don't have enough\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n return state.length;\n}\n\n// you can override either this method, or the async _read(n) below.\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n\n if (n !== 0) state.emittedReadable = false;\n\n // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state);\n\n // if we've ended, and we're now clear, then finish it up.\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n }\n\n // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n\n // if we need a readable event, then we need to do some reading.\n var doRead = state.needReadable;\n debug('need readable', doRead);\n\n // if we currently have less than the highWaterMark, then also read some\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n }\n\n // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true;\n // if the length is currently zero, then we *need* a readable event.\n if (state.length === 0) state.needReadable = true;\n // call internal read method\n this._read(state.highWaterMark);\n state.sync = false;\n // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = true;\n n = 0;\n } else {\n state.length -= n;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true;\n\n // If we tried to read() past the EOF, then emit end on the next tick.\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n\n return ret;\n};\n\nfunction onEofChunk(stream, state) {\n if (state.ended) return;\n if (state.decoder) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n state.ended = true;\n\n // emit 'readable' now to make sure it gets picked up.\n emitReadable(stream);\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n var state = stream._readableState;\n state.needReadable = false;\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);\n }\n}\n\nfunction emitReadable_(stream) {\n debug('emit readable');\n stream.emit('readable');\n flow(stream);\n}\n\n// at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n pna.nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n var len = state.length;\n while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length)\n // didn't get any data, stop spinning.\n break;else len = state.length;\n }\n state.readingMore = false;\n}\n\n// abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function (n) {\n this.emit('error', new Error('_read() is not implemented'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n default:\n state.pipes.push(dest);\n break;\n }\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n\n var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;\n\n var endFn = doEnd ? onend : unpipe;\n if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);\n\n dest.on('unpipe', onunpipe);\n function onunpipe(readable, unpipeInfo) {\n debug('onunpipe');\n if (readable === src) {\n if (unpipeInfo && unpipeInfo.hasUnpiped === false) {\n unpipeInfo.hasUnpiped = true;\n cleanup();\n }\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n }\n\n // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n\n var cleanedUp = false;\n function cleanup() {\n debug('cleanup');\n // cleanup event handlers once the pipe is broken\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', unpipe);\n src.removeListener('data', ondata);\n\n cleanedUp = true;\n\n // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n // If the user pushes more data while we're writing to dest then we'll end up\n // in ondata again. However, we only want to increase awaitDrain once because\n // dest will only emit one 'drain' event for the multiple writes.\n // => Introduce a guard on increasing awaitDrain.\n var increasedAwaitDrain = false;\n src.on('data', ondata);\n function ondata(chunk) {\n debug('ondata');\n increasedAwaitDrain = false;\n var ret = dest.write(chunk);\n if (false === ret && !increasedAwaitDrain) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', src._readableState.awaitDrain);\n src._readableState.awaitDrain++;\n increasedAwaitDrain = true;\n }\n src.pause();\n }\n }\n\n // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);\n }\n\n // Make sure our error handler is attached before userland ones.\n prependListener(dest, 'error', onerror);\n\n // Both close and finish should trigger unpipe, but only once.\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n dest.once('close', onclose);\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n }\n\n // tell the dest that it's being piped to\n dest.emit('pipe', src);\n\n // start the flow if it hasn't been started already.\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function () {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n var unpipeInfo = { hasUnpiped: false };\n\n // if we're not piping anywhere, then do nothing.\n if (state.pipesCount === 0) return this;\n\n // just one destination. most common case.\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n\n if (!dest) dest = state.pipes;\n\n // got a match.\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this, unpipeInfo);\n return this;\n }\n\n // slow case. multiple pipe destinations.\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var i = 0; i < len; i++) {\n dests[i].emit('unpipe', this, unpipeInfo);\n }return this;\n }\n\n // try to find the right one.\n var index = indexOf(state.pipes, dest);\n if (index === -1) return this;\n\n state.pipes.splice(index, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n\n dest.emit('unpipe', this, unpipeInfo);\n\n return this;\n};\n\n// set up data events if they are asked for\n// Ensure readable listeners eventually get something\nReadable.prototype.on = function (ev, fn) {\n var res = Stream.prototype.on.call(this, ev, fn);\n\n if (ev === 'data') {\n // Start flowing on next tick if stream isn't explicitly paused\n if (this._readableState.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n var state = this._readableState;\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.emittedReadable = false;\n if (!state.reading) {\n pna.nextTick(nReadingNextTick, this);\n } else if (state.length) {\n emitReadable(this);\n }\n }\n }\n\n return res;\n};\nReadable.prototype.addListener = Readable.prototype.on;\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n}\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function () {\n var state = this._readableState;\n if (!state.flowing) {\n debug('resume');\n state.flowing = true;\n resume(this, state);\n }\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n pna.nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n if (!state.reading) {\n debug('resume read 0');\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n state.awaitDrain = 0;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n if (false !== this._readableState.flowing) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n while (state.flowing && stream.read() !== null) {}\n}\n\n// wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function (stream) {\n var _this = this;\n\n var state = this._readableState;\n var paused = false;\n\n stream.on('end', function () {\n debug('wrapped end');\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) _this.push(chunk);\n }\n\n _this.push(null);\n });\n\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk);\n\n // don't skip over falsy values in objectMode\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = _this.push(chunk);\n if (!ret) {\n paused = true;\n stream.pause();\n }\n });\n\n // proxy all the other methods.\n // important when wrapping filters and duplexes.\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function (method) {\n return function () {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n }\n\n // proxy certain important events.\n for (var n = 0; n < kProxyEvents.length; n++) {\n stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));\n }\n\n // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n this._read = function (n) {\n debug('wrapped _read', n);\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return this;\n};\n\nObject.defineProperty(Readable.prototype, 'readableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._readableState.highWaterMark;\n }\n});\n\n// exposed for testing purposes only.\nReadable._fromList = fromList;\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n 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);\n state.buffer.clear();\n } else {\n // read part of list\n ret = fromListPartial(n, state.buffer, state.decoder);\n }\n\n return ret;\n}\n\n// Extracts only enough buffered data to satisfy the amount requested.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromListPartial(n, list, hasStrings) {\n var ret;\n if (n < list.head.data.length) {\n // slice is the same for buffers and strings\n ret = list.head.data.slice(0, n);\n list.head.data = list.head.data.slice(n);\n } else if (n === list.head.data.length) {\n // first chunk is a perfect match\n ret = list.shift();\n } else {\n // result spans more than one buffer\n ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);\n }\n return ret;\n}\n\n// Copies a specified amount of characters from the list of buffered data\n// chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBufferString(n, list) {\n var p = list.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = str.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\n// Copies a specified amount of bytes from the list of buffered data chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n\n // If we get here before consuming all the bytes, then that is a\n // bug in node. Should never happen.\n if (state.length > 0) throw new Error('\"endReadable()\" called on non-empty stream');\n\n if (!state.endEmitted) {\n state.ended = true;\n pna.nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n // Check that we didn't get one last unshift.\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n }\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n return -1;\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\n'use strict';\n\nmodule.exports = Transform;\n\nvar Duplex = require('./_stream_duplex');\n\n/**/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/**/\n\nutil.inherits(Transform, Duplex);\n\nfunction afterTransform(er, data) {\n var ts = this._transformState;\n ts.transforming = false;\n\n var cb = ts.writecb;\n\n if (!cb) {\n return this.emit('error', new Error('write callback called multiple times'));\n }\n\n ts.writechunk = null;\n ts.writecb = null;\n\n if (data != null) // single equals check for both `null` and `undefined`\n this.push(data);\n\n cb(er);\n\n var rs = this._readableState;\n rs.reading = false;\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n this._read(rs.highWaterMark);\n }\n}\n\nfunction Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n\n Duplex.call(this, options);\n\n this._transformState = {\n afterTransform: afterTransform.bind(this),\n needTransform: false,\n transforming: false,\n writecb: null,\n writechunk: null,\n writeencoding: null\n };\n\n // start out asking for a readable event once data is transformed.\n this._readableState.needReadable = true;\n\n // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n\n if (typeof options.flush === 'function') this._flush = options.flush;\n }\n\n // When the writable side finishes, then flush out anything remaining.\n this.on('prefinish', prefinish);\n}\n\nfunction prefinish() {\n var _this = this;\n\n if (typeof this._flush === 'function') {\n this._flush(function (er, data) {\n done(_this, er, data);\n });\n } else {\n done(this, null, null);\n }\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n};\n\n// This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\nTransform.prototype._transform = function (chunk, encoding, cb) {\n throw new Error('_transform() is not implemented');\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n};\n\n// Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && ts.writecb && !ts.transforming) {\n ts.transforming = true;\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nTransform.prototype._destroy = function (err, cb) {\n var _this2 = this;\n\n Duplex.prototype._destroy.call(this, err, function (err2) {\n cb(err2);\n _this2.emit('close');\n });\n};\n\nfunction done(stream, er, data) {\n if (er) return stream.emit('error', er);\n\n if (data != null) // single equals check for both `null` and `undefined`\n stream.push(data);\n\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');\n\n if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');\n\n return stream.push(null);\n}","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n'use strict';\n\n/**/\n\nvar pna = require('process-nextick-args');\n/**/\n\nmodule.exports = Writable;\n\n/* */\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n}\n\n// It seems a linked list but it is not\n// there will be only 2 of these for each stream\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n this.finish = function () {\n onCorkedFinish(_this, state);\n };\n}\n/* */\n\n/**/\nvar asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;\n/**/\n\n/**/\nvar Duplex;\n/**/\n\nWritable.WritableState = WritableState;\n\n/**/\nvar util = Object.create(require('core-util-is'));\nutil.inherits = require('inherits');\n/**/\n\n/**/\nvar internalUtil = {\n deprecate: require('util-deprecate')\n};\n/**/\n\n/**/\nvar Stream = require('./internal/streams/stream');\n/**/\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\nvar OurUint8Array = global.Uint8Array || function () {};\nfunction _uint8ArrayToBuffer(chunk) {\n return Buffer.from(chunk);\n}\nfunction _isUint8Array(obj) {\n return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;\n}\n\n/**/\n\nvar destroyImpl = require('./internal/streams/destroy');\n\nutil.inherits(Writable, Stream);\n\nfunction nop() {}\n\nfunction WritableState(options, stream) {\n Duplex = Duplex || require('./_stream_duplex');\n\n options = options || {};\n\n // Duplex streams are both readable and writable, but share\n // the same options object.\n // However, some cases require setting options to different\n // values for the readable and the writable sides of the duplex stream.\n // These options can be provided separately as readableXXX and writableXXX.\n var isDuplex = stream instanceof Duplex;\n\n // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n this.objectMode = !!options.objectMode;\n\n if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;\n\n // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n var hwm = options.highWaterMark;\n var writableHwm = options.writableHighWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n\n if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;\n\n // cast to ints.\n this.highWaterMark = Math.floor(this.highWaterMark);\n\n // if _final has been called\n this.finalCalled = false;\n\n // drain event flag.\n this.needDrain = false;\n // at the start of calling end()\n this.ending = false;\n // when end() has been called, and returned\n this.ended = false;\n // when 'finish' is emitted\n this.finished = false;\n\n // has it been destroyed\n this.destroyed = false;\n\n // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n this.length = 0;\n\n // a flag to see when we're in the middle of a write.\n this.writing = false;\n\n // when true all writes will be buffered until .uncork() call\n this.corked = 0;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n this.bufferProcessing = false;\n\n // the callback that's passed to _write(chunk,cb)\n this.onwrite = function (er) {\n onwrite(stream, er);\n };\n\n // the callback that the user supplies to write(chunk,encoding,cb)\n this.writecb = null;\n\n // the amount that is being written when _write is called.\n this.writelen = 0;\n\n this.bufferedRequest = null;\n this.lastBufferedRequest = null;\n\n // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n this.pendingcb = 0;\n\n // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n this.prefinished = false;\n\n // True if the error was already emitted and should not be thrown again\n this.errorEmitted = false;\n\n // count buffered requests\n this.bufferedRequestCount = 0;\n\n // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function getBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n while (current) {\n out.push(current);\n current = current.next;\n }\n return out;\n};\n\n(function () {\n try {\n Object.defineProperty(WritableState.prototype, 'buffer', {\n get: internalUtil.deprecate(function () {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')\n });\n } catch (_) {}\n})();\n\n// Test _writableState for inheritance to account for Duplex streams,\n// whose prototype chain only points to Readable.\nvar realHasInstance;\nif (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {\n realHasInstance = Function.prototype[Symbol.hasInstance];\n Object.defineProperty(Writable, Symbol.hasInstance, {\n value: function (object) {\n if (realHasInstance.call(this, object)) return true;\n if (this !== Writable) return false;\n\n return object && object._writableState instanceof WritableState;\n }\n });\n} else {\n realHasInstance = function (object) {\n return object instanceof this;\n };\n}\n\nfunction Writable(options) {\n Duplex = Duplex || require('./_stream_duplex');\n\n // Writable ctor is applied to Duplexes, too.\n // `realHasInstance` is necessary because using plain `instanceof`\n // would return false, as no `_writableState` property is attached.\n\n // Trying to use the custom `instanceof` for Writable here will also break the\n // Node.js LazyTransform implementation, which has a non-trivial getter for\n // `_writableState` that would lead to infinite recursion.\n if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {\n return new Writable(options);\n }\n\n this._writableState = new WritableState(options, this);\n\n // legacy.\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n\n if (typeof options.writev === 'function') this._writev = options.writev;\n\n if (typeof options.destroy === 'function') this._destroy = options.destroy;\n\n if (typeof options.final === 'function') this._final = options.final;\n }\n\n Stream.call(this);\n}\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n this.emit('error', new Error('Cannot pipe, not readable'));\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new Error('write after end');\n // TODO: defer error events consistently everywhere, not just the cb\n stream.emit('error', er);\n pna.nextTick(cb, er);\n}\n\n// Checks that a user-supplied chunk is valid, especially for the particular\n// mode the stream is in. Currently this means that `null` is never accepted\n// and undefined/non-string values are only allowed in object mode.\nfunction validChunk(stream, state, chunk, cb) {\n var valid = true;\n var er = false;\n\n if (chunk === null) {\n er = new TypeError('May not write null values to stream');\n } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n if (er) {\n stream.emit('error', er);\n pna.nextTick(cb, er);\n valid = false;\n }\n return valid;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n var isBuf = !state.objectMode && _isUint8Array(chunk);\n\n if (isBuf && !Buffer.isBuffer(chunk)) {\n chunk = _uint8ArrayToBuffer(chunk);\n }\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n\n if (typeof cb !== 'function') cb = nop;\n\n if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);\n }\n\n return ret;\n};\n\nWritable.prototype.cork = function () {\n var state = this._writableState;\n\n state.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n\n if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n 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);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n return chunk;\n}\n\nObject.defineProperty(Writable.prototype, 'writableHighWaterMark', {\n // making it explicit this property is not enumerable\n // because otherwise some prototype manipulation in\n // userland will fail\n enumerable: false,\n get: function () {\n return this._writableState.highWaterMark;\n }\n});\n\n// if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {\n if (!isBuf) {\n var newChunk = decodeChunk(state, chunk, encoding);\n if (chunk !== newChunk) {\n isBuf = true;\n encoding = 'buffer';\n chunk = newChunk;\n }\n }\n var len = state.objectMode ? 1 : chunk.length;\n\n state.length += len;\n\n var ret = state.length < state.highWaterMark;\n // we must ensure that previous needDrain will not be reset to false.\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = {\n chunk: chunk,\n encoding: encoding,\n isBuf: isBuf,\n callback: cb,\n next: null\n };\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n\n if (sync) {\n // defer the callback if we are being called synchronously\n // to avoid piling up things on the stack\n pna.nextTick(cb, er);\n // this can emit finish, and it will always happen\n // after error\n pna.nextTick(finishMaybe, stream, state);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n } else {\n // the caller expect this to happen before if\n // it is async\n cb(er);\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n // this can emit finish, but finish must\n // always follow error\n finishMaybe(stream, state);\n }\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n\n onwriteStateUpdate(state);\n\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state);\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n /**/\n asyncWrite(afterWrite, stream, state, finished, cb);\n /**/\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n}\n\n// Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n}\n\n// if there's something in the buffer waiting, then process it\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n\n var count = 0;\n var allBuffers = true;\n while (entry) {\n buffer[count] = entry;\n if (!entry.isBuf) allBuffers = false;\n entry = entry.next;\n count += 1;\n }\n buffer.allBuffers = allBuffers;\n\n doWrite(stream, state, true, state.length, buffer, '', holder.finish);\n\n // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n state.pendingcb++;\n state.lastBufferedRequest = null;\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n state.bufferedRequestCount = 0;\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n state.bufferedRequestCount--;\n // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new Error('_write() is not implemented'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);\n\n // .end() fully uncorks\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n }\n\n // ignore unnecessary end() calls.\n if (!state.ending && !state.finished) endWritable(this, state, cb);\n};\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\nfunction callFinal(stream, state) {\n stream._final(function (err) {\n state.pendingcb--;\n if (err) {\n stream.emit('error', err);\n }\n state.prefinished = true;\n stream.emit('prefinish');\n finishMaybe(stream, state);\n });\n}\nfunction prefinish(stream, state) {\n if (!state.prefinished && !state.finalCalled) {\n if (typeof stream._final === 'function') {\n state.pendingcb++;\n state.finalCalled = true;\n pna.nextTick(callFinal, stream, state);\n } else {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n if (need) {\n prefinish(stream, state);\n if (state.pendingcb === 0) {\n state.finished = true;\n stream.emit('finish');\n }\n }\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n if (cb) {\n if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);\n }\n state.ended = true;\n stream.writable = false;\n}\n\nfunction onCorkedFinish(corkReq, state, err) {\n var entry = corkReq.entry;\n corkReq.entry = null;\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n }\n if (state.corkedRequestsFree) {\n state.corkedRequestsFree.next = corkReq;\n } else {\n state.corkedRequestsFree = corkReq;\n }\n}\n\nObject.defineProperty(Writable.prototype, 'destroyed', {\n get: function () {\n if (this._writableState === undefined) {\n return false;\n }\n return this._writableState.destroyed;\n },\n set: function (value) {\n // we ignore the value if the stream\n // has not been initialized yet\n if (!this._writableState) {\n return;\n }\n\n // backward compatibility, the user is explicitly\n // managing destroyed\n this._writableState.destroyed = value;\n }\n});\n\nWritable.prototype.destroy = destroyImpl.destroy;\nWritable.prototype._undestroy = destroyImpl.undestroy;\nWritable.prototype._destroy = function (err, cb) {\n this.end();\n cb(err);\n};","'use strict';\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar Buffer = require('safe-buffer').Buffer;\nvar util = require('util');\n\nfunction copyBuffer(src, target, offset) {\n src.copy(target, offset);\n}\n\nmodule.exports = function () {\n function BufferList() {\n _classCallCheck(this, BufferList);\n\n this.head = null;\n this.tail = null;\n this.length = 0;\n }\n\n BufferList.prototype.push = function push(v) {\n var entry = { data: v, next: null };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n };\n\n BufferList.prototype.unshift = function unshift(v) {\n var entry = { data: v, next: this.head };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n };\n\n BufferList.prototype.shift = function shift() {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n };\n\n BufferList.prototype.clear = function clear() {\n this.head = this.tail = null;\n this.length = 0;\n };\n\n BufferList.prototype.join = function join(s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n while (p = p.next) {\n ret += s + p.data;\n }return ret;\n };\n\n BufferList.prototype.concat = function concat(n) {\n if (this.length === 0) return Buffer.alloc(0);\n if (this.length === 1) return this.head.data;\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n while (p) {\n copyBuffer(p.data, ret, i);\n i += p.data.length;\n p = p.next;\n }\n return ret;\n };\n\n return BufferList;\n}();\n\nif (util && util.inspect && util.inspect.custom) {\n module.exports.prototype[util.inspect.custom] = function () {\n var obj = util.inspect({ length: this.length });\n return this.constructor.name + ' ' + obj;\n };\n}","'use strict';\n\n/**/\n\nvar pna = require('process-nextick-args');\n/**/\n\n// undocumented cb() API, needed for core, not for public API\nfunction destroy(err, cb) {\n var _this = this;\n\n var readableDestroyed = this._readableState && this._readableState.destroyed;\n var writableDestroyed = this._writableState && this._writableState.destroyed;\n\n if (readableDestroyed || writableDestroyed) {\n if (cb) {\n cb(err);\n } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {\n pna.nextTick(emitErrorNT, this, err);\n }\n return this;\n }\n\n // we set destroyed to true before firing error callbacks in order\n // to make it re-entrance safe in case destroy() is called within callbacks\n\n if (this._readableState) {\n this._readableState.destroyed = true;\n }\n\n // if this is a duplex stream mark the writable part as destroyed as well\n if (this._writableState) {\n this._writableState.destroyed = true;\n }\n\n this._destroy(err || null, function (err) {\n if (!cb && err) {\n pna.nextTick(emitErrorNT, _this, err);\n if (_this._writableState) {\n _this._writableState.errorEmitted = true;\n }\n } else if (cb) {\n cb(err);\n }\n });\n\n return this;\n}\n\nfunction undestroy() {\n if (this._readableState) {\n this._readableState.destroyed = false;\n this._readableState.reading = false;\n this._readableState.ended = false;\n this._readableState.endEmitted = false;\n }\n\n if (this._writableState) {\n this._writableState.destroyed = false;\n this._writableState.ended = false;\n this._writableState.ending = false;\n this._writableState.finished = false;\n this._writableState.errorEmitted = false;\n }\n}\n\nfunction emitErrorNT(self, err) {\n self.emit('error', err);\n}\n\nmodule.exports = {\n destroy: destroy,\n undestroy: undestroy\n};","module.exports = require('stream');\n","var Stream = require('stream');\nif (process.env.READABLE_STREAM === 'disable' && Stream) {\n module.exports = Stream;\n exports = module.exports = Stream.Readable;\n exports.Readable = Stream.Readable;\n exports.Writable = Stream.Writable;\n exports.Duplex = Stream.Duplex;\n exports.Transform = Stream.Transform;\n exports.PassThrough = Stream.PassThrough;\n exports.Stream = Stream;\n} else {\n exports = module.exports = require('./lib/_stream_readable.js');\n exports.Stream = Stream || exports;\n exports.Readable = exports;\n exports.Writable = require('./lib/_stream_writable.js');\n exports.Duplex = require('./lib/_stream_duplex.js');\n exports.Transform = require('./lib/_stream_transform.js');\n exports.PassThrough = require('./lib/_stream_passthrough.js');\n}\n","/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\n/**/\n\nvar Buffer = require('safe-buffer').Buffer;\n/**/\n\nvar isEncoding = Buffer.isEncoding || function (encoding) {\n encoding = '' + encoding;\n switch (encoding && encoding.toLowerCase()) {\n 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':\n return true;\n default:\n return false;\n }\n};\n\nfunction _normalizeEncoding(enc) {\n if (!enc) return 'utf8';\n var retried;\n while (true) {\n switch (enc) {\n case 'utf8':\n case 'utf-8':\n return 'utf8';\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return 'utf16le';\n case 'latin1':\n case 'binary':\n return 'latin1';\n case 'base64':\n case 'ascii':\n case 'hex':\n return enc;\n default:\n if (retried) return; // undefined\n enc = ('' + enc).toLowerCase();\n retried = true;\n }\n }\n};\n\n// Do not cache `Buffer.isEncoding` when checking encoding names as some\n// modules monkey-patch it to support additional encodings\nfunction normalizeEncoding(enc) {\n var nenc = _normalizeEncoding(enc);\n if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);\n return nenc || enc;\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters.\nexports.StringDecoder = StringDecoder;\nfunction StringDecoder(encoding) {\n this.encoding = normalizeEncoding(encoding);\n var nb;\n switch (this.encoding) {\n case 'utf16le':\n this.text = utf16Text;\n this.end = utf16End;\n nb = 4;\n break;\n case 'utf8':\n this.fillLast = utf8FillLast;\n nb = 4;\n break;\n case 'base64':\n this.text = base64Text;\n this.end = base64End;\n nb = 3;\n break;\n default:\n this.write = simpleWrite;\n this.end = simpleEnd;\n return;\n }\n this.lastNeed = 0;\n this.lastTotal = 0;\n this.lastChar = Buffer.allocUnsafe(nb);\n}\n\nStringDecoder.prototype.write = function (buf) {\n if (buf.length === 0) return '';\n var r;\n var i;\n if (this.lastNeed) {\n r = this.fillLast(buf);\n if (r === undefined) return '';\n i = this.lastNeed;\n this.lastNeed = 0;\n } else {\n i = 0;\n }\n if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);\n return r || '';\n};\n\nStringDecoder.prototype.end = utf8End;\n\n// Returns only complete characters in a Buffer\nStringDecoder.prototype.text = utf8Text;\n\n// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer\nStringDecoder.prototype.fillLast = function (buf) {\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);\n this.lastNeed -= buf.length;\n};\n\n// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a\n// continuation byte. If an invalid byte is detected, -2 is returned.\nfunction utf8CheckByte(byte) {\n 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;\n return byte >> 6 === 0x02 ? -1 : -2;\n}\n\n// Checks at most 3 bytes at the end of a Buffer in order to detect an\n// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)\n// needed to complete the UTF-8 character (if applicable) are returned.\nfunction utf8CheckIncomplete(self, buf, i) {\n var j = buf.length - 1;\n if (j < i) return 0;\n var nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 1;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) self.lastNeed = nb - 2;\n return nb;\n }\n if (--j < i || nb === -2) return 0;\n nb = utf8CheckByte(buf[j]);\n if (nb >= 0) {\n if (nb > 0) {\n if (nb === 2) nb = 0;else self.lastNeed = nb - 3;\n }\n return nb;\n }\n return 0;\n}\n\n// Validates as many continuation bytes for a multi-byte UTF-8 character as\n// needed or are available. If we see a non-continuation byte where we expect\n// one, we \"replace\" the validated continuation bytes we've seen so far with\n// a single UTF-8 replacement character ('\\ufffd'), to match v8's UTF-8 decoding\n// behavior. The continuation byte check is included three times in the case\n// where all of the continuation bytes for a character exist in the same buffer.\n// It is also done this way as a slight performance increase instead of using a\n// loop.\nfunction utf8CheckExtraBytes(self, buf, p) {\n if ((buf[0] & 0xC0) !== 0x80) {\n self.lastNeed = 0;\n return '\\ufffd';\n }\n if (self.lastNeed > 1 && buf.length > 1) {\n if ((buf[1] & 0xC0) !== 0x80) {\n self.lastNeed = 1;\n return '\\ufffd';\n }\n if (self.lastNeed > 2 && buf.length > 2) {\n if ((buf[2] & 0xC0) !== 0x80) {\n self.lastNeed = 2;\n return '\\ufffd';\n }\n }\n }\n}\n\n// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.\nfunction utf8FillLast(buf) {\n var p = this.lastTotal - this.lastNeed;\n var r = utf8CheckExtraBytes(this, buf, p);\n if (r !== undefined) return r;\n if (this.lastNeed <= buf.length) {\n buf.copy(this.lastChar, p, 0, this.lastNeed);\n return this.lastChar.toString(this.encoding, 0, this.lastTotal);\n }\n buf.copy(this.lastChar, p, 0, buf.length);\n this.lastNeed -= buf.length;\n}\n\n// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a\n// partial character, the character's bytes are buffered until the required\n// number of bytes are available.\nfunction utf8Text(buf, i) {\n var total = utf8CheckIncomplete(this, buf, i);\n if (!this.lastNeed) return buf.toString('utf8', i);\n this.lastTotal = total;\n var end = buf.length - (total - this.lastNeed);\n buf.copy(this.lastChar, 0, end);\n return buf.toString('utf8', i, end);\n}\n\n// For UTF-8, a replacement character is added when ending on a partial\n// character.\nfunction utf8End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + '\\ufffd';\n return r;\n}\n\n// UTF-16LE typically needs two bytes per character, but even if we have an even\n// number of bytes available, we need to check if we end on a leading/high\n// surrogate. In that case, we need to wait for the next two bytes in order to\n// decode the last character properly.\nfunction utf16Text(buf, i) {\n if ((buf.length - i) % 2 === 0) {\n var r = buf.toString('utf16le', i);\n if (r) {\n var c = r.charCodeAt(r.length - 1);\n if (c >= 0xD800 && c <= 0xDBFF) {\n this.lastNeed = 2;\n this.lastTotal = 4;\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n return r.slice(0, -1);\n }\n }\n return r;\n }\n this.lastNeed = 1;\n this.lastTotal = 2;\n this.lastChar[0] = buf[buf.length - 1];\n return buf.toString('utf16le', i, buf.length - 1);\n}\n\n// For UTF-16LE we do not explicitly append special replacement characters if we\n// end on a partial character, we simply let v8 handle that.\nfunction utf16End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) {\n var end = this.lastTotal - this.lastNeed;\n return r + this.lastChar.toString('utf16le', 0, end);\n }\n return r;\n}\n\nfunction base64Text(buf, i) {\n var n = (buf.length - i) % 3;\n if (n === 0) return buf.toString('base64', i);\n this.lastNeed = 3 - n;\n this.lastTotal = 3;\n if (n === 1) {\n this.lastChar[0] = buf[buf.length - 1];\n } else {\n this.lastChar[0] = buf[buf.length - 2];\n this.lastChar[1] = buf[buf.length - 1];\n }\n return buf.toString('base64', i, buf.length - n);\n}\n\nfunction base64End(buf) {\n var r = buf && buf.length ? this.write(buf) : '';\n if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);\n return r;\n}\n\n// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)\nfunction simpleWrite(buf) {\n return buf.toString(this.encoding);\n}\n\nfunction simpleEnd(buf) {\n return buf && buf.length ? this.write(buf) : '';\n}","'use strict'\nvar EventEmitter = require('events').EventEmitter\nvar util = require('util')\n\nvar trackerId = 0\nvar TrackerBase = module.exports = function (name) {\n EventEmitter.call(this)\n this.id = ++trackerId\n this.name = name\n}\nutil.inherits(TrackerBase, EventEmitter)\n","'use strict'\nvar util = require('util')\nvar TrackerBase = require('./tracker-base.js')\nvar Tracker = require('./tracker.js')\nvar TrackerStream = require('./tracker-stream.js')\n\nvar TrackerGroup = module.exports = function (name) {\n TrackerBase.call(this, name)\n this.parentGroup = null\n this.trackers = []\n this.completion = {}\n this.weight = {}\n this.totalWeight = 0\n this.finished = false\n this.bubbleChange = bubbleChange(this)\n}\nutil.inherits(TrackerGroup, TrackerBase)\n\nfunction bubbleChange (trackerGroup) {\n return function (name, completed, tracker) {\n trackerGroup.completion[tracker.id] = completed\n if (trackerGroup.finished) return\n trackerGroup.emit('change', name || trackerGroup.name, trackerGroup.completed(), trackerGroup)\n }\n}\n\nTrackerGroup.prototype.nameInTree = function () {\n var names = []\n var from = this\n while (from) {\n names.unshift(from.name)\n from = from.parentGroup\n }\n return names.join('/')\n}\n\nTrackerGroup.prototype.addUnit = function (unit, weight) {\n if (unit.addUnit) {\n var toTest = this\n while (toTest) {\n if (unit === toTest) {\n throw new Error(\n 'Attempted to add tracker group ' +\n unit.name + ' to tree that already includes it ' +\n this.nameInTree(this))\n }\n toTest = toTest.parentGroup\n }\n unit.parentGroup = this\n }\n this.weight[unit.id] = weight || 1\n this.totalWeight += this.weight[unit.id]\n this.trackers.push(unit)\n this.completion[unit.id] = unit.completed()\n unit.on('change', this.bubbleChange)\n if (!this.finished) this.emit('change', unit.name, this.completion[unit.id], unit)\n return unit\n}\n\nTrackerGroup.prototype.completed = function () {\n if (this.trackers.length === 0) return 0\n var valPerWeight = 1 / this.totalWeight\n var completed = 0\n for (var ii = 0; ii < this.trackers.length; ii++) {\n var trackerId = this.trackers[ii].id\n completed += valPerWeight * this.weight[trackerId] * this.completion[trackerId]\n }\n return completed\n}\n\nTrackerGroup.prototype.newGroup = function (name, weight) {\n return this.addUnit(new TrackerGroup(name), weight)\n}\n\nTrackerGroup.prototype.newItem = function (name, todo, weight) {\n return this.addUnit(new Tracker(name, todo), weight)\n}\n\nTrackerGroup.prototype.newStream = function (name, todo, weight) {\n return this.addUnit(new TrackerStream(name, todo), weight)\n}\n\nTrackerGroup.prototype.finish = function () {\n this.finished = true\n if (!this.trackers.length) this.addUnit(new Tracker(), 1, true)\n for (var ii = 0; ii < this.trackers.length; ii++) {\n var tracker = this.trackers[ii]\n tracker.finish()\n tracker.removeListener('change', this.bubbleChange)\n }\n this.emit('change', this.name, 1, this)\n}\n\nvar buffer = ' '\nTrackerGroup.prototype.debug = function (depth) {\n depth = depth || 0\n var indent = depth ? buffer.substr(0, depth) : ''\n var output = indent + (this.name || 'top') + ': ' + this.completed() + '\\n'\n this.trackers.forEach(function (tracker) {\n if (tracker instanceof TrackerGroup) {\n output += tracker.debug(depth + 1)\n } else {\n output += indent + ' ' + tracker.name + ': ' + tracker.completed() + '\\n'\n }\n })\n return output\n}\n","'use strict'\nvar util = require('util')\nvar stream = require('readable-stream')\nvar delegate = require('delegates')\nvar Tracker = require('./tracker.js')\n\nvar TrackerStream = module.exports = function (name, size, options) {\n stream.Transform.call(this, options)\n this.tracker = new Tracker(name, size)\n this.name = name\n this.id = this.tracker.id\n this.tracker.on('change', delegateChange(this))\n}\nutil.inherits(TrackerStream, stream.Transform)\n\nfunction delegateChange (trackerStream) {\n return function (name, completion, tracker) {\n trackerStream.emit('change', name, completion, trackerStream)\n }\n}\n\nTrackerStream.prototype._transform = function (data, encoding, cb) {\n this.tracker.completeWork(data.length ? data.length : 1)\n this.push(data)\n cb()\n}\n\nTrackerStream.prototype._flush = function (cb) {\n this.tracker.finish()\n cb()\n}\n\ndelegate(TrackerStream.prototype, 'tracker')\n .method('completed')\n .method('addWork')\n .method('finish')\n","'use strict'\nvar util = require('util')\nvar TrackerBase = require('./tracker-base.js')\n\nvar Tracker = module.exports = function (name, todo) {\n TrackerBase.call(this, name)\n this.workDone = 0\n this.workTodo = todo || 0\n}\nutil.inherits(Tracker, TrackerBase)\n\nTracker.prototype.completed = function () {\n return this.workTodo === 0 ? 0 : this.workDone / this.workTodo\n}\n\nTracker.prototype.addWork = function (work) {\n this.workTodo += work\n this.emit('change', this.name, this.completed(), this)\n}\n\nTracker.prototype.completeWork = function (work) {\n this.workDone += work\n if (this.workDone > this.workTodo) this.workDone = this.workTodo\n this.emit('change', this.name, this.completed(), this)\n}\n\nTracker.prototype.finish = function () {\n this.workTodo = this.workDone = 1\n this.emit('change', this.name, 1, this)\n}\n","// Copyright 2011 Mark Cavage All rights reserved.\n\n\nmodule.exports = {\n\n newInvalidAsn1Error: function (msg) {\n var e = new Error();\n e.name = 'InvalidAsn1Error';\n e.message = msg || '';\n return e;\n }\n\n};\n","// Copyright 2011 Mark Cavage All rights reserved.\n\nvar errors = require('./errors');\nvar types = require('./types');\n\nvar Reader = require('./reader');\nvar Writer = require('./writer');\n\n\n// --- Exports\n\nmodule.exports = {\n\n Reader: Reader,\n\n Writer: Writer\n\n};\n\nfor (var t in types) {\n if (types.hasOwnProperty(t))\n module.exports[t] = types[t];\n}\nfor (var e in errors) {\n if (errors.hasOwnProperty(e))\n module.exports[e] = errors[e];\n}\n","// Copyright 2011 Mark Cavage All rights reserved.\n\nvar assert = require('assert');\nvar Buffer = require('safer-buffer').Buffer;\n\nvar ASN1 = require('./types');\nvar errors = require('./errors');\n\n\n// --- Globals\n\nvar newInvalidAsn1Error = errors.newInvalidAsn1Error;\n\n\n\n// --- API\n\nfunction Reader(data) {\n if (!data || !Buffer.isBuffer(data))\n throw new TypeError('data must be a node Buffer');\n\n this._buf = data;\n this._size = data.length;\n\n // These hold the \"current\" state\n this._len = 0;\n this._offset = 0;\n}\n\nObject.defineProperty(Reader.prototype, 'length', {\n enumerable: true,\n get: function () { return (this._len); }\n});\n\nObject.defineProperty(Reader.prototype, 'offset', {\n enumerable: true,\n get: function () { return (this._offset); }\n});\n\nObject.defineProperty(Reader.prototype, 'remain', {\n get: function () { return (this._size - this._offset); }\n});\n\nObject.defineProperty(Reader.prototype, 'buffer', {\n get: function () { return (this._buf.slice(this._offset)); }\n});\n\n\n/**\n * Reads a single byte and advances offset; you can pass in `true` to make this\n * a \"peek\" operation (i.e., get the byte, but don't advance the offset).\n *\n * @param {Boolean} peek true means don't move offset.\n * @return {Number} the next byte, null if not enough data.\n */\nReader.prototype.readByte = function (peek) {\n if (this._size - this._offset < 1)\n return null;\n\n var b = this._buf[this._offset] & 0xff;\n\n if (!peek)\n this._offset += 1;\n\n return b;\n};\n\n\nReader.prototype.peek = function () {\n return this.readByte(true);\n};\n\n\n/**\n * Reads a (potentially) variable length off the BER buffer. This call is\n * not really meant to be called directly, as callers have to manipulate\n * the internal buffer afterwards.\n *\n * As a result of this call, you can call `Reader.length`, until the\n * next thing called that does a readLength.\n *\n * @return {Number} the amount of offset to advance the buffer.\n * @throws {InvalidAsn1Error} on bad ASN.1\n */\nReader.prototype.readLength = function (offset) {\n if (offset === undefined)\n offset = this._offset;\n\n if (offset >= this._size)\n return null;\n\n var lenB = this._buf[offset++] & 0xff;\n if (lenB === null)\n return null;\n\n if ((lenB & 0x80) === 0x80) {\n lenB &= 0x7f;\n\n if (lenB === 0)\n throw newInvalidAsn1Error('Indefinite length not supported');\n\n if (lenB > 4)\n throw newInvalidAsn1Error('encoding too long');\n\n if (this._size - offset < lenB)\n return null;\n\n this._len = 0;\n for (var i = 0; i < lenB; i++)\n this._len = (this._len << 8) + (this._buf[offset++] & 0xff);\n\n } else {\n // Wasn't a variable length\n this._len = lenB;\n }\n\n return offset;\n};\n\n\n/**\n * Parses the next sequence in this BER buffer.\n *\n * To get the length of the sequence, call `Reader.length`.\n *\n * @return {Number} the sequence's tag.\n */\nReader.prototype.readSequence = function (tag) {\n var seq = this.peek();\n if (seq === null)\n return null;\n if (tag !== undefined && tag !== seq)\n throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +\n ': got 0x' + seq.toString(16));\n\n var o = this.readLength(this._offset + 1); // stored in `length`\n if (o === null)\n return null;\n\n this._offset = o;\n return seq;\n};\n\n\nReader.prototype.readInt = function () {\n return this._readTag(ASN1.Integer);\n};\n\n\nReader.prototype.readBoolean = function () {\n return (this._readTag(ASN1.Boolean) === 0 ? false : true);\n};\n\n\nReader.prototype.readEnumeration = function () {\n return this._readTag(ASN1.Enumeration);\n};\n\n\nReader.prototype.readString = function (tag, retbuf) {\n if (!tag)\n tag = ASN1.OctetString;\n\n var b = this.peek();\n if (b === null)\n return null;\n\n if (b !== tag)\n throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +\n ': got 0x' + b.toString(16));\n\n var o = this.readLength(this._offset + 1); // stored in `length`\n\n if (o === null)\n return null;\n\n if (this.length > this._size - o)\n return null;\n\n this._offset = o;\n\n if (this.length === 0)\n return retbuf ? Buffer.alloc(0) : '';\n\n var str = this._buf.slice(this._offset, this._offset + this.length);\n this._offset += this.length;\n\n return retbuf ? str : str.toString('utf8');\n};\n\nReader.prototype.readOID = function (tag) {\n if (!tag)\n tag = ASN1.OID;\n\n var b = this.readString(tag, true);\n if (b === null)\n return null;\n\n var values = [];\n var value = 0;\n\n for (var i = 0; i < b.length; i++) {\n var byte = b[i] & 0xff;\n\n value <<= 7;\n value += byte & 0x7f;\n if ((byte & 0x80) === 0) {\n values.push(value);\n value = 0;\n }\n }\n\n value = values.shift();\n values.unshift(value % 40);\n values.unshift((value / 40) >> 0);\n\n return values.join('.');\n};\n\n\nReader.prototype._readTag = function (tag) {\n assert.ok(tag !== undefined);\n\n var b = this.peek();\n\n if (b === null)\n return null;\n\n if (b !== tag)\n throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +\n ': got 0x' + b.toString(16));\n\n var o = this.readLength(this._offset + 1); // stored in `length`\n if (o === null)\n return null;\n\n if (this.length > 4)\n throw newInvalidAsn1Error('Integer too long: ' + this.length);\n\n if (this.length > this._size - o)\n return null;\n this._offset = o;\n\n var fb = this._buf[this._offset];\n var value = 0;\n\n for (var i = 0; i < this.length; i++) {\n value <<= 8;\n value |= (this._buf[this._offset++] & 0xff);\n }\n\n if ((fb & 0x80) === 0x80 && i !== 4)\n value -= (1 << (i * 8));\n\n return value >> 0;\n};\n\n\n\n// --- Exported API\n\nmodule.exports = Reader;\n","// Copyright 2011 Mark Cavage All rights reserved.\n\n\nmodule.exports = {\n EOC: 0,\n Boolean: 1,\n Integer: 2,\n BitString: 3,\n OctetString: 4,\n Null: 5,\n OID: 6,\n ObjectDescriptor: 7,\n External: 8,\n Real: 9, // float\n Enumeration: 10,\n PDV: 11,\n Utf8String: 12,\n RelativeOID: 13,\n Sequence: 16,\n Set: 17,\n NumericString: 18,\n PrintableString: 19,\n T61String: 20,\n VideotexString: 21,\n IA5String: 22,\n UTCTime: 23,\n GeneralizedTime: 24,\n GraphicString: 25,\n VisibleString: 26,\n GeneralString: 28,\n UniversalString: 29,\n CharacterString: 30,\n BMPString: 31,\n Constructor: 32,\n Context: 128\n};\n","// Copyright 2011 Mark Cavage All rights reserved.\n\nvar assert = require('assert');\nvar Buffer = require('safer-buffer').Buffer;\nvar ASN1 = require('./types');\nvar errors = require('./errors');\n\n\n// --- Globals\n\nvar newInvalidAsn1Error = errors.newInvalidAsn1Error;\n\nvar DEFAULT_OPTS = {\n size: 1024,\n growthFactor: 8\n};\n\n\n// --- Helpers\n\nfunction merge(from, to) {\n assert.ok(from);\n assert.equal(typeof (from), 'object');\n assert.ok(to);\n assert.equal(typeof (to), 'object');\n\n var keys = Object.getOwnPropertyNames(from);\n keys.forEach(function (key) {\n if (to[key])\n return;\n\n var value = Object.getOwnPropertyDescriptor(from, key);\n Object.defineProperty(to, key, value);\n });\n\n return to;\n}\n\n\n\n// --- API\n\nfunction Writer(options) {\n options = merge(DEFAULT_OPTS, options || {});\n\n this._buf = Buffer.alloc(options.size || 1024);\n this._size = this._buf.length;\n this._offset = 0;\n this._options = options;\n\n // A list of offsets in the buffer where we need to insert\n // sequence tag/len pairs.\n this._seq = [];\n}\n\nObject.defineProperty(Writer.prototype, 'buffer', {\n get: function () {\n if (this._seq.length)\n throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)');\n\n return (this._buf.slice(0, this._offset));\n }\n});\n\nWriter.prototype.writeByte = function (b) {\n if (typeof (b) !== 'number')\n throw new TypeError('argument must be a Number');\n\n this._ensure(1);\n this._buf[this._offset++] = b;\n};\n\n\nWriter.prototype.writeInt = function (i, tag) {\n if (typeof (i) !== 'number')\n throw new TypeError('argument must be a Number');\n if (typeof (tag) !== 'number')\n tag = ASN1.Integer;\n\n var sz = 4;\n\n while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) &&\n (sz > 1)) {\n sz--;\n i <<= 8;\n }\n\n if (sz > 4)\n throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff');\n\n this._ensure(2 + sz);\n this._buf[this._offset++] = tag;\n this._buf[this._offset++] = sz;\n\n while (sz-- > 0) {\n this._buf[this._offset++] = ((i & 0xff000000) >>> 24);\n i <<= 8;\n }\n\n};\n\n\nWriter.prototype.writeNull = function () {\n this.writeByte(ASN1.Null);\n this.writeByte(0x00);\n};\n\n\nWriter.prototype.writeEnumeration = function (i, tag) {\n if (typeof (i) !== 'number')\n throw new TypeError('argument must be a Number');\n if (typeof (tag) !== 'number')\n tag = ASN1.Enumeration;\n\n return this.writeInt(i, tag);\n};\n\n\nWriter.prototype.writeBoolean = function (b, tag) {\n if (typeof (b) !== 'boolean')\n throw new TypeError('argument must be a Boolean');\n if (typeof (tag) !== 'number')\n tag = ASN1.Boolean;\n\n this._ensure(3);\n this._buf[this._offset++] = tag;\n this._buf[this._offset++] = 0x01;\n this._buf[this._offset++] = b ? 0xff : 0x00;\n};\n\n\nWriter.prototype.writeString = function (s, tag) {\n if (typeof (s) !== 'string')\n throw new TypeError('argument must be a string (was: ' + typeof (s) + ')');\n if (typeof (tag) !== 'number')\n tag = ASN1.OctetString;\n\n var len = Buffer.byteLength(s);\n this.writeByte(tag);\n this.writeLength(len);\n if (len) {\n this._ensure(len);\n this._buf.write(s, this._offset);\n this._offset += len;\n }\n};\n\n\nWriter.prototype.writeBuffer = function (buf, tag) {\n if (typeof (tag) !== 'number')\n throw new TypeError('tag must be a number');\n if (!Buffer.isBuffer(buf))\n throw new TypeError('argument must be a buffer');\n\n this.writeByte(tag);\n this.writeLength(buf.length);\n this._ensure(buf.length);\n buf.copy(this._buf, this._offset, 0, buf.length);\n this._offset += buf.length;\n};\n\n\nWriter.prototype.writeStringArray = function (strings) {\n if ((!strings instanceof Array))\n throw new TypeError('argument must be an Array[String]');\n\n var self = this;\n strings.forEach(function (s) {\n self.writeString(s);\n });\n};\n\n// This is really to solve DER cases, but whatever for now\nWriter.prototype.writeOID = function (s, tag) {\n if (typeof (s) !== 'string')\n throw new TypeError('argument must be a string');\n if (typeof (tag) !== 'number')\n tag = ASN1.OID;\n\n if (!/^([0-9]+\\.){3,}[0-9]+$/.test(s))\n throw new Error('argument is not a valid OID string');\n\n function encodeOctet(bytes, octet) {\n if (octet < 128) {\n bytes.push(octet);\n } else if (octet < 16384) {\n bytes.push((octet >>> 7) | 0x80);\n bytes.push(octet & 0x7F);\n } else if (octet < 2097152) {\n bytes.push((octet >>> 14) | 0x80);\n bytes.push(((octet >>> 7) | 0x80) & 0xFF);\n bytes.push(octet & 0x7F);\n } else if (octet < 268435456) {\n bytes.push((octet >>> 21) | 0x80);\n bytes.push(((octet >>> 14) | 0x80) & 0xFF);\n bytes.push(((octet >>> 7) | 0x80) & 0xFF);\n bytes.push(octet & 0x7F);\n } else {\n bytes.push(((octet >>> 28) | 0x80) & 0xFF);\n bytes.push(((octet >>> 21) | 0x80) & 0xFF);\n bytes.push(((octet >>> 14) | 0x80) & 0xFF);\n bytes.push(((octet >>> 7) | 0x80) & 0xFF);\n bytes.push(octet & 0x7F);\n }\n }\n\n var tmp = s.split('.');\n var bytes = [];\n bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10));\n tmp.slice(2).forEach(function (b) {\n encodeOctet(bytes, parseInt(b, 10));\n });\n\n var self = this;\n this._ensure(2 + bytes.length);\n this.writeByte(tag);\n this.writeLength(bytes.length);\n bytes.forEach(function (b) {\n self.writeByte(b);\n });\n};\n\n\nWriter.prototype.writeLength = function (len) {\n if (typeof (len) !== 'number')\n throw new TypeError('argument must be a Number');\n\n this._ensure(4);\n\n if (len <= 0x7f) {\n this._buf[this._offset++] = len;\n } else if (len <= 0xff) {\n this._buf[this._offset++] = 0x81;\n this._buf[this._offset++] = len;\n } else if (len <= 0xffff) {\n this._buf[this._offset++] = 0x82;\n this._buf[this._offset++] = len >> 8;\n this._buf[this._offset++] = len;\n } else if (len <= 0xffffff) {\n this._buf[this._offset++] = 0x83;\n this._buf[this._offset++] = len >> 16;\n this._buf[this._offset++] = len >> 8;\n this._buf[this._offset++] = len;\n } else {\n throw newInvalidAsn1Error('Length too long (> 4 bytes)');\n }\n};\n\nWriter.prototype.startSequence = function (tag) {\n if (typeof (tag) !== 'number')\n tag = ASN1.Sequence | ASN1.Constructor;\n\n this.writeByte(tag);\n this._seq.push(this._offset);\n this._ensure(3);\n this._offset += 3;\n};\n\n\nWriter.prototype.endSequence = function () {\n var seq = this._seq.pop();\n var start = seq + 3;\n var len = this._offset - start;\n\n if (len <= 0x7f) {\n this._shift(start, len, -2);\n this._buf[seq] = len;\n } else if (len <= 0xff) {\n this._shift(start, len, -1);\n this._buf[seq] = 0x81;\n this._buf[seq + 1] = len;\n } else if (len <= 0xffff) {\n this._buf[seq] = 0x82;\n this._buf[seq + 1] = len >> 8;\n this._buf[seq + 2] = len;\n } else if (len <= 0xffffff) {\n this._shift(start, len, 1);\n this._buf[seq] = 0x83;\n this._buf[seq + 1] = len >> 16;\n this._buf[seq + 2] = len >> 8;\n this._buf[seq + 3] = len;\n } else {\n throw newInvalidAsn1Error('Sequence too long');\n }\n};\n\n\nWriter.prototype._shift = function (start, len, shift) {\n assert.ok(start !== undefined);\n assert.ok(len !== undefined);\n assert.ok(shift);\n\n this._buf.copy(this._buf, start + shift, start, start + len);\n this._offset += shift;\n};\n\nWriter.prototype._ensure = function (len) {\n assert.ok(len);\n\n if (this._size - this._offset < len) {\n var sz = this._size * this._options.growthFactor;\n if (sz - this._offset < len)\n sz += len;\n\n var buf = Buffer.alloc(sz);\n\n this._buf.copy(buf, 0, 0, this._offset);\n this._buf = buf;\n this._size = sz;\n }\n};\n\n\n\n// --- Exported API\n\nmodule.exports = Writer;\n","// Copyright 2011 Mark Cavage All rights reserved.\n\n// If you have no idea what ASN.1 or BER is, see this:\n// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc\n\nvar Ber = require('./ber/index');\n\n\n\n// --- Exported API\n\nmodule.exports = {\n\n Ber: Ber,\n\n BerReader: Ber.Reader,\n\n BerWriter: Ber.Writer\n\n};\n","// Copyright (c) 2012, Mark Cavage. All rights reserved.\n// Copyright 2015 Joyent, Inc.\n\nvar assert = require('assert');\nvar Stream = require('stream').Stream;\nvar util = require('util');\n\n\n///--- Globals\n\n/* JSSTYLED */\nvar UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/;\n\n\n///--- Internal\n\nfunction _capitalize(str) {\n return (str.charAt(0).toUpperCase() + str.slice(1));\n}\n\nfunction _toss(name, expected, oper, arg, actual) {\n throw new assert.AssertionError({\n message: util.format('%s (%s) is required', name, expected),\n actual: (actual === undefined) ? typeof (arg) : actual(arg),\n expected: expected,\n operator: oper || '===',\n stackStartFunction: _toss.caller\n });\n}\n\nfunction _getClass(arg) {\n return (Object.prototype.toString.call(arg).slice(8, -1));\n}\n\nfunction noop() {\n // Why even bother with asserts?\n}\n\n\n///--- Exports\n\nvar types = {\n bool: {\n check: function (arg) { return typeof (arg) === 'boolean'; }\n },\n func: {\n check: function (arg) { return typeof (arg) === 'function'; }\n },\n string: {\n check: function (arg) { return typeof (arg) === 'string'; }\n },\n object: {\n check: function (arg) {\n return typeof (arg) === 'object' && arg !== null;\n }\n },\n number: {\n check: function (arg) {\n return typeof (arg) === 'number' && !isNaN(arg);\n }\n },\n finite: {\n check: function (arg) {\n return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg);\n }\n },\n buffer: {\n check: function (arg) { return Buffer.isBuffer(arg); },\n operator: 'Buffer.isBuffer'\n },\n array: {\n check: function (arg) { return Array.isArray(arg); },\n operator: 'Array.isArray'\n },\n stream: {\n check: function (arg) { return arg instanceof Stream; },\n operator: 'instanceof',\n actual: _getClass\n },\n date: {\n check: function (arg) { return arg instanceof Date; },\n operator: 'instanceof',\n actual: _getClass\n },\n regexp: {\n check: function (arg) { return arg instanceof RegExp; },\n operator: 'instanceof',\n actual: _getClass\n },\n uuid: {\n check: function (arg) {\n return typeof (arg) === 'string' && UUID_REGEXP.test(arg);\n },\n operator: 'isUUID'\n }\n};\n\nfunction _setExports(ndebug) {\n var keys = Object.keys(types);\n var out;\n\n /* re-export standard assert */\n if (process.env.NODE_NDEBUG) {\n out = noop;\n } else {\n out = function (arg, msg) {\n if (!arg) {\n _toss(msg, 'true', arg);\n }\n };\n }\n\n /* standard checks */\n keys.forEach(function (k) {\n if (ndebug) {\n out[k] = noop;\n return;\n }\n var type = types[k];\n out[k] = function (arg, msg) {\n if (!type.check(arg)) {\n _toss(msg, k, type.operator, arg, type.actual);\n }\n };\n });\n\n /* optional checks */\n keys.forEach(function (k) {\n var name = 'optional' + _capitalize(k);\n if (ndebug) {\n out[name] = noop;\n return;\n }\n var type = types[k];\n out[name] = function (arg, msg) {\n if (arg === undefined || arg === null) {\n return;\n }\n if (!type.check(arg)) {\n _toss(msg, k, type.operator, arg, type.actual);\n }\n };\n });\n\n /* arrayOf checks */\n keys.forEach(function (k) {\n var name = 'arrayOf' + _capitalize(k);\n if (ndebug) {\n out[name] = noop;\n return;\n }\n var type = types[k];\n var expected = '[' + k + ']';\n out[name] = function (arg, msg) {\n if (!Array.isArray(arg)) {\n _toss(msg, expected, type.operator, arg, type.actual);\n }\n var i;\n for (i = 0; i < arg.length; i++) {\n if (!type.check(arg[i])) {\n _toss(msg, expected, type.operator, arg, type.actual);\n }\n }\n };\n });\n\n /* optionalArrayOf checks */\n keys.forEach(function (k) {\n var name = 'optionalArrayOf' + _capitalize(k);\n if (ndebug) {\n out[name] = noop;\n return;\n }\n var type = types[k];\n var expected = '[' + k + ']';\n out[name] = function (arg, msg) {\n if (arg === undefined || arg === null) {\n return;\n }\n if (!Array.isArray(arg)) {\n _toss(msg, expected, type.operator, arg, type.actual);\n }\n var i;\n for (i = 0; i < arg.length; i++) {\n if (!type.check(arg[i])) {\n _toss(msg, expected, type.operator, arg, type.actual);\n }\n }\n };\n });\n\n /* re-export built-in assertions */\n Object.keys(assert).forEach(function (k) {\n if (k === 'AssertionError') {\n out[k] = assert[k];\n return;\n }\n if (ndebug) {\n out[k] = noop;\n return;\n }\n out[k] = assert[k];\n });\n\n /* export ourselves (for unit tests _only_) */\n out._setExports = _setExports;\n\n return out;\n}\n\nmodule.exports = _setExports(process.env.NODE_NDEBUG);\n","(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n typeof define === 'function' && define.amd ? define(['exports'], factory) :\n (factory((global.async = {})));\n}(this, (function (exports) { 'use strict';\n\n /**\n * Creates a continuation function with some arguments already applied.\n *\n * Useful as a shorthand when combined with other control flow functions. Any\n * arguments passed to the returned function are added to the arguments\n * originally passed to apply.\n *\n * @name apply\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {Function} fn - The function you want to eventually apply all\n * arguments to. Invokes with (arguments...).\n * @param {...*} arguments... - Any number of arguments to automatically apply\n * when the continuation is called.\n * @returns {Function} the partially-applied function\n * @example\n *\n * // using apply\n * async.parallel([\n * async.apply(fs.writeFile, 'testfile1', 'test1'),\n * async.apply(fs.writeFile, 'testfile2', 'test2')\n * ]);\n *\n *\n * // the same process without using apply\n * async.parallel([\n * function(callback) {\n * fs.writeFile('testfile1', 'test1', callback);\n * },\n * function(callback) {\n * fs.writeFile('testfile2', 'test2', callback);\n * }\n * ]);\n *\n * // It's possible to pass any number of additional arguments when calling the\n * // continuation:\n *\n * node> var fn = async.apply(sys.puts, 'one');\n * node> fn('two', 'three');\n * one\n * two\n * three\n */\n function apply(fn, ...args) {\n return (...callArgs) => fn(...args,...callArgs);\n }\n\n function initialParams (fn) {\n return function (...args/*, callback*/) {\n var callback = args.pop();\n return fn.call(this, args, callback);\n };\n }\n\n /* istanbul ignore file */\n\n var hasSetImmediate = typeof setImmediate === 'function' && setImmediate;\n var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function';\n\n function fallback(fn) {\n setTimeout(fn, 0);\n }\n\n function wrap(defer) {\n return (fn, ...args) => defer(() => fn(...args));\n }\n\n var _defer;\n\n if (hasSetImmediate) {\n _defer = setImmediate;\n } else if (hasNextTick) {\n _defer = process.nextTick;\n } else {\n _defer = fallback;\n }\n\n var setImmediate$1 = wrap(_defer);\n\n /**\n * Take a sync function and make it async, passing its return value to a\n * callback. This is useful for plugging sync functions into a waterfall,\n * series, or other async functions. Any arguments passed to the generated\n * function will be passed to the wrapped function (except for the final\n * callback argument). Errors thrown will be passed to the callback.\n *\n * If the function passed to `asyncify` returns a Promise, that promises's\n * resolved/rejected state will be used to call the callback, rather than simply\n * the synchronous return value.\n *\n * This also means you can asyncify ES2017 `async` functions.\n *\n * @name asyncify\n * @static\n * @memberOf module:Utils\n * @method\n * @alias wrapSync\n * @category Util\n * @param {Function} func - The synchronous function, or Promise-returning\n * function to convert to an {@link AsyncFunction}.\n * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be\n * invoked with `(args..., callback)`.\n * @example\n *\n * // passing a regular synchronous function\n * async.waterfall([\n * async.apply(fs.readFile, filename, \"utf8\"),\n * async.asyncify(JSON.parse),\n * function (data, next) {\n * // data is the result of parsing the text.\n * // If there was a parsing error, it would have been caught.\n * }\n * ], callback);\n *\n * // passing a function returning a promise\n * async.waterfall([\n * async.apply(fs.readFile, filename, \"utf8\"),\n * async.asyncify(function (contents) {\n * return db.model.create(contents);\n * }),\n * function (model, next) {\n * // `model` is the instantiated model object.\n * // If there was an error, this function would be skipped.\n * }\n * ], callback);\n *\n * // es2017 example, though `asyncify` is not needed if your JS environment\n * // supports async functions out of the box\n * var q = async.queue(async.asyncify(async function(file) {\n * var intermediateStep = await processFile(file);\n * return await somePromise(intermediateStep)\n * }));\n *\n * q.push(files);\n */\n function asyncify(func) {\n if (isAsync(func)) {\n return function (...args/*, callback*/) {\n const callback = args.pop();\n const promise = func.apply(this, args);\n return handlePromise(promise, callback)\n }\n }\n\n return initialParams(function (args, callback) {\n var result;\n try {\n result = func.apply(this, args);\n } catch (e) {\n return callback(e);\n }\n // if result is Promise object\n if (result && typeof result.then === 'function') {\n return handlePromise(result, callback)\n } else {\n callback(null, result);\n }\n });\n }\n\n function handlePromise(promise, callback) {\n return promise.then(value => {\n invokeCallback(callback, null, value);\n }, err => {\n invokeCallback(callback, err && err.message ? err : new Error(err));\n });\n }\n\n function invokeCallback(callback, error, value) {\n try {\n callback(error, value);\n } catch (err) {\n setImmediate$1(e => { throw e }, err);\n }\n }\n\n function isAsync(fn) {\n return fn[Symbol.toStringTag] === 'AsyncFunction';\n }\n\n function isAsyncGenerator(fn) {\n return fn[Symbol.toStringTag] === 'AsyncGenerator';\n }\n\n function isAsyncIterable(obj) {\n return typeof obj[Symbol.asyncIterator] === 'function';\n }\n\n function wrapAsync(asyncFn) {\n if (typeof asyncFn !== 'function') throw new Error('expected a function')\n return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn;\n }\n\n // conditionally promisify a function.\n // only return a promise if a callback is omitted\n function awaitify (asyncFn, arity = asyncFn.length) {\n if (!arity) throw new Error('arity is undefined')\n function awaitable (...args) {\n if (typeof args[arity - 1] === 'function') {\n return asyncFn.apply(this, args)\n }\n\n return new Promise((resolve, reject) => {\n args[arity - 1] = (err, ...cbArgs) => {\n if (err) return reject(err)\n resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]);\n };\n asyncFn.apply(this, args);\n })\n }\n\n return awaitable\n }\n\n function applyEach (eachfn) {\n return function applyEach(fns, ...callArgs) {\n const go = awaitify(function (callback) {\n var that = this;\n return eachfn(fns, (fn, cb) => {\n wrapAsync(fn).apply(that, callArgs.concat(cb));\n }, callback);\n });\n return go;\n };\n }\n\n function _asyncMap(eachfn, arr, iteratee, callback) {\n arr = arr || [];\n var results = [];\n var counter = 0;\n var _iteratee = wrapAsync(iteratee);\n\n return eachfn(arr, (value, _, iterCb) => {\n var index = counter++;\n _iteratee(value, (err, v) => {\n results[index] = v;\n iterCb(err);\n });\n }, err => {\n callback(err, results);\n });\n }\n\n function isArrayLike(value) {\n return value &&\n typeof value.length === 'number' &&\n value.length >= 0 &&\n value.length % 1 === 0;\n }\n\n // A temporary value used to identify if the loop should be broken.\n // See #1064, #1293\n const breakLoop = {};\n\n function once(fn) {\n function wrapper (...args) {\n if (fn === null) return;\n var callFn = fn;\n fn = null;\n callFn.apply(this, args);\n }\n Object.assign(wrapper, fn);\n return wrapper\n }\n\n function getIterator (coll) {\n return coll[Symbol.iterator] && coll[Symbol.iterator]();\n }\n\n function createArrayIterator(coll) {\n var i = -1;\n var len = coll.length;\n return function next() {\n return ++i < len ? {value: coll[i], key: i} : null;\n }\n }\n\n function createES2015Iterator(iterator) {\n var i = -1;\n return function next() {\n var item = iterator.next();\n if (item.done)\n return null;\n i++;\n return {value: item.value, key: i};\n }\n }\n\n function createObjectIterator(obj) {\n var okeys = obj ? Object.keys(obj) : [];\n var i = -1;\n var len = okeys.length;\n return function next() {\n var key = okeys[++i];\n return i < len ? {value: obj[key], key} : null;\n };\n }\n\n function createIterator(coll) {\n if (isArrayLike(coll)) {\n return createArrayIterator(coll);\n }\n\n var iterator = getIterator(coll);\n return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);\n }\n\n function onlyOnce(fn) {\n return function (...args) {\n if (fn === null) throw new Error(\"Callback was already called.\");\n var callFn = fn;\n fn = null;\n callFn.apply(this, args);\n };\n }\n\n // for async generators\n function asyncEachOfLimit(generator, limit, iteratee, callback) {\n let done = false;\n let canceled = false;\n let awaiting = false;\n let running = 0;\n let idx = 0;\n\n function replenish() {\n //console.log('replenish')\n if (running >= limit || awaiting || done) return\n //console.log('replenish awaiting')\n awaiting = true;\n generator.next().then(({value, done: iterDone}) => {\n //console.log('got value', value)\n if (canceled || done) return\n awaiting = false;\n if (iterDone) {\n done = true;\n if (running <= 0) {\n //console.log('done nextCb')\n callback(null);\n }\n return;\n }\n running++;\n iteratee(value, idx, iterateeCallback);\n idx++;\n replenish();\n }).catch(handleError);\n }\n\n function iterateeCallback(err, result) {\n //console.log('iterateeCallback')\n running -= 1;\n if (canceled) return\n if (err) return handleError(err)\n\n if (err === false) {\n done = true;\n canceled = true;\n return\n }\n\n if (result === breakLoop || (done && running <= 0)) {\n done = true;\n //console.log('done iterCb')\n return callback(null);\n }\n replenish();\n }\n\n function handleError(err) {\n if (canceled) return\n awaiting = false;\n done = true;\n callback(err);\n }\n\n replenish();\n }\n\n var eachOfLimit = (limit) => {\n return (obj, iteratee, callback) => {\n callback = once(callback);\n if (limit <= 0) {\n throw new RangeError('concurrency limit cannot be less than 1')\n }\n if (!obj) {\n return callback(null);\n }\n if (isAsyncGenerator(obj)) {\n return asyncEachOfLimit(obj, limit, iteratee, callback)\n }\n if (isAsyncIterable(obj)) {\n return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback)\n }\n var nextElem = createIterator(obj);\n var done = false;\n var canceled = false;\n var running = 0;\n var looping = false;\n\n function iterateeCallback(err, value) {\n if (canceled) return\n running -= 1;\n if (err) {\n done = true;\n callback(err);\n }\n else if (err === false) {\n done = true;\n canceled = true;\n }\n else if (value === breakLoop || (done && running <= 0)) {\n done = true;\n return callback(null);\n }\n else if (!looping) {\n replenish();\n }\n }\n\n function replenish () {\n looping = true;\n while (running < limit && !done) {\n var elem = nextElem();\n if (elem === null) {\n done = true;\n if (running <= 0) {\n callback(null);\n }\n return;\n }\n running += 1;\n iteratee(elem.value, elem.key, onlyOnce(iterateeCallback));\n }\n looping = false;\n }\n\n replenish();\n };\n };\n\n /**\n * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a\n * time.\n *\n * @name eachOfLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.eachOf]{@link module:Collections.eachOf}\n * @alias forEachOfLimit\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - An async function to apply to each\n * item in `coll`. The `key` is the item's key, or index in the case of an\n * array.\n * Invoked with (item, key, callback).\n * @param {Function} [callback] - A callback which is called when all\n * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n * @returns {Promise} a promise, if a callback is omitted\n */\n function eachOfLimit$1(coll, limit, iteratee, callback) {\n return eachOfLimit(limit)(coll, wrapAsync(iteratee), callback);\n }\n\n var eachOfLimit$2 = awaitify(eachOfLimit$1, 4);\n\n // eachOf implementation optimized for array-likes\n function eachOfArrayLike(coll, iteratee, callback) {\n callback = once(callback);\n var index = 0,\n completed = 0,\n {length} = coll,\n canceled = false;\n if (length === 0) {\n callback(null);\n }\n\n function iteratorCallback(err, value) {\n if (err === false) {\n canceled = true;\n }\n if (canceled === true) return\n if (err) {\n callback(err);\n } else if ((++completed === length) || value === breakLoop) {\n callback(null);\n }\n }\n\n for (; index < length; index++) {\n iteratee(coll[index], index, onlyOnce(iteratorCallback));\n }\n }\n\n // a generic version of eachOf which can handle array, object, and iterator cases.\n function eachOfGeneric (coll, iteratee, callback) {\n return eachOfLimit$2(coll, Infinity, iteratee, callback);\n }\n\n /**\n * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument\n * to the iteratee.\n *\n * @name eachOf\n * @static\n * @memberOf module:Collections\n * @method\n * @alias forEachOf\n * @category Collection\n * @see [async.each]{@link module:Collections.each}\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - A function to apply to each\n * item in `coll`.\n * The `key` is the item's key, or index in the case of an array.\n * Invoked with (item, key, callback).\n * @param {Function} [callback] - A callback which is called when all\n * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n * @returns {Promise} a promise, if a callback is omitted\n * @example\n *\n * var obj = {dev: \"/dev.json\", test: \"/test.json\", prod: \"/prod.json\"};\n * var configs = {};\n *\n * async.forEachOf(obj, function (value, key, callback) {\n * fs.readFile(__dirname + value, \"utf8\", function (err, data) {\n * if (err) return callback(err);\n * try {\n * configs[key] = JSON.parse(data);\n * } catch (e) {\n * return callback(e);\n * }\n * callback();\n * });\n * }, function (err) {\n * if (err) console.error(err.message);\n * // configs is now a map of JSON data\n * doSomethingWith(configs);\n * });\n */\n function eachOf(coll, iteratee, callback) {\n var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric;\n return eachOfImplementation(coll, wrapAsync(iteratee), callback);\n }\n\n var eachOf$1 = awaitify(eachOf, 3);\n\n /**\n * Produces a new collection of values by mapping each value in `coll` through\n * the `iteratee` function. The `iteratee` is called with an item from `coll`\n * and a callback for when it has finished processing. Each of these callback\n * takes 2 arguments: an `error`, and the transformed item from `coll`. If\n * `iteratee` passes an error to its callback, the main `callback` (for the\n * `map` function) is immediately called with the error.\n *\n * Note, that since this function applies the `iteratee` to each item in\n * parallel, there is no guarantee that the `iteratee` functions will complete\n * in order. However, the results array will be in the same order as the\n * original `coll`.\n *\n * If `map` is passed an Object, the results will be an Array. The results\n * will roughly be in the order of the original Objects' keys (but this can\n * vary across JavaScript engines).\n *\n * @name map\n * @static\n * @memberOf module:Collections\n * @method\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The iteratee should complete with the transformed item.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Results is an Array of the\n * transformed items from the `coll`. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback is passed\n * @example\n *\n * async.map(['file1','file2','file3'], fs.stat, function(err, results) {\n * // results is now an array of stats for each file\n * });\n */\n function map (coll, iteratee, callback) {\n return _asyncMap(eachOf$1, coll, iteratee, callback)\n }\n var map$1 = awaitify(map, 3);\n\n /**\n * Applies the provided arguments to each function in the array, calling\n * `callback` after all functions have completed. If you only provide the first\n * argument, `fns`, then it will return a function which lets you pass in the\n * arguments as if it were a single function call. If more arguments are\n * provided, `callback` is required while `args` is still optional. The results\n * for each of the applied async functions are passed to the final callback\n * as an array.\n *\n * @name applyEach\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s\n * to all call with the same arguments\n * @param {...*} [args] - any number of separate arguments to pass to the\n * function.\n * @param {Function} [callback] - the final argument should be the callback,\n * called when all functions have completed processing.\n * @returns {AsyncFunction} - Returns a function that takes no args other than\n * an optional callback, that is the result of applying the `args` to each\n * of the functions.\n * @example\n *\n * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket')\n *\n * appliedFn((err, results) => {\n * // results[0] is the results for `enableSearch`\n * // results[1] is the results for `updateSchema`\n * });\n *\n * // partial application example:\n * async.each(\n * buckets,\n * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(),\n * callback\n * );\n */\n var applyEach$1 = applyEach(map$1);\n\n /**\n * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time.\n *\n * @name eachOfSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.eachOf]{@link module:Collections.eachOf}\n * @alias forEachOfSeries\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * Invoked with (item, key, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Invoked with (err).\n * @returns {Promise} a promise, if a callback is omitted\n */\n function eachOfSeries(coll, iteratee, callback) {\n return eachOfLimit$2(coll, 1, iteratee, callback)\n }\n var eachOfSeries$1 = awaitify(eachOfSeries, 3);\n\n /**\n * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time.\n *\n * @name mapSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.map]{@link module:Collections.map}\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The iteratee should complete with the transformed item.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Results is an array of the\n * transformed items from the `coll`. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback is passed\n */\n function mapSeries (coll, iteratee, callback) {\n return _asyncMap(eachOfSeries$1, coll, iteratee, callback)\n }\n var mapSeries$1 = awaitify(mapSeries, 3);\n\n /**\n * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time.\n *\n * @name applyEachSeries\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.applyEach]{@link module:ControlFlow.applyEach}\n * @category Control Flow\n * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all\n * call with the same arguments\n * @param {...*} [args] - any number of separate arguments to pass to the\n * function.\n * @param {Function} [callback] - the final argument should be the callback,\n * called when all functions have completed processing.\n * @returns {AsyncFunction} - A function, that when called, is the result of\n * appling the `args` to the list of functions. It takes no args, other than\n * a callback.\n */\n var applyEachSeries = applyEach(mapSeries$1);\n\n const PROMISE_SYMBOL = Symbol('promiseCallback');\n\n function promiseCallback () {\n let resolve, reject;\n function callback (err, ...args) {\n if (err) return reject(err)\n resolve(args.length > 1 ? args : args[0]);\n }\n\n callback[PROMISE_SYMBOL] = new Promise((res, rej) => {\n resolve = res,\n reject = rej;\n });\n\n return callback\n }\n\n /**\n * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on\n * their requirements. Each function can optionally depend on other functions\n * being completed first, and each function is run as soon as its requirements\n * are satisfied.\n *\n * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence\n * will stop. Further tasks will not execute (so any other functions depending\n * on it will not run), and the main `callback` is immediately called with the\n * error.\n *\n * {@link AsyncFunction}s also receive an object containing the results of functions which\n * have completed so far as the first argument, if they have dependencies. If a\n * task function has no dependencies, it will only be passed a callback.\n *\n * @name auto\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {Object} tasks - An object. Each of its properties is either a\n * function or an array of requirements, with the {@link AsyncFunction} itself the last item\n * in the array. The object's key of a property serves as the name of the task\n * defined by that property, i.e. can be used when specifying requirements for\n * other tasks. The function receives one or two arguments:\n * * a `results` object, containing the results of the previously executed\n * functions, only passed if the task has any dependencies,\n * * a `callback(err, result)` function, which must be called when finished,\n * passing an `error` (which can be `null`) and the result of the function's\n * execution.\n * @param {number} [concurrency=Infinity] - An optional `integer` for\n * determining the maximum number of tasks that can be run in parallel. By\n * default, as many as possible.\n * @param {Function} [callback] - An optional callback which is called when all\n * the tasks have been completed. It receives the `err` argument if any `tasks`\n * pass an error to their callback. Results are always returned; however, if an\n * error occurs, no further `tasks` will be performed, and the results object\n * will only contain partial results. Invoked with (err, results).\n * @returns {Promise} a promise, if a callback is not passed\n * @example\n *\n * async.auto({\n * // this function will just be passed a callback\n * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'),\n * showData: ['readData', function(results, cb) {\n * // results.readData is the file's contents\n * // ...\n * }]\n * }, callback);\n *\n * async.auto({\n * get_data: function(callback) {\n * console.log('in get_data');\n * // async code to get some data\n * callback(null, 'data', 'converted to array');\n * },\n * make_folder: function(callback) {\n * console.log('in make_folder');\n * // async code to create a directory to store a file in\n * // this is run at the same time as getting the data\n * callback(null, 'folder');\n * },\n * write_file: ['get_data', 'make_folder', function(results, callback) {\n * console.log('in write_file', JSON.stringify(results));\n * // once there is some data and the directory exists,\n * // write the data to a file in the directory\n * callback(null, 'filename');\n * }],\n * email_link: ['write_file', function(results, callback) {\n * console.log('in email_link', JSON.stringify(results));\n * // once the file is written let's email a link to it...\n * // results.write_file contains the filename returned by write_file.\n * callback(null, {'file':results.write_file, 'email':'user@example.com'});\n * }]\n * }, function(err, results) {\n * console.log('err = ', err);\n * console.log('results = ', results);\n * });\n */\n function auto(tasks, concurrency, callback) {\n if (typeof concurrency !== 'number') {\n // concurrency is optional, shift the args.\n callback = concurrency;\n concurrency = null;\n }\n callback = once(callback || promiseCallback());\n var numTasks = Object.keys(tasks).length;\n if (!numTasks) {\n return callback(null);\n }\n if (!concurrency) {\n concurrency = numTasks;\n }\n\n var results = {};\n var runningTasks = 0;\n var canceled = false;\n var hasError = false;\n\n var listeners = Object.create(null);\n\n var readyTasks = [];\n\n // for cycle detection:\n var readyToCheck = []; // tasks that have been identified as reachable\n // without the possibility of returning to an ancestor task\n var uncheckedDependencies = {};\n\n Object.keys(tasks).forEach(key => {\n var task = tasks[key];\n if (!Array.isArray(task)) {\n // no dependencies\n enqueueTask(key, [task]);\n readyToCheck.push(key);\n return;\n }\n\n var dependencies = task.slice(0, task.length - 1);\n var remainingDependencies = dependencies.length;\n if (remainingDependencies === 0) {\n enqueueTask(key, task);\n readyToCheck.push(key);\n return;\n }\n uncheckedDependencies[key] = remainingDependencies;\n\n dependencies.forEach(dependencyName => {\n if (!tasks[dependencyName]) {\n throw new Error('async.auto task `' + key +\n '` has a non-existent dependency `' +\n dependencyName + '` in ' +\n dependencies.join(', '));\n }\n addListener(dependencyName, () => {\n remainingDependencies--;\n if (remainingDependencies === 0) {\n enqueueTask(key, task);\n }\n });\n });\n });\n\n checkForDeadlocks();\n processQueue();\n\n function enqueueTask(key, task) {\n readyTasks.push(() => runTask(key, task));\n }\n\n function processQueue() {\n if (canceled) return\n if (readyTasks.length === 0 && runningTasks === 0) {\n return callback(null, results);\n }\n while(readyTasks.length && runningTasks < concurrency) {\n var run = readyTasks.shift();\n run();\n }\n\n }\n\n function addListener(taskName, fn) {\n var taskListeners = listeners[taskName];\n if (!taskListeners) {\n taskListeners = listeners[taskName] = [];\n }\n\n taskListeners.push(fn);\n }\n\n function taskComplete(taskName) {\n var taskListeners = listeners[taskName] || [];\n taskListeners.forEach(fn => fn());\n processQueue();\n }\n\n\n function runTask(key, task) {\n if (hasError) return;\n\n var taskCallback = onlyOnce((err, ...result) => {\n runningTasks--;\n if (err === false) {\n canceled = true;\n return\n }\n if (result.length < 2) {\n [result] = result;\n }\n if (err) {\n var safeResults = {};\n Object.keys(results).forEach(rkey => {\n safeResults[rkey] = results[rkey];\n });\n safeResults[key] = result;\n hasError = true;\n listeners = Object.create(null);\n if (canceled) return\n callback(err, safeResults);\n } else {\n results[key] = result;\n taskComplete(key);\n }\n });\n\n runningTasks++;\n var taskFn = wrapAsync(task[task.length - 1]);\n if (task.length > 1) {\n taskFn(results, taskCallback);\n } else {\n taskFn(taskCallback);\n }\n }\n\n function checkForDeadlocks() {\n // Kahn's algorithm\n // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm\n // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html\n var currentTask;\n var counter = 0;\n while (readyToCheck.length) {\n currentTask = readyToCheck.pop();\n counter++;\n getDependents(currentTask).forEach(dependent => {\n if (--uncheckedDependencies[dependent] === 0) {\n readyToCheck.push(dependent);\n }\n });\n }\n\n if (counter !== numTasks) {\n throw new Error(\n 'async.auto cannot execute tasks due to a recursive dependency'\n );\n }\n }\n\n function getDependents(taskName) {\n var result = [];\n Object.keys(tasks).forEach(key => {\n const task = tasks[key];\n if (Array.isArray(task) && task.indexOf(taskName) >= 0) {\n result.push(key);\n }\n });\n return result;\n }\n\n return callback[PROMISE_SYMBOL]\n }\n\n var FN_ARGS = /^(?:async\\s+)?(?:function)?\\s*\\w*\\s*\\(\\s*([^)]+)\\s*\\)(?:\\s*{)/;\n var ARROW_FN_ARGS = /^(?:async\\s+)?\\(?\\s*([^)=]+)\\s*\\)?(?:\\s*=>)/;\n var FN_ARG_SPLIT = /,/;\n var FN_ARG = /(=.+)?(\\s*)$/;\n var STRIP_COMMENTS = /((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))/mg;\n\n function parseParams(func) {\n const src = func.toString().replace(STRIP_COMMENTS, '');\n let match = src.match(FN_ARGS);\n if (!match) {\n match = src.match(ARROW_FN_ARGS);\n }\n if (!match) throw new Error('could not parse args in autoInject\\nSource:\\n' + src)\n let [, args] = match;\n return args\n .replace(/\\s/g, '')\n .split(FN_ARG_SPLIT)\n .map((arg) => arg.replace(FN_ARG, '').trim());\n }\n\n /**\n * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent\n * tasks are specified as parameters to the function, after the usual callback\n * parameter, with the parameter names matching the names of the tasks it\n * depends on. This can provide even more readable task graphs which can be\n * easier to maintain.\n *\n * If a final callback is specified, the task results are similarly injected,\n * specified as named parameters after the initial error parameter.\n *\n * The autoInject function is purely syntactic sugar and its semantics are\n * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}.\n *\n * @name autoInject\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.auto]{@link module:ControlFlow.auto}\n * @category Control Flow\n * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of\n * the form 'func([dependencies...], callback). The object's key of a property\n * serves as the name of the task defined by that property, i.e. can be used\n * when specifying requirements for other tasks.\n * * The `callback` parameter is a `callback(err, result)` which must be called\n * when finished, passing an `error` (which can be `null`) and the result of\n * the function's execution. The remaining parameters name other tasks on\n * which the task is dependent, and the results from those tasks are the\n * arguments of those parameters.\n * @param {Function} [callback] - An optional callback which is called when all\n * the tasks have been completed. It receives the `err` argument if any `tasks`\n * pass an error to their callback, and a `results` object with any completed\n * task results, similar to `auto`.\n * @returns {Promise} a promise, if no callback is passed\n * @example\n *\n * // The example from `auto` can be rewritten as follows:\n * async.autoInject({\n * get_data: function(callback) {\n * // async code to get some data\n * callback(null, 'data', 'converted to array');\n * },\n * make_folder: function(callback) {\n * // async code to create a directory to store a file in\n * // this is run at the same time as getting the data\n * callback(null, 'folder');\n * },\n * write_file: function(get_data, make_folder, callback) {\n * // once there is some data and the directory exists,\n * // write the data to a file in the directory\n * callback(null, 'filename');\n * },\n * email_link: function(write_file, callback) {\n * // once the file is written let's email a link to it...\n * // write_file contains the filename returned by write_file.\n * callback(null, {'file':write_file, 'email':'user@example.com'});\n * }\n * }, function(err, results) {\n * console.log('err = ', err);\n * console.log('email_link = ', results.email_link);\n * });\n *\n * // If you are using a JS minifier that mangles parameter names, `autoInject`\n * // will not work with plain functions, since the parameter names will be\n * // collapsed to a single letter identifier. To work around this, you can\n * // explicitly specify the names of the parameters your task function needs\n * // in an array, similar to Angular.js dependency injection.\n *\n * // This still has an advantage over plain `auto`, since the results a task\n * // depends on are still spread into arguments.\n * async.autoInject({\n * //...\n * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) {\n * callback(null, 'filename');\n * }],\n * email_link: ['write_file', function(write_file, callback) {\n * callback(null, {'file':write_file, 'email':'user@example.com'});\n * }]\n * //...\n * }, function(err, results) {\n * console.log('err = ', err);\n * console.log('email_link = ', results.email_link);\n * });\n */\n function autoInject(tasks, callback) {\n var newTasks = {};\n\n Object.keys(tasks).forEach(key => {\n var taskFn = tasks[key];\n var params;\n var fnIsAsync = isAsync(taskFn);\n var hasNoDeps =\n (!fnIsAsync && taskFn.length === 1) ||\n (fnIsAsync && taskFn.length === 0);\n\n if (Array.isArray(taskFn)) {\n params = [...taskFn];\n taskFn = params.pop();\n\n newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn);\n } else if (hasNoDeps) {\n // no dependencies, use the function as-is\n newTasks[key] = taskFn;\n } else {\n params = parseParams(taskFn);\n if ((taskFn.length === 0 && !fnIsAsync) && params.length === 0) {\n throw new Error(\"autoInject task functions require explicit parameters.\");\n }\n\n // remove callback param\n if (!fnIsAsync) params.pop();\n\n newTasks[key] = params.concat(newTask);\n }\n\n function newTask(results, taskCb) {\n var newArgs = params.map(name => results[name]);\n newArgs.push(taskCb);\n wrapAsync(taskFn)(...newArgs);\n }\n });\n\n return auto(newTasks, callback);\n }\n\n // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation\n // used for queues. This implementation assumes that the node provided by the user can be modified\n // to adjust the next and last properties. We implement only the minimal functionality\n // for queue support.\n class DLL {\n constructor() {\n this.head = this.tail = null;\n this.length = 0;\n }\n\n removeLink(node) {\n if (node.prev) node.prev.next = node.next;\n else this.head = node.next;\n if (node.next) node.next.prev = node.prev;\n else this.tail = node.prev;\n\n node.prev = node.next = null;\n this.length -= 1;\n return node;\n }\n\n empty () {\n while(this.head) this.shift();\n return this;\n }\n\n insertAfter(node, newNode) {\n newNode.prev = node;\n newNode.next = node.next;\n if (node.next) node.next.prev = newNode;\n else this.tail = newNode;\n node.next = newNode;\n this.length += 1;\n }\n\n insertBefore(node, newNode) {\n newNode.prev = node.prev;\n newNode.next = node;\n if (node.prev) node.prev.next = newNode;\n else this.head = newNode;\n node.prev = newNode;\n this.length += 1;\n }\n\n unshift(node) {\n if (this.head) this.insertBefore(this.head, node);\n else setInitial(this, node);\n }\n\n push(node) {\n if (this.tail) this.insertAfter(this.tail, node);\n else setInitial(this, node);\n }\n\n shift() {\n return this.head && this.removeLink(this.head);\n }\n\n pop() {\n return this.tail && this.removeLink(this.tail);\n }\n\n toArray() {\n return [...this]\n }\n\n *[Symbol.iterator] () {\n var cur = this.head;\n while (cur) {\n yield cur.data;\n cur = cur.next;\n }\n }\n\n remove (testFn) {\n var curr = this.head;\n while(curr) {\n var {next} = curr;\n if (testFn(curr)) {\n this.removeLink(curr);\n }\n curr = next;\n }\n return this;\n }\n }\n\n function setInitial(dll, node) {\n dll.length = 1;\n dll.head = dll.tail = node;\n }\n\n function queue(worker, concurrency, payload) {\n if (concurrency == null) {\n concurrency = 1;\n }\n else if(concurrency === 0) {\n throw new RangeError('Concurrency must not be zero');\n }\n\n var _worker = wrapAsync(worker);\n var numRunning = 0;\n var workersList = [];\n const events = {\n error: [],\n drain: [],\n saturated: [],\n unsaturated: [],\n empty: []\n };\n\n function on (event, handler) {\n events[event].push(handler);\n }\n\n function once (event, handler) {\n const handleAndRemove = (...args) => {\n off(event, handleAndRemove);\n handler(...args);\n };\n events[event].push(handleAndRemove);\n }\n\n function off (event, handler) {\n if (!event) return Object.keys(events).forEach(ev => events[ev] = [])\n if (!handler) return events[event] = []\n events[event] = events[event].filter(ev => ev !== handler);\n }\n\n function trigger (event, ...args) {\n events[event].forEach(handler => handler(...args));\n }\n\n var processingScheduled = false;\n function _insert(data, insertAtFront, rejectOnError, callback) {\n if (callback != null && typeof callback !== 'function') {\n throw new Error('task callback must be a function');\n }\n q.started = true;\n\n var res, rej;\n function promiseCallback (err, ...args) {\n // we don't care about the error, let the global error handler\n // deal with it\n if (err) return rejectOnError ? rej(err) : res()\n if (args.length <= 1) return res(args[0])\n res(args);\n }\n\n var item = {\n data,\n callback: rejectOnError ?\n promiseCallback :\n (callback || promiseCallback)\n };\n\n if (insertAtFront) {\n q._tasks.unshift(item);\n } else {\n q._tasks.push(item);\n }\n\n if (!processingScheduled) {\n processingScheduled = true;\n setImmediate$1(() => {\n processingScheduled = false;\n q.process();\n });\n }\n\n if (rejectOnError || !callback) {\n return new Promise((resolve, reject) => {\n res = resolve;\n rej = reject;\n })\n }\n }\n\n function _createCB(tasks) {\n return function (err, ...args) {\n numRunning -= 1;\n\n for (var i = 0, l = tasks.length; i < l; i++) {\n var task = tasks[i];\n\n var index = workersList.indexOf(task);\n if (index === 0) {\n workersList.shift();\n } else if (index > 0) {\n workersList.splice(index, 1);\n }\n\n task.callback(err, ...args);\n\n if (err != null) {\n trigger('error', err, task.data);\n }\n }\n\n if (numRunning <= (q.concurrency - q.buffer) ) {\n trigger('unsaturated');\n }\n\n if (q.idle()) {\n trigger('drain');\n }\n q.process();\n };\n }\n\n function _maybeDrain(data) {\n if (data.length === 0 && q.idle()) {\n // call drain immediately if there are no tasks\n setImmediate$1(() => trigger('drain'));\n return true\n }\n return false\n }\n\n const eventMethod = (name) => (handler) => {\n if (!handler) {\n return new Promise((resolve, reject) => {\n once(name, (err, data) => {\n if (err) return reject(err)\n resolve(data);\n });\n })\n }\n off(name);\n on(name, handler);\n\n };\n\n var isProcessing = false;\n var q = {\n _tasks: new DLL(),\n *[Symbol.iterator] () {\n yield* q._tasks[Symbol.iterator]();\n },\n concurrency,\n payload,\n buffer: concurrency / 4,\n started: false,\n paused: false,\n push (data, callback) {\n if (Array.isArray(data)) {\n if (_maybeDrain(data)) return\n return data.map(datum => _insert(datum, false, false, callback))\n }\n return _insert(data, false, false, callback);\n },\n pushAsync (data, callback) {\n if (Array.isArray(data)) {\n if (_maybeDrain(data)) return\n return data.map(datum => _insert(datum, false, true, callback))\n }\n return _insert(data, false, true, callback);\n },\n kill () {\n off();\n q._tasks.empty();\n },\n unshift (data, callback) {\n if (Array.isArray(data)) {\n if (_maybeDrain(data)) return\n return data.map(datum => _insert(datum, true, false, callback))\n }\n return _insert(data, true, false, callback);\n },\n unshiftAsync (data, callback) {\n if (Array.isArray(data)) {\n if (_maybeDrain(data)) return\n return data.map(datum => _insert(datum, true, true, callback))\n }\n return _insert(data, true, true, callback);\n },\n remove (testFn) {\n q._tasks.remove(testFn);\n },\n process () {\n // Avoid trying to start too many processing operations. This can occur\n // when callbacks resolve synchronously (#1267).\n if (isProcessing) {\n return;\n }\n isProcessing = true;\n while(!q.paused && numRunning < q.concurrency && q._tasks.length){\n var tasks = [], data = [];\n var l = q._tasks.length;\n if (q.payload) l = Math.min(l, q.payload);\n for (var i = 0; i < l; i++) {\n var node = q._tasks.shift();\n tasks.push(node);\n workersList.push(node);\n data.push(node.data);\n }\n\n numRunning += 1;\n\n if (q._tasks.length === 0) {\n trigger('empty');\n }\n\n if (numRunning === q.concurrency) {\n trigger('saturated');\n }\n\n var cb = onlyOnce(_createCB(tasks));\n _worker(data, cb);\n }\n isProcessing = false;\n },\n length () {\n return q._tasks.length;\n },\n running () {\n return numRunning;\n },\n workersList () {\n return workersList;\n },\n idle() {\n return q._tasks.length + numRunning === 0;\n },\n pause () {\n q.paused = true;\n },\n resume () {\n if (q.paused === false) { return; }\n q.paused = false;\n setImmediate$1(q.process);\n }\n };\n // define these as fixed properties, so people get useful errors when updating\n Object.defineProperties(q, {\n saturated: {\n writable: false,\n value: eventMethod('saturated')\n },\n unsaturated: {\n writable: false,\n value: eventMethod('unsaturated')\n },\n empty: {\n writable: false,\n value: eventMethod('empty')\n },\n drain: {\n writable: false,\n value: eventMethod('drain')\n },\n error: {\n writable: false,\n value: eventMethod('error')\n },\n });\n return q;\n }\n\n /**\n * Creates a `cargo` object with the specified payload. Tasks added to the\n * cargo will be processed altogether (up to the `payload` limit). If the\n * `worker` is in progress, the task is queued until it becomes available. Once\n * the `worker` has completed some tasks, each callback of those tasks is\n * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966)\n * for how `cargo` and `queue` work.\n *\n * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers\n * at a time, cargo passes an array of tasks to a single worker, repeating\n * when the worker is finished.\n *\n * @name cargo\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.queue]{@link module:ControlFlow.queue}\n * @category Control Flow\n * @param {AsyncFunction} worker - An asynchronous function for processing an array\n * of queued tasks. Invoked with `(tasks, callback)`.\n * @param {number} [payload=Infinity] - An optional `integer` for determining\n * how many tasks should be processed per round; if omitted, the default is\n * unlimited.\n * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can\n * attached as certain properties to listen for specific events during the\n * lifecycle of the cargo and inner queue.\n * @example\n *\n * // create a cargo object with payload 2\n * var cargo = async.cargo(function(tasks, callback) {\n * for (var i=0; i {\n _iteratee(memo, x, (err, v) => {\n memo = v;\n iterCb(err);\n });\n }, err => callback(err, memo));\n }\n var reduce$1 = awaitify(reduce, 4);\n\n /**\n * Version of the compose function that is more natural to read. Each function\n * consumes the return value of the previous function. It is the equivalent of\n * [compose]{@link module:ControlFlow.compose} with the arguments reversed.\n *\n * Each function is executed with the `this` binding of the composed function.\n *\n * @name seq\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.compose]{@link module:ControlFlow.compose}\n * @category Control Flow\n * @param {...AsyncFunction} functions - the asynchronous functions to compose\n * @returns {Function} a function that composes the `functions` in order\n * @example\n *\n * // Requires lodash (or underscore), express3 and dresende's orm2.\n * // Part of an app, that fetches cats of the logged user.\n * // This example uses `seq` function to avoid overnesting and error\n * // handling clutter.\n * app.get('/cats', function(request, response) {\n * var User = request.models.User;\n * async.seq(\n * _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data))\n * function(user, fn) {\n * user.getCats(fn); // 'getCats' has signature (callback(err, data))\n * }\n * )(req.session.user_id, function (err, cats) {\n * if (err) {\n * console.error(err);\n * response.json({ status: 'error', message: err.message });\n * } else {\n * response.json({ status: 'ok', message: 'Cats found', data: cats });\n * }\n * });\n * });\n */\n function seq(...functions) {\n var _functions = functions.map(wrapAsync);\n return function (...args) {\n var that = this;\n\n var cb = args[args.length - 1];\n if (typeof cb == 'function') {\n args.pop();\n } else {\n cb = promiseCallback();\n }\n\n reduce$1(_functions, args, (newargs, fn, iterCb) => {\n fn.apply(that, newargs.concat((err, ...nextargs) => {\n iterCb(err, nextargs);\n }));\n },\n (err, results) => cb(err, ...results));\n\n return cb[PROMISE_SYMBOL]\n };\n }\n\n /**\n * Creates a function which is a composition of the passed asynchronous\n * functions. Each function consumes the return value of the function that\n * follows. Composing functions `f()`, `g()`, and `h()` would produce the result\n * of `f(g(h()))`, only this version uses callbacks to obtain the return values.\n *\n * If the last argument to the composed function is not a function, a promise\n * is returned when you call it.\n *\n * Each function is executed with the `this` binding of the composed function.\n *\n * @name compose\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {...AsyncFunction} functions - the asynchronous functions to compose\n * @returns {Function} an asynchronous function that is the composed\n * asynchronous `functions`\n * @example\n *\n * function add1(n, callback) {\n * setTimeout(function () {\n * callback(null, n + 1);\n * }, 10);\n * }\n *\n * function mul3(n, callback) {\n * setTimeout(function () {\n * callback(null, n * 3);\n * }, 10);\n * }\n *\n * var add1mul3 = async.compose(mul3, add1);\n * add1mul3(4, function (err, result) {\n * // result now equals 15\n * });\n */\n function compose(...args) {\n return seq(...args.reverse());\n }\n\n /**\n * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time.\n *\n * @name mapLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.map]{@link module:Collections.map}\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The iteratee should complete with the transformed item.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Results is an array of the\n * transformed items from the `coll`. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback is passed\n */\n function mapLimit (coll, limit, iteratee, callback) {\n return _asyncMap(eachOfLimit(limit), coll, iteratee, callback)\n }\n var mapLimit$1 = awaitify(mapLimit, 4);\n\n /**\n * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time.\n *\n * @name concatLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.concat]{@link module:Collections.concat}\n * @category Collection\n * @alias flatMapLimit\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,\n * which should use an array as its result. Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished, or an error occurs. Results is an array\n * containing the concatenated results of the `iteratee` function. Invoked with\n * (err, results).\n * @returns A Promise, if no callback is passed\n */\n function concatLimit(coll, limit, iteratee, callback) {\n var _iteratee = wrapAsync(iteratee);\n return mapLimit$1(coll, limit, (val, iterCb) => {\n _iteratee(val, (err, ...args) => {\n if (err) return iterCb(err);\n return iterCb(err, args);\n });\n }, (err, mapResults) => {\n var result = [];\n for (var i = 0; i < mapResults.length; i++) {\n if (mapResults[i]) {\n result = result.concat(...mapResults[i]);\n }\n }\n\n return callback(err, result);\n });\n }\n var concatLimit$1 = awaitify(concatLimit, 4);\n\n /**\n * Applies `iteratee` to each item in `coll`, concatenating the results. Returns\n * the concatenated list. The `iteratee`s are called in parallel, and the\n * results are concatenated as they return. The results array will be returned in\n * the original order of `coll` passed to the `iteratee` function.\n *\n * @name concat\n * @static\n * @memberOf module:Collections\n * @method\n * @category Collection\n * @alias flatMap\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`,\n * which should use an array as its result. Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished, or an error occurs. Results is an array\n * containing the concatenated results of the `iteratee` function. Invoked with\n * (err, results).\n * @returns A Promise, if no callback is passed\n * @example\n *\n * async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files) {\n * // files is now a list of filenames that exist in the 3 directories\n * });\n */\n function concat(coll, iteratee, callback) {\n return concatLimit$1(coll, Infinity, iteratee, callback)\n }\n var concat$1 = awaitify(concat, 3);\n\n /**\n * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time.\n *\n * @name concatSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.concat]{@link module:Collections.concat}\n * @category Collection\n * @alias flatMapSeries\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`.\n * The iteratee should complete with an array an array of results.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished, or an error occurs. Results is an array\n * containing the concatenated results of the `iteratee` function. Invoked with\n * (err, results).\n * @returns A Promise, if no callback is passed\n */\n function concatSeries(coll, iteratee, callback) {\n return concatLimit$1(coll, 1, iteratee, callback)\n }\n var concatSeries$1 = awaitify(concatSeries, 3);\n\n /**\n * Returns a function that when called, calls-back with the values provided.\n * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to\n * [`auto`]{@link module:ControlFlow.auto}.\n *\n * @name constant\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {...*} arguments... - Any number of arguments to automatically invoke\n * callback with.\n * @returns {AsyncFunction} Returns a function that when invoked, automatically\n * invokes the callback with the previous given arguments.\n * @example\n *\n * async.waterfall([\n * async.constant(42),\n * function (value, next) {\n * // value === 42\n * },\n * //...\n * ], callback);\n *\n * async.waterfall([\n * async.constant(filename, \"utf8\"),\n * fs.readFile,\n * function (fileData, next) {\n * //...\n * }\n * //...\n * ], callback);\n *\n * async.auto({\n * hostname: async.constant(\"https://server.net/\"),\n * port: findFreePort,\n * launchServer: [\"hostname\", \"port\", function (options, cb) {\n * startServer(options, cb);\n * }],\n * //...\n * }, callback);\n */\n function constant(...args) {\n return function (...ignoredArgs/*, callback*/) {\n var callback = ignoredArgs.pop();\n return callback(null, ...args);\n };\n }\n\n function _createTester(check, getResult) {\n return (eachfn, arr, _iteratee, cb) => {\n var testPassed = false;\n var testResult;\n const iteratee = wrapAsync(_iteratee);\n eachfn(arr, (value, _, callback) => {\n iteratee(value, (err, result) => {\n if (err || err === false) return callback(err);\n\n if (check(result) && !testResult) {\n testPassed = true;\n testResult = getResult(true, value);\n return callback(null, breakLoop);\n }\n callback();\n });\n }, err => {\n if (err) return cb(err);\n cb(null, testPassed ? testResult : getResult(false));\n });\n };\n }\n\n /**\n * Returns the first value in `coll` that passes an async truth test. The\n * `iteratee` is applied in parallel, meaning the first iteratee to return\n * `true` will fire the detect `callback` with that result. That means the\n * result might not be the first item in the original `coll` (in terms of order)\n * that passes the test.\n\n * If order within the original `coll` is important, then look at\n * [`detectSeries`]{@link module:Collections.detectSeries}.\n *\n * @name detect\n * @static\n * @memberOf module:Collections\n * @method\n * @alias find\n * @category Collections\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.\n * The iteratee must complete with a boolean value as its result.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called as soon as any\n * iteratee returns `true`, or after all the `iteratee` functions have finished.\n * Result will be the first item in the array that passes the truth test\n * (iteratee) or the value `undefined` if none passed. Invoked with\n * (err, result).\n * @returns A Promise, if no callback is passed\n * @example\n *\n * async.detect(['file1','file2','file3'], function(filePath, callback) {\n * fs.access(filePath, function(err) {\n * callback(null, !err)\n * });\n * }, function(err, result) {\n * // result now equals the first file in the list that exists\n * });\n */\n function detect(coll, iteratee, callback) {\n return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback)\n }\n var detect$1 = awaitify(detect, 3);\n\n /**\n * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a\n * time.\n *\n * @name detectLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.detect]{@link module:Collections.detect}\n * @alias findLimit\n * @category Collections\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.\n * The iteratee must complete with a boolean value as its result.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called as soon as any\n * iteratee returns `true`, or after all the `iteratee` functions have finished.\n * Result will be the first item in the array that passes the truth test\n * (iteratee) or the value `undefined` if none passed. Invoked with\n * (err, result).\n * @returns a Promise if no callback is passed\n */\n function detectLimit(coll, limit, iteratee, callback) {\n return _createTester(bool => bool, (res, item) => item)(eachOfLimit(limit), coll, iteratee, callback)\n }\n var detectLimit$1 = awaitify(detectLimit, 4);\n\n /**\n * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time.\n *\n * @name detectSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.detect]{@link module:Collections.detect}\n * @alias findSeries\n * @category Collections\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`.\n * The iteratee must complete with a boolean value as its result.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called as soon as any\n * iteratee returns `true`, or after all the `iteratee` functions have finished.\n * Result will be the first item in the array that passes the truth test\n * (iteratee) or the value `undefined` if none passed. Invoked with\n * (err, result).\n * @returns a Promise if no callback is passed\n */\n function detectSeries(coll, iteratee, callback) {\n return _createTester(bool => bool, (res, item) => item)(eachOfLimit(1), coll, iteratee, callback)\n }\n\n var detectSeries$1 = awaitify(detectSeries, 3);\n\n function consoleFunc(name) {\n return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => {\n if (typeof console === 'object') {\n if (err) {\n if (console.error) {\n console.error(err);\n }\n } else if (console[name]) {\n resultArgs.forEach(x => console[name](x));\n }\n }\n })\n }\n\n /**\n * Logs the result of an [`async` function]{@link AsyncFunction} to the\n * `console` using `console.dir` to display the properties of the resulting object.\n * Only works in Node.js or in browsers that support `console.dir` and\n * `console.error` (such as FF and Chrome).\n * If multiple arguments are returned from the async function,\n * `console.dir` is called on each argument in order.\n *\n * @name dir\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {AsyncFunction} function - The function you want to eventually apply\n * all arguments to.\n * @param {...*} arguments... - Any number of arguments to apply to the function.\n * @example\n *\n * // in a module\n * var hello = function(name, callback) {\n * setTimeout(function() {\n * callback(null, {hello: name});\n * }, 1000);\n * };\n *\n * // in the node repl\n * node> async.dir(hello, 'world');\n * {hello: 'world'}\n */\n var dir = consoleFunc('dir');\n\n /**\n * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in\n * the order of operations, the arguments `test` and `iteratee` are switched.\n *\n * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.\n *\n * @name doWhilst\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.whilst]{@link module:ControlFlow.whilst}\n * @category Control Flow\n * @param {AsyncFunction} iteratee - A function which is called each time `test`\n * passes. Invoked with (callback).\n * @param {AsyncFunction} test - asynchronous truth test to perform after each\n * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the\n * non-error args from the previous callback of `iteratee`.\n * @param {Function} [callback] - A callback which is called after the test\n * function has failed and repeated execution of `iteratee` has stopped.\n * `callback` will be passed an error and any arguments passed to the final\n * `iteratee`'s callback. Invoked with (err, [results]);\n * @returns {Promise} a promise, if no callback is passed\n */\n function doWhilst(iteratee, test, callback) {\n callback = onlyOnce(callback);\n var _fn = wrapAsync(iteratee);\n var _test = wrapAsync(test);\n var results;\n\n function next(err, ...args) {\n if (err) return callback(err);\n if (err === false) return;\n results = args;\n _test(...args, check);\n }\n\n function check(err, truth) {\n if (err) return callback(err);\n if (err === false) return;\n if (!truth) return callback(null, ...results);\n _fn(next);\n }\n\n return check(null, true);\n }\n\n var doWhilst$1 = awaitify(doWhilst, 3);\n\n /**\n * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the\n * argument ordering differs from `until`.\n *\n * @name doUntil\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.doWhilst]{@link module:ControlFlow.doWhilst}\n * @category Control Flow\n * @param {AsyncFunction} iteratee - An async function which is called each time\n * `test` fails. Invoked with (callback).\n * @param {AsyncFunction} test - asynchronous truth test to perform after each\n * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the\n * non-error args from the previous callback of `iteratee`\n * @param {Function} [callback] - A callback which is called after the test\n * function has passed and repeated execution of `iteratee` has stopped. `callback`\n * will be passed an error and any arguments passed to the final `iteratee`'s\n * callback. Invoked with (err, [results]);\n * @returns {Promise} a promise, if no callback is passed\n */\n function doUntil(iteratee, test, callback) {\n const _test = wrapAsync(test);\n return doWhilst$1(iteratee, (...args) => {\n const cb = args.pop();\n _test(...args, (err, truth) => cb (err, !truth));\n }, callback);\n }\n\n function _withoutIndex(iteratee) {\n return (value, index, callback) => iteratee(value, callback);\n }\n\n /**\n * Applies the function `iteratee` to each item in `coll`, in parallel.\n * The `iteratee` is called with an item from the list, and a callback for when\n * it has finished. If the `iteratee` passes an error to its `callback`, the\n * main `callback` (for the `each` function) is immediately called with the\n * error.\n *\n * Note, that since this function applies `iteratee` to each item in parallel,\n * there is no guarantee that the iteratee functions will complete in order.\n *\n * @name each\n * @static\n * @memberOf module:Collections\n * @method\n * @alias forEach\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to\n * each item in `coll`. Invoked with (item, callback).\n * The array index is not passed to the iteratee.\n * If you need the index, use `eachOf`.\n * @param {Function} [callback] - A callback which is called when all\n * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n * @returns {Promise} a promise, if a callback is omitted\n * @example\n *\n * // assuming openFiles is an array of file names and saveFile is a function\n * // to save the modified contents of that file:\n *\n * async.each(openFiles, saveFile, function(err){\n * // if any of the saves produced an error, err would equal that error\n * });\n *\n * // assuming openFiles is an array of file names\n * async.each(openFiles, function(file, callback) {\n *\n * // Perform operation on file here.\n * console.log('Processing file ' + file);\n *\n * if( file.length > 32 ) {\n * console.log('This file name is too long');\n * callback('File name too long');\n * } else {\n * // Do work to process file here\n * console.log('File processed');\n * callback();\n * }\n * }, function(err) {\n * // if any of the file processing produced an error, err would equal that error\n * if( err ) {\n * // One of the iterations produced an error.\n * // All processing will now stop.\n * console.log('A file failed to process');\n * } else {\n * console.log('All files have been processed successfully');\n * }\n * });\n */\n function eachLimit(coll, iteratee, callback) {\n return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback);\n }\n\n var each = awaitify(eachLimit, 3);\n\n /**\n * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time.\n *\n * @name eachLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.each]{@link module:Collections.each}\n * @alias forEachLimit\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The array index is not passed to the iteratee.\n * If you need the index, use `eachOfLimit`.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called when all\n * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n * @returns {Promise} a promise, if a callback is omitted\n */\n function eachLimit$1(coll, limit, iteratee, callback) {\n return eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback);\n }\n var eachLimit$2 = awaitify(eachLimit$1, 4);\n\n /**\n * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time.\n *\n * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item\n * in series and therefore the iteratee functions will complete in order.\n\n * @name eachSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.each]{@link module:Collections.each}\n * @alias forEachSeries\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to each\n * item in `coll`.\n * The array index is not passed to the iteratee.\n * If you need the index, use `eachOfSeries`.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called when all\n * `iteratee` functions have finished, or an error occurs. Invoked with (err).\n * @returns {Promise} a promise, if a callback is omitted\n */\n function eachSeries(coll, iteratee, callback) {\n return eachLimit$2(coll, 1, iteratee, callback)\n }\n var eachSeries$1 = awaitify(eachSeries, 3);\n\n /**\n * Wrap an async function and ensure it calls its callback on a later tick of\n * the event loop. If the function already calls its callback on a next tick,\n * no extra deferral is added. This is useful for preventing stack overflows\n * (`RangeError: Maximum call stack size exceeded`) and generally keeping\n * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony)\n * contained. ES2017 `async` functions are returned as-is -- they are immune\n * to Zalgo's corrupting influences, as they always resolve on a later tick.\n *\n * @name ensureAsync\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {AsyncFunction} fn - an async function, one that expects a node-style\n * callback as its last argument.\n * @returns {AsyncFunction} Returns a wrapped function with the exact same call\n * signature as the function passed in.\n * @example\n *\n * function sometimesAsync(arg, callback) {\n * if (cache[arg]) {\n * return callback(null, cache[arg]); // this would be synchronous!!\n * } else {\n * doSomeIO(arg, callback); // this IO would be asynchronous\n * }\n * }\n *\n * // this has a risk of stack overflows if many results are cached in a row\n * async.mapSeries(args, sometimesAsync, done);\n *\n * // this will defer sometimesAsync's callback if necessary,\n * // preventing stack overflows\n * async.mapSeries(args, async.ensureAsync(sometimesAsync), done);\n */\n function ensureAsync(fn) {\n if (isAsync(fn)) return fn;\n return function (...args/*, callback*/) {\n var callback = args.pop();\n var sync = true;\n args.push((...innerArgs) => {\n if (sync) {\n setImmediate$1(() => callback(...innerArgs));\n } else {\n callback(...innerArgs);\n }\n });\n fn.apply(this, args);\n sync = false;\n };\n }\n\n /**\n * Returns `true` if every element in `coll` satisfies an async test. If any\n * iteratee call returns `false`, the main `callback` is immediately called.\n *\n * @name every\n * @static\n * @memberOf module:Collections\n * @method\n * @alias all\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async truth test to apply to each item\n * in the collection in parallel.\n * The iteratee must complete with a boolean result value.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Result will be either `true` or `false`\n * depending on the values of the async tests. Invoked with (err, result).\n * @returns {Promise} a promise, if no callback provided\n * @example\n *\n * async.every(['file1','file2','file3'], function(filePath, callback) {\n * fs.access(filePath, function(err) {\n * callback(null, !err)\n * });\n * }, function(err, result) {\n * // if result is true then every file exists\n * });\n */\n function every(coll, iteratee, callback) {\n return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback)\n }\n var every$1 = awaitify(every, 3);\n\n /**\n * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time.\n *\n * @name everyLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.every]{@link module:Collections.every}\n * @alias allLimit\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - An async truth test to apply to each item\n * in the collection in parallel.\n * The iteratee must complete with a boolean result value.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Result will be either `true` or `false`\n * depending on the values of the async tests. Invoked with (err, result).\n * @returns {Promise} a promise, if no callback provided\n */\n function everyLimit(coll, limit, iteratee, callback) {\n return _createTester(bool => !bool, res => !res)(eachOfLimit(limit), coll, iteratee, callback)\n }\n var everyLimit$1 = awaitify(everyLimit, 4);\n\n /**\n * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time.\n *\n * @name everySeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.every]{@link module:Collections.every}\n * @alias allSeries\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async truth test to apply to each item\n * in the collection in series.\n * The iteratee must complete with a boolean result value.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Result will be either `true` or `false`\n * depending on the values of the async tests. Invoked with (err, result).\n * @returns {Promise} a promise, if no callback provided\n */\n function everySeries(coll, iteratee, callback) {\n return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback)\n }\n var everySeries$1 = awaitify(everySeries, 3);\n\n function filterArray(eachfn, arr, iteratee, callback) {\n var truthValues = new Array(arr.length);\n eachfn(arr, (x, index, iterCb) => {\n iteratee(x, (err, v) => {\n truthValues[index] = !!v;\n iterCb(err);\n });\n }, err => {\n if (err) return callback(err);\n var results = [];\n for (var i = 0; i < arr.length; i++) {\n if (truthValues[i]) results.push(arr[i]);\n }\n callback(null, results);\n });\n }\n\n function filterGeneric(eachfn, coll, iteratee, callback) {\n var results = [];\n eachfn(coll, (x, index, iterCb) => {\n iteratee(x, (err, v) => {\n if (err) return iterCb(err);\n if (v) {\n results.push({index, value: x});\n }\n iterCb(err);\n });\n }, err => {\n if (err) return callback(err);\n callback(null, results\n .sort((a, b) => a.index - b.index)\n .map(v => v.value));\n });\n }\n\n function _filter(eachfn, coll, iteratee, callback) {\n var filter = isArrayLike(coll) ? filterArray : filterGeneric;\n return filter(eachfn, coll, wrapAsync(iteratee), callback);\n }\n\n /**\n * Returns a new array of all the values in `coll` which pass an async truth\n * test. This operation is performed in parallel, but the results array will be\n * in the same order as the original.\n *\n * @name filter\n * @static\n * @memberOf module:Collections\n * @method\n * @alias select\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {Function} iteratee - A truth test to apply to each item in `coll`.\n * The `iteratee` is passed a `callback(err, truthValue)`, which must be called\n * with a boolean argument once it has completed. Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback provided\n * @example\n *\n * async.filter(['file1','file2','file3'], function(filePath, callback) {\n * fs.access(filePath, function(err) {\n * callback(null, !err)\n * });\n * }, function(err, results) {\n * // results now equals an array of the existing files\n * });\n */\n function filter (coll, iteratee, callback) {\n return _filter(eachOf$1, coll, iteratee, callback)\n }\n var filter$1 = awaitify(filter, 3);\n\n /**\n * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a\n * time.\n *\n * @name filterLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.filter]{@link module:Collections.filter}\n * @alias selectLimit\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {Function} iteratee - A truth test to apply to each item in `coll`.\n * The `iteratee` is passed a `callback(err, truthValue)`, which must be called\n * with a boolean argument once it has completed. Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback provided\n */\n function filterLimit (coll, limit, iteratee, callback) {\n return _filter(eachOfLimit(limit), coll, iteratee, callback)\n }\n var filterLimit$1 = awaitify(filterLimit, 4);\n\n /**\n * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time.\n *\n * @name filterSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.filter]{@link module:Collections.filter}\n * @alias selectSeries\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {Function} iteratee - A truth test to apply to each item in `coll`.\n * The `iteratee` is passed a `callback(err, truthValue)`, which must be called\n * with a boolean argument once it has completed. Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Invoked with (err, results)\n * @returns {Promise} a promise, if no callback provided\n */\n function filterSeries (coll, iteratee, callback) {\n return _filter(eachOfSeries$1, coll, iteratee, callback)\n }\n var filterSeries$1 = awaitify(filterSeries, 3);\n\n /**\n * Calls the asynchronous function `fn` with a callback parameter that allows it\n * to call itself again, in series, indefinitely.\n\n * If an error is passed to the callback then `errback` is called with the\n * error, and execution stops, otherwise it will never be called.\n *\n * @name forever\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {AsyncFunction} fn - an async function to call repeatedly.\n * Invoked with (next).\n * @param {Function} [errback] - when `fn` passes an error to it's callback,\n * this function will be called, and execution stops. Invoked with (err).\n * @returns {Promise} a promise that rejects if an error occurs and an errback\n * is not passed\n * @example\n *\n * async.forever(\n * function(next) {\n * // next is suitable for passing to things that need a callback(err [, whatever]);\n * // it will result in this function being called again.\n * },\n * function(err) {\n * // if next is called with a value in its first parameter, it will appear\n * // in here as 'err', and execution will stop.\n * }\n * );\n */\n function forever(fn, errback) {\n var done = onlyOnce(errback);\n var task = wrapAsync(ensureAsync(fn));\n\n function next(err) {\n if (err) return done(err);\n if (err === false) return;\n task(next);\n }\n return next();\n }\n var forever$1 = awaitify(forever, 2);\n\n /**\n * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time.\n *\n * @name groupByLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.groupBy]{@link module:Collections.groupBy}\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The iteratee should complete with a `key` to group the value under.\n * Invoked with (value, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Result is an `Object` whoses\n * properties are arrays of values which returned the corresponding key.\n * @returns {Promise} a promise, if no callback is passed\n */\n function groupByLimit(coll, limit, iteratee, callback) {\n var _iteratee = wrapAsync(iteratee);\n return mapLimit$1(coll, limit, (val, iterCb) => {\n _iteratee(val, (err, key) => {\n if (err) return iterCb(err);\n return iterCb(err, {key, val});\n });\n }, (err, mapResults) => {\n var result = {};\n // from MDN, handle object having an `hasOwnProperty` prop\n var {hasOwnProperty} = Object.prototype;\n\n for (var i = 0; i < mapResults.length; i++) {\n if (mapResults[i]) {\n var {key} = mapResults[i];\n var {val} = mapResults[i];\n\n if (hasOwnProperty.call(result, key)) {\n result[key].push(val);\n } else {\n result[key] = [val];\n }\n }\n }\n\n return callback(err, result);\n });\n }\n\n var groupByLimit$1 = awaitify(groupByLimit, 4);\n\n /**\n * Returns a new object, where each value corresponds to an array of items, from\n * `coll`, that returned the corresponding key. That is, the keys of the object\n * correspond to the values passed to the `iteratee` callback.\n *\n * Note: Since this function applies the `iteratee` to each item in parallel,\n * there is no guarantee that the `iteratee` functions will complete in order.\n * However, the values for each key in the `result` will be in the same order as\n * the original `coll`. For Objects, the values will roughly be in the order of\n * the original Objects' keys (but this can vary across JavaScript engines).\n *\n * @name groupBy\n * @static\n * @memberOf module:Collections\n * @method\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The iteratee should complete with a `key` to group the value under.\n * Invoked with (value, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Result is an `Object` whoses\n * properties are arrays of values which returned the corresponding key.\n * @returns {Promise} a promise, if no callback is passed\n * @example\n *\n * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) {\n * db.findById(userId, function(err, user) {\n * if (err) return callback(err);\n * return callback(null, user.age);\n * });\n * }, function(err, result) {\n * // result is object containing the userIds grouped by age\n * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']};\n * });\n */\n function groupBy (coll, iteratee, callback) {\n return groupByLimit$1(coll, Infinity, iteratee, callback)\n }\n\n /**\n * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time.\n *\n * @name groupBySeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.groupBy]{@link module:Collections.groupBy}\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The iteratee should complete with a `key` to group the value under.\n * Invoked with (value, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. Result is an `Object` whoses\n * properties are arrays of values which returned the corresponding key.\n * @returns {Promise} a promise, if no callback is passed\n */\n function groupBySeries (coll, iteratee, callback) {\n return groupByLimit$1(coll, 1, iteratee, callback)\n }\n\n /**\n * Logs the result of an `async` function to the `console`. Only works in\n * Node.js or in browsers that support `console.log` and `console.error` (such\n * as FF and Chrome). If multiple arguments are returned from the async\n * function, `console.log` is called on each argument in order.\n *\n * @name log\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {AsyncFunction} function - The function you want to eventually apply\n * all arguments to.\n * @param {...*} arguments... - Any number of arguments to apply to the function.\n * @example\n *\n * // in a module\n * var hello = function(name, callback) {\n * setTimeout(function() {\n * callback(null, 'hello ' + name);\n * }, 1000);\n * };\n *\n * // in the node repl\n * node> async.log(hello, 'world');\n * 'hello world'\n */\n var log = consoleFunc('log');\n\n /**\n * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a\n * time.\n *\n * @name mapValuesLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.mapValues]{@link module:Collections.mapValues}\n * @category Collection\n * @param {Object} obj - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - A function to apply to each value and key\n * in `coll`.\n * The iteratee should complete with the transformed value as its result.\n * Invoked with (value, key, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. `result` is a new object consisting\n * of each key from `obj`, with each transformed value on the right-hand side.\n * Invoked with (err, result).\n * @returns {Promise} a promise, if no callback is passed\n */\n function mapValuesLimit(obj, limit, iteratee, callback) {\n callback = once(callback);\n var newObj = {};\n var _iteratee = wrapAsync(iteratee);\n return eachOfLimit(limit)(obj, (val, key, next) => {\n _iteratee(val, key, (err, result) => {\n if (err) return next(err);\n newObj[key] = result;\n next(err);\n });\n }, err => callback(err, newObj));\n }\n\n var mapValuesLimit$1 = awaitify(mapValuesLimit, 4);\n\n /**\n * A relative of [`map`]{@link module:Collections.map}, designed for use with objects.\n *\n * Produces a new Object by mapping each value of `obj` through the `iteratee`\n * function. The `iteratee` is called each `value` and `key` from `obj` and a\n * callback for when it has finished processing. Each of these callbacks takes\n * two arguments: an `error`, and the transformed item from `obj`. If `iteratee`\n * passes an error to its callback, the main `callback` (for the `mapValues`\n * function) is immediately called with the error.\n *\n * Note, the order of the keys in the result is not guaranteed. The keys will\n * be roughly in the order they complete, (but this is very engine-specific)\n *\n * @name mapValues\n * @static\n * @memberOf module:Collections\n * @method\n * @category Collection\n * @param {Object} obj - A collection to iterate over.\n * @param {AsyncFunction} iteratee - A function to apply to each value and key\n * in `coll`.\n * The iteratee should complete with the transformed value as its result.\n * Invoked with (value, key, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. `result` is a new object consisting\n * of each key from `obj`, with each transformed value on the right-hand side.\n * Invoked with (err, result).\n * @returns {Promise} a promise, if no callback is passed\n * @example\n *\n * async.mapValues({\n * f1: 'file1',\n * f2: 'file2',\n * f3: 'file3'\n * }, function (file, key, callback) {\n * fs.stat(file, callback);\n * }, function(err, result) {\n * // result is now a map of stats for each file, e.g.\n * // {\n * // f1: [stats for file1],\n * // f2: [stats for file2],\n * // f3: [stats for file3]\n * // }\n * });\n */\n function mapValues(obj, iteratee, callback) {\n return mapValuesLimit$1(obj, Infinity, iteratee, callback)\n }\n\n /**\n * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time.\n *\n * @name mapValuesSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.mapValues]{@link module:Collections.mapValues}\n * @category Collection\n * @param {Object} obj - A collection to iterate over.\n * @param {AsyncFunction} iteratee - A function to apply to each value and key\n * in `coll`.\n * The iteratee should complete with the transformed value as its result.\n * Invoked with (value, key, callback).\n * @param {Function} [callback] - A callback which is called when all `iteratee`\n * functions have finished, or an error occurs. `result` is a new object consisting\n * of each key from `obj`, with each transformed value on the right-hand side.\n * Invoked with (err, result).\n * @returns {Promise} a promise, if no callback is passed\n */\n function mapValuesSeries(obj, iteratee, callback) {\n return mapValuesLimit$1(obj, 1, iteratee, callback)\n }\n\n /**\n * Caches the results of an async function. When creating a hash to store\n * function results against, the callback is omitted from the hash and an\n * optional hash function can be used.\n *\n * **Note: if the async function errs, the result will not be cached and\n * subsequent calls will call the wrapped function.**\n *\n * If no hash function is specified, the first argument is used as a hash key,\n * which may work reasonably if it is a string or a data type that converts to a\n * distinct string. Note that objects and arrays will not behave reasonably.\n * Neither will cases where the other arguments are significant. In such cases,\n * specify your own hash function.\n *\n * The cache of results is exposed as the `memo` property of the function\n * returned by `memoize`.\n *\n * @name memoize\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {AsyncFunction} fn - The async function to proxy and cache results from.\n * @param {Function} hasher - An optional function for generating a custom hash\n * for storing results. It has all the arguments applied to it apart from the\n * callback, and must be synchronous.\n * @returns {AsyncFunction} a memoized version of `fn`\n * @example\n *\n * var slow_fn = function(name, callback) {\n * // do something\n * callback(null, result);\n * };\n * var fn = async.memoize(slow_fn);\n *\n * // fn can now be used as if it were slow_fn\n * fn('some name', function() {\n * // callback\n * });\n */\n function memoize(fn, hasher = v => v) {\n var memo = Object.create(null);\n var queues = Object.create(null);\n var _fn = wrapAsync(fn);\n var memoized = initialParams((args, callback) => {\n var key = hasher(...args);\n if (key in memo) {\n setImmediate$1(() => callback(null, ...memo[key]));\n } else if (key in queues) {\n queues[key].push(callback);\n } else {\n queues[key] = [callback];\n _fn(...args, (err, ...resultArgs) => {\n // #1465 don't memoize if an error occurred\n if (!err) {\n memo[key] = resultArgs;\n }\n var q = queues[key];\n delete queues[key];\n for (var i = 0, l = q.length; i < l; i++) {\n q[i](err, ...resultArgs);\n }\n });\n }\n });\n memoized.memo = memo;\n memoized.unmemoized = fn;\n return memoized;\n }\n\n /**\n * Calls `callback` on a later loop around the event loop. In Node.js this just\n * calls `process.nextTick`. In the browser it will use `setImmediate` if\n * available, otherwise `setTimeout(callback, 0)`, which means other higher\n * priority events may precede the execution of `callback`.\n *\n * This is used internally for browser-compatibility purposes.\n *\n * @name nextTick\n * @static\n * @memberOf module:Utils\n * @method\n * @see [async.setImmediate]{@link module:Utils.setImmediate}\n * @category Util\n * @param {Function} callback - The function to call on a later loop around\n * the event loop. Invoked with (args...).\n * @param {...*} args... - any number of additional arguments to pass to the\n * callback on the next tick.\n * @example\n *\n * var call_order = [];\n * async.nextTick(function() {\n * call_order.push('two');\n * // call_order now equals ['one','two']\n * });\n * call_order.push('one');\n *\n * async.setImmediate(function (a, b, c) {\n * // a, b, and c equal 1, 2, and 3\n * }, 1, 2, 3);\n */\n var _defer$1;\n\n if (hasNextTick) {\n _defer$1 = process.nextTick;\n } else if (hasSetImmediate) {\n _defer$1 = setImmediate;\n } else {\n _defer$1 = fallback;\n }\n\n var nextTick = wrap(_defer$1);\n\n var parallel = awaitify((eachfn, tasks, callback) => {\n var results = isArrayLike(tasks) ? [] : {};\n\n eachfn(tasks, (task, key, taskCb) => {\n wrapAsync(task)((err, ...result) => {\n if (result.length < 2) {\n [result] = result;\n }\n results[key] = result;\n taskCb(err);\n });\n }, err => callback(err, results));\n }, 3);\n\n /**\n * Run the `tasks` collection of functions in parallel, without waiting until\n * the previous function has completed. If any of the functions pass an error to\n * its callback, the main `callback` is immediately called with the value of the\n * error. Once the `tasks` have completed, the results are passed to the final\n * `callback` as an array.\n *\n * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about\n * parallel execution of code. If your tasks do not use any timers or perform\n * any I/O, they will actually be executed in series. Any synchronous setup\n * sections for each task will happen one after the other. JavaScript remains\n * single-threaded.\n *\n * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the\n * execution of other tasks when a task fails.\n *\n * It is also possible to use an object instead of an array. Each property will\n * be run as a function and the results will be passed to the final `callback`\n * as an object instead of an array. This can be a more readable way of handling\n * results from {@link async.parallel}.\n *\n * @name parallel\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of\n * [async functions]{@link AsyncFunction} to run.\n * Each async function can complete with any number of optional `result` values.\n * @param {Function} [callback] - An optional callback to run once all the\n * functions have completed successfully. This function gets a results array\n * (or object) containing all the result arguments passed to the task callbacks.\n * Invoked with (err, results).\n * @returns {Promise} a promise, if a callback is not passed\n *\n * @example\n * async.parallel([\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'one');\n * }, 200);\n * },\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'two');\n * }, 100);\n * }\n * ],\n * // optional callback\n * function(err, results) {\n * // the results array will equal ['one','two'] even though\n * // the second function had a shorter timeout.\n * });\n *\n * // an example using an object instead of an array\n * async.parallel({\n * one: function(callback) {\n * setTimeout(function() {\n * callback(null, 1);\n * }, 200);\n * },\n * two: function(callback) {\n * setTimeout(function() {\n * callback(null, 2);\n * }, 100);\n * }\n * }, function(err, results) {\n * // results is now equals to: {one: 1, two: 2}\n * });\n */\n function parallel$1(tasks, callback) {\n return parallel(eachOf$1, tasks, callback);\n }\n\n /**\n * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a\n * time.\n *\n * @name parallelLimit\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.parallel]{@link module:ControlFlow.parallel}\n * @category Control Flow\n * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of\n * [async functions]{@link AsyncFunction} to run.\n * Each async function can complete with any number of optional `result` values.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {Function} [callback] - An optional callback to run once all the\n * functions have completed successfully. This function gets a results array\n * (or object) containing all the result arguments passed to the task callbacks.\n * Invoked with (err, results).\n * @returns {Promise} a promise, if a callback is not passed\n */\n function parallelLimit(tasks, limit, callback) {\n return parallel(eachOfLimit(limit), tasks, callback);\n }\n\n /**\n * A queue of tasks for the worker function to complete.\n * @typedef {Iterable} QueueObject\n * @memberOf module:ControlFlow\n * @property {Function} length - a function returning the number of items\n * waiting to be processed. Invoke with `queue.length()`.\n * @property {boolean} started - a boolean indicating whether or not any\n * items have been pushed and processed by the queue.\n * @property {Function} running - a function returning the number of items\n * currently being processed. Invoke with `queue.running()`.\n * @property {Function} workersList - a function returning the array of items\n * currently being processed. Invoke with `queue.workersList()`.\n * @property {Function} idle - a function returning false if there are items\n * waiting or being processed, or true if not. Invoke with `queue.idle()`.\n * @property {number} concurrency - an integer for determining how many `worker`\n * functions should be run in parallel. This property can be changed after a\n * `queue` is created to alter the concurrency on-the-fly.\n * @property {number} payload - an integer that specifies how many items are\n * passed to the worker function at a time. only applies if this is a\n * [cargo]{@link module:ControlFlow.cargo} object\n * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback`\n * once the `worker` has finished processing the task. Instead of a single task,\n * a `tasks` array can be submitted. The respective callback is used for every\n * task in the list. Invoke with `queue.push(task, [callback])`,\n * @property {AsyncFunction} unshift - add a new task to the front of the `queue`.\n * Invoke with `queue.unshift(task, [callback])`.\n * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns\n * a promise that rejects if an error occurs.\n * @property {AsyncFunction} unshirtAsync - the same as `q.unshift`, except this returns\n * a promise that rejects if an error occurs.\n * @property {Function} remove - remove items from the queue that match a test\n * function. The test function will be passed an object with a `data` property,\n * and a `priority` property, if this is a\n * [priorityQueue]{@link module:ControlFlow.priorityQueue} object.\n * Invoked with `queue.remove(testFn)`, where `testFn` is of the form\n * `function ({data, priority}) {}` and returns a Boolean.\n * @property {Function} saturated - a function that sets a callback that is\n * called when the number of running workers hits the `concurrency` limit, and\n * further tasks will be queued. If the callback is omitted, `q.saturated()`\n * returns a promise for the next occurrence.\n * @property {Function} unsaturated - a function that sets a callback that is\n * called when the number of running workers is less than the `concurrency` &\n * `buffer` limits, and further tasks will not be queued. If the callback is\n * omitted, `q.unsaturated()` returns a promise for the next occurrence.\n * @property {number} buffer - A minimum threshold buffer in order to say that\n * the `queue` is `unsaturated`.\n * @property {Function} empty - a function that sets a callback that is called\n * when the last item from the `queue` is given to a `worker`. If the callback\n * is omitted, `q.empty()` returns a promise for the next occurrence.\n * @property {Function} drain - a function that sets a callback that is called\n * when the last item from the `queue` has returned from the `worker`. If the\n * callback is omitted, `q.drain()` returns a promise for the next occurrence.\n * @property {Function} error - a function that sets a callback that is called\n * when a task errors. Has the signature `function(error, task)`. If the\n * callback is omitted, `error()` returns a promise that rejects on the next\n * error.\n * @property {boolean} paused - a boolean for determining whether the queue is\n * in a paused state.\n * @property {Function} pause - a function that pauses the processing of tasks\n * until `resume()` is called. Invoke with `queue.pause()`.\n * @property {Function} resume - a function that resumes the processing of\n * queued tasks when the queue is paused. Invoke with `queue.resume()`.\n * @property {Function} kill - a function that removes the `drain` callback and\n * empties remaining tasks from the queue forcing it to go idle. No more tasks\n * should be pushed to the queue after calling this function. Invoke with `queue.kill()`.\n *\n * @example\n * const q = aync.queue(worker, 2)\n * q.push(item1)\n * q.push(item2)\n * q.push(item3)\n * // queues are iterable, spread into an array to inspect\n * const items = [...q] // [item1, item2, item3]\n * // or use for of\n * for (let item of q) {\n * console.log(item)\n * }\n *\n * q.drain(() => {\n * console.log('all done')\n * })\n * // or\n * await q.drain()\n */\n\n /**\n * Creates a `queue` object with the specified `concurrency`. Tasks added to the\n * `queue` are processed in parallel (up to the `concurrency` limit). If all\n * `worker`s are in progress, the task is queued until one becomes available.\n * Once a `worker` completes a `task`, that `task`'s callback is called.\n *\n * @name queue\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {AsyncFunction} worker - An async function for processing a queued task.\n * If you want to handle errors from an individual task, pass a callback to\n * `q.push()`. Invoked with (task, callback).\n * @param {number} [concurrency=1] - An `integer` for determining how many\n * `worker` functions should be run in parallel. If omitted, the concurrency\n * defaults to `1`. If the concurrency is `0`, an error is thrown.\n * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be\n * attached as certain properties to listen for specific events during the\n * lifecycle of the queue.\n * @example\n *\n * // create a queue object with concurrency 2\n * var q = async.queue(function(task, callback) {\n * console.log('hello ' + task.name);\n * callback();\n * }, 2);\n *\n * // assign a callback\n * q.drain(function() {\n * console.log('all items have been processed');\n * });\n * // or await the end\n * await q.drain()\n *\n * // assign an error callback\n * q.error(function(err, task) {\n * console.error('task experienced an error');\n * });\n *\n * // add some items to the queue\n * q.push({name: 'foo'}, function(err) {\n * console.log('finished processing foo');\n * });\n * // callback is optional\n * q.push({name: 'bar'});\n *\n * // add some items to the queue (batch-wise)\n * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {\n * console.log('finished processing item');\n * });\n *\n * // add some items to the front of the queue\n * q.unshift({name: 'bar'}, function (err) {\n * console.log('finished processing bar');\n * });\n */\n function queue$1 (worker, concurrency) {\n var _worker = wrapAsync(worker);\n return queue((items, cb) => {\n _worker(items[0], cb);\n }, concurrency, 1);\n }\n\n // Binary min-heap implementation used for priority queue.\n // Implementation is stable, i.e. push time is considered for equal priorities\n class Heap {\n constructor() {\n this.heap = [];\n this.pushCount = Number.MIN_SAFE_INTEGER;\n }\n\n get length() {\n return this.heap.length;\n }\n\n empty () {\n this.heap = [];\n return this;\n }\n\n percUp(index) {\n let p;\n\n while (index > 0 && smaller(this.heap[index], this.heap[p=parent(index)])) {\n let t = this.heap[index];\n this.heap[index] = this.heap[p];\n this.heap[p] = t;\n\n index = p;\n }\n }\n\n percDown(index) {\n let l;\n\n while ((l=leftChi(index)) < this.heap.length) {\n if (l+1 < this.heap.length && smaller(this.heap[l+1], this.heap[l])) {\n l = l+1;\n }\n\n if (smaller(this.heap[index], this.heap[l])) {\n break;\n }\n\n let t = this.heap[index];\n this.heap[index] = this.heap[l];\n this.heap[l] = t;\n\n index = l;\n }\n }\n\n push(node) {\n node.pushCount = ++this.pushCount;\n this.heap.push(node);\n this.percUp(this.heap.length-1);\n }\n\n unshift(node) {\n return this.heap.push(node);\n }\n\n shift() {\n let [top] = this.heap;\n\n this.heap[0] = this.heap[this.heap.length-1];\n this.heap.pop();\n this.percDown(0);\n\n return top;\n }\n\n toArray() {\n return [...this];\n }\n\n *[Symbol.iterator] () {\n for (let i = 0; i < this.heap.length; i++) {\n yield this.heap[i].data;\n }\n }\n\n remove (testFn) {\n let j = 0;\n for (let i = 0; i < this.heap.length; i++) {\n if (!testFn(this.heap[i])) {\n this.heap[j] = this.heap[i];\n j++;\n }\n }\n\n this.heap.splice(j);\n\n for (let i = parent(this.heap.length-1); i >= 0; i--) {\n this.percDown(i);\n }\n\n return this;\n }\n }\n\n function leftChi(i) {\n return (i<<1)+1;\n }\n\n function parent(i) {\n return ((i+1)>>1)-1;\n }\n\n function smaller(x, y) {\n if (x.priority !== y.priority) {\n return x.priority < y.priority;\n }\n else {\n return x.pushCount < y.pushCount;\n }\n }\n\n /**\n * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and\n * completed in ascending priority order.\n *\n * @name priorityQueue\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.queue]{@link module:ControlFlow.queue}\n * @category Control Flow\n * @param {AsyncFunction} worker - An async function for processing a queued task.\n * If you want to handle errors from an individual task, pass a callback to\n * `q.push()`.\n * Invoked with (task, callback).\n * @param {number} concurrency - An `integer` for determining how many `worker`\n * functions should be run in parallel. If omitted, the concurrency defaults to\n * `1`. If the concurrency is `0`, an error is thrown.\n * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two\n * differences between `queue` and `priorityQueue` objects:\n * * `push(task, priority, [callback])` - `priority` should be a number. If an\n * array of `tasks` is given, all tasks will be assigned the same priority.\n * * The `unshift` method was removed.\n */\n function priorityQueue(worker, concurrency) {\n // Start with a normal queue\n var q = queue$1(worker, concurrency);\n\n q._tasks = new Heap();\n\n // Override push to accept second parameter representing priority\n q.push = function(data, priority = 0, callback = () => {}) {\n if (typeof callback !== 'function') {\n throw new Error('task callback must be a function');\n }\n q.started = true;\n if (!Array.isArray(data)) {\n data = [data];\n }\n if (data.length === 0 && q.idle()) {\n // call drain immediately if there are no tasks\n return setImmediate$1(() => q.drain());\n }\n\n for (var i = 0, l = data.length; i < l; i++) {\n var item = {\n data: data[i],\n priority,\n callback\n };\n\n q._tasks.push(item);\n }\n\n setImmediate$1(q.process);\n };\n\n // Remove unshift function\n delete q.unshift;\n\n return q;\n }\n\n /**\n * Runs the `tasks` array of functions in parallel, without waiting until the\n * previous function has completed. Once any of the `tasks` complete or pass an\n * error to its callback, the main `callback` is immediately called. It's\n * equivalent to `Promise.race()`.\n *\n * @name race\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction}\n * to run. Each function can complete with an optional `result` value.\n * @param {Function} callback - A callback to run once any of the functions have\n * completed. This function gets an error or result from the first function that\n * completed. Invoked with (err, result).\n * @returns undefined\n * @example\n *\n * async.race([\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'one');\n * }, 200);\n * },\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'two');\n * }, 100);\n * }\n * ],\n * // main callback\n * function(err, result) {\n * // the result will be equal to 'two' as it finishes earlier\n * });\n */\n function race(tasks, callback) {\n callback = once(callback);\n if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions'));\n if (!tasks.length) return callback();\n for (var i = 0, l = tasks.length; i < l; i++) {\n wrapAsync(tasks[i])(callback);\n }\n }\n\n var race$1 = awaitify(race, 2);\n\n /**\n * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order.\n *\n * @name reduceRight\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.reduce]{@link module:Collections.reduce}\n * @alias foldr\n * @category Collection\n * @param {Array} array - A collection to iterate over.\n * @param {*} memo - The initial state of the reduction.\n * @param {AsyncFunction} iteratee - A function applied to each item in the\n * array to produce the next step in the reduction.\n * The `iteratee` should complete with the next state of the reduction.\n * If the iteratee complete with an error, the reduction is stopped and the\n * main `callback` is immediately called with the error.\n * Invoked with (memo, item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Result is the reduced value. Invoked with\n * (err, result).\n * @returns {Promise} a promise, if no callback is passed\n */\n function reduceRight (array, memo, iteratee, callback) {\n var reversed = [...array].reverse();\n return reduce$1(reversed, memo, iteratee, callback);\n }\n\n /**\n * Wraps the async function in another function that always completes with a\n * result object, even when it errors.\n *\n * The result object has either the property `error` or `value`.\n *\n * @name reflect\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {AsyncFunction} fn - The async function you want to wrap\n * @returns {Function} - A function that always passes null to it's callback as\n * the error. The second argument to the callback will be an `object` with\n * either an `error` or a `value` property.\n * @example\n *\n * async.parallel([\n * async.reflect(function(callback) {\n * // do some stuff ...\n * callback(null, 'one');\n * }),\n * async.reflect(function(callback) {\n * // do some more stuff but error ...\n * callback('bad stuff happened');\n * }),\n * async.reflect(function(callback) {\n * // do some more stuff ...\n * callback(null, 'two');\n * })\n * ],\n * // optional callback\n * function(err, results) {\n * // values\n * // results[0].value = 'one'\n * // results[1].error = 'bad stuff happened'\n * // results[2].value = 'two'\n * });\n */\n function reflect(fn) {\n var _fn = wrapAsync(fn);\n return initialParams(function reflectOn(args, reflectCallback) {\n args.push((error, ...cbArgs) => {\n let retVal = {};\n if (error) {\n retVal.error = error;\n }\n if (cbArgs.length > 0){\n var value = cbArgs;\n if (cbArgs.length <= 1) {\n [value] = cbArgs;\n }\n retVal.value = value;\n }\n reflectCallback(null, retVal);\n });\n\n return _fn.apply(this, args);\n });\n }\n\n /**\n * A helper function that wraps an array or an object of functions with `reflect`.\n *\n * @name reflectAll\n * @static\n * @memberOf module:Utils\n * @method\n * @see [async.reflect]{@link module:Utils.reflect}\n * @category Util\n * @param {Array|Object|Iterable} tasks - The collection of\n * [async functions]{@link AsyncFunction} to wrap in `async.reflect`.\n * @returns {Array} Returns an array of async functions, each wrapped in\n * `async.reflect`\n * @example\n *\n * let tasks = [\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'one');\n * }, 200);\n * },\n * function(callback) {\n * // do some more stuff but error ...\n * callback(new Error('bad stuff happened'));\n * },\n * function(callback) {\n * setTimeout(function() {\n * callback(null, 'two');\n * }, 100);\n * }\n * ];\n *\n * async.parallel(async.reflectAll(tasks),\n * // optional callback\n * function(err, results) {\n * // values\n * // results[0].value = 'one'\n * // results[1].error = Error('bad stuff happened')\n * // results[2].value = 'two'\n * });\n *\n * // an example using an object instead of an array\n * let tasks = {\n * one: function(callback) {\n * setTimeout(function() {\n * callback(null, 'one');\n * }, 200);\n * },\n * two: function(callback) {\n * callback('two');\n * },\n * three: function(callback) {\n * setTimeout(function() {\n * callback(null, 'three');\n * }, 100);\n * }\n * };\n *\n * async.parallel(async.reflectAll(tasks),\n * // optional callback\n * function(err, results) {\n * // values\n * // results.one.value = 'one'\n * // results.two.error = 'two'\n * // results.three.value = 'three'\n * });\n */\n function reflectAll(tasks) {\n var results;\n if (Array.isArray(tasks)) {\n results = tasks.map(reflect);\n } else {\n results = {};\n Object.keys(tasks).forEach(key => {\n results[key] = reflect.call(this, tasks[key]);\n });\n }\n return results;\n }\n\n function reject(eachfn, arr, _iteratee, callback) {\n const iteratee = wrapAsync(_iteratee);\n return _filter(eachfn, arr, (value, cb) => {\n iteratee(value, (err, v) => {\n cb(err, !v);\n });\n }, callback);\n }\n\n /**\n * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test.\n *\n * @name reject\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.filter]{@link module:Collections.filter}\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {Function} iteratee - An async truth test to apply to each item in\n * `coll`.\n * The should complete with a boolean value as its `result`.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback is passed\n * @example\n *\n * async.reject(['file1','file2','file3'], function(filePath, callback) {\n * fs.access(filePath, function(err) {\n * callback(null, !err)\n * });\n * }, function(err, results) {\n * // results now equals an array of missing files\n * createFiles(results);\n * });\n */\n function reject$1 (coll, iteratee, callback) {\n return reject(eachOf$1, coll, iteratee, callback)\n }\n var reject$2 = awaitify(reject$1, 3);\n\n /**\n * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a\n * time.\n *\n * @name rejectLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.reject]{@link module:Collections.reject}\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {Function} iteratee - An async truth test to apply to each item in\n * `coll`.\n * The should complete with a boolean value as its `result`.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback is passed\n */\n function rejectLimit (coll, limit, iteratee, callback) {\n return reject(eachOfLimit(limit), coll, iteratee, callback)\n }\n var rejectLimit$1 = awaitify(rejectLimit, 4);\n\n /**\n * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time.\n *\n * @name rejectSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.reject]{@link module:Collections.reject}\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {Function} iteratee - An async truth test to apply to each item in\n * `coll`.\n * The should complete with a boolean value as its `result`.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback is passed\n */\n function rejectSeries (coll, iteratee, callback) {\n return reject(eachOfSeries$1, coll, iteratee, callback)\n }\n var rejectSeries$1 = awaitify(rejectSeries, 3);\n\n function constant$1(value) {\n return function () {\n return value;\n }\n }\n\n /**\n * Attempts to get a successful response from `task` no more than `times` times\n * before returning an error. If the task is successful, the `callback` will be\n * passed the result of the successful task. If all attempts fail, the callback\n * will be passed the error and result (if any) of the final attempt.\n *\n * @name retry\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @see [async.retryable]{@link module:ControlFlow.retryable}\n * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an\n * object with `times` and `interval` or a number.\n * * `times` - The number of attempts to make before giving up. The default\n * is `5`.\n * * `interval` - The time to wait between retries, in milliseconds. The\n * default is `0`. The interval may also be specified as a function of the\n * retry count (see example).\n * * `errorFilter` - An optional synchronous function that is invoked on\n * erroneous result. If it returns `true` the retry attempts will continue;\n * if the function returns `false` the retry flow is aborted with the current\n * attempt's error and result being returned to the final callback.\n * Invoked with (err).\n * * If `opts` is a number, the number specifies the number of times to retry,\n * with the default interval of `0`.\n * @param {AsyncFunction} task - An async function to retry.\n * Invoked with (callback).\n * @param {Function} [callback] - An optional callback which is called when the\n * task has succeeded, or after the final failed attempt. It receives the `err`\n * and `result` arguments of the last attempt at completing the `task`. Invoked\n * with (err, results).\n * @returns {Promise} a promise if no callback provided\n *\n * @example\n *\n * // The `retry` function can be used as a stand-alone control flow by passing\n * // a callback, as shown below:\n *\n * // try calling apiMethod 3 times\n * async.retry(3, apiMethod, function(err, result) {\n * // do something with the result\n * });\n *\n * // try calling apiMethod 3 times, waiting 200 ms between each retry\n * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {\n * // do something with the result\n * });\n *\n * // try calling apiMethod 10 times with exponential backoff\n * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds)\n * async.retry({\n * times: 10,\n * interval: function(retryCount) {\n * return 50 * Math.pow(2, retryCount);\n * }\n * }, apiMethod, function(err, result) {\n * // do something with the result\n * });\n *\n * // try calling apiMethod the default 5 times no delay between each retry\n * async.retry(apiMethod, function(err, result) {\n * // do something with the result\n * });\n *\n * // try calling apiMethod only when error condition satisfies, all other\n * // errors will abort the retry control flow and return to final callback\n * async.retry({\n * errorFilter: function(err) {\n * return err.message === 'Temporary error'; // only retry on a specific error\n * }\n * }, apiMethod, function(err, result) {\n * // do something with the result\n * });\n *\n * // to retry individual methods that are not as reliable within other\n * // control flow functions, use the `retryable` wrapper:\n * async.auto({\n * users: api.getUsers.bind(api),\n * payments: async.retryable(3, api.getPayments.bind(api))\n * }, function(err, results) {\n * // do something with the results\n * });\n *\n */\n const DEFAULT_TIMES = 5;\n const DEFAULT_INTERVAL = 0;\n\n function retry(opts, task, callback) {\n var options = {\n times: DEFAULT_TIMES,\n intervalFunc: constant$1(DEFAULT_INTERVAL)\n };\n\n if (arguments.length < 3 && typeof opts === 'function') {\n callback = task || promiseCallback();\n task = opts;\n } else {\n parseTimes(options, opts);\n callback = callback || promiseCallback();\n }\n\n if (typeof task !== 'function') {\n throw new Error(\"Invalid arguments for async.retry\");\n }\n\n var _task = wrapAsync(task);\n\n var attempt = 1;\n function retryAttempt() {\n _task((err, ...args) => {\n if (err === false) return\n if (err && attempt++ < options.times &&\n (typeof options.errorFilter != 'function' ||\n options.errorFilter(err))) {\n setTimeout(retryAttempt, options.intervalFunc(attempt - 1));\n } else {\n callback(err, ...args);\n }\n });\n }\n\n retryAttempt();\n return callback[PROMISE_SYMBOL]\n }\n\n function parseTimes(acc, t) {\n if (typeof t === 'object') {\n acc.times = +t.times || DEFAULT_TIMES;\n\n acc.intervalFunc = typeof t.interval === 'function' ?\n t.interval :\n constant$1(+t.interval || DEFAULT_INTERVAL);\n\n acc.errorFilter = t.errorFilter;\n } else if (typeof t === 'number' || typeof t === 'string') {\n acc.times = +t || DEFAULT_TIMES;\n } else {\n throw new Error(\"Invalid arguments for async.retry\");\n }\n }\n\n /**\n * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method\n * wraps a task and makes it retryable, rather than immediately calling it\n * with retries.\n *\n * @name retryable\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.retry]{@link module:ControlFlow.retry}\n * @category Control Flow\n * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional\n * options, exactly the same as from `retry`, except for a `opts.arity` that\n * is the arity of the `task` function, defaulting to `task.length`\n * @param {AsyncFunction} task - the asynchronous function to wrap.\n * This function will be passed any arguments passed to the returned wrapper.\n * Invoked with (...args, callback).\n * @returns {AsyncFunction} The wrapped function, which when invoked, will\n * retry on an error, based on the parameters specified in `opts`.\n * This function will accept the same parameters as `task`.\n * @example\n *\n * async.auto({\n * dep1: async.retryable(3, getFromFlakyService),\n * process: [\"dep1\", async.retryable(3, function (results, cb) {\n * maybeProcessData(results.dep1, cb);\n * })]\n * }, callback);\n */\n function retryable (opts, task) {\n if (!task) {\n task = opts;\n opts = null;\n }\n let arity = (opts && opts.arity) || task.length;\n if (isAsync(task)) {\n arity += 1;\n }\n var _task = wrapAsync(task);\n return initialParams((args, callback) => {\n if (args.length < arity - 1 || callback == null) {\n args.push(callback);\n callback = promiseCallback();\n }\n function taskFn(cb) {\n _task(...args, cb);\n }\n\n if (opts) retry(opts, taskFn, callback);\n else retry(taskFn, callback);\n\n return callback[PROMISE_SYMBOL]\n });\n }\n\n /**\n * Run the functions in the `tasks` collection in series, each one running once\n * the previous function has completed. If any functions in the series pass an\n * error to its callback, no more functions are run, and `callback` is\n * immediately called with the value of the error. Otherwise, `callback`\n * receives an array of results when `tasks` have completed.\n *\n * It is also possible to use an object instead of an array. Each property will\n * be run as a function, and the results will be passed to the final `callback`\n * as an object instead of an array. This can be a more readable way of handling\n * results from {@link async.series}.\n *\n * **Note** that while many implementations preserve the order of object\n * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6)\n * explicitly states that\n *\n * > The mechanics and order of enumerating the properties is not specified.\n *\n * So if you rely on the order in which your series of functions are executed,\n * and want this to work on all platforms, consider using an array.\n *\n * @name series\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing\n * [async functions]{@link AsyncFunction} to run in series.\n * Each function can complete with any number of optional `result` values.\n * @param {Function} [callback] - An optional callback to run once all the\n * functions have completed. This function gets a results array (or object)\n * containing all the result arguments passed to the `task` callbacks. Invoked\n * with (err, result).\n * @return {Promise} a promise, if no callback is passed\n * @example\n * async.series([\n * function(callback) {\n * // do some stuff ...\n * callback(null, 'one');\n * },\n * function(callback) {\n * // do some more stuff ...\n * callback(null, 'two');\n * }\n * ],\n * // optional callback\n * function(err, results) {\n * // results is now equal to ['one', 'two']\n * });\n *\n * async.series({\n * one: function(callback) {\n * setTimeout(function() {\n * callback(null, 1);\n * }, 200);\n * },\n * two: function(callback){\n * setTimeout(function() {\n * callback(null, 2);\n * }, 100);\n * }\n * }, function(err, results) {\n * // results is now equal to: {one: 1, two: 2}\n * });\n */\n function series(tasks, callback) {\n return parallel(eachOfSeries$1, tasks, callback);\n }\n\n /**\n * Returns `true` if at least one element in the `coll` satisfies an async test.\n * If any iteratee call returns `true`, the main `callback` is immediately\n * called.\n *\n * @name some\n * @static\n * @memberOf module:Collections\n * @method\n * @alias any\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async truth test to apply to each item\n * in the collections in parallel.\n * The iteratee should complete with a boolean `result` value.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called as soon as any\n * iteratee returns `true`, or after all the iteratee functions have finished.\n * Result will be either `true` or `false` depending on the values of the async\n * tests. Invoked with (err, result).\n * @returns {Promise} a promise, if no callback provided\n * @example\n *\n * async.some(['file1','file2','file3'], function(filePath, callback) {\n * fs.access(filePath, function(err) {\n * callback(null, !err)\n * });\n * }, function(err, result) {\n * // if result is true then at least one of the files exists\n * });\n */\n function some(coll, iteratee, callback) {\n return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback)\n }\n var some$1 = awaitify(some, 3);\n\n /**\n * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time.\n *\n * @name someLimit\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.some]{@link module:Collections.some}\n * @alias anyLimit\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - An async truth test to apply to each item\n * in the collections in parallel.\n * The iteratee should complete with a boolean `result` value.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called as soon as any\n * iteratee returns `true`, or after all the iteratee functions have finished.\n * Result will be either `true` or `false` depending on the values of the async\n * tests. Invoked with (err, result).\n * @returns {Promise} a promise, if no callback provided\n */\n function someLimit(coll, limit, iteratee, callback) {\n return _createTester(Boolean, res => res)(eachOfLimit(limit), coll, iteratee, callback)\n }\n var someLimit$1 = awaitify(someLimit, 4);\n\n /**\n * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time.\n *\n * @name someSeries\n * @static\n * @memberOf module:Collections\n * @method\n * @see [async.some]{@link module:Collections.some}\n * @alias anySeries\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async truth test to apply to each item\n * in the collections in series.\n * The iteratee should complete with a boolean `result` value.\n * Invoked with (item, callback).\n * @param {Function} [callback] - A callback which is called as soon as any\n * iteratee returns `true`, or after all the iteratee functions have finished.\n * Result will be either `true` or `false` depending on the values of the async\n * tests. Invoked with (err, result).\n * @returns {Promise} a promise, if no callback provided\n */\n function someSeries(coll, iteratee, callback) {\n return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback)\n }\n var someSeries$1 = awaitify(someSeries, 3);\n\n /**\n * Sorts a list by the results of running each `coll` value through an async\n * `iteratee`.\n *\n * @name sortBy\n * @static\n * @memberOf module:Collections\n * @method\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {AsyncFunction} iteratee - An async function to apply to each item in\n * `coll`.\n * The iteratee should complete with a value to use as the sort criteria as\n * its `result`.\n * Invoked with (item, callback).\n * @param {Function} callback - A callback which is called after all the\n * `iteratee` functions have finished, or an error occurs. Results is the items\n * from the original `coll` sorted by the values returned by the `iteratee`\n * calls. Invoked with (err, results).\n * @returns {Promise} a promise, if no callback passed\n * @example\n *\n * async.sortBy(['file1','file2','file3'], function(file, callback) {\n * fs.stat(file, function(err, stats) {\n * callback(err, stats.mtime);\n * });\n * }, function(err, results) {\n * // results is now the original array of files sorted by\n * // modified date\n * });\n *\n * // By modifying the callback parameter the\n * // sorting order can be influenced:\n *\n * // ascending order\n * async.sortBy([1,9,3,5], function(x, callback) {\n * callback(null, x);\n * }, function(err,result) {\n * // result callback\n * });\n *\n * // descending order\n * async.sortBy([1,9,3,5], function(x, callback) {\n * callback(null, x*-1); //<- x*-1 instead of x, turns the order around\n * }, function(err,result) {\n * // result callback\n * });\n */\n function sortBy (coll, iteratee, callback) {\n var _iteratee = wrapAsync(iteratee);\n return map$1(coll, (x, iterCb) => {\n _iteratee(x, (err, criteria) => {\n if (err) return iterCb(err);\n iterCb(err, {value: x, criteria});\n });\n }, (err, results) => {\n if (err) return callback(err);\n callback(null, results.sort(comparator).map(v => v.value));\n });\n\n function comparator(left, right) {\n var a = left.criteria, b = right.criteria;\n return a < b ? -1 : a > b ? 1 : 0;\n }\n }\n var sortBy$1 = awaitify(sortBy, 3);\n\n /**\n * Sets a time limit on an asynchronous function. If the function does not call\n * its callback within the specified milliseconds, it will be called with a\n * timeout error. The code property for the error object will be `'ETIMEDOUT'`.\n *\n * @name timeout\n * @static\n * @memberOf module:Utils\n * @method\n * @category Util\n * @param {AsyncFunction} asyncFn - The async function to limit in time.\n * @param {number} milliseconds - The specified time limit.\n * @param {*} [info] - Any variable you want attached (`string`, `object`, etc)\n * to timeout Error for more information..\n * @returns {AsyncFunction} Returns a wrapped function that can be used with any\n * of the control flow functions.\n * Invoke this function with the same parameters as you would `asyncFunc`.\n * @example\n *\n * function myFunction(foo, callback) {\n * doAsyncTask(foo, function(err, data) {\n * // handle errors\n * if (err) return callback(err);\n *\n * // do some stuff ...\n *\n * // return processed data\n * return callback(null, data);\n * });\n * }\n *\n * var wrapped = async.timeout(myFunction, 1000);\n *\n * // call `wrapped` as you would `myFunction`\n * wrapped({ bar: 'bar' }, function(err, data) {\n * // if `myFunction` takes < 1000 ms to execute, `err`\n * // and `data` will have their expected values\n *\n * // else `err` will be an Error with the code 'ETIMEDOUT'\n * });\n */\n function timeout(asyncFn, milliseconds, info) {\n var fn = wrapAsync(asyncFn);\n\n return initialParams((args, callback) => {\n var timedOut = false;\n var timer;\n\n function timeoutCallback() {\n var name = asyncFn.name || 'anonymous';\n var error = new Error('Callback function \"' + name + '\" timed out.');\n error.code = 'ETIMEDOUT';\n if (info) {\n error.info = info;\n }\n timedOut = true;\n callback(error);\n }\n\n args.push((...cbArgs) => {\n if (!timedOut) {\n callback(...cbArgs);\n clearTimeout(timer);\n }\n });\n\n // setup timer and call original function\n timer = setTimeout(timeoutCallback, milliseconds);\n fn(...args);\n });\n }\n\n function range(size) {\n var result = Array(size);\n while (size--) {\n result[size] = size;\n }\n return result;\n }\n\n /**\n * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a\n * time.\n *\n * @name timesLimit\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.times]{@link module:ControlFlow.times}\n * @category Control Flow\n * @param {number} count - The number of times to run the function.\n * @param {number} limit - The maximum number of async operations at a time.\n * @param {AsyncFunction} iteratee - The async function to call `n` times.\n * Invoked with the iteration index and a callback: (n, next).\n * @param {Function} callback - see [async.map]{@link module:Collections.map}.\n * @returns {Promise} a promise, if no callback is provided\n */\n function timesLimit(count, limit, iteratee, callback) {\n var _iteratee = wrapAsync(iteratee);\n return mapLimit$1(range(count), limit, _iteratee, callback);\n }\n\n /**\n * Calls the `iteratee` function `n` times, and accumulates results in the same\n * manner you would use with [map]{@link module:Collections.map}.\n *\n * @name times\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.map]{@link module:Collections.map}\n * @category Control Flow\n * @param {number} n - The number of times to run the function.\n * @param {AsyncFunction} iteratee - The async function to call `n` times.\n * Invoked with the iteration index and a callback: (n, next).\n * @param {Function} callback - see {@link module:Collections.map}.\n * @returns {Promise} a promise, if no callback is provided\n * @example\n *\n * // Pretend this is some complicated async factory\n * var createUser = function(id, callback) {\n * callback(null, {\n * id: 'user' + id\n * });\n * };\n *\n * // generate 5 users\n * async.times(5, function(n, next) {\n * createUser(n, function(err, user) {\n * next(err, user);\n * });\n * }, function(err, users) {\n * // we should now have 5 users\n * });\n */\n function times (n, iteratee, callback) {\n return timesLimit(n, Infinity, iteratee, callback)\n }\n\n /**\n * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time.\n *\n * @name timesSeries\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.times]{@link module:ControlFlow.times}\n * @category Control Flow\n * @param {number} n - The number of times to run the function.\n * @param {AsyncFunction} iteratee - The async function to call `n` times.\n * Invoked with the iteration index and a callback: (n, next).\n * @param {Function} callback - see {@link module:Collections.map}.\n * @returns {Promise} a promise, if no callback is provided\n */\n function timesSeries (n, iteratee, callback) {\n return timesLimit(n, 1, iteratee, callback)\n }\n\n /**\n * A relative of `reduce`. Takes an Object or Array, and iterates over each\n * element in parallel, each step potentially mutating an `accumulator` value.\n * The type of the accumulator defaults to the type of collection passed in.\n *\n * @name transform\n * @static\n * @memberOf module:Collections\n * @method\n * @category Collection\n * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.\n * @param {*} [accumulator] - The initial state of the transform. If omitted,\n * it will default to an empty Object or Array, depending on the type of `coll`\n * @param {AsyncFunction} iteratee - A function applied to each item in the\n * collection that potentially modifies the accumulator.\n * Invoked with (accumulator, item, key, callback).\n * @param {Function} [callback] - A callback which is called after all the\n * `iteratee` functions have finished. Result is the transformed accumulator.\n * Invoked with (err, result).\n * @returns {Promise} a promise, if no callback provided\n * @example\n *\n * async.transform([1,2,3], function(acc, item, index, callback) {\n * // pointless async:\n * process.nextTick(function() {\n * acc[index] = item * 2\n * callback(null)\n * });\n * }, function(err, result) {\n * // result is now equal to [2, 4, 6]\n * });\n *\n * @example\n *\n * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) {\n * setImmediate(function () {\n * obj[key] = val * 2;\n * callback();\n * })\n * }, function (err, result) {\n * // result is equal to {a: 2, b: 4, c: 6}\n * })\n */\n function transform (coll, accumulator, iteratee, callback) {\n if (arguments.length <= 3 && typeof accumulator === 'function') {\n callback = iteratee;\n iteratee = accumulator;\n accumulator = Array.isArray(coll) ? [] : {};\n }\n callback = once(callback || promiseCallback());\n var _iteratee = wrapAsync(iteratee);\n\n eachOf$1(coll, (v, k, cb) => {\n _iteratee(accumulator, v, k, cb);\n }, err => callback(err, accumulator));\n return callback[PROMISE_SYMBOL]\n }\n\n /**\n * It runs each task in series but stops whenever any of the functions were\n * successful. If one of the tasks were successful, the `callback` will be\n * passed the result of the successful task. If all tasks fail, the callback\n * will be passed the error and result (if any) of the final attempt.\n *\n * @name tryEach\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to\n * run, each function is passed a `callback(err, result)` it must call on\n * completion with an error `err` (which can be `null`) and an optional `result`\n * value.\n * @param {Function} [callback] - An optional callback which is called when one\n * of the tasks has succeeded, or all have failed. It receives the `err` and\n * `result` arguments of the last attempt at completing the `task`. Invoked with\n * (err, results).\n * @returns {Promise} a promise, if no callback is passed\n * @example\n * async.tryEach([\n * function getDataFromFirstWebsite(callback) {\n * // Try getting the data from the first website\n * callback(err, data);\n * },\n * function getDataFromSecondWebsite(callback) {\n * // First website failed,\n * // Try getting the data from the backup website\n * callback(err, data);\n * }\n * ],\n * // optional callback\n * function(err, results) {\n * Now do something with the data.\n * });\n *\n */\n function tryEach(tasks, callback) {\n var error = null;\n var result;\n return eachSeries$1(tasks, (task, taskCb) => {\n wrapAsync(task)((err, ...args) => {\n if (err === false) return taskCb(err);\n\n if (args.length < 2) {\n [result] = args;\n } else {\n result = args;\n }\n error = err;\n taskCb(err ? null : {});\n });\n }, () => callback(error, result));\n }\n\n var tryEach$1 = awaitify(tryEach);\n\n /**\n * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original,\n * unmemoized form. Handy for testing.\n *\n * @name unmemoize\n * @static\n * @memberOf module:Utils\n * @method\n * @see [async.memoize]{@link module:Utils.memoize}\n * @category Util\n * @param {AsyncFunction} fn - the memoized function\n * @returns {AsyncFunction} a function that calls the original unmemoized function\n */\n function unmemoize(fn) {\n return (...args) => {\n return (fn.unmemoized || fn)(...args);\n };\n }\n\n /**\n * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when\n * stopped, or an error occurs.\n *\n * @name whilst\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {AsyncFunction} test - asynchronous truth test to perform before each\n * execution of `iteratee`. Invoked with ().\n * @param {AsyncFunction} iteratee - An async function which is called each time\n * `test` passes. Invoked with (callback).\n * @param {Function} [callback] - A callback which is called after the test\n * function has failed and repeated execution of `iteratee` has stopped. `callback`\n * will be passed an error and any arguments passed to the final `iteratee`'s\n * callback. Invoked with (err, [results]);\n * @returns {Promise} a promise, if no callback is passed\n * @example\n *\n * var count = 0;\n * async.whilst(\n * function test(cb) { cb(null, count < 5); },\n * function iter(callback) {\n * count++;\n * setTimeout(function() {\n * callback(null, count);\n * }, 1000);\n * },\n * function (err, n) {\n * // 5 seconds have passed, n = 5\n * }\n * );\n */\n function whilst(test, iteratee, callback) {\n callback = onlyOnce(callback);\n var _fn = wrapAsync(iteratee);\n var _test = wrapAsync(test);\n var results = [];\n\n function next(err, ...rest) {\n if (err) return callback(err);\n results = rest;\n if (err === false) return;\n _test(check);\n }\n\n function check(err, truth) {\n if (err) return callback(err);\n if (err === false) return;\n if (!truth) return callback(null, ...results);\n _fn(next);\n }\n\n return _test(check);\n }\n var whilst$1 = awaitify(whilst, 3);\n\n /**\n * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when\n * stopped, or an error occurs. `callback` will be passed an error and any\n * arguments passed to the final `iteratee`'s callback.\n *\n * The inverse of [whilst]{@link module:ControlFlow.whilst}.\n *\n * @name until\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @see [async.whilst]{@link module:ControlFlow.whilst}\n * @category Control Flow\n * @param {AsyncFunction} test - asynchronous truth test to perform before each\n * execution of `iteratee`. Invoked with (callback).\n * @param {AsyncFunction} iteratee - An async function which is called each time\n * `test` fails. Invoked with (callback).\n * @param {Function} [callback] - A callback which is called after the test\n * function has passed and repeated execution of `iteratee` has stopped. `callback`\n * will be passed an error and any arguments passed to the final `iteratee`'s\n * callback. Invoked with (err, [results]);\n * @returns {Promise} a promise, if a callback is not passed\n *\n * @example\n * const results = []\n * let finished = false\n * async.until(function test(page, cb) {\n * cb(null, finished)\n * }, function iter(next) {\n * fetchPage(url, (err, body) => {\n * if (err) return next(err)\n * results = results.concat(body.objects)\n * finished = !!body.next\n * next(err)\n * })\n * }, function done (err) {\n * // all pages have been fetched\n * })\n */\n function until(test, iteratee, callback) {\n const _test = wrapAsync(test);\n return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback);\n }\n\n /**\n * Runs the `tasks` array of functions in series, each passing their results to\n * the next in the array. However, if any of the `tasks` pass an error to their\n * own callback, the next function is not executed, and the main `callback` is\n * immediately called with the error.\n *\n * @name waterfall\n * @static\n * @memberOf module:ControlFlow\n * @method\n * @category Control Flow\n * @param {Array} tasks - An array of [async functions]{@link AsyncFunction}\n * to run.\n * Each function should complete with any number of `result` values.\n * The `result` values will be passed as arguments, in order, to the next task.\n * @param {Function} [callback] - An optional callback to run once all the\n * functions have completed. This will be passed the results of the last task's\n * callback. Invoked with (err, [results]).\n * @returns undefined\n * @example\n *\n * async.waterfall([\n * function(callback) {\n * callback(null, 'one', 'two');\n * },\n * function(arg1, arg2, callback) {\n * // arg1 now equals 'one' and arg2 now equals 'two'\n * callback(null, 'three');\n * },\n * function(arg1, callback) {\n * // arg1 now equals 'three'\n * callback(null, 'done');\n * }\n * ], function (err, result) {\n * // result now equals 'done'\n * });\n *\n * // Or, with named functions:\n * async.waterfall([\n * myFirstFunction,\n * mySecondFunction,\n * myLastFunction,\n * ], function (err, result) {\n * // result now equals 'done'\n * });\n * function myFirstFunction(callback) {\n * callback(null, 'one', 'two');\n * }\n * function mySecondFunction(arg1, arg2, callback) {\n * // arg1 now equals 'one' and arg2 now equals 'two'\n * callback(null, 'three');\n * }\n * function myLastFunction(arg1, callback) {\n * // arg1 now equals 'three'\n * callback(null, 'done');\n * }\n */\n function waterfall (tasks, callback) {\n callback = once(callback);\n if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions'));\n if (!tasks.length) return callback();\n var taskIndex = 0;\n\n function nextTask(args) {\n var task = wrapAsync(tasks[taskIndex++]);\n task(...args, onlyOnce(next));\n }\n\n function next(err, ...args) {\n if (err === false) return\n if (err || taskIndex === tasks.length) {\n return callback(err, ...args);\n }\n nextTask(args);\n }\n\n nextTask([]);\n }\n\n var waterfall$1 = awaitify(waterfall);\n\n /**\n * An \"async function\" in the context of Async is an asynchronous function with\n * a variable number of parameters, with the final parameter being a callback.\n * (`function (arg1, arg2, ..., callback) {}`)\n * The final callback is of the form `callback(err, results...)`, which must be\n * called once the function is completed. The callback should be called with a\n * Error as its first argument to signal that an error occurred.\n * Otherwise, if no error occurred, it should be called with `null` as the first\n * argument, and any additional `result` arguments that may apply, to signal\n * successful completion.\n * The callback must be called exactly once, ideally on a later tick of the\n * JavaScript event loop.\n *\n * This type of function is also referred to as a \"Node-style async function\",\n * or a \"continuation passing-style function\" (CPS). Most of the methods of this\n * library are themselves CPS/Node-style async functions, or functions that\n * return CPS/Node-style async functions.\n *\n * Wherever we accept a Node-style async function, we also directly accept an\n * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}.\n * In this case, the `async` function will not be passed a final callback\n * argument, and any thrown error will be used as the `err` argument of the\n * implicit callback, and the return value will be used as the `result` value.\n * (i.e. a `rejected` of the returned Promise becomes the `err` callback\n * argument, and a `resolved` value becomes the `result`.)\n *\n * Note, due to JavaScript limitations, we can only detect native `async`\n * functions and not transpilied implementations.\n * Your environment must have `async`/`await` support for this to work.\n * (e.g. Node > v7.6, or a recent version of a modern browser).\n * If you are using `async` functions through a transpiler (e.g. Babel), you\n * must still wrap the function with [asyncify]{@link module:Utils.asyncify},\n * because the `async function` will be compiled to an ordinary function that\n * returns a promise.\n *\n * @typedef {Function} AsyncFunction\n * @static\n */\n\n var index = {\n apply,\n applyEach: applyEach$1,\n applyEachSeries,\n asyncify,\n auto,\n autoInject,\n cargo,\n cargoQueue: cargo$1,\n compose,\n concat: concat$1,\n concatLimit: concatLimit$1,\n concatSeries: concatSeries$1,\n constant,\n detect: detect$1,\n detectLimit: detectLimit$1,\n detectSeries: detectSeries$1,\n dir,\n doUntil,\n doWhilst: doWhilst$1,\n each,\n eachLimit: eachLimit$2,\n eachOf: eachOf$1,\n eachOfLimit: eachOfLimit$2,\n eachOfSeries: eachOfSeries$1,\n eachSeries: eachSeries$1,\n ensureAsync,\n every: every$1,\n everyLimit: everyLimit$1,\n everySeries: everySeries$1,\n filter: filter$1,\n filterLimit: filterLimit$1,\n filterSeries: filterSeries$1,\n forever: forever$1,\n groupBy,\n groupByLimit: groupByLimit$1,\n groupBySeries,\n log,\n map: map$1,\n mapLimit: mapLimit$1,\n mapSeries: mapSeries$1,\n mapValues,\n mapValuesLimit: mapValuesLimit$1,\n mapValuesSeries,\n memoize,\n nextTick,\n parallel: parallel$1,\n parallelLimit,\n priorityQueue,\n queue: queue$1,\n race: race$1,\n reduce: reduce$1,\n reduceRight,\n reflect,\n reflectAll,\n reject: reject$2,\n rejectLimit: rejectLimit$1,\n rejectSeries: rejectSeries$1,\n retry,\n retryable,\n seq,\n series,\n setImmediate: setImmediate$1,\n some: some$1,\n someLimit: someLimit$1,\n someSeries: someSeries$1,\n sortBy: sortBy$1,\n timeout,\n times,\n timesLimit,\n timesSeries,\n transform,\n tryEach: tryEach$1,\n unmemoize,\n until,\n waterfall: waterfall$1,\n whilst: whilst$1,\n\n // aliases\n all: every$1,\n allLimit: everyLimit$1,\n allSeries: everySeries$1,\n any: some$1,\n anyLimit: someLimit$1,\n anySeries: someSeries$1,\n find: detect$1,\n findLimit: detectLimit$1,\n findSeries: detectSeries$1,\n flatMap: concat$1,\n flatMapLimit: concatLimit$1,\n flatMapSeries: concatSeries$1,\n forEach: each,\n forEachSeries: eachSeries$1,\n forEachLimit: eachLimit$2,\n forEachOf: eachOf$1,\n forEachOfSeries: eachOfSeries$1,\n forEachOfLimit: eachOfLimit$2,\n inject: reduce$1,\n foldl: reduce$1,\n foldr: reduceRight,\n select: filter$1,\n selectLimit: filterLimit$1,\n selectSeries: filterSeries$1,\n wrapSync: asyncify,\n during: whilst$1,\n doDuring: doWhilst$1\n };\n\n exports.default = index;\n exports.apply = apply;\n exports.applyEach = applyEach$1;\n exports.applyEachSeries = applyEachSeries;\n exports.asyncify = asyncify;\n exports.auto = auto;\n exports.autoInject = autoInject;\n exports.cargo = cargo;\n exports.cargoQueue = cargo$1;\n exports.compose = compose;\n exports.concat = concat$1;\n exports.concatLimit = concatLimit$1;\n exports.concatSeries = concatSeries$1;\n exports.constant = constant;\n exports.detect = detect$1;\n exports.detectLimit = detectLimit$1;\n exports.detectSeries = detectSeries$1;\n exports.dir = dir;\n exports.doUntil = doUntil;\n exports.doWhilst = doWhilst$1;\n exports.each = each;\n exports.eachLimit = eachLimit$2;\n exports.eachOf = eachOf$1;\n exports.eachOfLimit = eachOfLimit$2;\n exports.eachOfSeries = eachOfSeries$1;\n exports.eachSeries = eachSeries$1;\n exports.ensureAsync = ensureAsync;\n exports.every = every$1;\n exports.everyLimit = everyLimit$1;\n exports.everySeries = everySeries$1;\n exports.filter = filter$1;\n exports.filterLimit = filterLimit$1;\n exports.filterSeries = filterSeries$1;\n exports.forever = forever$1;\n exports.groupBy = groupBy;\n exports.groupByLimit = groupByLimit$1;\n exports.groupBySeries = groupBySeries;\n exports.log = log;\n exports.map = map$1;\n exports.mapLimit = mapLimit$1;\n exports.mapSeries = mapSeries$1;\n exports.mapValues = mapValues;\n exports.mapValuesLimit = mapValuesLimit$1;\n exports.mapValuesSeries = mapValuesSeries;\n exports.memoize = memoize;\n exports.nextTick = nextTick;\n exports.parallel = parallel$1;\n exports.parallelLimit = parallelLimit;\n exports.priorityQueue = priorityQueue;\n exports.queue = queue$1;\n exports.race = race$1;\n exports.reduce = reduce$1;\n exports.reduceRight = reduceRight;\n exports.reflect = reflect;\n exports.reflectAll = reflectAll;\n exports.reject = reject$2;\n exports.rejectLimit = rejectLimit$1;\n exports.rejectSeries = rejectSeries$1;\n exports.retry = retry;\n exports.retryable = retryable;\n exports.seq = seq;\n exports.series = series;\n exports.setImmediate = setImmediate$1;\n exports.some = some$1;\n exports.someLimit = someLimit$1;\n exports.someSeries = someSeries$1;\n exports.sortBy = sortBy$1;\n exports.timeout = timeout;\n exports.times = times;\n exports.timesLimit = timesLimit;\n exports.timesSeries = timesSeries;\n exports.transform = transform;\n exports.tryEach = tryEach$1;\n exports.unmemoize = unmemoize;\n exports.until = until;\n exports.waterfall = waterfall$1;\n exports.whilst = whilst$1;\n exports.all = every$1;\n exports.allLimit = everyLimit$1;\n exports.allSeries = everySeries$1;\n exports.any = some$1;\n exports.anyLimit = someLimit$1;\n exports.anySeries = someSeries$1;\n exports.find = detect$1;\n exports.findLimit = detectLimit$1;\n exports.findSeries = detectSeries$1;\n exports.flatMap = concat$1;\n exports.flatMapLimit = concatLimit$1;\n exports.flatMapSeries = concatSeries$1;\n exports.forEach = each;\n exports.forEachSeries = eachSeries$1;\n exports.forEachLimit = eachLimit$2;\n exports.forEachOf = eachOf$1;\n exports.forEachOfSeries = eachOfSeries$1;\n exports.forEachOfLimit = eachOfLimit$2;\n exports.inject = reduce$1;\n exports.foldl = reduce$1;\n exports.foldr = reduceRight;\n exports.select = filter$1;\n exports.selectLimit = filterLimit$1;\n exports.selectSeries = filterSeries$1;\n exports.wrapSync = asyncify;\n exports.during = whilst$1;\n exports.doDuring = doWhilst$1;\n\n Object.defineProperty(exports, '__esModule', { value: true });\n\n})));\n","module.exports =\n{\n parallel : require('./parallel.js'),\n serial : require('./serial.js'),\n serialOrdered : require('./serialOrdered.js')\n};\n","// API\nmodule.exports = abort;\n\n/**\n * Aborts leftover active jobs\n *\n * @param {object} state - current state object\n */\nfunction abort(state)\n{\n Object.keys(state.jobs).forEach(clean.bind(state));\n\n // reset leftover jobs\n state.jobs = {};\n}\n\n/**\n * Cleans up leftover job by invoking abort function for the provided job id\n *\n * @this state\n * @param {string|number} key - job id to abort\n */\nfunction clean(key)\n{\n if (typeof this.jobs[key] == 'function')\n {\n this.jobs[key]();\n }\n}\n","var defer = require('./defer.js');\n\n// API\nmodule.exports = async;\n\n/**\n * Runs provided callback asynchronously\n * even if callback itself is not\n *\n * @param {function} callback - callback to invoke\n * @returns {function} - augmented callback\n */\nfunction async(callback)\n{\n var isAsync = false;\n\n // check if async happened\n defer(function() { isAsync = true; });\n\n return function async_callback(err, result)\n {\n if (isAsync)\n {\n callback(err, result);\n }\n else\n {\n defer(function nextTick_callback()\n {\n callback(err, result);\n });\n }\n };\n}\n","module.exports = defer;\n\n/**\n * Runs provided function on next iteration of the event loop\n *\n * @param {function} fn - function to run\n */\nfunction defer(fn)\n{\n var nextTick = typeof setImmediate == 'function'\n ? setImmediate\n : (\n typeof process == 'object' && typeof process.nextTick == 'function'\n ? process.nextTick\n : null\n );\n\n if (nextTick)\n {\n nextTick(fn);\n }\n else\n {\n setTimeout(fn, 0);\n }\n}\n","var async = require('./async.js')\n , abort = require('./abort.js')\n ;\n\n// API\nmodule.exports = iterate;\n\n/**\n * Iterates over each job object\n *\n * @param {array|object} list - array or object (named list) to iterate over\n * @param {function} iterator - iterator to run\n * @param {object} state - current job status\n * @param {function} callback - invoked when all elements processed\n */\nfunction iterate(list, iterator, state, callback)\n{\n // store current index\n var key = state['keyedList'] ? state['keyedList'][state.index] : state.index;\n\n state.jobs[key] = runJob(iterator, key, list[key], function(error, output)\n {\n // don't repeat yourself\n // skip secondary callbacks\n if (!(key in state.jobs))\n {\n return;\n }\n\n // clean up jobs\n delete state.jobs[key];\n\n if (error)\n {\n // don't process rest of the results\n // stop still active jobs\n // and reset the list\n abort(state);\n }\n else\n {\n state.results[key] = output;\n }\n\n // return salvaged results\n callback(error, state.results);\n });\n}\n\n/**\n * Runs iterator over provided job element\n *\n * @param {function} iterator - iterator to invoke\n * @param {string|number} key - key/index of the element in the list of jobs\n * @param {mixed} item - job description\n * @param {function} callback - invoked after iterator is done with the job\n * @returns {function|mixed} - job abort function or something else\n */\nfunction runJob(iterator, key, item, callback)\n{\n var aborter;\n\n // allow shortcut if iterator expects only two arguments\n if (iterator.length == 2)\n {\n aborter = iterator(item, async(callback));\n }\n // otherwise go with full three arguments\n else\n {\n aborter = iterator(item, key, async(callback));\n }\n\n return aborter;\n}\n","// API\nmodule.exports = state;\n\n/**\n * Creates initial state object\n * for iteration over list\n *\n * @param {array|object} list - list to iterate over\n * @param {function|null} sortMethod - function to use for keys sort,\n * or `null` to keep them as is\n * @returns {object} - initial state object\n */\nfunction state(list, sortMethod)\n{\n var isNamedList = !Array.isArray(list)\n , initState =\n {\n index : 0,\n keyedList: isNamedList || sortMethod ? Object.keys(list) : null,\n jobs : {},\n results : isNamedList ? {} : [],\n size : isNamedList ? Object.keys(list).length : list.length\n }\n ;\n\n if (sortMethod)\n {\n // sort array keys based on it's values\n // sort object's keys just on own merit\n initState.keyedList.sort(isNamedList ? sortMethod : function(a, b)\n {\n return sortMethod(list[a], list[b]);\n });\n }\n\n return initState;\n}\n","var abort = require('./abort.js')\n , async = require('./async.js')\n ;\n\n// API\nmodule.exports = terminator;\n\n/**\n * Terminates jobs in the attached state context\n *\n * @this AsyncKitState#\n * @param {function} callback - final callback to invoke after termination\n */\nfunction terminator(callback)\n{\n if (!Object.keys(this.jobs).length)\n {\n return;\n }\n\n // fast forward iteration index\n this.index = this.size;\n\n // abort jobs\n abort(this);\n\n // send back results we have so far\n async(callback)(null, this.results);\n}\n","var iterate = require('./lib/iterate.js')\n , initState = require('./lib/state.js')\n , terminator = require('./lib/terminator.js')\n ;\n\n// Public API\nmodule.exports = parallel;\n\n/**\n * Runs iterator over provided array elements in parallel\n *\n * @param {array|object} list - array or object (named list) to iterate over\n * @param {function} iterator - iterator to run\n * @param {function} callback - invoked when all elements processed\n * @returns {function} - jobs terminator\n */\nfunction parallel(list, iterator, callback)\n{\n var state = initState(list);\n\n while (state.index < (state['keyedList'] || list).length)\n {\n iterate(list, iterator, state, function(error, result)\n {\n if (error)\n {\n callback(error, result);\n return;\n }\n\n // looks like it's the last one\n if (Object.keys(state.jobs).length === 0)\n {\n callback(null, state.results);\n return;\n }\n });\n\n state.index++;\n }\n\n return terminator.bind(state, callback);\n}\n","var serialOrdered = require('./serialOrdered.js');\n\n// Public API\nmodule.exports = serial;\n\n/**\n * Runs iterator over provided array elements in series\n *\n * @param {array|object} list - array or object (named list) to iterate over\n * @param {function} iterator - iterator to run\n * @param {function} callback - invoked when all elements processed\n * @returns {function} - jobs terminator\n */\nfunction serial(list, iterator, callback)\n{\n return serialOrdered(list, iterator, null, callback);\n}\n","var iterate = require('./lib/iterate.js')\n , initState = require('./lib/state.js')\n , terminator = require('./lib/terminator.js')\n ;\n\n// Public API\nmodule.exports = serialOrdered;\n// sorting helpers\nmodule.exports.ascending = ascending;\nmodule.exports.descending = descending;\n\n/**\n * Runs iterator over provided sorted array elements in series\n *\n * @param {array|object} list - array or object (named list) to iterate over\n * @param {function} iterator - iterator to run\n * @param {function} sortMethod - custom sort function\n * @param {function} callback - invoked when all elements processed\n * @returns {function} - jobs terminator\n */\nfunction serialOrdered(list, iterator, sortMethod, callback)\n{\n var state = initState(list, sortMethod);\n\n iterate(list, iterator, state, function iteratorHandler(error, result)\n {\n if (error)\n {\n callback(error, result);\n return;\n }\n\n state.index++;\n\n // are we there yet?\n if (state.index < (state['keyedList'] || list).length)\n {\n iterate(list, iterator, state, iteratorHandler);\n return;\n }\n\n // done here\n callback(null, state.results);\n });\n\n return terminator.bind(state, callback);\n}\n\n/*\n * -- Sort methods\n */\n\n/**\n * sort helper to sort array elements in ascending order\n *\n * @param {mixed} a - an item to compare\n * @param {mixed} b - an item to compare\n * @returns {number} - comparison result\n */\nfunction ascending(a, b)\n{\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\n/**\n * sort helper to sort array elements in descending order\n *\n * @param {mixed} a - an item to compare\n * @param {mixed} b - an item to compare\n * @returns {number} - comparison result\n */\nfunction descending(a, b)\n{\n return -1 * ascending(a, b);\n}\n","\n/*!\n * Copyright 2010 LearnBoost \n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Module dependencies.\n */\n\nvar crypto = require('crypto')\n , parse = require('url').parse\n ;\n\n/**\n * Valid keys.\n */\n\nvar keys = \n [ 'acl'\n , 'location'\n , 'logging'\n , 'notification'\n , 'partNumber'\n , 'policy'\n , 'requestPayment'\n , 'torrent'\n , 'uploadId'\n , 'uploads'\n , 'versionId'\n , 'versioning'\n , 'versions'\n , 'website'\n ]\n\n/**\n * Return an \"Authorization\" header value with the given `options`\n * in the form of \"AWS :\"\n *\n * @param {Object} options\n * @return {String}\n * @api private\n */\n\nfunction authorization (options) {\n return 'AWS ' + options.key + ':' + sign(options)\n}\n\nmodule.exports = authorization\nmodule.exports.authorization = authorization\n\n/**\n * Simple HMAC-SHA1 Wrapper\n *\n * @param {Object} options\n * @return {String}\n * @api private\n */ \n\nfunction hmacSha1 (options) {\n return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64')\n}\n\nmodule.exports.hmacSha1 = hmacSha1\n\n/**\n * Create a base64 sha1 HMAC for `options`. \n * \n * @param {Object} options\n * @return {String}\n * @api private\n */\n\nfunction sign (options) {\n options.message = stringToSign(options)\n return hmacSha1(options)\n}\nmodule.exports.sign = sign\n\n/**\n * Create a base64 sha1 HMAC for `options`. \n *\n * Specifically to be used with S3 presigned URLs\n * \n * @param {Object} options\n * @return {String}\n * @api private\n */\n\nfunction signQuery (options) {\n options.message = queryStringToSign(options)\n return hmacSha1(options)\n}\nmodule.exports.signQuery= signQuery\n\n/**\n * Return a string for sign() with the given `options`.\n *\n * Spec:\n * \n * \\n\n * \\n\n * \\n\n * \\n\n * [headers\\n]\n * \n *\n * @param {Object} options\n * @return {String}\n * @api private\n */\n\nfunction stringToSign (options) {\n var headers = options.amazonHeaders || ''\n if (headers) headers += '\\n'\n var r = \n [ options.verb\n , options.md5\n , options.contentType\n , options.date ? options.date.toUTCString() : ''\n , headers + options.resource\n ]\n return r.join('\\n')\n}\nmodule.exports.stringToSign = stringToSign\n\n/**\n * Return a string for sign() with the given `options`, but is meant exclusively\n * for S3 presigned URLs\n *\n * Spec:\n * \n * \\n\n * \n *\n * @param {Object} options\n * @return {String}\n * @api private\n */\n\nfunction queryStringToSign (options){\n return 'GET\\n\\n\\n' + options.date + '\\n' + options.resource\n}\nmodule.exports.queryStringToSign = queryStringToSign\n\n/**\n * Perform the following:\n *\n * - ignore non-amazon headers\n * - lowercase fields\n * - sort lexicographically\n * - trim whitespace between \":\"\n * - join with newline\n *\n * @param {Object} headers\n * @return {String}\n * @api private\n */\n\nfunction canonicalizeHeaders (headers) {\n var buf = []\n , fields = Object.keys(headers)\n ;\n for (var i = 0, len = fields.length; i < len; ++i) {\n var field = fields[i]\n , val = headers[field]\n , field = field.toLowerCase()\n ;\n if (0 !== field.indexOf('x-amz')) continue\n buf.push(field + ':' + val)\n }\n return buf.sort().join('\\n')\n}\nmodule.exports.canonicalizeHeaders = canonicalizeHeaders\n\n/**\n * Perform the following:\n *\n * - ignore non sub-resources\n * - sort lexicographically\n *\n * @param {String} resource\n * @return {String}\n * @api private\n */\n\nfunction canonicalizeResource (resource) {\n var url = parse(resource, true)\n , path = url.pathname\n , buf = []\n ;\n\n Object.keys(url.query).forEach(function(key){\n if (!~keys.indexOf(key)) return\n var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key])\n buf.push(key + val)\n })\n\n return path + (buf.length ? '?' + buf.sort().join('&') : '')\n}\nmodule.exports.canonicalizeResource = canonicalizeResource\n","var aws4 = exports,\n url = require('url'),\n querystring = require('querystring'),\n crypto = require('crypto'),\n lru = require('./lru'),\n credentialsCache = lru(1000)\n\n// http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html\n\nfunction hmac(key, string, encoding) {\n return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding)\n}\n\nfunction hash(string, encoding) {\n return crypto.createHash('sha256').update(string, 'utf8').digest(encoding)\n}\n\n// This function assumes the string has already been percent encoded\nfunction encodeRfc3986(urlEncodedString) {\n return urlEncodedString.replace(/[!'()*]/g, function(c) {\n return '%' + c.charCodeAt(0).toString(16).toUpperCase()\n })\n}\n\nfunction encodeRfc3986Full(str) {\n return encodeRfc3986(encodeURIComponent(str))\n}\n\n// A bit of a combination of:\n// https://github.com/aws/aws-sdk-java-v2/blob/dc695de6ab49ad03934e1b02e7263abbd2354be0/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/AbstractAws4Signer.java#L59\n// https://github.com/aws/aws-sdk-js/blob/18cb7e5b463b46239f9fdd4a65e2ff8c81831e8f/lib/signers/v4.js#L191-L199\n// https://github.com/mhart/aws4fetch/blob/b3aed16b6f17384cf36ea33bcba3c1e9f3bdfefd/src/main.js#L25-L34\nvar HEADERS_TO_IGNORE = {\n 'authorization': true,\n 'connection': true,\n 'x-amzn-trace-id': true,\n 'user-agent': true,\n 'expect': true,\n 'presigned-expires': true,\n 'range': true,\n}\n\n// request: { path | body, [host], [method], [headers], [service], [region] }\n// credentials: { accessKeyId, secretAccessKey, [sessionToken] }\nfunction RequestSigner(request, credentials) {\n\n if (typeof request === 'string') request = url.parse(request)\n\n var headers = request.headers = (request.headers || {}),\n hostParts = (!this.service || !this.region) && this.matchHost(request.hostname || request.host || headers.Host || headers.host)\n\n this.request = request\n this.credentials = credentials || this.defaultCredentials()\n\n this.service = request.service || hostParts[0] || ''\n this.region = request.region || hostParts[1] || 'us-east-1'\n\n // SES uses a different domain from the service name\n if (this.service === 'email') this.service = 'ses'\n\n if (!request.method && request.body)\n request.method = 'POST'\n\n if (!headers.Host && !headers.host) {\n headers.Host = request.hostname || request.host || this.createHost()\n\n // If a port is specified explicitly, use it as is\n if (request.port)\n headers.Host += ':' + request.port\n }\n if (!request.hostname && !request.host)\n request.hostname = headers.Host || headers.host\n\n this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT'\n}\n\nRequestSigner.prototype.matchHost = function(host) {\n var match = (host || '').match(/([^\\.]+)\\.(?:([^\\.]*)\\.)?amazonaws\\.com(\\.cn)?$/)\n var hostParts = (match || []).slice(1, 3)\n\n // ES's hostParts are sometimes the other way round, if the value that is expected\n // to be region equals ‘es’ switch them back\n // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com\n if (hostParts[1] === 'es')\n hostParts = hostParts.reverse()\n\n if (hostParts[1] == 's3') {\n hostParts[0] = 's3'\n hostParts[1] = 'us-east-1'\n } else {\n for (var i = 0; i < 2; i++) {\n if (/^s3-/.test(hostParts[i])) {\n hostParts[1] = hostParts[i].slice(3)\n hostParts[0] = 's3'\n break\n }\n }\n }\n\n return hostParts\n}\n\n// http://docs.aws.amazon.com/general/latest/gr/rande.html\nRequestSigner.prototype.isSingleRegion = function() {\n // Special case for S3 and SimpleDB in us-east-1\n if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true\n\n return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts']\n .indexOf(this.service) >= 0\n}\n\nRequestSigner.prototype.createHost = function() {\n var region = this.isSingleRegion() ? '' : '.' + this.region,\n subdomain = this.service === 'ses' ? 'email' : this.service\n return subdomain + region + '.amazonaws.com'\n}\n\nRequestSigner.prototype.prepareRequest = function() {\n this.parsePath()\n\n var request = this.request, headers = request.headers, query\n\n if (request.signQuery) {\n\n this.parsedPath.query = query = this.parsedPath.query || {}\n\n if (this.credentials.sessionToken)\n query['X-Amz-Security-Token'] = this.credentials.sessionToken\n\n if (this.service === 's3' && !query['X-Amz-Expires'])\n query['X-Amz-Expires'] = 86400\n\n if (query['X-Amz-Date'])\n this.datetime = query['X-Amz-Date']\n else\n query['X-Amz-Date'] = this.getDateTime()\n\n query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256'\n query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString()\n query['X-Amz-SignedHeaders'] = this.signedHeaders()\n\n } else {\n\n if (!request.doNotModifyHeaders && !this.isCodeCommitGit) {\n if (request.body && !headers['Content-Type'] && !headers['content-type'])\n headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'\n\n if (request.body && !headers['Content-Length'] && !headers['content-length'])\n headers['Content-Length'] = Buffer.byteLength(request.body)\n\n if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token'])\n headers['X-Amz-Security-Token'] = this.credentials.sessionToken\n\n if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256'])\n headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex')\n\n if (headers['X-Amz-Date'] || headers['x-amz-date'])\n this.datetime = headers['X-Amz-Date'] || headers['x-amz-date']\n else\n headers['X-Amz-Date'] = this.getDateTime()\n }\n\n delete headers.Authorization\n delete headers.authorization\n }\n}\n\nRequestSigner.prototype.sign = function() {\n if (!this.parsedPath) this.prepareRequest()\n\n if (this.request.signQuery) {\n this.parsedPath.query['X-Amz-Signature'] = this.signature()\n } else {\n this.request.headers.Authorization = this.authHeader()\n }\n\n this.request.path = this.formatPath()\n\n return this.request\n}\n\nRequestSigner.prototype.getDateTime = function() {\n if (!this.datetime) {\n var headers = this.request.headers,\n date = new Date(headers.Date || headers.date || new Date)\n\n this.datetime = date.toISOString().replace(/[:\\-]|\\.\\d{3}/g, '')\n\n // Remove the trailing 'Z' on the timestamp string for CodeCommit git access\n if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1)\n }\n return this.datetime\n}\n\nRequestSigner.prototype.getDate = function() {\n return this.getDateTime().substr(0, 8)\n}\n\nRequestSigner.prototype.authHeader = function() {\n return [\n 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(),\n 'SignedHeaders=' + this.signedHeaders(),\n 'Signature=' + this.signature(),\n ].join(', ')\n}\n\nRequestSigner.prototype.signature = function() {\n var date = this.getDate(),\n cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(),\n kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey)\n if (!kCredentials) {\n kDate = hmac('AWS4' + this.credentials.secretAccessKey, date)\n kRegion = hmac(kDate, this.region)\n kService = hmac(kRegion, this.service)\n kCredentials = hmac(kService, 'aws4_request')\n credentialsCache.set(cacheKey, kCredentials)\n }\n return hmac(kCredentials, this.stringToSign(), 'hex')\n}\n\nRequestSigner.prototype.stringToSign = function() {\n return [\n 'AWS4-HMAC-SHA256',\n this.getDateTime(),\n this.credentialString(),\n hash(this.canonicalString(), 'hex'),\n ].join('\\n')\n}\n\nRequestSigner.prototype.canonicalString = function() {\n if (!this.parsedPath) this.prepareRequest()\n\n var pathStr = this.parsedPath.path,\n query = this.parsedPath.query,\n headers = this.request.headers,\n queryStr = '',\n normalizePath = this.service !== 's3',\n decodePath = this.service === 's3' || this.request.doNotEncodePath,\n decodeSlashesInPath = this.service === 's3',\n firstValOnly = this.service === 's3',\n bodyHash\n\n if (this.service === 's3' && this.request.signQuery) {\n bodyHash = 'UNSIGNED-PAYLOAD'\n } else if (this.isCodeCommitGit) {\n bodyHash = ''\n } else {\n bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] ||\n hash(this.request.body || '', 'hex')\n }\n\n if (query) {\n var reducedQuery = Object.keys(query).reduce(function(obj, key) {\n if (!key) return obj\n obj[encodeRfc3986Full(key)] = !Array.isArray(query[key]) ? query[key] :\n (firstValOnly ? query[key][0] : query[key])\n return obj\n }, {})\n var encodedQueryPieces = []\n Object.keys(reducedQuery).sort().forEach(function(key) {\n if (!Array.isArray(reducedQuery[key])) {\n encodedQueryPieces.push(key + '=' + encodeRfc3986Full(reducedQuery[key]))\n } else {\n reducedQuery[key].map(encodeRfc3986Full).sort()\n .forEach(function(val) { encodedQueryPieces.push(key + '=' + val) })\n }\n })\n queryStr = encodedQueryPieces.join('&')\n }\n if (pathStr !== '/') {\n if (normalizePath) pathStr = pathStr.replace(/\\/{2,}/g, '/')\n pathStr = pathStr.split('/').reduce(function(path, piece) {\n if (normalizePath && piece === '..') {\n path.pop()\n } else if (!normalizePath || piece !== '.') {\n if (decodePath) piece = decodeURIComponent(piece.replace(/\\+/g, ' '))\n path.push(encodeRfc3986Full(piece))\n }\n return path\n }, []).join('/')\n if (pathStr[0] !== '/') pathStr = '/' + pathStr\n if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/')\n }\n\n return [\n this.request.method || 'GET',\n pathStr,\n queryStr,\n this.canonicalHeaders() + '\\n',\n this.signedHeaders(),\n bodyHash,\n ].join('\\n')\n}\n\nRequestSigner.prototype.canonicalHeaders = function() {\n var headers = this.request.headers\n function trimAll(header) {\n return header.toString().trim().replace(/\\s+/g, ' ')\n }\n return Object.keys(headers)\n .filter(function(key) { return HEADERS_TO_IGNORE[key.toLowerCase()] == null })\n .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 })\n .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) })\n .join('\\n')\n}\n\nRequestSigner.prototype.signedHeaders = function() {\n return Object.keys(this.request.headers)\n .map(function(key) { return key.toLowerCase() })\n .filter(function(key) { return HEADERS_TO_IGNORE[key] == null })\n .sort()\n .join(';')\n}\n\nRequestSigner.prototype.credentialString = function() {\n return [\n this.getDate(),\n this.region,\n this.service,\n 'aws4_request',\n ].join('/')\n}\n\nRequestSigner.prototype.defaultCredentials = function() {\n var env = process.env\n return {\n accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY,\n secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY,\n sessionToken: env.AWS_SESSION_TOKEN,\n }\n}\n\nRequestSigner.prototype.parsePath = function() {\n var path = this.request.path || '/'\n\n // S3 doesn't always encode characters > 127 correctly and\n // all services don't encode characters > 255 correctly\n // So if there are non-reserved chars (and it's not already all % encoded), just encode them all\n if (/[^0-9A-Za-z;,/?:@&=+$\\-_.!~*'()#%]/.test(path)) {\n path = encodeURI(decodeURI(path))\n }\n\n var queryIx = path.indexOf('?'),\n query = null\n\n if (queryIx >= 0) {\n query = querystring.parse(path.slice(queryIx + 1))\n path = path.slice(0, queryIx)\n }\n\n this.parsedPath = {\n path: path,\n query: query,\n }\n}\n\nRequestSigner.prototype.formatPath = function() {\n var path = this.parsedPath.path,\n query = this.parsedPath.query\n\n if (!query) return path\n\n // Services don't support empty query string keys\n if (query[''] != null) delete query['']\n\n return path + '?' + encodeRfc3986(querystring.stringify(query))\n}\n\naws4.RequestSigner = RequestSigner\n\naws4.sign = function(request, credentials) {\n return new RequestSigner(request, credentials).sign()\n}\n","module.exports = function(size) {\n return new LruCache(size)\n}\n\nfunction LruCache(size) {\n this.capacity = size | 0\n this.map = Object.create(null)\n this.list = new DoublyLinkedList()\n}\n\nLruCache.prototype.get = function(key) {\n var node = this.map[key]\n if (node == null) return undefined\n this.used(node)\n return node.val\n}\n\nLruCache.prototype.set = function(key, val) {\n var node = this.map[key]\n if (node != null) {\n node.val = val\n } else {\n if (!this.capacity) this.prune()\n if (!this.capacity) return false\n node = new DoublyLinkedNode(key, val)\n this.map[key] = node\n this.capacity--\n }\n this.used(node)\n return true\n}\n\nLruCache.prototype.used = function(node) {\n this.list.moveToFront(node)\n}\n\nLruCache.prototype.prune = function() {\n var node = this.list.pop()\n if (node != null) {\n delete this.map[node.key]\n this.capacity++\n }\n}\n\n\nfunction DoublyLinkedList() {\n this.firstNode = null\n this.lastNode = null\n}\n\nDoublyLinkedList.prototype.moveToFront = function(node) {\n if (this.firstNode == node) return\n\n this.remove(node)\n\n if (this.firstNode == null) {\n this.firstNode = node\n this.lastNode = node\n node.prev = null\n node.next = null\n } else {\n node.prev = null\n node.next = this.firstNode\n node.next.prev = node\n this.firstNode = node\n }\n}\n\nDoublyLinkedList.prototype.pop = function() {\n var lastNode = this.lastNode\n if (lastNode != null) {\n this.remove(lastNode)\n }\n return lastNode\n}\n\nDoublyLinkedList.prototype.remove = function(node) {\n if (this.firstNode == node) {\n this.firstNode = node.next\n } else if (node.prev != null) {\n node.prev.next = node.next\n }\n if (this.lastNode == node) {\n this.lastNode = node.prev\n } else if (node.next != null) {\n node.next.prev = node.prev\n }\n}\n\n\nfunction DoublyLinkedNode(key, val) {\n this.key = key\n this.val = val\n this.prev = null\n this.next = null\n}\n","module.exports = require('./lib/axios');","'use strict';\n\nvar utils = require('./../utils');\nvar settle = require('./../core/settle');\nvar buildFullPath = require('../core/buildFullPath');\nvar buildURL = require('./../helpers/buildURL');\nvar http = require('http');\nvar https = require('https');\nvar httpFollow = require('follow-redirects').http;\nvar httpsFollow = require('follow-redirects').https;\nvar url = require('url');\nvar zlib = require('zlib');\nvar pkg = require('./../../package.json');\nvar createError = require('../core/createError');\nvar enhanceError = require('../core/enhanceError');\n\nvar isHttps = /https:?/;\n\n/**\n *\n * @param {http.ClientRequestArgs} options\n * @param {AxiosProxyConfig} proxy\n * @param {string} location\n */\nfunction setProxy(options, proxy, location) {\n options.hostname = proxy.host;\n options.host = proxy.host;\n options.port = proxy.port;\n options.path = location;\n\n // Basic proxy authorization\n if (proxy.auth) {\n var base64 = Buffer.from(proxy.auth.username + ':' + proxy.auth.password, 'utf8').toString('base64');\n options.headers['Proxy-Authorization'] = 'Basic ' + base64;\n }\n\n // If a proxy is used, any redirects must also pass through the proxy\n options.beforeRedirect = function beforeRedirect(redirection) {\n redirection.headers.host = redirection.host;\n setProxy(redirection, proxy, redirection.href);\n };\n}\n\n/*eslint consistent-return:0*/\nmodule.exports = function httpAdapter(config) {\n return new Promise(function dispatchHttpRequest(resolvePromise, rejectPromise) {\n var resolve = function resolve(value) {\n resolvePromise(value);\n };\n var reject = function reject(value) {\n rejectPromise(value);\n };\n var data = config.data;\n var headers = config.headers;\n\n // Set User-Agent (required by some servers)\n // Only set header if it hasn't been set in config\n // See https://github.com/axios/axios/issues/69\n if (!headers['User-Agent'] && !headers['user-agent']) {\n headers['User-Agent'] = 'axios/' + pkg.version;\n }\n\n if (data && !utils.isStream(data)) {\n if (Buffer.isBuffer(data)) {\n // Nothing to do...\n } else if (utils.isArrayBuffer(data)) {\n data = Buffer.from(new Uint8Array(data));\n } else if (utils.isString(data)) {\n data = Buffer.from(data, 'utf-8');\n } else {\n return reject(createError(\n 'Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream',\n config\n ));\n }\n\n // Add Content-Length header if data exists\n headers['Content-Length'] = data.length;\n }\n\n // HTTP basic authentication\n var auth = undefined;\n if (config.auth) {\n var username = config.auth.username || '';\n var password = config.auth.password || '';\n auth = username + ':' + password;\n }\n\n // Parse url\n var fullPath = buildFullPath(config.baseURL, config.url);\n var parsed = url.parse(fullPath);\n var protocol = parsed.protocol || 'http:';\n\n if (!auth && parsed.auth) {\n var urlAuth = parsed.auth.split(':');\n var urlUsername = urlAuth[0] || '';\n var urlPassword = urlAuth[1] || '';\n auth = urlUsername + ':' + urlPassword;\n }\n\n if (auth) {\n delete headers.Authorization;\n }\n\n var isHttpsRequest = isHttps.test(protocol);\n var agent = isHttpsRequest ? config.httpsAgent : config.httpAgent;\n\n var options = {\n path: buildURL(parsed.path, config.params, config.paramsSerializer).replace(/^\\?/, ''),\n method: config.method.toUpperCase(),\n headers: headers,\n agent: agent,\n agents: { http: config.httpAgent, https: config.httpsAgent },\n auth: auth\n };\n\n if (config.socketPath) {\n options.socketPath = config.socketPath;\n } else {\n options.hostname = parsed.hostname;\n options.port = parsed.port;\n }\n\n var proxy = config.proxy;\n if (!proxy && proxy !== false) {\n var proxyEnv = protocol.slice(0, -1) + '_proxy';\n var proxyUrl = process.env[proxyEnv] || process.env[proxyEnv.toUpperCase()];\n if (proxyUrl) {\n var parsedProxyUrl = url.parse(proxyUrl);\n var noProxyEnv = process.env.no_proxy || process.env.NO_PROXY;\n var shouldProxy = true;\n\n if (noProxyEnv) {\n var noProxy = noProxyEnv.split(',').map(function trim(s) {\n return s.trim();\n });\n\n shouldProxy = !noProxy.some(function proxyMatch(proxyElement) {\n if (!proxyElement) {\n return false;\n }\n if (proxyElement === '*') {\n return true;\n }\n if (proxyElement[0] === '.' &&\n parsed.hostname.substr(parsed.hostname.length - proxyElement.length) === proxyElement) {\n return true;\n }\n\n return parsed.hostname === proxyElement;\n });\n }\n\n if (shouldProxy) {\n proxy = {\n host: parsedProxyUrl.hostname,\n port: parsedProxyUrl.port,\n protocol: parsedProxyUrl.protocol\n };\n\n if (parsedProxyUrl.auth) {\n var proxyUrlAuth = parsedProxyUrl.auth.split(':');\n proxy.auth = {\n username: proxyUrlAuth[0],\n password: proxyUrlAuth[1]\n };\n }\n }\n }\n }\n\n if (proxy) {\n options.headers.host = parsed.hostname + (parsed.port ? ':' + parsed.port : '');\n setProxy(options, proxy, protocol + '//' + parsed.hostname + (parsed.port ? ':' + parsed.port : '') + options.path);\n }\n\n var transport;\n var isHttpsProxy = isHttpsRequest && (proxy ? isHttps.test(proxy.protocol) : true);\n if (config.transport) {\n transport = config.transport;\n } else if (config.maxRedirects === 0) {\n transport = isHttpsProxy ? https : http;\n } else {\n if (config.maxRedirects) {\n options.maxRedirects = config.maxRedirects;\n }\n transport = isHttpsProxy ? httpsFollow : httpFollow;\n }\n\n if (config.maxBodyLength > -1) {\n options.maxBodyLength = config.maxBodyLength;\n }\n\n // Create the request\n var req = transport.request(options, function handleResponse(res) {\n if (req.aborted) return;\n\n // uncompress the response body transparently if required\n var stream = res;\n\n // return the last request in case of redirects\n var lastRequest = res.req || req;\n\n\n // if no content, is HEAD request or decompress disabled we should not decompress\n if (res.statusCode !== 204 && lastRequest.method !== 'HEAD' && config.decompress !== false) {\n switch (res.headers['content-encoding']) {\n /*eslint default-case:0*/\n case 'gzip':\n case 'compress':\n case 'deflate':\n // add the unzipper to the body stream processing pipeline\n stream = stream.pipe(zlib.createUnzip());\n\n // remove the content-encoding in order to not confuse downstream operations\n delete res.headers['content-encoding'];\n break;\n }\n }\n\n var response = {\n status: res.statusCode,\n statusText: res.statusMessage,\n headers: res.headers,\n config: config,\n request: lastRequest\n };\n\n if (config.responseType === 'stream') {\n response.data = stream;\n settle(resolve, reject, response);\n } else {\n var responseBuffer = [];\n stream.on('data', function handleStreamData(chunk) {\n responseBuffer.push(chunk);\n\n // make sure the content length is not over the maxContentLength if specified\n if (config.maxContentLength > -1 && Buffer.concat(responseBuffer).length > config.maxContentLength) {\n stream.destroy();\n reject(createError('maxContentLength size of ' + config.maxContentLength + ' exceeded',\n config, null, lastRequest));\n }\n });\n\n stream.on('error', function handleStreamError(err) {\n if (req.aborted) return;\n reject(enhanceError(err, config, null, lastRequest));\n });\n\n stream.on('end', function handleStreamEnd() {\n var responseData = Buffer.concat(responseBuffer);\n if (config.responseType !== 'arraybuffer') {\n responseData = responseData.toString(config.responseEncoding);\n if (!config.responseEncoding || config.responseEncoding === 'utf8') {\n responseData = utils.stripBOM(responseData);\n }\n }\n\n response.data = responseData;\n settle(resolve, reject, response);\n });\n }\n });\n\n // Handle errors\n req.on('error', function handleRequestError(err) {\n if (req.aborted && err.code !== 'ERR_FR_TOO_MANY_REDIRECTS') return;\n reject(enhanceError(err, config, null, req));\n });\n\n // Handle request timeout\n if (config.timeout) {\n // Sometime, the response will be very slow, and does not respond, the connect event will be block by event loop system.\n // And timer callback will be fired, and abort() will be invoked before connection, then get \"socket hang up\" and code ECONNRESET.\n // At this time, if we have a large number of request, nodejs will hang up some socket on background. and the number will up and up.\n // And then these socket which be hang up will devoring CPU little by little.\n // ClientRequest.setTimeout will be fired on the specify milliseconds, and can make sure that abort() will be fired after connect.\n req.setTimeout(config.timeout, function handleRequestTimeout() {\n req.abort();\n reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', req));\n });\n }\n\n if (config.cancelToken) {\n // Handle cancellation\n config.cancelToken.promise.then(function onCanceled(cancel) {\n if (req.aborted) return;\n\n req.abort();\n reject(cancel);\n });\n }\n\n // Send the request\n if (utils.isStream(data)) {\n data.on('error', function handleStreamError(err) {\n reject(enhanceError(err, config, null, req));\n }).pipe(req);\n } else {\n req.end(data);\n }\n });\n};\n","'use strict';\n\nvar utils = require('./../utils');\nvar settle = require('./../core/settle');\nvar cookies = require('./../helpers/cookies');\nvar buildURL = require('./../helpers/buildURL');\nvar buildFullPath = require('../core/buildFullPath');\nvar parseHeaders = require('./../helpers/parseHeaders');\nvar isURLSameOrigin = require('./../helpers/isURLSameOrigin');\nvar createError = require('../core/createError');\n\nmodule.exports = function xhrAdapter(config) {\n return new Promise(function dispatchXhrRequest(resolve, reject) {\n var requestData = config.data;\n var requestHeaders = config.headers;\n\n if (utils.isFormData(requestData)) {\n delete requestHeaders['Content-Type']; // Let the browser set it\n }\n\n var request = new XMLHttpRequest();\n\n // HTTP basic authentication\n if (config.auth) {\n var username = config.auth.username || '';\n var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';\n requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);\n }\n\n var fullPath = buildFullPath(config.baseURL, config.url);\n request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);\n\n // Set the request timeout in MS\n request.timeout = config.timeout;\n\n // Listen for ready state\n request.onreadystatechange = function handleLoad() {\n if (!request || request.readyState !== 4) {\n return;\n }\n\n // The request errored out and we didn't get a response, this will be\n // handled by onerror instead\n // With one exception: request that using file: protocol, most browsers\n // will return status as 0 even though it's a successful request\n if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {\n return;\n }\n\n // Prepare the response\n var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;\n var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;\n var response = {\n data: responseData,\n status: request.status,\n statusText: request.statusText,\n headers: responseHeaders,\n config: config,\n request: request\n };\n\n settle(resolve, reject, response);\n\n // Clean up request\n request = null;\n };\n\n // Handle browser request cancellation (as opposed to a manual cancellation)\n request.onabort = function handleAbort() {\n if (!request) {\n return;\n }\n\n reject(createError('Request aborted', config, 'ECONNABORTED', request));\n\n // Clean up request\n request = null;\n };\n\n // Handle low level network errors\n request.onerror = function handleError() {\n // Real errors are hidden from us by the browser\n // onerror should only fire if it's a network error\n reject(createError('Network Error', config, null, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle timeout\n request.ontimeout = function handleTimeout() {\n var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';\n if (config.timeoutErrorMessage) {\n timeoutErrorMessage = config.timeoutErrorMessage;\n }\n reject(createError(timeoutErrorMessage, config, 'ECONNABORTED',\n request));\n\n // Clean up request\n request = null;\n };\n\n // Add xsrf header\n // This is only done if running in a standard browser environment.\n // Specifically not if we're in a web worker, or react-native.\n if (utils.isStandardBrowserEnv()) {\n // Add xsrf header\n var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?\n cookies.read(config.xsrfCookieName) :\n undefined;\n\n if (xsrfValue) {\n requestHeaders[config.xsrfHeaderName] = xsrfValue;\n }\n }\n\n // Add headers to the request\n if ('setRequestHeader' in request) {\n utils.forEach(requestHeaders, function setRequestHeader(val, key) {\n if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {\n // Remove Content-Type if data is undefined\n delete requestHeaders[key];\n } else {\n // Otherwise add header to the request\n request.setRequestHeader(key, val);\n }\n });\n }\n\n // Add withCredentials to request if needed\n if (!utils.isUndefined(config.withCredentials)) {\n request.withCredentials = !!config.withCredentials;\n }\n\n // Add responseType to request if needed\n if (config.responseType) {\n try {\n request.responseType = config.responseType;\n } catch (e) {\n // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2.\n // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function.\n if (config.responseType !== 'json') {\n throw e;\n }\n }\n }\n\n // Handle progress if needed\n if (typeof config.onDownloadProgress === 'function') {\n request.addEventListener('progress', config.onDownloadProgress);\n }\n\n // Not all browsers support upload events\n if (typeof config.onUploadProgress === 'function' && request.upload) {\n request.upload.addEventListener('progress', config.onUploadProgress);\n }\n\n if (config.cancelToken) {\n // Handle cancellation\n config.cancelToken.promise.then(function onCanceled(cancel) {\n if (!request) {\n return;\n }\n\n request.abort();\n reject(cancel);\n // Clean up request\n request = null;\n });\n }\n\n if (!requestData) {\n requestData = null;\n }\n\n // Send the request\n request.send(requestData);\n });\n};\n","'use strict';\n\nvar utils = require('./utils');\nvar bind = require('./helpers/bind');\nvar Axios = require('./core/Axios');\nvar mergeConfig = require('./core/mergeConfig');\nvar defaults = require('./defaults');\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n * @return {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n var context = new Axios(defaultConfig);\n var instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context);\n\n // Copy context to instance\n utils.extend(instance, context);\n\n return instance;\n}\n\n// Create the default instance to be exported\nvar axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Factory for creating new instances\naxios.create = function create(instanceConfig) {\n return createInstance(mergeConfig(axios.defaults, instanceConfig));\n};\n\n// Expose Cancel & CancelToken\naxios.Cancel = require('./cancel/Cancel');\naxios.CancelToken = require('./cancel/CancelToken');\naxios.isCancel = require('./cancel/isCancel');\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\naxios.spread = require('./helpers/spread');\n\n// Expose isAxiosError\naxios.isAxiosError = require('./helpers/isAxiosError');\n\nmodule.exports = axios;\n\n// Allow use of default import syntax in TypeScript\nmodule.exports.default = axios;\n","'use strict';\n\n/**\n * A `Cancel` is an object that is thrown when an operation is canceled.\n *\n * @class\n * @param {string=} message The message.\n */\nfunction Cancel(message) {\n this.message = message;\n}\n\nCancel.prototype.toString = function toString() {\n return 'Cancel' + (this.message ? ': ' + this.message : '');\n};\n\nCancel.prototype.__CANCEL__ = true;\n\nmodule.exports = Cancel;\n","'use strict';\n\nvar Cancel = require('./Cancel');\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @class\n * @param {Function} executor The executor function.\n */\nfunction CancelToken(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n var resolvePromise;\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n var token = this;\n executor(function cancel(message) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new Cancel(message);\n resolvePromise(token.reason);\n });\n}\n\n/**\n * Throws a `Cancel` if cancellation has been requested.\n */\nCancelToken.prototype.throwIfRequested = function throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n};\n\n/**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\nCancelToken.source = function source() {\n var cancel;\n var token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token: token,\n cancel: cancel\n };\n};\n\nmodule.exports = CancelToken;\n","'use strict';\n\nmodule.exports = function isCancel(value) {\n return !!(value && value.__CANCEL__);\n};\n","'use strict';\n\nvar utils = require('./../utils');\nvar buildURL = require('../helpers/buildURL');\nvar InterceptorManager = require('./InterceptorManager');\nvar dispatchRequest = require('./dispatchRequest');\nvar mergeConfig = require('./mergeConfig');\n\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n */\nfunction Axios(instanceConfig) {\n this.defaults = instanceConfig;\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager()\n };\n}\n\n/**\n * Dispatch a request\n *\n * @param {Object} config The config specific for this request (merged with this.defaults)\n */\nAxios.prototype.request = function request(config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof config === 'string') {\n config = arguments[1] || {};\n config.url = arguments[0];\n } else {\n config = config || {};\n }\n\n config = mergeConfig(this.defaults, config);\n\n // Set config.method\n if (config.method) {\n config.method = config.method.toLowerCase();\n } else if (this.defaults.method) {\n config.method = this.defaults.method.toLowerCase();\n } else {\n config.method = 'get';\n }\n\n // Hook up interceptors middleware\n var chain = [dispatchRequest, undefined];\n var promise = Promise.resolve(config);\n\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n chain.unshift(interceptor.fulfilled, interceptor.rejected);\n });\n\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n chain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n while (chain.length) {\n promise = promise.then(chain.shift(), chain.shift());\n }\n\n return promise;\n};\n\nAxios.prototype.getUri = function getUri(config) {\n config = mergeConfig(this.defaults, config);\n return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\\?/, '');\n};\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, config) {\n return this.request(mergeConfig(config || {}, {\n method: method,\n url: url,\n data: (config || {}).data\n }));\n };\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, data, config) {\n return this.request(mergeConfig(config || {}, {\n method: method,\n url: url,\n data: data\n }));\n };\n});\n\nmodule.exports = Axios;\n","'use strict';\n\nvar utils = require('./../utils');\n\nfunction InterceptorManager() {\n this.handlers = [];\n}\n\n/**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n *\n * @return {Number} An ID used to remove interceptor later\n */\nInterceptorManager.prototype.use = function use(fulfilled, rejected) {\n this.handlers.push({\n fulfilled: fulfilled,\n rejected: rejected\n });\n return this.handlers.length - 1;\n};\n\n/**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n */\nInterceptorManager.prototype.eject = function eject(id) {\n if (this.handlers[id]) {\n this.handlers[id] = null;\n }\n};\n\n/**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n */\nInterceptorManager.prototype.forEach = function forEach(fn) {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n};\n\nmodule.exports = InterceptorManager;\n","'use strict';\n\nvar isAbsoluteURL = require('../helpers/isAbsoluteURL');\nvar combineURLs = require('../helpers/combineURLs');\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n * @returns {string} The combined full path\n */\nmodule.exports = function buildFullPath(baseURL, requestedURL) {\n if (baseURL && !isAbsoluteURL(requestedURL)) {\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n};\n","'use strict';\n\nvar enhanceError = require('./enhanceError');\n\n/**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {Object} config The config.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n * @returns {Error} The created error.\n */\nmodule.exports = function createError(message, config, code, request, response) {\n var error = new Error(message);\n return enhanceError(error, config, code, request, response);\n};\n","'use strict';\n\nvar utils = require('./../utils');\nvar transformData = require('./transformData');\nvar isCancel = require('../cancel/isCancel');\nvar defaults = require('../defaults');\n\n/**\n * Throws a `Cancel` if cancellation has been requested.\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n * @returns {Promise} The Promise to be fulfilled\n */\nmodule.exports = function dispatchRequest(config) {\n throwIfCancellationRequested(config);\n\n // Ensure headers exist\n config.headers = config.headers || {};\n\n // Transform request data\n config.data = transformData(\n config.data,\n config.headers,\n config.transformRequest\n );\n\n // Flatten headers\n config.headers = utils.merge(\n config.headers.common || {},\n config.headers[config.method] || {},\n config.headers\n );\n\n utils.forEach(\n ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],\n function cleanHeaderConfig(method) {\n delete config.headers[method];\n }\n );\n\n var adapter = config.adapter || defaults.adapter;\n\n return adapter(config).then(function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n response.data = transformData(\n response.data,\n response.headers,\n config.transformResponse\n );\n\n return response;\n }, function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.data = transformData(\n reason.response.data,\n reason.response.headers,\n config.transformResponse\n );\n }\n }\n\n return Promise.reject(reason);\n });\n};\n","'use strict';\n\n/**\n * Update an Error with the specified config, error code, and response.\n *\n * @param {Error} error The error to update.\n * @param {Object} config The config.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n * @returns {Error} The error.\n */\nmodule.exports = function enhanceError(error, config, code, request, response) {\n error.config = config;\n if (code) {\n error.code = code;\n }\n\n error.request = request;\n error.response = response;\n error.isAxiosError = true;\n\n error.toJSON = function toJSON() {\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: this.config,\n code: this.code\n };\n };\n return error;\n};\n","'use strict';\n\nvar utils = require('../utils');\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n * @returns {Object} New object resulting from merging config2 to config1\n */\nmodule.exports = function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config2 = config2 || {};\n var config = {};\n\n var valueFromConfig2Keys = ['url', 'method', 'data'];\n var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params'];\n var defaultToConfig2Keys = [\n 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer',\n 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',\n 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress',\n 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent',\n 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding'\n ];\n var directMergeKeys = ['validateStatus'];\n\n function getMergedValue(target, source) {\n if (utils.isPlainObject(target) && utils.isPlainObject(source)) {\n return utils.merge(target, source);\n } else if (utils.isPlainObject(source)) {\n return utils.merge({}, source);\n } else if (utils.isArray(source)) {\n return source.slice();\n }\n return source;\n }\n\n function mergeDeepProperties(prop) {\n if (!utils.isUndefined(config2[prop])) {\n config[prop] = getMergedValue(config1[prop], config2[prop]);\n } else if (!utils.isUndefined(config1[prop])) {\n config[prop] = getMergedValue(undefined, config1[prop]);\n }\n }\n\n utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {\n if (!utils.isUndefined(config2[prop])) {\n config[prop] = getMergedValue(undefined, config2[prop]);\n }\n });\n\n utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties);\n\n utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {\n if (!utils.isUndefined(config2[prop])) {\n config[prop] = getMergedValue(undefined, config2[prop]);\n } else if (!utils.isUndefined(config1[prop])) {\n config[prop] = getMergedValue(undefined, config1[prop]);\n }\n });\n\n utils.forEach(directMergeKeys, function merge(prop) {\n if (prop in config2) {\n config[prop] = getMergedValue(config1[prop], config2[prop]);\n } else if (prop in config1) {\n config[prop] = getMergedValue(undefined, config1[prop]);\n }\n });\n\n var axiosKeys = valueFromConfig2Keys\n .concat(mergeDeepPropertiesKeys)\n .concat(defaultToConfig2Keys)\n .concat(directMergeKeys);\n\n var otherKeys = Object\n .keys(config1)\n .concat(Object.keys(config2))\n .filter(function filterAxiosKeys(key) {\n return axiosKeys.indexOf(key) === -1;\n });\n\n utils.forEach(otherKeys, mergeDeepProperties);\n\n return config;\n};\n","'use strict';\n\nvar createError = require('./createError');\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n */\nmodule.exports = function settle(resolve, reject, response) {\n var validateStatus = response.config.validateStatus;\n if (!response.status || !validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(createError(\n 'Request failed with status code ' + response.status,\n response.config,\n null,\n response.request,\n response\n ));\n }\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\n/**\n * Transform the data for a request or a response\n *\n * @param {Object|String} data The data to be transformed\n * @param {Array} headers The headers for the request or response\n * @param {Array|Function} fns A single function or Array of functions\n * @returns {*} The resulting transformed data\n */\nmodule.exports = function transformData(data, headers, fns) {\n /*eslint no-param-reassign:0*/\n utils.forEach(fns, function transform(fn) {\n data = fn(data, headers);\n });\n\n return data;\n};\n","'use strict';\n\nvar utils = require('./utils');\nvar normalizeHeaderName = require('./helpers/normalizeHeaderName');\n\nvar DEFAULT_CONTENT_TYPE = {\n 'Content-Type': 'application/x-www-form-urlencoded'\n};\n\nfunction setContentTypeIfUnset(headers, value) {\n if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {\n headers['Content-Type'] = value;\n }\n}\n\nfunction getDefaultAdapter() {\n var adapter;\n if (typeof XMLHttpRequest !== 'undefined') {\n // For browsers use XHR adapter\n adapter = require('./adapters/xhr');\n } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {\n // For node use HTTP adapter\n adapter = require('./adapters/http');\n }\n return adapter;\n}\n\nvar defaults = {\n adapter: getDefaultAdapter(),\n\n transformRequest: [function transformRequest(data, headers) {\n normalizeHeaderName(headers, 'Accept');\n normalizeHeaderName(headers, 'Content-Type');\n if (utils.isFormData(data) ||\n utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');\n return data.toString();\n }\n if (utils.isObject(data)) {\n setContentTypeIfUnset(headers, 'application/json;charset=utf-8');\n return JSON.stringify(data);\n }\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n /*eslint no-param-reassign:0*/\n if (typeof data === 'string') {\n try {\n data = JSON.parse(data);\n } catch (e) { /* Ignore */ }\n }\n return data;\n }],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n maxBodyLength: -1,\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n }\n};\n\ndefaults.headers = {\n common: {\n 'Accept': 'application/json, text/plain, */*'\n }\n};\n\nutils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {\n defaults.headers[method] = {};\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);\n});\n\nmodule.exports = defaults;\n","'use strict';\n\nmodule.exports = function bind(fn, thisArg) {\n return function wrap() {\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n return fn.apply(thisArg, args);\n };\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @returns {string} The formatted url\n */\nmodule.exports = function buildURL(url, params, paramsSerializer) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n\n var serializedParams;\n if (paramsSerializer) {\n serializedParams = paramsSerializer(params);\n } else if (utils.isURLSearchParams(params)) {\n serializedParams = params.toString();\n } else {\n var parts = [];\n\n utils.forEach(params, function serialize(val, key) {\n if (val === null || typeof val === 'undefined') {\n return;\n }\n\n if (utils.isArray(val)) {\n key = key + '[]';\n } else {\n val = [val];\n }\n\n utils.forEach(val, function parseValue(v) {\n if (utils.isDate(v)) {\n v = v.toISOString();\n } else if (utils.isObject(v)) {\n v = JSON.stringify(v);\n }\n parts.push(encode(key) + '=' + encode(v));\n });\n });\n\n serializedParams = parts.join('&');\n }\n\n if (serializedParams) {\n var hashmarkIndex = url.indexOf('#');\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n};\n","'use strict';\n\n/**\n * Creates a new URL by combining the specified URLs\n *\n * @param {string} baseURL The base URL\n * @param {string} relativeURL The relative URL\n * @returns {string} The combined URL\n */\nmodule.exports = function combineURLs(baseURL, relativeURL) {\n return relativeURL\n ? baseURL.replace(/\\/+$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs support document.cookie\n (function standardBrowserEnv() {\n return {\n write: function write(name, value, expires, path, domain, secure) {\n var cookie = [];\n cookie.push(name + '=' + encodeURIComponent(value));\n\n if (utils.isNumber(expires)) {\n cookie.push('expires=' + new Date(expires).toGMTString());\n }\n\n if (utils.isString(path)) {\n cookie.push('path=' + path);\n }\n\n if (utils.isString(domain)) {\n cookie.push('domain=' + domain);\n }\n\n if (secure === true) {\n cookie.push('secure');\n }\n\n document.cookie = cookie.join('; ');\n },\n\n read: function read(name) {\n var match = document.cookie.match(new RegExp('(^|;\\\\s*)(' + name + ')=([^;]*)'));\n return (match ? decodeURIComponent(match[3]) : null);\n },\n\n remove: function remove(name) {\n this.write(name, '', Date.now() - 86400000);\n }\n };\n })() :\n\n // Non standard browser env (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return {\n write: function write() {},\n read: function read() { return null; },\n remove: function remove() {}\n };\n })()\n);\n","'use strict';\n\n/**\n * Determines whether the specified URL is absolute\n *\n * @param {string} url The URL to test\n * @returns {boolean} True if the specified URL is absolute, otherwise false\n */\nmodule.exports = function isAbsoluteURL(url) {\n // A URL is considered absolute if it begins with \"://\" or \"//\" (protocol-relative URL).\n // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed\n // by any combination of letters, digits, plus, period, or hyphen.\n return /^([a-z][a-z\\d\\+\\-\\.]*:)?\\/\\//i.test(url);\n};\n","'use strict';\n\n/**\n * Determines whether the payload is an error thrown by Axios\n *\n * @param {*} payload The value to test\n * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false\n */\nmodule.exports = function isAxiosError(payload) {\n return (typeof payload === 'object') && (payload.isAxiosError === true);\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs have full support of the APIs needed to test\n // whether the request URL is of the same origin as current location.\n (function standardBrowserEnv() {\n var msie = /(msie|trident)/i.test(navigator.userAgent);\n var urlParsingNode = document.createElement('a');\n var originURL;\n\n /**\n * Parse a URL to discover it's components\n *\n * @param {String} url The URL to be parsed\n * @returns {Object}\n */\n function resolveURL(url) {\n var href = url;\n\n if (msie) {\n // IE needs attribute set twice to normalize properties\n urlParsingNode.setAttribute('href', href);\n href = urlParsingNode.href;\n }\n\n urlParsingNode.setAttribute('href', href);\n\n // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils\n return {\n href: urlParsingNode.href,\n protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',\n host: urlParsingNode.host,\n search: urlParsingNode.search ? urlParsingNode.search.replace(/^\\?/, '') : '',\n hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',\n hostname: urlParsingNode.hostname,\n port: urlParsingNode.port,\n pathname: (urlParsingNode.pathname.charAt(0) === '/') ?\n urlParsingNode.pathname :\n '/' + urlParsingNode.pathname\n };\n }\n\n originURL = resolveURL(window.location.href);\n\n /**\n * Determine if a URL shares the same origin as the current location\n *\n * @param {String} requestURL The URL to test\n * @returns {boolean} True if URL shares the same origin, otherwise false\n */\n return function isURLSameOrigin(requestURL) {\n var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;\n return (parsed.protocol === originURL.protocol &&\n parsed.host === originURL.host);\n };\n })() :\n\n // Non standard browser envs (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return function isURLSameOrigin() {\n return true;\n };\n })()\n);\n","'use strict';\n\nvar utils = require('../utils');\n\nmodule.exports = function normalizeHeaderName(headers, normalizedName) {\n utils.forEach(headers, function processHeader(value, name) {\n if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {\n headers[normalizedName] = value;\n delete headers[name];\n }\n });\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\n// Headers whose duplicates are ignored by node\n// c.f. https://nodejs.org/api/http.html#http_message_headers\nvar ignoreDuplicateOf = [\n 'age', 'authorization', 'content-length', 'content-type', 'etag',\n 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',\n 'last-modified', 'location', 'max-forwards', 'proxy-authorization',\n 'referer', 'retry-after', 'user-agent'\n];\n\n/**\n * Parse headers into an object\n *\n * ```\n * Date: Wed, 27 Aug 2014 08:58:49 GMT\n * Content-Type: application/json\n * Connection: keep-alive\n * Transfer-Encoding: chunked\n * ```\n *\n * @param {String} headers Headers needing to be parsed\n * @returns {Object} Headers parsed into an object\n */\nmodule.exports = function parseHeaders(headers) {\n var parsed = {};\n var key;\n var val;\n var i;\n\n if (!headers) { return parsed; }\n\n utils.forEach(headers.split('\\n'), function parser(line) {\n i = line.indexOf(':');\n key = utils.trim(line.substr(0, i)).toLowerCase();\n val = utils.trim(line.substr(i + 1));\n\n if (key) {\n if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {\n return;\n }\n if (key === 'set-cookie') {\n parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);\n } else {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n }\n });\n\n return parsed;\n};\n","'use strict';\n\n/**\n * Syntactic sugar for invoking a function and expanding an array for arguments.\n *\n * Common use case would be to use `Function.prototype.apply`.\n *\n * ```js\n * function f(x, y, z) {}\n * var args = [1, 2, 3];\n * f.apply(null, args);\n * ```\n *\n * With `spread` this example can be re-written.\n *\n * ```js\n * spread(function(x, y, z) {})([1, 2, 3]);\n * ```\n *\n * @param {Function} callback\n * @returns {Function}\n */\nmodule.exports = function spread(callback) {\n return function wrap(arr) {\n return callback.apply(null, arr);\n };\n};\n","'use strict';\n\nvar bind = require('./helpers/bind');\n\n/*global toString:true*/\n\n// utils is a library of generic helper functions non-specific to axios\n\nvar toString = Object.prototype.toString;\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Array, otherwise false\n */\nfunction isArray(val) {\n return toString.call(val) === '[object Array]';\n}\n\n/**\n * Determine if a value is undefined\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nfunction isUndefined(val) {\n return typeof val === 'undefined';\n}\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)\n && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nfunction isArrayBuffer(val) {\n return toString.call(val) === '[object ArrayBuffer]';\n}\n\n/**\n * Determine if a value is a FormData\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nfunction isFormData(val) {\n return (typeof FormData !== 'undefined') && (val instanceof FormData);\n}\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n var result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a String, otherwise false\n */\nfunction isString(val) {\n return typeof val === 'string';\n}\n\n/**\n * Determine if a value is a Number\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Number, otherwise false\n */\nfunction isNumber(val) {\n return typeof val === 'number';\n}\n\n/**\n * Determine if a value is an Object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Object, otherwise false\n */\nfunction isObject(val) {\n return val !== null && typeof val === 'object';\n}\n\n/**\n * Determine if a value is a plain Object\n *\n * @param {Object} val The value to test\n * @return {boolean} True if value is a plain Object, otherwise false\n */\nfunction isPlainObject(val) {\n if (toString.call(val) !== '[object Object]') {\n return false;\n }\n\n var prototype = Object.getPrototypeOf(val);\n return prototype === null || prototype === Object.prototype;\n}\n\n/**\n * Determine if a value is a Date\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Date, otherwise false\n */\nfunction isDate(val) {\n return toString.call(val) === '[object Date]';\n}\n\n/**\n * Determine if a value is a File\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a File, otherwise false\n */\nfunction isFile(val) {\n return toString.call(val) === '[object File]';\n}\n\n/**\n * Determine if a value is a Blob\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nfunction isBlob(val) {\n return toString.call(val) === '[object Blob]';\n}\n\n/**\n * Determine if a value is a Function\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nfunction isFunction(val) {\n return toString.call(val) === '[object Function]';\n}\n\n/**\n * Determine if a value is a Stream\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nfunction isStream(val) {\n return isObject(val) && isFunction(val.pipe);\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nfunction isURLSearchParams(val) {\n return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;\n}\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n * @returns {String} The String freed of excess whitespace\n */\nfunction trim(str) {\n return str.replace(/^\\s*/, '').replace(/\\s*$/, '');\n}\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n */\nfunction isStandardBrowserEnv() {\n if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||\n navigator.product === 'NativeScript' ||\n navigator.product === 'NS')) {\n return false;\n }\n return (\n typeof window !== 'undefined' &&\n typeof document !== 'undefined'\n );\n}\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n */\nfunction forEach(obj, fn) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (var i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn.call(null, obj[key], key, obj);\n }\n }\n }\n}\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n var result = {};\n function assignValue(val, key) {\n if (isPlainObject(result[key]) && isPlainObject(val)) {\n result[key] = merge(result[key], val);\n } else if (isPlainObject(val)) {\n result[key] = merge({}, val);\n } else if (isArray(val)) {\n result[key] = val.slice();\n } else {\n result[key] = val;\n }\n }\n\n for (var i = 0, l = arguments.length; i < l; i++) {\n forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n * @return {Object} The resulting value of object a\n */\nfunction extend(a, b, thisArg) {\n forEach(b, function assignValue(val, key) {\n if (thisArg && typeof val === 'function') {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n });\n return a;\n}\n\n/**\n * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n *\n * @param {string} content with BOM\n * @return {string} content value without BOM\n */\nfunction stripBOM(content) {\n if (content.charCodeAt(0) === 0xFEFF) {\n content = content.slice(1);\n }\n return content;\n}\n\nmodule.exports = {\n isArray: isArray,\n isArrayBuffer: isArrayBuffer,\n isBuffer: isBuffer,\n isFormData: isFormData,\n isArrayBufferView: isArrayBufferView,\n isString: isString,\n isNumber: isNumber,\n isObject: isObject,\n isPlainObject: isPlainObject,\n isUndefined: isUndefined,\n isDate: isDate,\n isFile: isFile,\n isBlob: isBlob,\n isFunction: isFunction,\n isStream: isStream,\n isURLSearchParams: isURLSearchParams,\n isStandardBrowserEnv: isStandardBrowserEnv,\n forEach: forEach,\n merge: merge,\n extend: extend,\n trim: trim,\n stripBOM: stripBOM\n};\n","'use strict';\nmodule.exports = balanced;\nfunction balanced(a, b, str) {\n if (a instanceof RegExp) a = maybeMatch(a, str);\n if (b instanceof RegExp) b = maybeMatch(b, str);\n\n var r = range(a, b, str);\n\n return r && {\n start: r[0],\n end: r[1],\n pre: str.slice(0, r[0]),\n body: str.slice(r[0] + a.length, r[1]),\n post: str.slice(r[1] + b.length)\n };\n}\n\nfunction maybeMatch(reg, str) {\n var m = str.match(reg);\n return m ? m[0] : null;\n}\n\nbalanced.range = range;\nfunction range(a, b, str) {\n var begs, beg, left, right, result;\n var ai = str.indexOf(a);\n var bi = str.indexOf(b, ai + 1);\n var i = ai;\n\n if (ai >= 0 && bi > 0) {\n if(a===b) {\n return [ai, bi];\n }\n begs = [];\n left = str.length;\n\n while (i >= 0 && !result) {\n if (i == ai) {\n begs.push(i);\n ai = str.indexOf(a, i + 1);\n } else if (begs.length == 1) {\n result = [ begs.pop(), bi ];\n } else {\n beg = begs.pop();\n if (beg < left) {\n left = beg;\n right = bi;\n }\n\n bi = str.indexOf(b, i + 1);\n }\n\n i = ai < bi && ai >= 0 ? ai : bi;\n }\n\n if (begs.length) {\n result = [ left, right ];\n }\n }\n\n return result;\n}\n","'use strict';\n\nvar crypto_hash_sha512 = require('tweetnacl').lowlevel.crypto_hash;\n\n/*\n * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a\n * result, it retains the original copyright and license. The two files are\n * under slightly different (but compatible) licenses, and are here combined in\n * one file.\n *\n * Credit for the actual porting work goes to:\n * Devi Mandiri \n */\n\n/*\n * The Blowfish portions are under the following license:\n *\n * Blowfish block cipher for OpenBSD\n * Copyright 1997 Niels Provos \n * All rights reserved.\n *\n * Implementation advice by David Mazieres .\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. The name of the author may not be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/*\n * The bcrypt_pbkdf portions are under the following license:\n *\n * Copyright (c) 2013 Ted Unangst \n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n\n/*\n * Performance improvements (Javascript-specific):\n *\n * Copyright 2016, Joyent Inc\n * Author: Alex Wilson \n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n */\n\n// Ported from OpenBSD bcrypt_pbkdf.c v1.9\n\nvar BLF_J = 0;\n\nvar Blowfish = function() {\n this.S = [\n new Uint32Array([\n 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,\n 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,\n 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,\n 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,\n 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,\n 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,\n 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,\n 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,\n 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,\n 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,\n 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,\n 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,\n 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,\n 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,\n 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,\n 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,\n 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,\n 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,\n 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,\n 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,\n 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,\n 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,\n 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,\n 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,\n 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,\n 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,\n 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,\n 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,\n 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,\n 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,\n 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,\n 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,\n 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,\n 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,\n 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,\n 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,\n 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,\n 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,\n 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,\n 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,\n 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,\n 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,\n 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,\n 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,\n 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,\n 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,\n 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,\n 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,\n 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,\n 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,\n 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,\n 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,\n 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,\n 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,\n 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,\n 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,\n 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,\n 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,\n 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,\n 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,\n 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,\n 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,\n 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,\n 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]),\n new Uint32Array([\n 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,\n 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,\n 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,\n 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,\n 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,\n 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,\n 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,\n 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,\n 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,\n 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,\n 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,\n 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,\n 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,\n 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,\n 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,\n 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,\n 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,\n 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,\n 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,\n 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,\n 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,\n 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,\n 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,\n 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,\n 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,\n 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,\n 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,\n 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,\n 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,\n 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,\n 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,\n 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,\n 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,\n 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,\n 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,\n 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,\n 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,\n 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,\n 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,\n 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,\n 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,\n 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,\n 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,\n 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,\n 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,\n 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,\n 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,\n 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,\n 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,\n 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,\n 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,\n 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,\n 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,\n 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,\n 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,\n 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,\n 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,\n 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,\n 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,\n 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,\n 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,\n 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,\n 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,\n 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]),\n new Uint32Array([\n 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,\n 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,\n 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,\n 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,\n 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,\n 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,\n 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,\n 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,\n 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,\n 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,\n 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,\n 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,\n 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,\n 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,\n 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,\n 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,\n 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,\n 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,\n 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,\n 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,\n 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,\n 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,\n 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,\n 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,\n 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,\n 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,\n 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,\n 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,\n 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,\n 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,\n 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,\n 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,\n 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,\n 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,\n 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,\n 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,\n 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,\n 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,\n 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,\n 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,\n 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,\n 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,\n 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,\n 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,\n 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,\n 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,\n 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,\n 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,\n 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,\n 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,\n 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,\n 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,\n 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,\n 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,\n 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,\n 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,\n 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,\n 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,\n 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,\n 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,\n 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,\n 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,\n 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,\n 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]),\n new Uint32Array([\n 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,\n 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,\n 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,\n 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,\n 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,\n 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,\n 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,\n 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,\n 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,\n 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,\n 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,\n 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,\n 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,\n 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,\n 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,\n 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,\n 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,\n 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,\n 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,\n 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,\n 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,\n 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,\n 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,\n 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,\n 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,\n 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,\n 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,\n 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,\n 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,\n 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,\n 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,\n 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,\n 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,\n 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,\n 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,\n 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,\n 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,\n 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,\n 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,\n 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,\n 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,\n 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,\n 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,\n 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,\n 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,\n 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,\n 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,\n 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,\n 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,\n 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,\n 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,\n 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,\n 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,\n 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,\n 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,\n 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,\n 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,\n 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,\n 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,\n 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,\n 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,\n 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,\n 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,\n 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6])\n ];\n this.P = new Uint32Array([\n 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,\n 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,\n 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,\n 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,\n 0x9216d5d9, 0x8979fb1b]);\n};\n\nfunction F(S, x8, i) {\n return (((S[0][x8[i+3]] +\n S[1][x8[i+2]]) ^\n S[2][x8[i+1]]) +\n S[3][x8[i]]);\n};\n\nBlowfish.prototype.encipher = function(x, x8) {\n if (x8 === undefined) {\n x8 = new Uint8Array(x.buffer);\n if (x.byteOffset !== 0)\n x8 = x8.subarray(x.byteOffset);\n }\n x[0] ^= this.P[0];\n for (var i = 1; i < 16; i += 2) {\n x[1] ^= F(this.S, x8, 0) ^ this.P[i];\n x[0] ^= F(this.S, x8, 4) ^ this.P[i+1];\n }\n var t = x[0];\n x[0] = x[1] ^ this.P[17];\n x[1] = t;\n};\n\nBlowfish.prototype.decipher = function(x) {\n var x8 = new Uint8Array(x.buffer);\n if (x.byteOffset !== 0)\n x8 = x8.subarray(x.byteOffset);\n x[0] ^= this.P[17];\n for (var i = 16; i > 0; i -= 2) {\n x[1] ^= F(this.S, x8, 0) ^ this.P[i];\n x[0] ^= F(this.S, x8, 4) ^ this.P[i-1];\n }\n var t = x[0];\n x[0] = x[1] ^ this.P[0];\n x[1] = t;\n};\n\nfunction stream2word(data, databytes){\n var i, temp = 0;\n for (i = 0; i < 4; i++, BLF_J++) {\n if (BLF_J >= databytes) BLF_J = 0;\n temp = (temp << 8) | data[BLF_J];\n }\n return temp;\n};\n\nBlowfish.prototype.expand0state = function(key, keybytes) {\n var d = new Uint32Array(2), i, k;\n var d8 = new Uint8Array(d.buffer);\n\n for (i = 0, BLF_J = 0; i < 18; i++) {\n this.P[i] ^= stream2word(key, keybytes);\n }\n BLF_J = 0;\n\n for (i = 0; i < 18; i += 2) {\n this.encipher(d, d8);\n this.P[i] = d[0];\n this.P[i+1] = d[1];\n }\n\n for (i = 0; i < 4; i++) {\n for (k = 0; k < 256; k += 2) {\n this.encipher(d, d8);\n this.S[i][k] = d[0];\n this.S[i][k+1] = d[1];\n }\n }\n};\n\nBlowfish.prototype.expandstate = function(data, databytes, key, keybytes) {\n var d = new Uint32Array(2), i, k;\n\n for (i = 0, BLF_J = 0; i < 18; i++) {\n this.P[i] ^= stream2word(key, keybytes);\n }\n\n for (i = 0, BLF_J = 0; i < 18; i += 2) {\n d[0] ^= stream2word(data, databytes);\n d[1] ^= stream2word(data, databytes);\n this.encipher(d);\n this.P[i] = d[0];\n this.P[i+1] = d[1];\n }\n\n for (i = 0; i < 4; i++) {\n for (k = 0; k < 256; k += 2) {\n d[0] ^= stream2word(data, databytes);\n d[1] ^= stream2word(data, databytes);\n this.encipher(d);\n this.S[i][k] = d[0];\n this.S[i][k+1] = d[1];\n }\n }\n BLF_J = 0;\n};\n\nBlowfish.prototype.enc = function(data, blocks) {\n for (var i = 0; i < blocks; i++) {\n this.encipher(data.subarray(i*2));\n }\n};\n\nBlowfish.prototype.dec = function(data, blocks) {\n for (var i = 0; i < blocks; i++) {\n this.decipher(data.subarray(i*2));\n }\n};\n\nvar BCRYPT_BLOCKS = 8,\n BCRYPT_HASHSIZE = 32;\n\nfunction bcrypt_hash(sha2pass, sha2salt, out) {\n var state = new Blowfish(),\n cdata = new Uint32Array(BCRYPT_BLOCKS), i,\n ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105,\n 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109,\n 105,116,101]); //\"OxychromaticBlowfishSwatDynamite\"\n\n state.expandstate(sha2salt, 64, sha2pass, 64);\n for (i = 0; i < 64; i++) {\n state.expand0state(sha2salt, 64);\n state.expand0state(sha2pass, 64);\n }\n\n for (i = 0; i < BCRYPT_BLOCKS; i++)\n cdata[i] = stream2word(ciphertext, ciphertext.byteLength);\n for (i = 0; i < 64; i++)\n state.enc(cdata, cdata.byteLength / 8);\n\n for (i = 0; i < BCRYPT_BLOCKS; i++) {\n out[4*i+3] = cdata[i] >>> 24;\n out[4*i+2] = cdata[i] >>> 16;\n out[4*i+1] = cdata[i] >>> 8;\n out[4*i+0] = cdata[i];\n }\n};\n\nfunction bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) {\n var sha2pass = new Uint8Array(64),\n sha2salt = new Uint8Array(64),\n out = new Uint8Array(BCRYPT_HASHSIZE),\n tmpout = new Uint8Array(BCRYPT_HASHSIZE),\n countsalt = new Uint8Array(saltlen+4),\n i, j, amt, stride, dest, count,\n origkeylen = keylen;\n\n if (rounds < 1)\n return -1;\n if (passlen === 0 || saltlen === 0 || keylen === 0 ||\n keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20))\n return -1;\n\n stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength);\n amt = Math.floor((keylen + stride - 1) / stride);\n\n for (i = 0; i < saltlen; i++)\n countsalt[i] = salt[i];\n\n crypto_hash_sha512(sha2pass, pass, passlen);\n\n for (count = 1; keylen > 0; count++) {\n countsalt[saltlen+0] = count >>> 24;\n countsalt[saltlen+1] = count >>> 16;\n countsalt[saltlen+2] = count >>> 8;\n countsalt[saltlen+3] = count;\n\n crypto_hash_sha512(sha2salt, countsalt, saltlen + 4);\n bcrypt_hash(sha2pass, sha2salt, tmpout);\n for (i = out.byteLength; i--;)\n out[i] = tmpout[i];\n\n for (i = 1; i < rounds; i++) {\n crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength);\n bcrypt_hash(sha2pass, sha2salt, tmpout);\n for (j = 0; j < out.byteLength; j++)\n out[j] ^= tmpout[j];\n }\n\n amt = Math.min(amt, keylen);\n for (i = 0; i < amt; i++) {\n dest = i * stride + (count - 1);\n if (dest >= origkeylen)\n break;\n key[dest] = out[i];\n }\n keylen -= i;\n }\n\n return 0;\n};\n\nmodule.exports = {\n BLOCKS: BCRYPT_BLOCKS,\n HASHSIZE: BCRYPT_HASHSIZE,\n hash: bcrypt_hash,\n pbkdf: bcrypt_pbkdf\n};\n",";(function (globalObject) {\r\n 'use strict';\r\n\r\n/*\r\n * bignumber.js v9.0.0\r\n * A JavaScript library for arbitrary-precision arithmetic.\r\n * https://github.com/MikeMcl/bignumber.js\r\n * Copyright (c) 2019 Michael Mclaughlin \r\n * MIT Licensed.\r\n *\r\n * BigNumber.prototype methods | BigNumber methods\r\n * |\r\n * absoluteValue abs | clone\r\n * comparedTo | config set\r\n * decimalPlaces dp | DECIMAL_PLACES\r\n * dividedBy div | ROUNDING_MODE\r\n * dividedToIntegerBy idiv | EXPONENTIAL_AT\r\n * exponentiatedBy pow | RANGE\r\n * integerValue | CRYPTO\r\n * isEqualTo eq | MODULO_MODE\r\n * isFinite | POW_PRECISION\r\n * isGreaterThan gt | FORMAT\r\n * isGreaterThanOrEqualTo gte | ALPHABET\r\n * isInteger | isBigNumber\r\n * isLessThan lt | maximum max\r\n * isLessThanOrEqualTo lte | minimum min\r\n * isNaN | random\r\n * isNegative | sum\r\n * isPositive |\r\n * isZero |\r\n * minus |\r\n * modulo mod |\r\n * multipliedBy times |\r\n * negated |\r\n * plus |\r\n * precision sd |\r\n * shiftedBy |\r\n * squareRoot sqrt |\r\n * toExponential |\r\n * toFixed |\r\n * toFormat |\r\n * toFraction |\r\n * toJSON |\r\n * toNumber |\r\n * toPrecision |\r\n * toString |\r\n * valueOf |\r\n *\r\n */\r\n\r\n\r\n var BigNumber,\r\n isNumeric = /^-?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i,\r\n mathceil = Math.ceil,\r\n mathfloor = Math.floor,\r\n\r\n bignumberError = '[BigNumber Error] ',\r\n tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ',\r\n\r\n BASE = 1e14,\r\n LOG_BASE = 14,\r\n MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1\r\n // MAX_INT32 = 0x7fffffff, // 2^31 - 1\r\n POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],\r\n SQRT_BASE = 1e7,\r\n\r\n // EDITABLE\r\n // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and\r\n // the arguments to toExponential, toFixed, toFormat, and toPrecision.\r\n MAX = 1E9; // 0 to MAX_INT32\r\n\r\n\r\n /*\r\n * Create and return a BigNumber constructor.\r\n */\r\n function clone(configObject) {\r\n var div, convertBase, parseNumeric,\r\n P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null },\r\n ONE = new BigNumber(1),\r\n\r\n\r\n //----------------------------- EDITABLE CONFIG DEFAULTS -------------------------------\r\n\r\n\r\n // The default values below must be integers within the inclusive ranges stated.\r\n // The values can also be changed at run-time using BigNumber.set.\r\n\r\n // The maximum number of decimal places for operations involving division.\r\n DECIMAL_PLACES = 20, // 0 to MAX\r\n\r\n // The rounding mode used when rounding to the above decimal places, and when using\r\n // toExponential, toFixed, toFormat and toPrecision, and round (default value).\r\n // UP 0 Away from zero.\r\n // DOWN 1 Towards zero.\r\n // CEIL 2 Towards +Infinity.\r\n // FLOOR 3 Towards -Infinity.\r\n // HALF_UP 4 Towards nearest neighbour. If equidistant, up.\r\n // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.\r\n // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.\r\n // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.\r\n // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.\r\n ROUNDING_MODE = 4, // 0 to 8\r\n\r\n // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]\r\n\r\n // The exponent value at and beneath which toString returns exponential notation.\r\n // Number type: -7\r\n TO_EXP_NEG = -7, // 0 to -MAX\r\n\r\n // The exponent value at and above which toString returns exponential notation.\r\n // Number type: 21\r\n TO_EXP_POS = 21, // 0 to MAX\r\n\r\n // RANGE : [MIN_EXP, MAX_EXP]\r\n\r\n // The minimum exponent value, beneath which underflow to zero occurs.\r\n // Number type: -324 (5e-324)\r\n MIN_EXP = -1e7, // -1 to -MAX\r\n\r\n // The maximum exponent value, above which overflow to Infinity occurs.\r\n // Number type: 308 (1.7976931348623157e+308)\r\n // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.\r\n MAX_EXP = 1e7, // 1 to MAX\r\n\r\n // Whether to use cryptographically-secure random number generation, if available.\r\n CRYPTO = false, // true or false\r\n\r\n // The modulo mode used when calculating the modulus: a mod n.\r\n // The quotient (q = a / n) is calculated according to the corresponding rounding mode.\r\n // The remainder (r) is calculated as: r = a - n * q.\r\n //\r\n // UP 0 The remainder is positive if the dividend is negative, else is negative.\r\n // DOWN 1 The remainder has the same sign as the dividend.\r\n // This modulo mode is commonly known as 'truncated division' and is\r\n // equivalent to (a % n) in JavaScript.\r\n // FLOOR 3 The remainder has the same sign as the divisor (Python %).\r\n // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.\r\n // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).\r\n // The remainder is always positive.\r\n //\r\n // The truncated division, floored division, Euclidian division and IEEE 754 remainder\r\n // modes are commonly used for the modulus operation.\r\n // Although the other rounding modes can also be used, they may not give useful results.\r\n MODULO_MODE = 1, // 0 to 9\r\n\r\n // The maximum number of significant digits of the result of the exponentiatedBy operation.\r\n // If POW_PRECISION is 0, there will be unlimited significant digits.\r\n POW_PRECISION = 0, // 0 to MAX\r\n\r\n // The format specification used by the BigNumber.prototype.toFormat method.\r\n FORMAT = {\r\n prefix: '',\r\n groupSize: 3,\r\n secondaryGroupSize: 0,\r\n groupSeparator: ',',\r\n decimalSeparator: '.',\r\n fractionGroupSize: 0,\r\n fractionGroupSeparator: '\\xA0', // non-breaking space\r\n suffix: ''\r\n },\r\n\r\n // The alphabet used for base conversion. It must be at least 2 characters long, with no '+',\r\n // '-', '.', whitespace, or repeated character.\r\n // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'\r\n ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';\r\n\r\n\r\n //------------------------------------------------------------------------------------------\r\n\r\n\r\n // CONSTRUCTOR\r\n\r\n\r\n /*\r\n * The BigNumber constructor and exported function.\r\n * Create and return a new instance of a BigNumber object.\r\n *\r\n * v {number|string|BigNumber} A numeric value.\r\n * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive.\r\n */\r\n function BigNumber(v, b) {\r\n var alphabet, c, caseChanged, e, i, isNum, len, str,\r\n x = this;\r\n\r\n // Enable constructor call without `new`.\r\n if (!(x instanceof BigNumber)) return new BigNumber(v, b);\r\n\r\n if (b == null) {\r\n\r\n if (v && v._isBigNumber === true) {\r\n x.s = v.s;\r\n\r\n if (!v.c || v.e > MAX_EXP) {\r\n x.c = x.e = null;\r\n } else if (v.e < MIN_EXP) {\r\n x.c = [x.e = 0];\r\n } else {\r\n x.e = v.e;\r\n x.c = v.c.slice();\r\n }\r\n\r\n return;\r\n }\r\n\r\n if ((isNum = typeof v == 'number') && v * 0 == 0) {\r\n\r\n // Use `1 / n` to handle minus zero also.\r\n x.s = 1 / v < 0 ? (v = -v, -1) : 1;\r\n\r\n // Fast path for integers, where n < 2147483648 (2**31).\r\n if (v === ~~v) {\r\n for (e = 0, i = v; i >= 10; i /= 10, e++);\r\n\r\n if (e > MAX_EXP) {\r\n x.c = x.e = null;\r\n } else {\r\n x.e = e;\r\n x.c = [v];\r\n }\r\n\r\n return;\r\n }\r\n\r\n str = String(v);\r\n } else {\r\n\r\n if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum);\r\n\r\n x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1;\r\n }\r\n\r\n // Decimal point?\r\n if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n\r\n // Exponential form?\r\n if ((i = str.search(/e/i)) > 0) {\r\n\r\n // Determine exponent.\r\n if (e < 0) e = i;\r\n e += +str.slice(i + 1);\r\n str = str.substring(0, i);\r\n } else if (e < 0) {\r\n\r\n // Integer.\r\n e = str.length;\r\n }\r\n\r\n } else {\r\n\r\n // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'\r\n intCheck(b, 2, ALPHABET.length, 'Base');\r\n\r\n // Allow exponential notation to be used with base 10 argument, while\r\n // also rounding to DECIMAL_PLACES as with other bases.\r\n if (b == 10) {\r\n x = new BigNumber(v);\r\n return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE);\r\n }\r\n\r\n str = String(v);\r\n\r\n if (isNum = typeof v == 'number') {\r\n\r\n // Avoid potential interpretation of Infinity and NaN as base 44+ values.\r\n if (v * 0 != 0) return parseNumeric(x, str, isNum, b);\r\n\r\n x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1;\r\n\r\n // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'\r\n if (BigNumber.DEBUG && str.replace(/^0\\.0*|\\./, '').length > 15) {\r\n throw Error\r\n (tooManyDigits + v);\r\n }\r\n } else {\r\n x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1;\r\n }\r\n\r\n alphabet = ALPHABET.slice(0, b);\r\n e = i = 0;\r\n\r\n // Check that str is a valid base b number.\r\n // Don't use RegExp, so alphabet can contain special characters.\r\n for (len = str.length; i < len; i++) {\r\n if (alphabet.indexOf(c = str.charAt(i)) < 0) {\r\n if (c == '.') {\r\n\r\n // If '.' is not the first character and it has not be found before.\r\n if (i > e) {\r\n e = len;\r\n continue;\r\n }\r\n } else if (!caseChanged) {\r\n\r\n // Allow e.g. hexadecimal 'FF' as well as 'ff'.\r\n if (str == str.toUpperCase() && (str = str.toLowerCase()) ||\r\n str == str.toLowerCase() && (str = str.toUpperCase())) {\r\n caseChanged = true;\r\n i = -1;\r\n e = 0;\r\n continue;\r\n }\r\n }\r\n\r\n return parseNumeric(x, String(v), isNum, b);\r\n }\r\n }\r\n\r\n // Prevent later check for length on converted number.\r\n isNum = false;\r\n str = convertBase(str, b, 10, x.s);\r\n\r\n // Decimal point?\r\n if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n else e = str.length;\r\n }\r\n\r\n // Determine leading zeros.\r\n for (i = 0; str.charCodeAt(i) === 48; i++);\r\n\r\n // Determine trailing zeros.\r\n for (len = str.length; str.charCodeAt(--len) === 48;);\r\n\r\n if (str = str.slice(i, ++len)) {\r\n len -= i;\r\n\r\n // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'\r\n if (isNum && BigNumber.DEBUG &&\r\n len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) {\r\n throw Error\r\n (tooManyDigits + (x.s * v));\r\n }\r\n\r\n // Overflow?\r\n if ((e = e - i - 1) > MAX_EXP) {\r\n\r\n // Infinity.\r\n x.c = x.e = null;\r\n\r\n // Underflow?\r\n } else if (e < MIN_EXP) {\r\n\r\n // Zero.\r\n x.c = [x.e = 0];\r\n } else {\r\n x.e = e;\r\n x.c = [];\r\n\r\n // Transform base\r\n\r\n // e is the base 10 exponent.\r\n // i is where to slice str to get the first element of the coefficient array.\r\n i = (e + 1) % LOG_BASE;\r\n if (e < 0) i += LOG_BASE; // i < 1\r\n\r\n if (i < len) {\r\n if (i) x.c.push(+str.slice(0, i));\r\n\r\n for (len -= LOG_BASE; i < len;) {\r\n x.c.push(+str.slice(i, i += LOG_BASE));\r\n }\r\n\r\n i = LOG_BASE - (str = str.slice(i)).length;\r\n } else {\r\n i -= len;\r\n }\r\n\r\n for (; i--; str += '0');\r\n x.c.push(+str);\r\n }\r\n } else {\r\n\r\n // Zero.\r\n x.c = [x.e = 0];\r\n }\r\n }\r\n\r\n\r\n // CONSTRUCTOR PROPERTIES\r\n\r\n\r\n BigNumber.clone = clone;\r\n\r\n BigNumber.ROUND_UP = 0;\r\n BigNumber.ROUND_DOWN = 1;\r\n BigNumber.ROUND_CEIL = 2;\r\n BigNumber.ROUND_FLOOR = 3;\r\n BigNumber.ROUND_HALF_UP = 4;\r\n BigNumber.ROUND_HALF_DOWN = 5;\r\n BigNumber.ROUND_HALF_EVEN = 6;\r\n BigNumber.ROUND_HALF_CEIL = 7;\r\n BigNumber.ROUND_HALF_FLOOR = 8;\r\n BigNumber.EUCLID = 9;\r\n\r\n\r\n /*\r\n * Configure infrequently-changing library-wide settings.\r\n *\r\n * Accept an object with the following optional properties (if the value of a property is\r\n * a number, it must be an integer within the inclusive range stated):\r\n *\r\n * DECIMAL_PLACES {number} 0 to MAX\r\n * ROUNDING_MODE {number} 0 to 8\r\n * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX]\r\n * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX]\r\n * CRYPTO {boolean} true or false\r\n * MODULO_MODE {number} 0 to 9\r\n * POW_PRECISION {number} 0 to MAX\r\n * ALPHABET {string} A string of two or more unique characters which does\r\n * not contain '.'.\r\n * FORMAT {object} An object with some of the following properties:\r\n * prefix {string}\r\n * groupSize {number}\r\n * secondaryGroupSize {number}\r\n * groupSeparator {string}\r\n * decimalSeparator {string}\r\n * fractionGroupSize {number}\r\n * fractionGroupSeparator {string}\r\n * suffix {string}\r\n *\r\n * (The values assigned to the above FORMAT object properties are not checked for validity.)\r\n *\r\n * E.g.\r\n * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })\r\n *\r\n * Ignore properties/parameters set to null or undefined, except for ALPHABET.\r\n *\r\n * Return an object with the properties current values.\r\n */\r\n BigNumber.config = BigNumber.set = function (obj) {\r\n var p, v;\r\n\r\n if (obj != null) {\r\n\r\n if (typeof obj == 'object') {\r\n\r\n // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.\r\n // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) {\r\n v = obj[p];\r\n intCheck(v, 0, MAX, p);\r\n DECIMAL_PLACES = v;\r\n }\r\n\r\n // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.\r\n // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) {\r\n v = obj[p];\r\n intCheck(v, 0, 8, p);\r\n ROUNDING_MODE = v;\r\n }\r\n\r\n // EXPONENTIAL_AT {number|number[]}\r\n // Integer, -MAX to MAX inclusive or\r\n // [integer -MAX to 0 inclusive, 0 to MAX inclusive].\r\n // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) {\r\n v = obj[p];\r\n if (v && v.pop) {\r\n intCheck(v[0], -MAX, 0, p);\r\n intCheck(v[1], 0, MAX, p);\r\n TO_EXP_NEG = v[0];\r\n TO_EXP_POS = v[1];\r\n } else {\r\n intCheck(v, -MAX, MAX, p);\r\n TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v);\r\n }\r\n }\r\n\r\n // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or\r\n // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].\r\n // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}'\r\n if (obj.hasOwnProperty(p = 'RANGE')) {\r\n v = obj[p];\r\n if (v && v.pop) {\r\n intCheck(v[0], -MAX, -1, p);\r\n intCheck(v[1], 1, MAX, p);\r\n MIN_EXP = v[0];\r\n MAX_EXP = v[1];\r\n } else {\r\n intCheck(v, -MAX, MAX, p);\r\n if (v) {\r\n MIN_EXP = -(MAX_EXP = v < 0 ? -v : v);\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' cannot be zero: ' + v);\r\n }\r\n }\r\n }\r\n\r\n // CRYPTO {boolean} true or false.\r\n // '[BigNumber Error] CRYPTO not true or false: {v}'\r\n // '[BigNumber Error] crypto unavailable'\r\n if (obj.hasOwnProperty(p = 'CRYPTO')) {\r\n v = obj[p];\r\n if (v === !!v) {\r\n if (v) {\r\n if (typeof crypto != 'undefined' && crypto &&\r\n (crypto.getRandomValues || crypto.randomBytes)) {\r\n CRYPTO = v;\r\n } else {\r\n CRYPTO = !v;\r\n throw Error\r\n (bignumberError + 'crypto unavailable');\r\n }\r\n } else {\r\n CRYPTO = v;\r\n }\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' not true or false: ' + v);\r\n }\r\n }\r\n\r\n // MODULO_MODE {number} Integer, 0 to 9 inclusive.\r\n // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'MODULO_MODE')) {\r\n v = obj[p];\r\n intCheck(v, 0, 9, p);\r\n MODULO_MODE = v;\r\n }\r\n\r\n // POW_PRECISION {number} Integer, 0 to MAX inclusive.\r\n // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'POW_PRECISION')) {\r\n v = obj[p];\r\n intCheck(v, 0, MAX, p);\r\n POW_PRECISION = v;\r\n }\r\n\r\n // FORMAT {object}\r\n // '[BigNumber Error] FORMAT not an object: {v}'\r\n if (obj.hasOwnProperty(p = 'FORMAT')) {\r\n v = obj[p];\r\n if (typeof v == 'object') FORMAT = v;\r\n else throw Error\r\n (bignumberError + p + ' not an object: ' + v);\r\n }\r\n\r\n // ALPHABET {string}\r\n // '[BigNumber Error] ALPHABET invalid: {v}'\r\n if (obj.hasOwnProperty(p = 'ALPHABET')) {\r\n v = obj[p];\r\n\r\n // Disallow if only one character,\r\n // or if it contains '+', '-', '.', whitespace, or a repeated character.\r\n if (typeof v == 'string' && !/^.$|[+-.\\s]|(.).*\\1/.test(v)) {\r\n ALPHABET = v;\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' invalid: ' + v);\r\n }\r\n }\r\n\r\n } else {\r\n\r\n // '[BigNumber Error] Object expected: {v}'\r\n throw Error\r\n (bignumberError + 'Object expected: ' + obj);\r\n }\r\n }\r\n\r\n return {\r\n DECIMAL_PLACES: DECIMAL_PLACES,\r\n ROUNDING_MODE: ROUNDING_MODE,\r\n EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS],\r\n RANGE: [MIN_EXP, MAX_EXP],\r\n CRYPTO: CRYPTO,\r\n MODULO_MODE: MODULO_MODE,\r\n POW_PRECISION: POW_PRECISION,\r\n FORMAT: FORMAT,\r\n ALPHABET: ALPHABET\r\n };\r\n };\r\n\r\n\r\n /*\r\n * Return true if v is a BigNumber instance, otherwise return false.\r\n *\r\n * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed.\r\n *\r\n * v {any}\r\n *\r\n * '[BigNumber Error] Invalid BigNumber: {v}'\r\n */\r\n BigNumber.isBigNumber = function (v) {\r\n if (!v || v._isBigNumber !== true) return false;\r\n if (!BigNumber.DEBUG) return true;\r\n\r\n var i, n,\r\n c = v.c,\r\n e = v.e,\r\n s = v.s;\r\n\r\n out: if ({}.toString.call(c) == '[object Array]') {\r\n\r\n if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) {\r\n\r\n // If the first element is zero, the BigNumber value must be zero.\r\n if (c[0] === 0) {\r\n if (e === 0 && c.length === 1) return true;\r\n break out;\r\n }\r\n\r\n // Calculate number of digits that c[0] should have, based on the exponent.\r\n i = (e + 1) % LOG_BASE;\r\n if (i < 1) i += LOG_BASE;\r\n\r\n // Calculate number of digits of c[0].\r\n //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) {\r\n if (String(c[0]).length == i) {\r\n\r\n for (i = 0; i < c.length; i++) {\r\n n = c[i];\r\n if (n < 0 || n >= BASE || n !== mathfloor(n)) break out;\r\n }\r\n\r\n // Last element cannot be zero, unless it is the only element.\r\n if (n !== 0) return true;\r\n }\r\n }\r\n\r\n // Infinity/NaN\r\n } else if (c === null && e === null && (s === null || s === 1 || s === -1)) {\r\n return true;\r\n }\r\n\r\n throw Error\r\n (bignumberError + 'Invalid BigNumber: ' + v);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the maximum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.maximum = BigNumber.max = function () {\r\n return maxOrMin(arguments, P.lt);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the minimum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.minimum = BigNumber.min = function () {\r\n return maxOrMin(arguments, P.gt);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,\r\n * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing\r\n * zeros are produced).\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}'\r\n * '[BigNumber Error] crypto unavailable'\r\n */\r\n BigNumber.random = (function () {\r\n var pow2_53 = 0x20000000000000;\r\n\r\n // Return a 53 bit integer n, where 0 <= n < 9007199254740992.\r\n // Check if Math.random() produces more than 32 bits of randomness.\r\n // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.\r\n // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.\r\n var random53bitInt = (Math.random() * pow2_53) & 0x1fffff\r\n ? function () { return mathfloor(Math.random() * pow2_53); }\r\n : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +\r\n (Math.random() * 0x800000 | 0); };\r\n\r\n return function (dp) {\r\n var a, b, e, k, v,\r\n i = 0,\r\n c = [],\r\n rand = new BigNumber(ONE);\r\n\r\n if (dp == null) dp = DECIMAL_PLACES;\r\n else intCheck(dp, 0, MAX);\r\n\r\n k = mathceil(dp / LOG_BASE);\r\n\r\n if (CRYPTO) {\r\n\r\n // Browsers supporting crypto.getRandomValues.\r\n if (crypto.getRandomValues) {\r\n\r\n a = crypto.getRandomValues(new Uint32Array(k *= 2));\r\n\r\n for (; i < k;) {\r\n\r\n // 53 bits:\r\n // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)\r\n // 11111 11111111 11111111 11111111 11100000 00000000 00000000\r\n // ((Math.pow(2, 32) - 1) >>> 11).toString(2)\r\n // 11111 11111111 11111111\r\n // 0x20000 is 2^21.\r\n v = a[i] * 0x20000 + (a[i + 1] >>> 11);\r\n\r\n // Rejection sampling:\r\n // 0 <= v < 9007199254740992\r\n // Probability that v >= 9e15, is\r\n // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251\r\n if (v >= 9e15) {\r\n b = crypto.getRandomValues(new Uint32Array(2));\r\n a[i] = b[0];\r\n a[i + 1] = b[1];\r\n } else {\r\n\r\n // 0 <= v <= 8999999999999999\r\n // 0 <= (v % 1e14) <= 99999999999999\r\n c.push(v % 1e14);\r\n i += 2;\r\n }\r\n }\r\n i = k / 2;\r\n\r\n // Node.js supporting crypto.randomBytes.\r\n } else if (crypto.randomBytes) {\r\n\r\n // buffer\r\n a = crypto.randomBytes(k *= 7);\r\n\r\n for (; i < k;) {\r\n\r\n // 0x1000000000000 is 2^48, 0x10000000000 is 2^40\r\n // 0x100000000 is 2^32, 0x1000000 is 2^24\r\n // 11111 11111111 11111111 11111111 11111111 11111111 11111111\r\n // 0 <= v < 9007199254740992\r\n v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) +\r\n (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) +\r\n (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6];\r\n\r\n if (v >= 9e15) {\r\n crypto.randomBytes(7).copy(a, i);\r\n } else {\r\n\r\n // 0 <= (v % 1e14) <= 99999999999999\r\n c.push(v % 1e14);\r\n i += 7;\r\n }\r\n }\r\n i = k / 7;\r\n } else {\r\n CRYPTO = false;\r\n throw Error\r\n (bignumberError + 'crypto unavailable');\r\n }\r\n }\r\n\r\n // Use Math.random.\r\n if (!CRYPTO) {\r\n\r\n for (; i < k;) {\r\n v = random53bitInt();\r\n if (v < 9e15) c[i++] = v % 1e14;\r\n }\r\n }\r\n\r\n k = c[--i];\r\n dp %= LOG_BASE;\r\n\r\n // Convert trailing digits to zeros according to dp.\r\n if (k && dp) {\r\n v = POWS_TEN[LOG_BASE - dp];\r\n c[i] = mathfloor(k / v) * v;\r\n }\r\n\r\n // Remove trailing elements which are zero.\r\n for (; c[i] === 0; c.pop(), i--);\r\n\r\n // Zero?\r\n if (i < 0) {\r\n c = [e = 0];\r\n } else {\r\n\r\n // Remove leading elements which are zero and adjust exponent accordingly.\r\n for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);\r\n\r\n // Count the digits of the first element of c to determine leading zeros, and...\r\n for (i = 1, v = c[0]; v >= 10; v /= 10, i++);\r\n\r\n // adjust the exponent accordingly.\r\n if (i < LOG_BASE) e -= LOG_BASE - i;\r\n }\r\n\r\n rand.e = e;\r\n rand.c = c;\r\n return rand;\r\n };\r\n })();\r\n\r\n\r\n /*\r\n * Return a BigNumber whose value is the sum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.sum = function () {\r\n var i = 1,\r\n args = arguments,\r\n sum = new BigNumber(args[0]);\r\n for (; i < args.length;) sum = sum.plus(args[i++]);\r\n return sum;\r\n };\r\n\r\n\r\n // PRIVATE FUNCTIONS\r\n\r\n\r\n // Called by BigNumber and BigNumber.prototype.toString.\r\n convertBase = (function () {\r\n var decimal = '0123456789';\r\n\r\n /*\r\n * Convert string of baseIn to an array of numbers of baseOut.\r\n * Eg. toBaseOut('255', 10, 16) returns [15, 15].\r\n * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5].\r\n */\r\n function toBaseOut(str, baseIn, baseOut, alphabet) {\r\n var j,\r\n arr = [0],\r\n arrL,\r\n i = 0,\r\n len = str.length;\r\n\r\n for (; i < len;) {\r\n for (arrL = arr.length; arrL--; arr[arrL] *= baseIn);\r\n\r\n arr[0] += alphabet.indexOf(str.charAt(i++));\r\n\r\n for (j = 0; j < arr.length; j++) {\r\n\r\n if (arr[j] > baseOut - 1) {\r\n if (arr[j + 1] == null) arr[j + 1] = 0;\r\n arr[j + 1] += arr[j] / baseOut | 0;\r\n arr[j] %= baseOut;\r\n }\r\n }\r\n }\r\n\r\n return arr.reverse();\r\n }\r\n\r\n // Convert a numeric string of baseIn to a numeric string of baseOut.\r\n // If the caller is toString, we are converting from base 10 to baseOut.\r\n // If the caller is BigNumber, we are converting from baseIn to base 10.\r\n return function (str, baseIn, baseOut, sign, callerIsToString) {\r\n var alphabet, d, e, k, r, x, xc, y,\r\n i = str.indexOf('.'),\r\n dp = DECIMAL_PLACES,\r\n rm = ROUNDING_MODE;\r\n\r\n // Non-integer.\r\n if (i >= 0) {\r\n k = POW_PRECISION;\r\n\r\n // Unlimited precision.\r\n POW_PRECISION = 0;\r\n str = str.replace('.', '');\r\n y = new BigNumber(baseIn);\r\n x = y.pow(str.length - i);\r\n POW_PRECISION = k;\r\n\r\n // Convert str as if an integer, then restore the fraction part by dividing the\r\n // result by its base raised to a power.\r\n\r\n y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'),\r\n 10, baseOut, decimal);\r\n y.e = y.c.length;\r\n }\r\n\r\n // Convert the number as integer.\r\n\r\n xc = toBaseOut(str, baseIn, baseOut, callerIsToString\r\n ? (alphabet = ALPHABET, decimal)\r\n : (alphabet = decimal, ALPHABET));\r\n\r\n // xc now represents str as an integer and converted to baseOut. e is the exponent.\r\n e = k = xc.length;\r\n\r\n // Remove trailing zeros.\r\n for (; xc[--k] == 0; xc.pop());\r\n\r\n // Zero?\r\n if (!xc[0]) return alphabet.charAt(0);\r\n\r\n // Does str represent an integer? If so, no need for the division.\r\n if (i < 0) {\r\n --e;\r\n } else {\r\n x.c = xc;\r\n x.e = e;\r\n\r\n // The sign is needed for correct rounding.\r\n x.s = sign;\r\n x = div(x, y, dp, rm, baseOut);\r\n xc = x.c;\r\n r = x.r;\r\n e = x.e;\r\n }\r\n\r\n // xc now represents str converted to baseOut.\r\n\r\n // THe index of the rounding digit.\r\n d = e + dp + 1;\r\n\r\n // The rounding digit: the digit to the right of the digit that may be rounded up.\r\n i = xc[d];\r\n\r\n // Look at the rounding digits and mode to determine whether to round up.\r\n\r\n k = baseOut / 2;\r\n r = r || d < 0 || xc[d + 1] != null;\r\n\r\n r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))\r\n : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||\r\n rm == (x.s < 0 ? 8 : 7));\r\n\r\n // If the index of the rounding digit is not greater than zero, or xc represents\r\n // zero, then the result of the base conversion is zero or, if rounding up, a value\r\n // such as 0.00001.\r\n if (d < 1 || !xc[0]) {\r\n\r\n // 1^-dp or 0\r\n str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0);\r\n } else {\r\n\r\n // Truncate xc to the required number of decimal places.\r\n xc.length = d;\r\n\r\n // Round up?\r\n if (r) {\r\n\r\n // Rounding up may mean the previous digit has to be rounded up and so on.\r\n for (--baseOut; ++xc[--d] > baseOut;) {\r\n xc[d] = 0;\r\n\r\n if (!d) {\r\n ++e;\r\n xc = [1].concat(xc);\r\n }\r\n }\r\n }\r\n\r\n // Determine trailing zeros.\r\n for (k = xc.length; !xc[--k];);\r\n\r\n // E.g. [4, 11, 15] becomes 4bf.\r\n for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++]));\r\n\r\n // Add leading zeros, decimal point and trailing zeros as required.\r\n str = toFixedPoint(str, e, alphabet.charAt(0));\r\n }\r\n\r\n // The caller will add the sign.\r\n return str;\r\n };\r\n })();\r\n\r\n\r\n // Perform division in the specified base. Called by div and convertBase.\r\n div = (function () {\r\n\r\n // Assume non-zero x and k.\r\n function multiply(x, k, base) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for (x = x.slice(); i--;) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\r\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }\r\n\r\n function compare(a, b, aL, bL) {\r\n var i, cmp;\r\n\r\n if (aL != bL) {\r\n cmp = aL > bL ? 1 : -1;\r\n } else {\r\n\r\n for (i = cmp = 0; i < aL; i++) {\r\n\r\n if (a[i] != b[i]) {\r\n cmp = a[i] > b[i] ? 1 : -1;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n return cmp;\r\n }\r\n\r\n function subtract(a, b, aL, base) {\r\n var i = 0;\r\n\r\n // Subtract b from a.\r\n for (; aL--;) {\r\n a[aL] -= i;\r\n i = a[aL] < b[aL] ? 1 : 0;\r\n a[aL] = i * base + a[aL] - b[aL];\r\n }\r\n\r\n // Remove leading zeros.\r\n for (; !a[0] && a.length > 1; a.splice(0, 1));\r\n }\r\n\r\n // x: dividend, y: divisor.\r\n return function (x, y, dp, rm, base) {\r\n var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,\r\n yL, yz,\r\n s = x.s == y.s ? 1 : -1,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n // Either NaN, Infinity or 0?\r\n if (!xc || !xc[0] || !yc || !yc[0]) {\r\n\r\n return new BigNumber(\r\n\r\n // Return NaN if either NaN, or both Infinity or 0.\r\n !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN :\r\n\r\n // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.\r\n xc && xc[0] == 0 || !yc ? s * 0 : s / 0\r\n );\r\n }\r\n\r\n q = new BigNumber(s);\r\n qc = q.c = [];\r\n e = x.e - y.e;\r\n s = dp + e + 1;\r\n\r\n if (!base) {\r\n base = BASE;\r\n e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE);\r\n s = s / LOG_BASE | 0;\r\n }\r\n\r\n // Result exponent may be one less then the current value of e.\r\n // The coefficients of the BigNumbers from convertBase may have trailing zeros.\r\n for (i = 0; yc[i] == (xc[i] || 0); i++);\r\n\r\n if (yc[i] > (xc[i] || 0)) e--;\r\n\r\n if (s < 0) {\r\n qc.push(1);\r\n more = true;\r\n } else {\r\n xL = xc.length;\r\n yL = yc.length;\r\n i = 0;\r\n s += 2;\r\n\r\n // Normalise xc and yc so highest order digit of yc is >= base / 2.\r\n\r\n n = mathfloor(base / (yc[0] + 1));\r\n\r\n // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1.\r\n // if (n > 1 || n++ == 1 && yc[0] < base / 2) {\r\n if (n > 1) {\r\n yc = multiply(yc, n, base);\r\n xc = multiply(xc, n, base);\r\n yL = yc.length;\r\n xL = xc.length;\r\n }\r\n\r\n xi = yL;\r\n rem = xc.slice(0, yL);\r\n remL = rem.length;\r\n\r\n // Add zeros to make remainder as long as divisor.\r\n for (; remL < yL; rem[remL++] = 0);\r\n yz = yc.slice();\r\n yz = [0].concat(yz);\r\n yc0 = yc[0];\r\n if (yc[1] >= base / 2) yc0++;\r\n // Not necessary, but to prevent trial digit n > base, when using base 3.\r\n // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15;\r\n\r\n do {\r\n n = 0;\r\n\r\n // Compare divisor and remainder.\r\n cmp = compare(yc, rem, yL, remL);\r\n\r\n // If divisor < remainder.\r\n if (cmp < 0) {\r\n\r\n // Calculate trial digit, n.\r\n\r\n rem0 = rem[0];\r\n if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);\r\n\r\n // n is how many times the divisor goes into the current remainder.\r\n n = mathfloor(rem0 / yc0);\r\n\r\n // Algorithm:\r\n // product = divisor multiplied by trial digit (n).\r\n // Compare product and remainder.\r\n // If product is greater than remainder:\r\n // Subtract divisor from product, decrement trial digit.\r\n // Subtract product from remainder.\r\n // If product was less than remainder at the last compare:\r\n // Compare new remainder and divisor.\r\n // If remainder is greater than divisor:\r\n // Subtract divisor from remainder, increment trial digit.\r\n\r\n if (n > 1) {\r\n\r\n // n may be > base only when base is 3.\r\n if (n >= base) n = base - 1;\r\n\r\n // product = divisor * trial digit.\r\n prod = multiply(yc, n, base);\r\n prodL = prod.length;\r\n remL = rem.length;\r\n\r\n // Compare product and remainder.\r\n // If product > remainder then trial digit n too high.\r\n // n is 1 too high about 5% of the time, and is not known to have\r\n // ever been more than 1 too high.\r\n while (compare(prod, rem, prodL, remL) == 1) {\r\n n--;\r\n\r\n // Subtract divisor from product.\r\n subtract(prod, yL < prodL ? yz : yc, prodL, base);\r\n prodL = prod.length;\r\n cmp = 1;\r\n }\r\n } else {\r\n\r\n // n is 0 or 1, cmp is -1.\r\n // If n is 0, there is no need to compare yc and rem again below,\r\n // so change cmp to 1 to avoid it.\r\n // If n is 1, leave cmp as -1, so yc and rem are compared again.\r\n if (n == 0) {\r\n\r\n // divisor < remainder, so n must be at least 1.\r\n cmp = n = 1;\r\n }\r\n\r\n // product = divisor\r\n prod = yc.slice();\r\n prodL = prod.length;\r\n }\r\n\r\n if (prodL < remL) prod = [0].concat(prod);\r\n\r\n // Subtract product from remainder.\r\n subtract(rem, prod, remL, base);\r\n remL = rem.length;\r\n\r\n // If product was < remainder.\r\n if (cmp == -1) {\r\n\r\n // Compare divisor and new remainder.\r\n // If divisor < new remainder, subtract divisor from remainder.\r\n // Trial digit n too low.\r\n // n is 1 too low about 5% of the time, and very rarely 2 too low.\r\n while (compare(yc, rem, yL, remL) < 1) {\r\n n++;\r\n\r\n // Subtract divisor from remainder.\r\n subtract(rem, yL < remL ? yz : yc, remL, base);\r\n remL = rem.length;\r\n }\r\n }\r\n } else if (cmp === 0) {\r\n n++;\r\n rem = [0];\r\n } // else cmp === 1 and n will be 0\r\n\r\n // Add the next digit, n, to the result array.\r\n qc[i++] = n;\r\n\r\n // Update the remainder.\r\n if (rem[0]) {\r\n rem[remL++] = xc[xi] || 0;\r\n } else {\r\n rem = [xc[xi]];\r\n remL = 1;\r\n }\r\n } while ((xi++ < xL || rem[0] != null) && s--);\r\n\r\n more = rem[0] != null;\r\n\r\n // Leading zero?\r\n if (!qc[0]) qc.splice(0, 1);\r\n }\r\n\r\n if (base == BASE) {\r\n\r\n // To calculate q.e, first get the number of digits of qc[0].\r\n for (i = 1, s = qc[0]; s >= 10; s /= 10, i++);\r\n\r\n round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more);\r\n\r\n // Caller is convertBase.\r\n } else {\r\n q.e = e;\r\n q.r = +more;\r\n }\r\n\r\n return q;\r\n };\r\n })();\r\n\r\n\r\n /*\r\n * Return a string representing the value of BigNumber n in fixed-point or exponential\r\n * notation rounded to the specified decimal places or significant digits.\r\n *\r\n * n: a BigNumber.\r\n * i: the index of the last digit required (i.e. the digit that may be rounded up).\r\n * rm: the rounding mode.\r\n * id: 1 (toExponential) or 2 (toPrecision).\r\n */\r\n function format(n, i, rm, id) {\r\n var c0, e, ne, len, str;\r\n\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n if (!n.c) return n.toString();\r\n\r\n c0 = n.c[0];\r\n ne = n.e;\r\n\r\n if (i == null) {\r\n str = coeffToString(n.c);\r\n str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS)\r\n ? toExponential(str, ne)\r\n : toFixedPoint(str, ne, '0');\r\n } else {\r\n n = round(new BigNumber(n), i, rm);\r\n\r\n // n.e may have changed if the value was rounded up.\r\n e = n.e;\r\n\r\n str = coeffToString(n.c);\r\n len = str.length;\r\n\r\n // toPrecision returns exponential notation if the number of significant digits\r\n // specified is less than the number of digits necessary to represent the integer\r\n // part of the value in fixed-point notation.\r\n\r\n // Exponential notation.\r\n if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) {\r\n\r\n // Append zeros?\r\n for (; len < i; str += '0', len++);\r\n str = toExponential(str, e);\r\n\r\n // Fixed-point notation.\r\n } else {\r\n i -= ne;\r\n str = toFixedPoint(str, e, '0');\r\n\r\n // Append zeros?\r\n if (e + 1 > len) {\r\n if (--i > 0) for (str += '.'; i--; str += '0');\r\n } else {\r\n i += e - len;\r\n if (i > 0) {\r\n if (e + 1 == len) str += '.';\r\n for (; i--; str += '0');\r\n }\r\n }\r\n }\r\n }\r\n\r\n return n.s < 0 && c0 ? '-' + str : str;\r\n }\r\n\r\n\r\n // Handle BigNumber.max and BigNumber.min.\r\n function maxOrMin(args, method) {\r\n var n,\r\n i = 1,\r\n m = new BigNumber(args[0]);\r\n\r\n for (; i < args.length; i++) {\r\n n = new BigNumber(args[i]);\r\n\r\n // If any number is NaN, return NaN.\r\n if (!n.s) {\r\n m = n;\r\n break;\r\n } else if (method.call(m, n)) {\r\n m = n;\r\n }\r\n }\r\n\r\n return m;\r\n }\r\n\r\n\r\n /*\r\n * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.\r\n * Called by minus, plus and times.\r\n */\r\n function normalise(n, c, e) {\r\n var i = 1,\r\n j = c.length;\r\n\r\n // Remove trailing zeros.\r\n for (; !c[--j]; c.pop());\r\n\r\n // Calculate the base 10 exponent. First get the number of digits of c[0].\r\n for (j = c[0]; j >= 10; j /= 10, i++);\r\n\r\n // Overflow?\r\n if ((e = i + e * LOG_BASE - 1) > MAX_EXP) {\r\n\r\n // Infinity.\r\n n.c = n.e = null;\r\n\r\n // Underflow?\r\n } else if (e < MIN_EXP) {\r\n\r\n // Zero.\r\n n.c = [n.e = 0];\r\n } else {\r\n n.e = e;\r\n n.c = c;\r\n }\r\n\r\n return n;\r\n }\r\n\r\n\r\n // Handle values that fail the validity test in BigNumber.\r\n parseNumeric = (function () {\r\n var basePrefix = /^(-?)0([xbo])(?=\\w[\\w.]*$)/i,\r\n dotAfter = /^([^.]+)\\.$/,\r\n dotBefore = /^\\.([^.]+)$/,\r\n isInfinityOrNaN = /^-?(Infinity|NaN)$/,\r\n whitespaceOrPlus = /^\\s*\\+(?=[\\w.])|^\\s+|\\s+$/g;\r\n\r\n return function (x, str, isNum, b) {\r\n var base,\r\n s = isNum ? str : str.replace(whitespaceOrPlus, '');\r\n\r\n // No exception on ±Infinity or NaN.\r\n if (isInfinityOrNaN.test(s)) {\r\n x.s = isNaN(s) ? null : s < 0 ? -1 : 1;\r\n } else {\r\n if (!isNum) {\r\n\r\n // basePrefix = /^(-?)0([xbo])(?=\\w[\\w.]*$)/i\r\n s = s.replace(basePrefix, function (m, p1, p2) {\r\n base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8;\r\n return !b || b == base ? p1 : m;\r\n });\r\n\r\n if (b) {\r\n base = b;\r\n\r\n // E.g. '1.' to '1', '.1' to '0.1'\r\n s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1');\r\n }\r\n\r\n if (str != s) return new BigNumber(s, base);\r\n }\r\n\r\n // '[BigNumber Error] Not a number: {n}'\r\n // '[BigNumber Error] Not a base {b} number: {n}'\r\n if (BigNumber.DEBUG) {\r\n throw Error\r\n (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str);\r\n }\r\n\r\n // NaN\r\n x.s = null;\r\n }\r\n\r\n x.c = x.e = null;\r\n }\r\n })();\r\n\r\n\r\n /*\r\n * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.\r\n * If r is truthy, it is known that there are more digits after the rounding digit.\r\n */\r\n function round(x, sd, rm, r) {\r\n var d, i, j, k, n, ni, rd,\r\n xc = x.c,\r\n pows10 = POWS_TEN;\r\n\r\n // if x is not Infinity or NaN...\r\n if (xc) {\r\n\r\n // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.\r\n // n is a base 1e14 number, the value of the element of array x.c containing rd.\r\n // ni is the index of n within x.c.\r\n // d is the number of digits of n.\r\n // i is the index of rd within n including leading zeros.\r\n // j is the actual index of rd within n (if < 0, rd is a leading zero).\r\n out: {\r\n\r\n // Get the number of digits of the first element of xc.\r\n for (d = 1, k = xc[0]; k >= 10; k /= 10, d++);\r\n i = sd - d;\r\n\r\n // If the rounding digit is in the first element of xc...\r\n if (i < 0) {\r\n i += LOG_BASE;\r\n j = sd;\r\n n = xc[ni = 0];\r\n\r\n // Get the rounding digit at index j of n.\r\n rd = n / pows10[d - j - 1] % 10 | 0;\r\n } else {\r\n ni = mathceil((i + 1) / LOG_BASE);\r\n\r\n if (ni >= xc.length) {\r\n\r\n if (r) {\r\n\r\n // Needed by sqrt.\r\n for (; xc.length <= ni; xc.push(0));\r\n n = rd = 0;\r\n d = 1;\r\n i %= LOG_BASE;\r\n j = i - LOG_BASE + 1;\r\n } else {\r\n break out;\r\n }\r\n } else {\r\n n = k = xc[ni];\r\n\r\n // Get the number of digits of n.\r\n for (d = 1; k >= 10; k /= 10, d++);\r\n\r\n // Get the index of rd within n.\r\n i %= LOG_BASE;\r\n\r\n // Get the index of rd within n, adjusted for leading zeros.\r\n // The number of leading zeros of n is given by LOG_BASE - d.\r\n j = i - LOG_BASE + d;\r\n\r\n // Get the rounding digit at index j of n.\r\n rd = j < 0 ? 0 : n / pows10[d - j - 1] % 10 | 0;\r\n }\r\n }\r\n\r\n r = r || sd < 0 ||\r\n\r\n // Are there any non-zero digits after the rounding digit?\r\n // The expression n % pows10[d - j - 1] returns all digits of n to the right\r\n // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.\r\n xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]);\r\n\r\n r = rm < 4\r\n ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))\r\n : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 &&\r\n\r\n // Check whether the digit to the left of the rounding digit is odd.\r\n ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 ||\r\n rm == (x.s < 0 ? 8 : 7));\r\n\r\n if (sd < 1 || !xc[0]) {\r\n xc.length = 0;\r\n\r\n if (r) {\r\n\r\n // Convert sd to decimal places.\r\n sd -= x.e + 1;\r\n\r\n // 1, 0.1, 0.01, 0.001, 0.0001 etc.\r\n xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE];\r\n x.e = -sd || 0;\r\n } else {\r\n\r\n // Zero.\r\n xc[0] = x.e = 0;\r\n }\r\n\r\n return x;\r\n }\r\n\r\n // Remove excess digits.\r\n if (i == 0) {\r\n xc.length = ni;\r\n k = 1;\r\n ni--;\r\n } else {\r\n xc.length = ni + 1;\r\n k = pows10[LOG_BASE - i];\r\n\r\n // E.g. 56700 becomes 56000 if 7 is the rounding digit.\r\n // j > 0 means i > number of leading zeros of n.\r\n xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0;\r\n }\r\n\r\n // Round up?\r\n if (r) {\r\n\r\n for (; ;) {\r\n\r\n // If the digit to be rounded up is in the first element of xc...\r\n if (ni == 0) {\r\n\r\n // i will be the length of xc[0] before k is added.\r\n for (i = 1, j = xc[0]; j >= 10; j /= 10, i++);\r\n j = xc[0] += k;\r\n for (k = 1; j >= 10; j /= 10, k++);\r\n\r\n // if i != k the length has increased.\r\n if (i != k) {\r\n x.e++;\r\n if (xc[0] == BASE) xc[0] = 1;\r\n }\r\n\r\n break;\r\n } else {\r\n xc[ni] += k;\r\n if (xc[ni] != BASE) break;\r\n xc[ni--] = 0;\r\n k = 1;\r\n }\r\n }\r\n }\r\n\r\n // Remove trailing zeros.\r\n for (i = xc.length; xc[--i] === 0; xc.pop());\r\n }\r\n\r\n // Overflow? Infinity.\r\n if (x.e > MAX_EXP) {\r\n x.c = x.e = null;\r\n\r\n // Underflow? Zero.\r\n } else if (x.e < MIN_EXP) {\r\n x.c = [x.e = 0];\r\n }\r\n }\r\n\r\n return x;\r\n }\r\n\r\n\r\n function valueOf(n) {\r\n var str,\r\n e = n.e;\r\n\r\n if (e === null) return n.toString();\r\n\r\n str = coeffToString(n.c);\r\n\r\n str = e <= TO_EXP_NEG || e >= TO_EXP_POS\r\n ? toExponential(str, e)\r\n : toFixedPoint(str, e, '0');\r\n\r\n return n.s < 0 ? '-' + str : str;\r\n }\r\n\r\n\r\n // PROTOTYPE/INSTANCE METHODS\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the absolute value of this BigNumber.\r\n */\r\n P.absoluteValue = P.abs = function () {\r\n var x = new BigNumber(this);\r\n if (x.s < 0) x.s = 1;\r\n return x;\r\n };\r\n\r\n\r\n /*\r\n * Return\r\n * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),\r\n * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),\r\n * 0 if they have the same value,\r\n * or null if the value of either is NaN.\r\n */\r\n P.comparedTo = function (y, b) {\r\n return compare(this, new BigNumber(y, b));\r\n };\r\n\r\n\r\n /*\r\n * If dp is undefined or null or true or false, return the number of decimal places of the\r\n * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.\r\n *\r\n * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this\r\n * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or\r\n * ROUNDING_MODE if rm is omitted.\r\n *\r\n * [dp] {number} Decimal places: integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.decimalPlaces = P.dp = function (dp, rm) {\r\n var c, n, v,\r\n x = this;\r\n\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n return round(new BigNumber(x), dp + x.e + 1, rm);\r\n }\r\n\r\n if (!(c = x.c)) return null;\r\n n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE;\r\n\r\n // Subtract the number of trailing zeros of the last number.\r\n if (v = c[v]) for (; v % 10 == 0; v /= 10, n--);\r\n if (n < 0) n = 0;\r\n\r\n return n;\r\n };\r\n\r\n\r\n /*\r\n * n / 0 = I\r\n * n / N = N\r\n * n / I = 0\r\n * 0 / n = 0\r\n * 0 / 0 = N\r\n * 0 / N = N\r\n * 0 / I = 0\r\n * N / n = N\r\n * N / 0 = N\r\n * N / N = N\r\n * N / I = N\r\n * I / n = I\r\n * I / 0 = I\r\n * I / N = N\r\n * I / I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber divided by the value of\r\n * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.\r\n */\r\n P.dividedBy = P.div = function (y, b) {\r\n return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the integer part of dividing the value of this\r\n * BigNumber by the value of BigNumber(y, b).\r\n */\r\n P.dividedToIntegerBy = P.idiv = function (y, b) {\r\n return div(this, new BigNumber(y, b), 0, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a BigNumber whose value is the value of this BigNumber exponentiated by n.\r\n *\r\n * If m is present, return the result modulo m.\r\n * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.\r\n * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE.\r\n *\r\n * The modular power operation works efficiently when x, n, and m are integers, otherwise it\r\n * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0.\r\n *\r\n * n {number|string|BigNumber} The exponent. An integer.\r\n * [m] {number|string|BigNumber} The modulus.\r\n *\r\n * '[BigNumber Error] Exponent not an integer: {n}'\r\n */\r\n P.exponentiatedBy = P.pow = function (n, m) {\r\n var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y,\r\n x = this;\r\n\r\n n = new BigNumber(n);\r\n\r\n // Allow NaN and ±Infinity, but not other non-integers.\r\n if (n.c && !n.isInteger()) {\r\n throw Error\r\n (bignumberError + 'Exponent not an integer: ' + valueOf(n));\r\n }\r\n\r\n if (m != null) m = new BigNumber(m);\r\n\r\n // Exponent of MAX_SAFE_INTEGER is 15.\r\n nIsBig = n.e > 14;\r\n\r\n // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0.\r\n if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) {\r\n\r\n // The sign of the result of pow when x is negative depends on the evenness of n.\r\n // If +n overflows to ±Infinity, the evenness of n would be not be known.\r\n y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? 2 - isOdd(n) : +valueOf(n)));\r\n return m ? y.mod(m) : y;\r\n }\r\n\r\n nIsNeg = n.s < 0;\r\n\r\n if (m) {\r\n\r\n // x % m returns NaN if abs(m) is zero, or m is NaN.\r\n if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN);\r\n\r\n isModExp = !nIsNeg && x.isInteger() && m.isInteger();\r\n\r\n if (isModExp) x = x.mod(m);\r\n\r\n // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15.\r\n // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15.\r\n } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0\r\n // [1, 240000000]\r\n ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7\r\n // [80000000000000] [99999750000000]\r\n : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) {\r\n\r\n // If x is negative and n is odd, k = -0, else k = 0.\r\n k = x.s < 0 && isOdd(n) ? -0 : 0;\r\n\r\n // If x >= 1, k = ±Infinity.\r\n if (x.e > -1) k = 1 / k;\r\n\r\n // If n is negative return ±0, else return ±Infinity.\r\n return new BigNumber(nIsNeg ? 1 / k : k);\r\n\r\n } else if (POW_PRECISION) {\r\n\r\n // Truncating each coefficient array to a length of k after each multiplication\r\n // equates to truncating significant digits to POW_PRECISION + [28, 41],\r\n // i.e. there will be a minimum of 28 guard digits retained.\r\n k = mathceil(POW_PRECISION / LOG_BASE + 2);\r\n }\r\n\r\n if (nIsBig) {\r\n half = new BigNumber(0.5);\r\n if (nIsNeg) n.s = 1;\r\n nIsOdd = isOdd(n);\r\n } else {\r\n i = Math.abs(+valueOf(n));\r\n nIsOdd = i % 2;\r\n }\r\n\r\n y = new BigNumber(ONE);\r\n\r\n // Performs 54 loop iterations for n of 9007199254740991.\r\n for (; ;) {\r\n\r\n if (nIsOdd) {\r\n y = y.times(x);\r\n if (!y.c) break;\r\n\r\n if (k) {\r\n if (y.c.length > k) y.c.length = k;\r\n } else if (isModExp) {\r\n y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m));\r\n }\r\n }\r\n\r\n if (i) {\r\n i = mathfloor(i / 2);\r\n if (i === 0) break;\r\n nIsOdd = i % 2;\r\n } else {\r\n n = n.times(half);\r\n round(n, n.e + 1, 1);\r\n\r\n if (n.e > 14) {\r\n nIsOdd = isOdd(n);\r\n } else {\r\n i = +valueOf(n);\r\n if (i === 0) break;\r\n nIsOdd = i % 2;\r\n }\r\n }\r\n\r\n x = x.times(x);\r\n\r\n if (k) {\r\n if (x.c && x.c.length > k) x.c.length = k;\r\n } else if (isModExp) {\r\n x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m));\r\n }\r\n }\r\n\r\n if (isModExp) return y;\r\n if (nIsNeg) y = ONE.div(y);\r\n\r\n return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y;\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer\r\n * using rounding mode rm, or ROUNDING_MODE if rm is omitted.\r\n *\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}'\r\n */\r\n P.integerValue = function (rm) {\r\n var n = new BigNumber(this);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n return round(n, n.e + 1, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isEqualTo = P.eq = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) === 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is a finite number, otherwise return false.\r\n */\r\n P.isFinite = function () {\r\n return !!this.c;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isGreaterThan = P.gt = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) > 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is greater than or equal to the value of\r\n * BigNumber(y, b), otherwise return false.\r\n */\r\n P.isGreaterThanOrEqualTo = P.gte = function (y, b) {\r\n return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0;\r\n\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is an integer, otherwise return false.\r\n */\r\n P.isInteger = function () {\r\n return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isLessThan = P.lt = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) < 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is less than or equal to the value of\r\n * BigNumber(y, b), otherwise return false.\r\n */\r\n P.isLessThanOrEqualTo = P.lte = function (y, b) {\r\n return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is NaN, otherwise return false.\r\n */\r\n P.isNaN = function () {\r\n return !this.s;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is negative, otherwise return false.\r\n */\r\n P.isNegative = function () {\r\n return this.s < 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is positive, otherwise return false.\r\n */\r\n P.isPositive = function () {\r\n return this.s > 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is 0 or -0, otherwise return false.\r\n */\r\n P.isZero = function () {\r\n return !!this.c && this.c[0] == 0;\r\n };\r\n\r\n\r\n /*\r\n * n - 0 = n\r\n * n - N = N\r\n * n - I = -I\r\n * 0 - n = -n\r\n * 0 - 0 = 0\r\n * 0 - N = N\r\n * 0 - I = -I\r\n * N - n = N\r\n * N - 0 = N\r\n * N - N = N\r\n * N - I = N\r\n * I - n = I\r\n * I - 0 = I\r\n * I - N = N\r\n * I - I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber minus the value of\r\n * BigNumber(y, b).\r\n */\r\n P.minus = function (y, b) {\r\n var i, j, t, xLTy,\r\n x = this,\r\n a = x.s;\r\n\r\n y = new BigNumber(y, b);\r\n b = y.s;\r\n\r\n // Either NaN?\r\n if (!a || !b) return new BigNumber(NaN);\r\n\r\n // Signs differ?\r\n if (a != b) {\r\n y.s = -b;\r\n return x.plus(y);\r\n }\r\n\r\n var xe = x.e / LOG_BASE,\r\n ye = y.e / LOG_BASE,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n if (!xe || !ye) {\r\n\r\n // Either Infinity?\r\n if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN);\r\n\r\n // Either zero?\r\n if (!xc[0] || !yc[0]) {\r\n\r\n // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.\r\n return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x :\r\n\r\n // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity\r\n ROUNDING_MODE == 3 ? -0 : 0);\r\n }\r\n }\r\n\r\n xe = bitFloor(xe);\r\n ye = bitFloor(ye);\r\n xc = xc.slice();\r\n\r\n // Determine which is the bigger number.\r\n if (a = xe - ye) {\r\n\r\n if (xLTy = a < 0) {\r\n a = -a;\r\n t = xc;\r\n } else {\r\n ye = xe;\r\n t = yc;\r\n }\r\n\r\n t.reverse();\r\n\r\n // Prepend zeros to equalise exponents.\r\n for (b = a; b--; t.push(0));\r\n t.reverse();\r\n } else {\r\n\r\n // Exponents equal. Check digit by digit.\r\n j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b;\r\n\r\n for (a = b = 0; b < j; b++) {\r\n\r\n if (xc[b] != yc[b]) {\r\n xLTy = xc[b] < yc[b];\r\n break;\r\n }\r\n }\r\n }\r\n\r\n // x < y? Point xc to the array of the bigger number.\r\n if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s;\r\n\r\n b = (j = yc.length) - (i = xc.length);\r\n\r\n // Append zeros to xc if shorter.\r\n // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.\r\n if (b > 0) for (; b--; xc[i++] = 0);\r\n b = BASE - 1;\r\n\r\n // Subtract yc from xc.\r\n for (; j > a;) {\r\n\r\n if (xc[--j] < yc[j]) {\r\n for (i = j; i && !xc[--i]; xc[i] = b);\r\n --xc[i];\r\n xc[j] += BASE;\r\n }\r\n\r\n xc[j] -= yc[j];\r\n }\r\n\r\n // Remove leading zeros and adjust exponent accordingly.\r\n for (; xc[0] == 0; xc.splice(0, 1), --ye);\r\n\r\n // Zero?\r\n if (!xc[0]) {\r\n\r\n // Following IEEE 754 (2008) 6.3,\r\n // n - n = +0 but n - n = -0 when rounding towards -Infinity.\r\n y.s = ROUNDING_MODE == 3 ? -1 : 1;\r\n y.c = [y.e = 0];\r\n return y;\r\n }\r\n\r\n // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity\r\n // for finite x and y.\r\n return normalise(y, xc, ye);\r\n };\r\n\r\n\r\n /*\r\n * n % 0 = N\r\n * n % N = N\r\n * n % I = n\r\n * 0 % n = 0\r\n * -0 % n = -0\r\n * 0 % 0 = N\r\n * 0 % N = N\r\n * 0 % I = 0\r\n * N % n = N\r\n * N % 0 = N\r\n * N % N = N\r\n * N % I = N\r\n * I % n = N\r\n * I % 0 = N\r\n * I % N = N\r\n * I % I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber modulo the value of\r\n * BigNumber(y, b). The result depends on the value of MODULO_MODE.\r\n */\r\n P.modulo = P.mod = function (y, b) {\r\n var q, s,\r\n x = this;\r\n\r\n y = new BigNumber(y, b);\r\n\r\n // Return NaN if x is Infinity or NaN, or y is NaN or zero.\r\n if (!x.c || !y.s || y.c && !y.c[0]) {\r\n return new BigNumber(NaN);\r\n\r\n // Return x if y is Infinity or x is zero.\r\n } else if (!y.c || x.c && !x.c[0]) {\r\n return new BigNumber(x);\r\n }\r\n\r\n if (MODULO_MODE == 9) {\r\n\r\n // Euclidian division: q = sign(y) * floor(x / abs(y))\r\n // r = x - qy where 0 <= r < abs(y)\r\n s = y.s;\r\n y.s = 1;\r\n q = div(x, y, 0, 3);\r\n y.s = s;\r\n q.s *= s;\r\n } else {\r\n q = div(x, y, 0, MODULO_MODE);\r\n }\r\n\r\n y = x.minus(q.times(y));\r\n\r\n // To match JavaScript %, ensure sign of zero is sign of dividend.\r\n if (!y.c[0] && MODULO_MODE == 1) y.s = x.s;\r\n\r\n return y;\r\n };\r\n\r\n\r\n /*\r\n * n * 0 = 0\r\n * n * N = N\r\n * n * I = I\r\n * 0 * n = 0\r\n * 0 * 0 = 0\r\n * 0 * N = N\r\n * 0 * I = N\r\n * N * n = N\r\n * N * 0 = N\r\n * N * N = N\r\n * N * I = N\r\n * I * n = I\r\n * I * 0 = N\r\n * I * N = N\r\n * I * I = I\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value\r\n * of BigNumber(y, b).\r\n */\r\n P.multipliedBy = P.times = function (y, b) {\r\n var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,\r\n base, sqrtBase,\r\n x = this,\r\n xc = x.c,\r\n yc = (y = new BigNumber(y, b)).c;\r\n\r\n // Either NaN, ±Infinity or ±0?\r\n if (!xc || !yc || !xc[0] || !yc[0]) {\r\n\r\n // Return NaN if either is NaN, or one is 0 and the other is Infinity.\r\n if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) {\r\n y.c = y.e = y.s = null;\r\n } else {\r\n y.s *= x.s;\r\n\r\n // Return ±Infinity if either is ±Infinity.\r\n if (!xc || !yc) {\r\n y.c = y.e = null;\r\n\r\n // Return ±0 if either is ±0.\r\n } else {\r\n y.c = [0];\r\n y.e = 0;\r\n }\r\n }\r\n\r\n return y;\r\n }\r\n\r\n e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE);\r\n y.s *= x.s;\r\n xcL = xc.length;\r\n ycL = yc.length;\r\n\r\n // Ensure xc points to longer array and xcL to its length.\r\n if (xcL < ycL) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i;\r\n\r\n // Initialise the result array with zeros.\r\n for (i = xcL + ycL, zc = []; i--; zc.push(0));\r\n\r\n base = BASE;\r\n sqrtBase = SQRT_BASE;\r\n\r\n for (i = ycL; --i >= 0;) {\r\n c = 0;\r\n ylo = yc[i] % sqrtBase;\r\n yhi = yc[i] / sqrtBase | 0;\r\n\r\n for (k = xcL, j = i + k; j > i;) {\r\n xlo = xc[--k] % sqrtBase;\r\n xhi = xc[k] / sqrtBase | 0;\r\n m = yhi * xlo + xhi * ylo;\r\n xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c;\r\n c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi;\r\n zc[j--] = xlo % base;\r\n }\r\n\r\n zc[j] = c;\r\n }\r\n\r\n if (c) {\r\n ++e;\r\n } else {\r\n zc.splice(0, 1);\r\n }\r\n\r\n return normalise(y, zc, e);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber negated,\r\n * i.e. multiplied by -1.\r\n */\r\n P.negated = function () {\r\n var x = new BigNumber(this);\r\n x.s = -x.s || null;\r\n return x;\r\n };\r\n\r\n\r\n /*\r\n * n + 0 = n\r\n * n + N = N\r\n * n + I = I\r\n * 0 + n = n\r\n * 0 + 0 = 0\r\n * 0 + N = N\r\n * 0 + I = I\r\n * N + n = N\r\n * N + 0 = N\r\n * N + N = N\r\n * N + I = N\r\n * I + n = I\r\n * I + 0 = I\r\n * I + N = N\r\n * I + I = I\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber plus the value of\r\n * BigNumber(y, b).\r\n */\r\n P.plus = function (y, b) {\r\n var t,\r\n x = this,\r\n a = x.s;\r\n\r\n y = new BigNumber(y, b);\r\n b = y.s;\r\n\r\n // Either NaN?\r\n if (!a || !b) return new BigNumber(NaN);\r\n\r\n // Signs differ?\r\n if (a != b) {\r\n y.s = -b;\r\n return x.minus(y);\r\n }\r\n\r\n var xe = x.e / LOG_BASE,\r\n ye = y.e / LOG_BASE,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n if (!xe || !ye) {\r\n\r\n // Return ±Infinity if either ±Infinity.\r\n if (!xc || !yc) return new BigNumber(a / 0);\r\n\r\n // Either zero?\r\n // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.\r\n if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0);\r\n }\r\n\r\n xe = bitFloor(xe);\r\n ye = bitFloor(ye);\r\n xc = xc.slice();\r\n\r\n // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.\r\n if (a = xe - ye) {\r\n if (a > 0) {\r\n ye = xe;\r\n t = yc;\r\n } else {\r\n a = -a;\r\n t = xc;\r\n }\r\n\r\n t.reverse();\r\n for (; a--; t.push(0));\r\n t.reverse();\r\n }\r\n\r\n a = xc.length;\r\n b = yc.length;\r\n\r\n // Point xc to the longer array, and b to the shorter length.\r\n if (a - b < 0) t = yc, yc = xc, xc = t, b = a;\r\n\r\n // Only start adding at yc.length - 1 as the further digits of xc can be ignored.\r\n for (a = 0; b;) {\r\n a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0;\r\n xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;\r\n }\r\n\r\n if (a) {\r\n xc = [a].concat(xc);\r\n ++ye;\r\n }\r\n\r\n // No need to check for zero, as +x + +y != 0 && -x + -y != 0\r\n // ye = MAX_EXP + 1 possible\r\n return normalise(y, xc, ye);\r\n };\r\n\r\n\r\n /*\r\n * If sd is undefined or null or true or false, return the number of significant digits of\r\n * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.\r\n * If sd is true include integer-part trailing zeros in the count.\r\n *\r\n * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this\r\n * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or\r\n * ROUNDING_MODE if rm is omitted.\r\n *\r\n * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive.\r\n * boolean: whether to count integer-part trailing zeros: true or false.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'\r\n */\r\n P.precision = P.sd = function (sd, rm) {\r\n var c, n, v,\r\n x = this;\r\n\r\n if (sd != null && sd !== !!sd) {\r\n intCheck(sd, 1, MAX);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n return round(new BigNumber(x), sd, rm);\r\n }\r\n\r\n if (!(c = x.c)) return null;\r\n v = c.length - 1;\r\n n = v * LOG_BASE + 1;\r\n\r\n if (v = c[v]) {\r\n\r\n // Subtract the number of trailing zeros of the last element.\r\n for (; v % 10 == 0; v /= 10, n--);\r\n\r\n // Add the number of digits of the first element.\r\n for (v = c[0]; v >= 10; v /= 10, n++);\r\n }\r\n\r\n if (sd && x.e + 1 > n) n = x.e + 1;\r\n\r\n return n;\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber shifted by k places\r\n * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.\r\n *\r\n * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}'\r\n */\r\n P.shiftedBy = function (k) {\r\n intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);\r\n return this.times('1e' + k);\r\n };\r\n\r\n\r\n /*\r\n * sqrt(-n) = N\r\n * sqrt(N) = N\r\n * sqrt(-I) = N\r\n * sqrt(I) = I\r\n * sqrt(0) = 0\r\n * sqrt(-0) = -0\r\n *\r\n * Return a new BigNumber whose value is the square root of the value of this BigNumber,\r\n * rounded according to DECIMAL_PLACES and ROUNDING_MODE.\r\n */\r\n P.squareRoot = P.sqrt = function () {\r\n var m, n, r, rep, t,\r\n x = this,\r\n c = x.c,\r\n s = x.s,\r\n e = x.e,\r\n dp = DECIMAL_PLACES + 4,\r\n half = new BigNumber('0.5');\r\n\r\n // Negative/NaN/Infinity/zero?\r\n if (s !== 1 || !c || !c[0]) {\r\n return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0);\r\n }\r\n\r\n // Initial estimate.\r\n s = Math.sqrt(+valueOf(x));\r\n\r\n // Math.sqrt underflow/overflow?\r\n // Pass x to Math.sqrt as integer, then adjust the exponent of the result.\r\n if (s == 0 || s == 1 / 0) {\r\n n = coeffToString(c);\r\n if ((n.length + e) % 2 == 0) n += '0';\r\n s = Math.sqrt(+n);\r\n e = bitFloor((e + 1) / 2) - (e < 0 || e % 2);\r\n\r\n if (s == 1 / 0) {\r\n n = '1e' + e;\r\n } else {\r\n n = s.toExponential();\r\n n = n.slice(0, n.indexOf('e') + 1) + e;\r\n }\r\n\r\n r = new BigNumber(n);\r\n } else {\r\n r = new BigNumber(s + '');\r\n }\r\n\r\n // Check for zero.\r\n // r could be zero if MIN_EXP is changed after the this value was created.\r\n // This would cause a division by zero (x/t) and hence Infinity below, which would cause\r\n // coeffToString to throw.\r\n if (r.c[0]) {\r\n e = r.e;\r\n s = e + dp;\r\n if (s < 3) s = 0;\r\n\r\n // Newton-Raphson iteration.\r\n for (; ;) {\r\n t = r;\r\n r = half.times(t.plus(div(x, t, dp, 1)));\r\n\r\n if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) {\r\n\r\n // The exponent of r may here be one less than the final result exponent,\r\n // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits\r\n // are indexed correctly.\r\n if (r.e < e) --s;\r\n n = n.slice(s - 3, s + 1);\r\n\r\n // The 4th rounding digit may be in error by -1 so if the 4 rounding digits\r\n // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the\r\n // iteration.\r\n if (n == '9999' || !rep && n == '4999') {\r\n\r\n // On the first iteration only, check to see if rounding up gives the\r\n // exact result as the nines may infinitely repeat.\r\n if (!rep) {\r\n round(t, t.e + DECIMAL_PLACES + 2, 0);\r\n\r\n if (t.times(t).eq(x)) {\r\n r = t;\r\n break;\r\n }\r\n }\r\n\r\n dp += 4;\r\n s += 4;\r\n rep = 1;\r\n } else {\r\n\r\n // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact\r\n // result. If not, then there are further digits and m will be truthy.\r\n if (!+n || !+n.slice(1) && n.charAt(0) == '5') {\r\n\r\n // Truncate to the first rounding digit.\r\n round(r, r.e + DECIMAL_PLACES + 2, 1);\r\n m = !r.times(r).eq(x);\r\n }\r\n\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n\r\n return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in exponential notation and\r\n * rounded using ROUNDING_MODE to dp fixed decimal places.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.toExponential = function (dp, rm) {\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n dp++;\r\n }\r\n return format(this, dp, rm, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in fixed-point notation rounding\r\n * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.\r\n *\r\n * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',\r\n * but e.g. (-0.00001).toFixed(0) is '-0'.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.toFixed = function (dp, rm) {\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n dp = dp + this.e + 1;\r\n }\r\n return format(this, dp, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in fixed-point notation rounded\r\n * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties\r\n * of the format or FORMAT object (see BigNumber.set).\r\n *\r\n * The formatting object may contain some or all of the properties shown below.\r\n *\r\n * FORMAT = {\r\n * prefix: '',\r\n * groupSize: 3,\r\n * secondaryGroupSize: 0,\r\n * groupSeparator: ',',\r\n * decimalSeparator: '.',\r\n * fractionGroupSize: 0,\r\n * fractionGroupSeparator: '\\xA0', // non-breaking space\r\n * suffix: ''\r\n * };\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n * [format] {object} Formatting options. See FORMAT pbject above.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n * '[BigNumber Error] Argument not an object: {format}'\r\n */\r\n P.toFormat = function (dp, rm, format) {\r\n var str,\r\n x = this;\r\n\r\n if (format == null) {\r\n if (dp != null && rm && typeof rm == 'object') {\r\n format = rm;\r\n rm = null;\r\n } else if (dp && typeof dp == 'object') {\r\n format = dp;\r\n dp = rm = null;\r\n } else {\r\n format = FORMAT;\r\n }\r\n } else if (typeof format != 'object') {\r\n throw Error\r\n (bignumberError + 'Argument not an object: ' + format);\r\n }\r\n\r\n str = x.toFixed(dp, rm);\r\n\r\n if (x.c) {\r\n var i,\r\n arr = str.split('.'),\r\n g1 = +format.groupSize,\r\n g2 = +format.secondaryGroupSize,\r\n groupSeparator = format.groupSeparator || '',\r\n intPart = arr[0],\r\n fractionPart = arr[1],\r\n isNeg = x.s < 0,\r\n intDigits = isNeg ? intPart.slice(1) : intPart,\r\n len = intDigits.length;\r\n\r\n if (g2) i = g1, g1 = g2, g2 = i, len -= i;\r\n\r\n if (g1 > 0 && len > 0) {\r\n i = len % g1 || g1;\r\n intPart = intDigits.substr(0, i);\r\n for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1);\r\n if (g2 > 0) intPart += groupSeparator + intDigits.slice(i);\r\n if (isNeg) intPart = '-' + intPart;\r\n }\r\n\r\n str = fractionPart\r\n ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize)\r\n ? fractionPart.replace(new RegExp('\\\\d{' + g2 + '}\\\\B', 'g'),\r\n '$&' + (format.fractionGroupSeparator || ''))\r\n : fractionPart)\r\n : intPart;\r\n }\r\n\r\n return (format.prefix || '') + str + (format.suffix || '');\r\n };\r\n\r\n\r\n /*\r\n * Return an array of two BigNumbers representing the value of this BigNumber as a simple\r\n * fraction with an integer numerator and an integer denominator.\r\n * The denominator will be a positive non-zero value less than or equal to the specified\r\n * maximum denominator. If a maximum denominator is not specified, the denominator will be\r\n * the lowest value necessary to represent the number exactly.\r\n *\r\n * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator.\r\n *\r\n * '[BigNumber Error] Argument {not an integer|out of range} : {md}'\r\n */\r\n P.toFraction = function (md) {\r\n var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s,\r\n x = this,\r\n xc = x.c;\r\n\r\n if (md != null) {\r\n n = new BigNumber(md);\r\n\r\n // Throw if md is less than one or is not an integer, unless it is Infinity.\r\n if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) {\r\n throw Error\r\n (bignumberError + 'Argument ' +\r\n (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n));\r\n }\r\n }\r\n\r\n if (!xc) return new BigNumber(x);\r\n\r\n d = new BigNumber(ONE);\r\n n1 = d0 = new BigNumber(ONE);\r\n d1 = n0 = new BigNumber(ONE);\r\n s = coeffToString(xc);\r\n\r\n // Determine initial denominator.\r\n // d is a power of 10 and the minimum max denominator that specifies the value exactly.\r\n e = d.e = s.length - x.e - 1;\r\n d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp];\r\n md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n;\r\n\r\n exp = MAX_EXP;\r\n MAX_EXP = 1 / 0;\r\n n = new BigNumber(s);\r\n\r\n // n0 = d1 = 0\r\n n0.c[0] = 0;\r\n\r\n for (; ;) {\r\n q = div(n, d, 0, 1);\r\n d2 = d0.plus(q.times(d1));\r\n if (d2.comparedTo(md) == 1) break;\r\n d0 = d1;\r\n d1 = d2;\r\n n1 = n0.plus(q.times(d2 = n1));\r\n n0 = d2;\r\n d = n.minus(q.times(d2 = d));\r\n n = d2;\r\n }\r\n\r\n d2 = div(md.minus(d0), d1, 0, 1);\r\n n0 = n0.plus(d2.times(n1));\r\n d0 = d0.plus(d2.times(d1));\r\n n0.s = n1.s = x.s;\r\n e = e * 2;\r\n\r\n // Determine which fraction is closer to x, n0/d0 or n1/d1\r\n r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo(\r\n div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0];\r\n\r\n MAX_EXP = exp;\r\n\r\n return r;\r\n };\r\n\r\n\r\n /*\r\n * Return the value of this BigNumber converted to a number primitive.\r\n */\r\n P.toNumber = function () {\r\n return +valueOf(this);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber rounded to sd significant digits\r\n * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits\r\n * necessary to represent the integer part of the value in fixed-point notation, then use\r\n * exponential notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'\r\n */\r\n P.toPrecision = function (sd, rm) {\r\n if (sd != null) intCheck(sd, 1, MAX);\r\n return format(this, sd, rm, 2);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in base b, or base 10 if b is\r\n * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and\r\n * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent\r\n * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than\r\n * TO_EXP_NEG, return exponential notation.\r\n *\r\n * [b] {number} Integer, 2 to ALPHABET.length inclusive.\r\n *\r\n * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'\r\n */\r\n P.toString = function (b) {\r\n var str,\r\n n = this,\r\n s = n.s,\r\n e = n.e;\r\n\r\n // Infinity or NaN?\r\n if (e === null) {\r\n if (s) {\r\n str = 'Infinity';\r\n if (s < 0) str = '-' + str;\r\n } else {\r\n str = 'NaN';\r\n }\r\n } else {\r\n if (b == null) {\r\n str = e <= TO_EXP_NEG || e >= TO_EXP_POS\r\n ? toExponential(coeffToString(n.c), e)\r\n : toFixedPoint(coeffToString(n.c), e, '0');\r\n } else if (b === 10) {\r\n n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE);\r\n str = toFixedPoint(coeffToString(n.c), n.e, '0');\r\n } else {\r\n intCheck(b, 2, ALPHABET.length, 'Base');\r\n str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true);\r\n }\r\n\r\n if (s < 0 && n.c[0]) str = '-' + str;\r\n }\r\n\r\n return str;\r\n };\r\n\r\n\r\n /*\r\n * Return as toString, but do not accept a base argument, and include the minus sign for\r\n * negative zero.\r\n */\r\n P.valueOf = P.toJSON = function () {\r\n return valueOf(this);\r\n };\r\n\r\n\r\n P._isBigNumber = true;\r\n\r\n if (configObject != null) BigNumber.set(configObject);\r\n\r\n return BigNumber;\r\n }\r\n\r\n\r\n // PRIVATE HELPER FUNCTIONS\r\n\r\n // These functions don't need access to variables,\r\n // e.g. DECIMAL_PLACES, in the scope of the `clone` function above.\r\n\r\n\r\n function bitFloor(n) {\r\n var i = n | 0;\r\n return n > 0 || n === i ? i : i - 1;\r\n }\r\n\r\n\r\n // Return a coefficient array as a string of base 10 digits.\r\n function coeffToString(a) {\r\n var s, z,\r\n i = 1,\r\n j = a.length,\r\n r = a[0] + '';\r\n\r\n for (; i < j;) {\r\n s = a[i++] + '';\r\n z = LOG_BASE - s.length;\r\n for (; z--; s = '0' + s);\r\n r += s;\r\n }\r\n\r\n // Determine trailing zeros.\r\n for (j = r.length; r.charCodeAt(--j) === 48;);\r\n\r\n return r.slice(0, j + 1 || 1);\r\n }\r\n\r\n\r\n // Compare the value of BigNumbers x and y.\r\n function compare(x, y) {\r\n var a, b,\r\n xc = x.c,\r\n yc = y.c,\r\n i = x.s,\r\n j = y.s,\r\n k = x.e,\r\n l = y.e;\r\n\r\n // Either NaN?\r\n if (!i || !j) return null;\r\n\r\n a = xc && !xc[0];\r\n b = yc && !yc[0];\r\n\r\n // Either zero?\r\n if (a || b) return a ? b ? 0 : -j : i;\r\n\r\n // Signs differ?\r\n if (i != j) return i;\r\n\r\n a = i < 0;\r\n b = k == l;\r\n\r\n // Either Infinity?\r\n if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1;\r\n\r\n // Compare exponents.\r\n if (!b) return k > l ^ a ? 1 : -1;\r\n\r\n j = (k = xc.length) < (l = yc.length) ? k : l;\r\n\r\n // Compare digit by digit.\r\n for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1;\r\n\r\n // Compare lengths.\r\n return k == l ? 0 : k > l ^ a ? 1 : -1;\r\n }\r\n\r\n\r\n /*\r\n * Check that n is a primitive number, an integer, and in range, otherwise throw.\r\n */\r\n function intCheck(n, min, max, name) {\r\n if (n < min || n > max || n !== mathfloor(n)) {\r\n throw Error\r\n (bignumberError + (name || 'Argument') + (typeof n == 'number'\r\n ? n < min || n > max ? ' out of range: ' : ' not an integer: '\r\n : ' not a primitive number: ') + String(n));\r\n }\r\n }\r\n\r\n\r\n // Assumes finite n.\r\n function isOdd(n) {\r\n var k = n.c.length - 1;\r\n return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0;\r\n }\r\n\r\n\r\n function toExponential(str, e) {\r\n return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) +\r\n (e < 0 ? 'e' : 'e+') + e;\r\n }\r\n\r\n\r\n function toFixedPoint(str, e, z) {\r\n var len, zs;\r\n\r\n // Negative exponent?\r\n if (e < 0) {\r\n\r\n // Prepend zeros.\r\n for (zs = z + '.'; ++e; zs += z);\r\n str = zs + str;\r\n\r\n // Positive exponent\r\n } else {\r\n len = str.length;\r\n\r\n // Append zeros.\r\n if (++e > len) {\r\n for (zs = z, e -= len; --e; zs += z);\r\n str += zs;\r\n } else if (e < len) {\r\n str = str.slice(0, e) + '.' + str.slice(e);\r\n }\r\n }\r\n\r\n return str;\r\n }\r\n\r\n\r\n // EXPORT\r\n\r\n\r\n BigNumber = clone();\r\n BigNumber['default'] = BigNumber.BigNumber = BigNumber;\r\n\r\n // AMD.\r\n if (typeof define == 'function' && define.amd) {\r\n define(function () { return BigNumber; });\r\n\r\n // Node.js and other environments that support module.exports.\r\n } else if (typeof module != 'undefined' && module.exports) {\r\n module.exports = BigNumber;\r\n\r\n // Browser.\r\n } else {\r\n if (!globalObject) {\r\n globalObject = typeof self != 'undefined' && self ? self : window;\r\n }\r\n\r\n globalObject.BigNumber = BigNumber;\r\n }\r\n})(this);\r\n","'use strict'\nvar DuplexStream = require('readable-stream').Duplex\n , util = require('util')\n\nfunction BufferList (callback) {\n if (!(this instanceof BufferList))\n return new BufferList(callback)\n\n this._bufs = []\n this.length = 0\n\n if (typeof callback == 'function') {\n this._callback = callback\n\n var piper = function piper (err) {\n if (this._callback) {\n this._callback(err)\n this._callback = null\n }\n }.bind(this)\n\n this.on('pipe', function onPipe (src) {\n src.on('error', piper)\n })\n this.on('unpipe', function onUnpipe (src) {\n src.removeListener('error', piper)\n })\n } else {\n this.append(callback)\n }\n\n DuplexStream.call(this)\n}\n\n\nutil.inherits(BufferList, DuplexStream)\n\n\nBufferList.prototype._offset = function _offset (offset) {\n var tot = 0, i = 0, _t\n if (offset === 0) return [ 0, 0 ]\n for (; i < this._bufs.length; i++) {\n _t = tot + this._bufs[i].length\n if (offset < _t || i == this._bufs.length - 1) {\n return [ i, offset - tot ]\n }\n tot = _t\n }\n}\n\nBufferList.prototype._reverseOffset = function (blOffset) {\n var bufferId = blOffset[0]\n var offset = blOffset[1]\n for (var i = 0; i < bufferId; i++) {\n offset += this._bufs[i].length\n }\n return offset\n}\n\nBufferList.prototype.append = function append (buf) {\n var i = 0\n\n if (Buffer.isBuffer(buf)) {\n this._appendBuffer(buf)\n } else if (Array.isArray(buf)) {\n for (; i < buf.length; i++)\n this.append(buf[i])\n } else if (buf instanceof BufferList) {\n // unwrap argument into individual BufferLists\n for (; i < buf._bufs.length; i++)\n this.append(buf._bufs[i])\n } else if (buf != null) {\n // coerce number arguments to strings, since Buffer(number) does\n // uninitialized memory allocation\n if (typeof buf == 'number')\n buf = buf.toString()\n\n this._appendBuffer(Buffer.from(buf))\n }\n\n return this\n}\n\n\nBufferList.prototype._appendBuffer = function appendBuffer (buf) {\n this._bufs.push(buf)\n this.length += buf.length\n}\n\n\nBufferList.prototype._write = function _write (buf, encoding, callback) {\n this._appendBuffer(buf)\n\n if (typeof callback == 'function')\n callback()\n}\n\n\nBufferList.prototype._read = function _read (size) {\n if (!this.length)\n return this.push(null)\n\n size = Math.min(size, this.length)\n this.push(this.slice(0, size))\n this.consume(size)\n}\n\n\nBufferList.prototype.end = function end (chunk) {\n DuplexStream.prototype.end.call(this, chunk)\n\n if (this._callback) {\n this._callback(null, this.slice())\n this._callback = null\n }\n}\n\n\nBufferList.prototype.get = function get (index) {\n if (index > this.length || index < 0) {\n return undefined\n }\n var offset = this._offset(index)\n return this._bufs[offset[0]][offset[1]]\n}\n\n\nBufferList.prototype.slice = function slice (start, end) {\n if (typeof start == 'number' && start < 0)\n start += this.length\n if (typeof end == 'number' && end < 0)\n end += this.length\n return this.copy(null, 0, start, end)\n}\n\n\nBufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {\n if (typeof srcStart != 'number' || srcStart < 0)\n srcStart = 0\n if (typeof srcEnd != 'number' || srcEnd > this.length)\n srcEnd = this.length\n if (srcStart >= this.length)\n return dst || Buffer.alloc(0)\n if (srcEnd <= 0)\n return dst || Buffer.alloc(0)\n\n var copy = !!dst\n , off = this._offset(srcStart)\n , len = srcEnd - srcStart\n , bytes = len\n , bufoff = (copy && dstStart) || 0\n , start = off[1]\n , l\n , i\n\n // copy/slice everything\n if (srcStart === 0 && srcEnd == this.length) {\n if (!copy) { // slice, but full concat if multiple buffers\n return this._bufs.length === 1\n ? this._bufs[0]\n : Buffer.concat(this._bufs, this.length)\n }\n\n // copy, need to copy individual buffers\n for (i = 0; i < this._bufs.length; i++) {\n this._bufs[i].copy(dst, bufoff)\n bufoff += this._bufs[i].length\n }\n\n return dst\n }\n\n // easy, cheap case where it's a subset of one of the buffers\n if (bytes <= this._bufs[off[0]].length - start) {\n return copy\n ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)\n : this._bufs[off[0]].slice(start, start + bytes)\n }\n\n if (!copy) // a slice, we need something to copy in to\n dst = Buffer.allocUnsafe(len)\n\n for (i = off[0]; i < this._bufs.length; i++) {\n l = this._bufs[i].length - start\n\n if (bytes > l) {\n this._bufs[i].copy(dst, bufoff, start)\n bufoff += l\n } else {\n this._bufs[i].copy(dst, bufoff, start, start + bytes)\n bufoff += l\n break\n }\n\n bytes -= l\n\n if (start)\n start = 0\n }\n\n // safeguard so that we don't return uninitialized memory\n if (dst.length > bufoff) return dst.slice(0, bufoff)\n\n return dst\n}\n\nBufferList.prototype.shallowSlice = function shallowSlice (start, end) {\n start = start || 0\n end = typeof end !== 'number' ? this.length : end\n\n if (start < 0)\n start += this.length\n if (end < 0)\n end += this.length\n\n if (start === end) {\n return new BufferList()\n }\n var startOffset = this._offset(start)\n , endOffset = this._offset(end)\n , buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1)\n\n if (endOffset[1] == 0)\n buffers.pop()\n else\n buffers[buffers.length-1] = buffers[buffers.length-1].slice(0, endOffset[1])\n\n if (startOffset[1] != 0)\n buffers[0] = buffers[0].slice(startOffset[1])\n\n return new BufferList(buffers)\n}\n\nBufferList.prototype.toString = function toString (encoding, start, end) {\n return this.slice(start, end).toString(encoding)\n}\n\nBufferList.prototype.consume = function consume (bytes) {\n // first, normalize the argument, in accordance with how Buffer does it\n bytes = Math.trunc(bytes)\n // do nothing if not a positive number\n if (Number.isNaN(bytes) || bytes <= 0) return this\n\n while (this._bufs.length) {\n if (bytes >= this._bufs[0].length) {\n bytes -= this._bufs[0].length\n this.length -= this._bufs[0].length\n this._bufs.shift()\n } else {\n this._bufs[0] = this._bufs[0].slice(bytes)\n this.length -= bytes\n break\n }\n }\n return this\n}\n\n\nBufferList.prototype.duplicate = function duplicate () {\n var i = 0\n , copy = new BufferList()\n\n for (; i < this._bufs.length; i++)\n copy.append(this._bufs[i])\n\n return copy\n}\n\n\nBufferList.prototype._destroy = function _destroy (err, cb) {\n this._bufs.length = 0\n this.length = 0\n cb(err)\n}\n\n\nBufferList.prototype.indexOf = function (search, offset, encoding) {\n if (encoding === undefined && typeof offset === 'string') {\n encoding = offset\n offset = undefined\n }\n if (typeof search === 'function' || Array.isArray(search)) {\n throw new TypeError('The \"value\" argument must be one of type string, Buffer, BufferList, or Uint8Array.')\n } else if (typeof search === 'number') {\n search = Buffer.from([search])\n } else if (typeof search === 'string') {\n search = Buffer.from(search, encoding)\n } else if (search instanceof BufferList) {\n search = search.slice()\n } else if (!Buffer.isBuffer(search)) {\n search = Buffer.from(search)\n }\n\n offset = Number(offset || 0)\n if (isNaN(offset)) {\n offset = 0\n }\n\n if (offset < 0) {\n offset = this.length + offset\n }\n\n if (offset < 0) {\n offset = 0\n }\n\n if (search.length === 0) {\n return offset > this.length ? this.length : offset\n }\n\n var blOffset = this._offset(offset)\n var blIndex = blOffset[0] // index of which internal buffer we're working on\n var buffOffset = blOffset[1] // offset of the internal buffer we're working on\n\n // scan over each buffer\n for (blIndex; blIndex < this._bufs.length; blIndex++) {\n var buff = this._bufs[blIndex]\n while(buffOffset < buff.length) {\n var availableWindow = buff.length - buffOffset\n if (availableWindow >= search.length) {\n var nativeSearchResult = buff.indexOf(search, buffOffset)\n if (nativeSearchResult !== -1) {\n return this._reverseOffset([blIndex, nativeSearchResult])\n }\n buffOffset = buff.length - search.length + 1 // end of native search window\n } else {\n var revOffset = this._reverseOffset([blIndex, buffOffset])\n if (this._match(revOffset, search)) {\n return revOffset\n }\n buffOffset++\n }\n }\n buffOffset = 0\n }\n return -1\n}\n\nBufferList.prototype._match = function(offset, search) {\n if (this.length - offset < search.length) {\n return false\n }\n for (var searchOffset = 0; searchOffset < search.length ; searchOffset++) {\n if(this.get(offset + searchOffset) !== search[searchOffset]){\n return false\n }\n }\n return true\n}\n\n\n;(function () {\n var methods = {\n 'readDoubleBE' : 8\n , 'readDoubleLE' : 8\n , 'readFloatBE' : 4\n , 'readFloatLE' : 4\n , 'readInt32BE' : 4\n , 'readInt32LE' : 4\n , 'readUInt32BE' : 4\n , 'readUInt32LE' : 4\n , 'readInt16BE' : 2\n , 'readInt16LE' : 2\n , 'readUInt16BE' : 2\n , 'readUInt16LE' : 2\n , 'readInt8' : 1\n , 'readUInt8' : 1\n , 'readIntBE' : null\n , 'readIntLE' : null\n , 'readUIntBE' : null\n , 'readUIntLE' : null\n }\n\n for (var m in methods) {\n (function (m) {\n if (methods[m] === null) {\n BufferList.prototype[m] = function (offset, byteLength) {\n return this.slice(offset, offset + byteLength)[m](0, byteLength)\n }\n }\n else {\n BufferList.prototype[m] = function (offset) {\n return this.slice(offset, offset + methods[m])[m](0)\n }\n }\n }(m))\n }\n}())\n\n\nmodule.exports = BufferList\n","var concatMap = require('concat-map');\nvar balanced = require('balanced-match');\n\nmodule.exports = expandTop;\n\nvar escSlash = '\\0SLASH'+Math.random()+'\\0';\nvar escOpen = '\\0OPEN'+Math.random()+'\\0';\nvar escClose = '\\0CLOSE'+Math.random()+'\\0';\nvar escComma = '\\0COMMA'+Math.random()+'\\0';\nvar escPeriod = '\\0PERIOD'+Math.random()+'\\0';\n\nfunction numeric(str) {\n return parseInt(str, 10) == str\n ? parseInt(str, 10)\n : str.charCodeAt(0);\n}\n\nfunction escapeBraces(str) {\n return str.split('\\\\\\\\').join(escSlash)\n .split('\\\\{').join(escOpen)\n .split('\\\\}').join(escClose)\n .split('\\\\,').join(escComma)\n .split('\\\\.').join(escPeriod);\n}\n\nfunction unescapeBraces(str) {\n return str.split(escSlash).join('\\\\')\n .split(escOpen).join('{')\n .split(escClose).join('}')\n .split(escComma).join(',')\n .split(escPeriod).join('.');\n}\n\n\n// Basically just str.split(\",\"), but handling cases\n// where we have nested braced sections, which should be\n// treated as individual members, like {a,{b,c},d}\nfunction parseCommaParts(str) {\n if (!str)\n return [''];\n\n var parts = [];\n var m = balanced('{', '}', str);\n\n if (!m)\n return str.split(',');\n\n var pre = m.pre;\n var body = m.body;\n var post = m.post;\n var p = pre.split(',');\n\n p[p.length-1] += '{' + body + '}';\n var postParts = parseCommaParts(post);\n if (post.length) {\n p[p.length-1] += postParts.shift();\n p.push.apply(p, postParts);\n }\n\n parts.push.apply(parts, p);\n\n return parts;\n}\n\nfunction expandTop(str) {\n if (!str)\n return [];\n\n // I don't know why Bash 4.3 does this, but it does.\n // Anything starting with {} will have the first two bytes preserved\n // but *only* at the top level, so {},a}b will not expand to anything,\n // but a{},b}c will be expanded to [a}c,abc].\n // One could argue that this is a bug in Bash, but since the goal of\n // this module is to match Bash's rules, we escape a leading {}\n if (str.substr(0, 2) === '{}') {\n str = '\\\\{\\\\}' + str.substr(2);\n }\n\n return expand(escapeBraces(str), true).map(unescapeBraces);\n}\n\nfunction identity(e) {\n return e;\n}\n\nfunction embrace(str) {\n return '{' + str + '}';\n}\nfunction isPadded(el) {\n return /^-?0\\d/.test(el);\n}\n\nfunction lte(i, y) {\n return i <= y;\n}\nfunction gte(i, y) {\n return i >= y;\n}\n\nfunction expand(str, isTop) {\n var expansions = [];\n\n var m = balanced('{', '}', str);\n if (!m || /\\$$/.test(m.pre)) return [str];\n\n var isNumericSequence = /^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(m.body);\n var isAlphaSequence = /^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(m.body);\n var isSequence = isNumericSequence || isAlphaSequence;\n var isOptions = m.body.indexOf(',') >= 0;\n if (!isSequence && !isOptions) {\n // {a},b}\n if (m.post.match(/,.*\\}/)) {\n str = m.pre + '{' + m.body + escClose + m.post;\n return expand(str);\n }\n return [str];\n }\n\n var n;\n if (isSequence) {\n n = m.body.split(/\\.\\./);\n } else {\n n = parseCommaParts(m.body);\n if (n.length === 1) {\n // x{{a,b}}y ==> x{a}y x{b}y\n n = expand(n[0], false).map(embrace);\n if (n.length === 1) {\n var post = m.post.length\n ? expand(m.post, false)\n : [''];\n return post.map(function(p) {\n return m.pre + n[0] + p;\n });\n }\n }\n }\n\n // at this point, n is the parts, and we know it's not a comma set\n // with a single entry.\n\n // no need to expand pre, since it is guaranteed to be free of brace-sets\n var pre = m.pre;\n var post = m.post.length\n ? expand(m.post, false)\n : [''];\n\n var N;\n\n if (isSequence) {\n var x = numeric(n[0]);\n var y = numeric(n[1]);\n var width = Math.max(n[0].length, n[1].length)\n var incr = n.length == 3\n ? Math.abs(numeric(n[2]))\n : 1;\n var test = lte;\n var reverse = y < x;\n if (reverse) {\n incr *= -1;\n test = gte;\n }\n var pad = n.some(isPadded);\n\n N = [];\n\n for (var i = x; test(i, y); i += incr) {\n var c;\n if (isAlphaSequence) {\n c = String.fromCharCode(i);\n if (c === '\\\\')\n c = '';\n } else {\n c = String(i);\n if (pad) {\n var need = width - c.length;\n if (need > 0) {\n var z = new Array(need + 1).join('0');\n if (i < 0)\n c = '-' + z + c.slice(1);\n else\n c = z + c;\n }\n }\n }\n N.push(c);\n }\n } else {\n N = concatMap(n, function(el) { return expand(el, false) });\n }\n\n for (var j = 0; j < N.length; j++) {\n for (var k = 0; k < post.length; k++) {\n var expansion = pre + N[j] + post[k];\n if (!isTop || isSequence || expansion)\n expansions.push(expansion);\n }\n }\n\n return expansions;\n}\n\n","/*jshint node:true */\n'use strict';\nvar Buffer = require('buffer').Buffer; // browserify\nvar SlowBuffer = require('buffer').SlowBuffer;\n\nmodule.exports = bufferEq;\n\nfunction bufferEq(a, b) {\n\n // shortcutting on type is necessary for correctness\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n return false;\n }\n\n // buffer sizes should be well-known information, so despite this\n // shortcutting, it doesn't leak any information about the *contents* of the\n // buffers.\n if (a.length !== b.length) {\n return false;\n }\n\n var c = 0;\n for (var i = 0; i < a.length; i++) {\n /*jshint bitwise:false */\n c |= a[i] ^ b[i]; // XOR\n }\n return c === 0;\n}\n\nbufferEq.install = function() {\n Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) {\n return bufferEq(this, that);\n };\n};\n\nvar origBufEqual = Buffer.prototype.equal;\nvar origSlowBufEqual = SlowBuffer.prototype.equal;\nbufferEq.restore = function() {\n Buffer.prototype.equal = origBufEqual;\n SlowBuffer.prototype.equal = origSlowBufEqual;\n};\n","function Caseless (dict) {\n this.dict = dict || {}\n}\nCaseless.prototype.set = function (name, value, clobber) {\n if (typeof name === 'object') {\n for (var i in name) {\n this.set(i, name[i], value)\n }\n } else {\n if (typeof clobber === 'undefined') clobber = true\n var has = this.has(name)\n\n if (!clobber && has) this.dict[has] = this.dict[has] + ',' + value\n else this.dict[has || name] = value\n return has\n }\n}\nCaseless.prototype.has = function (name) {\n var keys = Object.keys(this.dict)\n , name = name.toLowerCase()\n ;\n for (var i=0;i {\n\tif (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {\n\t\tthrow new Error('The `level` option should be an integer from 0 to 3');\n\t}\n\n\t// Detect level if not set manually\n\tconst colorLevel = stdoutColor ? stdoutColor.level : 0;\n\tobject.level = options.level === undefined ? colorLevel : options.level;\n};\n\nclass ChalkClass {\n\tconstructor(options) {\n\t\t// eslint-disable-next-line no-constructor-return\n\t\treturn chalkFactory(options);\n\t}\n}\n\nconst chalkFactory = options => {\n\tconst chalk = {};\n\tapplyOptions(chalk, options);\n\n\tchalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);\n\n\tObject.setPrototypeOf(chalk, Chalk.prototype);\n\tObject.setPrototypeOf(chalk.template, chalk);\n\n\tchalk.template.constructor = () => {\n\t\tthrow new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');\n\t};\n\n\tchalk.template.Instance = ChalkClass;\n\n\treturn chalk.template;\n};\n\nfunction Chalk(options) {\n\treturn chalkFactory(options);\n}\n\nfor (const [styleName, style] of Object.entries(ansiStyles)) {\n\tstyles[styleName] = {\n\t\tget() {\n\t\t\tconst builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);\n\t\t\tObject.defineProperty(this, styleName, {value: builder});\n\t\t\treturn builder;\n\t\t}\n\t};\n}\n\nstyles.visible = {\n\tget() {\n\t\tconst builder = createBuilder(this, this._styler, true);\n\t\tObject.defineProperty(this, 'visible', {value: builder});\n\t\treturn builder;\n\t}\n};\n\nconst usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];\n\nfor (const model of usedModels) {\n\tstyles[model] = {\n\t\tget() {\n\t\t\tconst {level} = this;\n\t\t\treturn function (...arguments_) {\n\t\t\t\tconst styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler);\n\t\t\t\treturn createBuilder(this, styler, this._isEmpty);\n\t\t\t};\n\t\t}\n\t};\n}\n\nfor (const model of usedModels) {\n\tconst bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);\n\tstyles[bgModel] = {\n\t\tget() {\n\t\t\tconst {level} = this;\n\t\t\treturn function (...arguments_) {\n\t\t\t\tconst styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler);\n\t\t\t\treturn createBuilder(this, styler, this._isEmpty);\n\t\t\t};\n\t\t}\n\t};\n}\n\nconst proto = Object.defineProperties(() => {}, {\n\t...styles,\n\tlevel: {\n\t\tenumerable: true,\n\t\tget() {\n\t\t\treturn this._generator.level;\n\t\t},\n\t\tset(level) {\n\t\t\tthis._generator.level = level;\n\t\t}\n\t}\n});\n\nconst createStyler = (open, close, parent) => {\n\tlet openAll;\n\tlet closeAll;\n\tif (parent === undefined) {\n\t\topenAll = open;\n\t\tcloseAll = close;\n\t} else {\n\t\topenAll = parent.openAll + open;\n\t\tcloseAll = close + parent.closeAll;\n\t}\n\n\treturn {\n\t\topen,\n\t\tclose,\n\t\topenAll,\n\t\tcloseAll,\n\t\tparent\n\t};\n};\n\nconst createBuilder = (self, _styler, _isEmpty) => {\n\tconst builder = (...arguments_) => {\n\t\tif (isArray(arguments_[0]) && isArray(arguments_[0].raw)) {\n\t\t\t// Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`\n\t\t\treturn applyStyle(builder, chalkTag(builder, ...arguments_));\n\t\t}\n\n\t\t// Single argument is hot path, implicit coercion is faster than anything\n\t\t// eslint-disable-next-line no-implicit-coercion\n\t\treturn applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));\n\t};\n\n\t// We alter the prototype because we must return a function, but there is\n\t// no way to create a function with a different prototype\n\tObject.setPrototypeOf(builder, proto);\n\n\tbuilder._generator = self;\n\tbuilder._styler = _styler;\n\tbuilder._isEmpty = _isEmpty;\n\n\treturn builder;\n};\n\nconst applyStyle = (self, string) => {\n\tif (self.level <= 0 || !string) {\n\t\treturn self._isEmpty ? '' : string;\n\t}\n\n\tlet styler = self._styler;\n\n\tif (styler === undefined) {\n\t\treturn string;\n\t}\n\n\tconst {openAll, closeAll} = styler;\n\tif (string.indexOf('\\u001B') !== -1) {\n\t\twhile (styler !== undefined) {\n\t\t\t// Replace any instances already present with a re-opening code\n\t\t\t// otherwise only the part of the string until said closing code\n\t\t\t// will be colored, and the rest will simply be 'plain'.\n\t\t\tstring = stringReplaceAll(string, styler.close, styler.open);\n\n\t\t\tstyler = styler.parent;\n\t\t}\n\t}\n\n\t// We can move both next actions out of loop, because remaining actions in loop won't have\n\t// any/visible effect on parts we add here. Close the styling before a linebreak and reopen\n\t// after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92\n\tconst lfIndex = string.indexOf('\\n');\n\tif (lfIndex !== -1) {\n\t\tstring = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);\n\t}\n\n\treturn openAll + string + closeAll;\n};\n\nlet template;\nconst chalkTag = (chalk, ...strings) => {\n\tconst [firstString] = strings;\n\n\tif (!isArray(firstString) || !isArray(firstString.raw)) {\n\t\t// If chalk() was called by itself or with a string,\n\t\t// return the string itself as a string.\n\t\treturn strings.join(' ');\n\t}\n\n\tconst arguments_ = strings.slice(1);\n\tconst parts = [firstString.raw[0]];\n\n\tfor (let i = 1; i < firstString.length; i++) {\n\t\tparts.push(\n\t\t\tString(arguments_[i - 1]).replace(/[{}\\\\]/g, '\\\\$&'),\n\t\t\tString(firstString.raw[i])\n\t\t);\n\t}\n\n\tif (template === undefined) {\n\t\ttemplate = require('./templates');\n\t}\n\n\treturn template(chalk, parts.join(''));\n};\n\nObject.defineProperties(Chalk.prototype, styles);\n\nconst chalk = Chalk(); // eslint-disable-line new-cap\nchalk.supportsColor = stdoutColor;\nchalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap\nchalk.stderr.supportsColor = stderrColor;\n\nmodule.exports = chalk;\n","'use strict';\nconst TEMPLATE_REGEX = /(?:\\\\(u(?:[a-f\\d]{4}|\\{[a-f\\d]{1,6}\\})|x[a-f\\d]{2}|.))|(?:\\{(~)?(\\w+(?:\\([^)]*\\))?(?:\\.\\w+(?:\\([^)]*\\))?)*)(?:[ \\t]|(?=\\r?\\n)))|(\\})|((?:.|[\\r\\n\\f])+?)/gi;\nconst STYLE_REGEX = /(?:^|\\.)(\\w+)(?:\\(([^)]*)\\))?/g;\nconst STRING_REGEX = /^(['\"])((?:\\\\.|(?!\\1)[^\\\\])*)\\1$/;\nconst ESCAPE_REGEX = /\\\\(u(?:[a-f\\d]{4}|{[a-f\\d]{1,6}})|x[a-f\\d]{2}|.)|([^\\\\])/gi;\n\nconst ESCAPES = new Map([\n\t['n', '\\n'],\n\t['r', '\\r'],\n\t['t', '\\t'],\n\t['b', '\\b'],\n\t['f', '\\f'],\n\t['v', '\\v'],\n\t['0', '\\0'],\n\t['\\\\', '\\\\'],\n\t['e', '\\u001B'],\n\t['a', '\\u0007']\n]);\n\nfunction unescape(c) {\n\tconst u = c[0] === 'u';\n\tconst bracket = c[1] === '{';\n\n\tif ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) {\n\t\treturn String.fromCharCode(parseInt(c.slice(1), 16));\n\t}\n\n\tif (u && bracket) {\n\t\treturn String.fromCodePoint(parseInt(c.slice(2, -1), 16));\n\t}\n\n\treturn ESCAPES.get(c) || c;\n}\n\nfunction parseArguments(name, arguments_) {\n\tconst results = [];\n\tconst chunks = arguments_.trim().split(/\\s*,\\s*/g);\n\tlet matches;\n\n\tfor (const chunk of chunks) {\n\t\tconst number = Number(chunk);\n\t\tif (!Number.isNaN(number)) {\n\t\t\tresults.push(number);\n\t\t} else if ((matches = chunk.match(STRING_REGEX))) {\n\t\t\tresults.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character));\n\t\t} else {\n\t\t\tthrow new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);\n\t\t}\n\t}\n\n\treturn results;\n}\n\nfunction parseStyle(style) {\n\tSTYLE_REGEX.lastIndex = 0;\n\n\tconst results = [];\n\tlet matches;\n\n\twhile ((matches = STYLE_REGEX.exec(style)) !== null) {\n\t\tconst name = matches[1];\n\n\t\tif (matches[2]) {\n\t\t\tconst args = parseArguments(name, matches[2]);\n\t\t\tresults.push([name].concat(args));\n\t\t} else {\n\t\t\tresults.push([name]);\n\t\t}\n\t}\n\n\treturn results;\n}\n\nfunction buildStyle(chalk, styles) {\n\tconst enabled = {};\n\n\tfor (const layer of styles) {\n\t\tfor (const style of layer.styles) {\n\t\t\tenabled[style[0]] = layer.inverse ? null : style.slice(1);\n\t\t}\n\t}\n\n\tlet current = chalk;\n\tfor (const [styleName, styles] of Object.entries(enabled)) {\n\t\tif (!Array.isArray(styles)) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!(styleName in current)) {\n\t\t\tthrow new Error(`Unknown Chalk style: ${styleName}`);\n\t\t}\n\n\t\tcurrent = styles.length > 0 ? current[styleName](...styles) : current[styleName];\n\t}\n\n\treturn current;\n}\n\nmodule.exports = (chalk, temporary) => {\n\tconst styles = [];\n\tconst chunks = [];\n\tlet chunk = [];\n\n\t// eslint-disable-next-line max-params\n\ttemporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => {\n\t\tif (escapeCharacter) {\n\t\t\tchunk.push(unescape(escapeCharacter));\n\t\t} else if (style) {\n\t\t\tconst string = chunk.join('');\n\t\t\tchunk = [];\n\t\t\tchunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string));\n\t\t\tstyles.push({inverse, styles: parseStyle(style)});\n\t\t} else if (close) {\n\t\t\tif (styles.length === 0) {\n\t\t\t\tthrow new Error('Found extraneous } in Chalk template literal');\n\t\t\t}\n\n\t\t\tchunks.push(buildStyle(chalk, styles)(chunk.join('')));\n\t\t\tchunk = [];\n\t\t\tstyles.pop();\n\t\t} else {\n\t\t\tchunk.push(character);\n\t\t}\n\t});\n\n\tchunks.push(chunk.join(''));\n\n\tif (styles.length > 0) {\n\t\tconst errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\\`}\\`)`;\n\t\tthrow new Error(errMessage);\n\t}\n\n\treturn chunks.join('');\n};\n","'use strict';\n\nconst stringReplaceAll = (string, substring, replacer) => {\n\tlet index = string.indexOf(substring);\n\tif (index === -1) {\n\t\treturn string;\n\t}\n\n\tconst substringLength = substring.length;\n\tlet endIndex = 0;\n\tlet returnValue = '';\n\tdo {\n\t\treturnValue += string.substr(endIndex, index - endIndex) + substring + replacer;\n\t\tendIndex = index + substringLength;\n\t\tindex = string.indexOf(substring, endIndex);\n\t} while (index !== -1);\n\n\treturnValue += string.substr(endIndex);\n\treturn returnValue;\n};\n\nconst stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => {\n\tlet endIndex = 0;\n\tlet returnValue = '';\n\tdo {\n\t\tconst gotCR = string[index - 1] === '\\r';\n\t\treturnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\\r\\n' : '\\n') + postfix;\n\t\tendIndex = index + 1;\n\t\tindex = string.indexOf('\\n', endIndex);\n\t} while (index !== -1);\n\n\treturnValue += string.substr(endIndex);\n\treturn returnValue;\n};\n\nmodule.exports = {\n\tstringReplaceAll,\n\tstringEncaseCRLFWithFirstIndex\n};\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.supportsLanguage = exports.listLanguages = exports.highlight = void 0;\nvar hljs = __importStar(require(\"highlight.js\"));\nvar parse5 = __importStar(require(\"parse5\"));\nvar parse5_htmlparser2_tree_adapter_1 = __importDefault(require(\"parse5-htmlparser2-tree-adapter\"));\nvar theme_1 = require(\"./theme\");\nfunction colorizeNode(node, theme, context) {\n if (theme === void 0) { theme = {}; }\n switch (node.type) {\n case 'text': {\n var text = node.data;\n if (context === undefined) {\n return (theme.default || theme_1.DEFAULT_THEME.default || theme_1.plain)(text);\n }\n return text;\n }\n case 'tag': {\n var hljsClass = /hljs-(\\w+)/.exec(node.attribs.class);\n if (hljsClass) {\n var token_1 = hljsClass[1];\n var nodeData = node.childNodes\n .map(function (node) { return colorizeNode(node, theme, token_1); })\n .join('');\n return (theme[token_1] || theme_1.DEFAULT_THEME[token_1] || theme_1.plain)(nodeData);\n }\n // Return the data itself when the class name isn't prefixed with a highlight.js token prefix.\n // This is common in instances of sublanguages (JSX, Markdown Code Blocks, etc.)\n return node.childNodes.map(function (node) { return colorizeNode(node, theme); }).join('');\n }\n }\n throw new Error('Invalid node type ' + node.type);\n}\nfunction colorize(code, theme) {\n if (theme === void 0) { theme = {}; }\n var fragment = parse5.parseFragment(code, {\n treeAdapter: parse5_htmlparser2_tree_adapter_1.default,\n });\n return fragment.childNodes.map(function (node) { return colorizeNode(node, theme); }).join('');\n}\n/**\n * Apply syntax highlighting to `code` with ASCII color codes. The language is automatically\n * detected if not set.\n *\n * ```ts\n * import {highlight} from 'cli-highlight';\n * import * as fs from 'fs';\n *\n * fs.readFile('package.json', 'utf8', (err: any, json: string) => {\n * console.log('package.json:');\n * console.log(highlight(json));\n * });\n * ```\n *\n * @param code The code to highlight\n * @param options Optional options\n */\nfunction highlight(code, options) {\n if (options === void 0) { options = {}; }\n var html;\n if (options.language) {\n html = hljs.highlight(code, { language: options.language, ignoreIllegals: options.ignoreIllegals }).value;\n }\n else {\n html = hljs.highlightAuto(code, options.languageSubset).value;\n }\n return colorize(html, options.theme);\n}\nexports.highlight = highlight;\n/**\n * Returns all supported languages\n */\nfunction listLanguages() {\n return hljs.listLanguages();\n}\nexports.listLanguages = listLanguages;\n/**\n * Returns true if the language is supported\n * @param name A language name, alias or file extension\n */\nfunction supportsLanguage(name) {\n return !!hljs.getLanguage(name);\n}\nexports.supportsLanguage = supportsLanguage;\nexports.default = highlight;\n__exportStar(require(\"./theme\"), exports);\n//# sourceMappingURL=index.js.map","\"use strict\";\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.parse = exports.stringify = exports.toJson = exports.fromJson = exports.DEFAULT_THEME = exports.plain = void 0;\nvar chalk_1 = __importDefault(require(\"chalk\"));\n/**\n * Identity function for tokens that should not be styled (returns the input string as-is).\n * See [[Theme]] for an example.\n */\nvar plain = function (codePart) { return codePart; };\nexports.plain = plain;\n/**\n * The default theme. It is possible to override just individual keys.\n */\nexports.DEFAULT_THEME = {\n /**\n * keyword in a regular Algol-style language\n */\n keyword: chalk_1.default.blue,\n /**\n * built-in or library object (constant, class, function)\n */\n built_in: chalk_1.default.cyan,\n /**\n * user-defined type in a language with first-class syntactically significant types, like\n * Haskell\n */\n type: chalk_1.default.cyan.dim,\n /**\n * special identifier for a built-in value (\"true\", \"false\", \"null\")\n */\n literal: chalk_1.default.blue,\n /**\n * number, including units and modifiers, if any.\n */\n number: chalk_1.default.green,\n /**\n * literal regular expression\n */\n regexp: chalk_1.default.red,\n /**\n * literal string, character\n */\n string: chalk_1.default.red,\n /**\n * parsed section inside a literal string\n */\n subst: exports.plain,\n /**\n * symbolic constant, interned string, goto label\n */\n symbol: exports.plain,\n /**\n * class or class-level declaration (interfaces, traits, modules, etc)\n */\n class: chalk_1.default.blue,\n /**\n * function or method declaration\n */\n function: chalk_1.default.yellow,\n /**\n * name of a class or a function at the place of declaration\n */\n title: exports.plain,\n /**\n * block of function arguments (parameters) at the place of declaration\n */\n params: exports.plain,\n /**\n * comment\n */\n comment: chalk_1.default.green,\n /**\n * documentation markup within comments\n */\n doctag: chalk_1.default.green,\n /**\n * flags, modifiers, annotations, processing instructions, preprocessor directive, etc\n */\n meta: chalk_1.default.grey,\n /**\n * keyword or built-in within meta construct\n */\n 'meta-keyword': exports.plain,\n /**\n * string within meta construct\n */\n 'meta-string': exports.plain,\n /**\n * heading of a section in a config file, heading in text markup\n */\n section: exports.plain,\n /**\n * XML/HTML tag\n */\n tag: chalk_1.default.grey,\n /**\n * name of an XML tag, the first word in an s-expression\n */\n name: chalk_1.default.blue,\n /**\n * s-expression name from the language standard library\n */\n 'builtin-name': exports.plain,\n /**\n * name of an attribute with no language defined semantics (keys in JSON, setting names in\n * .ini), also sub-attribute within another highlighted object, like XML tag\n */\n attr: chalk_1.default.cyan,\n /**\n * name of an attribute followed by a structured value part, like CSS properties\n */\n attribute: exports.plain,\n /**\n * variable in a config or a template file, environment var expansion in a script\n */\n variable: exports.plain,\n /**\n * list item bullet in text markup\n */\n bullet: exports.plain,\n /**\n * code block in text markup\n */\n code: exports.plain,\n /**\n * emphasis in text markup\n */\n emphasis: chalk_1.default.italic,\n /**\n * strong emphasis in text markup\n */\n strong: chalk_1.default.bold,\n /**\n * mathematical formula in text markup\n */\n formula: exports.plain,\n /**\n * hyperlink in text markup\n */\n link: chalk_1.default.underline,\n /**\n * quotation in text markup\n */\n quote: exports.plain,\n /**\n * tag selector in CSS\n */\n 'selector-tag': exports.plain,\n /**\n * #id selector in CSS\n */\n 'selector-id': exports.plain,\n /**\n * .class selector in CSS\n */\n 'selector-class': exports.plain,\n /**\n * [attr] selector in CSS\n */\n 'selector-attr': exports.plain,\n /**\n * :pseudo selector in CSS\n */\n 'selector-pseudo': exports.plain,\n /**\n * tag of a template language\n */\n 'template-tag': exports.plain,\n /**\n * variable in a template language\n */\n 'template-variable': exports.plain,\n /**\n * added or changed line in a diff\n */\n addition: chalk_1.default.green,\n /**\n * deleted line in a diff\n */\n deletion: chalk_1.default.red,\n /**\n * things not matched by any token\n */\n default: exports.plain,\n};\n/**\n * Converts a [[JsonTheme]] with string values to a [[Theme]] with formatter functions. Used by [[parse]].\n */\nfunction fromJson(json) {\n var theme = {};\n for (var _i = 0, _a = Object.keys(json); _i < _a.length; _i++) {\n var key = _a[_i];\n var style = json[key];\n if (Array.isArray(style)) {\n ;\n theme[key] = style.reduce(function (previous, current) { return (current === 'plain' ? exports.plain : previous[current]); }, chalk_1.default);\n }\n else {\n ;\n theme[key] = chalk_1.default[style];\n }\n }\n return theme;\n}\nexports.fromJson = fromJson;\n/**\n * Converts a [[Theme]] with formatter functions to a [[JsonTheme]] with string values. Used by [[stringify]].\n */\nfunction toJson(theme) {\n var jsonTheme = {};\n for (var _i = 0, _a = Object.keys(jsonTheme); _i < _a.length; _i++) {\n var key = _a[_i];\n var style = jsonTheme[key];\n jsonTheme[key] = style._styles;\n }\n return jsonTheme;\n}\nexports.toJson = toJson;\n/**\n * Stringifies a [[Theme]] with formatter functions to a JSON string.\n *\n * ```ts\n * import chalk = require('chalk');\n * import {stringify} from 'cli-highlight';\n * import * as fs from 'fs';\n *\n * const myTheme: Theme = {\n * keyword: chalk.red.bold,\n * addition: chalk.green,\n * deletion: chalk.red.strikethrough,\n * number: plain\n * }\n * const json = stringify(myTheme);\n * fs.writeFile('mytheme.json', json, (err: any) => {\n * if (err) throw err;\n * console.log('Theme saved');\n * });\n * ```\n */\nfunction stringify(theme) {\n return JSON.stringify(toJson(theme));\n}\nexports.stringify = stringify;\n/**\n * Parses a JSON string into a [[Theme]] with formatter functions.\n *\n * ```ts\n * import * as fs from 'fs';\n * import {parse, highlight} from 'cli-highlight';\n *\n * fs.readFile('mytheme.json', 'utf8', (err: any, json: string) => {\n * if (err) throw err;\n * const code = highlight('SELECT * FROM table', {theme: parse(json)});\n * console.log(code);\n * });\n * ```\n */\nfunction parse(json) {\n return fromJson(JSON.parse(json));\n}\nexports.parse = parse;\n//# sourceMappingURL=theme.js.map","'use strict';\n\nconst { DOCUMENT_MODE } = require('./html');\n\n//Const\nconst VALID_DOCTYPE_NAME = 'html';\nconst VALID_SYSTEM_ID = 'about:legacy-compat';\nconst QUIRKS_MODE_SYSTEM_ID = 'http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd';\n\nconst QUIRKS_MODE_PUBLIC_ID_PREFIXES = [\n '+//silmaril//dtd html pro v0r11 19970101//',\n '-//as//dtd html 3.0 aswedit + extensions//',\n '-//advasoft ltd//dtd html 3.0 aswedit + extensions//',\n '-//ietf//dtd html 2.0 level 1//',\n '-//ietf//dtd html 2.0 level 2//',\n '-//ietf//dtd html 2.0 strict level 1//',\n '-//ietf//dtd html 2.0 strict level 2//',\n '-//ietf//dtd html 2.0 strict//',\n '-//ietf//dtd html 2.0//',\n '-//ietf//dtd html 2.1e//',\n '-//ietf//dtd html 3.0//',\n '-//ietf//dtd html 3.2 final//',\n '-//ietf//dtd html 3.2//',\n '-//ietf//dtd html 3//',\n '-//ietf//dtd html level 0//',\n '-//ietf//dtd html level 1//',\n '-//ietf//dtd html level 2//',\n '-//ietf//dtd html level 3//',\n '-//ietf//dtd html strict level 0//',\n '-//ietf//dtd html strict level 1//',\n '-//ietf//dtd html strict level 2//',\n '-//ietf//dtd html strict level 3//',\n '-//ietf//dtd html strict//',\n '-//ietf//dtd html//',\n '-//metrius//dtd metrius presentational//',\n '-//microsoft//dtd internet explorer 2.0 html strict//',\n '-//microsoft//dtd internet explorer 2.0 html//',\n '-//microsoft//dtd internet explorer 2.0 tables//',\n '-//microsoft//dtd internet explorer 3.0 html strict//',\n '-//microsoft//dtd internet explorer 3.0 html//',\n '-//microsoft//dtd internet explorer 3.0 tables//',\n '-//netscape comm. corp.//dtd html//',\n '-//netscape comm. corp.//dtd strict html//',\n \"-//o'reilly and associates//dtd html 2.0//\",\n \"-//o'reilly and associates//dtd html extended 1.0//\",\n \"-//o'reilly and associates//dtd html extended relaxed 1.0//\",\n '-//sq//dtd html 2.0 hotmetal + extensions//',\n '-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//',\n '-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//',\n '-//spyglass//dtd html 2.0 extended//',\n '-//sun microsystems corp.//dtd hotjava html//',\n '-//sun microsystems corp.//dtd hotjava strict html//',\n '-//w3c//dtd html 3 1995-03-24//',\n '-//w3c//dtd html 3.2 draft//',\n '-//w3c//dtd html 3.2 final//',\n '-//w3c//dtd html 3.2//',\n '-//w3c//dtd html 3.2s draft//',\n '-//w3c//dtd html 4.0 frameset//',\n '-//w3c//dtd html 4.0 transitional//',\n '-//w3c//dtd html experimental 19960712//',\n '-//w3c//dtd html experimental 970421//',\n '-//w3c//dtd w3 html//',\n '-//w3o//dtd w3 html 3.0//',\n '-//webtechs//dtd mozilla html 2.0//',\n '-//webtechs//dtd mozilla html//'\n];\n\nconst QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES = QUIRKS_MODE_PUBLIC_ID_PREFIXES.concat([\n '-//w3c//dtd html 4.01 frameset//',\n '-//w3c//dtd html 4.01 transitional//'\n]);\n\nconst QUIRKS_MODE_PUBLIC_IDS = ['-//w3o//dtd w3 html strict 3.0//en//', '-/w3c/dtd html 4.0 transitional/en', 'html'];\nconst LIMITED_QUIRKS_PUBLIC_ID_PREFIXES = ['-//w3c//dtd xhtml 1.0 frameset//', '-//w3c//dtd xhtml 1.0 transitional//'];\n\nconst LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES = LIMITED_QUIRKS_PUBLIC_ID_PREFIXES.concat([\n '-//w3c//dtd html 4.01 frameset//',\n '-//w3c//dtd html 4.01 transitional//'\n]);\n\n//Utils\nfunction enquoteDoctypeId(id) {\n const quote = id.indexOf('\"') !== -1 ? \"'\" : '\"';\n\n return quote + id + quote;\n}\n\nfunction hasPrefix(publicId, prefixes) {\n for (let i = 0; i < prefixes.length; i++) {\n if (publicId.indexOf(prefixes[i]) === 0) {\n return true;\n }\n }\n\n return false;\n}\n\n//API\nexports.isConforming = function(token) {\n return (\n token.name === VALID_DOCTYPE_NAME &&\n token.publicId === null &&\n (token.systemId === null || token.systemId === VALID_SYSTEM_ID)\n );\n};\n\nexports.getDocumentMode = function(token) {\n if (token.name !== VALID_DOCTYPE_NAME) {\n return DOCUMENT_MODE.QUIRKS;\n }\n\n const systemId = token.systemId;\n\n if (systemId && systemId.toLowerCase() === QUIRKS_MODE_SYSTEM_ID) {\n return DOCUMENT_MODE.QUIRKS;\n }\n\n let publicId = token.publicId;\n\n if (publicId !== null) {\n publicId = publicId.toLowerCase();\n\n if (QUIRKS_MODE_PUBLIC_IDS.indexOf(publicId) > -1) {\n return DOCUMENT_MODE.QUIRKS;\n }\n\n let prefixes = systemId === null ? QUIRKS_MODE_NO_SYSTEM_ID_PUBLIC_ID_PREFIXES : QUIRKS_MODE_PUBLIC_ID_PREFIXES;\n\n if (hasPrefix(publicId, prefixes)) {\n return DOCUMENT_MODE.QUIRKS;\n }\n\n prefixes =\n systemId === null ? LIMITED_QUIRKS_PUBLIC_ID_PREFIXES : LIMITED_QUIRKS_WITH_SYSTEM_ID_PUBLIC_ID_PREFIXES;\n\n if (hasPrefix(publicId, prefixes)) {\n return DOCUMENT_MODE.LIMITED_QUIRKS;\n }\n }\n\n return DOCUMENT_MODE.NO_QUIRKS;\n};\n\nexports.serializeContent = function(name, publicId, systemId) {\n let str = '!DOCTYPE ';\n\n if (name) {\n str += name;\n }\n\n if (publicId) {\n str += ' PUBLIC ' + enquoteDoctypeId(publicId);\n } else if (systemId) {\n str += ' SYSTEM';\n }\n\n if (systemId !== null) {\n str += ' ' + enquoteDoctypeId(systemId);\n }\n\n return str;\n};\n","'use strict';\n\nmodule.exports = {\n controlCharacterInInputStream: 'control-character-in-input-stream',\n noncharacterInInputStream: 'noncharacter-in-input-stream',\n surrogateInInputStream: 'surrogate-in-input-stream',\n nonVoidHtmlElementStartTagWithTrailingSolidus: 'non-void-html-element-start-tag-with-trailing-solidus',\n endTagWithAttributes: 'end-tag-with-attributes',\n endTagWithTrailingSolidus: 'end-tag-with-trailing-solidus',\n unexpectedSolidusInTag: 'unexpected-solidus-in-tag',\n unexpectedNullCharacter: 'unexpected-null-character',\n unexpectedQuestionMarkInsteadOfTagName: 'unexpected-question-mark-instead-of-tag-name',\n invalidFirstCharacterOfTagName: 'invalid-first-character-of-tag-name',\n unexpectedEqualsSignBeforeAttributeName: 'unexpected-equals-sign-before-attribute-name',\n missingEndTagName: 'missing-end-tag-name',\n unexpectedCharacterInAttributeName: 'unexpected-character-in-attribute-name',\n unknownNamedCharacterReference: 'unknown-named-character-reference',\n missingSemicolonAfterCharacterReference: 'missing-semicolon-after-character-reference',\n unexpectedCharacterAfterDoctypeSystemIdentifier: 'unexpected-character-after-doctype-system-identifier',\n unexpectedCharacterInUnquotedAttributeValue: 'unexpected-character-in-unquoted-attribute-value',\n eofBeforeTagName: 'eof-before-tag-name',\n eofInTag: 'eof-in-tag',\n missingAttributeValue: 'missing-attribute-value',\n missingWhitespaceBetweenAttributes: 'missing-whitespace-between-attributes',\n missingWhitespaceAfterDoctypePublicKeyword: 'missing-whitespace-after-doctype-public-keyword',\n missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers:\n 'missing-whitespace-between-doctype-public-and-system-identifiers',\n missingWhitespaceAfterDoctypeSystemKeyword: 'missing-whitespace-after-doctype-system-keyword',\n missingQuoteBeforeDoctypePublicIdentifier: 'missing-quote-before-doctype-public-identifier',\n missingQuoteBeforeDoctypeSystemIdentifier: 'missing-quote-before-doctype-system-identifier',\n missingDoctypePublicIdentifier: 'missing-doctype-public-identifier',\n missingDoctypeSystemIdentifier: 'missing-doctype-system-identifier',\n abruptDoctypePublicIdentifier: 'abrupt-doctype-public-identifier',\n abruptDoctypeSystemIdentifier: 'abrupt-doctype-system-identifier',\n cdataInHtmlContent: 'cdata-in-html-content',\n incorrectlyOpenedComment: 'incorrectly-opened-comment',\n eofInScriptHtmlCommentLikeText: 'eof-in-script-html-comment-like-text',\n eofInDoctype: 'eof-in-doctype',\n nestedComment: 'nested-comment',\n abruptClosingOfEmptyComment: 'abrupt-closing-of-empty-comment',\n eofInComment: 'eof-in-comment',\n incorrectlyClosedComment: 'incorrectly-closed-comment',\n eofInCdata: 'eof-in-cdata',\n absenceOfDigitsInNumericCharacterReference: 'absence-of-digits-in-numeric-character-reference',\n nullCharacterReference: 'null-character-reference',\n surrogateCharacterReference: 'surrogate-character-reference',\n characterReferenceOutsideUnicodeRange: 'character-reference-outside-unicode-range',\n controlCharacterReference: 'control-character-reference',\n noncharacterCharacterReference: 'noncharacter-character-reference',\n missingWhitespaceBeforeDoctypeName: 'missing-whitespace-before-doctype-name',\n missingDoctypeName: 'missing-doctype-name',\n invalidCharacterSequenceAfterDoctypeName: 'invalid-character-sequence-after-doctype-name',\n duplicateAttribute: 'duplicate-attribute',\n nonConformingDoctype: 'non-conforming-doctype',\n missingDoctype: 'missing-doctype',\n misplacedDoctype: 'misplaced-doctype',\n endTagWithoutMatchingOpenElement: 'end-tag-without-matching-open-element',\n closingOfElementWithOpenChildElements: 'closing-of-element-with-open-child-elements',\n disallowedContentInNoscriptInHead: 'disallowed-content-in-noscript-in-head',\n openElementsLeftAfterEof: 'open-elements-left-after-eof',\n abandonedHeadElementChild: 'abandoned-head-element-child',\n misplacedStartTagForHeadElement: 'misplaced-start-tag-for-head-element',\n nestedNoscriptInHead: 'nested-noscript-in-head',\n eofInElementThatCanContainOnlyText: 'eof-in-element-that-can-contain-only-text'\n};\n","'use strict';\n\nconst Tokenizer = require('../tokenizer');\nconst HTML = require('./html');\n\n//Aliases\nconst $ = HTML.TAG_NAMES;\nconst NS = HTML.NAMESPACES;\nconst ATTRS = HTML.ATTRS;\n\n//MIME types\nconst MIME_TYPES = {\n TEXT_HTML: 'text/html',\n APPLICATION_XML: 'application/xhtml+xml'\n};\n\n//Attributes\nconst DEFINITION_URL_ATTR = 'definitionurl';\nconst ADJUSTED_DEFINITION_URL_ATTR = 'definitionURL';\nconst SVG_ATTRS_ADJUSTMENT_MAP = {\n attributename: 'attributeName',\n attributetype: 'attributeType',\n basefrequency: 'baseFrequency',\n baseprofile: 'baseProfile',\n calcmode: 'calcMode',\n clippathunits: 'clipPathUnits',\n diffuseconstant: 'diffuseConstant',\n edgemode: 'edgeMode',\n filterunits: 'filterUnits',\n glyphref: 'glyphRef',\n gradienttransform: 'gradientTransform',\n gradientunits: 'gradientUnits',\n kernelmatrix: 'kernelMatrix',\n kernelunitlength: 'kernelUnitLength',\n keypoints: 'keyPoints',\n keysplines: 'keySplines',\n keytimes: 'keyTimes',\n lengthadjust: 'lengthAdjust',\n limitingconeangle: 'limitingConeAngle',\n markerheight: 'markerHeight',\n markerunits: 'markerUnits',\n markerwidth: 'markerWidth',\n maskcontentunits: 'maskContentUnits',\n maskunits: 'maskUnits',\n numoctaves: 'numOctaves',\n pathlength: 'pathLength',\n patterncontentunits: 'patternContentUnits',\n patterntransform: 'patternTransform',\n patternunits: 'patternUnits',\n pointsatx: 'pointsAtX',\n pointsaty: 'pointsAtY',\n pointsatz: 'pointsAtZ',\n preservealpha: 'preserveAlpha',\n preserveaspectratio: 'preserveAspectRatio',\n primitiveunits: 'primitiveUnits',\n refx: 'refX',\n refy: 'refY',\n repeatcount: 'repeatCount',\n repeatdur: 'repeatDur',\n requiredextensions: 'requiredExtensions',\n requiredfeatures: 'requiredFeatures',\n specularconstant: 'specularConstant',\n specularexponent: 'specularExponent',\n spreadmethod: 'spreadMethod',\n startoffset: 'startOffset',\n stddeviation: 'stdDeviation',\n stitchtiles: 'stitchTiles',\n surfacescale: 'surfaceScale',\n systemlanguage: 'systemLanguage',\n tablevalues: 'tableValues',\n targetx: 'targetX',\n targety: 'targetY',\n textlength: 'textLength',\n viewbox: 'viewBox',\n viewtarget: 'viewTarget',\n xchannelselector: 'xChannelSelector',\n ychannelselector: 'yChannelSelector',\n zoomandpan: 'zoomAndPan'\n};\n\nconst XML_ATTRS_ADJUSTMENT_MAP = {\n 'xlink:actuate': { prefix: 'xlink', name: 'actuate', namespace: NS.XLINK },\n 'xlink:arcrole': { prefix: 'xlink', name: 'arcrole', namespace: NS.XLINK },\n 'xlink:href': { prefix: 'xlink', name: 'href', namespace: NS.XLINK },\n 'xlink:role': { prefix: 'xlink', name: 'role', namespace: NS.XLINK },\n 'xlink:show': { prefix: 'xlink', name: 'show', namespace: NS.XLINK },\n 'xlink:title': { prefix: 'xlink', name: 'title', namespace: NS.XLINK },\n 'xlink:type': { prefix: 'xlink', name: 'type', namespace: NS.XLINK },\n 'xml:base': { prefix: 'xml', name: 'base', namespace: NS.XML },\n 'xml:lang': { prefix: 'xml', name: 'lang', namespace: NS.XML },\n 'xml:space': { prefix: 'xml', name: 'space', namespace: NS.XML },\n xmlns: { prefix: '', name: 'xmlns', namespace: NS.XMLNS },\n 'xmlns:xlink': { prefix: 'xmlns', name: 'xlink', namespace: NS.XMLNS }\n};\n\n//SVG tag names adjustment map\nconst SVG_TAG_NAMES_ADJUSTMENT_MAP = (exports.SVG_TAG_NAMES_ADJUSTMENT_MAP = {\n altglyph: 'altGlyph',\n altglyphdef: 'altGlyphDef',\n altglyphitem: 'altGlyphItem',\n animatecolor: 'animateColor',\n animatemotion: 'animateMotion',\n animatetransform: 'animateTransform',\n clippath: 'clipPath',\n feblend: 'feBlend',\n fecolormatrix: 'feColorMatrix',\n fecomponenttransfer: 'feComponentTransfer',\n fecomposite: 'feComposite',\n feconvolvematrix: 'feConvolveMatrix',\n fediffuselighting: 'feDiffuseLighting',\n fedisplacementmap: 'feDisplacementMap',\n fedistantlight: 'feDistantLight',\n feflood: 'feFlood',\n fefunca: 'feFuncA',\n fefuncb: 'feFuncB',\n fefuncg: 'feFuncG',\n fefuncr: 'feFuncR',\n fegaussianblur: 'feGaussianBlur',\n feimage: 'feImage',\n femerge: 'feMerge',\n femergenode: 'feMergeNode',\n femorphology: 'feMorphology',\n feoffset: 'feOffset',\n fepointlight: 'fePointLight',\n fespecularlighting: 'feSpecularLighting',\n fespotlight: 'feSpotLight',\n fetile: 'feTile',\n feturbulence: 'feTurbulence',\n foreignobject: 'foreignObject',\n glyphref: 'glyphRef',\n lineargradient: 'linearGradient',\n radialgradient: 'radialGradient',\n textpath: 'textPath'\n});\n\n//Tags that causes exit from foreign content\nconst EXITS_FOREIGN_CONTENT = {\n [$.B]: true,\n [$.BIG]: true,\n [$.BLOCKQUOTE]: true,\n [$.BODY]: true,\n [$.BR]: true,\n [$.CENTER]: true,\n [$.CODE]: true,\n [$.DD]: true,\n [$.DIV]: true,\n [$.DL]: true,\n [$.DT]: true,\n [$.EM]: true,\n [$.EMBED]: true,\n [$.H1]: true,\n [$.H2]: true,\n [$.H3]: true,\n [$.H4]: true,\n [$.H5]: true,\n [$.H6]: true,\n [$.HEAD]: true,\n [$.HR]: true,\n [$.I]: true,\n [$.IMG]: true,\n [$.LI]: true,\n [$.LISTING]: true,\n [$.MENU]: true,\n [$.META]: true,\n [$.NOBR]: true,\n [$.OL]: true,\n [$.P]: true,\n [$.PRE]: true,\n [$.RUBY]: true,\n [$.S]: true,\n [$.SMALL]: true,\n [$.SPAN]: true,\n [$.STRONG]: true,\n [$.STRIKE]: true,\n [$.SUB]: true,\n [$.SUP]: true,\n [$.TABLE]: true,\n [$.TT]: true,\n [$.U]: true,\n [$.UL]: true,\n [$.VAR]: true\n};\n\n//Check exit from foreign content\nexports.causesExit = function(startTagToken) {\n const tn = startTagToken.tagName;\n const isFontWithAttrs =\n tn === $.FONT &&\n (Tokenizer.getTokenAttr(startTagToken, ATTRS.COLOR) !== null ||\n Tokenizer.getTokenAttr(startTagToken, ATTRS.SIZE) !== null ||\n Tokenizer.getTokenAttr(startTagToken, ATTRS.FACE) !== null);\n\n return isFontWithAttrs ? true : EXITS_FOREIGN_CONTENT[tn];\n};\n\n//Token adjustments\nexports.adjustTokenMathMLAttrs = function(token) {\n for (let i = 0; i < token.attrs.length; i++) {\n if (token.attrs[i].name === DEFINITION_URL_ATTR) {\n token.attrs[i].name = ADJUSTED_DEFINITION_URL_ATTR;\n break;\n }\n }\n};\n\nexports.adjustTokenSVGAttrs = function(token) {\n for (let i = 0; i < token.attrs.length; i++) {\n const adjustedAttrName = SVG_ATTRS_ADJUSTMENT_MAP[token.attrs[i].name];\n\n if (adjustedAttrName) {\n token.attrs[i].name = adjustedAttrName;\n }\n }\n};\n\nexports.adjustTokenXMLAttrs = function(token) {\n for (let i = 0; i < token.attrs.length; i++) {\n const adjustedAttrEntry = XML_ATTRS_ADJUSTMENT_MAP[token.attrs[i].name];\n\n if (adjustedAttrEntry) {\n token.attrs[i].prefix = adjustedAttrEntry.prefix;\n token.attrs[i].name = adjustedAttrEntry.name;\n token.attrs[i].namespace = adjustedAttrEntry.namespace;\n }\n }\n};\n\nexports.adjustTokenSVGTagName = function(token) {\n const adjustedTagName = SVG_TAG_NAMES_ADJUSTMENT_MAP[token.tagName];\n\n if (adjustedTagName) {\n token.tagName = adjustedTagName;\n }\n};\n\n//Integration points\nfunction isMathMLTextIntegrationPoint(tn, ns) {\n return ns === NS.MATHML && (tn === $.MI || tn === $.MO || tn === $.MN || tn === $.MS || tn === $.MTEXT);\n}\n\nfunction isHtmlIntegrationPoint(tn, ns, attrs) {\n if (ns === NS.MATHML && tn === $.ANNOTATION_XML) {\n for (let i = 0; i < attrs.length; i++) {\n if (attrs[i].name === ATTRS.ENCODING) {\n const value = attrs[i].value.toLowerCase();\n\n return value === MIME_TYPES.TEXT_HTML || value === MIME_TYPES.APPLICATION_XML;\n }\n }\n }\n\n return ns === NS.SVG && (tn === $.FOREIGN_OBJECT || tn === $.DESC || tn === $.TITLE);\n}\n\nexports.isIntegrationPoint = function(tn, ns, attrs, foreignNS) {\n if ((!foreignNS || foreignNS === NS.HTML) && isHtmlIntegrationPoint(tn, ns, attrs)) {\n return true;\n }\n\n if ((!foreignNS || foreignNS === NS.MATHML) && isMathMLTextIntegrationPoint(tn, ns)) {\n return true;\n }\n\n return false;\n};\n","'use strict';\n\nconst NS = (exports.NAMESPACES = {\n HTML: 'http://www.w3.org/1999/xhtml',\n MATHML: 'http://www.w3.org/1998/Math/MathML',\n SVG: 'http://www.w3.org/2000/svg',\n XLINK: 'http://www.w3.org/1999/xlink',\n XML: 'http://www.w3.org/XML/1998/namespace',\n XMLNS: 'http://www.w3.org/2000/xmlns/'\n});\n\nexports.ATTRS = {\n TYPE: 'type',\n ACTION: 'action',\n ENCODING: 'encoding',\n PROMPT: 'prompt',\n NAME: 'name',\n COLOR: 'color',\n FACE: 'face',\n SIZE: 'size'\n};\n\nexports.DOCUMENT_MODE = {\n NO_QUIRKS: 'no-quirks',\n QUIRKS: 'quirks',\n LIMITED_QUIRKS: 'limited-quirks'\n};\n\nconst $ = (exports.TAG_NAMES = {\n A: 'a',\n ADDRESS: 'address',\n ANNOTATION_XML: 'annotation-xml',\n APPLET: 'applet',\n AREA: 'area',\n ARTICLE: 'article',\n ASIDE: 'aside',\n\n B: 'b',\n BASE: 'base',\n BASEFONT: 'basefont',\n BGSOUND: 'bgsound',\n BIG: 'big',\n BLOCKQUOTE: 'blockquote',\n BODY: 'body',\n BR: 'br',\n BUTTON: 'button',\n\n CAPTION: 'caption',\n CENTER: 'center',\n CODE: 'code',\n COL: 'col',\n COLGROUP: 'colgroup',\n\n DD: 'dd',\n DESC: 'desc',\n DETAILS: 'details',\n DIALOG: 'dialog',\n DIR: 'dir',\n DIV: 'div',\n DL: 'dl',\n DT: 'dt',\n\n EM: 'em',\n EMBED: 'embed',\n\n FIELDSET: 'fieldset',\n FIGCAPTION: 'figcaption',\n FIGURE: 'figure',\n FONT: 'font',\n FOOTER: 'footer',\n FOREIGN_OBJECT: 'foreignObject',\n FORM: 'form',\n FRAME: 'frame',\n FRAMESET: 'frameset',\n\n H1: 'h1',\n H2: 'h2',\n H3: 'h3',\n H4: 'h4',\n H5: 'h5',\n H6: 'h6',\n HEAD: 'head',\n HEADER: 'header',\n HGROUP: 'hgroup',\n HR: 'hr',\n HTML: 'html',\n\n I: 'i',\n IMG: 'img',\n IMAGE: 'image',\n INPUT: 'input',\n IFRAME: 'iframe',\n\n KEYGEN: 'keygen',\n\n LABEL: 'label',\n LI: 'li',\n LINK: 'link',\n LISTING: 'listing',\n\n MAIN: 'main',\n MALIGNMARK: 'malignmark',\n MARQUEE: 'marquee',\n MATH: 'math',\n MENU: 'menu',\n META: 'meta',\n MGLYPH: 'mglyph',\n MI: 'mi',\n MO: 'mo',\n MN: 'mn',\n MS: 'ms',\n MTEXT: 'mtext',\n\n NAV: 'nav',\n NOBR: 'nobr',\n NOFRAMES: 'noframes',\n NOEMBED: 'noembed',\n NOSCRIPT: 'noscript',\n\n OBJECT: 'object',\n OL: 'ol',\n OPTGROUP: 'optgroup',\n OPTION: 'option',\n\n P: 'p',\n PARAM: 'param',\n PLAINTEXT: 'plaintext',\n PRE: 'pre',\n\n RB: 'rb',\n RP: 'rp',\n RT: 'rt',\n RTC: 'rtc',\n RUBY: 'ruby',\n\n S: 's',\n SCRIPT: 'script',\n SECTION: 'section',\n SELECT: 'select',\n SOURCE: 'source',\n SMALL: 'small',\n SPAN: 'span',\n STRIKE: 'strike',\n STRONG: 'strong',\n STYLE: 'style',\n SUB: 'sub',\n SUMMARY: 'summary',\n SUP: 'sup',\n\n TABLE: 'table',\n TBODY: 'tbody',\n TEMPLATE: 'template',\n TEXTAREA: 'textarea',\n TFOOT: 'tfoot',\n TD: 'td',\n TH: 'th',\n THEAD: 'thead',\n TITLE: 'title',\n TR: 'tr',\n TRACK: 'track',\n TT: 'tt',\n\n U: 'u',\n UL: 'ul',\n\n SVG: 'svg',\n\n VAR: 'var',\n\n WBR: 'wbr',\n\n XMP: 'xmp'\n});\n\nexports.SPECIAL_ELEMENTS = {\n [NS.HTML]: {\n [$.ADDRESS]: true,\n [$.APPLET]: true,\n [$.AREA]: true,\n [$.ARTICLE]: true,\n [$.ASIDE]: true,\n [$.BASE]: true,\n [$.BASEFONT]: true,\n [$.BGSOUND]: true,\n [$.BLOCKQUOTE]: true,\n [$.BODY]: true,\n [$.BR]: true,\n [$.BUTTON]: true,\n [$.CAPTION]: true,\n [$.CENTER]: true,\n [$.COL]: true,\n [$.COLGROUP]: true,\n [$.DD]: true,\n [$.DETAILS]: true,\n [$.DIR]: true,\n [$.DIV]: true,\n [$.DL]: true,\n [$.DT]: true,\n [$.EMBED]: true,\n [$.FIELDSET]: true,\n [$.FIGCAPTION]: true,\n [$.FIGURE]: true,\n [$.FOOTER]: true,\n [$.FORM]: true,\n [$.FRAME]: true,\n [$.FRAMESET]: true,\n [$.H1]: true,\n [$.H2]: true,\n [$.H3]: true,\n [$.H4]: true,\n [$.H5]: true,\n [$.H6]: true,\n [$.HEAD]: true,\n [$.HEADER]: true,\n [$.HGROUP]: true,\n [$.HR]: true,\n [$.HTML]: true,\n [$.IFRAME]: true,\n [$.IMG]: true,\n [$.INPUT]: true,\n [$.LI]: true,\n [$.LINK]: true,\n [$.LISTING]: true,\n [$.MAIN]: true,\n [$.MARQUEE]: true,\n [$.MENU]: true,\n [$.META]: true,\n [$.NAV]: true,\n [$.NOEMBED]: true,\n [$.NOFRAMES]: true,\n [$.NOSCRIPT]: true,\n [$.OBJECT]: true,\n [$.OL]: true,\n [$.P]: true,\n [$.PARAM]: true,\n [$.PLAINTEXT]: true,\n [$.PRE]: true,\n [$.SCRIPT]: true,\n [$.SECTION]: true,\n [$.SELECT]: true,\n [$.SOURCE]: true,\n [$.STYLE]: true,\n [$.SUMMARY]: true,\n [$.TABLE]: true,\n [$.TBODY]: true,\n [$.TD]: true,\n [$.TEMPLATE]: true,\n [$.TEXTAREA]: true,\n [$.TFOOT]: true,\n [$.TH]: true,\n [$.THEAD]: true,\n [$.TITLE]: true,\n [$.TR]: true,\n [$.TRACK]: true,\n [$.UL]: true,\n [$.WBR]: true,\n [$.XMP]: true\n },\n [NS.MATHML]: {\n [$.MI]: true,\n [$.MO]: true,\n [$.MN]: true,\n [$.MS]: true,\n [$.MTEXT]: true,\n [$.ANNOTATION_XML]: true\n },\n [NS.SVG]: {\n [$.TITLE]: true,\n [$.FOREIGN_OBJECT]: true,\n [$.DESC]: true\n }\n};\n","'use strict';\n\nconst UNDEFINED_CODE_POINTS = [\n 0xfffe,\n 0xffff,\n 0x1fffe,\n 0x1ffff,\n 0x2fffe,\n 0x2ffff,\n 0x3fffe,\n 0x3ffff,\n 0x4fffe,\n 0x4ffff,\n 0x5fffe,\n 0x5ffff,\n 0x6fffe,\n 0x6ffff,\n 0x7fffe,\n 0x7ffff,\n 0x8fffe,\n 0x8ffff,\n 0x9fffe,\n 0x9ffff,\n 0xafffe,\n 0xaffff,\n 0xbfffe,\n 0xbffff,\n 0xcfffe,\n 0xcffff,\n 0xdfffe,\n 0xdffff,\n 0xefffe,\n 0xeffff,\n 0xffffe,\n 0xfffff,\n 0x10fffe,\n 0x10ffff\n];\n\nexports.REPLACEMENT_CHARACTER = '\\uFFFD';\n\nexports.CODE_POINTS = {\n EOF: -1,\n NULL: 0x00,\n TABULATION: 0x09,\n CARRIAGE_RETURN: 0x0d,\n LINE_FEED: 0x0a,\n FORM_FEED: 0x0c,\n SPACE: 0x20,\n EXCLAMATION_MARK: 0x21,\n QUOTATION_MARK: 0x22,\n NUMBER_SIGN: 0x23,\n AMPERSAND: 0x26,\n APOSTROPHE: 0x27,\n HYPHEN_MINUS: 0x2d,\n SOLIDUS: 0x2f,\n DIGIT_0: 0x30,\n DIGIT_9: 0x39,\n SEMICOLON: 0x3b,\n LESS_THAN_SIGN: 0x3c,\n EQUALS_SIGN: 0x3d,\n GREATER_THAN_SIGN: 0x3e,\n QUESTION_MARK: 0x3f,\n LATIN_CAPITAL_A: 0x41,\n LATIN_CAPITAL_F: 0x46,\n LATIN_CAPITAL_X: 0x58,\n LATIN_CAPITAL_Z: 0x5a,\n RIGHT_SQUARE_BRACKET: 0x5d,\n GRAVE_ACCENT: 0x60,\n LATIN_SMALL_A: 0x61,\n LATIN_SMALL_F: 0x66,\n LATIN_SMALL_X: 0x78,\n LATIN_SMALL_Z: 0x7a,\n REPLACEMENT_CHARACTER: 0xfffd\n};\n\nexports.CODE_POINT_SEQUENCES = {\n DASH_DASH_STRING: [0x2d, 0x2d], //--\n DOCTYPE_STRING: [0x44, 0x4f, 0x43, 0x54, 0x59, 0x50, 0x45], //DOCTYPE\n CDATA_START_STRING: [0x5b, 0x43, 0x44, 0x41, 0x54, 0x41, 0x5b], //[CDATA[\n SCRIPT_STRING: [0x73, 0x63, 0x72, 0x69, 0x70, 0x74], //script\n PUBLIC_STRING: [0x50, 0x55, 0x42, 0x4c, 0x49, 0x43], //PUBLIC\n SYSTEM_STRING: [0x53, 0x59, 0x53, 0x54, 0x45, 0x4d] //SYSTEM\n};\n\n//Surrogates\nexports.isSurrogate = function(cp) {\n return cp >= 0xd800 && cp <= 0xdfff;\n};\n\nexports.isSurrogatePair = function(cp) {\n return cp >= 0xdc00 && cp <= 0xdfff;\n};\n\nexports.getSurrogatePairCodePoint = function(cp1, cp2) {\n return (cp1 - 0xd800) * 0x400 + 0x2400 + cp2;\n};\n\n//NOTE: excluding NULL and ASCII whitespace\nexports.isControlCodePoint = function(cp) {\n return (\n (cp !== 0x20 && cp !== 0x0a && cp !== 0x0d && cp !== 0x09 && cp !== 0x0c && cp >= 0x01 && cp <= 0x1f) ||\n (cp >= 0x7f && cp <= 0x9f)\n );\n};\n\nexports.isUndefinedCodePoint = function(cp) {\n return (cp >= 0xfdd0 && cp <= 0xfdef) || UNDEFINED_CODE_POINTS.indexOf(cp) > -1;\n};\n","'use strict';\n\nconst Mixin = require('../../utils/mixin');\n\nclass ErrorReportingMixinBase extends Mixin {\n constructor(host, opts) {\n super(host);\n\n this.posTracker = null;\n this.onParseError = opts.onParseError;\n }\n\n _setErrorLocation(err) {\n err.startLine = err.endLine = this.posTracker.line;\n err.startCol = err.endCol = this.posTracker.col;\n err.startOffset = err.endOffset = this.posTracker.offset;\n }\n\n _reportError(code) {\n const err = {\n code: code,\n startLine: -1,\n startCol: -1,\n startOffset: -1,\n endLine: -1,\n endCol: -1,\n endOffset: -1\n };\n\n this._setErrorLocation(err);\n this.onParseError(err);\n }\n\n _getOverriddenMethods(mxn) {\n return {\n _err(code) {\n mxn._reportError(code);\n }\n };\n }\n}\n\nmodule.exports = ErrorReportingMixinBase;\n","'use strict';\n\nconst ErrorReportingMixinBase = require('./mixin-base');\nconst ErrorReportingTokenizerMixin = require('./tokenizer-mixin');\nconst LocationInfoTokenizerMixin = require('../location-info/tokenizer-mixin');\nconst Mixin = require('../../utils/mixin');\n\nclass ErrorReportingParserMixin extends ErrorReportingMixinBase {\n constructor(parser, opts) {\n super(parser, opts);\n\n this.opts = opts;\n this.ctLoc = null;\n this.locBeforeToken = false;\n }\n\n _setErrorLocation(err) {\n if (this.ctLoc) {\n err.startLine = this.ctLoc.startLine;\n err.startCol = this.ctLoc.startCol;\n err.startOffset = this.ctLoc.startOffset;\n\n err.endLine = this.locBeforeToken ? this.ctLoc.startLine : this.ctLoc.endLine;\n err.endCol = this.locBeforeToken ? this.ctLoc.startCol : this.ctLoc.endCol;\n err.endOffset = this.locBeforeToken ? this.ctLoc.startOffset : this.ctLoc.endOffset;\n }\n }\n\n _getOverriddenMethods(mxn, orig) {\n return {\n _bootstrap(document, fragmentContext) {\n orig._bootstrap.call(this, document, fragmentContext);\n\n Mixin.install(this.tokenizer, ErrorReportingTokenizerMixin, mxn.opts);\n Mixin.install(this.tokenizer, LocationInfoTokenizerMixin);\n },\n\n _processInputToken(token) {\n mxn.ctLoc = token.location;\n\n orig._processInputToken.call(this, token);\n },\n\n _err(code, options) {\n mxn.locBeforeToken = options && options.beforeToken;\n mxn._reportError(code);\n }\n };\n }\n}\n\nmodule.exports = ErrorReportingParserMixin;\n","'use strict';\n\nconst ErrorReportingMixinBase = require('./mixin-base');\nconst PositionTrackingPreprocessorMixin = require('../position-tracking/preprocessor-mixin');\nconst Mixin = require('../../utils/mixin');\n\nclass ErrorReportingPreprocessorMixin extends ErrorReportingMixinBase {\n constructor(preprocessor, opts) {\n super(preprocessor, opts);\n\n this.posTracker = Mixin.install(preprocessor, PositionTrackingPreprocessorMixin);\n this.lastErrOffset = -1;\n }\n\n _reportError(code) {\n //NOTE: avoid reporting error twice on advance/retreat\n if (this.lastErrOffset !== this.posTracker.offset) {\n this.lastErrOffset = this.posTracker.offset;\n super._reportError(code);\n }\n }\n}\n\nmodule.exports = ErrorReportingPreprocessorMixin;\n","'use strict';\n\nconst ErrorReportingMixinBase = require('./mixin-base');\nconst ErrorReportingPreprocessorMixin = require('./preprocessor-mixin');\nconst Mixin = require('../../utils/mixin');\n\nclass ErrorReportingTokenizerMixin extends ErrorReportingMixinBase {\n constructor(tokenizer, opts) {\n super(tokenizer, opts);\n\n const preprocessorMixin = Mixin.install(tokenizer.preprocessor, ErrorReportingPreprocessorMixin, opts);\n\n this.posTracker = preprocessorMixin.posTracker;\n }\n}\n\nmodule.exports = ErrorReportingTokenizerMixin;\n","'use strict';\n\nconst Mixin = require('../../utils/mixin');\n\nclass LocationInfoOpenElementStackMixin extends Mixin {\n constructor(stack, opts) {\n super(stack);\n\n this.onItemPop = opts.onItemPop;\n }\n\n _getOverriddenMethods(mxn, orig) {\n return {\n pop() {\n mxn.onItemPop(this.current);\n orig.pop.call(this);\n },\n\n popAllUpToHtmlElement() {\n for (let i = this.stackTop; i > 0; i--) {\n mxn.onItemPop(this.items[i]);\n }\n\n orig.popAllUpToHtmlElement.call(this);\n },\n\n remove(element) {\n mxn.onItemPop(this.current);\n orig.remove.call(this, element);\n }\n };\n }\n}\n\nmodule.exports = LocationInfoOpenElementStackMixin;\n","'use strict';\n\nconst Mixin = require('../../utils/mixin');\nconst Tokenizer = require('../../tokenizer');\nconst LocationInfoTokenizerMixin = require('./tokenizer-mixin');\nconst LocationInfoOpenElementStackMixin = require('./open-element-stack-mixin');\nconst HTML = require('../../common/html');\n\n//Aliases\nconst $ = HTML.TAG_NAMES;\n\nclass LocationInfoParserMixin extends Mixin {\n constructor(parser) {\n super(parser);\n\n this.parser = parser;\n this.treeAdapter = this.parser.treeAdapter;\n this.posTracker = null;\n this.lastStartTagToken = null;\n this.lastFosterParentingLocation = null;\n this.currentToken = null;\n }\n\n _setStartLocation(element) {\n let loc = null;\n\n if (this.lastStartTagToken) {\n loc = Object.assign({}, this.lastStartTagToken.location);\n loc.startTag = this.lastStartTagToken.location;\n }\n\n this.treeAdapter.setNodeSourceCodeLocation(element, loc);\n }\n\n _setEndLocation(element, closingToken) {\n const loc = this.treeAdapter.getNodeSourceCodeLocation(element);\n\n if (loc) {\n if (closingToken.location) {\n const ctLoc = closingToken.location;\n const tn = this.treeAdapter.getTagName(element);\n\n // NOTE: For cases like

- First 'p' closes without a closing\n // tag and for cases like

- 'p' closes without a closing tag.\n const isClosingEndTag = closingToken.type === Tokenizer.END_TAG_TOKEN && tn === closingToken.tagName;\n\n if (isClosingEndTag) {\n loc.endTag = Object.assign({}, ctLoc);\n loc.endLine = ctLoc.endLine;\n loc.endCol = ctLoc.endCol;\n loc.endOffset = ctLoc.endOffset;\n } else {\n loc.endLine = ctLoc.startLine;\n loc.endCol = ctLoc.startCol;\n loc.endOffset = ctLoc.startOffset;\n }\n }\n }\n }\n\n _getOverriddenMethods(mxn, orig) {\n return {\n _bootstrap(document, fragmentContext) {\n orig._bootstrap.call(this, document, fragmentContext);\n\n mxn.lastStartTagToken = null;\n mxn.lastFosterParentingLocation = null;\n mxn.currentToken = null;\n\n const tokenizerMixin = Mixin.install(this.tokenizer, LocationInfoTokenizerMixin);\n\n mxn.posTracker = tokenizerMixin.posTracker;\n\n Mixin.install(this.openElements, LocationInfoOpenElementStackMixin, {\n onItemPop: function(element) {\n mxn._setEndLocation(element, mxn.currentToken);\n }\n });\n },\n\n _runParsingLoop(scriptHandler) {\n orig._runParsingLoop.call(this, scriptHandler);\n\n // NOTE: generate location info for elements\n // that remains on open element stack\n for (let i = this.openElements.stackTop; i >= 0; i--) {\n mxn._setEndLocation(this.openElements.items[i], mxn.currentToken);\n }\n },\n\n //Token processing\n _processTokenInForeignContent(token) {\n mxn.currentToken = token;\n orig._processTokenInForeignContent.call(this, token);\n },\n\n _processToken(token) {\n mxn.currentToken = token;\n orig._processToken.call(this, token);\n\n //NOTE: and are never popped from the stack, so we need to updated\n //their end location explicitly.\n const requireExplicitUpdate =\n token.type === Tokenizer.END_TAG_TOKEN &&\n (token.tagName === $.HTML || (token.tagName === $.BODY && this.openElements.hasInScope($.BODY)));\n\n if (requireExplicitUpdate) {\n for (let i = this.openElements.stackTop; i >= 0; i--) {\n const element = this.openElements.items[i];\n\n if (this.treeAdapter.getTagName(element) === token.tagName) {\n mxn._setEndLocation(element, token);\n break;\n }\n }\n }\n },\n\n //Doctype\n _setDocumentType(token) {\n orig._setDocumentType.call(this, token);\n\n const documentChildren = this.treeAdapter.getChildNodes(this.document);\n const cnLength = documentChildren.length;\n\n for (let i = 0; i < cnLength; i++) {\n const node = documentChildren[i];\n\n if (this.treeAdapter.isDocumentTypeNode(node)) {\n this.treeAdapter.setNodeSourceCodeLocation(node, token.location);\n break;\n }\n }\n },\n\n //Elements\n _attachElementToTree(element) {\n //NOTE: _attachElementToTree is called from _appendElement, _insertElement and _insertTemplate methods.\n //So we will use token location stored in this methods for the element.\n mxn._setStartLocation(element);\n mxn.lastStartTagToken = null;\n orig._attachElementToTree.call(this, element);\n },\n\n _appendElement(token, namespaceURI) {\n mxn.lastStartTagToken = token;\n orig._appendElement.call(this, token, namespaceURI);\n },\n\n _insertElement(token, namespaceURI) {\n mxn.lastStartTagToken = token;\n orig._insertElement.call(this, token, namespaceURI);\n },\n\n _insertTemplate(token) {\n mxn.lastStartTagToken = token;\n orig._insertTemplate.call(this, token);\n\n const tmplContent = this.treeAdapter.getTemplateContent(this.openElements.current);\n\n this.treeAdapter.setNodeSourceCodeLocation(tmplContent, null);\n },\n\n _insertFakeRootElement() {\n orig._insertFakeRootElement.call(this);\n this.treeAdapter.setNodeSourceCodeLocation(this.openElements.current, null);\n },\n\n //Comments\n _appendCommentNode(token, parent) {\n orig._appendCommentNode.call(this, token, parent);\n\n const children = this.treeAdapter.getChildNodes(parent);\n const commentNode = children[children.length - 1];\n\n this.treeAdapter.setNodeSourceCodeLocation(commentNode, token.location);\n },\n\n //Text\n _findFosterParentingLocation() {\n //NOTE: store last foster parenting location, so we will be able to find inserted text\n //in case of foster parenting\n mxn.lastFosterParentingLocation = orig._findFosterParentingLocation.call(this);\n\n return mxn.lastFosterParentingLocation;\n },\n\n _insertCharacters(token) {\n orig._insertCharacters.call(this, token);\n\n const hasFosterParent = this._shouldFosterParentOnInsertion();\n\n const parent =\n (hasFosterParent && mxn.lastFosterParentingLocation.parent) ||\n this.openElements.currentTmplContent ||\n this.openElements.current;\n\n const siblings = this.treeAdapter.getChildNodes(parent);\n\n const textNodeIdx =\n hasFosterParent && mxn.lastFosterParentingLocation.beforeElement\n ? siblings.indexOf(mxn.lastFosterParentingLocation.beforeElement) - 1\n : siblings.length - 1;\n\n const textNode = siblings[textNodeIdx];\n\n //NOTE: if we have location assigned by another token, then just update end position\n const tnLoc = this.treeAdapter.getNodeSourceCodeLocation(textNode);\n\n if (tnLoc) {\n tnLoc.endLine = token.location.endLine;\n tnLoc.endCol = token.location.endCol;\n tnLoc.endOffset = token.location.endOffset;\n } else {\n this.treeAdapter.setNodeSourceCodeLocation(textNode, token.location);\n }\n }\n };\n }\n}\n\nmodule.exports = LocationInfoParserMixin;\n","'use strict';\n\nconst Mixin = require('../../utils/mixin');\nconst Tokenizer = require('../../tokenizer');\nconst PositionTrackingPreprocessorMixin = require('../position-tracking/preprocessor-mixin');\n\nclass LocationInfoTokenizerMixin extends Mixin {\n constructor(tokenizer) {\n super(tokenizer);\n\n this.tokenizer = tokenizer;\n this.posTracker = Mixin.install(tokenizer.preprocessor, PositionTrackingPreprocessorMixin);\n this.currentAttrLocation = null;\n this.ctLoc = null;\n }\n\n _getCurrentLocation() {\n return {\n startLine: this.posTracker.line,\n startCol: this.posTracker.col,\n startOffset: this.posTracker.offset,\n endLine: -1,\n endCol: -1,\n endOffset: -1\n };\n }\n\n _attachCurrentAttrLocationInfo() {\n this.currentAttrLocation.endLine = this.posTracker.line;\n this.currentAttrLocation.endCol = this.posTracker.col;\n this.currentAttrLocation.endOffset = this.posTracker.offset;\n\n const currentToken = this.tokenizer.currentToken;\n const currentAttr = this.tokenizer.currentAttr;\n\n if (!currentToken.location.attrs) {\n currentToken.location.attrs = Object.create(null);\n }\n\n currentToken.location.attrs[currentAttr.name] = this.currentAttrLocation;\n }\n\n _getOverriddenMethods(mxn, orig) {\n const methods = {\n _createStartTagToken() {\n orig._createStartTagToken.call(this);\n this.currentToken.location = mxn.ctLoc;\n },\n\n _createEndTagToken() {\n orig._createEndTagToken.call(this);\n this.currentToken.location = mxn.ctLoc;\n },\n\n _createCommentToken() {\n orig._createCommentToken.call(this);\n this.currentToken.location = mxn.ctLoc;\n },\n\n _createDoctypeToken(initialName) {\n orig._createDoctypeToken.call(this, initialName);\n this.currentToken.location = mxn.ctLoc;\n },\n\n _createCharacterToken(type, ch) {\n orig._createCharacterToken.call(this, type, ch);\n this.currentCharacterToken.location = mxn.ctLoc;\n },\n\n _createEOFToken() {\n orig._createEOFToken.call(this);\n this.currentToken.location = mxn._getCurrentLocation();\n },\n\n _createAttr(attrNameFirstCh) {\n orig._createAttr.call(this, attrNameFirstCh);\n mxn.currentAttrLocation = mxn._getCurrentLocation();\n },\n\n _leaveAttrName(toState) {\n orig._leaveAttrName.call(this, toState);\n mxn._attachCurrentAttrLocationInfo();\n },\n\n _leaveAttrValue(toState) {\n orig._leaveAttrValue.call(this, toState);\n mxn._attachCurrentAttrLocationInfo();\n },\n\n _emitCurrentToken() {\n const ctLoc = this.currentToken.location;\n\n //NOTE: if we have pending character token make it's end location equal to the\n //current token's start location.\n if (this.currentCharacterToken) {\n this.currentCharacterToken.location.endLine = ctLoc.startLine;\n this.currentCharacterToken.location.endCol = ctLoc.startCol;\n this.currentCharacterToken.location.endOffset = ctLoc.startOffset;\n }\n\n if (this.currentToken.type === Tokenizer.EOF_TOKEN) {\n ctLoc.endLine = ctLoc.startLine;\n ctLoc.endCol = ctLoc.startCol;\n ctLoc.endOffset = ctLoc.startOffset;\n } else {\n ctLoc.endLine = mxn.posTracker.line;\n ctLoc.endCol = mxn.posTracker.col + 1;\n ctLoc.endOffset = mxn.posTracker.offset + 1;\n }\n\n orig._emitCurrentToken.call(this);\n },\n\n _emitCurrentCharacterToken() {\n const ctLoc = this.currentCharacterToken && this.currentCharacterToken.location;\n\n //NOTE: if we have character token and it's location wasn't set in the _emitCurrentToken(),\n //then set it's location at the current preprocessor position.\n //We don't need to increment preprocessor position, since character token\n //emission is always forced by the start of the next character token here.\n //So, we already have advanced position.\n if (ctLoc && ctLoc.endOffset === -1) {\n ctLoc.endLine = mxn.posTracker.line;\n ctLoc.endCol = mxn.posTracker.col;\n ctLoc.endOffset = mxn.posTracker.offset;\n }\n\n orig._emitCurrentCharacterToken.call(this);\n }\n };\n\n //NOTE: patch initial states for each mode to obtain token start position\n Object.keys(Tokenizer.MODE).forEach(modeName => {\n const state = Tokenizer.MODE[modeName];\n\n methods[state] = function(cp) {\n mxn.ctLoc = mxn._getCurrentLocation();\n orig[state].call(this, cp);\n };\n });\n\n return methods;\n }\n}\n\nmodule.exports = LocationInfoTokenizerMixin;\n","'use strict';\n\nconst Mixin = require('../../utils/mixin');\n\nclass PositionTrackingPreprocessorMixin extends Mixin {\n constructor(preprocessor) {\n super(preprocessor);\n\n this.preprocessor = preprocessor;\n this.isEol = false;\n this.lineStartPos = 0;\n this.droppedBufferSize = 0;\n\n this.offset = 0;\n this.col = 0;\n this.line = 1;\n }\n\n _getOverriddenMethods(mxn, orig) {\n return {\n advance() {\n const pos = this.pos + 1;\n const ch = this.html[pos];\n\n //NOTE: LF should be in the last column of the line\n if (mxn.isEol) {\n mxn.isEol = false;\n mxn.line++;\n mxn.lineStartPos = pos;\n }\n\n if (ch === '\\n' || (ch === '\\r' && this.html[pos + 1] !== '\\n')) {\n mxn.isEol = true;\n }\n\n mxn.col = pos - mxn.lineStartPos + 1;\n mxn.offset = mxn.droppedBufferSize + pos;\n\n return orig.advance.call(this);\n },\n\n retreat() {\n orig.retreat.call(this);\n\n mxn.isEol = false;\n mxn.col = this.pos - mxn.lineStartPos + 1;\n },\n\n dropParsedChunk() {\n const prevPos = this.pos;\n\n orig.dropParsedChunk.call(this);\n\n const reduction = prevPos - this.pos;\n\n mxn.lineStartPos -= reduction;\n mxn.droppedBufferSize += reduction;\n mxn.offset = mxn.droppedBufferSize + this.pos;\n }\n };\n }\n}\n\nmodule.exports = PositionTrackingPreprocessorMixin;\n","'use strict';\n\nconst Parser = require('./parser');\nconst Serializer = require('./serializer');\n\n// Shorthands\nexports.parse = function parse(html, options) {\n const parser = new Parser(options);\n\n return parser.parse(html);\n};\n\nexports.parseFragment = function parseFragment(fragmentContext, html, options) {\n if (typeof fragmentContext === 'string') {\n options = html;\n html = fragmentContext;\n fragmentContext = null;\n }\n\n const parser = new Parser(options);\n\n return parser.parseFragment(html, fragmentContext);\n};\n\nexports.serialize = function(node, options) {\n const serializer = new Serializer(node, options);\n\n return serializer.serialize();\n};\n","'use strict';\n\n//Const\nconst NOAH_ARK_CAPACITY = 3;\n\n//List of formatting elements\nclass FormattingElementList {\n constructor(treeAdapter) {\n this.length = 0;\n this.entries = [];\n this.treeAdapter = treeAdapter;\n this.bookmark = null;\n }\n\n //Noah Ark's condition\n //OPTIMIZATION: at first we try to find possible candidates for exclusion using\n //lightweight heuristics without thorough attributes check.\n _getNoahArkConditionCandidates(newElement) {\n const candidates = [];\n\n if (this.length >= NOAH_ARK_CAPACITY) {\n const neAttrsLength = this.treeAdapter.getAttrList(newElement).length;\n const neTagName = this.treeAdapter.getTagName(newElement);\n const neNamespaceURI = this.treeAdapter.getNamespaceURI(newElement);\n\n for (let i = this.length - 1; i >= 0; i--) {\n const entry = this.entries[i];\n\n if (entry.type === FormattingElementList.MARKER_ENTRY) {\n break;\n }\n\n const element = entry.element;\n const elementAttrs = this.treeAdapter.getAttrList(element);\n\n const isCandidate =\n this.treeAdapter.getTagName(element) === neTagName &&\n this.treeAdapter.getNamespaceURI(element) === neNamespaceURI &&\n elementAttrs.length === neAttrsLength;\n\n if (isCandidate) {\n candidates.push({ idx: i, attrs: elementAttrs });\n }\n }\n }\n\n return candidates.length < NOAH_ARK_CAPACITY ? [] : candidates;\n }\n\n _ensureNoahArkCondition(newElement) {\n const candidates = this._getNoahArkConditionCandidates(newElement);\n let cLength = candidates.length;\n\n if (cLength) {\n const neAttrs = this.treeAdapter.getAttrList(newElement);\n const neAttrsLength = neAttrs.length;\n const neAttrsMap = Object.create(null);\n\n //NOTE: build attrs map for the new element so we can perform fast lookups\n for (let i = 0; i < neAttrsLength; i++) {\n const neAttr = neAttrs[i];\n\n neAttrsMap[neAttr.name] = neAttr.value;\n }\n\n for (let i = 0; i < neAttrsLength; i++) {\n for (let j = 0; j < cLength; j++) {\n const cAttr = candidates[j].attrs[i];\n\n if (neAttrsMap[cAttr.name] !== cAttr.value) {\n candidates.splice(j, 1);\n cLength--;\n }\n\n if (candidates.length < NOAH_ARK_CAPACITY) {\n return;\n }\n }\n }\n\n //NOTE: remove bottommost candidates until Noah's Ark condition will not be met\n for (let i = cLength - 1; i >= NOAH_ARK_CAPACITY - 1; i--) {\n this.entries.splice(candidates[i].idx, 1);\n this.length--;\n }\n }\n }\n\n //Mutations\n insertMarker() {\n this.entries.push({ type: FormattingElementList.MARKER_ENTRY });\n this.length++;\n }\n\n pushElement(element, token) {\n this._ensureNoahArkCondition(element);\n\n this.entries.push({\n type: FormattingElementList.ELEMENT_ENTRY,\n element: element,\n token: token\n });\n\n this.length++;\n }\n\n insertElementAfterBookmark(element, token) {\n let bookmarkIdx = this.length - 1;\n\n for (; bookmarkIdx >= 0; bookmarkIdx--) {\n if (this.entries[bookmarkIdx] === this.bookmark) {\n break;\n }\n }\n\n this.entries.splice(bookmarkIdx + 1, 0, {\n type: FormattingElementList.ELEMENT_ENTRY,\n element: element,\n token: token\n });\n\n this.length++;\n }\n\n removeEntry(entry) {\n for (let i = this.length - 1; i >= 0; i--) {\n if (this.entries[i] === entry) {\n this.entries.splice(i, 1);\n this.length--;\n break;\n }\n }\n }\n\n clearToLastMarker() {\n while (this.length) {\n const entry = this.entries.pop();\n\n this.length--;\n\n if (entry.type === FormattingElementList.MARKER_ENTRY) {\n break;\n }\n }\n }\n\n //Search\n getElementEntryInScopeWithTagName(tagName) {\n for (let i = this.length - 1; i >= 0; i--) {\n const entry = this.entries[i];\n\n if (entry.type === FormattingElementList.MARKER_ENTRY) {\n return null;\n }\n\n if (this.treeAdapter.getTagName(entry.element) === tagName) {\n return entry;\n }\n }\n\n return null;\n }\n\n getElementEntry(element) {\n for (let i = this.length - 1; i >= 0; i--) {\n const entry = this.entries[i];\n\n if (entry.type === FormattingElementList.ELEMENT_ENTRY && entry.element === element) {\n return entry;\n }\n }\n\n return null;\n }\n}\n\n//Entry types\nFormattingElementList.MARKER_ENTRY = 'MARKER_ENTRY';\nFormattingElementList.ELEMENT_ENTRY = 'ELEMENT_ENTRY';\n\nmodule.exports = FormattingElementList;\n","'use strict';\n\nconst Tokenizer = require('../tokenizer');\nconst OpenElementStack = require('./open-element-stack');\nconst FormattingElementList = require('./formatting-element-list');\nconst LocationInfoParserMixin = require('../extensions/location-info/parser-mixin');\nconst ErrorReportingParserMixin = require('../extensions/error-reporting/parser-mixin');\nconst Mixin = require('../utils/mixin');\nconst defaultTreeAdapter = require('../tree-adapters/default');\nconst mergeOptions = require('../utils/merge-options');\nconst doctype = require('../common/doctype');\nconst foreignContent = require('../common/foreign-content');\nconst ERR = require('../common/error-codes');\nconst unicode = require('../common/unicode');\nconst HTML = require('../common/html');\n\n//Aliases\nconst $ = HTML.TAG_NAMES;\nconst NS = HTML.NAMESPACES;\nconst ATTRS = HTML.ATTRS;\n\nconst DEFAULT_OPTIONS = {\n scriptingEnabled: true,\n sourceCodeLocationInfo: false,\n onParseError: null,\n treeAdapter: defaultTreeAdapter\n};\n\n//Misc constants\nconst HIDDEN_INPUT_TYPE = 'hidden';\n\n//Adoption agency loops iteration count\nconst AA_OUTER_LOOP_ITER = 8;\nconst AA_INNER_LOOP_ITER = 3;\n\n//Insertion modes\nconst INITIAL_MODE = 'INITIAL_MODE';\nconst BEFORE_HTML_MODE = 'BEFORE_HTML_MODE';\nconst BEFORE_HEAD_MODE = 'BEFORE_HEAD_MODE';\nconst IN_HEAD_MODE = 'IN_HEAD_MODE';\nconst IN_HEAD_NO_SCRIPT_MODE = 'IN_HEAD_NO_SCRIPT_MODE';\nconst AFTER_HEAD_MODE = 'AFTER_HEAD_MODE';\nconst IN_BODY_MODE = 'IN_BODY_MODE';\nconst TEXT_MODE = 'TEXT_MODE';\nconst IN_TABLE_MODE = 'IN_TABLE_MODE';\nconst IN_TABLE_TEXT_MODE = 'IN_TABLE_TEXT_MODE';\nconst IN_CAPTION_MODE = 'IN_CAPTION_MODE';\nconst IN_COLUMN_GROUP_MODE = 'IN_COLUMN_GROUP_MODE';\nconst IN_TABLE_BODY_MODE = 'IN_TABLE_BODY_MODE';\nconst IN_ROW_MODE = 'IN_ROW_MODE';\nconst IN_CELL_MODE = 'IN_CELL_MODE';\nconst IN_SELECT_MODE = 'IN_SELECT_MODE';\nconst IN_SELECT_IN_TABLE_MODE = 'IN_SELECT_IN_TABLE_MODE';\nconst IN_TEMPLATE_MODE = 'IN_TEMPLATE_MODE';\nconst AFTER_BODY_MODE = 'AFTER_BODY_MODE';\nconst IN_FRAMESET_MODE = 'IN_FRAMESET_MODE';\nconst AFTER_FRAMESET_MODE = 'AFTER_FRAMESET_MODE';\nconst AFTER_AFTER_BODY_MODE = 'AFTER_AFTER_BODY_MODE';\nconst AFTER_AFTER_FRAMESET_MODE = 'AFTER_AFTER_FRAMESET_MODE';\n\n//Insertion mode reset map\nconst INSERTION_MODE_RESET_MAP = {\n [$.TR]: IN_ROW_MODE,\n [$.TBODY]: IN_TABLE_BODY_MODE,\n [$.THEAD]: IN_TABLE_BODY_MODE,\n [$.TFOOT]: IN_TABLE_BODY_MODE,\n [$.CAPTION]: IN_CAPTION_MODE,\n [$.COLGROUP]: IN_COLUMN_GROUP_MODE,\n [$.TABLE]: IN_TABLE_MODE,\n [$.BODY]: IN_BODY_MODE,\n [$.FRAMESET]: IN_FRAMESET_MODE\n};\n\n//Template insertion mode switch map\nconst TEMPLATE_INSERTION_MODE_SWITCH_MAP = {\n [$.CAPTION]: IN_TABLE_MODE,\n [$.COLGROUP]: IN_TABLE_MODE,\n [$.TBODY]: IN_TABLE_MODE,\n [$.TFOOT]: IN_TABLE_MODE,\n [$.THEAD]: IN_TABLE_MODE,\n [$.COL]: IN_COLUMN_GROUP_MODE,\n [$.TR]: IN_TABLE_BODY_MODE,\n [$.TD]: IN_ROW_MODE,\n [$.TH]: IN_ROW_MODE\n};\n\n//Token handlers map for insertion modes\nconst TOKEN_HANDLERS = {\n [INITIAL_MODE]: {\n [Tokenizer.CHARACTER_TOKEN]: tokenInInitialMode,\n [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInInitialMode,\n [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: ignoreToken,\n [Tokenizer.COMMENT_TOKEN]: appendComment,\n [Tokenizer.DOCTYPE_TOKEN]: doctypeInInitialMode,\n [Tokenizer.START_TAG_TOKEN]: tokenInInitialMode,\n [Tokenizer.END_TAG_TOKEN]: tokenInInitialMode,\n [Tokenizer.EOF_TOKEN]: tokenInInitialMode\n },\n [BEFORE_HTML_MODE]: {\n [Tokenizer.CHARACTER_TOKEN]: tokenBeforeHtml,\n [Tokenizer.NULL_CHARACTER_TOKEN]: tokenBeforeHtml,\n [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: ignoreToken,\n [Tokenizer.COMMENT_TOKEN]: appendComment,\n [Tokenizer.DOCTYPE_TOKEN]: ignoreToken,\n [Tokenizer.START_TAG_TOKEN]: startTagBeforeHtml,\n [Tokenizer.END_TAG_TOKEN]: endTagBeforeHtml,\n [Tokenizer.EOF_TOKEN]: tokenBeforeHtml\n },\n [BEFORE_HEAD_MODE]: {\n [Tokenizer.CHARACTER_TOKEN]: tokenBeforeHead,\n [Tokenizer.NULL_CHARACTER_TOKEN]: tokenBeforeHead,\n [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: ignoreToken,\n [Tokenizer.COMMENT_TOKEN]: appendComment,\n [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype,\n [Tokenizer.START_TAG_TOKEN]: startTagBeforeHead,\n [Tokenizer.END_TAG_TOKEN]: endTagBeforeHead,\n [Tokenizer.EOF_TOKEN]: tokenBeforeHead\n },\n [IN_HEAD_MODE]: {\n [Tokenizer.CHARACTER_TOKEN]: tokenInHead,\n [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInHead,\n [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters,\n [Tokenizer.COMMENT_TOKEN]: appendComment,\n [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype,\n [Tokenizer.START_TAG_TOKEN]: startTagInHead,\n [Tokenizer.END_TAG_TOKEN]: endTagInHead,\n [Tokenizer.EOF_TOKEN]: tokenInHead\n },\n [IN_HEAD_NO_SCRIPT_MODE]: {\n [Tokenizer.CHARACTER_TOKEN]: tokenInHeadNoScript,\n [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInHeadNoScript,\n [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters,\n [Tokenizer.COMMENT_TOKEN]: appendComment,\n [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype,\n [Tokenizer.START_TAG_TOKEN]: startTagInHeadNoScript,\n [Tokenizer.END_TAG_TOKEN]: endTagInHeadNoScript,\n [Tokenizer.EOF_TOKEN]: tokenInHeadNoScript\n },\n [AFTER_HEAD_MODE]: {\n [Tokenizer.CHARACTER_TOKEN]: tokenAfterHead,\n [Tokenizer.NULL_CHARACTER_TOKEN]: tokenAfterHead,\n [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters,\n [Tokenizer.COMMENT_TOKEN]: appendComment,\n [Tokenizer.DOCTYPE_TOKEN]: misplacedDoctype,\n [Tokenizer.START_TAG_TOKEN]: startTagAfterHead,\n [Tokenizer.END_TAG_TOKEN]: endTagAfterHead,\n [Tokenizer.EOF_TOKEN]: tokenAfterHead\n },\n [IN_BODY_MODE]: {\n [Tokenizer.CHARACTER_TOKEN]: characterInBody,\n [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken,\n [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody,\n [Tokenizer.COMMENT_TOKEN]: appendComment,\n [Tokenizer.DOCTYPE_TOKEN]: ignoreToken,\n [Tokenizer.START_TAG_TOKEN]: startTagInBody,\n [Tokenizer.END_TAG_TOKEN]: endTagInBody,\n [Tokenizer.EOF_TOKEN]: eofInBody\n },\n [TEXT_MODE]: {\n [Tokenizer.CHARACTER_TOKEN]: insertCharacters,\n [Tokenizer.NULL_CHARACTER_TOKEN]: insertCharacters,\n [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters,\n [Tokenizer.COMMENT_TOKEN]: ignoreToken,\n [Tokenizer.DOCTYPE_TOKEN]: ignoreToken,\n [Tokenizer.START_TAG_TOKEN]: ignoreToken,\n [Tokenizer.END_TAG_TOKEN]: endTagInText,\n [Tokenizer.EOF_TOKEN]: eofInText\n },\n [IN_TABLE_MODE]: {\n [Tokenizer.CHARACTER_TOKEN]: characterInTable,\n [Tokenizer.NULL_CHARACTER_TOKEN]: characterInTable,\n [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: characterInTable,\n [Tokenizer.COMMENT_TOKEN]: appendComment,\n [Tokenizer.DOCTYPE_TOKEN]: ignoreToken,\n [Tokenizer.START_TAG_TOKEN]: startTagInTable,\n [Tokenizer.END_TAG_TOKEN]: endTagInTable,\n [Tokenizer.EOF_TOKEN]: eofInBody\n },\n [IN_TABLE_TEXT_MODE]: {\n [Tokenizer.CHARACTER_TOKEN]: characterInTableText,\n [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken,\n [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInTableText,\n [Tokenizer.COMMENT_TOKEN]: tokenInTableText,\n [Tokenizer.DOCTYPE_TOKEN]: tokenInTableText,\n [Tokenizer.START_TAG_TOKEN]: tokenInTableText,\n [Tokenizer.END_TAG_TOKEN]: tokenInTableText,\n [Tokenizer.EOF_TOKEN]: tokenInTableText\n },\n [IN_CAPTION_MODE]: {\n [Tokenizer.CHARACTER_TOKEN]: characterInBody,\n [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken,\n [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody,\n [Tokenizer.COMMENT_TOKEN]: appendComment,\n [Tokenizer.DOCTYPE_TOKEN]: ignoreToken,\n [Tokenizer.START_TAG_TOKEN]: startTagInCaption,\n [Tokenizer.END_TAG_TOKEN]: endTagInCaption,\n [Tokenizer.EOF_TOKEN]: eofInBody\n },\n [IN_COLUMN_GROUP_MODE]: {\n [Tokenizer.CHARACTER_TOKEN]: tokenInColumnGroup,\n [Tokenizer.NULL_CHARACTER_TOKEN]: tokenInColumnGroup,\n [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters,\n [Tokenizer.COMMENT_TOKEN]: appendComment,\n [Tokenizer.DOCTYPE_TOKEN]: ignoreToken,\n [Tokenizer.START_TAG_TOKEN]: startTagInColumnGroup,\n [Tokenizer.END_TAG_TOKEN]: endTagInColumnGroup,\n [Tokenizer.EOF_TOKEN]: eofInBody\n },\n [IN_TABLE_BODY_MODE]: {\n [Tokenizer.CHARACTER_TOKEN]: characterInTable,\n [Tokenizer.NULL_CHARACTER_TOKEN]: characterInTable,\n [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: characterInTable,\n [Tokenizer.COMMENT_TOKEN]: appendComment,\n [Tokenizer.DOCTYPE_TOKEN]: ignoreToken,\n [Tokenizer.START_TAG_TOKEN]: startTagInTableBody,\n [Tokenizer.END_TAG_TOKEN]: endTagInTableBody,\n [Tokenizer.EOF_TOKEN]: eofInBody\n },\n [IN_ROW_MODE]: {\n [Tokenizer.CHARACTER_TOKEN]: characterInTable,\n [Tokenizer.NULL_CHARACTER_TOKEN]: characterInTable,\n [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: characterInTable,\n [Tokenizer.COMMENT_TOKEN]: appendComment,\n [Tokenizer.DOCTYPE_TOKEN]: ignoreToken,\n [Tokenizer.START_TAG_TOKEN]: startTagInRow,\n [Tokenizer.END_TAG_TOKEN]: endTagInRow,\n [Tokenizer.EOF_TOKEN]: eofInBody\n },\n [IN_CELL_MODE]: {\n [Tokenizer.CHARACTER_TOKEN]: characterInBody,\n [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken,\n [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody,\n [Tokenizer.COMMENT_TOKEN]: appendComment,\n [Tokenizer.DOCTYPE_TOKEN]: ignoreToken,\n [Tokenizer.START_TAG_TOKEN]: startTagInCell,\n [Tokenizer.END_TAG_TOKEN]: endTagInCell,\n [Tokenizer.EOF_TOKEN]: eofInBody\n },\n [IN_SELECT_MODE]: {\n [Tokenizer.CHARACTER_TOKEN]: insertCharacters,\n [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken,\n [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters,\n [Tokenizer.COMMENT_TOKEN]: appendComment,\n [Tokenizer.DOCTYPE_TOKEN]: ignoreToken,\n [Tokenizer.START_TAG_TOKEN]: startTagInSelect,\n [Tokenizer.END_TAG_TOKEN]: endTagInSelect,\n [Tokenizer.EOF_TOKEN]: eofInBody\n },\n [IN_SELECT_IN_TABLE_MODE]: {\n [Tokenizer.CHARACTER_TOKEN]: insertCharacters,\n [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken,\n [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters,\n [Tokenizer.COMMENT_TOKEN]: appendComment,\n [Tokenizer.DOCTYPE_TOKEN]: ignoreToken,\n [Tokenizer.START_TAG_TOKEN]: startTagInSelectInTable,\n [Tokenizer.END_TAG_TOKEN]: endTagInSelectInTable,\n [Tokenizer.EOF_TOKEN]: eofInBody\n },\n [IN_TEMPLATE_MODE]: {\n [Tokenizer.CHARACTER_TOKEN]: characterInBody,\n [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken,\n [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody,\n [Tokenizer.COMMENT_TOKEN]: appendComment,\n [Tokenizer.DOCTYPE_TOKEN]: ignoreToken,\n [Tokenizer.START_TAG_TOKEN]: startTagInTemplate,\n [Tokenizer.END_TAG_TOKEN]: endTagInTemplate,\n [Tokenizer.EOF_TOKEN]: eofInTemplate\n },\n [AFTER_BODY_MODE]: {\n [Tokenizer.CHARACTER_TOKEN]: tokenAfterBody,\n [Tokenizer.NULL_CHARACTER_TOKEN]: tokenAfterBody,\n [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody,\n [Tokenizer.COMMENT_TOKEN]: appendCommentToRootHtmlElement,\n [Tokenizer.DOCTYPE_TOKEN]: ignoreToken,\n [Tokenizer.START_TAG_TOKEN]: startTagAfterBody,\n [Tokenizer.END_TAG_TOKEN]: endTagAfterBody,\n [Tokenizer.EOF_TOKEN]: stopParsing\n },\n [IN_FRAMESET_MODE]: {\n [Tokenizer.CHARACTER_TOKEN]: ignoreToken,\n [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken,\n [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters,\n [Tokenizer.COMMENT_TOKEN]: appendComment,\n [Tokenizer.DOCTYPE_TOKEN]: ignoreToken,\n [Tokenizer.START_TAG_TOKEN]: startTagInFrameset,\n [Tokenizer.END_TAG_TOKEN]: endTagInFrameset,\n [Tokenizer.EOF_TOKEN]: stopParsing\n },\n [AFTER_FRAMESET_MODE]: {\n [Tokenizer.CHARACTER_TOKEN]: ignoreToken,\n [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken,\n [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: insertCharacters,\n [Tokenizer.COMMENT_TOKEN]: appendComment,\n [Tokenizer.DOCTYPE_TOKEN]: ignoreToken,\n [Tokenizer.START_TAG_TOKEN]: startTagAfterFrameset,\n [Tokenizer.END_TAG_TOKEN]: endTagAfterFrameset,\n [Tokenizer.EOF_TOKEN]: stopParsing\n },\n [AFTER_AFTER_BODY_MODE]: {\n [Tokenizer.CHARACTER_TOKEN]: tokenAfterAfterBody,\n [Tokenizer.NULL_CHARACTER_TOKEN]: tokenAfterAfterBody,\n [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody,\n [Tokenizer.COMMENT_TOKEN]: appendCommentToDocument,\n [Tokenizer.DOCTYPE_TOKEN]: ignoreToken,\n [Tokenizer.START_TAG_TOKEN]: startTagAfterAfterBody,\n [Tokenizer.END_TAG_TOKEN]: tokenAfterAfterBody,\n [Tokenizer.EOF_TOKEN]: stopParsing\n },\n [AFTER_AFTER_FRAMESET_MODE]: {\n [Tokenizer.CHARACTER_TOKEN]: ignoreToken,\n [Tokenizer.NULL_CHARACTER_TOKEN]: ignoreToken,\n [Tokenizer.WHITESPACE_CHARACTER_TOKEN]: whitespaceCharacterInBody,\n [Tokenizer.COMMENT_TOKEN]: appendCommentToDocument,\n [Tokenizer.DOCTYPE_TOKEN]: ignoreToken,\n [Tokenizer.START_TAG_TOKEN]: startTagAfterAfterFrameset,\n [Tokenizer.END_TAG_TOKEN]: ignoreToken,\n [Tokenizer.EOF_TOKEN]: stopParsing\n }\n};\n\n//Parser\nclass Parser {\n constructor(options) {\n this.options = mergeOptions(DEFAULT_OPTIONS, options);\n\n this.treeAdapter = this.options.treeAdapter;\n this.pendingScript = null;\n\n if (this.options.sourceCodeLocationInfo) {\n Mixin.install(this, LocationInfoParserMixin);\n }\n\n if (this.options.onParseError) {\n Mixin.install(this, ErrorReportingParserMixin, { onParseError: this.options.onParseError });\n }\n }\n\n // API\n parse(html) {\n const document = this.treeAdapter.createDocument();\n\n this._bootstrap(document, null);\n this.tokenizer.write(html, true);\n this._runParsingLoop(null);\n\n return document;\n }\n\n parseFragment(html, fragmentContext) {\n //NOTE: use