@azure/identity 1.0.0-preview.1 → 1.0.0-preview.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of @azure/identity might be problematic. Click here for more details.
- package/CHANGELOG.md +24 -0
- package/README.md +50 -23
- package/browser/identity.js +9828 -0
- package/browser/identity.js.map +1 -0
- package/browser/identity.min.js +2 -0
- package/browser/identity.min.js.map +1 -0
- package/dist/index.js +475 -205
- package/dist/index.js.map +1 -1
- package/dist-esm/src/client/errors.d.ts +1 -1
- package/dist-esm/src/client/errors.d.ts.map +1 -1
- package/dist-esm/src/client/errors.js +9 -1
- package/dist-esm/src/client/errors.js.map +1 -1
- package/dist-esm/src/client/identityClient.d.ts +20 -17
- package/dist-esm/src/client/identityClient.d.ts.map +1 -1
- package/dist-esm/src/client/identityClient.js +42 -206
- package/dist-esm/src/client/identityClient.js.map +1 -1
- package/dist-esm/src/credentials/clientCertificateCredential.browser.d.ts +7 -0
- package/dist-esm/src/credentials/clientCertificateCredential.browser.d.ts.map +1 -0
- package/dist-esm/src/credentials/clientCertificateCredential.browser.js +12 -0
- package/dist-esm/src/credentials/clientCertificateCredential.browser.js.map +1 -0
- package/dist-esm/src/credentials/clientCertificateCredential.d.ts +5 -5
- package/dist-esm/src/credentials/clientCertificateCredential.d.ts.map +1 -1
- package/dist-esm/src/credentials/clientCertificateCredential.js +59 -5
- package/dist-esm/src/credentials/clientCertificateCredential.js.map +1 -1
- package/dist-esm/src/credentials/clientSecretCredential.d.ts +3 -3
- package/dist-esm/src/credentials/clientSecretCredential.d.ts.map +1 -1
- package/dist-esm/src/credentials/clientSecretCredential.js +27 -4
- package/dist-esm/src/credentials/clientSecretCredential.js.map +1 -1
- package/dist-esm/src/credentials/deviceCodeCredential.browser.d.ts +7 -0
- package/dist-esm/src/credentials/deviceCodeCredential.browser.d.ts.map +1 -0
- package/dist-esm/src/credentials/deviceCodeCredential.browser.js +12 -0
- package/dist-esm/src/credentials/deviceCodeCredential.browser.js.map +1 -0
- package/dist-esm/src/credentials/deviceCodeCredential.d.ts +67 -0
- package/dist-esm/src/credentials/deviceCodeCredential.d.ts.map +1 -0
- package/dist-esm/src/credentials/deviceCodeCredential.js +139 -0
- package/dist-esm/src/credentials/deviceCodeCredential.js.map +1 -0
- package/dist-esm/src/credentials/environmentCredential.browser.d.ts +7 -0
- package/dist-esm/src/credentials/environmentCredential.browser.d.ts.map +1 -0
- package/dist-esm/src/credentials/environmentCredential.browser.js +12 -0
- package/dist-esm/src/credentials/environmentCredential.browser.js.map +1 -0
- package/dist-esm/src/credentials/environmentCredential.d.ts.map +1 -1
- package/dist-esm/src/credentials/environmentCredential.js +0 -4
- package/dist-esm/src/credentials/environmentCredential.js.map +1 -1
- package/dist-esm/src/credentials/interactiveBrowserCredential.browser.d.ts +32 -0
- package/dist-esm/src/credentials/interactiveBrowserCredential.browser.d.ts.map +1 -0
- package/dist-esm/src/credentials/interactiveBrowserCredential.browser.js +112 -0
- package/dist-esm/src/credentials/interactiveBrowserCredential.browser.js.map +1 -0
- package/dist-esm/src/credentials/interactiveBrowserCredential.d.ts +12 -0
- package/dist-esm/src/credentials/interactiveBrowserCredential.d.ts.map +1 -0
- package/dist-esm/src/credentials/interactiveBrowserCredential.js +17 -0
- package/dist-esm/src/credentials/interactiveBrowserCredential.js.map +1 -0
- package/dist-esm/src/credentials/interactiveBrowserCredentialOptions.d.ts +24 -0
- package/dist-esm/src/credentials/interactiveBrowserCredentialOptions.d.ts.map +1 -0
- package/dist-esm/src/credentials/interactiveBrowserCredentialOptions.js +3 -0
- package/dist-esm/src/credentials/interactiveBrowserCredentialOptions.js.map +1 -0
- package/dist-esm/src/credentials/managedIdentityCredential.browser.d.ts +7 -0
- package/dist-esm/src/credentials/managedIdentityCredential.browser.d.ts.map +1 -0
- package/dist-esm/src/credentials/managedIdentityCredential.browser.js +15 -0
- package/dist-esm/src/credentials/managedIdentityCredential.browser.js.map +1 -0
- package/dist-esm/src/credentials/managedIdentityCredential.d.ts +10 -1
- package/dist-esm/src/credentials/managedIdentityCredential.d.ts.map +1 -1
- package/dist-esm/src/credentials/managedIdentityCredential.js +144 -2
- package/dist-esm/src/credentials/managedIdentityCredential.js.map +1 -1
- package/dist-esm/src/credentials/usernamePasswordCredential.d.ts +39 -0
- package/dist-esm/src/credentials/usernamePasswordCredential.d.ts.map +1 -0
- package/dist-esm/src/credentials/usernamePasswordCredential.js +67 -0
- package/dist-esm/src/credentials/usernamePasswordCredential.js.map +1 -0
- package/dist-esm/src/index.d.ts +4 -0
- package/dist-esm/src/index.d.ts.map +1 -1
- package/dist-esm/src/index.js +3 -0
- package/dist-esm/src/index.js.map +1 -1
- package/package.json +32 -14
- package/src/client/errors.ts +11 -3
- package/src/client/identityClient.ts +64 -246
- package/src/credentials/clientCertificateCredential.browser.ts +27 -0
- package/src/credentials/clientCertificateCredential.ts +72 -22
- package/src/credentials/clientSecretCredential.ts +32 -17
- package/src/credentials/deviceCodeCredential.browser.ts +27 -0
- package/src/credentials/deviceCodeCredential.ts +203 -0
- package/src/credentials/environmentCredential.browser.ts +19 -0
- package/src/credentials/environmentCredential.ts +5 -9
- package/src/credentials/interactiveBrowserCredential.browser.ts +134 -0
- package/src/credentials/interactiveBrowserCredential.ts +31 -0
- package/src/credentials/interactiveBrowserCredentialOptions.ts +30 -0
- package/src/credentials/managedIdentityCredential.browser.ts +22 -0
- package/src/credentials/managedIdentityCredential.ts +179 -8
- package/src/credentials/usernamePasswordCredential.ts +83 -0
- package/src/index.ts +4 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"identity.min.js","sources":["../../../../common/temp/node_modules/.registry.npmjs.org/tslib/1.10.0/node_modules/tslib/tslib.es6.js","../src/client/errors.ts","../src/credentials/chainedTokenCredential.ts","../src/credentials/environmentCredential.browser.ts","../src/credentials/managedIdentityCredential.browser.ts","../src/credentials/defaultAzureCredential.ts","../../../../common/temp/node_modules/.registry.npmjs.org/qs/6.7.0/node_modules/qs/lib/utils.js","../../../../common/temp/node_modules/.registry.npmjs.org/qs/6.7.0/node_modules/qs/lib/formats.js","../../../../common/temp/node_modules/.registry.npmjs.org/qs/6.7.0/node_modules/qs/lib/stringify.js","../../../../common/temp/node_modules/.registry.npmjs.org/qs/6.7.0/node_modules/qs/lib/parse.js","../node_modules/qs/lib/index.js","../../../core/core-http/lib/httpHeaders.ts","../../../core/core-http/lib/util/base64.browser.ts","../../../../common/temp/node_modules/.registry.npmjs.org/uuid/3.3.2/node_modules/uuid/lib/bytesToUuid.js","../../../core/core-http/node_modules/uuid/lib/rng-browser.js","../../../core/core-http/node_modules/uuid/v4.js","../../../core/core-http/lib/util/constants.ts","../../../core/core-http/lib/util/utils.ts","../../../core/core-http/lib/serializer.ts","../../../core/core-http/lib/webResource.ts","../../../core/core-http/lib/restError.ts","../../../core/core-http/lib/xhrHttpClient.ts","../../../core/core-http/lib/httpPipelineLogLevel.ts","../../../../common/temp/node_modules/.registry.npmjs.org/@azure/core-auth/1.0.0-preview.2/node_modules/@azure/core-auth/src/tokenCredential.ts","../../../core/core-http/lib/operationParameter.ts","../../../core/core-http/lib/operationSpec.ts","../../../core/core-http/lib/util/xml.browser.ts","../../../core/core-http/lib/policies/requestPolicy.ts","../../../core/core-http/lib/policies/deserializationPolicy.ts","../../../core/core-http/lib/policies/exponentialRetryPolicy.ts","../../../core/core-http/lib/policies/generateClientRequestIdPolicy.ts","../../../core/core-http/lib/policies/msRestUserAgentPolicy.browser.ts","../../../core/core-http/lib/policies/userAgentPolicy.ts","../../../core/core-http/lib/url.ts","../../../core/core-http/lib/policies/redirectPolicy.ts","../../../core/core-http/lib/policies/rpRegistrationPolicy.ts","../../../core/core-http/lib/credentials/accessTokenCache.ts","../../../core/core-http/lib/policies/bearerTokenAuthenticationPolicy.ts","../../../core/core-http/lib/policies/systemErrorRetryPolicy.ts","../../../core/core-http/lib/queryCollectionFormat.ts","../../../core/core-http/lib/policies/proxyPolicy.browser.ts","../../../core/core-http/lib/policies/throttlingRetryPolicy.ts","../../../core/core-http/lib/serviceClient.ts","../src/client/identityClient.ts","../src/credentials/clientSecretCredential.ts","../src/credentials/clientCertificateCredential.browser.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/Constants.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/error/AuthError.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/error/ClientAuthError.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/js-base64/base64.js","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/Utils.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/AccessTokenKey.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/AccessTokenValue.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/ServerRequestParameters.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/ClientInfo.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/IdToken.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/AccessTokenCacheItem.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/error/ClientConfigurationError.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/Storage.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/Account.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/XHRClient.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/Authority.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/AadAuthority.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/B2cAuthority.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/AuthorityFactory.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/Logger.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/Configuration.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/AuthenticationParameters.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/error/ServerError.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/error/InteractionRequiredAuthError.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/AuthResponse.ts","../../../../common/temp/node_modules/.registry.npmjs.org/msal/1.0.2/node_modules/msal/src/UserAgentApplication.ts","../src/credentials/interactiveBrowserCredential.browser.ts","../src/credentials/deviceCodeCredential.browser.ts","../src/credentials/usernamePasswordCredential.ts","../src/index.ts"],"sourcesContent":["/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation. All rights reserved.\r\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\r\nthis file except in compliance with the License. You may obtain a copy of the\r\nLicense at http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\r\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\r\nMERCHANTABLITY OR NON-INFRINGEMENT.\r\n\r\nSee the Apache Version 2.0 License for specific language governing permissions\r\nand limitations under the License.\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 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) : new P(function (resolve) { resolve(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 __exportStar(m, exports) {\r\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\r\n if (m) return m.call(o);\r\n 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}\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","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * See the official documentation for more details:\n *\n * https://docs.microsoft.com/en-us/azure/active-directory/develop/v1-protocols-oauth-code#error-response-1\n *\n * NOTE: This documentation is for v1 OAuth support but the same error\n * response details still apply to v2.\n */\nexport interface ErrorResponse {\n error: string;\n error_description: string;\n error_codes?: number[];\n timestamp?: string;\n trace_id?: string;\n correlation_id?: string;\n}\n\nfunction isErrorResponse(errorResponse: any): errorResponse is ErrorResponse {\n return errorResponse &&\n typeof errorResponse.error === \"string\" &&\n typeof errorResponse.error_description === \"string\";\n}\n\n/**\n * Provides details about a failure to authenticate with Azure Active\n * Directory. The `errorResponse` field contains more details about\n * the specific failure.\n */\nexport class AuthenticationError extends Error {\n public readonly statusCode: number;\n public readonly errorResponse: ErrorResponse;\n\n constructor(statusCode: number, errorBody: object | string | undefined | null) {\n let errorResponse = {\n error: \"unknown\",\n error_description: \"An unknown error occurred and no additional details are available.\"\n };\n\n if (isErrorResponse(errorBody)) {\n errorResponse = errorBody;\n } else if (typeof errorBody === \"string\") {\n try {\n // Most error responses will contain JSON-formatted error details\n // in the response body\n errorResponse = JSON.parse(errorBody);\n } catch (e) {\n if (statusCode === 400) {\n errorResponse = {\n error: \"authority_not_found\",\n error_description: \"The specified authority URL was not found.\"\n };\n } else {\n errorResponse = {\n error: \"unknown_error\",\n error_description: `An unknown error has occurred. Response body:\\n\\n${errorBody}`\n };\n }\n }\n } else {\n errorResponse = {\n error: \"unknown_error\",\n error_description: \"An unknown error occurred and no additional details are available.\"\n };\n }\n\n super(\n `An error was returned while authenticating to Azure Active Directory (status code ${statusCode}).\\n\\nMore details:\\n\\n${JSON.stringify(\n errorResponse,\n null,\n \" \"\n )}`\n );\n this.statusCode = statusCode;\n this.errorResponse = errorResponse;\n\n // Ensure that this type reports the correct name\n this.name = \"AuthenticationError\";\n }\n}\n\n/**\n * Provides an `errors` array containing {@link AuthenticationError} instance\n * for authentication failures from credentials in a {@link ChainedTokenCredential}.\n */\nexport class AggregateAuthenticationError extends Error {\n public errors: any[];\n constructor(errors: any[]) {\n super(\"Authentication failed to complete due to errors\");\n this.errors = errors;\n\n // Ensure that this type reports the correct name\n this.name = \"AggregateAuthenticationError\";\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken, TokenCredential, GetTokenOptions } from \"@azure/core-http\";\nimport { AggregateAuthenticationError } from \"../client/errors\";\n\n/**\n * Enables multiple {@link TokenCredential} implementations to be tried in order\n * until one of the getToken methods returns an {@link AccessToken}.\n */\nexport class ChainedTokenCredential implements TokenCredential {\n private _sources: TokenCredential[] = [];\n\n constructor(...sources: TokenCredential[]) {\n this._sources = sources;\n }\n\n /**\n * Returns the first {@link AccessToken} returned by one of the chained\n * {@link TokenCredential} implementations. Throws an {@link AggregateAuthenticationError}\n * when one or more credentials throws an {@link AuthenticationError} and\n * no credentials have returned an {@link AccessToken}.\n * \n * @param scopes The list of scopes for which the token will have access.\n * @param options The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n let token = null;\n const errors = [];\n\n for (let i = 0; i < this._sources.length && token === null; i++) {\n try {\n token = await this._sources[i].getToken(scopes, options);\n } catch (err) {\n errors.push(err);\n }\n }\n\n if (!token && errors.length > 0) {\n throw new AggregateAuthenticationError(errors);\n }\n\n return token;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport { AccessToken, TokenCredential, GetTokenOptions } from \"@azure/core-http\";\nimport { IdentityClientOptions } from \"../client/identityClient\";\n\nconst BrowserNotSupportedError = new Error(\"EnvironmentCredential is not supported in the browser.\");\n\nexport class EnvironmentCredential implements TokenCredential {\n constructor(options?: IdentityClientOptions) {\n throw BrowserNotSupportedError;\n }\n\n getToken(scopes: string | string[], options?: GetTokenOptions): Promise<AccessToken | null> {\n throw BrowserNotSupportedError;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport { AccessToken, GetTokenOptions, TokenCredential } from \"@azure/core-http\";\nimport { IdentityClientOptions } from \"../client/identityClient\";\n\nconst BrowserNotSupportedError = new Error(\"ManagedIdentityCredential is not supported in the browser.\");\n\nexport class ManagedIdentityCredential implements TokenCredential {\n constructor(clientId?: string, options?: IdentityClientOptions) {\n throw BrowserNotSupportedError;\n }\n\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n throw BrowserNotSupportedError;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { IdentityClientOptions } from \"../client/identityClient\";\nimport { ChainedTokenCredential } from \"./chainedTokenCredential\";\nimport { EnvironmentCredential } from \"./environmentCredential\";\nimport { ManagedIdentityCredential } from \"./managedIdentityCredential\";\n\n/**\n * Provides a default {@link ChainedTokenCredential} configuration for\n * applications that will be deployed to Azure. The following credential\n * types will be tried, in order:\n * \n * - {@link EnvironmentCredential}\n * - {@link ManagedIdentityCredential}\n * \n * Consult the documentation of these credential types for more information\n * on how they attempt authentication.\n */\nexport class DefaultAzureCredential extends ChainedTokenCredential {\n /**\n * Creates an instance of the DefaultAzureCredential class.\n * \n * @param options Options for configuring the client which makes the authentication request.\n */\n constructor(identityClientOptions?: IdentityClientOptions) {\n super(\n new EnvironmentCredential(identityClientOptions),\n new ManagedIdentityCredential(undefined, identityClientOptions)\n );\n }\n}\n","'use strict';\n\nvar has = Object.prototype.hasOwnProperty;\nvar isArray = Array.isArray;\n\nvar hexTable = (function () {\n var array = [];\n for (var i = 0; i < 256; ++i) {\n array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());\n }\n\n return array;\n}());\n\nvar compactQueue = function compactQueue(queue) {\n while (queue.length > 1) {\n var item = queue.pop();\n var obj = item.obj[item.prop];\n\n if (isArray(obj)) {\n var compacted = [];\n\n for (var j = 0; j < obj.length; ++j) {\n if (typeof obj[j] !== 'undefined') {\n compacted.push(obj[j]);\n }\n }\n\n item.obj[item.prop] = compacted;\n }\n }\n};\n\nvar arrayToObject = function arrayToObject(source, options) {\n var obj = options && options.plainObjects ? Object.create(null) : {};\n for (var i = 0; i < source.length; ++i) {\n if (typeof source[i] !== 'undefined') {\n obj[i] = source[i];\n }\n }\n\n return obj;\n};\n\nvar merge = function merge(target, source, options) {\n if (!source) {\n return target;\n }\n\n if (typeof source !== 'object') {\n if (isArray(target)) {\n target.push(source);\n } else if (target && typeof target === 'object') {\n if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) {\n target[source] = true;\n }\n } else {\n return [target, source];\n }\n\n return target;\n }\n\n if (!target || typeof target !== 'object') {\n return [target].concat(source);\n }\n\n var mergeTarget = target;\n if (isArray(target) && !isArray(source)) {\n mergeTarget = arrayToObject(target, options);\n }\n\n if (isArray(target) && isArray(source)) {\n source.forEach(function (item, i) {\n if (has.call(target, i)) {\n var targetItem = target[i];\n if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') {\n target[i] = merge(targetItem, item, options);\n } else {\n target.push(item);\n }\n } else {\n target[i] = item;\n }\n });\n return target;\n }\n\n return Object.keys(source).reduce(function (acc, key) {\n var value = source[key];\n\n if (has.call(acc, key)) {\n acc[key] = merge(acc[key], value, options);\n } else {\n acc[key] = value;\n }\n return acc;\n }, mergeTarget);\n};\n\nvar assign = function assignSingleSource(target, source) {\n return Object.keys(source).reduce(function (acc, key) {\n acc[key] = source[key];\n return acc;\n }, target);\n};\n\nvar decode = function (str, decoder, charset) {\n var strWithoutPlus = str.replace(/\\+/g, ' ');\n if (charset === 'iso-8859-1') {\n // unescape never throws, no try...catch needed:\n return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);\n }\n // utf-8\n try {\n return decodeURIComponent(strWithoutPlus);\n } catch (e) {\n return strWithoutPlus;\n }\n};\n\nvar encode = function encode(str, defaultEncoder, charset) {\n // This code was originally written by Brian White (mscdex) for the io.js core querystring library.\n // It has been adapted here for stricter adherence to RFC 3986\n if (str.length === 0) {\n return str;\n }\n\n var string = typeof str === 'string' ? str : String(str);\n\n if (charset === 'iso-8859-1') {\n return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) {\n return '%26%23' + parseInt($0.slice(2), 16) + '%3B';\n });\n }\n\n var out = '';\n for (var i = 0; i < string.length; ++i) {\n var c = string.charCodeAt(i);\n\n if (\n c === 0x2D // -\n || c === 0x2E // .\n || c === 0x5F // _\n || c === 0x7E // ~\n || (c >= 0x30 && c <= 0x39) // 0-9\n || (c >= 0x41 && c <= 0x5A) // a-z\n || (c >= 0x61 && c <= 0x7A) // A-Z\n ) {\n out += string.charAt(i);\n continue;\n }\n\n if (c < 0x80) {\n out = out + hexTable[c];\n continue;\n }\n\n if (c < 0x800) {\n out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);\n continue;\n }\n\n if (c < 0xD800 || c >= 0xE000) {\n out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);\n continue;\n }\n\n i += 1;\n c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));\n out += hexTable[0xF0 | (c >> 18)]\n + hexTable[0x80 | ((c >> 12) & 0x3F)]\n + hexTable[0x80 | ((c >> 6) & 0x3F)]\n + hexTable[0x80 | (c & 0x3F)];\n }\n\n return out;\n};\n\nvar compact = function compact(value) {\n var queue = [{ obj: { o: value }, prop: 'o' }];\n var refs = [];\n\n for (var i = 0; i < queue.length; ++i) {\n var item = queue[i];\n var obj = item.obj[item.prop];\n\n var keys = Object.keys(obj);\n for (var j = 0; j < keys.length; ++j) {\n var key = keys[j];\n var val = obj[key];\n if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {\n queue.push({ obj: obj, prop: key });\n refs.push(val);\n }\n }\n }\n\n compactQueue(queue);\n\n return value;\n};\n\nvar isRegExp = function isRegExp(obj) {\n return Object.prototype.toString.call(obj) === '[object RegExp]';\n};\n\nvar isBuffer = function isBuffer(obj) {\n if (!obj || typeof obj !== 'object') {\n return false;\n }\n\n return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));\n};\n\nvar combine = function combine(a, b) {\n return [].concat(a, b);\n};\n\nmodule.exports = {\n arrayToObject: arrayToObject,\n assign: assign,\n combine: combine,\n compact: compact,\n decode: decode,\n encode: encode,\n isBuffer: isBuffer,\n isRegExp: isRegExp,\n merge: merge\n};\n","'use strict';\n\nvar replace = String.prototype.replace;\nvar percentTwenties = /%20/g;\n\nmodule.exports = {\n 'default': 'RFC3986',\n formatters: {\n RFC1738: function (value) {\n return replace.call(value, percentTwenties, '+');\n },\n RFC3986: function (value) {\n return value;\n }\n },\n RFC1738: 'RFC1738',\n RFC3986: 'RFC3986'\n};\n","'use strict';\n\nvar utils = require('./utils');\nvar formats = require('./formats');\nvar has = Object.prototype.hasOwnProperty;\n\nvar arrayPrefixGenerators = {\n brackets: function brackets(prefix) { // eslint-disable-line func-name-matching\n return prefix + '[]';\n },\n comma: 'comma',\n indices: function indices(prefix, key) { // eslint-disable-line func-name-matching\n return prefix + '[' + key + ']';\n },\n repeat: function repeat(prefix) { // eslint-disable-line func-name-matching\n return prefix;\n }\n};\n\nvar isArray = Array.isArray;\nvar push = Array.prototype.push;\nvar pushToArray = function (arr, valueOrArray) {\n push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]);\n};\n\nvar toISO = Date.prototype.toISOString;\n\nvar defaults = {\n addQueryPrefix: false,\n allowDots: false,\n charset: 'utf-8',\n charsetSentinel: false,\n delimiter: '&',\n encode: true,\n encoder: utils.encode,\n encodeValuesOnly: false,\n formatter: formats.formatters[formats['default']],\n // deprecated\n indices: false,\n serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching\n return toISO.call(date);\n },\n skipNulls: false,\n strictNullHandling: false\n};\n\nvar stringify = function stringify( // eslint-disable-line func-name-matching\n object,\n prefix,\n generateArrayPrefix,\n strictNullHandling,\n skipNulls,\n encoder,\n filter,\n sort,\n allowDots,\n serializeDate,\n formatter,\n encodeValuesOnly,\n charset\n) {\n var obj = object;\n if (typeof filter === 'function') {\n obj = filter(prefix, obj);\n } else if (obj instanceof Date) {\n obj = serializeDate(obj);\n } else if (generateArrayPrefix === 'comma' && isArray(obj)) {\n obj = obj.join(',');\n }\n\n if (obj === null) {\n if (strictNullHandling) {\n return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset) : prefix;\n }\n\n obj = '';\n }\n\n if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) {\n if (encoder) {\n var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset);\n return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset))];\n }\n return [formatter(prefix) + '=' + formatter(String(obj))];\n }\n\n var values = [];\n\n if (typeof obj === 'undefined') {\n return values;\n }\n\n var objKeys;\n if (isArray(filter)) {\n objKeys = filter;\n } else {\n var keys = Object.keys(obj);\n objKeys = sort ? keys.sort(sort) : keys;\n }\n\n for (var i = 0; i < objKeys.length; ++i) {\n var key = objKeys[i];\n\n if (skipNulls && obj[key] === null) {\n continue;\n }\n\n if (isArray(obj)) {\n pushToArray(values, stringify(\n obj[key],\n typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix,\n generateArrayPrefix,\n strictNullHandling,\n skipNulls,\n encoder,\n filter,\n sort,\n allowDots,\n serializeDate,\n formatter,\n encodeValuesOnly,\n charset\n ));\n } else {\n pushToArray(values, stringify(\n obj[key],\n prefix + (allowDots ? '.' + key : '[' + key + ']'),\n generateArrayPrefix,\n strictNullHandling,\n skipNulls,\n encoder,\n filter,\n sort,\n allowDots,\n serializeDate,\n formatter,\n encodeValuesOnly,\n charset\n ));\n }\n }\n\n return values;\n};\n\nvar normalizeStringifyOptions = function normalizeStringifyOptions(opts) {\n if (!opts) {\n return defaults;\n }\n\n if (opts.encoder !== null && opts.encoder !== undefined && typeof opts.encoder !== 'function') {\n throw new TypeError('Encoder has to be a function.');\n }\n\n var charset = opts.charset || defaults.charset;\n if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {\n throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');\n }\n\n var format = formats['default'];\n if (typeof opts.format !== 'undefined') {\n if (!has.call(formats.formatters, opts.format)) {\n throw new TypeError('Unknown format option provided.');\n }\n format = opts.format;\n }\n var formatter = formats.formatters[format];\n\n var filter = defaults.filter;\n if (typeof opts.filter === 'function' || isArray(opts.filter)) {\n filter = opts.filter;\n }\n\n return {\n addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix,\n allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,\n charset: charset,\n charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,\n delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter,\n encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode,\n encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder,\n encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly,\n filter: filter,\n formatter: formatter,\n serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate,\n skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls,\n sort: typeof opts.sort === 'function' ? opts.sort : null,\n strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling\n };\n};\n\nmodule.exports = function (object, opts) {\n var obj = object;\n var options = normalizeStringifyOptions(opts);\n\n var objKeys;\n var filter;\n\n if (typeof options.filter === 'function') {\n filter = options.filter;\n obj = filter('', obj);\n } else if (isArray(options.filter)) {\n filter = options.filter;\n objKeys = filter;\n }\n\n var keys = [];\n\n if (typeof obj !== 'object' || obj === null) {\n return '';\n }\n\n var arrayFormat;\n if (opts && opts.arrayFormat in arrayPrefixGenerators) {\n arrayFormat = opts.arrayFormat;\n } else if (opts && 'indices' in opts) {\n arrayFormat = opts.indices ? 'indices' : 'repeat';\n } else {\n arrayFormat = 'indices';\n }\n\n var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];\n\n if (!objKeys) {\n objKeys = Object.keys(obj);\n }\n\n if (options.sort) {\n objKeys.sort(options.sort);\n }\n\n for (var i = 0; i < objKeys.length; ++i) {\n var key = objKeys[i];\n\n if (options.skipNulls && obj[key] === null) {\n continue;\n }\n pushToArray(keys, stringify(\n obj[key],\n key,\n generateArrayPrefix,\n options.strictNullHandling,\n options.skipNulls,\n options.encode ? options.encoder : null,\n options.filter,\n options.sort,\n options.allowDots,\n options.serializeDate,\n options.formatter,\n options.encodeValuesOnly,\n options.charset\n ));\n }\n\n var joined = keys.join(options.delimiter);\n var prefix = options.addQueryPrefix === true ? '?' : '';\n\n if (options.charsetSentinel) {\n if (options.charset === 'iso-8859-1') {\n // encodeURIComponent('✓'), the \"numeric entity\" representation of a checkmark\n prefix += 'utf8=%26%2310003%3B&';\n } else {\n // encodeURIComponent('✓')\n prefix += 'utf8=%E2%9C%93&';\n }\n }\n\n return joined.length > 0 ? prefix + joined : '';\n};\n","'use strict';\n\nvar utils = require('./utils');\n\nvar has = Object.prototype.hasOwnProperty;\n\nvar defaults = {\n allowDots: false,\n allowPrototypes: false,\n arrayLimit: 20,\n charset: 'utf-8',\n charsetSentinel: false,\n comma: false,\n decoder: utils.decode,\n delimiter: '&',\n depth: 5,\n ignoreQueryPrefix: false,\n interpretNumericEntities: false,\n parameterLimit: 1000,\n parseArrays: true,\n plainObjects: false,\n strictNullHandling: false\n};\n\nvar interpretNumericEntities = function (str) {\n return str.replace(/&#(\\d+);/g, function ($0, numberStr) {\n return String.fromCharCode(parseInt(numberStr, 10));\n });\n};\n\n// This is what browsers will submit when the ✓ character occurs in an\n// application/x-www-form-urlencoded body and the encoding of the page containing\n// the form is iso-8859-1, or when the submitted form has an accept-charset\n// attribute of iso-8859-1. Presumably also with other charsets that do not contain\n// the ✓ character, such as us-ascii.\nvar isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓')\n\n// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded.\nvar charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓')\n\nvar parseValues = function parseQueryStringValues(str, options) {\n var obj = {};\n var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\\?/, '') : str;\n var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;\n var parts = cleanStr.split(options.delimiter, limit);\n var skipIndex = -1; // Keep track of where the utf8 sentinel was found\n var i;\n\n var charset = options.charset;\n if (options.charsetSentinel) {\n for (i = 0; i < parts.length; ++i) {\n if (parts[i].indexOf('utf8=') === 0) {\n if (parts[i] === charsetSentinel) {\n charset = 'utf-8';\n } else if (parts[i] === isoSentinel) {\n charset = 'iso-8859-1';\n }\n skipIndex = i;\n i = parts.length; // The eslint settings do not allow break;\n }\n }\n }\n\n for (i = 0; i < parts.length; ++i) {\n if (i === skipIndex) {\n continue;\n }\n var part = parts[i];\n\n var bracketEqualsPos = part.indexOf(']=');\n var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;\n\n var key, val;\n if (pos === -1) {\n key = options.decoder(part, defaults.decoder, charset);\n val = options.strictNullHandling ? null : '';\n } else {\n key = options.decoder(part.slice(0, pos), defaults.decoder, charset);\n val = options.decoder(part.slice(pos + 1), defaults.decoder, charset);\n }\n\n if (val && options.interpretNumericEntities && charset === 'iso-8859-1') {\n val = interpretNumericEntities(val);\n }\n\n if (val && options.comma && val.indexOf(',') > -1) {\n val = val.split(',');\n }\n\n if (has.call(obj, key)) {\n obj[key] = utils.combine(obj[key], val);\n } else {\n obj[key] = val;\n }\n }\n\n return obj;\n};\n\nvar parseObject = function (chain, val, options) {\n var leaf = val;\n\n for (var i = chain.length - 1; i >= 0; --i) {\n var obj;\n var root = chain[i];\n\n if (root === '[]' && options.parseArrays) {\n obj = [].concat(leaf);\n } else {\n obj = options.plainObjects ? Object.create(null) : {};\n var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;\n var index = parseInt(cleanRoot, 10);\n if (!options.parseArrays && cleanRoot === '') {\n obj = { 0: leaf };\n } else if (\n !isNaN(index)\n && root !== cleanRoot\n && String(index) === cleanRoot\n && index >= 0\n && (options.parseArrays && index <= options.arrayLimit)\n ) {\n obj = [];\n obj[index] = leaf;\n } else {\n obj[cleanRoot] = leaf;\n }\n }\n\n leaf = obj;\n }\n\n return leaf;\n};\n\nvar parseKeys = function parseQueryStringKeys(givenKey, val, options) {\n if (!givenKey) {\n return;\n }\n\n // Transform dot notation to bracket notation\n var key = options.allowDots ? givenKey.replace(/\\.([^.[]+)/g, '[$1]') : givenKey;\n\n // The regex chunks\n\n var brackets = /(\\[[^[\\]]*])/;\n var child = /(\\[[^[\\]]*])/g;\n\n // Get the parent\n\n var segment = brackets.exec(key);\n var parent = segment ? key.slice(0, segment.index) : key;\n\n // Stash the parent if it exists\n\n var keys = [];\n if (parent) {\n // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties\n if (!options.plainObjects && has.call(Object.prototype, parent)) {\n if (!options.allowPrototypes) {\n return;\n }\n }\n\n keys.push(parent);\n }\n\n // Loop through children appending to the array until we hit depth\n\n var i = 0;\n while ((segment = child.exec(key)) !== null && i < options.depth) {\n i += 1;\n if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {\n if (!options.allowPrototypes) {\n return;\n }\n }\n keys.push(segment[1]);\n }\n\n // If there's a remainder, just add whatever is left\n\n if (segment) {\n keys.push('[' + key.slice(segment.index) + ']');\n }\n\n return parseObject(keys, val, options);\n};\n\nvar normalizeParseOptions = function normalizeParseOptions(opts) {\n if (!opts) {\n return defaults;\n }\n\n if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') {\n throw new TypeError('Decoder has to be a function.');\n }\n\n if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {\n throw new Error('The charset option must be either utf-8, iso-8859-1, or undefined');\n }\n var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset;\n\n return {\n allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,\n allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes,\n arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit,\n charset: charset,\n charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,\n comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma,\n decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder,\n delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter,\n depth: typeof opts.depth === 'number' ? opts.depth : defaults.depth,\n ignoreQueryPrefix: opts.ignoreQueryPrefix === true,\n interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities,\n parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit,\n parseArrays: opts.parseArrays !== false,\n plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects,\n strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling\n };\n};\n\nmodule.exports = function (str, opts) {\n var options = normalizeParseOptions(opts);\n\n if (str === '' || str === null || typeof str === 'undefined') {\n return options.plainObjects ? Object.create(null) : {};\n }\n\n var tempObj = typeof str === 'string' ? parseValues(str, options) : str;\n var obj = options.plainObjects ? Object.create(null) : {};\n\n // Iterate over the keys and setup the new object\n\n var keys = Object.keys(tempObj);\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n var newObj = parseKeys(key, tempObj[key], options);\n obj = utils.merge(obj, newObj, options);\n }\n\n return utils.compact(obj);\n};\n","'use strict';\n\nvar stringify = require('./stringify');\nvar parse = require('./parse');\nvar formats = require('./formats');\n\nmodule.exports = {\n formats: formats,\n parse: parse,\n stringify: stringify\n};\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * A collection of HttpHeaders that can be sent with a HTTP request.\n */\nfunction getHeaderKey(headerName: string) {\n return headerName.toLowerCase();\n}\n\n/**\n * An individual header within a HttpHeaders collection.\n */\nexport interface HttpHeader {\n /**\n * The name of the header.\n */\n name: string;\n\n /**\n * The value of the header.\n */\n value: string;\n}\n\n/**\n * A HttpHeaders collection represented as a simple JSON object.\n */\nexport type RawHttpHeaders = { [headerName: string]: string };\n\n/**\n * A collection of HTTP header key/value pairs.\n */\nexport class HttpHeaders {\n private readonly _headersMap: { [headerKey: string]: HttpHeader };\n\n constructor(rawHeaders?: RawHttpHeaders) {\n this._headersMap = {};\n if (rawHeaders) {\n for (const headerName in rawHeaders) {\n this.set(headerName, rawHeaders[headerName]);\n }\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 public set(headerName: string, headerValue: string | number): void {\n this._headersMap[getHeaderKey(headerName)] = { name: headerName, value: headerValue.toString() };\n }\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 public get(headerName: string): string | undefined {\n const header: HttpHeader = this._headersMap[getHeaderKey(headerName)];\n return !header ? undefined : header.value;\n }\n\n /**\n * Get whether or not this header collection contains a header entry for the provided header name.\n */\n public contains(headerName: string): boolean {\n return !!this._headersMap[getHeaderKey(headerName)];\n }\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 public remove(headerName: string): boolean {\n const result: boolean = this.contains(headerName);\n delete this._headersMap[getHeaderKey(headerName)];\n return result;\n }\n\n /**\n * Get the headers that are contained this collection as an object.\n */\n public rawHeaders(): RawHttpHeaders {\n const result: RawHttpHeaders = {};\n for (const headerKey in this._headersMap) {\n const header: HttpHeader = this._headersMap[headerKey];\n result[header.name.toLowerCase()] = header.value;\n }\n return result;\n }\n\n /**\n * Get the headers that are contained in this collection as an array.\n */\n public headersArray(): HttpHeader[] {\n const headers: HttpHeader[] = [];\n for (const headerKey in this._headersMap) {\n headers.push(this._headersMap[headerKey]);\n }\n return headers;\n }\n\n /**\n * Get the header names that are contained in this collection.\n */\n public headerNames(): string[] {\n const headerNames: string[] = [];\n const headers: HttpHeader[] = this.headersArray();\n for (let i = 0; i < headers.length; ++i) {\n headerNames.push(headers[i].name);\n }\n return headerNames;\n }\n\n /**\n * Get the header names that are contained in this collection.\n */\n public headerValues(): string[] {\n const headerValues: string[] = [];\n const headers: HttpHeader[] = this.headersArray();\n for (let i = 0; i < headers.length; ++i) {\n headerValues.push(headers[i].value);\n }\n return headerValues;\n }\n\n /**\n * Get the JSON object representation of this HTTP header collection.\n */\n public toJson(): RawHttpHeaders {\n return this.rawHeaders();\n }\n\n /**\n * Get the string representation of this HTTP header collection.\n */\n public toString(): string {\n return JSON.stringify(this.toJson());\n }\n\n /**\n * Create a deep clone/copy of this HttpHeaders collection.\n */\n public clone(): HttpHeaders {\n return new HttpHeaders(this.rawHeaders());\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * Encodes a string in base64 format.\n * @param value the string to encode\n */\nexport function encodeString(value: string): string {\n return btoa(value);\n}\n\n/**\n * Encodes a byte array in base64 format.\n * @param value the Uint8Aray to encode\n */\nexport function encodeByteArray(value: Uint8Array): string {\n let str = \"\";\n for (let i = 0; i < value.length; i++) {\n str += String.fromCharCode(value[i]);\n }\n return btoa(str);\n}\n\n/**\n * Decodes a base64 string into a byte array.\n * @param value the base64 string to decode\n */\nexport function decodeString(value: string): Uint8Array {\n const byteString = atob(value);\n const arr = new Uint8Array(byteString.length);\n for (let i = 0; i < byteString.length; i++) {\n arr[i] = byteString.charCodeAt(i);\n }\n return arr;\n}\n","/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nvar byteToHex = [];\nfor (var i = 0; i < 256; ++i) {\n byteToHex[i] = (i + 0x100).toString(16).substr(1);\n}\n\nfunction bytesToUuid(buf, offset) {\n var i = offset || 0;\n var bth = byteToHex;\n // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4\n return ([bth[buf[i++]], bth[buf[i++]], \n\tbth[buf[i++]], bth[buf[i++]], '-',\n\tbth[buf[i++]], bth[buf[i++]], '-',\n\tbth[buf[i++]], bth[buf[i++]], '-',\n\tbth[buf[i++]], bth[buf[i++]], '-',\n\tbth[buf[i++]], bth[buf[i++]],\n\tbth[buf[i++]], bth[buf[i++]],\n\tbth[buf[i++]], bth[buf[i++]]]).join('');\n}\n\nmodule.exports = bytesToUuid;\n","// Unique ID creation requires a high quality random # generator. In the\n// browser this is a little complicated due to unknown quality of Math.random()\n// and inconsistent support for the `crypto` API. We do the best we can via\n// feature-detection\n\n// getRandomValues needs to be invoked in a context where \"this\" is a Crypto\n// implementation. Also, find the complete implementation of crypto on IE11.\nvar getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||\n (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));\n\nif (getRandomValues) {\n // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto\n var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef\n\n module.exports = function whatwgRNG() {\n getRandomValues(rnds8);\n return rnds8;\n };\n} else {\n // Math.random()-based (RNG)\n //\n // If all else fails, use Math.random(). It's fast, but is of unspecified\n // quality.\n var rnds = new Array(16);\n\n module.exports = function mathRNG() {\n for (var i = 0, r; i < 16; i++) {\n if ((i & 0x03) === 0) r = Math.random() * 0x100000000;\n rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;\n }\n\n return rnds;\n };\n}\n","var rng = require('./lib/rng');\nvar bytesToUuid = require('./lib/bytesToUuid');\n\nfunction v4(options, buf, offset) {\n var i = buf && offset || 0;\n\n if (typeof(options) == 'string') {\n buf = options === 'binary' ? new Array(16) : null;\n options = null;\n }\n options = options || {};\n\n var rnds = options.random || (options.rng || rng)();\n\n // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n\n // Copy bytes to buffer, if provided\n if (buf) {\n for (var ii = 0; ii < 16; ++ii) {\n buf[i + ii] = rnds[ii];\n }\n }\n\n return buf || bytesToUuid(rnds);\n}\n\nmodule.exports = v4;\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nexport const Constants = {\n /**\n * The core-http version\n * @const\n * @type {string}\n */\n coreHttpVersion: \"1.0.0-preview.1\",\n\n /**\n * Specifies HTTP.\n *\n * @const\n * @type {string}\n */\n HTTP: \"http:\",\n\n /**\n * Specifies HTTPS.\n *\n * @const\n * @type {string}\n */\n HTTPS: \"https:\",\n\n /**\n * Specifies HTTP Proxy.\n *\n * @const\n * @type {string}\n */\n HTTP_PROXY: \"HTTP_PROXY\",\n\n /**\n * Specifies HTTPS Proxy.\n *\n * @const\n * @type {string}\n */\n HTTPS_PROXY: \"HTTPS_PROXY\",\n\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\n StatusCodes: {\n TooManyRequests: 429\n }\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\n AUTHORIZATION_SCHEME: \"Bearer\",\n\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 /**\n * The UserAgent header.\n *\n * @const\n * @type {string}\n */\n USER_AGENT: \"User-Agent\"\n }\n};\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport uuidv4 from \"uuid/v4\";\nimport { HttpOperationResponse } from \"../httpOperationResponse\";\nimport { RestError } from \"../restError\";\nimport { WebResource } from \"../webResource\";\nimport { Constants } from \"./constants\";\n\n/**\n * A constant that indicates whether the environment is node.js or browser based.\n */\nexport const isNode = (typeof process !== \"undefined\") && !!process.version && !!process.versions && !!process.versions.node;\n\n/**\n * Checks if a parsed URL is HTTPS\n *\n * @param {object} urlToCheck The url to check\n * @return {boolean} True if the URL is HTTPS; false otherwise.\n */\nexport function urlIsHTTPS(urlToCheck: { protocol: string }): boolean {\n return urlToCheck.protocol.toLowerCase() === Constants.HTTPS;\n}\n\n/**\n * Encodes an URI.\n *\n * @param {string} uri The URI to be encoded.\n * @return {string} The encoded URI.\n */\nexport function encodeUri(uri: string): string {\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/**\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 */\nexport function stripResponse(response: HttpOperationResponse): any {\n const strippedResponse: any = {};\n strippedResponse.body = response.bodyAsText;\n strippedResponse.headers = response.headers;\n strippedResponse.status = response.status;\n return strippedResponse;\n}\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 */\nexport function stripRequest(request: WebResource): WebResource {\n const strippedRequest = request.clone();\n if (strippedRequest.headers) {\n strippedRequest.headers.remove(\"authorization\");\n }\n return strippedRequest;\n}\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 */\nexport function isValidUuid(uuid: string): boolean {\n const 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/**\n * Provides an array of values of an object. For example\n * for a given object { \"a\": \"foo\", \"b\": \"bar\" }, the method returns [\"foo\", \"bar\"].\n *\n * @param {object} obj An object whose properties need to be enumerated so that it\"s values can be provided as an array\n *\n * @return {any[]} An array of values of the given object.\n */\nexport function objectValues(obj: { [key: string]: any; }): any[] {\n const result: any[] = [];\n if (obj && obj instanceof Object) {\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n result.push((<any>obj)[key]);\n }\n }\n } else {\n throw new Error(`The provided object ${JSON.stringify(obj, undefined, 2)} is not a valid object that can be ` +\n `enumerated to provide its values as an array.`);\n }\n return result;\n}\n\n/**\n * Generated UUID\n *\n * @return {string} RFC4122 v4 UUID.\n */\nexport function generateUuid(): string {\n return uuidv4();\n}\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 */\nexport function executePromisesSequentially(promiseFactories: Array<any>, kickstart: any) {\n let result = Promise.resolve(kickstart);\n promiseFactories.forEach((promiseFactory) => {\n result = result.then(promiseFactory);\n });\n return result;\n}\n\n/**\n * Merges source object into the target object\n * @param {object} source The object that needs to be merged\n *\n * @param {object} target The object to be merged into\n *\n * @returns {object} Returns the merged target object.\n */\nexport function mergeObjects(source: { [key: string]: any; }, target: { [key: string]: any; }) {\n Object.keys(source).forEach((key) => {\n target[key] = source[key];\n });\n return target;\n}\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<T>} Resolved promise\n */\nexport function delay<T>(t: number, value?: T): Promise<T> {\n return new Promise((resolve) => setTimeout(() => resolve(value), t));\n}\n\n/**\n * Service callback that is returned for REST requests initiated by the service client.\n */\nexport interface ServiceCallback<TResult> {\n /**\n * A method that will be invoked as a callback to a service function.\n * @param {Error | RestError | null} err The error occurred if any, while executing the request; otherwise null.\n * @param {TResult} [result] The deserialized response body if an error did not occur.\n * @param {WebResource} [request] The raw/actual request sent to the server if an error did not occur.\n * @param {HttpOperationResponse} [response] The raw/actual response from the server if an error did not occur.\n */\n (err: Error | RestError | null, result?: TResult, request?: WebResource, response?: HttpOperationResponse): void;\n}\n\n/**\n * Converts a Promise to a callback.\n * @param {Promise<any>} 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 */\nexport function promiseToCallback(promise: Promise<any>): Function {\n if (typeof promise.then !== \"function\") {\n throw new Error(\"The provided input is not a Promise.\");\n }\n return (cb: Function): void => {\n promise.then((data: any) => {\n cb(undefined, data);\n }, (err: Error) => {\n cb(err);\n });\n };\n}\n\n/**\n * Converts a Promise to a service callback.\n * @param {Promise<HttpOperationResponse>} promise - The Promise of HttpOperationResponse to be converted to a service callback\n * @returns {Function} A function that takes the service callback (cb: ServiceCallback<T>): void\n */\nexport function promiseToServiceCallback<T>(promise: Promise<HttpOperationResponse>): Function {\n if (typeof promise.then !== \"function\") {\n throw new Error(\"The provided input is not a Promise.\");\n }\n return (cb: ServiceCallback<T>): void => {\n promise.then((data: HttpOperationResponse) => {\n process.nextTick(cb, undefined, data.parsedBody as T, data.request, data);\n }, (err: Error) => {\n process.nextTick(cb, err);\n });\n };\n}\n\nexport function prepareXMLRootList(obj: any, elementName: string) {\n if (!Array.isArray(obj)) {\n obj = [obj];\n }\n return { [elementName]: obj };\n}\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<object>} sourceCtors An array of source objects from which the properties need to be taken.\n */\nexport function applyMixins(targetCtor: any, sourceCtors: any[]): void {\n sourceCtors.forEach(sourceCtors => {\n Object.getOwnPropertyNames(sourceCtors.prototype).forEach(name => {\n targetCtor.prototype[name] = sourceCtors.prototype[name];\n });\n });\n}\n\nconst 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/**\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 */\nexport function isDuration(value: string): boolean {\n return validateISODuration.test(value);\n}\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 */\nexport function replaceAll(value: string | undefined, searchValue: string, replaceValue: string): string | undefined {\n return !value || !searchValue ? value : value.split(searchValue).join(replaceValue || \"\");\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport * as base64 from \"./util/base64\";\nimport * as utils from \"./util/utils\";\n\nexport class Serializer {\n constructor(public readonly modelMappers: { [key: string]: any } = {}, public readonly isXML?: boolean) { }\n\n validateConstraints(mapper: Mapper, value: any, objectName: string): void {\n const failValidation = (constraintName: keyof MapperConstraints, constraintValue: any) => {\n throw new Error(`\"${objectName}\" with value \"${value}\" should satisfy the constraint \"${constraintName}\": ${constraintValue}.`);\n };\n if (mapper.constraints && (value != undefined)) {\n const {\n ExclusiveMaximum,\n ExclusiveMinimum,\n InclusiveMaximum,\n InclusiveMinimum,\n MaxItems,\n MaxLength,\n MinItems,\n MinLength,\n MultipleOf,\n Pattern,\n UniqueItems\n } = mapper.constraints;\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((item: any, i: number, ar: Array<any>) => ar.indexOf(item) !== i)) {\n failValidation(\"UniqueItems\", UniqueItems);\n }\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 serialize(mapper: Mapper, object: any, objectName?: string): any {\n let payload: any = {};\n const mapperType = mapper.type.name as string;\n if (!objectName) {\n objectName = mapper.serializedName!;\n }\n if (mapperType.match(/^Sequence$/ig) !== null) {\n payload = [];\n }\n\n if (object == undefined && (mapper.defaultValue != undefined || mapper.isConstant)) {\n object = mapper.defaultValue;\n }\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\n const { required, nullable } = mapper;\n\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\n if (object == undefined) {\n payload = object;\n } else {\n // Validate Constraints if any\n this.validateConstraints(mapper, object, objectName);\n if (mapperType.match(/^any$/ig) !== null) {\n payload = object;\n } else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/ig) !== null) {\n payload = serializeBasicTypes(mapperType, objectName, object);\n } else if (mapperType.match(/^Enum$/ig) !== null) {\n const enumMapper: EnumMapper = mapper as EnumMapper;\n payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object);\n } else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/ig) !== null) {\n payload = serializeDateTypes(mapperType, object, objectName);\n } else if (mapperType.match(/^ByteArray$/ig) !== null) {\n payload = serializeByteArrayType(objectName, object);\n } else if (mapperType.match(/^Base64Url$/ig) !== null) {\n payload = serializeBase64UrlType(objectName, object);\n } else if (mapperType.match(/^Sequence$/ig) !== null) {\n payload = serializeSequenceType(this, mapper as SequenceMapper, object, objectName);\n } else if (mapperType.match(/^Dictionary$/ig) !== null) {\n payload = serializeDictionaryType(this, mapper as DictionaryMapper, object, objectName);\n } else if (mapperType.match(/^Composite$/ig) !== null) {\n payload = serializeCompositeType(this, mapper as CompositeMapper, object, objectName);\n }\n }\n return payload;\n }\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 deserialize(mapper: Mapper, responseBody: any, objectName: string): any {\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\n let payload: any;\n const mapperType = mapper.type.name;\n if (!objectName) {\n objectName = mapper.serializedName!;\n }\n\n if (mapperType.match(/^Composite$/ig) !== null) {\n payload = deserializeCompositeType(this, mapper as CompositeMapper, responseBody, objectName);\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\n if (mapperType.match(/^Number$/ig) !== null) {\n payload = parseFloat(responseBody);\n if (isNaN(payload)) {\n payload = responseBody;\n }\n } else if (mapperType.match(/^Boolean$/ig) !== null) {\n if (responseBody === \"true\") {\n payload = true;\n } else if (responseBody === \"false\") {\n payload = false;\n } else {\n payload = responseBody;\n }\n } else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/ig) !== null) {\n payload = responseBody;\n } else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/ig) !== null) {\n payload = new Date(responseBody);\n } else if (mapperType.match(/^UnixTime$/ig) !== null) {\n payload = unixTimeToDate(responseBody);\n } else if (mapperType.match(/^ByteArray$/ig) !== null) {\n payload = base64.decodeString(responseBody);\n } else if (mapperType.match(/^Base64Url$/ig) !== null) {\n payload = base64UrlToByteArray(responseBody);\n } else if (mapperType.match(/^Sequence$/ig) !== null) {\n payload = deserializeSequenceType(this, mapper as SequenceMapper, responseBody, objectName);\n } else if (mapperType.match(/^Dictionary$/ig) !== null) {\n payload = deserializeDictionaryType(this, mapper as DictionaryMapper, responseBody, objectName);\n }\n }\n\n if (mapper.isConstant) {\n payload = mapper.defaultValue;\n }\n\n return payload;\n }\n}\n\nfunction trimEnd(str: string, ch: string) {\n let len = str.length;\n while ((len - 1) >= 0 && str[len - 1] === ch) {\n --len;\n }\n return str.substr(0, len);\n}\n\nfunction bufferToBase64Url(buffer: any): string | undefined {\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 const str = base64.encodeByteArray(buffer);\n // Base64 to Base64Url.\n return trimEnd(str, \"=\").replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n}\n\nfunction base64UrlToByteArray(str: string): Uint8Array | undefined {\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 base64.decodeString(str);\n}\n\nfunction splitSerializeName(prop: string | undefined): string[] {\n const classes: string[] = [];\n let partialclass = \"\";\n if (prop) {\n const subwords = prop.split(\".\");\n\n for (const item of subwords) {\n if (item.charAt(item.length - 1) === \"\\\\\") {\n partialclass += item.substr(0, item.length - 1) + \".\";\n } else {\n partialclass += item;\n classes.push(partialclass);\n partialclass = \"\";\n }\n }\n }\n\n return classes;\n}\n\nfunction dateToUnixTime(d: string | Date): number | undefined {\n if (!d) {\n return undefined;\n }\n\n if (typeof d.valueOf() === \"string\") {\n d = new Date(d as string);\n }\n return Math.floor((d as Date).getTime() / 1000);\n}\n\nfunction unixTimeToDate(n: number): Date | undefined {\n if (!n) {\n return undefined;\n }\n return new Date(n * 1000);\n}\n\nfunction serializeBasicTypes(typeName: string, objectName: string, value: any): any {\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 } 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 } else if (typeName.match(/^Uuid$/ig) !== null) {\n if (!(typeof value.valueOf() === \"string\" && utils.isValidUuid(value))) {\n throw new Error(`${objectName} with value \"${value}\" must be of type string and a valid uuid.`);\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 } else if (typeName.match(/^Stream$/ig) !== null) {\n const 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}\n\nfunction serializeEnumType(objectName: string, allowedValues: Array<any>, value: any): any {\n if (!allowedValues) {\n throw new Error(`Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`);\n }\n const isPresent = allowedValues.some((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}\n\nfunction serializeByteArrayType(objectName: string, value: any): any {\n if (value != undefined) {\n if (!(value instanceof Uint8Array)) {\n throw new Error(`${objectName} must be of type Uint8Array.`);\n }\n value = base64.encodeByteArray(value);\n }\n return value;\n}\n\nfunction serializeBase64UrlType(objectName: string, value: any): any {\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}\n\nfunction serializeDateTypes(typeName: string, value: any, objectName: string) {\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 } 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 } 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 } 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 } else if (typeName.match(/^TimeSpan$/ig) !== null) {\n if (!utils.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}\n\nfunction serializeSequenceType(serializer: Serializer, mapper: SequenceMapper, object: any, objectName: string) {\n if (!Array.isArray(object)) {\n throw new Error(`${objectName} must be of type Array.`);\n }\n const 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 const tempArray = [];\n for (let i = 0; i < object.length; i++) {\n tempArray[i] = serializer.serialize(elementType, object[i], objectName);\n }\n return tempArray;\n}\n\nfunction serializeDictionaryType(serializer: Serializer, mapper: DictionaryMapper, object: any, objectName: string) {\n if (typeof object !== \"object\") {\n throw new Error(`${objectName} must be of type object.`);\n }\n const 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 const tempDictionary: { [key: string]: any } = {};\n for (const key of Object.keys(object)) {\n tempDictionary[key] = serializer.serialize(valueType, object[key], objectName + \".\" + key);\n }\n return tempDictionary;\n}\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: Serializer, mapper: CompositeMapper, objectName: string): { [propertyName: string]: Mapper } {\n let modelProps = mapper.type.modelProperties;\n if (!modelProps) {\n const 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\n const 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\n return modelProps;\n}\n\nfunction serializeCompositeType(serializer: Serializer, mapper: CompositeMapper, object: any, objectName: string) {\n if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {\n mapper = getPolymorphicMapper(serializer, mapper, object, \"clientName\");\n }\n\n if (object != undefined) {\n const payload: any = {};\n const modelProps = resolveModelProperties(serializer, mapper, objectName);\n for (const key of Object.keys(modelProps)) {\n const propertyMapper = modelProps[key];\n if (propertyMapper.readOnly) {\n continue;\n }\n\n let propName: string | undefined;\n let parentObject: any = payload;\n if (serializer.isXML) {\n if (propertyMapper.xmlIsWrapped) {\n propName = propertyMapper.xmlName;\n } else {\n propName = propertyMapper.xmlElementName || propertyMapper.xmlName;\n }\n } else {\n const paths = splitSerializeName(propertyMapper.serializedName!);\n propName = paths.pop();\n\n for (const pathName of paths) {\n const childObject = parentObject[pathName];\n if ((childObject == undefined) && (object[key] != undefined)) {\n parentObject[pathName] = {};\n }\n parentObject = parentObject[pathName];\n }\n }\n\n if (parentObject != undefined) {\n const propertyObjectName = propertyMapper.serializedName !== \"\"\n ? objectName + \".\" + propertyMapper.serializedName\n : objectName;\n\n let toSerialize = object[key];\n const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);\n if (polymorphicDiscriminator && polymorphicDiscriminator.clientName === key && toSerialize == undefined) {\n toSerialize = mapper.serializedName;\n }\n\n const 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 } else if (propertyMapper.xmlIsWrapped) {\n parentObject[propName] = { [propertyMapper.xmlElementName!]: serializedValue };\n } else {\n parentObject[propName] = serializedValue;\n }\n }\n }\n }\n\n const additionalPropertiesMapper = mapper.type.additionalProperties;\n if (additionalPropertiesMapper) {\n const propNames = Object.keys(modelProps);\n for (const clientPropName in object) {\n const isAdditionalProperty = propNames.every(pn => pn !== clientPropName);\n if (isAdditionalProperty) {\n payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '[\"' + clientPropName + '\"]');\n }\n }\n }\n\n return payload;\n }\n return object;\n}\n\nfunction isSpecialXmlProperty(propertyName: string): boolean {\n return [\"$\", \"_\"].includes(propertyName);\n}\n\nfunction deserializeCompositeType(serializer: Serializer, mapper: CompositeMapper, responseBody: any, objectName: string): any {\n if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {\n mapper = getPolymorphicMapper(serializer, mapper, responseBody, \"serializedName\");\n }\n\n const modelProps = resolveModelProperties(serializer, mapper, objectName);\n let instance: { [key: string]: any } = {};\n const handledPropertyNames: string[] = [];\n\n for (const key of Object.keys(modelProps)) {\n const propertyMapper = modelProps[key];\n const paths = splitSerializeName(modelProps[key].serializedName!);\n handledPropertyNames.push(paths[0]);\n const { serializedName, xmlName, xmlElementName } = propertyMapper;\n let propertyObjectName = objectName;\n if (serializedName !== \"\" && serializedName !== undefined) {\n propertyObjectName = objectName + \".\" + serializedName;\n }\n\n const headerCollectionPrefix = (propertyMapper as DictionaryMapper).headerCollectionPrefix;\n if (headerCollectionPrefix) {\n const dictionary: any = {};\n for (const headerKey of Object.keys(responseBody)) {\n if (headerKey.startsWith(headerCollectionPrefix)) {\n dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize((propertyMapper as DictionaryMapper).type.value, responseBody[headerKey], propertyObjectName);\n }\n\n handledPropertyNames.push(headerKey);\n }\n instance[key] = dictionary;\n } else if (serializer.isXML) {\n if (propertyMapper.xmlIsAttribute && responseBody.$) {\n instance[key] = serializer.deserialize(propertyMapper, responseBody.$[xmlName!], propertyObjectName);\n } else {\n const propertyName = xmlElementName || xmlName || serializedName;\n let unwrappedProperty = responseBody[propertyName!];\n if (propertyMapper.xmlIsWrapped) {\n unwrappedProperty = responseBody[xmlName!];\n unwrappedProperty = unwrappedProperty && unwrappedProperty[xmlElementName!];\n\n const isEmptyWrappedList = unwrappedProperty === undefined;\n if (isEmptyWrappedList) {\n unwrappedProperty = [];\n }\n }\n instance[key] = serializer.deserialize(propertyMapper, unwrappedProperty, propertyObjectName);\n }\n } else {\n // deserialize the property if it is present in the provided responseBody instance\n let propertyInstance;\n let res = responseBody;\n // traversing the object step by step.\n for (const item of paths) {\n if (!res) break;\n res = res[item];\n }\n propertyInstance = res;\n const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator;\n if (polymorphicDiscriminator && propertyMapper.serializedName === polymorphicDiscriminator.serializedName && propertyInstance == undefined) {\n propertyInstance = mapper.serializedName;\n }\n\n let serializedValue;\n // paging\n if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === \"\") {\n propertyInstance = responseBody[key];\n instance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName);\n } else if (propertyInstance !== undefined) {\n serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName);\n instance[key] = serializedValue;\n }\n }\n }\n\n const additionalPropertiesMapper = mapper.type.additionalProperties;\n if (additionalPropertiesMapper) {\n const isAdditionalProperty = (responsePropName: string) => {\n for (const clientPropName in modelProps) {\n const paths = splitSerializeName(modelProps[clientPropName].serializedName);\n if (paths[0] === responsePropName) {\n return false;\n }\n }\n return true;\n };\n\n for (const responsePropName in responseBody) {\n if (isAdditionalProperty(responsePropName)) {\n instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '[\"' + responsePropName + '\"]');\n }\n }\n } else if (responseBody) {\n for (const key of Object.keys(responseBody)) {\n if (instance[key] === undefined && !handledPropertyNames.includes(key) && !isSpecialXmlProperty(key)) {\n instance[key] = responseBody[key];\n }\n }\n }\n\n return instance;\n}\n\nfunction deserializeDictionaryType(serializer: Serializer, mapper: DictionaryMapper, responseBody: any, objectName: string): any {\n /*jshint validthis: true */\n const 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 const tempDictionary: { [key: string]: any } = {};\n for (const key of Object.keys(responseBody)) {\n tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName);\n }\n return tempDictionary;\n }\n return responseBody;\n}\n\nfunction deserializeSequenceType(serializer: Serializer, mapper: SequenceMapper, responseBody: any, objectName: string): any {\n /*jshint validthis: true */\n const 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\n const tempArray = [];\n for (let 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}\n\nfunction getPolymorphicMapper(serializer: Serializer, mapper: CompositeMapper, object: any, polymorphicPropertyName: \"clientName\" | \"serializedName\"): CompositeMapper {\n const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);\n if (polymorphicDiscriminator) {\n const discriminatorName = polymorphicDiscriminator[polymorphicPropertyName];\n if (discriminatorName != undefined) {\n const discriminatorValue = object[discriminatorName];\n if (discriminatorValue != undefined) {\n const typeName = mapper.type.uberParent || mapper.type.className;\n const indexDiscriminator = discriminatorValue === typeName\n ? discriminatorValue\n : typeName + \".\" + discriminatorValue;\n const polymorphicMapper = serializer.modelMappers.discriminators[indexDiscriminator];\n if (polymorphicMapper) {\n mapper = polymorphicMapper;\n }\n }\n }\n }\n return mapper;\n}\n\nfunction getPolymorphicDiscriminatorRecursively(serializer: Serializer, mapper: CompositeMapper): PolymorphicDiscriminator | undefined {\n return mapper.type.polymorphicDiscriminator\n || getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent)\n || getPolymorphicDiscriminatorSafely(serializer, mapper.type.className);\n}\n\nfunction getPolymorphicDiscriminatorSafely(serializer: Serializer, typeName?: string) {\n return (typeName && serializer.modelMappers[typeName] && serializer.modelMappers[typeName].type.polymorphicDiscriminator);\n}\n\nexport interface MapperConstraints {\n InclusiveMaximum?: number;\n ExclusiveMaximum?: number;\n InclusiveMinimum?: number;\n ExclusiveMinimum?: number;\n MaxLength?: number;\n MinLength?: number;\n Pattern?: RegExp;\n MaxItems?: number;\n MinItems?: number;\n UniqueItems?: true;\n MultipleOf?: number;\n}\n\nexport type MapperType = SimpleMapperType | CompositeMapperType | SequenceMapperType | DictionaryMapperType | EnumMapperType;\n\nexport interface SimpleMapperType {\n name: \"Base64Url\"\n | \"Boolean\"\n | \"ByteArray\"\n | \"Date\"\n | \"DateTime\"\n | \"DateTimeRfc1123\"\n | \"Object\"\n | \"Stream\"\n | \"String\"\n | \"TimeSpan\"\n | \"UnixTime\"\n | \"Uuid\"\n | \"Number\"\n | \"any\";\n}\n\nexport interface CompositeMapperType {\n name: \"Composite\";\n\n // Only one of the two below properties should be present.\n // Use className to reference another type definition,\n // and use modelProperties/additionalProperties when the reference to the other type has been resolved.\n className?: string;\n\n modelProperties?: { [propertyName: string]: Mapper };\n additionalProperties?: Mapper;\n\n uberParent?: string;\n polymorphicDiscriminator?: PolymorphicDiscriminator;\n}\n\nexport interface SequenceMapperType {\n name: \"Sequence\";\n element: Mapper;\n}\n\nexport interface DictionaryMapperType {\n name: \"Dictionary\";\n value: Mapper;\n}\n\nexport interface EnumMapperType {\n name: \"Enum\";\n allowedValues: any[];\n}\n\nexport interface BaseMapper {\n xmlName?: string;\n xmlIsAttribute?: boolean;\n xmlElementName?: string;\n xmlIsWrapped?: boolean;\n readOnly?: boolean;\n isConstant?: boolean;\n required?: boolean;\n nullable?: boolean;\n serializedName?: string;\n type: MapperType;\n defaultValue?: any;\n constraints?: MapperConstraints;\n}\n\nexport type Mapper = BaseMapper | CompositeMapper | SequenceMapper | DictionaryMapper | EnumMapper;\n\nexport interface PolymorphicDiscriminator {\n serializedName: string;\n clientName: string;\n [key: string]: string;\n}\n\nexport interface CompositeMapper extends BaseMapper {\n type: CompositeMapperType;\n}\n\nexport interface SequenceMapper extends BaseMapper {\n type: SequenceMapperType;\n}\n\nexport interface DictionaryMapper extends BaseMapper {\n type: DictionaryMapperType;\n headerCollectionPrefix?: string;\n}\n\nexport interface EnumMapper extends BaseMapper {\n type: EnumMapperType;\n}\n\nexport interface UrlParameterValue {\n value: string;\n skipUrlEncoding: boolean;\n}\n\n// TODO: why is this here?\nexport function serializeObject(toSerialize: any): any {\n if (toSerialize == undefined) return undefined;\n if (toSerialize instanceof Uint8Array) {\n toSerialize = base64.encodeByteArray(toSerialize);\n return toSerialize;\n }\n else if (toSerialize instanceof Date) {\n return toSerialize.toISOString();\n }\n else if (Array.isArray(toSerialize)) {\n const array = [];\n for (let i = 0; i < toSerialize.length; i++) {\n array.push(serializeObject(toSerialize[i]));\n }\n return array;\n } else if (typeof toSerialize === \"object\") {\n const dictionary: { [key: string]: any } = {};\n for (const property in toSerialize) {\n dictionary[property] = serializeObject(toSerialize[property]);\n }\n return dictionary;\n }\n return toSerialize;\n}\n\n/**\n * Utility function to create a K:V from a list of strings\n */\nfunction strEnum<T extends string>(o: Array<T>): { [K in T]: K } {\n const result: any = {};\n for (const key of o) {\n result[key] = key;\n }\n return result;\n}\n\nexport const 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","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { HttpHeaders } from \"./httpHeaders\";\nimport { OperationSpec } from \"./operationSpec\";\nimport { Mapper, Serializer } from \"./serializer\";\nimport { generateUuid } from \"./util/utils\";\nimport { HttpOperationResponse } from \"./httpOperationResponse\";\nimport { OperationResponse } from \"./operationResponse\";\nimport { ProxySettings } from \"./serviceClient\";\n\nexport type HttpMethods = \"GET\" | \"PUT\" | \"POST\" | \"DELETE\" | \"PATCH\" | \"HEAD\" | \"OPTIONS\" | \"TRACE\";\nexport type HttpRequestBody = Blob | string | ArrayBuffer | ArrayBufferView | (() => NodeJS.ReadableStream);\n\n/**\n * Fired in response to upload or download progress.\n */\nexport type TransferProgressEvent = {\n /**\n * The number of bytes loaded so far.\n */\n loadedBytes: number\n};\n\n/**\n * Allows the request to be aborted upon firing of the \"abort\" event.\n * Compatible with the browser built-in AbortSignal and common polyfills.\n */\nexport interface AbortSignalLike {\n readonly aborted: boolean;\n addEventListener(type: \"abort\", listener: (this: AbortSignalLike, ev: any) => any, options?: any): void;\n removeEventListener(type: \"abort\", listener: (this: AbortSignalLike, ev: any) => any, options?: any): void;\n}\n\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 */\nexport class WebResource {\n url: string;\n method: HttpMethods;\n body?: any;\n headers: HttpHeaders;\n /**\n * Whether or not the body of the HttpOperationResponse should be treated as a stream.\n */\n streamResponseBody?: boolean;\n /**\n * Whether or not the HttpOperationResponse should be deserialized. If this is undefined, then the\n * HttpOperationResponse should be deserialized.\n */\n shouldDeserialize?: boolean | ((response: HttpOperationResponse) => boolean);\n /**\n * A function that returns the proper OperationResponse for the given OperationSpec and\n * HttpOperationResponse combination. If this is undefined, then a simple status code lookup will\n * be used.\n */\n operationResponseGetter?: (operationSpec: OperationSpec, response: HttpOperationResponse) => (undefined | OperationResponse);\n formData?: any;\n query?: { [key: string]: any; };\n operationSpec?: OperationSpec;\n withCredentials: boolean;\n timeout: number;\n proxySettings?: ProxySettings;\n\n abortSignal?: AbortSignalLike;\n\n /** Callback which fires upon upload progress. */\n onUploadProgress?: (progress: TransferProgressEvent) => void;\n\n /** Callback which fires upon download progress. */\n onDownloadProgress?: (progress: TransferProgressEvent) => void;\n\n constructor(\n url?: string,\n method?: HttpMethods,\n body?: any,\n query?: { [key: string]: any; },\n headers?: { [key: string]: any; } | HttpHeaders,\n streamResponseBody?: boolean,\n withCredentials?: boolean,\n abortSignal?: AbortSignalLike,\n timeout?: number,\n onUploadProgress?: (progress: TransferProgressEvent) => void,\n onDownloadProgress?: (progress: TransferProgressEvent) => void,\n proxySettings?: ProxySettings) {\n\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 }\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 validateRequestProperties(): void {\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 /**\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 prepare(options: RequestPrepareOptions): WebResource {\n if (!options) {\n throw new Error(\"options object is required\");\n }\n\n if (options.method == undefined || typeof options.method.valueOf() !== \"string\") {\n throw new Error(\"options.method must be a string.\");\n }\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\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\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\n // set the method\n if (options.method) {\n const 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() as HttpMethods);\n\n // construct the url if path template is provided\n if (options.pathTemplate) {\n const { pathTemplate, pathParameters } = options;\n if (typeof pathTemplate !== \"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 const baseUrl = options.baseUrl;\n let url = baseUrl + (baseUrl.endsWith(\"/\") ? \"\" : \"/\") + (pathTemplate.startsWith(\"/\") ? pathTemplate.slice(1) : pathTemplate);\n const segments = url.match(/({\\w*\\s*\\w*})/ig);\n if (segments && segments.length) {\n if (!pathParameters) {\n throw new Error(`pathTemplate: ${pathTemplate} has been provided. Hence, options.pathParameters must also be provided.`);\n }\n segments.forEach(function (item) {\n const pathParamName = item.slice(1, -1);\n const pathParam = (pathParameters as { [key: string]: any })[pathParamName];\n if (pathParam === null || pathParam === undefined || !(typeof pathParam === \"string\" || typeof pathParam === \"object\")) {\n throw new Error(`pathTemplate: ${pathTemplate} contains the path parameter ${pathParamName}` +\n ` however, it is not present in ${pathParameters} - ${JSON.stringify(pathParameters, 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\n if (typeof pathParam.valueOf() === \"string\") {\n url = url.replace(item, encodeURIComponent(pathParam));\n }\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 = url.replace(item, pathParam.value);\n } else {\n url = url.replace(item, encodeURIComponent(pathParam.value));\n }\n }\n });\n }\n this.url = url;\n }\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 const 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 const 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 (const queryParamName in queryParameters) {\n const queryParam: any = 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 } 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\n // add headers to the request if they are provided\n if (options.headers) {\n const headers = options.headers;\n for (const headerName of Object.keys(options.headers)) {\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\n // default\n if (!this.headers.get(\"Content-Type\")) {\n this.headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n }\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 } 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\n this.abortSignal = options.abortSignal;\n this.onDownloadProgress = options.onDownloadProgress;\n this.onUploadProgress = options.onUploadProgress;\n\n return this;\n }\n\n /**\n * Clone this WebResource HTTP request object.\n * @returns {WebResource} The clone of this WebResource HTTP request object.\n */\n clone(): WebResource {\n const result = new WebResource(\n this.url,\n this.method,\n this.body,\n this.query,\n this.headers && this.headers.clone(),\n this.streamResponseBody,\n this.withCredentials,\n this.abortSignal,\n this.timeout,\n this.onUploadProgress,\n this.onDownloadProgress);\n\n if (this.formData) {\n result.formData = this.formData;\n }\n\n if (this.operationSpec) {\n result.operationSpec = this.operationSpec;\n }\n\n if (this.shouldDeserialize) {\n result.shouldDeserialize = this.shouldDeserialize;\n }\n\n if (this.operationResponseGetter) {\n result.operationResponseGetter = this.operationResponseGetter;\n }\n\n return result;\n }\n}\n\nexport interface RequestPrepareOptions {\n /**\n * The HTTP request method. Valid values are \"GET\", \"PUT\", \"HEAD\", \"DELETE\", \"OPTIONS\", \"POST\",\n * or \"PATCH\".\n */\n method: HttpMethods;\n /**\n * The request url. It may or may not have query parameters in it. Either provide the \"url\" or\n * provide the \"pathTemplate\" in the options object. Both the options are mutually exclusive.\n */\n url?: string;\n /**\n * A dictionary of query parameters to be appended to the url, where\n * the \"key\" is the \"query-parameter-name\" and the \"value\" is the \"query-parameter-value\".\n * The \"query-parameter-value\" can be of type \"string\" or it can be of type \"object\".\n * The \"object\" format should be used when you want to skip url encoding. While using the object format,\n * the object must have a property named value which provides the \"query-parameter-value\".\n * Example:\n * - query-parameter-value in \"object\" format: { \"query-parameter-name\": { value: \"query-parameter-value\", skipUrlEncoding: true } }\n * - query-parameter-value in \"string\" format: { \"query-parameter-name\": \"query-parameter-value\"}.\n * Note: \"If options.url already has some query parameters, then the value provided in options.queryParameters will be appended to the url.\n */\n queryParameters?: { [key: string]: any | ParameterValue };\n /**\n * The path template of the request url. Either provide the \"url\" or provide the \"pathTemplate\" in\n * the options object. Both the options are mutually exclusive.\n * Example: \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}\"\n */\n pathTemplate?: string;\n /**\n * The base url of the request. Default value is: \"https://management.azure.com\". This is\n * applicable only with pathTemplate. If you are providing options.url then it is expected that\n * you provide the complete url.\n */\n baseUrl?: string;\n /**\n * A dictionary of path parameters that need to be replaced with actual values in the pathTemplate.\n * Here the key is the \"path-parameter-name\" and the value is the \"path-parameter-value\".\n * The \"path-parameter-value\" can be of type \"string\" or it can be of type \"object\".\n * The \"object\" format should be used when you want to skip url encoding. While using the object format,\n * the object must have a property named value which provides the \"path-parameter-value\".\n * Example:\n * - path-parameter-value in \"object\" format: { \"path-parameter-name\": { value: \"path-parameter-value\", skipUrlEncoding: true } }\n * - path-parameter-value in \"string\" format: { \"path-parameter-name\": \"path-parameter-value\" }.\n */\n pathParameters?: { [key: string]: any | ParameterValue };\n formData?: { [key: string]: any };\n /**\n * A dictionary of request headers that need to be applied to the request.\n * Here the key is the \"header-name\" and the value is the \"header-value\". The header-value MUST be of type string.\n * - ContentType must be provided with the key name as \"Content-Type\". Default value \"application/json; charset=utf-8\".\n * - \"Transfer-Encoding\" is set to \"chunked\" by default if \"options.bodyIsStream\" is set to true.\n * - \"Content-Type\" is set to \"application/octet-stream\" by default if \"options.bodyIsStream\" is set to true.\n * - \"accept-language\" by default is set to \"en-US\"\n * - \"x-ms-client-request-id\" by default is set to a new Guid. To not generate a guid for the request, please set options.disableClientRequestId to true\n */\n headers?: { [key: string]: any };\n /**\n * When set to true, instructs the client to not set \"x-ms-client-request-id\" header to a new Guid().\n */\n disableClientRequestId?: boolean;\n /**\n * The request body. It can be of any type. This value will be serialized if it is not a stream.\n */\n body?: any;\n /**\n * Provides information on how to serialize the request body.\n */\n serializationMapper?: Mapper;\n /**\n * A dictionary of mappers that may be used while [de]serialization.\n */\n mappers?: { [x: string]: any };\n /**\n * Provides information on how to deserialize the response body.\n */\n deserializationMapper?: object;\n /**\n * Indicates whether this method should JSON.stringify() the request body. Default value: false.\n */\n disableJsonStringifyOnBody?: boolean;\n /**\n * Indicates whether the request body is a stream (useful for file upload scenarios).\n */\n bodyIsStream?: boolean;\n abortSignal?: AbortSignalLike;\n onUploadProgress?: (progress: TransferProgressEvent) => void;\n onDownloadProgress?: (progress: TransferProgressEvent) => void;\n}\n\n/**\n * The Parameter value provided for path or query parameters in RequestPrepareOptions\n */\nexport interface ParameterValue {\n value: any;\n skipUrlEncoding: boolean;\n [key: string]: any;\n}\n\n/**\n * Describes the base structure of the options object that will be used in every operation.\n */\nexport interface RequestOptionsBase {\n /**\n * @property {object} [customHeaders] User defined custom request headers that\n * will be applied before the request is sent.\n */\n customHeaders?: { [key: string]: string };\n\n /**\n * The signal which can be used to abort requests.\n */\n abortSignal?: AbortSignalLike;\n\n /**\n * The number of milliseconds a request can take before automatically being terminated.\n */\n timeout?: number;\n\n /**\n * Callback which fires upon upload progress.\n */\n onUploadProgress?: (progress: TransferProgressEvent) => void;\n\n /**\n * Callback which fires upon download progress.\n */\n onDownloadProgress?: (progress: TransferProgressEvent) => void;\n\n /**\n * Options used to create a span when tracing is enabled.\n */\n spanOptions?: any;\n\n [key: string]: any;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { HttpOperationResponse } from \"./httpOperationResponse\";\nimport { WebResource } from \"./webResource\";\n\nexport class RestError extends Error {\n static readonly REQUEST_SEND_ERROR: string = \"REQUEST_SEND_ERROR\";\n static readonly REQUEST_ABORTED_ERROR: string = \"REQUEST_ABORTED_ERROR\";\n static readonly PARSE_ERROR: string = \"PARSE_ERROR\";\n\n code?: string;\n statusCode?: number;\n request?: WebResource;\n response?: HttpOperationResponse;\n body?: any;\n constructor(message: string, code?: string, statusCode?: number, request?: WebResource, response?: HttpOperationResponse, body?: any) {\n super(message);\n this.code = code;\n this.statusCode = statusCode;\n this.request = request;\n this.response = response;\n this.body = body;\n\n Object.setPrototypeOf(this, RestError.prototype);\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { HttpClient } from \"./httpClient\";\nimport { HttpHeaders } from \"./httpHeaders\";\nimport { WebResource, TransferProgressEvent } from \"./webResource\";\nimport { HttpOperationResponse } from \"./httpOperationResponse\";\nimport { RestError } from \"./restError\";\n\n/**\n * A HttpClient implementation that uses XMLHttpRequest to send HTTP requests.\n */\nexport class XhrHttpClient implements HttpClient {\n public sendRequest(request: WebResource): Promise<HttpOperationResponse> {\n const xhr = new XMLHttpRequest();\n\n if (request.proxySettings) {\n throw new Error(\"HTTP proxy is not supported in browser environment\");\n }\n\n const abortSignal = request.abortSignal;\n if (abortSignal) {\n const listener = () => {\n xhr.abort();\n };\n abortSignal.addEventListener(\"abort\", listener);\n xhr.addEventListener(\"readystatechange\", () => {\n if (xhr.readyState === XMLHttpRequest.DONE) {\n abortSignal.removeEventListener(\"abort\", listener);\n }\n });\n }\n\n addProgressListener(xhr.upload, request.onUploadProgress);\n addProgressListener(xhr, request.onDownloadProgress);\n\n if (request.formData) {\n const formData = request.formData;\n const requestForm = new FormData();\n const appendFormValue = (key: string, value: any) => {\n if (value && value.hasOwnProperty(\"value\") && value.hasOwnProperty(\"options\")) {\n requestForm.append(key, value.value, value.options);\n } else {\n requestForm.append(key, value);\n }\n };\n for (const formKey of Object.keys(formData)) {\n const formValue = formData[formKey];\n if (Array.isArray(formValue)) {\n for (let j = 0; j < formValue.length; j++) {\n appendFormValue(formKey, formValue[j]);\n }\n } else {\n appendFormValue(formKey, formValue);\n }\n }\n\n request.body = requestForm;\n request.formData = undefined;\n const contentType = request.headers.get(\"Content-Type\");\n if (contentType && contentType.indexOf(\"multipart/form-data\") !== -1) {\n // browser will automatically apply a suitable content-type header\n request.headers.remove(\"Content-Type\");\n }\n }\n\n xhr.open(request.method, request.url);\n xhr.timeout = request.timeout;\n xhr.withCredentials = request.withCredentials;\n for (const header of request.headers.headersArray()) {\n xhr.setRequestHeader(header.name, header.value);\n }\n xhr.responseType = request.streamResponseBody ? \"blob\" : \"text\";\n\n // tslint:disable-next-line:no-null-keyword\n xhr.send(request.body === undefined ? null : request.body);\n\n if (request.streamResponseBody) {\n return new Promise((resolve, reject) => {\n xhr.addEventListener(\"readystatechange\", () => {\n // Resolve as soon as headers are loaded\n if (xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) {\n const blobBody = new Promise<Blob>((resolve, reject) => {\n xhr.addEventListener(\"load\", () => {\n resolve(xhr.response);\n });\n rejectOnTerminalEvent(request, xhr, reject);\n });\n resolve({\n request,\n status: xhr.status,\n headers: parseHeaders(xhr),\n blobBody\n });\n }\n });\n rejectOnTerminalEvent(request, xhr, reject);\n });\n } else {\n return new Promise(function (resolve, reject) {\n xhr.addEventListener(\"load\", () => resolve({\n request,\n status: xhr.status,\n headers: parseHeaders(xhr),\n bodyAsText: xhr.responseText\n }));\n rejectOnTerminalEvent(request, xhr, reject);\n });\n }\n }\n}\n\nfunction addProgressListener(xhr: XMLHttpRequestEventTarget, listener?: (progress: TransferProgressEvent) => void) {\n if (listener) {\n xhr.addEventListener(\"progress\", rawEvent => listener({\n loadedBytes: rawEvent.loaded\n }));\n }\n}\n\n// exported locally for testing\nexport function parseHeaders(xhr: XMLHttpRequest) {\n const responseHeaders = new HttpHeaders();\n const headerLines = xhr.getAllResponseHeaders().trim().split(/[\\r\\n]+/);\n for (const line of headerLines) {\n const index = line.indexOf(\":\");\n const headerName = line.slice(0, index);\n const headerValue = line.slice(index + 2);\n responseHeaders.set(headerName, headerValue);\n }\n return responseHeaders;\n}\n\nfunction rejectOnTerminalEvent(request: WebResource, xhr: XMLHttpRequest, reject: (err: any) => void) {\n xhr.addEventListener(\"error\", () => reject(new RestError(`Failed to send request to ${request.url}`, RestError.REQUEST_SEND_ERROR, undefined, request)));\n xhr.addEventListener(\"abort\", () => reject(new RestError(\"The request was aborted\", RestError.REQUEST_ABORTED_ERROR, undefined, request)));\n xhr.addEventListener(\"timeout\", () => reject(new RestError(`timeout of ${xhr.timeout}ms exceeded`, RestError.REQUEST_SEND_ERROR, undefined, request)));\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * The different levels of logs that can be used with the HttpPipelineLogger.\n */\nexport enum HttpPipelineLogLevel {\n /**\n * A log level that indicates that no logs will be logged.\n */\n OFF,\n\n /**\n * An error log.\n */\n ERROR,\n\n /**\n * A warning log.\n */\n WARNING,\n\n /**\n * An information log.\n */\n INFO\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AbortSignalLike } from \"@azure/abort-controller\";\n\n/**\n * Represents a credential capable of providing an authentication token.\n */\nexport interface TokenCredential {\n /**\n * Gets the token provided by this credential.\n *\n * @param scopes The list of scopes for which the token will have access.\n * @param options The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n getToken(scopes: string | string[], options?: GetTokenOptions): Promise<AccessToken | null>;\n}\n\n/**\n * Defines options for TokenCredential.getToken.\n */\nexport interface GetTokenOptions {\n /**\n * An AbortSignalLike implementation that can be used to cancel\n * the token request.\n */\n abortSignal?: AbortSignalLike;\n}\n\n/**\n * Represents an access token with an expiration time.\n */\nexport interface AccessToken {\n /**\n * The access token.\n */\n token: string;\n\n /**\n * The access token's expiration timestamp.\n */\n expiresOnTimestamp: number;\n}\n\n/**\n * Tests an object to determine whether it implements TokenCredential.\n *\n * @param credential The assumed TokenCredential to be tested.\n */\nexport function isTokenCredential(credential: any): credential is TokenCredential {\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 return credential\n && typeof credential.getToken === \"function\"\n && (credential.signRequest === undefined || credential.getToken.length > 0);\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { QueryCollectionFormat } from \"./queryCollectionFormat\";\nimport { Mapper } from \"./serializer\";\n\nexport type ParameterPath = string | string[] | { [propertyName: string]: ParameterPath };\n\n/**\n * A common interface that all Operation parameter's extend.\n */\nexport interface OperationParameter {\n /**\n * The path to this parameter's value in OperationArguments or the object that contains paths for\n * each property's value in OperationArguments.\n */\n parameterPath: ParameterPath;\n\n /**\n * The mapper that defines how to validate and serialize this parameter's value.\n */\n mapper: Mapper;\n}\n\n/**\n * A parameter for an operation that will be substituted into the operation's request URL.\n */\nexport interface OperationURLParameter extends OperationParameter {\n /**\n * Whether or not to skip encoding the URL parameter's value before adding it to the URL.\n */\n skipEncoding?: boolean;\n}\n\n/**\n * A parameter for an operation that will be added as a query parameter to the operation's HTTP\n * request.\n */\nexport interface OperationQueryParameter extends OperationParameter {\n /**\n * Whether or not to skip encoding the query parameter's value before adding it to the URL.\n */\n skipEncoding?: boolean;\n\n /**\n * If this query parameter's value is a collection, what type of format should the value be\n * converted to.\n */\n collectionFormat?: QueryCollectionFormat;\n}\n\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 */\nexport function getPathStringFromParameter(parameter: OperationParameter): string {\n return getPathStringFromParameterPath(parameter.parameterPath, parameter.mapper);\n}\n\nexport function getPathStringFromParameterPath(parameterPath: ParameterPath, mapper: Mapper): string {\n let result: string;\n if (typeof parameterPath === \"string\") {\n result = parameterPath;\n } else if (Array.isArray(parameterPath)) {\n result = parameterPath.join(\".\");\n } else {\n result = mapper.serializedName!;\n }\n return result;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { OperationParameter, OperationQueryParameter, OperationURLParameter } from \"./operationParameter\";\nimport { OperationResponse } from \"./operationResponse\";\nimport { MapperType, Serializer } from \"./serializer\";\nimport { HttpMethods } from \"./webResource\";\n\n/**\n * A specification that defines an operation.\n */\nexport interface OperationSpec {\n /**\n * The serializer to use in this operation.\n */\n readonly serializer: Serializer;\n\n /**\n * The HTTP method that should be used by requests for this operation.\n */\n readonly httpMethod: HttpMethods;\n\n /**\n * The URL that was provided in the service's specification. This will still have all of the URL\n * template variables in it. If this is not provided when the OperationSpec is created, then it\n * will be populated by a \"baseUri\" property on the ServiceClient.\n */\n readonly baseUrl?: string;\n\n /**\n * The fixed path for this operation's URL. This will still have all of the URL template variables\n * in it.\n */\n readonly path?: string;\n\n /**\n * The content type of the request body. This value will be used as the \"Content-Type\" header if\n * it is provided.\n */\n readonly contentType?: string;\n\n /**\n * The parameter that will be used to construct the HTTP request's body.\n */\n readonly requestBody?: OperationParameter;\n\n /**\n * Whether or not this operation uses XML request and response bodies.\n */\n readonly isXML?: boolean;\n\n /**\n * The parameters to the operation method that will be substituted into the constructed URL.\n */\n readonly urlParameters?: ReadonlyArray<OperationURLParameter>;\n\n /**\n * The parameters to the operation method that will be added to the constructed URL's query.\n */\n readonly queryParameters?: ReadonlyArray<OperationQueryParameter>;\n\n /**\n * The parameters to the operation method that will be converted to headers on the operation's\n * HTTP request.\n */\n readonly headerParameters?: ReadonlyArray<OperationParameter>;\n\n /**\n * The parameters to the operation method that will be used to create a formdata body for the\n * operation's HTTP request.\n */\n readonly formDataParameters?: ReadonlyArray<OperationParameter>;\n\n /**\n * The different types of responses that this operation can return based on what status code is\n * returned.\n */\n readonly responses: { [responseCode: string]: OperationResponse };\n}\n\nexport function isStreamOperation(operationSpec: OperationSpec): boolean {\n let result = false;\n for (const statusCode in operationSpec.responses) {\n const operationResponse: 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","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nconst parser = new DOMParser();\nexport function parseXML(str: string): Promise<any> {\n try {\n const dom = parser.parseFromString(str, \"application/xml\");\n throwIfError(dom);\n\n const obj = domToObject(dom.childNodes[0]);\n return Promise.resolve(obj);\n } catch (err) {\n return Promise.reject(err);\n }\n}\n\nlet errorNS = \"\";\ntry {\n errorNS = parser.parseFromString(\"INVALID\", \"text/xml\").getElementsByTagName(\"parsererror\")[0].namespaceURI!;\n} catch (ignored) {\n // Most browsers will return a document containing <parsererror>, but IE will throw.\n}\n\nfunction throwIfError(dom: Document) {\n if (errorNS) {\n const parserErrors = dom.getElementsByTagNameNS(errorNS, \"parsererror\");\n if (parserErrors.length) {\n throw new Error(parserErrors.item(0)!.innerHTML);\n }\n }\n}\n\nfunction isElement(node: Node): node is Element {\n return !!(node as Element).attributes;\n}\n\n/**\n * Get the Element-typed version of the provided Node if the provided node is an element with\n * attributes. If it isn't, then undefined is returned.\n */\nfunction asElementWithAttributes(node: Node): Element | undefined {\n return isElement(node) && node.hasAttributes() ? node : undefined;\n}\n\nfunction domToObject(node: Node): any {\n let result: any = {};\n\n const childNodeCount: number = node.childNodes.length;\n\n const firstChildNode: Node = node.childNodes[0];\n const onlyChildTextValue: string | undefined = (firstChildNode && childNodeCount === 1 && firstChildNode.nodeType === Node.TEXT_NODE && firstChildNode.nodeValue) || undefined;\n\n const elementWithAttributes: Element | undefined = asElementWithAttributes(node);\n if (elementWithAttributes) {\n result[\"$\"] = {};\n\n for (let i = 0; i < elementWithAttributes.attributes.length; i++) {\n const attr = elementWithAttributes.attributes[i];\n result[\"$\"][attr.nodeName] = attr.nodeValue;\n }\n\n if (onlyChildTextValue) {\n result[\"_\"] = onlyChildTextValue;\n }\n } else if (childNodeCount === 0) {\n result = \"\";\n } else if (onlyChildTextValue) {\n result = onlyChildTextValue;\n }\n\n if (!onlyChildTextValue) {\n for (let i = 0; i < childNodeCount; i++) {\n const child = node.childNodes[i];\n // Ignore leading/trailing whitespace nodes\n if (child.nodeType !== Node.TEXT_NODE) {\n const childObject: any = domToObject(child);\n if (!result[child.nodeName]) {\n result[child.nodeName] = childObject;\n } else if (Array.isArray(result[child.nodeName])) {\n result[child.nodeName].push(childObject);\n } else {\n result[child.nodeName] = [result[child.nodeName], childObject];\n }\n }\n }\n }\n\n return result;\n}\n\n// tslint:disable-next-line:no-null-keyword\nconst doc = document.implementation.createDocument(null, null, null);\nconst serializer = new XMLSerializer();\n\nexport function stringifyXML(obj: any, opts?: { rootName?: string }) {\n const rootName = opts && opts.rootName || \"root\";\n const dom = buildNode(obj, rootName)[0];\n return '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>' + serializer.serializeToString(dom);\n}\n\nfunction buildAttributes(attrs: { [key: string]: { toString(): string; } }): Attr[] {\n const result = [];\n for (const key of Object.keys(attrs)) {\n const attr = doc.createAttribute(key);\n attr.value = attrs[key].toString();\n result.push(attr);\n }\n return result;\n}\n\nfunction buildNode(obj: any, elementName: string): Node[] {\n if (typeof obj === \"string\" || typeof obj === \"number\" || typeof obj === \"boolean\") {\n const elem = doc.createElement(elementName);\n elem.textContent = obj.toString();\n return [elem];\n }\n else if (Array.isArray(obj)) {\n const result = [];\n for (const arrayElem of obj) {\n for (const child of buildNode(arrayElem, elementName)) {\n result.push(child);\n }\n }\n return result;\n } else if (typeof obj === \"object\") {\n const elem = doc.createElement(elementName);\n for (const key of Object.keys(obj)) {\n if (key === \"$\") {\n for (const attr of buildAttributes(obj[key])) {\n elem.attributes.setNamedItem(attr);\n }\n } else {\n for (const child of buildNode(obj[key], key)) {\n elem.appendChild(child);\n }\n }\n }\n return [elem];\n }\n else {\n throw new Error(`Illegal value passed to buildObject: ${obj}`);\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { HttpOperationResponse } from \"../httpOperationResponse\";\nimport { HttpPipelineLogger } from \"../httpPipelineLogger\";\nimport { HttpPipelineLogLevel } from \"../httpPipelineLogLevel\";\nimport { WebResource } from \"../webResource\";\n\n/**\n * Creates a new RequestPolicy per-request that uses the provided nextPolicy.\n */\nexport type RequestPolicyFactory = {\n create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): RequestPolicy\n};\n\nexport interface RequestPolicy {\n sendRequest(httpRequest: WebResource): Promise<HttpOperationResponse>;\n}\n\nexport abstract class BaseRequestPolicy implements RequestPolicy {\n protected constructor(readonly _nextPolicy: RequestPolicy, readonly _options: RequestPolicyOptions) {\n }\n\n public abstract sendRequest(webResource: WebResource): Promise<HttpOperationResponse>;\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 public shouldLog(logLevel: HttpPipelineLogLevel): boolean {\n return this._options.shouldLog(logLevel);\n }\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 public log(logLevel: HttpPipelineLogLevel, message: string): void {\n this._options.log(logLevel, message);\n }\n}\n\n/**\n * Optional properties that can be used when creating a RequestPolicy.\n */\nexport class RequestPolicyOptions {\n constructor(private _logger?: HttpPipelineLogger) {\n }\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 public shouldLog(logLevel: HttpPipelineLogLevel): boolean {\n return !!this._logger &&\n logLevel !== HttpPipelineLogLevel.OFF &&\n logLevel <= this._logger.minimumLogLevel;\n }\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 public log(logLevel: HttpPipelineLogLevel, message: string): void {\n if (this._logger && this.shouldLog(logLevel)) {\n this._logger.log(logLevel, message);\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { HttpOperationResponse } from \"../httpOperationResponse\";\nimport { OperationResponse } from \"../operationResponse\";\nimport { OperationSpec, isStreamOperation } from \"../operationSpec\";\nimport { RestError } from \"../restError\";\nimport { Mapper, MapperType } from \"../serializer\";\nimport * as utils from \"../util/utils\";\nimport { parseXML } from \"../util/xml\";\nimport { WebResource } from \"../webResource\";\nimport { BaseRequestPolicy, RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from \"./requestPolicy\";\n\n/**\n * The content-types that will indicate that an operation response should be deserialized in a\n * particular way.\n */\nexport interface DeserializationContentTypes {\n /**\n * The content-types that indicate that an operation response should be deserialized as JSON.\n * Defaults to [ \"application/json\", \"text/json\" ].\n */\n json?: string[];\n\n /**\n * The content-types that indicate that an operation response should be deserialized as XML.\n * Defaults to [ \"application/xml\", \"application/atom+xml\" ].\n */\n xml?: string[];\n}\n\n/**\n * Create a new serialization RequestPolicyCreator that will serialized HTTP request bodies as they\n * pass through the HTTP pipeline.\n */\nexport function deserializationPolicy(deserializationContentTypes?: DeserializationContentTypes): RequestPolicyFactory {\n return {\n create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions) => {\n return new DeserializationPolicy(nextPolicy, deserializationContentTypes, options);\n }\n };\n}\n\nexport const defaultJsonContentTypes = [\"application/json\", \"text/json\"];\nexport const defaultXmlContentTypes = [\"application/xml\", \"application/atom+xml\"];\n\n/**\n * A RequestPolicy that will deserialize HTTP response bodies and headers as they pass through the\n * HTTP pipeline.\n */\nexport class DeserializationPolicy extends BaseRequestPolicy {\n public readonly jsonContentTypes: string[];\n public readonly xmlContentTypes: string[];\n\n constructor(nextPolicy: RequestPolicy, deserializationContentTypes: DeserializationContentTypes | undefined, options: RequestPolicyOptions) {\n super(nextPolicy, options);\n\n this.jsonContentTypes = deserializationContentTypes && deserializationContentTypes.json || defaultJsonContentTypes;\n this.xmlContentTypes = deserializationContentTypes && deserializationContentTypes.xml || defaultXmlContentTypes;\n }\n\n public async sendRequest(request: WebResource): Promise<HttpOperationResponse> {\n return this._nextPolicy.sendRequest(request).then((response: HttpOperationResponse) => deserializeResponseBody(this.jsonContentTypes, this.xmlContentTypes, response));\n }\n}\n\nfunction getOperationResponse(parsedResponse: HttpOperationResponse): undefined | OperationResponse {\n let result: OperationResponse | undefined;\n const request: WebResource = parsedResponse.request;\n const operationSpec: OperationSpec | undefined = request.operationSpec;\n if (operationSpec) {\n const operationResponseGetter: undefined | ((operationSpec: OperationSpec, response: HttpOperationResponse) => (undefined | OperationResponse)) = request.operationResponseGetter;\n if (!operationResponseGetter) {\n result = operationSpec.responses[parsedResponse.status];\n } else {\n result = operationResponseGetter(operationSpec, parsedResponse);\n }\n }\n return result;\n}\n\nfunction shouldDeserializeResponse(parsedResponse: HttpOperationResponse): boolean {\n const shouldDeserialize: undefined | boolean | ((response: HttpOperationResponse) => boolean) = parsedResponse.request.shouldDeserialize;\n let result: boolean;\n if (shouldDeserialize === undefined) {\n result = true;\n } else if (typeof shouldDeserialize === \"boolean\") {\n result = shouldDeserialize;\n } else {\n result = shouldDeserialize(parsedResponse);\n }\n return result;\n}\n\nexport function deserializeResponseBody(jsonContentTypes: string[], xmlContentTypes: string[], response: HttpOperationResponse): Promise<HttpOperationResponse> {\n return parse(jsonContentTypes, xmlContentTypes, response).then(parsedResponse => {\n const shouldDeserialize: boolean = shouldDeserializeResponse(parsedResponse);\n if (shouldDeserialize) {\n const operationSpec: OperationSpec | undefined = parsedResponse.request.operationSpec;\n if (operationSpec && operationSpec.responses) {\n const statusCode: number = parsedResponse.status;\n\n const expectedStatusCodes: string[] = Object.keys(operationSpec.responses);\n\n const hasNoExpectedStatusCodes: boolean = (expectedStatusCodes.length === 0 || (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === \"default\"));\n\n const responseSpec: OperationResponse | undefined = getOperationResponse(parsedResponse);\n\n const isExpectedStatusCode: boolean = hasNoExpectedStatusCodes ? (200 <= statusCode && statusCode < 300) : !!responseSpec;\n if (!isExpectedStatusCode) {\n const defaultResponseSpec: OperationResponse = operationSpec.responses.default;\n if (defaultResponseSpec) {\n const initialErrorMessage: string = isStreamOperation(operationSpec)\n ? `Unexpected status code: ${statusCode}`\n : parsedResponse.bodyAsText as string;\n\n const error = new RestError(initialErrorMessage);\n error.statusCode = statusCode;\n error.request = utils.stripRequest(parsedResponse.request);\n error.response = utils.stripResponse(parsedResponse);\n\n let parsedErrorResponse: { [key: string]: any } = parsedResponse.parsedBody;\n try {\n if (parsedErrorResponse) {\n const defaultResponseBodyMapper: Mapper | undefined = 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 } else {\n let internalError: any = parsedErrorResponse;\n if (parsedErrorResponse.error) {\n internalError = parsedErrorResponse.error;\n }\n\n error.code = internalError.code;\n if (internalError.message) {\n error.message = internalError.message;\n }\n }\n\n if (defaultResponseBodyMapper) {\n let valueToDeserialize: any = 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 } 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 } else if (responseSpec) {\n if (responseSpec.bodyMapper) {\n let valueToDeserialize: any = 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 } catch (error) {\n const restError = new RestError(`Error ${error} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`);\n restError.request = utils.stripRequest(parsedResponse.request);\n restError.response = utils.stripResponse(parsedResponse);\n return Promise.reject(restError);\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\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}\n\nfunction parse(jsonContentTypes: string[], xmlContentTypes: string[], operationResponse: HttpOperationResponse): Promise<HttpOperationResponse> {\n const errorHandler = (err: Error & { code: string }) => {\n const msg = `Error \"${err}\" occurred while parsing the response body - ${operationResponse.bodyAsText}.`;\n const errCode = err.code || RestError.PARSE_ERROR;\n const e = new RestError(msg, errCode, operationResponse.status, operationResponse.request, operationResponse, operationResponse.bodyAsText);\n return Promise.reject(e);\n };\n\n if (!operationResponse.request.streamResponseBody && operationResponse.bodyAsText) {\n const text = operationResponse.bodyAsText;\n const contentType: string = operationResponse.headers.get(\"Content-Type\") || \"\";\n const contentComponents: string[] = !contentType ? [] : contentType.split(\";\").map(component => component.toLowerCase());\n if (contentComponents.length === 0 || contentComponents.some(component => jsonContentTypes.indexOf(component) !== -1)) {\n return new Promise<HttpOperationResponse>(resolve => {\n operationResponse.parsedBody = JSON.parse(text);\n resolve(operationResponse);\n }).catch(errorHandler);\n } else if (contentComponents.some(component => xmlContentTypes.indexOf(component) !== -1)) {\n return parseXML(text)\n .then(body => {\n operationResponse.parsedBody = body;\n return operationResponse;\n })\n .catch(errorHandler);\n }\n }\n\n return Promise.resolve(operationResponse);\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { HttpOperationResponse } from \"../httpOperationResponse\";\nimport * as utils from \"../util/utils\";\nimport { WebResource } from \"../webResource\";\nimport { BaseRequestPolicy, RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from \"./requestPolicy\";\nimport { RestError } from \"../restError\";\n\nexport interface RetryData {\n retryCount: number;\n retryInterval: number;\n error?: RetryError;\n}\n\nexport interface RetryError extends Error {\n message: string;\n code?: string;\n innerError?: RetryError;\n}\n\nexport function exponentialRetryPolicy(retryCount?: number, retryInterval?: number, minRetryInterval?: number, maxRetryInterval?: number): RequestPolicyFactory {\n return {\n create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions) => {\n return new ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval);\n }\n };\n}\n\nconst DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30;\nconst DEFAULT_CLIENT_RETRY_COUNT = 3;\nconst DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90;\nconst DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3;\n\n/**\n * @class\n * Instantiates a new \"ExponentialRetryPolicyFilter\" instance.\n */\nexport class ExponentialRetryPolicy extends BaseRequestPolicy {\n /**\n * The client retry count.\n */\n retryCount: number;\n /**\n * The client retry interval in milliseconds.\n */\n retryInterval: number;\n /**\n * The minimum retry interval in milliseconds.\n */\n minRetryInterval: number;\n /**\n * The maximum retry interval in milliseconds.\n */\n maxRetryInterval: number;\n\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 constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, retryCount?: number, retryInterval?: number, minRetryInterval?: number, maxRetryInterval?: number) {\n super(nextPolicy, options);\n function isNumber(n: any): n is number { 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 }\n\n public sendRequest(request: WebResource): Promise<HttpOperationResponse> {\n return this._nextPolicy.sendRequest(request.clone())\n .then(response => retry(this, request, response))\n .catch(error => retry(this, request, error.response, undefined, error));\n }\n}\n\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: ExponentialRetryPolicy, statusCode: number | undefined, retryData: RetryData): boolean {\n if (statusCode == undefined || (statusCode < 500 && statusCode !== 408) || statusCode === 501 || statusCode === 505) {\n return false;\n }\n\n let currentCount: number;\n if (!retryData) {\n throw new Error(\"retryData for the ExponentialRetryPolicyFilter cannot be null.\");\n } else {\n currentCount = (retryData && retryData.retryCount);\n }\n\n return (currentCount < policy.retryCount);\n}\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: ExponentialRetryPolicy, retryData?: RetryData, err?: RetryError): RetryData {\n if (!retryData) {\n retryData = {\n retryCount: 0,\n retryInterval: 0\n };\n }\n\n if (err) {\n if (retryData.error) {\n err.innerError = retryData.error;\n }\n\n retryData.error = err;\n }\n\n // Adjust retry count\n retryData.retryCount++;\n\n // Adjust retry interval\n let incrementDelta = Math.pow(2, retryData.retryCount) - 1;\n const boundedRandDelta = policy.retryInterval * 0.8 +\n Math.floor(Math.random() * (policy.retryInterval * 1.2 - policy.retryInterval * 0.8));\n incrementDelta *= boundedRandDelta;\n\n retryData.retryInterval = Math.min(policy.minRetryInterval + incrementDelta, policy.maxRetryInterval);\n\n return retryData;\n}\n\nfunction retry(policy: ExponentialRetryPolicy, request: WebResource, response?: HttpOperationResponse, retryData?: RetryData, requestError?: RetryError): Promise<HttpOperationResponse> {\n retryData = updateRetryData(policy, retryData, requestError);\n const isAborted: boolean | undefined = request.abortSignal && request.abortSignal.aborted;\n if (!isAborted && shouldRetry(policy, response && response.status, retryData)) {\n return utils.delay(retryData.retryInterval)\n .then(() => policy._nextPolicy.sendRequest(request.clone()))\n .then(res => retry(policy, request, res, retryData, undefined))\n .catch(err => retry(policy, request, response, retryData, err));\n } else if (isAborted || requestError || !response) {\n // If the operation failed in the end, return all errors instead of just the last one\n const err = retryData.error ||\n new RestError(\n \"Failed to send the request.\",\n RestError.REQUEST_SEND_ERROR,\n response && response.status,\n response && response.request,\n response);\n return Promise.reject(err);\n } else {\n return Promise.resolve(response);\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { HttpOperationResponse } from \"../httpOperationResponse\";\nimport * as utils from \"../util/utils\";\nimport { WebResource } from \"../webResource\";\nimport { BaseRequestPolicy, RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from \"./requestPolicy\";\n\nexport function generateClientRequestIdPolicy(requestIdHeaderName = \"x-ms-client-request-id\"): RequestPolicyFactory {\n return {\n create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions) => {\n return new GenerateClientRequestIdPolicy(nextPolicy, options, requestIdHeaderName);\n }\n };\n}\n\nexport class GenerateClientRequestIdPolicy extends BaseRequestPolicy {\n constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, private _requestIdHeaderName: string) {\n super(nextPolicy, options);\n }\n\n public sendRequest(request: WebResource): Promise<HttpOperationResponse> {\n if (!request.headers.contains(this._requestIdHeaderName)) {\n request.headers.set(this._requestIdHeaderName, utils.generateUuid());\n }\n return this._nextPolicy.sendRequest(request);\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/*\n * NOTE: When moving this file, please update \"browser\" section in package.json\n * and \"plugins\" section in webpack.testconfig.ts.\n */\n\nimport { TelemetryInfo } from \"./userAgentPolicy\";\n\ninterface NavigatorEx extends Navigator {\n readonly oscpu: string | undefined;\n}\n\nexport function getDefaultUserAgentKey(): string {\n return \"x-ms-command-name\";\n}\n\nexport function getPlatformSpecificData(): TelemetryInfo[] {\n const navigator = window.navigator as NavigatorEx;\n const osInfo = {\n key: \"OS\",\n value: (navigator.oscpu || navigator.platform).replace(\" \", \"\")\n };\n\n return [osInfo];\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { HttpHeaders } from \"../httpHeaders\";\nimport { HttpOperationResponse } from \"../httpOperationResponse\";\nimport { Constants } from \"../util/constants\";\nimport { WebResource } from \"../webResource\";\nimport { getDefaultUserAgentKey, getPlatformSpecificData } from \"./msRestUserAgentPolicy\";\nimport { BaseRequestPolicy, RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from \"./requestPolicy\";\n\nexport type TelemetryInfo = { key?: string; value?: string };\n\nfunction getRuntimeInfo(): TelemetryInfo[] {\n const msRestRuntime = {\n key: \"core-http\",\n value: Constants.coreHttpVersion\n };\n\n return [msRestRuntime];\n}\n\nfunction getUserAgentString(telemetryInfo: TelemetryInfo[], keySeparator = \" \", valueSeparator = \"/\"): string {\n return telemetryInfo.map(info => {\n const value = info.value ? `${valueSeparator}${info.value}` : \"\";\n return `${info.key}${value}`;\n }).join(keySeparator);\n}\n\nexport const getDefaultUserAgentHeaderName = getDefaultUserAgentKey;\n\nexport function getDefaultUserAgentValue(): string {\n const runtimeInfo = getRuntimeInfo();\n const platformSpecificData = getPlatformSpecificData();\n const userAgent = getUserAgentString(runtimeInfo.concat(platformSpecificData));\n return userAgent;\n}\n\nexport function userAgentPolicy(userAgentData?: TelemetryInfo): RequestPolicyFactory {\n const key: string = (!userAgentData || userAgentData.key == undefined) ? getDefaultUserAgentKey() : userAgentData.key;\n const value: string = (!userAgentData || userAgentData.value == undefined) ? getDefaultUserAgentValue() : userAgentData.value;\n\n return {\n create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions) => {\n return new UserAgentPolicy(nextPolicy, options, key, value);\n }\n };\n}\n\nexport class UserAgentPolicy extends BaseRequestPolicy {\n constructor(readonly _nextPolicy: RequestPolicy, readonly _options: RequestPolicyOptions, protected headerKey: string, protected headerValue: string) {\n super(_nextPolicy, _options);\n }\n\n sendRequest(request: WebResource): Promise<HttpOperationResponse> {\n this.addUserAgentHeader(request);\n return this._nextPolicy.sendRequest(request);\n }\n\n addUserAgentHeader(request: WebResource): void {\n if (!request.headers) {\n request.headers = new HttpHeaders();\n }\n\n if (!request.headers.get(this.headerKey) && this.headerValue) {\n request.headers.set(this.headerKey, this.headerValue);\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { replaceAll } from \"./util/utils\";\n\ntype URLQueryParseState = \"ParameterName\" | \"ParameterValue\" | \"Invalid\";\n\n/**\n * A class that handles the query portion of a URLBuilder.\n */\nexport class URLQuery {\n private readonly _rawQuery: { [queryParameterName: string]: string | string[] } = {};\n\n /**\n * Get whether or not there any query parameters in this URLQuery.\n */\n public any(): boolean {\n return Object.keys(this._rawQuery).length > 0;\n }\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 public set(parameterName: string, parameterValue: any): void {\n if (parameterName) {\n if (parameterValue != undefined) {\n const newValue = Array.isArray(parameterValue) ? parameterValue : parameterValue.toString();\n this._rawQuery[parameterName] = newValue;\n } else {\n delete this._rawQuery[parameterName];\n }\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 public get(parameterName: string): string | string[] | undefined {\n return parameterName ? this._rawQuery[parameterName] : undefined;\n }\n\n /**\n * Get the string representation of this query. The return value will not start with a \"?\".\n */\n public toString(): string {\n let result = \"\";\n for (const parameterName in this._rawQuery) {\n if (result) {\n result += \"&\";\n }\n const parameterValue = this._rawQuery[parameterName];\n if (Array.isArray(parameterValue)) {\n const parameterStrings = [];\n for (const parameterValueElement of parameterValue) {\n parameterStrings.push(`${parameterName}=${parameterValueElement}`);\n }\n result += parameterStrings.join(\"&\");\n } else {\n result += `${parameterName}=${parameterValue}`;\n }\n }\n return result;\n }\n\n /**\n * Parse a URLQuery from the provided text.\n */\n public static parse(text: string): URLQuery {\n const result = new URLQuery();\n\n if (text) {\n if (text.startsWith(\"?\")) {\n text = text.substring(1);\n }\n\n let currentState: URLQueryParseState = \"ParameterName\";\n\n let parameterName = \"\";\n let parameterValue = \"\";\n for (let i = 0; i < text.length; ++i) {\n const currentCharacter: string = text[i];\n switch (currentState) {\n case \"ParameterName\":\n switch (currentCharacter) {\n case \"=\":\n currentState = \"ParameterValue\";\n break;\n\n case \"&\":\n parameterName = \"\";\n parameterValue = \"\";\n break;\n\n default:\n parameterName += currentCharacter;\n break;\n }\n break;\n\n case \"ParameterValue\":\n switch (currentCharacter) {\n case \"=\":\n parameterName = \"\";\n parameterValue = \"\";\n currentState = \"Invalid\";\n break;\n\n case \"&\":\n result.set(parameterName, parameterValue);\n parameterName = \"\";\n parameterValue = \"\";\n currentState = \"ParameterName\";\n break;\n\n default:\n parameterValue += currentCharacter;\n break;\n }\n break;\n\n case \"Invalid\":\n if (currentCharacter === \"&\") {\n currentState = \"ParameterName\";\n }\n break;\n\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\n return result;\n }\n}\n\n/**\n * A class that handles creating, modifying, and parsing URLs.\n */\nexport class URLBuilder {\n private _scheme: string | undefined;\n private _host: string | undefined;\n private _port: string | undefined;\n private _path: string | undefined;\n private _query: URLQuery | undefined;\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 public setScheme(scheme: string | undefined): void {\n if (!scheme) {\n this._scheme = undefined;\n } else {\n this.set(scheme, \"SCHEME\");\n }\n }\n\n /**\n * Get the scheme that has been set in this URL.\n */\n public getScheme(): string | undefined {\n return this._scheme;\n }\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 public setHost(host: string | undefined): void {\n if (!host) {\n this._host = undefined;\n } else {\n this.set(host, \"SCHEME_OR_HOST\");\n }\n }\n\n /**\n * Get the host that has been set in this URL.\n */\n public getHost(): string | undefined {\n return this._host;\n }\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 public setPort(port: number | string | undefined): void {\n if (port == undefined || port === \"\") {\n this._port = undefined;\n } else {\n this.set(port.toString(), \"PORT\");\n }\n }\n\n /**\n * Get the port that has been set in this URL.\n */\n public getPort(): string | undefined {\n return this._port;\n }\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 public setPath(path: string | undefined): void {\n if (!path) {\n this._path = undefined;\n } else {\n if (path.indexOf(\"://\") !== -1) {\n this.set(path, \"SCHEME\");\n } else {\n this.set(path, \"PATH\");\n }\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 public appendPath(path: string | undefined): void {\n if (path) {\n let currentPath: string | undefined = this.getPath();\n if (currentPath) {\n if (!currentPath.endsWith(\"/\")) {\n currentPath += \"/\";\n }\n\n if (path.startsWith(\"/\")) {\n path = path.substring(1);\n }\n\n path = currentPath + path;\n }\n this.set(path, \"PATH\");\n }\n }\n\n /**\n * Get the path that has been set in this URL.\n */\n public getPath(): string | undefined {\n return this._path;\n }\n\n /**\n * Set the query in this URL.\n */\n public setQuery(query: string | undefined): void {\n if (!query) {\n this._query = undefined;\n } else {\n this._query = URLQuery.parse(query);\n }\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 public setQueryParameter(queryParameterName: string, queryParameterValue: any): void {\n if (queryParameterName) {\n if (!this._query) {\n this._query = new URLQuery();\n }\n this._query.set(queryParameterName, queryParameterValue);\n }\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 public getQueryParameterValue(queryParameterName: string): string | string[] | undefined {\n return this._query ? this._query.get(queryParameterName) : undefined;\n }\n\n /**\n * Get the query in this URL.\n */\n public getQuery(): string | undefined {\n return this._query ? this._query.toString() : undefined;\n }\n\n /**\n * Set the parts of this URL by parsing the provided text using the provided startState.\n */\n private set(text: string, startState: URLTokenizerState): void {\n const tokenizer = new URLTokenizer(text, startState);\n\n while (tokenizer.next()) {\n const token: URLToken | undefined = tokenizer.current();\n if (token) {\n switch (token.type) {\n case \"SCHEME\":\n this._scheme = token.text || undefined;\n break;\n\n case \"HOST\":\n this._host = token.text || undefined;\n break;\n\n case \"PORT\":\n this._port = token.text || undefined;\n break;\n\n case \"PATH\":\n const tokenPath: string | undefined = token.text || undefined;\n if (!this._path || this._path === \"/\" || tokenPath !== \"/\") {\n this._path = tokenPath;\n }\n break;\n\n case \"QUERY\":\n this._query = URLQuery.parse(token.text);\n break;\n\n default:\n throw new Error(`Unrecognized URLTokenType: ${token.type}`);\n }\n }\n }\n }\n\n public toString(): string {\n let result = \"\";\n\n if (this._scheme) {\n result += `${this._scheme}://`;\n }\n\n if (this._host) {\n result += this._host;\n }\n\n if (this._port) {\n result += `:${this._port}`;\n }\n\n if (this._path) {\n if (!this._path.startsWith(\"/\")) {\n result += \"/\";\n }\n result += this._path;\n }\n\n if (this._query && this._query.any()) {\n result += `?${this._query.toString()}`;\n }\n\n return result;\n }\n\n /**\n * If the provided searchValue is found in this URLBuilder, then replace it with the provided\n * replaceValue.\n */\n public replaceAll(searchValue: string, replaceValue: string): void {\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\n public static parse(text: string): URLBuilder {\n const result = new URLBuilder();\n result.set(text, \"SCHEME_OR_HOST\");\n return result;\n }\n}\n\ntype URLTokenizerState = \"SCHEME\" | \"SCHEME_OR_HOST\" | \"HOST\" | \"PORT\" | \"PATH\" | \"QUERY\" | \"DONE\";\n\ntype URLTokenType = \"SCHEME\" | \"HOST\" | \"PORT\" | \"PATH\" | \"QUERY\";\n\nexport class URLToken {\n public constructor(public readonly text: string, public readonly type: URLTokenType) {\n }\n\n public static scheme(text: string): URLToken {\n return new URLToken(text, \"SCHEME\");\n }\n\n public static host(text: string): URLToken {\n return new URLToken(text, \"HOST\");\n }\n\n public static port(text: string): URLToken {\n return new URLToken(text, \"PORT\");\n }\n\n public static path(text: string): URLToken {\n return new URLToken(text, \"PATH\");\n }\n\n public static query(text: string): URLToken {\n return new URLToken(text, \"QUERY\");\n }\n}\n\n/**\n * Get whether or not the provided character (single character string) is an alphanumeric (letter or\n * digit) character.\n */\nexport function isAlphaNumericCharacter(character: string): boolean {\n const characterCode: number = 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/**\n * A class that tokenizes URL strings.\n */\nexport class URLTokenizer {\n readonly _textLength: number;\n _currentState: URLTokenizerState;\n _currentIndex: number;\n _currentToken: URLToken | undefined;\n\n public constructor(readonly _text: string, state?: URLTokenizerState) {\n this._textLength = _text ? _text.length : 0;\n this._currentState = state != undefined ? state : \"SCHEME_OR_HOST\";\n this._currentIndex = 0;\n }\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 public current(): URLToken | undefined {\n return this._currentToken;\n }\n\n /**\n * Advance to the next URLToken and return whether or not a URLToken was found.\n */\n public next(): boolean {\n if (!hasCurrentCharacter(this)) {\n this._currentToken = undefined;\n } else {\n switch (this._currentState) {\n case \"SCHEME\":\n nextScheme(this);\n break;\n\n case \"SCHEME_OR_HOST\":\n nextSchemeOrHost(this);\n break;\n\n case \"HOST\":\n nextHost(this);\n break;\n\n case \"PORT\":\n nextPort(this);\n break;\n\n case \"PATH\":\n nextPath(this);\n break;\n\n case \"QUERY\":\n nextQuery(this);\n break;\n\n default:\n throw new Error(`Unrecognized URLTokenizerState: ${this._currentState}`);\n }\n }\n return !!this._currentToken;\n }\n}\n\n\n/**\n * Read the remaining characters from this Tokenizer's character stream.\n */\nfunction readRemaining(tokenizer: URLTokenizer): string {\n let 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/**\n * Whether or not this URLTokenizer has a current character.\n */\nfunction hasCurrentCharacter(tokenizer: URLTokenizer): boolean {\n return tokenizer._currentIndex < tokenizer._textLength;\n}\n\n/**\n * Get the character in the text string at the current index.\n */\nfunction getCurrentCharacter(tokenizer: URLTokenizer): string {\n return tokenizer._text[tokenizer._currentIndex];\n}\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: URLTokenizer, step?: number): void {\n if (hasCurrentCharacter(tokenizer)) {\n if (!step) {\n step = 1;\n }\n tokenizer._currentIndex += step;\n }\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: URLTokenizer, charactersToPeek: number): string {\n let endIndex: number = tokenizer._currentIndex + charactersToPeek;\n if (tokenizer._textLength < endIndex) {\n endIndex = tokenizer._textLength;\n }\n return tokenizer._text.substring(tokenizer._currentIndex, endIndex);\n}\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: URLTokenizer, condition: (character: string) => boolean): string {\n let result = \"\";\n\n while (hasCurrentCharacter(tokenizer)) {\n const currentCharacter: string = getCurrentCharacter(tokenizer);\n if (!condition(currentCharacter)) {\n break;\n } else {\n result += currentCharacter;\n nextCharacter(tokenizer);\n }\n }\n\n return result;\n}\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: URLTokenizer): string {\n return readWhile(tokenizer, (character: string) => isAlphaNumericCharacter(character));\n}\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: URLTokenizer, ...terminatingCharacters: string[]): string {\n return readWhile(tokenizer, (character: string) => terminatingCharacters.indexOf(character) === -1);\n}\n\nfunction nextScheme(tokenizer: URLTokenizer): void {\n const scheme: string = readWhileLetterOrDigit(tokenizer);\n tokenizer._currentToken = URLToken.scheme(scheme);\n if (!hasCurrentCharacter(tokenizer)) {\n tokenizer._currentState = \"DONE\";\n } else {\n tokenizer._currentState = \"HOST\";\n }\n}\n\nfunction nextSchemeOrHost(tokenizer: URLTokenizer): void {\n const schemeOrHost: string = readUntilCharacter(tokenizer, \":\", \"/\", \"?\");\n if (!hasCurrentCharacter(tokenizer)) {\n tokenizer._currentToken = URLToken.host(schemeOrHost);\n tokenizer._currentState = \"DONE\";\n } else if (getCurrentCharacter(tokenizer) === \":\") {\n if (peekCharacters(tokenizer, 3) === \"://\") {\n tokenizer._currentToken = URLToken.scheme(schemeOrHost);\n tokenizer._currentState = \"HOST\";\n } else {\n tokenizer._currentToken = URLToken.host(schemeOrHost);\n tokenizer._currentState = \"PORT\";\n }\n } else {\n tokenizer._currentToken = URLToken.host(schemeOrHost);\n if (getCurrentCharacter(tokenizer) === \"/\") {\n tokenizer._currentState = \"PATH\";\n } else {\n tokenizer._currentState = \"QUERY\";\n }\n }\n}\n\nfunction nextHost(tokenizer: URLTokenizer): void {\n if (peekCharacters(tokenizer, 3) === \"://\") {\n nextCharacter(tokenizer, 3);\n }\n\n const host: string = readUntilCharacter(tokenizer, \":\", \"/\", \"?\");\n tokenizer._currentToken = URLToken.host(host);\n\n if (!hasCurrentCharacter(tokenizer)) {\n tokenizer._currentState = \"DONE\";\n } else if (getCurrentCharacter(tokenizer) === \":\") {\n tokenizer._currentState = \"PORT\";\n } else if (getCurrentCharacter(tokenizer) === \"/\") {\n tokenizer._currentState = \"PATH\";\n } else {\n tokenizer._currentState = \"QUERY\";\n }\n}\n\nfunction nextPort(tokenizer: URLTokenizer): void {\n if (getCurrentCharacter(tokenizer) === \":\") {\n nextCharacter(tokenizer);\n }\n\n const port: string = readUntilCharacter(tokenizer, \"/\", \"?\");\n tokenizer._currentToken = URLToken.port(port);\n\n if (!hasCurrentCharacter(tokenizer)) {\n tokenizer._currentState = \"DONE\";\n } else if (getCurrentCharacter(tokenizer) === \"/\") {\n tokenizer._currentState = \"PATH\";\n } else {\n tokenizer._currentState = \"QUERY\";\n }\n}\n\nfunction nextPath(tokenizer: URLTokenizer): void {\n const path: string = readUntilCharacter(tokenizer, \"?\");\n tokenizer._currentToken = URLToken.path(path);\n\n if (!hasCurrentCharacter(tokenizer)) {\n tokenizer._currentState = \"DONE\";\n } else {\n tokenizer._currentState = \"QUERY\";\n }\n}\n\nfunction nextQuery(tokenizer: URLTokenizer): void {\n if (getCurrentCharacter(tokenizer) === \"?\") {\n nextCharacter(tokenizer);\n }\n\n const query: string = readRemaining(tokenizer);\n tokenizer._currentToken = URLToken.query(query);\n tokenizer._currentState = \"DONE\";\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { HttpOperationResponse } from \"../httpOperationResponse\";\nimport { URLBuilder } from \"../url\";\nimport { WebResource } from \"../webResource\";\nimport { BaseRequestPolicy, RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from \"./requestPolicy\";\n\nexport function redirectPolicy(maximumRetries = 20): RequestPolicyFactory {\n return {\n create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions) => {\n return new RedirectPolicy(nextPolicy, options, maximumRetries);\n }\n };\n}\n\nexport class RedirectPolicy extends BaseRequestPolicy {\n constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, readonly maxRetries = 20) {\n super(nextPolicy, options);\n }\n\n public sendRequest(request: WebResource): Promise<HttpOperationResponse> {\n return this._nextPolicy.sendRequest(request).then(response => handleRedirect(this, response, 0));\n }\n}\n\nfunction handleRedirect(policy: RedirectPolicy, response: HttpOperationResponse, currentRetries: number): Promise<HttpOperationResponse> {\n const { request, status } = response;\n const 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\n const builder = URLBuilder.parse(request.url);\n builder.setPath(locationHeader);\n request.url = builder.toString();\n\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\n return policy._nextPolicy.sendRequest(request)\n .then(res => handleRedirect(policy, res, currentRetries + 1));\n }\n\n return Promise.resolve(response);\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\nimport { HttpOperationResponse } from \"../httpOperationResponse\";\nimport * as utils from \"../util/utils\";\nimport { WebResource } from \"../webResource\";\nimport { BaseRequestPolicy, RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from \"./requestPolicy\";\n\nexport function rpRegistrationPolicy(retryTimeout = 30): RequestPolicyFactory {\n return {\n create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions) => {\n return new RPRegistrationPolicy(nextPolicy, options, retryTimeout);\n }\n };\n}\n\nexport class RPRegistrationPolicy extends BaseRequestPolicy {\n constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, readonly _retryTimeout = 30) {\n super(nextPolicy, options);\n }\n\n public sendRequest(request: WebResource): Promise<HttpOperationResponse> {\n return this._nextPolicy.sendRequest(request.clone())\n .then(response => registerIfNeeded(this, request, response));\n }\n}\n\n\nfunction registerIfNeeded(policy: RPRegistrationPolicy, request: WebResource, response: HttpOperationResponse): Promise<HttpOperationResponse> {\n if (response.status === 409) {\n const rpName = checkRPNotRegisteredError(response.bodyAsText as string);\n if (rpName) {\n const 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(() => false)\n .then(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\", utils.generateUuid());\n return policy._nextPolicy.sendRequest(request.clone());\n }\n return response;\n });\n }\n }\n\n return Promise.resolve(response);\n}\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: WebResource, reuseUrlToo = false): WebResource {\n const reqOptions: WebResource = originalRequest.clone();\n if (reuseUrlToo) {\n reqOptions.url = originalRequest.url;\n }\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\", utils.generateUuid());\n\n // Set content-type to application/json\n reqOptions.headers.set(\"Content-Type\", \"application/json; charset=utf-8\");\n\n return reqOptions;\n}\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: string): string {\n let result, responseBody;\n if (body) {\n try {\n responseBody = JSON.parse(body);\n } catch (err) {\n // do nothing;\n }\n if (responseBody && responseBody.error && responseBody.error.message &&\n responseBody.error.code && responseBody.error.code === \"MissingSubscriptionRegistration\") {\n const matchRes = responseBody.error.message.match(/.*'(.*)'/i);\n if (matchRes) {\n result = matchRes.pop();\n }\n }\n }\n return result;\n}\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: string): string {\n let result;\n const matchRes = url.match(/.*\\/subscriptions\\/[a-f0-9-]+\\//ig);\n if (matchRes && matchRes[0]) {\n result = matchRes[0];\n } else {\n throw new Error(`Unable to extract subscriptionId from the given url - ${url}.`);\n }\n return result;\n}\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: RPRegistrationPolicy, urlPrefix: string, provider: string, originalRequest: WebResource): Promise<boolean> {\n const postUrl = `${urlPrefix}providers/${provider}/register?api-version=2016-02-01`;\n const getUrl = `${urlPrefix}providers/${provider}?api-version=2016-02-01`;\n const reqOptions = getRequestEssentials(originalRequest);\n reqOptions.method = \"POST\";\n reqOptions.url = postUrl;\n\n return policy._nextPolicy.sendRequest(reqOptions)\n .then(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/**\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<boolean>} True if RP Registration is successful.\n */\nfunction getRegistrationStatus(policy: RPRegistrationPolicy, url: string, originalRequest: WebResource): Promise<boolean> {\n const reqOptions: any = getRequestEssentials(originalRequest);\n reqOptions.url = url;\n reqOptions.method = \"GET\";\n\n return policy._nextPolicy.sendRequest(reqOptions).then(res => {\n const obj = (res.parsedBody as any);\n if (res.parsedBody && obj.registrationState && obj.registrationState === \"Registered\") {\n return true;\n } else {\n return utils.delay(policy._retryTimeout * 1000).then(() => getRegistrationStatus(policy, url, originalRequest));\n }\n });\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { AccessToken } from \"@azure/core-auth\";\n\n/**\n * Defines the default token refresh buffer duration.\n */\nexport const TokenRefreshBufferMs = 2 * 60 * 1000; // 2 Minutes\n\n/**\n * Provides a cache for an AccessToken that was that\n * was returned from a TokenCredential.\n */\nexport interface AccessTokenCache {\n /**\n * Sets the cached token.\n *\n * @param The {@link AccessToken} to be cached or null to\n * clear the cached token.\n */\n setCachedToken(accessToken: AccessToken | undefined): void;\n\n /**\n * Returns the cached {@link AccessToken} or undefined if nothing is cached.\n */\n getCachedToken(): AccessToken | undefined;\n}\n\n/**\n * Provides an {@link AccessTokenCache} implementation which clears\n * the cached {@link AccessToken}'s after the expiresOnTimestamp has\n * passed.\n */\nexport class ExpiringAccessTokenCache implements AccessTokenCache {\n private tokenRefreshBufferMs: number;\n private cachedToken?: AccessToken = undefined;\n\n /**\n * Constructs an instance of {@link ExpiringAccessTokenCache} with\n * an optional expiration buffer time.\n */\n constructor(tokenRefreshBufferMs: number = TokenRefreshBufferMs) {\n this.tokenRefreshBufferMs = tokenRefreshBufferMs;\n }\n\n setCachedToken(accessToken: AccessToken | undefined): void {\n this.cachedToken = accessToken;\n }\n\n getCachedToken(): AccessToken | undefined {\n if (\n this.cachedToken &&\n Date.now() + this.tokenRefreshBufferMs >= this.cachedToken.expiresOnTimestamp\n ) {\n this.cachedToken = undefined;\n }\n\n return this.cachedToken;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { TokenCredential, GetTokenOptions } from \"@azure/core-auth\";\nimport { BaseRequestPolicy, RequestPolicy, RequestPolicyOptions, RequestPolicyFactory } from \"../policies/requestPolicy\";\nimport { Constants } from \"../util/constants\";\nimport { HttpOperationResponse } from \"../httpOperationResponse\";\nimport { HttpHeaders, } from \"../httpHeaders\";\nimport { WebResource } from \"../webResource\";\nimport { AccessTokenCache, ExpiringAccessTokenCache } from \"../credentials/accessTokenCache\";\n\n/**\n * Creates a new BearerTokenAuthenticationPolicy factory.\n *\n * @param credential The TokenCredential implementation that can supply the bearer token.\n * @param scopes The scopes for which the bearer token applies.\n */\nexport function bearerTokenAuthenticationPolicy(credential: TokenCredential, scopes: string | string[]): RequestPolicyFactory {\n const tokenCache: AccessTokenCache = new ExpiringAccessTokenCache();\n return {\n create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions) => {\n return new BearerTokenAuthenticationPolicy(nextPolicy, options, credential, scopes, tokenCache);\n }\n };\n}\n\n/**\n *\n * Provides a RequestPolicy that can request a token from a TokenCredential\n * implementation and then apply it to the Authorization header of a request\n * as a Bearer token.\n *\n */\nexport class BearerTokenAuthenticationPolicy extends BaseRequestPolicy {\n /**\n * Creates a new BearerTokenAuthenticationPolicy object.\n *\n * @param nextPolicy The next RequestPolicy in the request pipeline.\n * @param options Options for this RequestPolicy.\n * @param credential The TokenCredential implementation that can supply the bearer token.\n * @param scopes The scopes for which the bearer token applies.\n * @param tokenCache The cache for the most recent AccessToken returned from the TokenCredential.\n */\n constructor(\n nextPolicy: RequestPolicy,\n options: RequestPolicyOptions,\n private credential: TokenCredential,\n private scopes: string | string[],\n private tokenCache: AccessTokenCache\n ) {\n super(nextPolicy, options);\n }\n\n /**\n * Applies the Bearer token to the request through the Authorization header.\n * @param webResource\n */\n public async sendRequest(\n webResource: WebResource\n ): Promise<HttpOperationResponse> {\n if (!webResource.headers) webResource.headers = new HttpHeaders();\n const token = await this.getToken({\n abortSignal: webResource.abortSignal\n });\n webResource.headers.set(\n Constants.HeaderConstants.AUTHORIZATION,\n `Bearer ${token}`\n );\n return this._nextPolicy.sendRequest(webResource);\n }\n\n private async getToken(options: GetTokenOptions): Promise<string | undefined> {\n let accessToken = this.tokenCache.getCachedToken();\n if (accessToken === undefined) {\n accessToken = await this.credential.getToken(this.scopes, options) || undefined;\n this.tokenCache.setCachedToken(accessToken);\n }\n\n return accessToken ? accessToken.token : undefined;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { HttpOperationResponse } from \"../httpOperationResponse\";\nimport * as utils from \"../util/utils\";\nimport { WebResource } from \"../webResource\";\nimport { BaseRequestPolicy, RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from \"./requestPolicy\";\n\nexport interface RetryData {\n retryCount: number;\n retryInterval: number;\n error?: RetryError;\n}\n\nexport interface RetryError extends Error {\n message: string;\n code?: string;\n innerError?: RetryError;\n}\n\nexport function systemErrorRetryPolicy(retryCount?: number, retryInterval?: number, minRetryInterval?: number, maxRetryInterval?: number): RequestPolicyFactory {\n return {\n create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions) => {\n return new SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval);\n }\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 */\nexport class SystemErrorRetryPolicy extends BaseRequestPolicy {\n retryCount: number;\n retryInterval: number;\n minRetryInterval: number;\n maxRetryInterval: number;\n DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30;\n DEFAULT_CLIENT_RETRY_COUNT = 3;\n DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90;\n DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3;\n\n constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, retryCount?: number, retryInterval?: number, minRetryInterval?: number, maxRetryInterval?: number) {\n super(nextPolicy, options);\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 }\n\n public sendRequest(request: WebResource): Promise<HttpOperationResponse> {\n return this._nextPolicy.sendRequest(request.clone()).then(response => retry(this, request, response));\n }\n}\n\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(policy: SystemErrorRetryPolicy, retryData: RetryData): boolean {\n let currentCount;\n if (!retryData) {\n throw new Error(\"retryData for the SystemErrorRetryPolicyFilter cannot be null.\");\n } else {\n currentCount = (retryData && retryData.retryCount);\n }\n return (currentCount < policy.retryCount);\n}\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(policy: SystemErrorRetryPolicy, retryData?: RetryData, err?: RetryError): RetryData {\n if (!retryData) {\n retryData = {\n retryCount: 0,\n retryInterval: 0\n };\n }\n\n if (err) {\n if (retryData.error) {\n err.innerError = retryData.error;\n }\n\n retryData.error = err;\n }\n\n // Adjust retry count\n retryData.retryCount++;\n\n // Adjust retry interval\n let incrementDelta = Math.pow(2, retryData.retryCount) - 1;\n const boundedRandDelta = policy.retryInterval * 0.8 +\n Math.floor(Math.random() * (policy.retryInterval * 1.2 - policy.retryInterval * 0.8));\n incrementDelta *= boundedRandDelta;\n\n retryData.retryInterval = Math.min(policy.minRetryInterval + incrementDelta, policy.maxRetryInterval);\n\n return retryData;\n}\n\nfunction retry(policy: SystemErrorRetryPolicy, request: WebResource, operationResponse: HttpOperationResponse, retryData?: RetryData, err?: RetryError): Promise<HttpOperationResponse> {\n retryData = updateRetryData(policy, retryData, err);\n if (err && err.code && shouldRetry(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 utils.delay(retryData.retryInterval)\n .then(() => policy._nextPolicy.sendRequest(request.clone()))\n .then(res => retry(policy, request, res, retryData, err))\n .catch(err => retry(policy, request, operationResponse, retryData, err));\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","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/**\n * The format that will be used to join an array of values together for a query parameter value.\n */\nexport enum QueryCollectionFormat {\n Csv = \",\",\n Ssv = \" \",\n Tsv = \"\\t\",\n Pipes = \"|\",\n Multi = \"Multi\",\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { ProxySettings } from \"../serviceClient\";\nimport { BaseRequestPolicy, RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from \"./requestPolicy\";\nimport { HttpOperationResponse } from \"../httpOperationResponse\";\nimport { WebResource } from \"../webResource\";\n\nconst proxyNotSupportedInBrowser = new Error(\"ProxyPolicy is not supported in browser environment\");\n\nexport function getDefaultProxySettings(_proxyUrl?: string): ProxySettings | undefined {\n return undefined;\n}\n\nexport function proxyPolicy(_proxySettings?: ProxySettings): RequestPolicyFactory {\n return {\n create: (_nextPolicy: RequestPolicy, _options: RequestPolicyOptions) => {\n throw proxyNotSupportedInBrowser;\n }\n };\n}\n\nexport class ProxyPolicy extends BaseRequestPolicy {\n constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions) {\n super(nextPolicy, options);\n throw proxyNotSupportedInBrowser;\n }\n\n public sendRequest(_request: WebResource): Promise<HttpOperationResponse> {\n throw proxyNotSupportedInBrowser;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { BaseRequestPolicy, RequestPolicy, RequestPolicyOptions, RequestPolicyFactory } from \"./requestPolicy\";\nimport { WebResource } from \"../webResource\";\nimport { HttpOperationResponse } from \"../httpOperationResponse\";\nimport { Constants } from \"../util/constants\";\nimport { delay } from \"../util/utils\";\n\ntype ResponseHandler = (httpRequest: WebResource, response: HttpOperationResponse) => Promise<HttpOperationResponse>;\nconst StatusCodes = Constants.HttpConstants.StatusCodes;\n\nexport function throttlingRetryPolicy(): RequestPolicyFactory {\n return {\n create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions) => {\n return new ThrottlingRetryPolicy(nextPolicy, options);\n }\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 */\nexport class ThrottlingRetryPolicy extends BaseRequestPolicy {\n private _handleResponse: ResponseHandler;\n\n constructor(nextPolicy: RequestPolicy, options: RequestPolicyOptions, _handleResponse?: ResponseHandler) {\n super(nextPolicy, options);\n this._handleResponse = _handleResponse || this._defaultResponseHandler;\n }\n\n public async sendRequest(httpRequest: WebResource): Promise<HttpOperationResponse> {\n return this._nextPolicy.sendRequest(httpRequest.clone()).then(response => {\n if (response.status !== StatusCodes.TooManyRequests) {\n return response;\n } else {\n return this._handleResponse(httpRequest, response);\n }\n });\n }\n\n private async _defaultResponseHandler(httpRequest: WebResource, httpResponse: HttpOperationResponse): Promise<HttpOperationResponse> {\n const retryAfterHeader: string | undefined = httpResponse.headers.get(Constants.HeaderConstants.RETRY_AFTER);\n\n if (retryAfterHeader) {\n const delayInMs: number | undefined = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader);\n if (delayInMs) {\n return delay(delayInMs).then((_: any) => this._nextPolicy.sendRequest(httpRequest));\n }\n }\n\n return httpResponse;\n }\n\n public static parseRetryAfterHeader(headerValue: string): number | undefined {\n const retryAfterInSeconds = Number(headerValue);\n if (Number.isNaN(retryAfterInSeconds)) {\n return ThrottlingRetryPolicy.parseDateRetryAfterHeader(headerValue);\n } else {\n return retryAfterInSeconds * 1000;\n }\n }\n\n public static parseDateRetryAfterHeader(headerValue: string): number | undefined {\n try {\n const now: number = Date.now();\n const date: number = Date.parse(headerValue);\n const diff = date - now;\n\n return Number.isNaN(diff) ? undefined : diff;\n } catch (error) {\n return undefined;\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { TokenCredential, isTokenCredential } from \"@azure/core-auth\";\nimport { DefaultHttpClient } from \"./defaultHttpClient\";\nimport { HttpClient } from \"./httpClient\";\nimport { HttpOperationResponse, RestResponse } from \"./httpOperationResponse\";\nimport { HttpPipelineLogger } from \"./httpPipelineLogger\";\nimport { OperationArguments } from \"./operationArguments\";\nimport { getPathStringFromParameter, getPathStringFromParameterPath, OperationParameter, ParameterPath } from \"./operationParameter\";\nimport { isStreamOperation, OperationSpec } from \"./operationSpec\";\nimport { deserializationPolicy, DeserializationContentTypes } from \"./policies/deserializationPolicy\";\nimport { exponentialRetryPolicy } from \"./policies/exponentialRetryPolicy\";\nimport { generateClientRequestIdPolicy } from \"./policies/generateClientRequestIdPolicy\";\nimport { userAgentPolicy, getDefaultUserAgentHeaderName, getDefaultUserAgentValue } from \"./policies/userAgentPolicy\";\nimport { redirectPolicy } from \"./policies/redirectPolicy\";\nimport { RequestPolicy, RequestPolicyFactory, RequestPolicyOptions } from \"./policies/requestPolicy\";\nimport { rpRegistrationPolicy } from \"./policies/rpRegistrationPolicy\";\nimport { bearerTokenAuthenticationPolicy } from \"./policies/bearerTokenAuthenticationPolicy\";\nimport { systemErrorRetryPolicy } from \"./policies/systemErrorRetryPolicy\";\nimport { QueryCollectionFormat } from \"./queryCollectionFormat\";\nimport { CompositeMapper, DictionaryMapper, Mapper, MapperType, Serializer } from \"./serializer\";\nimport { URLBuilder } from \"./url\";\nimport * as utils from \"./util/utils\";\nimport { stringifyXML } from \"./util/xml\";\nimport { RequestOptionsBase, RequestPrepareOptions, WebResource } from \"./webResource\";\nimport { OperationResponse } from \"./operationResponse\";\nimport { ServiceCallback } from \"./util/utils\";\nimport { proxyPolicy, getDefaultProxySettings } from \"./policies/proxyPolicy\";\nimport { throttlingRetryPolicy } from \"./policies/throttlingRetryPolicy\";\n\n\n/**\n * HTTP proxy settings (Node.js only)\n */\nexport interface ProxySettings {\n host: string;\n port: number;\n username?: string;\n password?: string;\n}\n\n/**\n * Options to be provided while creating the client.\n */\nexport interface ServiceClientOptions {\n /**\n * An array of factories which get called to create the RequestPolicy pipeline used to send a HTTP\n * request on the wire, or a function that takes in the defaultRequestPolicyFactories and returns\n * the requestPolicyFactories that will be used.\n */\n requestPolicyFactories?: RequestPolicyFactory[] | ((defaultRequestPolicyFactories: RequestPolicyFactory[]) => (void | RequestPolicyFactory[]));\n /**\n * The HttpClient that will be used to send HTTP requests.\n */\n httpClient?: HttpClient;\n /**\n * The HttpPipelineLogger that can be used to debug RequestPolicies within the HTTP pipeline.\n */\n httpPipelineLogger?: HttpPipelineLogger;\n /**\n * If set to true, turn off the default retry policy.\n */\n noRetryPolicy?: boolean;\n /**\n * Gets or sets the retry timeout in seconds for AutomaticRPRegistration. Default value is 30.\n */\n rpRegistrationRetryTimeout?: number;\n /**\n * Whether or not to generate a client request ID header for each HTTP request.\n */\n generateClientRequestIdHeader?: boolean;\n /**\n * Whether to include credentials in CORS requests in the browser.\n * See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials for more information.\n */\n withCredentials?: boolean;\n /**\n * If specified, a GenerateRequestIdPolicy will be added to the HTTP pipeline that will add a\n * header to all outgoing requests with this header name and a random UUID as the request ID.\n */\n clientRequestIdHeaderName?: string;\n /**\n * The content-types that will be associated with JSON or XML serialization.\n */\n deserializationContentTypes?: DeserializationContentTypes;\n /**\n * The header name to use for the telemetry header while sending the request. If this is not\n * specified, then \"User-Agent\" will be used when running on Node.js and \"x-ms-command-name\" will\n * be used when running in a browser.\n */\n userAgentHeaderName?: string | ((defaultUserAgentHeaderName: string) => string);\n /**\n * The string to be set to the telemetry header while sending the request, or a function that\n * takes in the default user-agent string and returns the user-agent string that will be used.\n */\n userAgent?: string | ((defaultUserAgent: string) => string);\n /**\n * Proxy settings which will be used for every HTTP request (Node.js only).\n */\n proxySettings?: ProxySettings;\n}\n\n/**\n * @class\n * Initializes a new instance of the ServiceClient.\n */\nexport class ServiceClient {\n /**\n * If specified, this is the base URI that requests will be made against for this ServiceClient.\n * If it is not specified, then all OperationSpecs must contain a baseUrl property.\n */\n protected baseUri?: string;\n\n /**\n * The default request content type for the service.\n * Used if no requestContentType is present on an OperationSpec.\n */\n protected requestContentType?: string;\n\n\n /**\n * The HTTP client that will be used to send requests.\n */\n private readonly _httpClient: HttpClient;\n private readonly _requestPolicyOptions: RequestPolicyOptions;\n\n private readonly _requestPolicyFactories: RequestPolicyFactory[];\n private readonly _withCredentials: boolean;\n\n /**\n * The ServiceClient constructor\n * @constructor\n * @param {TokenCredential} [credentials] The credentials object used for authentication.\n * @param {ServiceClientOptions} [options] The service client options that govern the behavior of the client.\n */\n constructor(credentials?: TokenCredential, options?: ServiceClientOptions) {\n if (!options) {\n options = {};\n }\n\n this._withCredentials = options.withCredentials || false;\n this._httpClient = options.httpClient || new DefaultHttpClient();\n this._requestPolicyOptions = new RequestPolicyOptions(options.httpPipelineLogger);\n\n let requestPolicyFactories: RequestPolicyFactory[];\n if (Array.isArray(options.requestPolicyFactories)) {\n requestPolicyFactories = options.requestPolicyFactories;\n } else {\n let authPolicyFactory: RequestPolicyFactory | undefined = undefined;\n if (isTokenCredential(credentials)) {\n // Create a wrapped RequestPolicyFactory here so that we can provide the\n // correct scope to the BearerTokenAuthenticationPolicy at the first time\n // one is requested. This is needed because generated ServiceClient\n // implementations do not set baseUri until after ServiceClient's constructor\n // is finished, leaving baseUri empty at the time when it is needed to\n // build the correct scope name.\n const wrappedPolicyFactory: () => RequestPolicyFactory = () => {\n let bearerTokenPolicyFactory: RequestPolicyFactory | undefined = undefined;\n let serviceClient = this;\n return {\n create(nextPolicy: RequestPolicy, options: RequestPolicyOptions): RequestPolicy {\n if (bearerTokenPolicyFactory === undefined) {\n bearerTokenPolicyFactory = bearerTokenAuthenticationPolicy(credentials, `${serviceClient.baseUri || \"\"}/.default`)\n }\n\n return bearerTokenPolicyFactory.create(nextPolicy, options);\n }\n }\n };\n\n authPolicyFactory = wrappedPolicyFactory();\n } else if (credentials !== undefined) {\n throw new Error(\"The credentials argument must implement the TokenCredential interface\");\n }\n\n requestPolicyFactories = createDefaultRequestPolicyFactories(authPolicyFactory, options);\n if (options.requestPolicyFactories) {\n // options.requestPolicyFactories can also be a function that manipulates\n // the default requestPolicyFactories array\n const newRequestPolicyFactories: void | RequestPolicyFactory[] = options.requestPolicyFactories(requestPolicyFactories);\n if (newRequestPolicyFactories) {\n requestPolicyFactories = newRequestPolicyFactories;\n }\n }\n }\n this._requestPolicyFactories = requestPolicyFactories;\n }\n\n /**\n * Send the provided httpRequest.\n */\n sendRequest(options: RequestPrepareOptions | WebResource): Promise<HttpOperationResponse> {\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\n let httpRequest: WebResource;\n try {\n if (options instanceof WebResource) {\n options.validateRequestProperties();\n httpRequest = options;\n } else {\n httpRequest = new WebResource();\n httpRequest = httpRequest.prepare(options);\n }\n } catch (error) {\n return Promise.reject(error);\n }\n\n let httpPipeline: RequestPolicy = this._httpClient;\n if (this._requestPolicyFactories && this._requestPolicyFactories.length > 0) {\n for (let 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 /**\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 sendOperationRequest(operationArguments: OperationArguments, operationSpec: OperationSpec, callback?: ServiceCallback<any>): Promise<RestResponse> {\n if (typeof operationArguments.options === \"function\") {\n callback = operationArguments.options;\n operationArguments.options = undefined;\n }\n\n const httpRequest = new WebResource();\n\n let result: Promise<RestResponse>;\n try {\n const baseUri: string | undefined = 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\n httpRequest.method = operationSpec.httpMethod;\n httpRequest.operationSpec = operationSpec;\n\n const requestUrl: URLBuilder = URLBuilder.parse(baseUri);\n if (operationSpec.path) {\n requestUrl.appendPath(operationSpec.path);\n }\n if (operationSpec.urlParameters && operationSpec.urlParameters.length > 0) {\n for (const urlParameter of operationSpec.urlParameters) {\n let urlParameterValue: string = 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 (const queryParameter of operationSpec.queryParameters) {\n let queryParameterValue: any = 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 === QueryCollectionFormat.Multi) {\n if (queryParameterValue.length === 0) {\n queryParameterValue = \"\";\n } else {\n for (const index in queryParameterValue) {\n const item = queryParameterValue[index];\n queryParameterValue[index] = item == undefined ? \"\" : item.toString();\n }\n }\n } else {\n queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat);\n }\n }\n if (!queryParameter.skipEncoding) {\n if (Array.isArray(queryParameterValue)) {\n for (const 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\n const contentType = operationSpec.contentType || this.requestContentType;\n if (contentType) {\n httpRequest.headers.set(\"Content-Type\", contentType);\n }\n\n if (operationSpec.headerParameters) {\n for (const headerParameter of operationSpec.headerParameters) {\n let headerValue: any = getOperationArgumentValueFromParameter(this, operationArguments, headerParameter, operationSpec.serializer);\n if (headerValue != undefined) {\n headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter));\n const headerCollectionPrefix = (headerParameter.mapper as DictionaryMapper).headerCollectionPrefix;\n if (headerCollectionPrefix) {\n for (const key of Object.keys(headerValue)) {\n httpRequest.headers.set(headerCollectionPrefix + key, headerValue[key]);\n }\n } else {\n httpRequest.headers.set(headerParameter.mapper.serializedName || getPathStringFromParameter(headerParameter), headerValue);\n }\n }\n }\n }\n\n const options: RequestOptionsBase | undefined = operationArguments.options;\n if (options) {\n if (options.customHeaders) {\n for (const customHeaderName in options.customHeaders) {\n httpRequest.headers.set(customHeaderName, options.customHeaders[customHeaderName]);\n }\n }\n\n if (options.abortSignal) {\n httpRequest.abortSignal = options.abortSignal;\n }\n\n if (options.timeout) {\n httpRequest.timeout = options.timeout;\n }\n\n if (options.onUploadProgress) {\n httpRequest.onUploadProgress = options.onUploadProgress;\n }\n\n if (options.onDownloadProgress) {\n httpRequest.onDownloadProgress = options.onDownloadProgress;\n }\n }\n\n httpRequest.withCredentials = this._withCredentials;\n\n serializeRequestBody(this, httpRequest, operationArguments, operationSpec);\n\n if (httpRequest.streamResponseBody == undefined) {\n httpRequest.streamResponseBody = isStreamOperation(operationSpec);\n }\n\n result = this.sendRequest(httpRequest)\n .then(res => flattenResponse(res, operationSpec.responses[res.status]));\n } catch (error) {\n result = Promise.reject(error);\n }\n\n const cb = callback;\n if (cb) {\n result\n // tslint:disable-next-line:no-null-keyword\n .then(res => cb(null, res._response.parsedBody, res._response.request, res._response))\n .catch(err => cb(err));\n }\n\n return result;\n }\n}\n\nexport function serializeRequestBody(serviceClient: ServiceClient, httpRequest: WebResource, operationArguments: OperationArguments, operationSpec: OperationSpec): void {\n if (operationSpec.requestBody && operationSpec.requestBody.mapper) {\n httpRequest.body = getOperationArgumentValueFromParameter(serviceClient, operationArguments, operationSpec.requestBody, operationSpec.serializer);\n\n const bodyMapper = operationSpec.requestBody.mapper;\n const { required, xmlName, xmlElementName, serializedName } = bodyMapper;\n const typeName = bodyMapper.type.name;\n try {\n if (httpRequest.body != undefined || required) {\n const requestBodyParameterPathString: string = getPathStringFromParameter(operationSpec.requestBody);\n httpRequest.body = operationSpec.serializer.serialize(bodyMapper, httpRequest.body, requestBodyParameterPathString);\n const isStream = typeName === MapperType.Stream;\n if (operationSpec.isXML) {\n if (typeName === MapperType.Sequence) {\n httpRequest.body = stringifyXML(utils.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 } else if (!isStream) {\n httpRequest.body = JSON.stringify(httpRequest.body);\n }\n }\n } catch (error) {\n throw new Error(`Error \"${error.message}\" occurred in serializing the payload - ${JSON.stringify(serializedName, undefined, \" \")}.`);\n }\n } else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) {\n httpRequest.formData = {};\n for (const formDataParameter of operationSpec.formDataParameters) {\n const formDataParameterValue: any = getOperationArgumentValueFromParameter(serviceClient, operationArguments, formDataParameter, operationSpec.serializer);\n if (formDataParameterValue != undefined) {\n const formDataParameterPropertyName: string = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter);\n httpRequest.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter));\n }\n }\n }\n}\n\nfunction getValueOrFunctionResult(value: undefined | string | ((defaultValue: string) => string), defaultValueCreator: (() => string)): string {\n let result: string;\n if (typeof value === \"string\") {\n result = value;\n } else {\n result = defaultValueCreator();\n if (typeof value === \"function\") {\n result = value(result);\n }\n }\n return result;\n}\n\nfunction createDefaultRequestPolicyFactories(authPolicyFactory: RequestPolicyFactory | undefined, options: ServiceClientOptions): RequestPolicyFactory[] {\n const factories: RequestPolicyFactory[] = [];\n\n if (options.generateClientRequestIdHeader) {\n factories.push(generateClientRequestIdPolicy(options.clientRequestIdHeaderName));\n }\n\n if (authPolicyFactory) {\n factories.push(authPolicyFactory);\n }\n\n const userAgentHeaderName: string = getValueOrFunctionResult(options.userAgentHeaderName, getDefaultUserAgentHeaderName);\n const userAgentHeaderValue: string = 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\n if (!options.noRetryPolicy) {\n factories.push(exponentialRetryPolicy());\n factories.push(systemErrorRetryPolicy());\n factories.push(throttlingRetryPolicy());\n }\n\n factories.push(deserializationPolicy(options.deserializationContentTypes));\n\n const proxySettings = options.proxySettings || getDefaultProxySettings();\n if (proxySettings) {\n factories.push(proxyPolicy(proxySettings));\n }\n\n return factories;\n}\n\nexport type PropertyParent = { [propertyName: string]: any };\n\n/**\n * Get the property parent for the property at the provided path when starting with the provided\n * parent object.\n */\nexport function getPropertyParent(parent: PropertyParent, propertyPath: string[]): PropertyParent {\n if (parent && propertyPath) {\n const propertyPathLength: number = propertyPath.length;\n for (let i = 0; i < propertyPathLength - 1; ++i) {\n const propertyName: string = propertyPath[i];\n if (!parent[propertyName]) {\n parent[propertyName] = {};\n }\n parent = parent[propertyName];\n }\n }\n return parent;\n}\n\nfunction getOperationArgumentValueFromParameter(serviceClient: ServiceClient, operationArguments: OperationArguments, parameter: OperationParameter, serializer: Serializer): any {\n return getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameter.parameterPath, parameter.mapper, serializer);\n}\n\nexport function getOperationArgumentValueFromParameterPath(serviceClient: ServiceClient, operationArguments: OperationArguments, parameterPath: ParameterPath, parameterMapper: Mapper, serializer: Serializer): any {\n let value: any;\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 } else {\n let propertySearchResult: PropertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath);\n if (!propertySearchResult.propertyFound) {\n propertySearchResult = getPropertyFromParameterPath(serviceClient, parameterPath);\n }\n\n let 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\n // Serialize just for validation purposes.\n const parameterPathString: string = getPathStringFromParameterPath(parameterPath, parameterMapper);\n serializer.serialize(parameterMapper, value, parameterPathString);\n }\n } else {\n if (parameterMapper.required) {\n value = {};\n }\n\n for (const propertyName in parameterPath) {\n const propertyMapper: Mapper = (parameterMapper as CompositeMapper).type.modelProperties![propertyName];\n const propertyPath: ParameterPath = parameterPath[propertyName];\n const propertyValue: any = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, propertyPath, propertyMapper, serializer);\n // Serialize just for validation purposes.\n const propertyPathString: string = 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}\n\ninterface PropertySearchResult {\n propertyValue?: any;\n propertyFound: boolean;\n}\n\nfunction getPropertyFromParameterPath(parent: { [parameterName: string]: any }, parameterPath: string[]): PropertySearchResult {\n const result: PropertySearchResult = { propertyFound: false };\n let i = 0;\n for (; i < parameterPath.length; ++i) {\n const parameterPathPart: string = 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 } else {\n break;\n }\n }\n if (i === parameterPath.length) {\n result.propertyValue = parent;\n result.propertyFound = true;\n }\n return result;\n}\n\nexport function flattenResponse(_response: HttpOperationResponse, responseSpec: OperationResponse | undefined): RestResponse {\n const parsedHeaders = _response.parsedHeaders;\n const bodyMapper = responseSpec && responseSpec.bodyMapper;\n\n const addOperationResponse = (obj: {}) =>\n Object.defineProperty(obj, \"_response\", {\n value: _response\n });\n\n if (bodyMapper) {\n const typeName = bodyMapper.type.name;\n if (typeName === \"Stream\") {\n return addOperationResponse({\n ...parsedHeaders,\n blobBody: _response.blobBody,\n readableStreamBody: _response.readableStreamBody\n });\n }\n\n const modelProperties = typeName === \"Composite\" && (bodyMapper as CompositeMapper).type.modelProperties || {};\n const isPageableResponse = Object.keys(modelProperties).some(k => modelProperties[k].serializedName === \"\");\n if (typeName === \"Sequence\" || isPageableResponse) {\n const arrayResponse = [...(_response.parsedBody || [])] as RestResponse & any[];\n\n for (const key of Object.keys(modelProperties)) {\n if (modelProperties[key].serializedName) {\n arrayResponse[key] = _response.parsedBody[key];\n }\n }\n\n if (parsedHeaders) {\n for (const key of Object.keys(parsedHeaders)) {\n arrayResponse[key] = parsedHeaders[key];\n }\n }\n addOperationResponse(arrayResponse);\n return arrayResponse;\n }\n\n if (typeName === \"Composite\" || typeName === \"Dictionary\") {\n return addOperationResponse({\n ...parsedHeaders,\n ..._response.parsedBody\n });\n }\n }\n\n if (bodyMapper || _response.request.method === \"HEAD\") {\n // primitive body types and HEAD booleans\n return addOperationResponse({\n ...parsedHeaders,\n body: _response.parsedBody\n });\n }\n\n return addOperationResponse({\n ...parsedHeaders,\n ..._response.parsedBody\n });\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport qs from \"qs\";\nimport {\n AccessToken,\n ServiceClient,\n ServiceClientOptions,\n WebResource,\n RequestPrepareOptions,\n GetTokenOptions\n} from \"@azure/core-http\";\nimport { AuthenticationError } from \"./errors\";\n\nconst DefaultAuthorityHost = \"https://login.microsoftonline.com\";\n\n/**\n * An internal type used to communicate details of a token request's\n * response that should not be sent back as part of the AccessToken.\n */\nexport interface TokenResponse {\n /**\n * The AccessToken to be returned from getToken.\n */\n accessToken: AccessToken,\n\n /**\n * The refresh token if the 'offline_access' scope was used.\n */\n refreshToken?: string\n}\n\nexport class IdentityClient extends ServiceClient {\n public authorityHost: string;\n\n constructor(options?: IdentityClientOptions) {\n options = options || IdentityClient.getDefaultOptions();\n super(undefined, options);\n\n this.baseUri = this.authorityHost = options.authorityHost || DefaultAuthorityHost;\n\n if (!this.baseUri.startsWith(\"https:\")) {\n throw new Error(\"The authorityHost address must use the 'https' protocol.\");\n }\n }\n\n createWebResource(requestOptions: RequestPrepareOptions): WebResource {\n const webResource = new WebResource();\n webResource.prepare(requestOptions);\n return webResource;\n }\n\n async sendTokenRequest(\n webResource: WebResource,\n expiresOnParser?: (responseBody: any) => number,\n ): Promise<TokenResponse | null> {\n const response = await this.sendRequest(webResource);\n\n expiresOnParser = expiresOnParser || ((responseBody: any) => {\n return Date.now() + responseBody.expires_in * 1000\n });\n\n if (response.status === 200 || response.status === 201) {\n return {\n accessToken: {\n token: response.parsedBody.access_token,\n expiresOnTimestamp: expiresOnParser(response.parsedBody)\n },\n refreshToken: response.parsedBody.refresh_token,\n };\n } else {\n throw new AuthenticationError(response.status, response.parsedBody || response.bodyAsText);\n }\n }\n\n async refreshAccessToken(\n tenantId: string,\n clientId: string,\n scopes: string,\n refreshToken: string | undefined,\n clientSecret: string | undefined,\n expiresOnParser?: (responseBody: any) => number,\n options?: GetTokenOptions\n ): Promise<TokenResponse | null> {\n if (refreshToken === undefined) {\n return null;\n }\n\n const refreshParams = {\n grant_type: \"refresh_token\",\n client_id: clientId,\n refresh_token: refreshToken,\n scope: scopes\n };\n\n if (clientSecret !== undefined) {\n (refreshParams as any).client_secret = clientSecret;\n }\n\n const webResource = this.createWebResource({\n url: `${this.authorityHost}/${tenantId}/oauth2/v2.0/token`,\n method: \"POST\",\n disableJsonStringifyOnBody: true,\n deserializationMapper: undefined,\n body: qs.stringify(refreshParams),\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/x-www-form-urlencoded\"\n },\n abortSignal: options && options.abortSignal\n });\n\n try {\n return await this.sendTokenRequest(webResource, expiresOnParser);\n } catch (err) {\n if (err instanceof AuthenticationError && err.errorResponse.error === \"interaction_required\") {\n // It's likely that the refresh token has expired, so\n // return null so that the credential implementation will\n // initiate the authentication flow again.\n return null;\n } else {\n throw err;\n }\n }\n }\n\n static getDefaultOptions(): IdentityClientOptions {\n return {\n authorityHost: DefaultAuthorityHost\n };\n }\n}\n\nexport interface IdentityClientOptions extends ServiceClientOptions {\n authorityHost?: string;\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport qs from \"qs\";\nimport { TokenCredential, GetTokenOptions, AccessToken } from \"@azure/core-http\";\nimport { IdentityClientOptions, IdentityClient } from \"../client/identityClient\";\n\n/**\n * Enables authentication to Azure Active Directory using a client secret\n * that was generated for an App Registration. More information on how\n * to configure a client secret can be found here:\n *\n * https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-configure-app-access-web-apis#add-credentials-to-your-web-application\n *\n */\nexport class ClientSecretCredential implements TokenCredential {\n private identityClient: IdentityClient;\n private tenantId: string;\n private clientId: string;\n private clientSecret: string;\n\n /**\n * Creates an instance of the ClientSecretCredential with the details\n * needed to authenticate against Azure Active Directory with a client\n * secret.\n *\n * @param tenantId The Azure Active Directory tenant (directory) ID.\n * @param clientId The client (application) ID of an App Registration in the tenant.\n * @param clientSecret A client secret that was generated for the App Registration.\n * @param options Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n clientSecret: string,\n options?: IdentityClientOptions\n ) {\n this.identityClient = new IdentityClient(options);\n this.tenantId = tenantId;\n this.clientId = clientId;\n this.clientSecret = clientSecret;\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an {@link AccessToken} if\n * successful. If authentication cannot be performed at this time, this method may\n * return null. If an error occurs during authentication, an {@link AuthenticationError}\n * containing failure details will be thrown.\n *\n * @param scopes The list of scopes for which the token will have access.\n * @param options The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n const webResource = this.identityClient.createWebResource({\n url: `${this.identityClient.authorityHost}/${this.tenantId}/oauth2/v2.0/token`,\n method: \"POST\",\n disableJsonStringifyOnBody: true,\n deserializationMapper: undefined,\n body: qs.stringify({\n response_type: \"token\",\n grant_type: \"client_credentials\",\n client_id: this.clientId,\n client_secret: this.clientSecret,\n scope: typeof scopes === \"string\" ? scopes : scopes.join(\" \")\n }),\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/x-www-form-urlencoded\"\n },\n abortSignal: options && options.abortSignal\n });\n\n const tokenResponse = await this.identityClient.sendTokenRequest(webResource);\n return (tokenResponse && tokenResponse.accessToken) || null;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport { TokenCredential, GetTokenOptions, AccessToken } from \"@azure/core-http\";\nimport { IdentityClientOptions } from \"../client/identityClient\";\n\nconst BrowserNotSupportedError = new Error(\"ClientCertificateCredential is not supported in the browser.\");\n\nexport class ClientCertificateCredential implements TokenCredential {\n constructor(\n tenantId: string,\n clientId: string,\n certificatePath: string,\n options?: IdentityClientOptions\n ) {\n throw BrowserNotSupportedError;\n }\n\n public getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n throw BrowserNotSupportedError;\n }\n}\n","import { CacheLocation } from \"./Configuration\";\r\n\r\n// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\n/**\r\n * @hidden\r\n */\r\nexport class Constants {\r\n static get errorDescription(): string { return \"error_description\"; }\r\n static get error(): string { return \"error\"; }\r\n\r\n static get scope(): string { return \"scope\"; }\r\n static get clientInfo(): string { return \"client_info\"; }\r\n static get clientId(): string { return \"clientId\"; }\r\n\r\n static get idToken(): string { return \"id_token\"; }\r\n static get adalIdToken(): string { return \"adal.idtoken\"; }\r\n static get accessToken(): string { return \"access_token\"; }\r\n static get expiresIn(): string { return \"expires_in\"; }\r\n static get sessionState(): string { return \"session_state\"; }\r\n static get claims(): string { return \"claims\"; }\r\n\r\n static get msalClientInfo(): string { return \"msal.client.info\"; }\r\n static get msalError(): string { return \"msal.error\"; }\r\n static get msalErrorDescription(): string { return \"msal.error.description\"; }\r\n\r\n static get msalSessionState(): string { return \"msal.session.state\"; }\r\n static get tokenKeys(): string { return \"msal.token.keys\"; }\r\n static get accessTokenKey(): string { return \"msal.access.token.key\"; }\r\n static get expirationKey(): string { return \"msal.expiration.key\"; }\r\n static get stateLogin(): string { return \"msal.state.login\"; }\r\n static get stateAcquireToken(): string { return \"msal.state.acquireToken\"; }\r\n static get stateRenew(): string { return \"msal.state.renew\"; }\r\n static get nonceIdToken(): string { return \"msal.nonce.idtoken\"; }\r\n static get userName(): string { return \"msal.username\"; }\r\n static get idTokenKey(): string { return \"msal.idtoken\"; }\r\n static get loginRequest(): string { return \"msal.login.request\"; }\r\n static get loginError(): string { return \"msal.login.error\"; }\r\n static get renewStatus(): string { return \"msal.token.renew.status\"; }\r\n static get urlHash(): string { return \"msal.urlHash\"; }\r\n static get angularLoginRequest(): string { return \"msal.angular.login.request\"; }\r\n static get msal(): string { return \"msal\"; }\r\n\r\n static get no_account(): string { return \"NO_ACCOUNT\"; }\r\n static get consumersUtid(): string { return \"9188040d-6c67-4c5b-b112-36a304b66dad\"; }\r\n static get upn(): string { return \"upn\"; }\r\n\r\n static get prompt_select_account(): string { return \"&prompt=select_account\"; }\r\n static get prompt_none(): string { return \"&prompt=none\"; }\r\n static get prompt(): string { return \"prompt\"; }\r\n\r\n static get response_mode_fragment(): string { return \"&response_mode=fragment\"; }\r\n static get resourceDelimiter(): string { return \"|\"; }\r\n\r\n static get tokenRenewStatusCancelled(): string { return \"Canceled\"; }\r\n static get tokenRenewStatusCompleted(): string { return \"Completed\"; }\r\n static get tokenRenewStatusInProgress(): string { return \"In Progress\"; }\r\n\r\n private static _popUpWidth: number = 483;\r\n static get popUpWidth(): number { return this._popUpWidth; }\r\n static set popUpWidth(width: number) {\r\n this._popUpWidth = width;\r\n }\r\n private static _popUpHeight: number = 600;\r\n static get popUpHeight(): number { return this._popUpHeight; }\r\n static set popUpHeight(height: number) {\r\n this._popUpHeight = height;\r\n }\r\n\r\n static get login(): string { return \"LOGIN\"; }\r\n static get renewToken(): string { return \"RENEW_TOKEN\"; }\r\n static get unknown(): string { return \"UNKNOWN\"; }\r\n\r\n static get homeAccountIdentifier(): string { return \"homeAccountIdentifier\"; }\r\n\r\n static get common(): string { return \"common\"; }\r\n static get openidScope(): string { return \"openid\"; }\r\n static get profileScope(): string { return \"profile\"; }\r\n\r\n static get cacheLocationLocal(): CacheLocation { return \"localStorage\"; }\r\n static get cacheLocationSession(): CacheLocation { return \"sessionStorage\"; }\r\n}\r\n\r\n/**\r\n * @hidden\r\n */\r\nexport const CacheKeys = {\r\n AUTHORITY: \"msal.authority\",\r\n ACQUIRE_TOKEN_ACCOUNT: \"msal.acquireTokenAccount\"\r\n};\r\n\r\n/**\r\n * @hidden\r\n */\r\nexport const SSOTypes = {\r\n ACCOUNT: \"account\",\r\n SID: \"sid\",\r\n LOGIN_HINT: \"login_hint\",\r\n ID_TOKEN: \"id_token\",\r\n DOMAIN_HINT: \"domain_hint\",\r\n ORGANIZATIONS: \"organizations\",\r\n CONSUMERS: \"consumers\",\r\n ACCOUNT_ID: \"accountIdentifier\",\r\n HOMEACCOUNT_ID: \"homeAccountIdentifier\",\r\n LOGIN_REQ: \"login_req\",\r\n DOMAIN_REQ: \"domain_req\"\r\n};\r\n\r\n/**\r\n * we considered making this \"enum\" in the request instead of string, however it looks like the allowed list of\r\n * prompt values kept changing over past couple of years. There are some undocumented prompt values for some\r\n * internal partners too, hence the choice of generic \"string\" type instead of the \"enum\"\r\n * @hidden\r\n */\r\nexport const PromptState = {\r\n\tLOGIN: \"login\",\r\n\tSELECT_ACCOUNT: \"select_account\",\r\n\tCONSENT: \"consent\",\r\n\tNONE: \"none\",\r\n};\r\n\r\nexport const Library = {\r\n version: \"1.0.2\"\r\n};\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nexport const AuthErrorMessage = {\r\n unexpectedError: {\r\n code: \"unexpected_error\",\r\n desc: \"Unexpected error in authentication.\"\r\n }\r\n};\r\n\r\n/**\r\n* General error class thrown by the MSAL.js library.\r\n*/\r\nexport class AuthError extends Error {\r\n\r\n errorCode: string;\r\n errorMessage: string;\r\n\r\n constructor(errorCode: string, errorMessage?: string) {\r\n super(errorMessage);\r\n Object.setPrototypeOf(this, AuthError.prototype);\r\n\r\n this.errorCode = errorCode;\r\n this.errorMessage = errorMessage;\r\n this.name = \"AuthError\";\r\n }\r\n\r\n static createUnexpectedError(errDesc: string) {\r\n return new AuthError(AuthErrorMessage.unexpectedError.code, `${AuthErrorMessage.unexpectedError.desc}: ${errDesc}`);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nimport { AuthError } from \"./AuthError\";\r\nimport { Utils } from \"../Utils\";\r\nimport { IdToken } from \"../IdToken\";\r\n\r\nexport const ClientAuthErrorMessage = {\r\n multipleMatchingTokens: {\r\n code: \"multiple_matching_tokens\",\r\n desc: \"The cache contains multiple tokens satisfying the requirements. \" +\r\n \"Call AcquireToken again providing more requirements like authority.\"\r\n },\r\n multipleCacheAuthorities: {\r\n code: \"multiple_authorities\",\r\n desc: \"Multiple authorities found in the cache. Pass authority in the API overload.\"\r\n },\r\n endpointResolutionError: {\r\n code: \"endpoints_resolution_error\",\r\n desc: \"Error: could not resolve endpoints. Please check network and try again.\"\r\n },\r\n popUpWindowError: {\r\n code: \"popup_window_error\",\r\n desc: \"Error opening popup window. This can happen if you are using IE or if popups are blocked in the browser.\"\r\n },\r\n tokenRenewalError: {\r\n code: \"token_renewal_error\",\r\n desc: \"Token renewal operation failed due to timeout.\"\r\n },\r\n invalidIdToken: {\r\n code: \"invalid_id_token\",\r\n desc: \"Invalid ID token format.\"\r\n },\r\n invalidStateError: {\r\n code: \"invalid_state_error\",\r\n desc: \"Invalid state.\"\r\n },\r\n nonceMismatchError: {\r\n code: \"nonce_mismatch_error\",\r\n desc: \"Nonce is not matching, Nonce received: \"\r\n },\r\n loginProgressError: {\r\n code: \"login_progress_error\",\r\n desc: \"Login_In_Progress: Error during login call - login is already in progress.\"\r\n },\r\n acquireTokenProgressError: {\r\n code: \"acquiretoken_progress_error\",\r\n desc: \"AcquireToken_In_Progress: Error during login call - login is already in progress.\"\r\n },\r\n userCancelledError: {\r\n code: \"user_cancelled\",\r\n desc: \"User cancelled the flow.\"\r\n },\r\n callbackError: {\r\n code: \"callback_error\",\r\n desc: \"Error occurred in token received callback function.\"\r\n },\r\n userLoginRequiredError: {\r\n code: \"user_login_error\",\r\n desc: \"User login is required.\"\r\n },\r\n userDoesNotExistError: {\r\n code: \"user_non_existent\",\r\n desc: \"User object does not exist. Please call a login API.\"\r\n },\r\n clientInfoDecodingError: {\r\n code: \"client_info_decoding_error\",\r\n desc: \"The client info could not be parsed/decoded correctly. Please review the trace to determine the root cause.\"\r\n },\r\n clientInfoNotPopulatedError: {\r\n code: \"client_info_not_populated_error\",\r\n desc: \"The service did not populate client_info in the response, Please verify with the service team\"\r\n },\r\n nullOrEmptyIdToken: {\r\n code: \"null_or_empty_id_token\",\r\n desc: \"The idToken is null or empty. Please review the trace to determine the root cause.\"\r\n },\r\n idTokenNotParsed: {\r\n code: \"id_token_parsing_error\",\r\n desc: \"ID token cannot be parsed. Please review stack trace to determine root cause.\"\r\n },\r\n tokenEncodingError: {\r\n code: \"token_encoding_error\",\r\n desc: \"The token to be decoded is not encoded correctly.\"\r\n }\r\n};\r\n\r\n/**\r\n * Error thrown when there is an error in the client code running on the browser.\r\n */\r\nexport class ClientAuthError extends AuthError {\r\n\r\n constructor(errorCode: string, errorMessage?: string) {\r\n super(errorCode, errorMessage);\r\n this.name = \"ClientAuthError\";\r\n\r\n Object.setPrototypeOf(this, ClientAuthError.prototype);\r\n }\r\n\r\n static createEndpointResolutionError(errDetail?: string): ClientAuthError {\r\n let errorMessage = ClientAuthErrorMessage.endpointResolutionError.desc;\r\n if (errDetail && !Utils.isEmpty(errDetail)) {\r\n errorMessage += ` Details: ${errDetail}`;\r\n }\r\n return new ClientAuthError(ClientAuthErrorMessage.endpointResolutionError.code, errorMessage);\r\n }\r\n\r\n static createMultipleMatchingTokensInCacheError(scope: string): ClientAuthError {\r\n return new ClientAuthError(ClientAuthErrorMessage.multipleMatchingTokens.code,\r\n `Cache error for scope ${scope}: ${ClientAuthErrorMessage.multipleMatchingTokens.desc}.`);\r\n }\r\n\r\n static createMultipleAuthoritiesInCacheError(scope: string): ClientAuthError {\r\n return new ClientAuthError(ClientAuthErrorMessage.multipleCacheAuthorities.code,\r\n `Cache error for scope ${scope}: ${ClientAuthErrorMessage.multipleCacheAuthorities.desc}.`);\r\n }\r\n\r\n static createPopupWindowError(errDetail?: string): ClientAuthError {\r\n var errorMessage = ClientAuthErrorMessage.popUpWindowError.desc;\r\n if (errDetail && !Utils.isEmpty(errDetail)) {\r\n errorMessage += ` Details: ${errDetail}`;\r\n }\r\n return new ClientAuthError(ClientAuthErrorMessage.popUpWindowError.code, errorMessage);\r\n }\r\n\r\n static createTokenRenewalTimeoutError(): ClientAuthError {\r\n return new ClientAuthError(ClientAuthErrorMessage.tokenRenewalError.code,\r\n ClientAuthErrorMessage.tokenRenewalError.desc);\r\n }\r\n\r\n static createInvalidIdTokenError(idToken: IdToken) : ClientAuthError {\r\n return new ClientAuthError(ClientAuthErrorMessage.invalidIdToken.code,\r\n `${ClientAuthErrorMessage.invalidIdToken.desc} Given token: ${idToken}`);\r\n }\r\n\r\n //TODO: Is this not a security flaw to send the user the state expected??\r\n static createInvalidStateError(invalidState: string, actualState: string): ClientAuthError {\r\n return new ClientAuthError(ClientAuthErrorMessage.invalidStateError.code,\r\n `${ClientAuthErrorMessage.invalidStateError.desc} ${invalidState}, state expected : ${actualState}.`);\r\n }\r\n\r\n //TODO: Is this not a security flaw to send the user the Nonce expected??\r\n static createNonceMismatchError(invalidNonce: string, actualNonce: string): ClientAuthError {\r\n return new ClientAuthError(ClientAuthErrorMessage.nonceMismatchError.code,\r\n `${ClientAuthErrorMessage.nonceMismatchError.desc} ${invalidNonce}, nonce expected : ${actualNonce}.`);\r\n }\r\n\r\n static createLoginInProgressError(): ClientAuthError {\r\n return new ClientAuthError(ClientAuthErrorMessage.loginProgressError.code,\r\n ClientAuthErrorMessage.loginProgressError.desc);\r\n }\r\n\r\n static createAcquireTokenInProgressError(): ClientAuthError {\r\n return new ClientAuthError(ClientAuthErrorMessage.acquireTokenProgressError.code,\r\n ClientAuthErrorMessage.acquireTokenProgressError.desc);\r\n }\r\n\r\n static createUserCancelledError(): ClientAuthError {\r\n return new ClientAuthError(ClientAuthErrorMessage.userCancelledError.code,\r\n ClientAuthErrorMessage.userCancelledError.desc);\r\n }\r\n\r\n static createErrorInCallbackFunction(errorDesc: string): ClientAuthError {\r\n return new ClientAuthError(ClientAuthErrorMessage.callbackError.code,\r\n `${ClientAuthErrorMessage.callbackError.desc} ${errorDesc}.`);\r\n }\r\n\r\n static createUserLoginRequiredError() : ClientAuthError {\r\n return new ClientAuthError(ClientAuthErrorMessage.userLoginRequiredError.code,\r\n ClientAuthErrorMessage.userLoginRequiredError.desc);\r\n }\r\n\r\n static createUserDoesNotExistError() : ClientAuthError {\r\n return new ClientAuthError(ClientAuthErrorMessage.userDoesNotExistError.code,\r\n ClientAuthErrorMessage.userDoesNotExistError.desc);\r\n }\r\n\r\n static createClientInfoDecodingError(caughtError: string) : ClientAuthError {\r\n return new ClientAuthError(ClientAuthErrorMessage.clientInfoDecodingError.code,\r\n `${ClientAuthErrorMessage.clientInfoDecodingError.desc} Failed with error: ${caughtError}`);\r\n }\r\n\r\n static createClientInfoNotPopulatedError(caughtError: string) : ClientAuthError {\r\n return new ClientAuthError(ClientAuthErrorMessage.clientInfoNotPopulatedError.code,\r\n `${ClientAuthErrorMessage.clientInfoNotPopulatedError.desc} Failed with error: ${caughtError}`);\r\n }\r\n\r\n static createIdTokenNullOrEmptyError(invalidRawTokenString: string) : ClientAuthError {\r\n return new ClientAuthError(ClientAuthErrorMessage.nullOrEmptyIdToken.code,\r\n `${ClientAuthErrorMessage.nullOrEmptyIdToken.desc} Raw ID Token Value: ${invalidRawTokenString}`);\r\n }\r\n\r\n static createIdTokenParsingError(caughtParsingError: string) : ClientAuthError {\r\n return new ClientAuthError(ClientAuthErrorMessage.idTokenNotParsed.code,\r\n `${ClientAuthErrorMessage.idTokenNotParsed.desc} Failed with error: ${caughtParsingError}`);\r\n }\r\n\r\n static createTokenEncodingError(incorrectlyEncodedToken: string) : ClientAuthError {\r\n return new ClientAuthError(ClientAuthErrorMessage.tokenEncodingError.code,\r\n `${ClientAuthErrorMessage.tokenEncodingError.desc} Attempted to decode: ${incorrectlyEncodedToken}`);\r\n }\r\n}\r\n","/*\n * base64.js\n *\n * Licensed under the BSD 3-Clause License.\n * http://opensource.org/licenses/BSD-3-Clause\n *\n * References:\n * http://en.wikipedia.org/wiki/Base64\n */\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n ? module.exports = factory(global)\n : typeof define === 'function' && define.amd\n ? define(factory) : factory(global)\n}((\n typeof self !== 'undefined' ? self\n : typeof window !== 'undefined' ? window\n : typeof global !== 'undefined' ? global\n: this\n), function(global) {\n 'use strict';\n // existing version for noConflict()\n global = global || {};\n var _Base64 = global.Base64;\n var version = \"2.5.1\";\n // if node.js and NOT React Native, we use Buffer\n var buffer;\n if (typeof module !== 'undefined' && module.exports) {\n try {\n buffer = eval(\"require('buffer').Buffer\");\n } catch (err) {\n buffer = undefined;\n }\n }\n // constants\n var b64chars\n = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n var b64tab = function(bin) {\n var t = {};\n for (var i = 0, l = bin.length; i < l; i++) t[bin.charAt(i)] = i;\n return t;\n }(b64chars);\n var fromCharCode = String.fromCharCode;\n // encoder stuff\n var cb_utob = function(c) {\n if (c.length < 2) {\n var cc = c.charCodeAt(0);\n return cc < 0x80 ? c\n : cc < 0x800 ? (fromCharCode(0xc0 | (cc >>> 6))\n + fromCharCode(0x80 | (cc & 0x3f)))\n : (fromCharCode(0xe0 | ((cc >>> 12) & 0x0f))\n + fromCharCode(0x80 | ((cc >>> 6) & 0x3f))\n + fromCharCode(0x80 | ( cc & 0x3f)));\n } else {\n var cc = 0x10000\n + (c.charCodeAt(0) - 0xD800) * 0x400\n + (c.charCodeAt(1) - 0xDC00);\n return (fromCharCode(0xf0 | ((cc >>> 18) & 0x07))\n + fromCharCode(0x80 | ((cc >>> 12) & 0x3f))\n + fromCharCode(0x80 | ((cc >>> 6) & 0x3f))\n + fromCharCode(0x80 | ( cc & 0x3f)));\n }\n };\n var re_utob = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFFF]|[^\\x00-\\x7F]/g;\n var utob = function(u) {\n return u.replace(re_utob, cb_utob);\n };\n var cb_encode = function(ccc) {\n var padlen = [0, 2, 1][ccc.length % 3],\n ord = ccc.charCodeAt(0) << 16\n | ((ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8)\n | ((ccc.length > 2 ? ccc.charCodeAt(2) : 0)),\n chars = [\n b64chars.charAt( ord >>> 18),\n b64chars.charAt((ord >>> 12) & 63),\n padlen >= 2 ? '=' : b64chars.charAt((ord >>> 6) & 63),\n padlen >= 1 ? '=' : b64chars.charAt(ord & 63)\n ];\n return chars.join('');\n };\n var btoa = global.btoa ? function(b) {\n return global.btoa(b);\n } : function(b) {\n return b.replace(/[\\s\\S]{1,3}/g, cb_encode);\n };\n var _encode = buffer ?\n buffer.from && Uint8Array && buffer.from !== Uint8Array.from\n ? function (u) {\n return (u.constructor === buffer.constructor ? u : buffer.from(u))\n .toString('base64')\n }\n : function (u) {\n return (u.constructor === buffer.constructor ? u : new buffer(u))\n .toString('base64')\n }\n : function (u) { return btoa(utob(u)) }\n ;\n var encode = function(u, urisafe) {\n return !urisafe\n ? _encode(String(u))\n : _encode(String(u)).replace(/[+\\/]/g, function(m0) {\n return m0 == '+' ? '-' : '_';\n }).replace(/=/g, '');\n };\n var encodeURI = function(u) { return encode(u, true) };\n // decoder stuff\n var re_btou = new RegExp([\n '[\\xC0-\\xDF][\\x80-\\xBF]',\n '[\\xE0-\\xEF][\\x80-\\xBF]{2}',\n '[\\xF0-\\xF7][\\x80-\\xBF]{3}'\n ].join('|'), 'g');\n var cb_btou = function(cccc) {\n switch(cccc.length) {\n case 4:\n var cp = ((0x07 & cccc.charCodeAt(0)) << 18)\n | ((0x3f & cccc.charCodeAt(1)) << 12)\n | ((0x3f & cccc.charCodeAt(2)) << 6)\n | (0x3f & cccc.charCodeAt(3)),\n offset = cp - 0x10000;\n return (fromCharCode((offset >>> 10) + 0xD800)\n + fromCharCode((offset & 0x3FF) + 0xDC00));\n case 3:\n return fromCharCode(\n ((0x0f & cccc.charCodeAt(0)) << 12)\n | ((0x3f & cccc.charCodeAt(1)) << 6)\n | (0x3f & cccc.charCodeAt(2))\n );\n default:\n return fromCharCode(\n ((0x1f & cccc.charCodeAt(0)) << 6)\n | (0x3f & cccc.charCodeAt(1))\n );\n }\n };\n var btou = function(b) {\n return b.replace(re_btou, cb_btou);\n };\n var cb_decode = function(cccc) {\n var len = cccc.length,\n padlen = len % 4,\n n = (len > 0 ? b64tab[cccc.charAt(0)] << 18 : 0)\n | (len > 1 ? b64tab[cccc.charAt(1)] << 12 : 0)\n | (len > 2 ? b64tab[cccc.charAt(2)] << 6 : 0)\n | (len > 3 ? b64tab[cccc.charAt(3)] : 0),\n chars = [\n fromCharCode( n >>> 16),\n fromCharCode((n >>> 8) & 0xff),\n fromCharCode( n & 0xff)\n ];\n chars.length -= [0, 0, 2, 1][padlen];\n return chars.join('');\n };\n var _atob = global.atob ? function(a) {\n return global.atob(a);\n } : function(a){\n return a.replace(/\\S{1,4}/g, cb_decode);\n };\n var atob = function(a) {\n return _atob(String(a).replace(/[^A-Za-z0-9\\+\\/]/g, ''));\n };\n var _decode = buffer ?\n buffer.from && Uint8Array && buffer.from !== Uint8Array.from\n ? function(a) {\n return (a.constructor === buffer.constructor\n ? a : buffer.from(a, 'base64')).toString();\n }\n : function(a) {\n return (a.constructor === buffer.constructor\n ? a : new buffer(a, 'base64')).toString();\n }\n : function(a) { return btou(_atob(a)) };\n var decode = function(a){\n return _decode(\n String(a).replace(/[-_]/g, function(m0) { return m0 == '-' ? '+' : '/' })\n .replace(/[^A-Za-z0-9\\+\\/]/g, '')\n );\n };\n var noConflict = function() {\n var Base64 = global.Base64;\n global.Base64 = _Base64;\n return Base64;\n };\n // export Base64\n global.Base64 = {\n VERSION: version,\n atob: atob,\n btoa: btoa,\n fromBase64: decode,\n toBase64: encode,\n utob: utob,\n encode: encode,\n encodeURI: encodeURI,\n btou: btou,\n decode: decode,\n noConflict: noConflict,\n __buffer__: buffer\n };\n // if ES5 is available, make Base64.extendString() available\n if (typeof Object.defineProperty === 'function') {\n var noEnum = function(v){\n return {value:v,enumerable:false,writable:true,configurable:true};\n };\n global.Base64.extendString = function () {\n Object.defineProperty(\n String.prototype, 'fromBase64', noEnum(function () {\n return decode(this)\n }));\n Object.defineProperty(\n String.prototype, 'toBase64', noEnum(function (urisafe) {\n return encode(this, urisafe)\n }));\n Object.defineProperty(\n String.prototype, 'toBase64URI', noEnum(function () {\n return encode(this, true)\n }));\n };\n }\n //\n // export Base64 to the namespace\n //\n if (global['Meteor']) { // Meteor.js\n Base64 = global.Base64;\n }\n // module.exports and AMD are mutually exclusive.\n // module.exports has precedence.\n if (typeof module !== 'undefined' && module.exports) {\n module.exports.Base64 = global.Base64;\n }\n else if (typeof define === 'function' && define.amd) {\n // AMD. Register as an anonymous module.\n define([], function(){ return global.Base64 });\n }\n // that's it!\n return {Base64: global.Base64}\n}));\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nimport { IUri } from \"./IUri\";\r\nimport { Account } from \"./Account\";\r\nimport {Constants, SSOTypes, PromptState} from \"./Constants\";\r\nimport { AuthenticationParameters, QPDict } from \"./AuthenticationParameters\";\r\nimport { AuthResponse } from \"./AuthResponse\";\r\nimport { IdToken } from \"./IdToken\";\r\nimport { ClientAuthError } from \"./error/ClientAuthError\";\r\nimport { Library } from \"./Constants\";\r\nimport { Base64 } from \"js-base64\";\r\n\r\n/**\r\n * @hidden\r\n */\r\nexport class Utils {\r\n\r\n //#region General Util\r\n\r\n /**\r\n * Utils function to compare two Account objects - used to check if the same user account is logged in\r\n *\r\n * @param a1: Account object\r\n * @param a2: Account object\r\n */\r\n static compareAccounts(a1: Account, a2: Account): boolean {\r\n if (!a1 || !a2) {\r\n return false;\r\n }\r\n if (a1.homeAccountIdentifier && a2.homeAccountIdentifier) {\r\n if (a1.homeAccountIdentifier === a2.homeAccountIdentifier) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Decimal to Hex\r\n *\r\n * @param num\r\n */\r\n static decimalToHex(num: number): string {\r\n var hex: string = num.toString(16);\r\n while (hex.length < 2) {\r\n hex = \"0\" + hex;\r\n }\r\n return hex;\r\n }\r\n\r\n /**\r\n * MSAL JS Library Version\r\n */\r\n static getLibraryVersion(): string {\r\n return Library.version;\r\n }\r\n\r\n /**\r\n * Creates a new random GUID - used to populate state?\r\n * @returns string (GUID)\r\n */\r\n static createNewGuid(): string {\r\n // RFC4122: The version 4 UUID is meant for generating UUIDs from truly-random or\r\n // pseudo-random numbers.\r\n // The algorithm is as follows:\r\n // Set the two most significant bits (bits 6 and 7) of the\r\n // clock_seq_hi_and_reserved to zero and one, respectively.\r\n // Set the four most significant bits (bits 12 through 15) of the\r\n // time_hi_and_version field to the 4-bit version number from\r\n // Section 4.1.3. Version4\r\n // Set all the other bits to randomly (or pseudo-randomly) chosen\r\n // values.\r\n // UUID = time-low \"-\" time-mid \"-\"time-high-and-version \"-\"clock-seq-reserved and low(2hexOctet)\"-\" node\r\n // time-low = 4hexOctet\r\n // time-mid = 2hexOctet\r\n // time-high-and-version = 2hexOctet\r\n // clock-seq-and-reserved = hexOctet:\r\n // clock-seq-low = hexOctet\r\n // node = 6hexOctet\r\n // Format: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\r\n // y could be 1000, 1001, 1010, 1011 since most significant two bits needs to be 10\r\n // y values are 8, 9, A, B\r\n\r\n const cryptoObj: Crypto = window.crypto; // for IE 11\r\n if (cryptoObj && cryptoObj.getRandomValues) {\r\n const buffer: Uint8Array = new Uint8Array(16);\r\n cryptoObj.getRandomValues(buffer);\r\n\r\n //buffer[6] and buffer[7] represents the time_hi_and_version field. We will set the four most significant bits (4 through 7) of buffer[6] to represent decimal number 4 (UUID version number).\r\n buffer[6] |= 0x40; //buffer[6] | 01000000 will set the 6 bit to 1.\r\n buffer[6] &= 0x4f; //buffer[6] & 01001111 will set the 4, 5, and 7 bit to 0 such that bits 4-7 == 0100 = \"4\".\r\n\r\n //buffer[8] represents the clock_seq_hi_and_reserved field. We will set the two most significant bits (6 and 7) of the clock_seq_hi_and_reserved to zero and one, respectively.\r\n buffer[8] |= 0x80; //buffer[8] | 10000000 will set the 7 bit to 1.\r\n buffer[8] &= 0xbf; //buffer[8] & 10111111 will set the 6 bit to 0.\r\n\r\n return Utils.decimalToHex(buffer[0]) + Utils.decimalToHex(buffer[1])\r\n + Utils.decimalToHex(buffer[2]) + Utils.decimalToHex(buffer[3])\r\n + \"-\" + Utils.decimalToHex(buffer[4]) + Utils.decimalToHex(buffer[5])\r\n + \"-\" + Utils.decimalToHex(buffer[6]) + Utils.decimalToHex(buffer[7])\r\n + \"-\" + Utils.decimalToHex(buffer[8]) + Utils.decimalToHex(buffer[9])\r\n + \"-\" + Utils.decimalToHex(buffer[10]) + Utils.decimalToHex(buffer[11])\r\n + Utils.decimalToHex(buffer[12]) + Utils.decimalToHex(buffer[13])\r\n + Utils.decimalToHex(buffer[14]) + Utils.decimalToHex(buffer[15]);\r\n }\r\n else {\r\n const guidHolder: string = \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\";\r\n const hex: string = \"0123456789abcdef\";\r\n let r: number = 0;\r\n let guidResponse: string = \"\";\r\n for (let i: number = 0; i < 36; i++) {\r\n if (guidHolder[i] !== \"-\" && guidHolder[i] !== \"4\") {\r\n // each x and y needs to be random\r\n r = Math.random() * 16 | 0;\r\n }\r\n if (guidHolder[i] === \"x\") {\r\n guidResponse += hex[r];\r\n } else if (guidHolder[i] === \"y\") {\r\n // clock-seq-and-reserved first hex is filtered and remaining hex values are random\r\n r &= 0x3; // bit and with 0011 to set pos 2 to zero ?0??\r\n r |= 0x8; // set pos 3 to 1 as 1???\r\n guidResponse += hex[r];\r\n } else {\r\n guidResponse += guidHolder[i];\r\n }\r\n }\r\n return guidResponse;\r\n }\r\n }\r\n\r\n //#endregion\r\n\r\n //#region Time\r\n\r\n /**\r\n * Returns time in seconds for expiration based on string value passed in.\r\n *\r\n * @param expires\r\n */\r\n static expiresIn(expires: string): number {\r\n // if AAD did not send \"expires_in\" property, use default expiration of 3599 seconds, for some reason AAD sends 3599 as \"expires_in\" value instead of 3600\r\n if (!expires) {\r\n expires = \"3599\";\r\n }\r\n return this.now() + parseInt(expires, 10);\r\n }\r\n\r\n /**\r\n * return the current time in Unix time. Date.getTime() returns in milliseconds.\r\n */\r\n static now(): number {\r\n return Math.round(new Date().getTime() / 1000.0);\r\n }\r\n\r\n //#endregion\r\n\r\n //#region String Ops\r\n\r\n /**\r\n * Check if a string is empty\r\n *\r\n * @param str\r\n */\r\n static isEmpty(str: string): boolean {\r\n return (typeof str === \"undefined\" || !str || 0 === str.length);\r\n }\r\n\r\n //#endregion\r\n\r\n //#region Token Processing (Extract to TokenProcessing.ts)\r\n\r\n /**\r\n * decode a JWT\r\n *\r\n * @param jwtToken\r\n */\r\n static decodeJwt(jwtToken: string): any {\r\n if (this.isEmpty(jwtToken)) {\r\n return null;\r\n }\r\n const idTokenPartsRegex = /^([^\\.\\s]*)\\.([^\\.\\s]+)\\.([^\\.\\s]*)$/;\r\n const matches = idTokenPartsRegex.exec(jwtToken);\r\n if (!matches || matches.length < 4) {\r\n //this._requestContext.logger.warn(\"The returned id_token is not parseable.\");\r\n return null;\r\n }\r\n const crackedToken = {\r\n header: matches[1],\r\n JWSPayload: matches[2],\r\n JWSSig: matches[3]\r\n };\r\n return crackedToken;\r\n }\r\n\r\n /**\r\n * Extract IdToken by decoding the RAWIdToken\r\n *\r\n * @param encodedIdToken\r\n */\r\n static extractIdToken(encodedIdToken: string): any {\r\n // id token will be decoded to get the username\r\n const decodedToken = this.decodeJwt(encodedIdToken);\r\n if (!decodedToken) {\r\n return null;\r\n }\r\n try {\r\n const base64IdToken = decodedToken.JWSPayload;\r\n const base64Decoded = this.base64DecodeStringUrlSafe(base64IdToken);\r\n if (!base64Decoded) {\r\n //this._requestContext.logger.info(\"The returned id_token could not be base64 url safe decoded.\");\r\n return null;\r\n }\r\n // ECMA script has JSON built-in support\r\n return JSON.parse(base64Decoded);\r\n } catch (err) {\r\n //this._requestContext.logger.error(\"The returned id_token could not be decoded\" + err);\r\n }\r\n\r\n return null;\r\n }\r\n\r\n //#endregion\r\n\r\n //#region Encode and Decode\r\n\r\n /**\r\n * encoding string to base64 - platform specific check\r\n *\r\n * @param input\r\n */\r\n static base64EncodeStringUrlSafe(input: string): string {\r\n // html5 should support atob function for decoding\r\n return Base64.encode(input);\r\n }\r\n\r\n /**\r\n * decoding base64 token - platform specific check\r\n *\r\n * @param base64IdToken\r\n */\r\n static base64DecodeStringUrlSafe(base64IdToken: string): string {\r\n // html5 should support atob function for decoding\r\n base64IdToken = base64IdToken.replace(/-/g, \"+\").replace(/_/g, \"/\");\r\n return decodeURIComponent(encodeURIComponent(Base64.decode(base64IdToken))); // jshint ignore:line\r\n }\r\n\r\n /**\r\n * base64 encode a string\r\n *\r\n * @param input\r\n */\r\n // TODO: Rename to specify type of encoding\r\n static encode(input: string): string {\r\n const keyStr: string = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\r\n let output = \"\";\r\n let chr1: number, chr2: number, chr3: number, enc1: number, enc2: number, enc3: number, enc4: number;\r\n var i = 0;\r\n\r\n input = this.utf8Encode(input);\r\n\r\n while (i < input.length) {\r\n chr1 = input.charCodeAt(i++);\r\n chr2 = input.charCodeAt(i++);\r\n chr3 = input.charCodeAt(i++);\r\n\r\n enc1 = chr1 >> 2;\r\n enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);\r\n enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);\r\n enc4 = chr3 & 63;\r\n\r\n if (isNaN(chr2)) {\r\n enc3 = enc4 = 64;\r\n } else if (isNaN(chr3)) {\r\n enc4 = 64;\r\n }\r\n\r\n output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);\r\n }\r\n\r\n return output.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\r\n }\r\n\r\n /**\r\n * utf8 encode a string\r\n *\r\n * @param input\r\n */\r\n static utf8Encode(input: string): string {\r\n input = input.replace(/\\r\\n/g, \"\\n\");\r\n var utftext = \"\";\r\n\r\n for (var n = 0; n < input.length; n++) {\r\n var c = input.charCodeAt(n);\r\n\r\n if (c < 128) {\r\n utftext += String.fromCharCode(c);\r\n }\r\n else if ((c > 127) && (c < 2048)) {\r\n utftext += String.fromCharCode((c >> 6) | 192);\r\n utftext += String.fromCharCode((c & 63) | 128);\r\n }\r\n else {\r\n utftext += String.fromCharCode((c >> 12) | 224);\r\n utftext += String.fromCharCode(((c >> 6) & 63) | 128);\r\n utftext += String.fromCharCode((c & 63) | 128);\r\n }\r\n }\r\n\r\n return utftext;\r\n }\r\n\r\n /**\r\n * decode a base64 token string\r\n *\r\n * @param base64IdToken\r\n */\r\n // TODO: Rename to specify type of encoding\r\n static decode(base64IdToken: string): string {\r\n var codes = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\";\r\n base64IdToken = String(base64IdToken).replace(/=+$/, \"\");\r\n var length = base64IdToken.length;\r\n if (length % 4 === 1) {\r\n throw ClientAuthError.createTokenEncodingError(base64IdToken);\r\n }\r\n let h1: number, h2: number, h3: number, h4: number, bits: number, c1: number, c2: number, c3: number, decoded = \"\";\r\n for (var i = 0; i < length; i += 4) {\r\n //Every 4 base64 encoded character will be converted to 3 byte string, which is 24 bits\r\n // then 6 bits per base64 encoded character\r\n h1 = codes.indexOf(base64IdToken.charAt(i));\r\n h2 = codes.indexOf(base64IdToken.charAt(i + 1));\r\n h3 = codes.indexOf(base64IdToken.charAt(i + 2));\r\n h4 = codes.indexOf(base64IdToken.charAt(i + 3));\r\n // For padding, if last two are \"=\"\r\n if (i + 2 === length - 1) {\r\n bits = h1 << 18 | h2 << 12 | h3 << 6;\r\n c1 = bits >> 16 & 255;\r\n c2 = bits >> 8 & 255;\r\n decoded += String.fromCharCode(c1, c2);\r\n break;\r\n }\r\n // if last one is \"=\"\r\n else if (i + 1 === length - 1) {\r\n bits = h1 << 18 | h2 << 12;\r\n c1 = bits >> 16 & 255;\r\n decoded += String.fromCharCode(c1);\r\n break;\r\n }\r\n bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;\r\n // then convert to 3 byte chars\r\n c1 = bits >> 16 & 255;\r\n c2 = bits >> 8 & 255;\r\n c3 = bits & 255;\r\n decoded += String.fromCharCode(c1, c2, c3);\r\n }\r\n return decoded;\r\n }\r\n\r\n /**\r\n * deserialize a string\r\n *\r\n * @param query\r\n */\r\n static deserialize(query: string): any {\r\n let match: Array<string>; // Regex for replacing addition symbol with a space\r\n const pl = /\\+/g;\r\n const search = /([^&=]+)=([^&]*)/g;\r\n const decode = (s: string) => decodeURIComponent(s.replace(pl, \" \"));\r\n const obj: {} = {};\r\n match = search.exec(query);\r\n while (match) {\r\n obj[decode(match[1])] = decode(match[2]);\r\n match = search.exec(query);\r\n }\r\n return obj;\r\n }\r\n\r\n //#endregion\r\n\r\n //#region Scopes (extract to Scopes.ts)\r\n\r\n /**\r\n * Check if there are dup scopes in a given request\r\n *\r\n * @param cachedScopes\r\n * @param scopes\r\n */\r\n // TODO: Rename this, intersecting scopes isn't a great name for duplicate checker\r\n static isIntersectingScopes(cachedScopes: Array<string>, scopes: Array<string>): boolean {\r\n cachedScopes = this.convertToLowerCase(cachedScopes);\r\n for (let i = 0; i < scopes.length; i++) {\r\n if (cachedScopes.indexOf(scopes[i].toLowerCase()) > -1) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Check if a given scope is present in the request\r\n *\r\n * @param cachedScopes\r\n * @param scopes\r\n */\r\n static containsScope(cachedScopes: Array<string>, scopes: Array<string>): boolean {\r\n cachedScopes = this.convertToLowerCase(cachedScopes);\r\n return scopes.every((value: any): boolean => cachedScopes.indexOf(value.toString().toLowerCase()) >= 0);\r\n }\r\n\r\n /**\r\n * toLower\r\n *\r\n * @param scopes\r\n */\r\n // TODO: Rename this, too generic name for a function that only deals with scopes\r\n static convertToLowerCase(scopes: Array<string>): Array<string> {\r\n return scopes.map(scope => scope.toLowerCase());\r\n }\r\n\r\n /**\r\n * remove one element from a scope array\r\n *\r\n * @param scopes\r\n * @param scope\r\n */\r\n // TODO: Rename this, too generic name for a function that only deals with scopes\r\n static removeElement(scopes: Array<string>, scope: string): Array<string> {\r\n return scopes.filter(value => value !== scope);\r\n }\r\n\r\n //#endregion\r\n\r\n //#region URL Processing (Extract to UrlProcessing.ts?)\r\n\r\n static getDefaultRedirectUri(): string {\r\n return window.location.href.split(\"?\")[0].split(\"#\")[0];\r\n }\r\n\r\n /**\r\n * Given a url like https://a:b/common/d?e=f#g, and a tenantId, returns https://a:b/tenantId/d\r\n * @param href The url\r\n * @param tenantId The tenant id to replace\r\n */\r\n static replaceTenantPath(url: string, tenantId: string): string {\r\n url = url.toLowerCase();\r\n var urlObject = this.GetUrlComponents(url);\r\n var pathArray = urlObject.PathSegments;\r\n if (tenantId && (pathArray.length !== 0 && (pathArray[0] === Constants.common || pathArray[0] === SSOTypes.ORGANIZATIONS))) {\r\n pathArray[0] = tenantId;\r\n }\r\n return this.constructAuthorityUriFromObject(urlObject, pathArray);\r\n }\r\n\r\n static constructAuthorityUriFromObject(urlObject: IUri, pathArray: string[]) {\r\n return this.CanonicalizeUri(urlObject.Protocol + \"//\" + urlObject.HostNameAndPort + \"/\" + pathArray.join(\"/\"));\r\n }\r\n\r\n /**\r\n * Parses out the components from a url string.\r\n * @returns An object with the various components. Please cache this value insted of calling this multiple times on the same url.\r\n */\r\n static GetUrlComponents(url: string): IUri {\r\n if (!url) {\r\n throw \"Url required\";\r\n }\r\n\r\n // https://gist.github.com/curtisz/11139b2cfcaef4a261e0\r\n var regEx = RegExp(\"^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\\\?([^#]*))?(#(.*))?\");\r\n\r\n var match = url.match(regEx);\r\n\r\n if (!match || match.length < 6) {\r\n throw \"Valid url required\";\r\n }\r\n\r\n let urlComponents = <IUri>{\r\n Protocol: match[1],\r\n HostNameAndPort: match[4],\r\n AbsolutePath: match[5]\r\n };\r\n\r\n let pathSegments = urlComponents.AbsolutePath.split(\"/\");\r\n pathSegments = pathSegments.filter((val) => val && val.length > 0); // remove empty elements\r\n urlComponents.PathSegments = pathSegments;\r\n return urlComponents;\r\n }\r\n\r\n /**\r\n * Given a url or path, append a trailing slash if one doesnt exist\r\n *\r\n * @param url\r\n */\r\n static CanonicalizeUri(url: string): string {\r\n if (url) {\r\n url = url.toLowerCase();\r\n }\r\n\r\n if (url && !Utils.endsWith(url, \"/\")) {\r\n url += \"/\";\r\n }\r\n\r\n return url;\r\n }\r\n\r\n /**\r\n * Checks to see if the url ends with the suffix\r\n * Required because we are compiling for es5 instead of es6\r\n * @param url\r\n * @param str\r\n */\r\n // TODO: Rename this, not clear what it is supposed to do\r\n static endsWith(url: string, suffix: string): boolean {\r\n if (!url || !suffix) {\r\n return false;\r\n }\r\n\r\n return url.indexOf(suffix, url.length - suffix.length) !== -1;\r\n }\r\n\r\n /**\r\n * Utils function to remove the login_hint and domain_hint from the i/p extraQueryParameters\r\n * @param url\r\n * @param name\r\n */\r\n static urlRemoveQueryStringParameter(url: string, name: string): string {\r\n if (this.isEmpty(url)) {\r\n return url;\r\n }\r\n\r\n var regex = new RegExp(\"(\\\\&\" + name + \"=)[^\\&]+\");\r\n url = url.replace(regex, \"\");\r\n // name=value&\r\n regex = new RegExp(\"(\" + name + \"=)[^\\&]+&\");\r\n url = url.replace(regex, \"\");\r\n // name=value\r\n regex = new RegExp(\"(\" + name + \"=)[^\\&]+\");\r\n url = url.replace(regex, \"\");\r\n return url;\r\n }\r\n\r\n //#endregion\r\n\r\n //#region ExtraQueryParameters Processing (Extract?)\r\n\r\n /**\r\n * Constructs extraQueryParameters to be sent to the server for the AuthenticationParameters set by the developer\r\n * in any login() or acquireToken() calls\r\n * @param idTokenObject\r\n * @param extraQueryParameters\r\n * @param sid\r\n * @param loginHint\r\n */\r\n //TODO: check how this behaves when domain_hint only is sent in extraparameters and idToken has no upn.\r\n static constructUnifiedCacheQueryParameter(request: AuthenticationParameters, idTokenObject: any): QPDict {\r\n\r\n // preference order: account > sid > login_hint\r\n let ssoType;\r\n let ssoData;\r\n let serverReqParam: QPDict = {};\r\n // if account info is passed, account.sid > account.login_hint\r\n if (request) {\r\n if (request.account) {\r\n const account: Account = request.account;\r\n if (account.sid) {\r\n ssoType = SSOTypes.SID;\r\n ssoData = account.sid;\r\n }\r\n else if (account.userName) {\r\n ssoType = SSOTypes.LOGIN_HINT;\r\n ssoData = account.userName;\r\n }\r\n }\r\n // sid from request\r\n else if (request.sid) {\r\n ssoType = SSOTypes.SID;\r\n ssoData = request.sid;\r\n }\r\n // loginHint from request\r\n else if (request.loginHint) {\r\n ssoType = SSOTypes.LOGIN_HINT;\r\n ssoData = request.loginHint;\r\n }\r\n }\r\n // adalIdToken retrieved from cache\r\n else if (idTokenObject) {\r\n if (idTokenObject.hasOwnProperty(Constants.upn)) {\r\n ssoType = SSOTypes.ID_TOKEN;\r\n ssoData = idTokenObject.upn;\r\n }\r\n else {\r\n ssoType = SSOTypes.ORGANIZATIONS;\r\n ssoData = null;\r\n }\r\n }\r\n\r\n serverReqParam = this.addSSOParameter(ssoType, ssoData);\r\n\r\n // add the HomeAccountIdentifier info/ domain_hint\r\n if (request && request.account && request.account.homeAccountIdentifier) {\r\n serverReqParam = this.addSSOParameter(SSOTypes.HOMEACCOUNT_ID, request.account.homeAccountIdentifier, serverReqParam);\r\n }\r\n\r\n return serverReqParam;\r\n }\r\n\r\n\r\n /**\r\n * Add SID to extraQueryParameters\r\n * @param sid\r\n */\r\n static addSSOParameter(ssoType: string, ssoData: string, ssoParam?: QPDict): QPDict {\r\n if (!ssoParam) {\r\n ssoParam = {};\r\n }\r\n\r\n if (!ssoData) {\r\n return ssoParam;\r\n }\r\n\r\n switch (ssoType) {\r\n case SSOTypes.SID: {\r\n ssoParam[SSOTypes.SID] = ssoData;\r\n break;\r\n }\r\n case SSOTypes.ID_TOKEN: {\r\n ssoParam[SSOTypes.LOGIN_HINT] = ssoData;\r\n ssoParam[SSOTypes.DOMAIN_HINT] = SSOTypes.ORGANIZATIONS;\r\n break;\r\n }\r\n case SSOTypes.LOGIN_HINT: {\r\n ssoParam[SSOTypes.LOGIN_HINT] = ssoData;\r\n break;\r\n }\r\n case SSOTypes.ORGANIZATIONS: {\r\n ssoParam[SSOTypes.DOMAIN_HINT] = SSOTypes.ORGANIZATIONS;\r\n break;\r\n }\r\n case SSOTypes.CONSUMERS: {\r\n ssoParam[SSOTypes.DOMAIN_HINT] = SSOTypes.CONSUMERS;\r\n break;\r\n }\r\n case SSOTypes.HOMEACCOUNT_ID: {\r\n let homeAccountId = ssoData.split(\".\");\r\n const uid = Utils.base64DecodeStringUrlSafe(homeAccountId[0]);\r\n const utid = Utils.base64DecodeStringUrlSafe(homeAccountId[1]);\r\n\r\n // TODO: domain_req and login_req are not needed according to eSTS team\r\n ssoParam[SSOTypes.LOGIN_REQ] = uid;\r\n ssoParam[SSOTypes.DOMAIN_REQ] = utid;\r\n\r\n if (utid === Constants.consumersUtid) {\r\n ssoParam[SSOTypes.DOMAIN_HINT] = SSOTypes.CONSUMERS;\r\n }\r\n else {\r\n ssoParam[SSOTypes.DOMAIN_HINT] = SSOTypes.ORGANIZATIONS;\r\n }\r\n break;\r\n }\r\n case SSOTypes.LOGIN_REQ: {\r\n ssoParam[SSOTypes.LOGIN_REQ] = ssoData;\r\n break;\r\n }\r\n case SSOTypes.DOMAIN_REQ: {\r\n ssoParam[SSOTypes.DOMAIN_REQ] = ssoData;\r\n break;\r\n }\r\n }\r\n\r\n return ssoParam;\r\n }\r\n\r\n /**\r\n * Utility to generate a QueryParameterString from a Key-Value mapping of extraQueryParameters passed\r\n * @param extraQueryParameters\r\n */\r\n static generateQueryParametersString(queryParameters: QPDict): string {\r\n let paramsString: string = null;\r\n\r\n if (queryParameters) {\r\n Object.keys(queryParameters).forEach((key: string) => {\r\n if (paramsString == null) {\r\n paramsString = `${key}=${encodeURIComponent(queryParameters[key])}`;\r\n }\r\n else {\r\n paramsString += `&${key}=${encodeURIComponent(queryParameters[key])}`;\r\n }\r\n });\r\n }\r\n\r\n return paramsString;\r\n }\r\n\r\n /**\r\n * Check to see if there are SSO params set in the Request\r\n * @param request\r\n */\r\n static isSSOParam(request: AuthenticationParameters) {\r\n return request && (request.account || request.sid || request.loginHint);\r\n }\r\n\r\n //#endregion\r\n\r\n //#region Response Helpers\r\n\r\n static setResponseIdToken(originalResponse: AuthResponse, idToken: IdToken) : AuthResponse {\r\n var response = { ...originalResponse };\r\n response.idToken = idToken;\r\n if (response.idToken.objectId) {\r\n response.uniqueId = response.idToken.objectId;\r\n } else {\r\n response.uniqueId = response.idToken.subject;\r\n }\r\n response.tenantId = response.idToken.tenantId;\r\n return response;\r\n }\r\n\r\n //#endregion\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nimport { Utils } from \"./Utils\";\r\n\r\n/**\r\n * @hidden\r\n */\r\nexport class AccessTokenKey {\r\n\r\n authority: string;\r\n clientId: string;\r\n scopes: string;\r\n homeAccountIdentifier: string;\r\n\r\n constructor(authority: string, clientId: string, scopes: string, uid: string, utid: string) {\r\n this.authority = Utils.CanonicalizeUri(authority);\r\n this.clientId = clientId;\r\n this.scopes = scopes;\r\n this.homeAccountIdentifier = Utils.base64EncodeStringUrlSafe(uid) + \".\" + Utils.base64EncodeStringUrlSafe(utid);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\n/**\r\n * @hidden\r\n */\r\nexport class AccessTokenValue {\r\n\r\n accessToken: string;\r\n idToken: string;\r\n expiresIn: string;\r\n homeAccountIdentifier: string;\r\n\r\n constructor(accessToken: string, idToken: string, expiresIn: string, homeAccountIdentifier: string) {\r\n this.accessToken = accessToken;\r\n this.idToken = idToken;\r\n this.expiresIn = expiresIn;\r\n this.homeAccountIdentifier = homeAccountIdentifier;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nimport { Authority } from \"./Authority\";\r\nimport { Utils } from \"./Utils\";\r\n\r\n/**\r\n * Nonce: OIDC Nonce definition: https://openid.net/specs/openid-connect-core-1_0.html#IDToken\r\n * State: OAuth Spec: https://tools.ietf.org/html/rfc6749#section-10.12\r\n * @hidden\r\n */\r\nexport class ServerRequestParameters {\r\n\r\n authorityInstance: Authority;\r\n clientId: string;\r\n scopes: Array<string>;\r\n\r\n nonce: string;\r\n state: string;\r\n\r\n // telemetry information\r\n xClientVer: string;\r\n xClientSku: string;\r\n correlationId: string;\r\n\r\n responseType: string;\r\n redirectUri: string;\r\n\r\n promptValue: string;\r\n claimsValue: string;\r\n\r\n queryParameters: string;\r\n extraQueryParameters: string;\r\n\r\n public get authority(): string {\r\n return this.authorityInstance ? this.authorityInstance.CanonicalAuthority : null;\r\n }\r\n\r\n /**\r\n * Constructor\r\n * @param authority\r\n * @param clientId\r\n * @param scope\r\n * @param responseType\r\n * @param redirectUri\r\n * @param state\r\n */\r\n constructor (authority: Authority, clientId: string, scope: Array<string>, responseType: string, redirectUri: string, state: string ) {\r\n this.authorityInstance = authority;\r\n this.clientId = clientId;\r\n this.scopes = scope;\r\n\r\n this.nonce = Utils.createNewGuid();\r\n this.state = state && !Utils.isEmpty(state) ? Utils.createNewGuid() + \"|\" + state : Utils.createNewGuid();\r\n\r\n // TODO: Change this to user passed vs generated with the new PR\r\n this.correlationId = Utils.createNewGuid();\r\n\r\n // telemetry information\r\n this.xClientSku = \"MSAL.JS\";\r\n this.xClientVer = Utils.getLibraryVersion();\r\n\r\n this.responseType = responseType;\r\n this.redirectUri = redirectUri;\r\n }\r\n\r\n /**\r\n * generates the URL with QueryString Parameters\r\n * @param scopes\r\n */\r\n createNavigateUrl(scopes: Array<string>): string {\r\n const str = this.createNavigationUrlString(scopes);\r\n let authEndpoint: string = this.authorityInstance.AuthorizationEndpoint;\r\n // if the endpoint already has queryparams, lets add to it, otherwise add the first one\r\n if (authEndpoint.indexOf(\"?\") < 0) {\r\n authEndpoint += \"?\";\r\n } else {\r\n authEndpoint += \"&\";\r\n }\r\n\r\n const requestUrl: string = `${authEndpoint}${str.join(\"&\")}`;\r\n return requestUrl;\r\n }\r\n\r\n /**\r\n * Generate the array of all QueryStringParams to be sent to the server\r\n * @param scopes\r\n */\r\n createNavigationUrlString(scopes: Array<string>): Array<string> {\r\n if (!scopes) {\r\n scopes = [this.clientId];\r\n }\r\n\r\n if (scopes.indexOf(this.clientId) === -1) {\r\n scopes.push(this.clientId);\r\n }\r\n const str: Array<string> = [];\r\n str.push(\"response_type=\" + this.responseType);\r\n\r\n this.translateclientIdUsedInScope(scopes);\r\n str.push(\"scope=\" + encodeURIComponent(this.parseScope(scopes)));\r\n str.push(\"client_id=\" + encodeURIComponent(this.clientId));\r\n str.push(\"redirect_uri=\" + encodeURIComponent(this.redirectUri));\r\n\r\n str.push(\"state=\" + encodeURIComponent(this.state));\r\n str.push(\"nonce=\" + encodeURIComponent(this.nonce));\r\n\r\n str.push(\"client_info=1\");\r\n str.push(`x-client-SKU=${this.xClientSku}`);\r\n str.push(`x-client-Ver=${this.xClientVer}`);\r\n if (this.promptValue) {\r\n str.push(\"prompt=\" + encodeURIComponent(this.promptValue));\r\n }\r\n\r\n if (this.claimsValue) {\r\n str.push(\"claims=\" + encodeURIComponent(this.claimsValue));\r\n }\r\n\r\n if (this.queryParameters) {\r\n str.push(this.queryParameters);\r\n }\r\n\r\n if (this.extraQueryParameters) {\r\n str.push(this.extraQueryParameters);\r\n }\r\n\r\n str.push(\"client-request-id=\" + encodeURIComponent(this.correlationId));\r\n return str;\r\n }\r\n\r\n /**\r\n * append the required scopes: https://openid.net/specs/openid-connect-basic-1_0.html#Scopes\r\n * @param scopes\r\n */\r\n translateclientIdUsedInScope(scopes: Array<string>): void {\r\n const clientIdIndex: number = scopes.indexOf(this.clientId);\r\n if (clientIdIndex >= 0) {\r\n scopes.splice(clientIdIndex, 1);\r\n if (scopes.indexOf(\"openid\") === -1) {\r\n scopes.push(\"openid\");\r\n }\r\n if (scopes.indexOf(\"profile\") === -1) {\r\n scopes.push(\"profile\");\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * Parse the scopes into a formatted scopeList\r\n * @param scopes\r\n */\r\n parseScope(scopes: Array<string>): string {\r\n let scopeList: string = \"\";\r\n if (scopes) {\r\n for (let i: number = 0; i < scopes.length; ++i) {\r\n scopeList += (i !== scopes.length - 1) ? scopes[i] + \" \" : scopes[i];\r\n }\r\n }\r\n\r\n return scopeList;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nimport { Utils } from \"./Utils\";\r\nimport { ClientAuthError } from \"./error/ClientAuthError\";\r\n\r\n/**\r\n * @hidden\r\n */\r\nexport class ClientInfo {\r\n\r\n private _uid: string;\r\n get uid(): string {\r\n return this._uid ? this._uid : \"\";\r\n }\r\n\r\n set uid(uid: string) {\r\n this._uid = uid;\r\n }\r\n\r\n private _utid: string;\r\n get utid(): string {\r\n return this._utid ? this._utid : \"\";\r\n }\r\n\r\n set utid(utid: string) {\r\n this._utid = utid;\r\n }\r\n\r\n constructor(rawClientInfo: string) {\r\n if (!rawClientInfo || Utils.isEmpty(rawClientInfo)) {\r\n this.uid = \"\";\r\n this.utid = \"\";\r\n return;\r\n }\r\n\r\n try {\r\n const decodedClientInfo: string = Utils.base64DecodeStringUrlSafe(rawClientInfo);\r\n const clientInfo: ClientInfo = <ClientInfo>JSON.parse(decodedClientInfo);\r\n if (clientInfo) {\r\n if (clientInfo.hasOwnProperty(\"uid\")) {\r\n this.uid = clientInfo.uid;\r\n }\r\n\r\n if (clientInfo.hasOwnProperty(\"utid\")) {\r\n this.utid = clientInfo.utid;\r\n }\r\n }\r\n } catch (e) {\r\n throw ClientAuthError.createClientInfoDecodingError(e);\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nimport { Utils } from \"./Utils\";\r\nimport { ClientAuthError } from \"./error/ClientAuthError\";\r\n\r\n/**\r\n * @hidden\r\n */\r\nexport class IdToken {\r\n\r\n issuer: string;\r\n objectId: string;\r\n subject: string;\r\n tenantId: string;\r\n version: string;\r\n preferredName: string;\r\n name: string;\r\n homeObjectId: string;\r\n nonce: string;\r\n expiration: string;\r\n rawIdToken: string;\r\n decodedIdToken: Object;\r\n sid: string;\r\n /* tslint:disable:no-string-literal */\r\n constructor(rawIdToken: string) {\r\n if (Utils.isEmpty(rawIdToken)) {\r\n throw ClientAuthError.createIdTokenNullOrEmptyError(rawIdToken);\r\n }\r\n try {\r\n this.rawIdToken = rawIdToken;\r\n this.decodedIdToken = Utils.extractIdToken(rawIdToken);\r\n if (this.decodedIdToken) {\r\n if (this.decodedIdToken.hasOwnProperty(\"iss\")) {\r\n this.issuer = this.decodedIdToken[\"iss\"];\r\n }\r\n\r\n if (this.decodedIdToken.hasOwnProperty(\"oid\")) {\r\n this.objectId = this.decodedIdToken[\"oid\"];\r\n }\r\n\r\n if (this.decodedIdToken.hasOwnProperty(\"sub\")) {\r\n this.subject = this.decodedIdToken[\"sub\"];\r\n }\r\n\r\n if (this.decodedIdToken.hasOwnProperty(\"tid\")) {\r\n this.tenantId = this.decodedIdToken[\"tid\"];\r\n }\r\n\r\n if (this.decodedIdToken.hasOwnProperty(\"ver\")) {\r\n this.version = this.decodedIdToken[\"ver\"];\r\n }\r\n\r\n if (this.decodedIdToken.hasOwnProperty(\"preferred_username\")) {\r\n this.preferredName = this.decodedIdToken[\"preferred_username\"];\r\n }\r\n\r\n if (this.decodedIdToken.hasOwnProperty(\"name\")) {\r\n this.name = this.decodedIdToken[\"name\"];\r\n }\r\n\r\n if (this.decodedIdToken.hasOwnProperty(\"nonce\")) {\r\n this.nonce = this.decodedIdToken[\"nonce\"];\r\n }\r\n\r\n if (this.decodedIdToken.hasOwnProperty(\"exp\")) {\r\n this.expiration = this.decodedIdToken[\"exp\"];\r\n }\r\n\r\n if (this.decodedIdToken.hasOwnProperty(\"home_oid\")) {\r\n this.homeObjectId = this.decodedIdToken[\"home_oid\"];\r\n }\r\n\r\n if (this.decodedIdToken.hasOwnProperty(\"sid\")) {\r\n this.sid = this.decodedIdToken[\"sid\"];\r\n }\r\n /* tslint:enable:no-string-literal */\r\n }\r\n } catch (e) {\r\n // TODO: This error here won't really every be thrown, since extractIdToken() returns null if the decodeJwt() fails.\r\n // Need to add better error handling here to account for being unable to decode jwts.\r\n throw ClientAuthError.createIdTokenParsingError(e);\r\n }\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nimport { AccessTokenKey } from \"./AccessTokenKey\";\r\nimport { AccessTokenValue } from \"./AccessTokenValue\";\r\n\r\n/**\r\n * @hidden\r\n */\r\nexport class AccessTokenCacheItem {\r\n\r\n key: AccessTokenKey;\r\n value: AccessTokenValue;\r\n\r\n constructor(key: AccessTokenKey, value: AccessTokenValue) {\r\n this.key = key;\r\n this.value = value;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nimport { Constants } from \"../Constants\";\r\nimport { ClientAuthError } from \"./ClientAuthError\";\r\n\r\nexport const ClientConfigurationErrorMessage = {\r\n configurationNotSet: {\r\n code: \"no_config_set\",\r\n desc: \"Configuration has not been set. Please call the UserAgentApplication constructor with a valid Configuration object.\"\r\n },\r\n invalidCacheLocation: {\r\n code: \"invalid_cache_location\",\r\n desc: \"The cache location provided is not valid.\"\r\n },\r\n noStorageSupported: {\r\n code: \"browser_storage_not_supported\",\r\n desc: \"localStorage and sessionStorage are not supported.\"\r\n },\r\n noRedirectCallbacksSet: {\r\n code: \"no_redirect_callbacks\",\r\n desc: \"No redirect callbacks have been set. Please call setRedirectCallbacks() with the appropriate function arguments before continuing. \" +\r\n \"More information is available here: https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics.\"\r\n },\r\n invalidCallbackObject: {\r\n code: \"invalid_callback_object\",\r\n desc: \"The object passed for the callback was invalid. \" +\r\n \"More information is available here: https://github.com/AzureAD/microsoft-authentication-library-for-js/wiki/MSAL-basics.\"\r\n },\r\n scopesRequired: {\r\n code: \"scopes_required\",\r\n desc: \"Scopes are required to obtain an access token.\"\r\n },\r\n emptyScopes: {\r\n code: \"empty_input_scopes_error\",\r\n desc: \"Scopes cannot be passed as empty array.\"\r\n },\r\n nonArrayScopes: {\r\n code: \"nonarray_input_scopes_error\",\r\n desc: \"Scopes cannot be passed as non-array.\"\r\n },\r\n clientScope: {\r\n code: \"clientid_input_scopes_error\",\r\n desc: \"Client ID can only be provided as a single scope.\"\r\n },\r\n invalidPrompt: {\r\n code: \"invalid_prompt_value\",\r\n desc: \"Supported prompt values are 'login', 'select_account', 'consent' and 'none'\",\r\n },\r\n invalidAuthorityType: {\r\n code: \"invalid_authority_type\",\r\n desc: \"The given authority is not a valid type of authority supported by MSAL. Please see here for valid authorities: <insert URL here>.\"\r\n },\r\n authorityUriInsecure: {\r\n code: \"authority_uri_insecure\",\r\n desc: \"Authority URIs must use https.\"\r\n },\r\n authorityUriInvalidPath: {\r\n code: \"authority_uri_invalid_path\",\r\n desc: \"Given authority URI is invalid.\"\r\n },\r\n unsupportedAuthorityValidation: {\r\n code: \"unsupported_authority_validation\",\r\n desc: \"The authority validation is not supported for this authority type.\"\r\n },\r\n b2cAuthorityUriInvalidPath: {\r\n code: \"b2c_authority_uri_invalid_path\",\r\n desc: \"The given URI for the B2C authority is invalid.\"\r\n },\r\n claimsRequestParsingError: {\r\n code: \"claims_request_parsing_error\",\r\n desc: \"Could not parse the given claims request object.\"\r\n }\r\n};\r\n\r\n/**\r\n * Error thrown when there is an error in configuration of the .js library.\r\n */\r\nexport class ClientConfigurationError extends ClientAuthError {\r\n\r\n constructor(errorCode: string, errorMessage?: string) {\r\n super(errorCode, errorMessage);\r\n this.name = \"ClientConfigurationError\";\r\n Object.setPrototypeOf(this, ClientConfigurationError.prototype);\r\n }\r\n\r\n static createNoSetConfigurationError(): ClientConfigurationError {\r\n return new ClientConfigurationError(ClientConfigurationErrorMessage.configurationNotSet.code,\r\n `${ClientConfigurationErrorMessage.configurationNotSet.desc}`);\r\n }\r\n\r\n static createInvalidCacheLocationConfigError(givenCacheLocation: string): ClientConfigurationError {\r\n return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidCacheLocation.code,\r\n `${ClientConfigurationErrorMessage.invalidCacheLocation.desc} Provided value: ${givenCacheLocation}. Possible values are: ${Constants.cacheLocationLocal}, ${Constants.cacheLocationSession}.`);\r\n }\r\n\r\n static createNoStorageSupportedError() : ClientConfigurationError {\r\n return new ClientConfigurationError(ClientConfigurationErrorMessage.noStorageSupported.code,\r\n ClientConfigurationErrorMessage.noStorageSupported.desc);\r\n }\r\n\r\n static createRedirectCallbacksNotSetError(): ClientConfigurationError {\r\n return new ClientConfigurationError(ClientConfigurationErrorMessage.noRedirectCallbacksSet.code, ClientConfigurationErrorMessage.noRedirectCallbacksSet.desc);\r\n }\r\n\r\n static createInvalidCallbackObjectError(callbackObject: object): ClientConfigurationError {\r\n return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidCallbackObject.code,\r\n `${ClientConfigurationErrorMessage.invalidCallbackObject.desc} Given value for callback function: ${callbackObject}`);\r\n }\r\n\r\n static createEmptyScopesArrayError(scopesValue: string): ClientConfigurationError {\r\n return new ClientConfigurationError(ClientConfigurationErrorMessage.emptyScopes.code,\r\n `${ClientConfigurationErrorMessage.emptyScopes.desc} Given value: ${scopesValue}.`);\r\n }\r\n\r\n static createScopesNonArrayError(scopesValue: string): ClientConfigurationError {\r\n return new ClientConfigurationError(ClientConfigurationErrorMessage.nonArrayScopes.code,\r\n `${ClientConfigurationErrorMessage.nonArrayScopes.desc} Given value: ${scopesValue}.`);\r\n }\r\n\r\n static createClientIdSingleScopeError(scopesValue: string): ClientConfigurationError {\r\n return new ClientConfigurationError(ClientConfigurationErrorMessage.clientScope.code,\r\n `${ClientConfigurationErrorMessage.clientScope.desc} Given value: ${scopesValue}.`);\r\n }\r\n\r\n static createScopesRequiredError(scopesValue: any): ClientConfigurationError {\r\n return new ClientConfigurationError(ClientConfigurationErrorMessage.scopesRequired.code,\r\n `${ClientConfigurationErrorMessage.scopesRequired.desc} Given value: ${scopesValue}`);\r\n }\r\n\r\n static createInvalidPromptError(promptValue: any): ClientConfigurationError {\r\n return new ClientConfigurationError(ClientConfigurationErrorMessage.invalidPrompt.code,\r\n `${ClientConfigurationErrorMessage.invalidPrompt.desc} Given value: ${promptValue}`);\r\n }\r\n\r\n static createClaimsRequestParsingError(claimsRequestParseError: string): ClientConfigurationError {\r\n return new ClientConfigurationError(ClientConfigurationErrorMessage.claimsRequestParsingError.code,\r\n `${ClientConfigurationErrorMessage.claimsRequestParsingError.desc} Given value: ${claimsRequestParseError}`);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nimport { Constants } from \"./Constants\";\r\nimport { AccessTokenCacheItem } from \"./AccessTokenCacheItem\";\r\nimport { CacheLocation } from \"./Configuration\";\r\nimport { CacheKeys } from \"./Constants\";\r\nimport { ClientConfigurationError } from \"./error/ClientConfigurationError\";\r\n\r\n/**\r\n * @hidden\r\n */\r\nexport class Storage {// Singleton\r\n\r\n private static instance: Storage;\r\n private localStorageSupported: boolean;\r\n private sessionStorageSupported: boolean;\r\n private cacheLocation: CacheLocation;\r\n\r\n constructor(cacheLocation: CacheLocation) {\r\n if (Storage.instance) {\r\n return Storage.instance;\r\n }\r\n\r\n this.cacheLocation = cacheLocation;\r\n this.localStorageSupported = typeof window[this.cacheLocation] !== \"undefined\" && window[this.cacheLocation] != null;\r\n this.sessionStorageSupported = typeof window[cacheLocation] !== \"undefined\" && window[cacheLocation] != null;\r\n Storage.instance = this;\r\n if (!this.localStorageSupported && !this.sessionStorageSupported) {\r\n throw ClientConfigurationError.createNoStorageSupportedError();\r\n }\r\n\r\n return Storage.instance;\r\n }\r\n\r\n // add value to storage\r\n setItem(key: string, value: string, enableCookieStorage?: boolean): void {\r\n if (window[this.cacheLocation]) {\r\n window[this.cacheLocation].setItem(key, value);\r\n }\r\n if (enableCookieStorage) {\r\n this.setItemCookie(key, value);\r\n }\r\n }\r\n\r\n // get one item by key from storage\r\n getItem(key: string, enableCookieStorage?: boolean): string {\r\n if (enableCookieStorage && this.getItemCookie(key)) {\r\n return this.getItemCookie(key);\r\n }\r\n if (window[this.cacheLocation]) {\r\n return window[this.cacheLocation].getItem(key);\r\n }\r\n return null;\r\n }\r\n\r\n // remove value from storage\r\n removeItem(key: string): void {\r\n if (window[this.cacheLocation]) {\r\n return window[this.cacheLocation].removeItem(key);\r\n }\r\n }\r\n\r\n // clear storage (remove all items from it)\r\n clear(): void {\r\n if (window[this.cacheLocation]) {\r\n return window[this.cacheLocation].clear();\r\n }\r\n }\r\n\r\n getAllAccessTokens(clientId: string, homeAccountIdentifier: string): Array<AccessTokenCacheItem> {\r\n const results: Array<AccessTokenCacheItem> = [];\r\n let accessTokenCacheItem: AccessTokenCacheItem;\r\n const storage = window[this.cacheLocation];\r\n if (storage) {\r\n let key: string;\r\n for (key in storage) {\r\n if (storage.hasOwnProperty(key)) {\r\n if (key.match(clientId) && key.match(homeAccountIdentifier)) {\r\n const value = this.getItem(key);\r\n if (value) {\r\n accessTokenCacheItem = new AccessTokenCacheItem(JSON.parse(key), JSON.parse(value));\r\n results.push(accessTokenCacheItem);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n return results;\r\n }\r\n\r\n removeAcquireTokenEntries(state?: string): void {\r\n const storage = window[this.cacheLocation];\r\n if (storage) {\r\n let key: string;\r\n for (key in storage) {\r\n if (storage.hasOwnProperty(key)) {\r\n if ((key.indexOf(CacheKeys.AUTHORITY) !== -1 || key.indexOf(CacheKeys.ACQUIRE_TOKEN_ACCOUNT) !== 1) && (!state || key.indexOf(state) !== -1)) {\r\n const splitKey = key.split(Constants.resourceDelimiter);\r\n let state;\r\n if (splitKey.length > 1) {\r\n state = splitKey[1];\r\n }\r\n if (state && !this.tokenRenewalInProgress(state)) {\r\n this.removeItem(key);\r\n this.removeItem(Constants.renewStatus + state);\r\n this.removeItem(Constants.stateLogin);\r\n this.removeItem(Constants.stateAcquireToken);\r\n this.setItemCookie(key, \"\", -1);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n this.clearCookie();\r\n }\r\n\r\n private tokenRenewalInProgress(stateValue: string): boolean {\r\n const storage = window[this.cacheLocation];\r\n const renewStatus = storage[Constants.renewStatus + stateValue];\r\n return !(!renewStatus || renewStatus !== Constants.tokenRenewStatusInProgress);\r\n }\r\n\r\n resetCacheItems(): void {\r\n const storage = window[this.cacheLocation];\r\n if (storage) {\r\n let key: string;\r\n for (key in storage) {\r\n if (storage.hasOwnProperty(key)) {\r\n if (key.indexOf(Constants.msal) !== -1) {\r\n this.removeItem(key);\r\n }\r\n }\r\n }\r\n this.removeAcquireTokenEntries();\r\n }\r\n }\r\n\r\n setItemCookie(cName: string, cValue: string, expires?: number): void {\r\n let cookieStr = cName + \"=\" + cValue + \";\";\r\n if (expires) {\r\n const expireTime = this.getCookieExpirationTime(expires);\r\n cookieStr += \"expires=\" + expireTime + \";\";\r\n }\r\n\r\n document.cookie = cookieStr;\r\n }\r\n\r\n getItemCookie(cName: string): string {\r\n const name = cName + \"=\";\r\n const ca = document.cookie.split(\";\");\r\n for (let i = 0; i < ca.length; i++) {\r\n let c = ca[i];\r\n while (c.charAt(0) === \" \") {\r\n c = c.substring(1);\r\n }\r\n if (c.indexOf(name) === 0) {\r\n return c.substring(name.length, c.length);\r\n }\r\n }\r\n return \"\";\r\n }\r\n\r\n getCookieExpirationTime(cookieLifeDays: number): string {\r\n const today = new Date();\r\n const expr = new Date(today.getTime() + cookieLifeDays * 24 * 60 * 60 * 1000);\r\n return expr.toUTCString();\r\n }\r\n\r\n clearCookie(): void {\r\n this.setItemCookie(Constants.nonceIdToken, \"\", -1);\r\n this.setItemCookie(Constants.stateLogin, \"\", -1);\r\n this.setItemCookie(Constants.loginRequest, \"\", -1);\r\n this.setItemCookie(Constants.stateAcquireToken, \"\", -1);\r\n }\r\n\r\n /**\r\n * Create acquireTokenAccountKey to cache account object\r\n * @param accountId\r\n * @param state\r\n */\r\n static generateAcquireTokenAccountKey(accountId: any, state: string): string {\r\n return CacheKeys.ACQUIRE_TOKEN_ACCOUNT + Constants.resourceDelimiter +\r\n `${accountId}` + Constants.resourceDelimiter + `${state}`;\r\n }\r\n\r\n /**\r\n * Create authorityKey to cache authority\r\n * @param state\r\n */\r\n static generateAuthorityKey(state: string): string {\r\n return CacheKeys.AUTHORITY + Constants.resourceDelimiter + `${state}`;\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nimport { ClientInfo } from \"./ClientInfo\";\r\nimport { IdToken } from \"./IdToken\";\r\nimport { Utils } from \"./Utils\";\r\n\r\n/**\r\n * accountIdentifier combination of idToken.uid and idToken.utid\r\n * homeAccountIdentifier combination of clientInfo.uid and clientInfo.utid\r\n * userName idToken.preferred_username\r\n * name idToken.name\r\n * idToken idToken\r\n * sid idToken.sid - session identifier\r\n * environment idtoken.issuer (the authority that issues the token)\r\n */\r\nexport class Account {\r\n\r\n accountIdentifier: string;\r\n homeAccountIdentifier: string;\r\n userName: string;\r\n name: string;\r\n idToken: Object;\r\n sid: string;\r\n environment: string;\r\n\r\n /**\r\n * Creates an Account Object\r\n * @praram accountIdentifier\r\n * @param homeAccountIdentifier\r\n * @param userName\r\n * @param name\r\n * @param idToken\r\n * @param sid\r\n * @param environment\r\n */\r\n constructor(accountIdentifier: string, homeAccountIdentifier: string, userName: string, name: string, idToken: Object, sid: string, environment: string) {\r\n this.accountIdentifier = accountIdentifier;\r\n this.homeAccountIdentifier = homeAccountIdentifier;\r\n this.userName = userName;\r\n this.name = name;\r\n this.idToken = idToken;\r\n this.sid = sid;\r\n this.environment = environment;\r\n }\r\n\r\n /**\r\n * @hidden\r\n * @param idToken\r\n * @param clientInfo\r\n */\r\n static createAccount(idToken: IdToken, clientInfo: ClientInfo): Account {\r\n\r\n // create accountIdentifier\r\n const accountIdentifier: string = idToken.objectId || idToken.subject;\r\n\r\n // create homeAccountIdentifier\r\n const uid: string = clientInfo ? clientInfo.uid : \"\";\r\n const utid: string = clientInfo ? clientInfo.utid : \"\";\r\n\r\n let homeAccountIdentifier: string;\r\n if (!Utils.isEmpty(uid) && !Utils.isEmpty(utid)) {\r\n homeAccountIdentifier = Utils.base64EncodeStringUrlSafe(uid) + \".\" + Utils.base64EncodeStringUrlSafe(utid);\r\n }\r\n return new Account(accountIdentifier, homeAccountIdentifier, idToken.preferredName, idToken.name, idToken.decodedIdToken, idToken.sid, idToken.issuer);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\n/**\r\n * XHR client for JSON endpoints\r\n * https://www.npmjs.com/package/async-promise\r\n * @hidden\r\n */\r\nexport class XhrClient {\r\n public sendRequestAsync(url: string, method: string, enableCaching?: boolean): Promise<any> {\r\n return new Promise<string>((resolve, reject) => {\r\n var xhr = new XMLHttpRequest();\r\n xhr.open(method, url, /*async: */ true);\r\n if (enableCaching) {\r\n // TODO: (shivb) ensure that this can be cached\r\n // xhr.setRequestHeader(\"Cache-Control\", \"Public\");\r\n }\r\n\r\n xhr.onload = (ev) => {\r\n if (xhr.status < 200 || xhr.status >= 300) {\r\n reject(this.handleError(xhr.responseText));\r\n }\r\n\r\n try {\r\n var jsonResponse = JSON.parse(xhr.responseText);\r\n } catch (e) {\r\n reject(this.handleError(xhr.responseText));\r\n }\r\n\r\n resolve(jsonResponse);\r\n };\r\n\r\n xhr.onerror = (ev) => {\r\n reject(xhr.status);\r\n };\r\n\r\n if (method === \"GET\") {\r\n xhr.send();\r\n }\r\n else {\r\n throw \"not implemented\";\r\n }\r\n });\r\n }\r\n\r\n protected handleError(responseText: string): any {\r\n var jsonResponse;\r\n try {\r\n jsonResponse = JSON.parse(responseText);\r\n if (jsonResponse.error) {\r\n return jsonResponse.error;\r\n } else {\r\n throw responseText;\r\n }\r\n } catch (e) {\r\n return responseText;\r\n }\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nimport { IUri } from \"./IUri\";\r\nimport { Utils } from \"./Utils\";\r\nimport { ITenantDiscoveryResponse } from \"./ITenantDiscoveryResponse\";\r\nimport { ClientConfigurationErrorMessage } from \"./error/ClientConfigurationError\";\r\nimport { XhrClient } from \"./XHRClient\";\r\n\r\n/**\r\n * @hidden\r\n */\r\nexport enum AuthorityType {\r\n Aad,\r\n Adfs,\r\n B2C\r\n}\r\n\r\n/**\r\n * @hidden\r\n */\r\nexport abstract class Authority {\r\n constructor(authority: string, validateAuthority: boolean) {\r\n this.IsValidationEnabled = validateAuthority;\r\n this.CanonicalAuthority = authority;\r\n\r\n this.validateAsUri();\r\n }\r\n\r\n public abstract get AuthorityType(): AuthorityType;\r\n\r\n public IsValidationEnabled: boolean;\r\n\r\n public get Tenant(): string {\r\n return this.CanonicalAuthorityUrlComponents.PathSegments[0];\r\n }\r\n\r\n private tenantDiscoveryResponse: ITenantDiscoveryResponse;\r\n\r\n public get AuthorizationEndpoint(): string {\r\n this.validateResolved();\r\n return this.tenantDiscoveryResponse.AuthorizationEndpoint.replace(\"{tenant}\", this.Tenant);\r\n }\r\n\r\n public get EndSessionEndpoint(): string {\r\n this.validateResolved();\r\n return this.tenantDiscoveryResponse.EndSessionEndpoint.replace(\"{tenant}\", this.Tenant);\r\n }\r\n\r\n public get SelfSignedJwtAudience(): string {\r\n this.validateResolved();\r\n return this.tenantDiscoveryResponse.Issuer.replace(\"{tenant}\", this.Tenant);\r\n }\r\n\r\n private validateResolved() {\r\n if (!this.tenantDiscoveryResponse) {\r\n throw \"Please call ResolveEndpointsAsync first\";\r\n }\r\n }\r\n\r\n /**\r\n * A URL that is the authority set by the developer\r\n */\r\n public get CanonicalAuthority(): string {\r\n return this.canonicalAuthority;\r\n }\r\n\r\n public set CanonicalAuthority(url: string) {\r\n this.canonicalAuthority = Utils.CanonicalizeUri(url);\r\n this.canonicalAuthorityUrlComponents = null;\r\n }\r\n\r\n private canonicalAuthority: string;\r\n private canonicalAuthorityUrlComponents: IUri;\r\n\r\n public get CanonicalAuthorityUrlComponents(): IUri {\r\n if (!this.canonicalAuthorityUrlComponents) {\r\n this.canonicalAuthorityUrlComponents = Utils.GetUrlComponents(this.CanonicalAuthority);\r\n }\r\n\r\n return this.canonicalAuthorityUrlComponents;\r\n }\r\n\r\n /**\r\n * // http://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata\r\n */\r\n protected get DefaultOpenIdConfigurationEndpoint(): string {\r\n return `${this.CanonicalAuthority}v2.0/.well-known/openid-configuration`;\r\n }\r\n\r\n /**\r\n * Given a string, validate that it is of the form https://domain/path\r\n */\r\n private validateAsUri() {\r\n let components;\r\n try {\r\n components = this.CanonicalAuthorityUrlComponents;\r\n } catch (e) {\r\n throw ClientConfigurationErrorMessage.invalidAuthorityType;\r\n }\r\n\r\n if (!components.Protocol || components.Protocol.toLowerCase() !== \"https:\") {\r\n throw ClientConfigurationErrorMessage.authorityUriInsecure;\r\n }\r\n\r\n if (!components.PathSegments || components.PathSegments.length < 1) {\r\n throw ClientConfigurationErrorMessage.authorityUriInvalidPath;\r\n }\r\n }\r\n\r\n /**\r\n * Calls the OIDC endpoint and returns the response\r\n */\r\n private DiscoverEndpoints(openIdConfigurationEndpoint: string): Promise<ITenantDiscoveryResponse> {\r\n const client = new XhrClient();\r\n return client.sendRequestAsync(openIdConfigurationEndpoint, \"GET\", /*enableCaching: */ true)\r\n .then((response: any) => {\r\n return <ITenantDiscoveryResponse>{\r\n AuthorizationEndpoint: response.authorization_endpoint,\r\n EndSessionEndpoint: response.end_session_endpoint,\r\n Issuer: response.issuer\r\n };\r\n });\r\n }\r\n\r\n /**\r\n * Returns a promise.\r\n * Checks to see if the authority is in the cache\r\n * Discover endpoints via openid-configuration\r\n * If successful, caches the endpoint for later use in OIDC\r\n */\r\n public resolveEndpointsAsync(): Promise<Authority> {\r\n let openIdConfigurationEndpoint = \"\";\r\n return this.GetOpenIdConfigurationEndpointAsync().then(openIdConfigurationEndpointResponse => {\r\n openIdConfigurationEndpoint = openIdConfigurationEndpointResponse;\r\n return this.DiscoverEndpoints(openIdConfigurationEndpoint);\r\n }).then((tenantDiscoveryResponse: ITenantDiscoveryResponse) => {\r\n this.tenantDiscoveryResponse = tenantDiscoveryResponse;\r\n return this;\r\n });\r\n }\r\n\r\n /**\r\n * Returns a promise with the TenantDiscoveryEndpoint\r\n */\r\n public abstract GetOpenIdConfigurationEndpointAsync(): Promise<string>;\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nimport { Authority, AuthorityType } from \"./Authority\";\r\nimport { XhrClient } from \"./XHRClient\";\r\n\r\n/**\r\n * @hidden\r\n */\r\nexport class AadAuthority extends Authority {\r\n private static readonly AadInstanceDiscoveryEndpoint: string = \"https://login.microsoftonline.com/common/discovery/instance\";\r\n\r\n private get AadInstanceDiscoveryEndpointUrl(): string {\r\n return `${AadAuthority.AadInstanceDiscoveryEndpoint}?api-version=1.0&authorization_endpoint=${this.CanonicalAuthority}oauth2/v2.0/authorize`;\r\n }\r\n\r\n public constructor(authority: string, validateAuthority: boolean) {\r\n super(authority, validateAuthority);\r\n }\r\n\r\n public get AuthorityType(): AuthorityType {\r\n return AuthorityType.Aad;\r\n }\r\n\r\n private static readonly TrustedHostList: any = {\r\n \"login.windows.net\": \"login.windows.net\",\r\n \"login.chinacloudapi.cn\": \"login.chinacloudapi.cn\",\r\n \"login.cloudgovapi.us\": \"login.cloudgovapi.us\",\r\n \"login.microsoftonline.com\": \"login.microsoftonline.com\",\r\n \"login.microsoftonline.de\": \"login.microsoftonline.de\",\r\n \"login.microsoftonline.us\": \"login.microsoftonline.us\"\r\n };\r\n\r\n /**\r\n * Returns a promise which resolves to the OIDC endpoint\r\n * Only responds with the endpoint\r\n */\r\n public GetOpenIdConfigurationEndpointAsync(): Promise<string> {\r\n const resultPromise: Promise<string> = new Promise<string>((resolve, reject) =>\r\n resolve(this.DefaultOpenIdConfigurationEndpoint));\r\n\r\n if (!this.IsValidationEnabled) {\r\n return resultPromise;\r\n }\r\n\r\n let host: string = this.CanonicalAuthorityUrlComponents.HostNameAndPort;\r\n if (this.IsInTrustedHostList(host)) {\r\n return resultPromise;\r\n }\r\n\r\n let client: XhrClient = new XhrClient();\r\n\r\n return client.sendRequestAsync(this.AadInstanceDiscoveryEndpointUrl, \"GET\", true)\r\n .then((response) => {\r\n return response.tenant_discovery_endpoint;\r\n });\r\n }\r\n\r\n /**\r\n * Checks to see if the host is in a list of trusted hosts\r\n * @param {string} The host to look up\r\n */\r\n public IsInTrustedHostList(host: string): boolean {\r\n return AadAuthority.TrustedHostList[host.toLowerCase()];\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nimport { AadAuthority } from \"./AadAuthority\";\r\nimport { Authority, AuthorityType } from \"./Authority\";\r\nimport { ClientConfigurationErrorMessage } from \"./error/ClientConfigurationError\";\r\nimport { Utils } from \"./Utils\";\r\n\r\n/**\r\n * @hidden\r\n */\r\nexport class B2cAuthority extends AadAuthority {\r\n public constructor(authority: string, validateAuthority: boolean) {\r\n super(authority, validateAuthority);\r\n const urlComponents = Utils.GetUrlComponents(authority);\r\n\r\n const pathSegments = urlComponents.PathSegments;\r\n if (pathSegments.length < 3) {\r\n throw ClientConfigurationErrorMessage.b2cAuthorityUriInvalidPath;\r\n }\r\n\r\n this.CanonicalAuthority = `https://${urlComponents.HostNameAndPort}/${pathSegments[0]}/${pathSegments[1]}/${pathSegments[2]}/`;\r\n }\r\n\r\n public get AuthorityType(): AuthorityType {\r\n return AuthorityType.B2C;\r\n }\r\n\r\n /**\r\n * Returns a promise with the TenantDiscoveryEndpoint\r\n */\r\n public GetOpenIdConfigurationEndpointAsync(): Promise<string> {\r\n const resultPromise = new Promise<string>((resolve, reject) =>\r\n resolve(this.DefaultOpenIdConfigurationEndpoint));\r\n\r\n if (!this.IsValidationEnabled) {\r\n return resultPromise;\r\n }\r\n\r\n if (this.IsInTrustedHostList(this.CanonicalAuthorityUrlComponents.HostNameAndPort)) {\r\n return resultPromise;\r\n }\r\n\r\n return new Promise<string>((resolve, reject) =>\r\n reject(ClientConfigurationErrorMessage.unsupportedAuthorityValidation));\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\n/**\r\n * @hidden\r\n */\r\nimport { Utils } from \"./Utils\";\r\nimport { AadAuthority } from \"./AadAuthority\";\r\nimport { B2cAuthority } from \"./B2cAuthority\";\r\nimport { Authority, AuthorityType } from \"./Authority\";\r\nimport { ClientConfigurationErrorMessage } from \"./error/ClientConfigurationError\";\r\n\r\nexport class AuthorityFactory {\r\n /**\r\n * Parse the url and determine the type of authority\r\n */\r\n private static DetectAuthorityFromUrl(authorityUrl: string): AuthorityType {\r\n authorityUrl = Utils.CanonicalizeUri(authorityUrl);\r\n const components = Utils.GetUrlComponents(authorityUrl);\r\n const pathSegments = components.PathSegments;\r\n switch (pathSegments[0]) {\r\n case \"tfp\":\r\n return AuthorityType.B2C;\r\n case \"adfs\":\r\n return AuthorityType.Adfs;\r\n default:\r\n return AuthorityType.Aad;\r\n }\r\n }\r\n\r\n /**\r\n * Create an authority object of the correct type based on the url\r\n * Performs basic authority validation - checks to see if the authority is of a valid type (eg aad, b2c)\r\n */\r\n public static CreateInstance(authorityUrl: string, validateAuthority: boolean): Authority {\r\n if (Utils.isEmpty(authorityUrl)) {\r\n return null;\r\n }\r\n const type = AuthorityFactory.DetectAuthorityFromUrl(authorityUrl);\r\n // Depending on above detection, create the right type.\r\n switch (type) {\r\n case AuthorityType.B2C:\r\n return new B2cAuthority(authorityUrl, validateAuthority);\r\n case AuthorityType.Aad:\r\n return new AadAuthority(authorityUrl, validateAuthority);\r\n default:\r\n throw ClientConfigurationErrorMessage.invalidAuthorityType;\r\n }\r\n }\r\n\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nimport { Utils } from \"./Utils\";\r\n\r\nexport interface ILoggerCallback {\r\n (level: LogLevel, message: string, containsPii: boolean): void;\r\n}\r\n\r\nexport enum LogLevel {\r\n Error,\r\n Warning,\r\n Info,\r\n Verbose\r\n}\r\n\r\nexport class Logger {// Singleton Class\r\n\r\n /**\r\n * @hidden\r\n */\r\n // TODO: This does not seem to be a singleton!! Change or Delete.\r\n private static instance: Logger;\r\n\r\n /**\r\n * @hidden\r\n */\r\n private correlationId: string;\r\n\r\n /**\r\n * @hidden\r\n */\r\n private level: LogLevel = LogLevel.Info;\r\n\r\n /**\r\n * @hidden\r\n */\r\n private piiLoggingEnabled: boolean;\r\n\r\n /**\r\n * @hidden\r\n */\r\n private localCallback: ILoggerCallback;\r\n\r\n constructor(localCallback: ILoggerCallback,\r\n options:\r\n {\r\n correlationId?: string,\r\n level?: LogLevel,\r\n piiLoggingEnabled?: boolean,\r\n } = {}) {\r\n const {\r\n correlationId = \"\",\r\n level = LogLevel.Info,\r\n piiLoggingEnabled = false\r\n } = options;\r\n\r\n this.localCallback = localCallback;\r\n this.correlationId = correlationId;\r\n this.level = level;\r\n this.piiLoggingEnabled = piiLoggingEnabled;\r\n }\r\n\r\n /**\r\n * @hidden\r\n */\r\n private logMessage(logLevel: LogLevel, logMessage: string, containsPii: boolean): void {\r\n if ((logLevel > this.level) || (!this.piiLoggingEnabled && containsPii)) {\r\n return;\r\n }\r\n const timestamp = new Date().toUTCString();\r\n let log: string;\r\n if (!Utils.isEmpty(this.correlationId)) {\r\n log = timestamp + \":\" + this.correlationId + \"-\" + Utils.getLibraryVersion() + \"-\" + LogLevel[logLevel] + \" \" + logMessage;\r\n }\r\n else {\r\n log = timestamp + \":\" + Utils.getLibraryVersion() + \"-\" + LogLevel[logLevel] + \" \" + logMessage;\r\n }\r\n this.executeCallback(logLevel, log, containsPii);\r\n }\r\n\r\n /**\r\n * @hidden\r\n */\r\n executeCallback(level: LogLevel, message: string, containsPii: boolean) {\r\n if (this.localCallback) {\r\n this.localCallback(level, message, containsPii);\r\n }\r\n }\r\n\r\n /**\r\n * @hidden\r\n */\r\n error(message: string): void {\r\n this.logMessage(LogLevel.Error, message, false);\r\n }\r\n\r\n /**\r\n * @hidden\r\n */\r\n errorPii(message: string): void {\r\n this.logMessage(LogLevel.Error, message, true);\r\n }\r\n\r\n /**\r\n * @hidden\r\n */\r\n warning(message: string): void {\r\n this.logMessage(LogLevel.Warning, message, false);\r\n }\r\n\r\n /**\r\n * @hidden\r\n */\r\n warningPii(message: string): void {\r\n this.logMessage(LogLevel.Warning, message, true);\r\n }\r\n\r\n /**\r\n * @hidden\r\n */\r\n info(message: string): void {\r\n this.logMessage(LogLevel.Info, message, false);\r\n }\r\n\r\n /**\r\n * @hidden\r\n */\r\n infoPii(message: string): void {\r\n this.logMessage(LogLevel.Info, message, true);\r\n }\r\n\r\n /**\r\n * @hidden\r\n */\r\n verbose(message: string): void {\r\n this.logMessage(LogLevel.Verbose, message, false);\r\n }\r\n\r\n /**\r\n * @hidden\r\n */\r\n verbosePii(message: string): void {\r\n this.logMessage(LogLevel.Verbose, message, true);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nimport { Logger } from \"./Logger\";\r\nimport { Utils } from \"./Utils\";\r\n\r\n/**\r\n * Cache location options supported by MSAL are:\r\n * - local storage: MSAL uses browsers local storage to store its cache\r\n * - session storage: MSAL uses the browsers session storage to store its cache\r\n */\r\nexport type CacheLocation = \"localStorage\" | \"sessionStorage\";\r\n\r\n/**\r\n * Defaults for the Configuration Options\r\n */\r\nconst FRAME_TIMEOUT = 6000;\r\nconst OFFSET = 300;\r\nconst NAVIGATE_FRAME_WAIT = 500;\r\n\r\n\r\n/**\r\n * @type AuthOptions: Use this to configure the auth options in the Configuration object\r\n *\r\n * - clientId - Client ID of your app registered with our Application registration portal : https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredAppsPreview in Microsoft Identity Platform\r\n * - authority - You can configure a specific authority, defaults to \" \" or \"https://login.microsoftonline.com/common\"\r\n * - validateAuthority - Used to turn authority validation on/off. When set to true (default), MSAL will compare the application's authority against well-known URLs templates representing well-formed authorities. It is useful when the authority is obtained at run time to prevent MSAL from displaying authentication prompts from malicious pages.\r\n * - redirectUri - The redirect URI of the application, this should be same as the value in the application registration portal.Defaults to `window.location.href`.\r\n * - postLogoutRedirectUri - Used to redirect the user to this location after logout. Defaults to `window.location.href`.\r\n * - state - Use to send the state parameter with authentication request\r\n * - navigateToLoginRequestUrl - Used to turn off default navigation to start page after login. Default is true. This is used only for redirect flows.\r\n *\r\n */\r\nexport type AuthOptions = {\r\n clientId: string;\r\n authority?: string;\r\n validateAuthority?: boolean;\r\n redirectUri?: string | (() => string);\r\n postLogoutRedirectUri?: string | (() => string);\r\n navigateToLoginRequestUrl?: boolean;\r\n};\r\n\r\n/**\r\n * Use this to configure the below cache configuration options:\r\n *\r\n * - cacheLocation - Used to specify the cacheLocation user wants to set. Valid values are \"localStorage\" and \"sessionStorage\"\r\n * - storeAuthStateInCookie - If set, MSAL store's the auth request state required for validation of the auth flows in the browser cookies. By default this flag is set to false.\r\n */\r\nexport type CacheOptions = {\r\n cacheLocation?: CacheLocation;\r\n storeAuthStateInCookie?: boolean;\r\n};\r\n\r\n/**\r\n * Library Specific Options\r\n *\r\n * - logger - Used to initialize the Logger object; TODO: Expand on logger details or link to the documentation on logger\r\n * - loadFrameTimeout - maximum time the library should wait for a frame to load\r\n * - tokenRenewalOffsetSeconds - sets the window of offset needed to renew the token before expiry\r\n *\r\n */\r\nexport type SystemOptions = {\r\n logger?: Logger;\r\n loadFrameTimeout?: number;\r\n tokenRenewalOffsetSeconds?: number;\r\n navigateFrameWait?: number;\r\n};\r\n\r\n/**\r\n * App/Framework specific environment support\r\n *\r\n * - isAngular - flag set to determine if it is Angular Framework. MSAL uses this to broadcast tokens. More to come here: detangle this dependency from core.\r\n * - unprotectedResources - Array of URI's which are unprotected resources. MSAL will not attach a token to outgoing requests that have these URI. Defaults to 'null'.\r\n * - protectedResourceMap - This is mapping of resources to scopes used by MSAL for automatically attaching access tokens in web API calls.A single access token is obtained for the resource. So you can map a specific resource path as follows: {\"https://graph.microsoft.com/v1.0/me\", [\"user.read\"]}, or the app URL of the resource as: {\"https://graph.microsoft.com/\", [\"user.read\", \"mail.send\"]}. This is required for CORS calls.\r\n *\r\n */\r\nexport type FrameworkOptions = {\r\n isAngular?: boolean;\r\n unprotectedResources?: Array<string>;\r\n protectedResourceMap?: Map<string, Array<string>>;\r\n};\r\n\r\n/**\r\n * Use the configuration object to configure MSAL and initialize the UserAgentApplication.\r\n *\r\n * This object allows you to configure important elements of MSAL functionality:\r\n * - auth: this is where you configure auth elements like clientID, authority used for authenticating against the Microsoft Identity Platform\r\n * - cache: this is where you configure cache location and whether to store cache in cookies\r\n * - system: this is where you can configure the logger, frame timeout etc.\r\n * - framework: this is where you can configure the running mode of angular. More to come here soon.\r\n */\r\nexport type Configuration = {\r\n auth: AuthOptions,\r\n cache?: CacheOptions,\r\n system?: SystemOptions,\r\n framework?: FrameworkOptions\r\n};\r\n\r\nconst DEFAULT_AUTH_OPTIONS: AuthOptions = {\r\n clientId: \"\",\r\n authority: null,\r\n validateAuthority: true,\r\n redirectUri: () => Utils.getDefaultRedirectUri(),\r\n postLogoutRedirectUri: () => Utils.getDefaultRedirectUri(),\r\n navigateToLoginRequestUrl: true\r\n};\r\n\r\nconst DEFAULT_CACHE_OPTIONS: CacheOptions = {\r\n cacheLocation: \"sessionStorage\",\r\n storeAuthStateInCookie: false\r\n};\r\n\r\nconst DEFAULT_SYSTEM_OPTIONS: SystemOptions = {\r\n logger: new Logger(null),\r\n loadFrameTimeout: FRAME_TIMEOUT,\r\n tokenRenewalOffsetSeconds: OFFSET,\r\n navigateFrameWait: NAVIGATE_FRAME_WAIT\r\n};\r\n\r\nconst DEFAULT_FRAMEWORK_OPTIONS: FrameworkOptions = {\r\n isAngular: false,\r\n unprotectedResources: new Array<string>(),\r\n protectedResourceMap: new Map<string, Array<string>>()\r\n};\r\n\r\n/**\r\n * MSAL function that sets the default options when not explicitly configured from app developer\r\n *\r\n * @param TAuthOptions\r\n * @param TCacheOptions\r\n * @param TSystemOptions\r\n * @param TFrameworkOptions\r\n *\r\n * @returns TConfiguration object\r\n */\r\n\r\nexport function buildConfiguration({ auth, cache = {}, system = {}, framework = {}}: Configuration): Configuration {\r\n const overlayedConfig: Configuration = {\r\n auth: { ...DEFAULT_AUTH_OPTIONS, ...auth },\r\n cache: { ...DEFAULT_CACHE_OPTIONS, ...cache },\r\n system: { ...DEFAULT_SYSTEM_OPTIONS, ...system },\r\n framework: { ...DEFAULT_FRAMEWORK_OPTIONS, ...framework }\r\n };\r\n return overlayedConfig;\r\n}\r\n\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nimport { Account } from \"./Account\";\r\nimport { ClientConfigurationError } from \"./error/ClientConfigurationError\";\r\n\r\n/**\r\n * Key-Value type to support queryParams and extraQueryParams\r\n */\r\nexport type QPDict = {[key: string]: string};\r\n\r\n/**\r\n * @link AuthenticationParameters}AuthenticationParameters\r\n */\r\nexport type AuthenticationParameters = {\r\n scopes?: Array<string>;\r\n extraScopesToConsent?: Array<string>;\r\n prompt?: string;\r\n extraQueryParameters?: QPDict;\r\n claimsRequest?: string;\r\n authority?: string;\r\n state?: string;\r\n correlationId?: string;\r\n account?: Account;\r\n sid?: string;\r\n loginHint?: string;\r\n};\r\n\r\nexport function validateClaimsRequest(request: AuthenticationParameters) {\r\n if (!request.claimsRequest) {\r\n return;\r\n }\r\n let claims;\r\n try {\r\n claims = JSON.parse(request.claimsRequest);\r\n } catch (e) {\r\n throw ClientConfigurationError.createClaimsRequestParsingError(e);\r\n }\r\n\r\n // TODO: More validation will be added when the server team tells us how they have actually implemented claims\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nimport { AuthError } from \"./AuthError\";\r\n\r\nexport const ServerErrorMessage = {\r\n serverUnavailable: {\r\n code: \"server_unavailable\",\r\n desc: \"Server is temporarily unavailable.\"\r\n },\r\n unknownServerError: {\r\n code: \"unknown_server_error\"\r\n },\r\n};\r\n\r\n/**\r\n * Error thrown when there is an error with the server code, for example, unavailability.\r\n */\r\nexport class ServerError extends AuthError {\r\n\r\n constructor(errorCode: string, errorMessage?: string) {\r\n super(errorCode, errorMessage);\r\n this.name = \"ServerError\";\r\n\r\n Object.setPrototypeOf(this, ServerError.prototype);\r\n }\r\n\r\n static createServerUnavailableError(): ServerError {\r\n return new ServerError(ServerErrorMessage.serverUnavailable.code,\r\n ServerErrorMessage.serverUnavailable.desc);\r\n }\r\n\r\n static createUnknownServerError(errorDesc: string): ServerError {\r\n return new ServerError(ServerErrorMessage.unknownServerError.code,\r\n errorDesc);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nimport { ServerError } from \"./ServerError\";\r\n\r\nexport const InteractionRequiredAuthErrorMessage = {\r\n loginRequired: {\r\n code: \"login_required\"\r\n },\r\n interactionRequired: {\r\n code: \"interaction_required\"\r\n },\r\n consentRequired: {\r\n code: \"consent_required\"\r\n },\r\n};\r\n\r\n/**\r\n * Error thrown when the user is required to perform an interactive token request.\r\n */\r\nexport class InteractionRequiredAuthError extends ServerError {\r\n\r\n constructor(errorCode: string, errorMessage?: string) {\r\n super(errorCode, errorMessage);\r\n this.name = \"InteractionRequiredAuthError\";\r\n\r\n Object.setPrototypeOf(this, InteractionRequiredAuthError.prototype);\r\n }\r\n\r\n static createLoginRequiredAuthError(errorDesc: string): InteractionRequiredAuthError {\r\n return new InteractionRequiredAuthError(InteractionRequiredAuthErrorMessage.loginRequired.code, errorDesc);\r\n }\r\n\r\n static createInteractionRequiredAuthError(errorDesc: string): InteractionRequiredAuthError {\r\n return new InteractionRequiredAuthError(InteractionRequiredAuthErrorMessage.interactionRequired.code, errorDesc);\r\n }\r\n\r\n static createConsentRequiredAuthError(errorDesc: string): InteractionRequiredAuthError {\r\n return new InteractionRequiredAuthError(InteractionRequiredAuthErrorMessage.consentRequired.code, errorDesc);\r\n }\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nimport { Account } from \"./Account\";\r\nimport { IdToken } from \"./IdToken\";\r\n\r\n// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nexport type AuthResponse = {\r\n uniqueId: string;\r\n tenantId: string;\r\n tokenType: string;\r\n idToken: IdToken;\r\n accessToken: string;\r\n scopes: Array<string>;\r\n expiresOn: Date;\r\n account: Account;\r\n accountState: string;\r\n};\r\n\r\nexport function buildResponseStateOnly(state: string) : AuthResponse {\r\n return {\r\n uniqueId: \"\",\r\n tenantId: \"\",\r\n tokenType: \"\",\r\n idToken: null,\r\n accessToken: \"\",\r\n scopes: null,\r\n expiresOn: null,\r\n account: null,\r\n accountState: state\r\n };\r\n}\r\n","// Copyright (c) Microsoft Corporation. All rights reserved.\r\n// Licensed under the MIT License.\r\n\r\nimport { AccessTokenCacheItem } from \"./AccessTokenCacheItem\";\r\nimport { AccessTokenKey } from \"./AccessTokenKey\";\r\nimport { AccessTokenValue } from \"./AccessTokenValue\";\r\nimport { ServerRequestParameters } from \"./ServerRequestParameters\";\r\nimport { Authority } from \"./Authority\";\r\nimport { ClientInfo } from \"./ClientInfo\";\r\nimport { Constants, SSOTypes, PromptState } from \"./Constants\";\r\nimport { IdToken } from \"./IdToken\";\r\nimport { Logger } from \"./Logger\";\r\nimport { Storage } from \"./Storage\";\r\nimport { Account } from \"./Account\";\r\nimport { Utils } from \"./Utils\";\r\nimport { AuthorityFactory } from \"./AuthorityFactory\";\r\nimport { Configuration, buildConfiguration } from \"./Configuration\";\r\nimport { AuthenticationParameters, QPDict, validateClaimsRequest } from \"./AuthenticationParameters\";\r\nimport { ClientConfigurationError } from \"./error/ClientConfigurationError\";\r\nimport { AuthError } from \"./error/AuthError\";\r\nimport { ClientAuthError, ClientAuthErrorMessage } from \"./error/ClientAuthError\";\r\nimport { ServerError } from \"./error/ServerError\";\r\nimport { InteractionRequiredAuthError } from \"./error/InteractionRequiredAuthError\";\r\nimport { AuthResponse, buildResponseStateOnly } from \"./AuthResponse\";\r\n\r\n// default authority\r\nconst DEFAULT_AUTHORITY = \"https://login.microsoftonline.com/common\";\r\n\r\n/**\r\n * Interface to handle iFrame generation, Popup Window creation and redirect handling\r\n */\r\ndeclare global {\r\n interface Window {\r\n msal: Object;\r\n CustomEvent: CustomEvent;\r\n Event: Event;\r\n activeRenewals: {};\r\n renewStates: Array<string>;\r\n callbackMappedToRenewStates : {};\r\n promiseMappedToRenewStates: {};\r\n openedWindows: Array<Window>;\r\n requestType: string;\r\n }\r\n}\r\n\r\n/**\r\n * @hidden\r\n * @ignore\r\n * response_type from OpenIDConnect\r\n * References: https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html & https://tools.ietf.org/html/rfc6749#section-4.2.1\r\n * Since we support only implicit flow in this library, we restrict the response_type support to only 'token' and 'id_token'\r\n *\r\n */\r\nconst ResponseTypes = {\r\n id_token: \"id_token\",\r\n token: \"token\",\r\n id_token_token: \"id_token token\"\r\n};\r\n\r\n/**\r\n * @hidden\r\n * @ignore\r\n */\r\nexport interface CacheResult {\r\n errorDesc: string;\r\n token: string;\r\n error: string;\r\n}\r\n\r\n/**\r\n * @hidden\r\n * @ignore\r\n * Data type to hold information about state returned from the server\r\n */\r\nexport type ResponseStateInfo = {\r\n state: string;\r\n stateMatch: boolean;\r\n requestType: string;\r\n};\r\n\r\n/**\r\n * A type alias for an authResponseCallback function.\r\n * {@link (authResponseCallback:type)}\r\n * @param authErr error created for failure cases\r\n * @param response response containing token strings in success cases, or just state value in error cases\r\n */\r\nexport type authResponseCallback = (authErr: AuthError, response?: AuthResponse) => void;\r\n\r\n/**\r\n * A type alias for a tokenReceivedCallback function.\r\n * {@link (tokenReceivedCallback:type)}\r\n * @returns response of type {@link (AuthResponse:type)}\r\n * The function that will get the call back once this API is completed (either successfully or with a failure).\r\n */\r\nexport type tokenReceivedCallback = (response: AuthResponse) => void;\r\n\r\n/**\r\n * A type alias for a errorReceivedCallback function.\r\n * {@link (errorReceivedCallback:type)}\r\n * @returns response of type {@link (AuthError:class)}\r\n * @returns {string} account state\r\n */\r\nexport type errorReceivedCallback = (authErr: AuthError, accountState: string) => void;\r\n\r\n/**\r\n * @hidden\r\n * @ignore\r\n * A wrapper to handle the token response/error within the iFrame always\r\n *\r\n * @param target\r\n * @param propertyKey\r\n * @param descriptor\r\n */\r\nconst resolveTokenOnlyIfOutOfIframe = (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {\r\n const tokenAcquisitionMethod = descriptor.value;\r\n descriptor.value = function (...args: any[]) {\r\n return this.isInIframe()\r\n ? new Promise(() => {\r\n return;\r\n })\r\n : tokenAcquisitionMethod.apply(this, args);\r\n };\r\n return descriptor;\r\n};\r\n\r\n/**\r\n * UserAgentApplication class\r\n *\r\n * Object Instance that the developer can use to make loginXX OR acquireTokenXX functions\r\n */\r\nexport class UserAgentApplication {\r\n\r\n // input Configuration by the developer/user\r\n private config: Configuration;\r\n\r\n // callbacks for token/error\r\n private authResponseCallback: authResponseCallback = null;\r\n private tokenReceivedCallback: tokenReceivedCallback = null;\r\n private errorReceivedCallback: errorReceivedCallback = null;\r\n\r\n // Added for readability as these params are very frequently used\r\n private logger: Logger;\r\n private clientId: string;\r\n private inCookie: boolean;\r\n\r\n // Cache and Account info referred across token grant flow\r\n protected cacheStorage: Storage;\r\n private account: Account;\r\n\r\n // state variables\r\n private loginInProgress: boolean;\r\n private acquireTokenInProgress: boolean;\r\n private silentAuthenticationState: string;\r\n private silentLogin: boolean;\r\n private redirectCallbacksSet: boolean;\r\n\r\n // Authority Functionality\r\n protected authorityInstance: Authority;\r\n\r\n /**\r\n * setter for the authority URL\r\n * @param {string} authority\r\n */\r\n // If the developer passes an authority, create an instance\r\n public set authority(val) {\r\n this.authorityInstance = AuthorityFactory.CreateInstance(val, this.config.auth.validateAuthority);\r\n }\r\n\r\n /**\r\n * Method to manage the authority URL.\r\n *\r\n * @returns {string} authority\r\n */\r\n public get authority(): string {\r\n return this.authorityInstance.CanonicalAuthority;\r\n }\r\n\r\n /**\r\n * Get the current authority instance from the MSAL configuration object\r\n *\r\n * @returns {@link Authority} authority instance\r\n */\r\n public getAuthorityInstance(): Authority {\r\n return this.authorityInstance;\r\n }\r\n\r\n /**\r\n * @constructor\r\n * Constructor for the UserAgentApplication used to instantiate the UserAgentApplication object\r\n *\r\n * Important attributes in the Configuration object for auth are:\r\n * - clientID: the application ID of your application.\r\n * You can obtain one by registering your application with our Application registration portal : https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredAppsPreview\r\n * - authority: the authority URL for your application.\r\n *\r\n * In Azure AD, authority is a URL indicating the Azure active directory that MSAL uses to obtain tokens.\r\n * It is of the form https://login.microsoftonline.com/<Enter_the_Tenant_Info_Here>.\r\n * If your application supports Accounts in one organizational directory, replace \"Enter_the_Tenant_Info_Here\" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com).\r\n * If your application supports Accounts in any organizational directory, replace \"Enter_the_Tenant_Info_Here\" value with organizations.\r\n * If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace \"Enter_the_Tenant_Info_Here\" value with common.\r\n * To restrict support to Personal Microsoft accounts only, replace \"Enter_the_Tenant_Info_Here\" value with consumers.\r\n *\r\n *\r\n * In Azure B2C, authority is of the form https://<instance>/tfp/<tenant>/<policyName>/\r\n\r\n * @param {@link (Configuration:type)} configuration object for the MSAL UserAgentApplication instance\r\n */\r\n constructor(configuration: Configuration) {\r\n\r\n // Set the Configuration\r\n this.config = buildConfiguration(configuration);\r\n\r\n // Set the callback boolean\r\n this.redirectCallbacksSet = false;\r\n\r\n this.logger = this.config.system.logger;\r\n this.clientId = this.config.auth.clientId;\r\n this.inCookie = this.config.cache.storeAuthStateInCookie;\r\n\r\n // if no authority is passed, set the default: \"https://login.microsoftonline.com/common\"\r\n this.authority = this.config.auth.authority || DEFAULT_AUTHORITY;\r\n\r\n // track login and acquireToken in progress\r\n this.loginInProgress = false;\r\n this.acquireTokenInProgress = false;\r\n\r\n // cache keys msal - typescript throws an error if any value other than \"localStorage\" or \"sessionStorage\" is passed\r\n try {\r\n this.cacheStorage = new Storage(this.config.cache.cacheLocation);\r\n } catch (e) {\r\n throw ClientConfigurationError.createInvalidCacheLocationConfigError(this.config.cache.cacheLocation);\r\n }\r\n\r\n // Initialize window handling code\r\n window.openedWindows = [];\r\n window.activeRenewals = {};\r\n window.renewStates = [];\r\n window.callbackMappedToRenewStates = { };\r\n window.promiseMappedToRenewStates = { };\r\n window.msal = this;\r\n\r\n const urlHash = window.location.hash;\r\n const isCallback = this.isCallback(urlHash);\r\n\r\n // On the server 302 - Redirect, handle this\r\n if (!this.config.framework.isAngular) {\r\n if (isCallback) {\r\n this.handleAuthenticationResponse(urlHash);\r\n }\r\n }\r\n }\r\n\r\n //#region Redirect Callbacks\r\n /**\r\n * @hidden\r\n * @ignore\r\n * Set the callback functions for the redirect flow to send back the success or error object.\r\n * @param {@link (tokenReceivedCallback:type)} successCallback - Callback which contains the AuthResponse object, containing data from the server.\r\n * @param {@link (errorReceivedCallback:type)} errorCallback - Callback which contains a AuthError object, containing error data from either the server\r\n * or the library, depending on the origin of the error.\r\n */\r\n handleRedirectCallback(tokenReceivedCallback: tokenReceivedCallback, errorReceivedCallback: errorReceivedCallback): void;\r\n handleRedirectCallback(authCallback: authResponseCallback): void;\r\n handleRedirectCallback(authOrTokenCallback: authResponseCallback | tokenReceivedCallback, errorReceivedCallback?: errorReceivedCallback): void {\r\n if (!authOrTokenCallback) {\r\n this.redirectCallbacksSet = false;\r\n throw ClientConfigurationError.createInvalidCallbackObjectError(authOrTokenCallback);\r\n }\r\n\r\n // Set callbacks\r\n if (errorReceivedCallback) {\r\n this.tokenReceivedCallback = authOrTokenCallback as tokenReceivedCallback;\r\n this.errorReceivedCallback = errorReceivedCallback;\r\n this.logger.warning(\"This overload for callback is deprecated - please change the format of the callbacks to a single callback as shown: (err: AuthError, response: AuthResponse).\");\r\n } else {\r\n this.authResponseCallback = authOrTokenCallback as authResponseCallback;\r\n }\r\n\r\n this.redirectCallbacksSet = true;\r\n\r\n // On the server 302 - Redirect, handle this\r\n if (!this.config.framework.isAngular) {\r\n const cachedHash = this.cacheStorage.getItem(Constants.urlHash);\r\n if (cachedHash) {\r\n this.processCallBack(cachedHash, null);\r\n }\r\n }\r\n }\r\n\r\n private redirectSuccessHandler(response: AuthResponse) : void {\r\n if (this.errorReceivedCallback) {\r\n this.tokenReceivedCallback(response);\r\n } else if (this.authResponseCallback) {\r\n this.authResponseCallback(null, response);\r\n }\r\n }\r\n\r\n private redirectErrorHandler(authErr: AuthError, response: AuthResponse) : void {\r\n if (this.errorReceivedCallback) {\r\n this.errorReceivedCallback(authErr, response.accountState);\r\n } else {\r\n this.authResponseCallback(authErr, response);\r\n }\r\n }\r\n\r\n //#endregion\r\n\r\n //#region Redirect Flow\r\n\r\n /**\r\n * Use when initiating the login process by redirecting the user's browser to the authorization endpoint.\r\n * @param {@link (AuthenticationParameters:type)}\r\n */\r\n loginRedirect(request?: AuthenticationParameters): void {\r\n\r\n // Throw error if callbacks are not set before redirect\r\n if (!this.redirectCallbacksSet) {\r\n throw ClientConfigurationError.createRedirectCallbacksNotSetError();\r\n }\r\n\r\n // Creates navigate url; saves value in cache; redirect user to AAD\r\n if (this.loginInProgress) {\r\n this.redirectErrorHandler(ClientAuthError.createLoginInProgressError(), buildResponseStateOnly(request && request.state));\r\n return;\r\n }\r\n\r\n // if extraScopesToConsent is passed, append them to the login request\r\n let scopes: Array<string> = this.appendScopes(request);\r\n\r\n // Validate and filter scopes (the validate function will throw if validation fails)\r\n this.validateInputScope(scopes, false);\r\n\r\n const account: Account = this.getAccount();\r\n\r\n // defer queryParameters generation to Helper if developer passes account/sid/login_hint\r\n if (Utils.isSSOParam(request)) {\r\n // if account is not provided, we pass null\r\n this.loginRedirectHelper(account, request, scopes);\r\n }\r\n // else handle the library data\r\n else {\r\n // extract ADAL id_token if exists\r\n let adalIdToken = this.extractADALIdToken();\r\n\r\n // silent login if ADAL id_token is retrieved successfully - SSO\r\n if (adalIdToken && !scopes) {\r\n this.logger.info(\"ADAL's idToken exists. Extracting login information from ADAL's idToken \");\r\n let tokenRequest: AuthenticationParameters = this.buildIDTokenRequest(request);\r\n\r\n this.silentLogin = true;\r\n this.acquireTokenSilent(tokenRequest).then(response => {\r\n this.silentLogin = false;\r\n this.logger.info(\"Unified cache call is successful\");\r\n\r\n if (this.redirectCallbacksSet) {\r\n this.redirectSuccessHandler(response);\r\n }\r\n return;\r\n }, (error) => {\r\n this.silentLogin = false;\r\n this.logger.error(\"Error occurred during unified cache ATS\");\r\n\r\n // call the loginRedirectHelper later with no user account context\r\n this.loginRedirectHelper(null, request, scopes);\r\n });\r\n }\r\n // else proceed to login\r\n else {\r\n // call the loginRedirectHelper later with no user account context\r\n this.loginRedirectHelper(null, request, scopes);\r\n }\r\n }\r\n\r\n }\r\n\r\n /**\r\n * @hidden\r\n * @ignore\r\n * Helper function to loginRedirect\r\n *\r\n * @param account\r\n * @param AuthenticationParameters\r\n * @param scopes\r\n */\r\n private loginRedirectHelper(account: Account, request?: AuthenticationParameters, scopes?: Array<string>) {\r\n // Track login in progress\r\n this.loginInProgress = true;\r\n\r\n this.authorityInstance.resolveEndpointsAsync().then(() => {\r\n\r\n // create the Request to be sent to the Server\r\n let serverAuthenticationRequest = new ServerRequestParameters(\r\n this.authorityInstance,\r\n this.clientId, scopes,\r\n ResponseTypes.id_token,\r\n this.getRedirectUri(),\r\n request && request.state\r\n );\r\n\r\n // populate QueryParameters (sid/login_hint/domain_hint) and any other extraQueryParameters set by the developer\r\n serverAuthenticationRequest = this.populateQueryParams(account, request, serverAuthenticationRequest);\r\n\r\n // if the user sets the login start page - angular only??\r\n let loginStartPage = this.cacheStorage.getItem(Constants.angularLoginRequest);\r\n if (!loginStartPage || loginStartPage === \"\") {\r\n loginStartPage = window.location.href;\r\n } else {\r\n this.cacheStorage.setItem(Constants.angularLoginRequest, \"\");\r\n }\r\n\r\n this.updateCacheEntries(serverAuthenticationRequest, account, loginStartPage);\r\n\r\n // build URL to navigate to proceed with the login\r\n let urlNavigate = serverAuthenticationRequest.createNavigateUrl(scopes) + Constants.response_mode_fragment;\r\n\r\n // Redirect user to login URL\r\n this.promptUser(urlNavigate);\r\n }).catch((err) => {\r\n this.logger.warning(\"could not resolve endpoints\");\r\n this.redirectErrorHandler(ClientAuthError.createEndpointResolutionError(err.toString), buildResponseStateOnly(request && request.state));\r\n });\r\n }\r\n\r\n /**\r\n * Use when you want to obtain an access_token for your API by redirecting the user's browser window to the authorization endpoint.\r\n * @param {@link (AuthenticationParameters:type)}\r\n *\r\n * To renew idToken, please pass clientId as the only scope in the Authentication Parameters\r\n */\r\n acquireTokenRedirect(request: AuthenticationParameters): void {\r\n // Throw error if callbacks are not set before redirect\r\n if (!this.redirectCallbacksSet) {\r\n throw ClientConfigurationError.createRedirectCallbacksNotSetError();\r\n }\r\n\r\n // Validate and filter scopes (the validate function will throw if validation fails)\r\n this.validateInputScope(request.scopes, true);\r\n\r\n // Get the account object if a session exists\r\n const account: Account = request.account || this.getAccount();\r\n\r\n // If already in progress, do not proceed\r\n if (this.acquireTokenInProgress) {\r\n this.redirectErrorHandler(ClientAuthError.createAcquireTokenInProgressError(), buildResponseStateOnly(this.getAccountState(request.state)));\r\n return;\r\n }\r\n\r\n // If no session exists, prompt the user to login.\r\n if (!account && !(request.sid || request.loginHint)) {\r\n this.logger.info(\"User login is required\");\r\n throw ClientAuthError.createUserLoginRequiredError();\r\n }\r\n\r\n let serverAuthenticationRequest: ServerRequestParameters;\r\n const acquireTokenAuthority = request.authority ? AuthorityFactory.CreateInstance(request.authority, this.config.auth.validateAuthority) : this.authorityInstance;\r\n\r\n // Track the acquireToken progress\r\n this.acquireTokenInProgress = true;\r\n\r\n acquireTokenAuthority.resolveEndpointsAsync().then(() => {\r\n // On Fulfillment\r\n const responseType = this.getTokenType(account, request.scopes, false);\r\n serverAuthenticationRequest = new ServerRequestParameters(\r\n acquireTokenAuthority,\r\n this.clientId,\r\n request.scopes,\r\n responseType,\r\n this.getRedirectUri(),\r\n request.state\r\n );\r\n\r\n this.updateCacheEntries(serverAuthenticationRequest, account);\r\n\r\n // populate QueryParameters (sid/login_hint/domain_hint) and any other extraQueryParameters set by the developer\r\n serverAuthenticationRequest = this.populateQueryParams(account, request, serverAuthenticationRequest);\r\n\r\n // Construct urlNavigate\r\n let urlNavigate = serverAuthenticationRequest.createNavigateUrl(request.scopes) + Constants.response_mode_fragment;\r\n\r\n // set state in cache and redirect to urlNavigate\r\n if (urlNavigate) {\r\n this.cacheStorage.setItem(Constants.stateAcquireToken, serverAuthenticationRequest.state, this.inCookie);\r\n window.location.replace(urlNavigate);\r\n }\r\n }).catch((err) => {\r\n this.logger.warning(\"could not resolve endpoints\");\r\n this.redirectErrorHandler(ClientAuthError.createEndpointResolutionError(err.toString), buildResponseStateOnly(request.state));\r\n });\r\n }\r\n\r\n /**\r\n * @hidden\r\n * @ignore\r\n * Checks if the redirect response is received from the STS. In case of redirect, the url fragment has either id_token, access_token or error.\r\n * @param {string} hash - Hash passed from redirect page.\r\n * @returns {Boolean} - true if response contains id_token, access_token or error, false otherwise.\r\n */\r\n // TODO - rename this, the name is confusing\r\n isCallback(hash: string): boolean {\r\n hash = this.getHash(hash);\r\n const parameters = Utils.deserialize(hash);\r\n return (\r\n parameters.hasOwnProperty(Constants.errorDescription) ||\r\n parameters.hasOwnProperty(Constants.error) ||\r\n parameters.hasOwnProperty(Constants.accessToken) ||\r\n parameters.hasOwnProperty(Constants.idToken)\r\n );\r\n }\r\n\r\n //#endregion\r\n\r\n //#region Popup Flow\r\n\r\n /**\r\n * Use when initiating the login process via opening a popup window in the user's browser\r\n *\r\n * @param {@link (AuthenticationParameters:type)}\r\n *\r\n * @returns {Promise.<AuthResponse>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse} object\r\n */\r\n loginPopup(request?: AuthenticationParameters): Promise<AuthResponse> {\r\n // Creates navigate url; saves value in cache; redirect user to AAD\r\n return new Promise<AuthResponse>((resolve, reject) => {\r\n // Fail if login is already in progress\r\n if (this.loginInProgress) {\r\n return reject(ClientAuthError.createLoginInProgressError());\r\n }\r\n\r\n // if extraScopesToConsent is passed, append them to the login request\r\n let scopes: Array<string> = this.appendScopes(request);\r\n\r\n // Validate and filter scopes (the validate function will throw if validation fails)\r\n this.validateInputScope(scopes, false);\r\n\r\n let account = this.getAccount();\r\n\r\n // add the prompt parameter to the 'extraQueryParameters' if passed\r\n if (Utils.isSSOParam(request)) {\r\n // if account is not provided, we pass null\r\n this.loginPopupHelper(account, resolve, reject, request, scopes);\r\n }\r\n // else handle the library data\r\n else {\r\n // Extract ADAL id_token if it exists\r\n let adalIdToken = this.extractADALIdToken();\r\n\r\n // silent login if ADAL id_token is retrieved successfully - SSO\r\n if (adalIdToken && !scopes) {\r\n this.logger.info(\"ADAL's idToken exists. Extracting login information from ADAL's idToken \");\r\n let tokenRequest: AuthenticationParameters = this.buildIDTokenRequest(request);\r\n\r\n this.silentLogin = true;\r\n this.acquireTokenSilent(tokenRequest)\r\n .then(response => {\r\n this.silentLogin = false;\r\n this.logger.info(\"Unified cache call is successful\");\r\n\r\n resolve(response);\r\n }, (error) => {\r\n this.silentLogin = false;\r\n this.logger.error(\"Error occurred during unified cache ATS\");\r\n this.loginPopupHelper(null, resolve, reject, request, scopes);\r\n });\r\n }\r\n // else proceed with login\r\n else {\r\n this.loginPopupHelper(null, resolve, reject, request, scopes);\r\n }\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * @hidden\r\n * Helper function to loginPopup\r\n *\r\n * @param account\r\n * @param request\r\n * @param resolve\r\n * @param reject\r\n * @param scopes\r\n */\r\n private loginPopupHelper(account: Account, resolve: any, reject: any, request?: AuthenticationParameters, scopes?: Array<string>) {\r\n if (!scopes) {\r\n scopes = [this.clientId];\r\n }\r\n const scope = scopes.join(\" \").toLowerCase();\r\n\r\n // Generate a popup window\r\n const popUpWindow = this.openWindow(\"about:blank\", \"_blank\", 1, this, resolve, reject);\r\n if (!popUpWindow) {\r\n // We pass reject in openWindow, we reject there during an error\r\n return;\r\n }\r\n\r\n // Track login progress\r\n this.loginInProgress = true;\r\n\r\n // Resolve endpoint\r\n this.authorityInstance.resolveEndpointsAsync().then(() => {\r\n let serverAuthenticationRequest = new ServerRequestParameters(this.authorityInstance, this.clientId, scopes, ResponseTypes.id_token, this.getRedirectUri(), request && request.state);\r\n\r\n // populate QueryParameters (sid/login_hint/domain_hint) and any other extraQueryParameters set by the developer;\r\n serverAuthenticationRequest = this.populateQueryParams(account, request, serverAuthenticationRequest);\r\n\r\n this.updateCacheEntries(serverAuthenticationRequest, account, window.location.href);\r\n\r\n // Cache the state, nonce, and login request data\r\n this.cacheStorage.setItem(Constants.loginRequest, window.location.href, this.inCookie);\r\n this.cacheStorage.setItem(Constants.loginError, \"\");\r\n\r\n this.cacheStorage.setItem(Constants.nonceIdToken, serverAuthenticationRequest.nonce, this.inCookie);\r\n\r\n this.cacheStorage.setItem(Constants.msalError, \"\");\r\n this.cacheStorage.setItem(Constants.msalErrorDescription, \"\");\r\n\r\n // cache authorityKey\r\n this.setAuthorityCache(serverAuthenticationRequest.state, this.authority);\r\n\r\n // Build the URL to navigate to in the popup window\r\n let urlNavigate = serverAuthenticationRequest.createNavigateUrl(scopes) + Constants.response_mode_fragment;\r\n\r\n window.renewStates.push(serverAuthenticationRequest.state);\r\n window.requestType = Constants.login;\r\n\r\n // Register callback to capture results from server\r\n this.registerCallback(serverAuthenticationRequest.state, scope, resolve, reject);\r\n\r\n // Navigate url in popupWindow\r\n if (popUpWindow) {\r\n this.logger.infoPii(\"Navigated Popup window to:\" + urlNavigate);\r\n popUpWindow.location.href = urlNavigate;\r\n }\r\n }, () => {\r\n // Endpoint resolution failure error\r\n this.logger.info(ClientAuthErrorMessage.endpointResolutionError.code + \":\" + ClientAuthErrorMessage.endpointResolutionError.desc);\r\n this.cacheStorage.setItem(Constants.msalError, ClientAuthErrorMessage.endpointResolutionError.code);\r\n this.cacheStorage.setItem(Constants.msalErrorDescription, ClientAuthErrorMessage.endpointResolutionError.desc);\r\n\r\n // reject that is passed in - REDO this in the subsequent refactor, passing reject is confusing\r\n if (reject) {\r\n reject(ClientAuthError.createEndpointResolutionError());\r\n }\r\n\r\n // Close the popup window\r\n if (popUpWindow) {\r\n popUpWindow.close();\r\n }\r\n // this is an all catch for any failure for the above code except the specific 'reject' call\r\n }).catch((err) => {\r\n this.logger.warning(\"could not resolve endpoints\");\r\n reject(ClientAuthError.createEndpointResolutionError(err.toString));\r\n });\r\n }\r\n\r\n /**\r\n * Use when you want to obtain an access_token for your API via opening a popup window in the user's browser\r\n * @param {@link AuthenticationParameters}\r\n *\r\n * To renew idToken, please pass clientId as the only scope in the Authentication Parameters\r\n * @returns {Promise.<AuthResponse>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse} object\r\n */\r\n acquireTokenPopup(request: AuthenticationParameters): Promise<AuthResponse> {\r\n return new Promise<AuthResponse>((resolve, reject) => {\r\n // Validate and filter scopes (the validate function will throw if validation fails)\r\n this.validateInputScope(request.scopes, true);\r\n\r\n const scope = request.scopes.join(\" \").toLowerCase();\r\n\r\n // Get the account object if a session exists\r\n const account: Account = request.account || this.getAccount();\r\n\r\n // If already in progress, throw an error and reject the request\r\n if (this.acquireTokenInProgress) {\r\n return reject(ClientAuthError.createAcquireTokenInProgressError());\r\n }\r\n\r\n // If no session exists, prompt the user to login.\r\n if (!account && !(request.sid || request.loginHint)) {\r\n this.logger.info(\"User login is required\");\r\n return reject(ClientAuthError.createUserLoginRequiredError());\r\n }\r\n\r\n // track the acquireToken progress\r\n this.acquireTokenInProgress = true;\r\n\r\n let serverAuthenticationRequest: ServerRequestParameters;\r\n const acquireTokenAuthority = request.authority ? AuthorityFactory.CreateInstance(request.authority, this.config.auth.validateAuthority) : this.authorityInstance;\r\n\r\n // Open the popup window\r\n const popUpWindow = this.openWindow(\"about:blank\", \"_blank\", 1, this, resolve, reject);\r\n if (!popUpWindow) {\r\n // We pass reject to openWindow, so we are rejecting there.\r\n return;\r\n }\r\n\r\n acquireTokenAuthority.resolveEndpointsAsync().then(() => {\r\n // On fullfillment\r\n const responseType = this.getTokenType(account, request.scopes, false);\r\n serverAuthenticationRequest = new ServerRequestParameters(\r\n acquireTokenAuthority,\r\n this.clientId,\r\n request.scopes,\r\n responseType,\r\n this.getRedirectUri(),\r\n request.state\r\n );\r\n\r\n // populate QueryParameters (sid/login_hint/domain_hint) and any other extraQueryParameters set by the developer\r\n serverAuthenticationRequest = this.populateQueryParams(account, request, serverAuthenticationRequest);\r\n\r\n this.updateCacheEntries(serverAuthenticationRequest, account);\r\n\r\n // Construct the urlNavigate\r\n let urlNavigate = serverAuthenticationRequest.createNavigateUrl(request.scopes) + Constants.response_mode_fragment;\r\n\r\n window.renewStates.push(serverAuthenticationRequest.state);\r\n window.requestType = Constants.renewToken;\r\n this.registerCallback(serverAuthenticationRequest.state, scope, resolve, reject);\r\n\r\n // open popup window to urlNavigate\r\n if (popUpWindow) {\r\n popUpWindow.location.href = urlNavigate;\r\n }\r\n\r\n }, () => {\r\n // Endpoint resolution failure error\r\n this.logger.info(ClientAuthErrorMessage.endpointResolutionError.code + \":\" + ClientAuthErrorMessage.endpointResolutionError.desc);\r\n this.cacheStorage.setItem(Constants.msalError, ClientAuthErrorMessage.endpointResolutionError.code);\r\n this.cacheStorage.setItem(Constants.msalErrorDescription, ClientAuthErrorMessage.endpointResolutionError.desc);\r\n\r\n // reject that is passed in - REDO this in the subsequent refactor, passing reject is confusing\r\n if (reject) {\r\n reject(ClientAuthError.createEndpointResolutionError());\r\n }\r\n if (popUpWindow) {\r\n popUpWindow.close();\r\n }\r\n // this is an all catch for any failure for the above code except the specific 'reject' call\r\n }).catch((err) => {\r\n this.logger.warning(\"could not resolve endpoints\");\r\n reject(ClientAuthError.createEndpointResolutionError(err.toString()));\r\n });\r\n });\r\n }\r\n\r\n /**\r\n * @hidden\r\n *\r\n * Used to send the user to the redirect_uri after authentication is complete. The user's bearer token is attached to the URI fragment as an id_token/access_token field.\r\n * This function also closes the popup window after redirection.\r\n *\r\n * @param urlNavigate\r\n * @param title\r\n * @param interval\r\n * @param instance\r\n * @param resolve\r\n * @param reject\r\n * @ignore\r\n */\r\n private openWindow(urlNavigate: string, title: string, interval: number, instance: this, resolve?: Function, reject?: Function): Window {\r\n // Generate a popup window\r\n var popupWindow: Window;\r\n try {\r\n popupWindow = this.openPopup(urlNavigate, title, Constants.popUpWidth, Constants.popUpHeight);\r\n } catch (e) {\r\n instance.loginInProgress = false;\r\n instance.acquireTokenInProgress = false;\r\n\r\n this.logger.info(ClientAuthErrorMessage.popUpWindowError.code + \":\" + ClientAuthErrorMessage.popUpWindowError.desc);\r\n this.cacheStorage.setItem(Constants.msalError, ClientAuthErrorMessage.popUpWindowError.code);\r\n this.cacheStorage.setItem(Constants.msalErrorDescription, ClientAuthErrorMessage.popUpWindowError.desc);\r\n if (reject) {\r\n reject(ClientAuthError.createPopupWindowError());\r\n }\r\n return null;\r\n }\r\n\r\n // Push popup window handle onto stack for tracking\r\n window.openedWindows.push(popupWindow);\r\n\r\n const pollTimer = window.setInterval(() => {\r\n // If popup closed or login in progress, cancel login\r\n if (popupWindow && popupWindow.closed && (instance.loginInProgress || instance.acquireTokenInProgress)) {\r\n if (reject) {\r\n reject(ClientAuthError.createUserCancelledError());\r\n }\r\n window.clearInterval(pollTimer);\r\n if (this.config.framework.isAngular) {\r\n this.broadcast(\"msal:popUpClosed\", ClientAuthErrorMessage.userCancelledError.code + Constants.resourceDelimiter + ClientAuthErrorMessage.userCancelledError.desc);\r\n return;\r\n }\r\n instance.loginInProgress = false;\r\n instance.acquireTokenInProgress = false;\r\n }\r\n\r\n try {\r\n const popUpWindowLocation = popupWindow.location;\r\n\r\n // If the popup hash changes, close the popup window\r\n if (popUpWindowLocation.href.indexOf(this.getRedirectUri()) !== -1) {\r\n window.clearInterval(pollTimer);\r\n instance.loginInProgress = false;\r\n instance.acquireTokenInProgress = false;\r\n this.logger.info(\"Closing popup window\");\r\n // TODO: Check how this can be extracted for any framework specific code?\r\n if (this.config.framework.isAngular) {\r\n this.broadcast(\"msal:popUpHashChanged\", popUpWindowLocation.hash);\r\n for (let i = 0; i < window.openedWindows.length; i++) {\r\n window.openedWindows[i].close();\r\n }\r\n }\r\n }\r\n } catch (e) {\r\n // Cross Domain url check error.\r\n // Will be thrown until AAD redirects the user back to the app\"s root page with the token.\r\n // No need to log or throw this error as it will create unnecessary traffic.\r\n }\r\n },\r\n interval);\r\n\r\n return popupWindow;\r\n }\r\n\r\n /**\r\n * @hidden\r\n *\r\n * Configures popup window for login.\r\n *\r\n * @param urlNavigate\r\n * @param title\r\n * @param popUpWidth\r\n * @param popUpHeight\r\n * @ignore\r\n * @hidden\r\n */\r\n private openPopup(urlNavigate: string, title: string, popUpWidth: number, popUpHeight: number) {\r\n try {\r\n /**\r\n * adding winLeft and winTop to account for dual monitor\r\n * using screenLeft and screenTop for IE8 and earlier\r\n */\r\n const winLeft = window.screenLeft ? window.screenLeft : window.screenX;\r\n const winTop = window.screenTop ? window.screenTop : window.screenY;\r\n /**\r\n * window.innerWidth displays browser window\"s height and width excluding toolbars\r\n * using document.documentElement.clientWidth for IE8 and earlier\r\n */\r\n const width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;\r\n const height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;\r\n const left = ((width / 2) - (popUpWidth / 2)) + winLeft;\r\n const top = ((height / 2) - (popUpHeight / 2)) + winTop;\r\n\r\n // open the window\r\n const popupWindow = window.open(urlNavigate, title, \"width=\" + popUpWidth + \", height=\" + popUpHeight + \", top=\" + top + \", left=\" + left);\r\n if (!popupWindow) {\r\n throw ClientAuthError.createPopupWindowError();\r\n }\r\n if (popupWindow.focus) {\r\n popupWindow.focus();\r\n }\r\n\r\n return popupWindow;\r\n } catch (e) {\r\n this.logger.error(\"error opening popup \" + e.message);\r\n this.loginInProgress = false;\r\n this.acquireTokenInProgress = false;\r\n throw ClientAuthError.createPopupWindowError(e.toString());\r\n }\r\n }\r\n\r\n //#endregion\r\n\r\n //#region Silent Flow\r\n\r\n /**\r\n * Use this function to obtain a token before every call to the API / resource provider\r\n *\r\n * MSAL return's a cached token when available\r\n * Or it send's a request to the STS to obtain a new token using a hidden iframe.\r\n *\r\n * @param {@link AuthenticationParameters}\r\n *\r\n * To renew idToken, please pass clientId as the only scope in the Authentication Parameters\r\n * @returns {Promise.<AuthResponse>} - a promise that is fulfilled when this function has completed, or rejected if an error was raised. Returns the {@link AuthResponse} object\r\n *\r\n */\r\n @resolveTokenOnlyIfOutOfIframe\r\n acquireTokenSilent(request: AuthenticationParameters): Promise<AuthResponse> {\r\n return new Promise<AuthResponse>((resolve, reject) => {\r\n\r\n // Validate and filter scopes (the validate function will throw if validation fails)\r\n this.validateInputScope(request.scopes, true);\r\n\r\n const scope = request.scopes.join(\" \").toLowerCase();\r\n\r\n // if the developer passes an account give him the priority\r\n const account: Account = request.account || this.getAccount();\r\n\r\n // extract if there is an adalIdToken stashed in the cache\r\n const adalIdToken = this.cacheStorage.getItem(Constants.adalIdToken);\r\n\r\n //if there is no account logged in and no login_hint/sid is passed in the request\r\n if (!account && !(request.sid || request.loginHint) && Utils.isEmpty(adalIdToken) ) {\r\n this.logger.info(\"User login is required\");\r\n return reject(ClientAuthError.createUserLoginRequiredError());\r\n }\r\n\r\n const responseType = this.getTokenType(account, request.scopes, true);\r\n\r\n let serverAuthenticationRequest = new ServerRequestParameters(\r\n AuthorityFactory.CreateInstance(request.authority, this.config.auth.validateAuthority),\r\n this.clientId,\r\n request.scopes,\r\n responseType,\r\n this.getRedirectUri(),\r\n request && request.state\r\n );\r\n\r\n // populate QueryParameters (sid/login_hint/domain_hint) and any other extraQueryParameters set by the developer\r\n if (Utils.isSSOParam(request) || account) {\r\n serverAuthenticationRequest = this.populateQueryParams(account, request, serverAuthenticationRequest);\r\n }\r\n //if user didn't pass login_hint/sid and adal's idtoken is present, extract the login_hint from the adalIdToken\r\n else if (!account && !Utils.isEmpty(adalIdToken)) {\r\n // if adalIdToken exists, extract the SSO info from the same\r\n const adalIdTokenObject = Utils.extractIdToken(adalIdToken);\r\n this.logger.verbose(\"ADAL's idToken exists. Extracting login information from ADAL's idToken \");\r\n serverAuthenticationRequest = this.populateQueryParams(account, null, serverAuthenticationRequest, adalIdTokenObject);\r\n }\r\n let userContainedClaims = request.claimsRequest || serverAuthenticationRequest.claimsValue;\r\n\r\n let authErr: AuthError;\r\n let cacheResultResponse;\r\n\r\n if (!userContainedClaims) {\r\n try {\r\n cacheResultResponse = this.getCachedToken(serverAuthenticationRequest, account);\r\n } catch (e) {\r\n authErr = e;\r\n }\r\n }\r\n\r\n // resolve/reject based on cacheResult\r\n if (cacheResultResponse) {\r\n this.logger.info(\"Token is already in cache for scope:\" + scope);\r\n resolve(cacheResultResponse);\r\n return null;\r\n }\r\n else if (authErr) {\r\n this.logger.infoPii(authErr.errorCode + \":\" + authErr.errorMessage);\r\n reject(authErr);\r\n return null;\r\n }\r\n // else proceed with login\r\n else {\r\n if (userContainedClaims) {\r\n this.logger.verbose(\"Skipped cache lookup since claims were given.\");\r\n } else {\r\n this.logger.verbose(\"Token is not in cache for scope:\" + scope);\r\n }\r\n // Cache result can return null if cache is empty. In that case, set authority to default value if no authority is passed to the api.\r\n if (!serverAuthenticationRequest.authorityInstance) {\r\n serverAuthenticationRequest.authorityInstance = request.authority ? AuthorityFactory.CreateInstance(request.authority, this.config.auth.validateAuthority) : this.authorityInstance;\r\n }\r\n // cache miss\r\n return serverAuthenticationRequest.authorityInstance.resolveEndpointsAsync()\r\n .then(() => {\r\n // refresh attempt with iframe\r\n // Already renewing for this scope, callback when we get the token.\r\n if (window.activeRenewals[scope]) {\r\n this.logger.verbose(\"Renew token for scope: \" + scope + \" is in progress. Registering callback\");\r\n // Active renewals contains the state for each renewal.\r\n this.registerCallback(window.activeRenewals[scope], scope, resolve, reject);\r\n }\r\n else {\r\n if (request.scopes && request.scopes.indexOf(this.clientId) > -1 && request.scopes.length === 1) {\r\n // App uses idToken to send to api endpoints\r\n // Default scope is tracked as clientId to store this token\r\n this.logger.verbose(\"renewing idToken\");\r\n this.renewIdToken(request.scopes, resolve, reject, account, serverAuthenticationRequest);\r\n } else {\r\n // renew access token\r\n this.logger.verbose(\"renewing accesstoken\");\r\n this.renewToken(request.scopes, resolve, reject, account, serverAuthenticationRequest);\r\n }\r\n }\r\n }).catch((err) => {\r\n this.logger.warning(\"could not resolve endpoints\");\r\n reject(ClientAuthError.createEndpointResolutionError(err.toString()));\r\n return null;\r\n });\r\n }\r\n });\r\n }\r\n\r\n /**\r\n * @hidden\r\n * Returns whether current window is in ifram for token renewal\r\n * @ignore\r\n */\r\n public isInIframe() {\r\n return window.parent !== window;\r\n }\r\n\r\n /**\r\n * @hidden\r\n * Returns whether parent window exists and has msal\r\n */\r\n private parentIsMsal() {\r\n return window.parent !== window && window.parent.msal;\r\n }\r\n\r\n /**\r\n * @hidden\r\n */\r\n private isInteractionRequired(errorString: string) : boolean {\r\n if (errorString.indexOf(\"interaction_required\") !== -1 ||\r\n errorString.indexOf(\"consent_required\") !== -1 ||\r\n errorString.indexOf(\"login_required\") !== -1) {\r\n return true;\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * @hidden\r\n * Calling _loadFrame but with a timeout to signal failure in loadframeStatus. Callbacks are left.\r\n * registered when network errors occur and subsequent token requests for same resource are registered to the pending request.\r\n * @ignore\r\n */\r\n private loadIframeTimeout(urlNavigate: string, frameName: string, scope: string): void {\r\n //set iframe session to pending\r\n const expectedState = window.activeRenewals[scope];\r\n this.logger.verbose(\"Set loading state to pending for: \" + scope + \":\" + expectedState);\r\n this.cacheStorage.setItem(Constants.renewStatus + expectedState, Constants.tokenRenewStatusInProgress);\r\n this.loadFrame(urlNavigate, frameName);\r\n setTimeout(() => {\r\n if (this.cacheStorage.getItem(Constants.renewStatus + expectedState) === Constants.tokenRenewStatusInProgress) {\r\n // fail the iframe session if it\"s in pending state\r\n this.logger.verbose(\"Loading frame has timed out after: \" + (this.config.system.loadFrameTimeout / 1000) + \" seconds for scope \" + scope + \":\" + expectedState);\r\n // Error after timeout\r\n if (expectedState && window.callbackMappedToRenewStates[expectedState]) {\r\n window.callbackMappedToRenewStates[expectedState](null, ClientAuthError.createTokenRenewalTimeoutError());\r\n }\r\n\r\n this.cacheStorage.setItem(Constants.renewStatus + expectedState, Constants.tokenRenewStatusCancelled);\r\n }\r\n }, this.config.system.loadFrameTimeout);\r\n }\r\n\r\n /**\r\n * @hidden\r\n * Loads iframe with authorization endpoint URL\r\n * @ignore\r\n */\r\n private loadFrame(urlNavigate: string, frameName: string): void {\r\n // This trick overcomes iframe navigation in IE\r\n // IE does not load the page consistently in iframe\r\n this.logger.info(\"LoadFrame: \" + frameName);\r\n const frameCheck = frameName;\r\n\r\n setTimeout(() => {\r\n const frameHandle = this.addHiddenIFrame(frameCheck);\r\n if (frameHandle.src === \"\" || frameHandle.src === \"about:blank\") {\r\n frameHandle.src = urlNavigate;\r\n this.logger.infoPii(\"Frame Name : \" + frameName + \" Navigated to: \" + urlNavigate);\r\n }\r\n },\r\n this.config.system.navigateFrameWait);\r\n }\r\n\r\n /**\r\n * @hidden\r\n * Adds the hidden iframe for silent token renewal.\r\n * @ignore\r\n */\r\n private addHiddenIFrame(iframeId: string): HTMLIFrameElement {\r\n if (typeof iframeId === \"undefined\") {\r\n return null;\r\n }\r\n\r\n this.logger.info(\"Add msal frame to document:\" + iframeId);\r\n let adalFrame = document.getElementById(iframeId) as HTMLIFrameElement;\r\n if (!adalFrame) {\r\n if (document.createElement &&\r\n document.documentElement &&\r\n (window.navigator.userAgent.indexOf(\"MSIE 5.0\") === -1)) {\r\n const ifr = document.createElement(\"iframe\");\r\n ifr.setAttribute(\"id\", iframeId);\r\n ifr.style.visibility = \"hidden\";\r\n ifr.style.position = \"absolute\";\r\n ifr.style.width = ifr.style.height = \"0\";\r\n ifr.style.border = \"0\";\r\n adalFrame = (document.getElementsByTagName(\"body\")[0].appendChild(ifr) as HTMLIFrameElement);\r\n } else if (document.body && document.body.insertAdjacentHTML) {\r\n document.body.insertAdjacentHTML(\"beforeend\", \"<iframe name='\" + iframeId + \"' id='\" + iframeId + \"' style='display:none'></iframe>\");\r\n }\r\n\r\n if (window.frames && window.frames[iframeId]) {\r\n adalFrame = window.frames[iframeId];\r\n }\r\n }\r\n\r\n return adalFrame;\r\n }\r\n\r\n //#endregion\r\n\r\n //#region General Helpers\r\n\r\n /**\r\n * @hidden\r\n *\r\n * Adds login_hint to authorization URL which is used to pre-fill the username field of sign in page for the user if known ahead of time\r\n * domain_hint can be one of users/organizations which when added skips the email based discovery process of the user\r\n * domain_req utid received as part of the clientInfo\r\n * login_req uid received as part of clientInfo\r\n * Also does a sanity check for extraQueryParameters passed by the user to ensure no repeat queryParameters\r\n *\r\n * @param {@link Account} account - Account for which the token is requested\r\n * @param queryparams\r\n * @param {@link ServerRequestParameters}\r\n * @ignore\r\n */\r\n private addHintParameters(accountObj: Account, qParams: QPDict, serverReqParams: ServerRequestParameters): QPDict {\r\n\r\n const account: Account = accountObj || this.getAccount();\r\n\r\n // This is a final check for all queryParams added so far; preference order: sid > login_hint\r\n // sid cannot be passed along with login_hint or domain_hint, hence we check both are not populated yet in queryParameters\r\n if (account && !qParams[SSOTypes.SID]) {\r\n // sid - populate only if login_hint is not already populated and the account has sid\r\n const populateSID = !qParams[SSOTypes.LOGIN_HINT] && account.sid && serverReqParams.promptValue === PromptState.NONE;\r\n if (populateSID) {\r\n qParams = Utils.addSSOParameter(SSOTypes.SID, account.sid, qParams);\r\n }\r\n // login_hint - account.userName\r\n else {\r\n const populateLoginHint = !qParams[SSOTypes.LOGIN_HINT] && account.userName && !Utils.isEmpty(account.userName);\r\n if (populateLoginHint) {\r\n qParams = Utils.addSSOParameter(SSOTypes.LOGIN_HINT, account.userName, qParams);\r\n }\r\n }\r\n\r\n const populateReqParams = !qParams[SSOTypes.DOMAIN_REQ] && !qParams[SSOTypes.LOGIN_REQ];\r\n if (populateReqParams) {\r\n qParams = Utils.addSSOParameter(SSOTypes.HOMEACCOUNT_ID, account.homeAccountIdentifier, qParams);\r\n }\r\n }\r\n\r\n return qParams;\r\n }\r\n\r\n /**\r\n * @hidden\r\n * Used to redirect the browser to the STS authorization endpoint\r\n * @param {string} urlNavigate - URL of the authorization endpoint\r\n */\r\n private promptUser(urlNavigate: string) {\r\n // Navigate if valid URL\r\n if (urlNavigate && !Utils.isEmpty(urlNavigate)) {\r\n this.logger.infoPii(\"Navigate to:\" + urlNavigate);\r\n window.location.replace(urlNavigate);\r\n }\r\n else {\r\n this.logger.info(\"Navigate url is empty\");\r\n throw AuthError.createUnexpectedError(\"Navigate url is empty\");\r\n }\r\n }\r\n\r\n /**\r\n * @hidden\r\n * Used to add the developer requested callback to the array of callbacks for the specified scopes. The updated array is stored on the window object\r\n * @param {string} expectedState - Unique state identifier (guid).\r\n * @param {string} scope - Developer requested permissions. Not all scopes are guaranteed to be included in the access token returned.\r\n * @param {Function} resolve - The resolve function of the promise object.\r\n * @param {Function} reject - The reject function of the promise object.\r\n * @ignore\r\n */\r\n private registerCallback(expectedState: string, scope: string, resolve: Function, reject: Function): void {\r\n // track active renewals\r\n window.activeRenewals[scope] = expectedState;\r\n\r\n // initialize callbacks mapped array\r\n if (!window.promiseMappedToRenewStates[expectedState]) {\r\n window.promiseMappedToRenewStates[expectedState] = [];\r\n }\r\n // indexing on the current state, push the callback params to callbacks mapped\r\n window.promiseMappedToRenewStates[expectedState].push({ resolve: resolve, reject: reject });\r\n\r\n // Store the server esponse in the current window??\r\n if (!window.callbackMappedToRenewStates[expectedState]) {\r\n window.callbackMappedToRenewStates[expectedState] =\r\n (response: AuthResponse, error: AuthError) => {\r\n // reset active renewals\r\n window.activeRenewals[scope] = null;\r\n\r\n // for all promiseMappedtoRenewStates for a given 'state' - call the reject/resolve with error/token respectively\r\n for (let i = 0; i < window.promiseMappedToRenewStates[expectedState].length; ++i) {\r\n try {\r\n if (error) {\r\n window.promiseMappedToRenewStates[expectedState][i].reject(error);\r\n } else if (response) {\r\n window.promiseMappedToRenewStates[expectedState][i].resolve(response);\r\n } else {\r\n throw AuthError.createUnexpectedError(\"Error and response are both null\");\r\n }\r\n } catch (e) {\r\n this.logger.warning(e);\r\n }\r\n }\r\n\r\n // reset\r\n window.promiseMappedToRenewStates[expectedState] = null;\r\n window.callbackMappedToRenewStates[expectedState] = null;\r\n };\r\n }\r\n }\r\n\r\n //#endregion\r\n\r\n //#region Logout\r\n\r\n /**\r\n * Use to log out the current user, and redirect the user to the postLogoutRedirectUri.\r\n * Default behaviour is to redirect the user to `window.location.href`.\r\n */\r\n logout(): void {\r\n this.clearCache();\r\n this.account = null;\r\n let logout = \"\";\r\n if (this.getPostLogoutRedirectUri()) {\r\n logout = \"post_logout_redirect_uri=\" + encodeURIComponent(this.getPostLogoutRedirectUri());\r\n }\r\n this.authorityInstance.resolveEndpointsAsync().then(authority => {\r\n const urlNavigate = authority.EndSessionEndpoint\r\n ? `${authority.EndSessionEndpoint}?${logout}`\r\n : `${this.authority}oauth2/v2.0/logout?${logout}`;\r\n this.promptUser(urlNavigate);\r\n });\r\n }\r\n\r\n /**\r\n * @hidden\r\n * Clear all access tokens in the cache.\r\n * @ignore\r\n */\r\n protected clearCache(): void {\r\n window.renewStates = [];\r\n const accessTokenItems = this.cacheStorage.getAllAccessTokens(Constants.clientId, Constants.homeAccountIdentifier);\r\n for (let i = 0; i < accessTokenItems.length; i++) {\r\n this.cacheStorage.removeItem(JSON.stringify(accessTokenItems[i].key));\r\n }\r\n this.cacheStorage.resetCacheItems();\r\n this.cacheStorage.clearCookie();\r\n }\r\n\r\n /**\r\n * @hidden\r\n * Clear a given access token from the cache.\r\n *\r\n * @param accessToken\r\n */\r\n protected clearCacheForScope(accessToken: string) {\r\n const accessTokenItems = this.cacheStorage.getAllAccessTokens(Constants.clientId, Constants.homeAccountIdentifier);\r\n for (let i = 0; i < accessTokenItems.length; i++) {\r\n let token = accessTokenItems[i];\r\n if (token.value.accessToken === accessToken) {\r\n this.cacheStorage.removeItem(JSON.stringify(token.key));\r\n }\r\n }\r\n }\r\n\r\n //#endregion\r\n\r\n //#region Response\r\n\r\n /**\r\n * @hidden\r\n * Used to call the constructor callback with the token/error\r\n * @param {string} [hash=window.location.hash] - Hash fragment of Url.\r\n */\r\n private processCallBack(hash: string, stateInfo: ResponseStateInfo, parentCallback?: Function): void {\r\n this.logger.info(\"Processing the callback from redirect response\");\r\n // get the state info from the hash\r\n if (!stateInfo) {\r\n stateInfo = this.getResponseState(hash);\r\n }\r\n\r\n let response : AuthResponse;\r\n let authErr : AuthError;\r\n // Save the token info from the hash\r\n try {\r\n response = this.saveTokenFromHash(hash, stateInfo);\r\n } catch (err) {\r\n authErr = err;\r\n }\r\n\r\n // remove hash from the cache\r\n this.cacheStorage.removeItem(Constants.urlHash);\r\n\r\n try {\r\n // Clear the cookie in the hash\r\n this.cacheStorage.clearCookie();\r\n const accountState: string = this.getAccountState(stateInfo.state);\r\n if (response) {\r\n if ((stateInfo.requestType === Constants.renewToken) || response.accessToken) {\r\n if (window.parent !== window) {\r\n this.logger.verbose(\"Window is in iframe, acquiring token silently\");\r\n } else {\r\n this.logger.verbose(\"acquiring token interactive in progress\");\r\n }\r\n response.tokenType = Constants.accessToken;\r\n }\r\n else if (stateInfo.requestType === Constants.login) {\r\n response.tokenType = Constants.idToken;\r\n }\r\n if (!parentCallback) {\r\n this.redirectSuccessHandler(response);\r\n return;\r\n }\r\n } else if (!parentCallback) {\r\n this.redirectErrorHandler(authErr, buildResponseStateOnly(accountState));\r\n return;\r\n }\r\n\r\n parentCallback(response, authErr);\r\n } catch (err) {\r\n this.logger.error(\"Error occurred in token received callback function: \" + err);\r\n throw ClientAuthError.createErrorInCallbackFunction(err.toString());\r\n }\r\n }\r\n\r\n /**\r\n * @hidden\r\n * This method must be called for processing the response received from the STS. It extracts the hash, processes the token or error information and saves it in the cache. It then\r\n * calls the registered callbacks in case of redirect or resolves the promises with the result.\r\n * @param {string} [hash=window.location.hash] - Hash fragment of Url.\r\n */\r\n private handleAuthenticationResponse(hash: string): void {\r\n // retrieve the hash\r\n if (hash == null) {\r\n hash = window.location.hash;\r\n }\r\n\r\n let self = null;\r\n let isPopup: boolean = false;\r\n let isWindowOpenerMsal = false;\r\n\r\n // Check if the current window opened the iFrame/popup\r\n try {\r\n isWindowOpenerMsal = window.opener && window.opener.msal && window.opener.msal !== window.msal;\r\n } catch (err) {\r\n // err = SecurityError: Blocked a frame with origin \"[url]\" from accessing a cross-origin frame.\r\n isWindowOpenerMsal = false;\r\n }\r\n\r\n // Set the self to the window that created the popup/iframe\r\n if (isWindowOpenerMsal) {\r\n self = window.opener.msal;\r\n isPopup = true;\r\n } else if (window.parent && window.parent.msal) {\r\n self = window.parent.msal;\r\n }\r\n\r\n // if (window.parent !== window), by using self, window.parent becomes equal to window in getResponseState method specifically\r\n const stateInfo = self.getResponseState(hash);\r\n\r\n let tokenResponseCallback: (response: AuthResponse, error: AuthError) => void = null;\r\n\r\n self.logger.info(\"Returned from redirect url\");\r\n // If parent window is the msal instance which opened the current window (iframe)\r\n if (this.parentIsMsal()) {\r\n tokenResponseCallback = window.parent.callbackMappedToRenewStates[stateInfo.state];\r\n }\r\n // Current window is window opener (popup)\r\n else if (isWindowOpenerMsal) {\r\n tokenResponseCallback = window.opener.callbackMappedToRenewStates[stateInfo.state];\r\n }\r\n // Redirect cases\r\n else {\r\n tokenResponseCallback = null;\r\n // if set to navigate to loginRequest page post login\r\n if (self.config.auth.navigateToLoginRequestUrl) {\r\n self.cacheStorage.setItem(Constants.urlHash, hash);\r\n if (window.parent === window && !isPopup) {\r\n window.location.href = self.cacheStorage.getItem(Constants.loginRequest, self.inCookie);\r\n }\r\n return;\r\n }\r\n else {\r\n window.location.hash = \"\";\r\n }\r\n if (!this.redirectCallbacksSet) {\r\n // We reached this point too early - cache hash, return and process in handleRedirectCallbacks\r\n self.cacheStorage.setItem(Constants.urlHash, hash);\r\n return;\r\n }\r\n }\r\n\r\n self.processCallBack(hash, stateInfo, tokenResponseCallback);\r\n\r\n // If current window is opener, close all windows\r\n if (isWindowOpenerMsal) {\r\n for (let i = 0; i < window.opener.openedWindows.length; i++) {\r\n window.opener.openedWindows[i].close();\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * @hidden\r\n * Returns deserialized portion of URL hash\r\n * @param hash\r\n */\r\n private deserializeHash(hash: string) {\r\n hash = this.getHash(hash);\r\n return Utils.deserialize(hash);\r\n }\r\n\r\n /**\r\n * @hidden\r\n * Creates a stateInfo object from the URL fragment and returns it.\r\n * @param {string} hash - Hash passed from redirect page\r\n * @returns {TokenResponse} an object created from the redirect response from AAD comprising of the keys - parameters, requestType, stateMatch, stateResponse and valid.\r\n * @ignore\r\n */\r\n protected getResponseState(hash: string): ResponseStateInfo {\r\n const parameters = this.deserializeHash(hash);\r\n let stateResponse: ResponseStateInfo;\r\n if (!parameters) {\r\n throw AuthError.createUnexpectedError(\"Hash was not parsed correctly.\");\r\n }\r\n if (parameters.hasOwnProperty(\"state\")) {\r\n stateResponse = {\r\n requestType: Constants.unknown,\r\n state: parameters.state,\r\n stateMatch: false\r\n };\r\n } else {\r\n throw AuthError.createUnexpectedError(\"Hash does not contain state.\");\r\n }\r\n // async calls can fire iframe and login request at the same time if developer does not use the API as expected\r\n // incoming callback needs to be looked up to find the request type\r\n\r\n // loginRedirect\r\n if (stateResponse.state === this.cacheStorage.getItem(Constants.stateLogin, this.inCookie) || stateResponse.state === this.silentAuthenticationState) { // loginRedirect\r\n stateResponse.requestType = Constants.login;\r\n stateResponse.stateMatch = true;\r\n return stateResponse;\r\n }\r\n // acquireTokenRedirect\r\n else if (stateResponse.state === this.cacheStorage.getItem(Constants.stateAcquireToken, this.inCookie)) { //acquireTokenRedirect\r\n stateResponse.requestType = Constants.renewToken;\r\n stateResponse.stateMatch = true;\r\n return stateResponse;\r\n }\r\n\r\n // external api requests may have many renewtoken requests for different resource\r\n if (!stateResponse.stateMatch) {\r\n stateResponse.requestType = window.requestType;\r\n const statesInParentContext = window.renewStates;\r\n for (let i = 0; i < statesInParentContext.length; i++) {\r\n if (statesInParentContext[i] === stateResponse.state) {\r\n stateResponse.stateMatch = true;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n return stateResponse;\r\n }\r\n\r\n //#endregion\r\n\r\n //#region Token Processing (Extract to TokenProcessing.ts)\r\n\r\n /**\r\n * @hidden\r\n * Used to get token for the specified set of scopes from the cache\r\n * @param {@link ServerRequestParameters} - Request sent to the STS to obtain an id_token/access_token\r\n * @param {Account} account - Account for which the scopes were requested\r\n */\r\n private getCachedToken(serverAuthenticationRequest: ServerRequestParameters, account: Account): AuthResponse {\r\n let accessTokenCacheItem: AccessTokenCacheItem = null;\r\n const scopes = serverAuthenticationRequest.scopes;\r\n\r\n // filter by clientId and account\r\n const tokenCacheItems = this.cacheStorage.getAllAccessTokens(this.clientId, account ? account.homeAccountIdentifier : null);\r\n\r\n // No match found after initial filtering\r\n if (tokenCacheItems.length === 0) {\r\n return null;\r\n }\r\n\r\n const filteredItems: Array<AccessTokenCacheItem> = [];\r\n\r\n // if no authority passed\r\n if (!serverAuthenticationRequest.authority) {\r\n // filter by scope\r\n for (let i = 0; i < tokenCacheItems.length; i++) {\r\n const cacheItem = tokenCacheItems[i];\r\n const cachedScopes = cacheItem.key.scopes.split(\" \");\r\n if (Utils.containsScope(cachedScopes, scopes)) {\r\n filteredItems.push(cacheItem);\r\n }\r\n }\r\n\r\n // if only one cached token found\r\n if (filteredItems.length === 1) {\r\n accessTokenCacheItem = filteredItems[0];\r\n serverAuthenticationRequest.authorityInstance = AuthorityFactory.CreateInstance(accessTokenCacheItem.key.authority, this.config.auth.validateAuthority);\r\n }\r\n // if more than one cached token is found\r\n else if (filteredItems.length > 1) {\r\n throw ClientAuthError.createMultipleMatchingTokensInCacheError(scopes.toString());\r\n }\r\n // if no match found, check if there was a single authority used\r\n else {\r\n const authorityList = this.getUniqueAuthority(tokenCacheItems, \"authority\");\r\n if (authorityList.length > 1) {\r\n throw ClientAuthError.createMultipleAuthoritiesInCacheError(scopes.toString());\r\n }\r\n\r\n serverAuthenticationRequest.authorityInstance = AuthorityFactory.CreateInstance(authorityList[0], this.config.auth.validateAuthority);\r\n }\r\n }\r\n // if an authority is passed in the API\r\n else {\r\n // filter by authority and scope\r\n for (let i = 0; i < tokenCacheItems.length; i++) {\r\n const cacheItem = tokenCacheItems[i];\r\n const cachedScopes = cacheItem.key.scopes.split(\" \");\r\n if (Utils.containsScope(cachedScopes, scopes) && Utils.CanonicalizeUri(cacheItem.key.authority) === serverAuthenticationRequest.authority) {\r\n filteredItems.push(cacheItem);\r\n }\r\n }\r\n // no match\r\n if (filteredItems.length === 0) {\r\n return null;\r\n }\r\n // if only one cachedToken Found\r\n else if (filteredItems.length === 1) {\r\n accessTokenCacheItem = filteredItems[0];\r\n }\r\n else {\r\n // if more than cached token is found\r\n throw ClientAuthError.createMultipleMatchingTokensInCacheError(scopes.toString());\r\n }\r\n }\r\n\r\n if (accessTokenCacheItem != null) {\r\n let expired = Number(accessTokenCacheItem.value.expiresIn);\r\n // If expiration is within offset, it will force renew\r\n const offset = this.config.system.tokenRenewalOffsetSeconds || 300;\r\n if (expired && (expired > Utils.now() + offset)) {\r\n let idToken = new IdToken(accessTokenCacheItem.value.idToken);\r\n if (!account) {\r\n account = this.getAccount();\r\n if (!account) {\r\n throw AuthError.createUnexpectedError(\"Account should not be null here.\");\r\n }\r\n }\r\n const aState = this.getAccountState(serverAuthenticationRequest.state);\r\n let response : AuthResponse = {\r\n uniqueId: \"\",\r\n tenantId: \"\",\r\n tokenType: (accessTokenCacheItem.value.idToken === accessTokenCacheItem.value.accessToken) ? Constants.idToken : Constants.accessToken,\r\n idToken: idToken,\r\n accessToken: accessTokenCacheItem.value.accessToken,\r\n scopes: accessTokenCacheItem.key.scopes.split(\" \"),\r\n expiresOn: new Date(expired * 1000),\r\n account: account,\r\n accountState: aState,\r\n };\r\n Utils.setResponseIdToken(response, idToken);\r\n return response;\r\n } else {\r\n this.cacheStorage.removeItem(JSON.stringify(filteredItems[0].key));\r\n return null;\r\n }\r\n } else {\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * @hidden\r\n * Used to get a unique list of authoritues from the cache\r\n * @param {Array<AccessTokenCacheItem>} accessTokenCacheItems - accessTokenCacheItems saved in the cache\r\n * @ignore\r\n */\r\n private getUniqueAuthority(accessTokenCacheItems: Array<AccessTokenCacheItem>, property: string): Array<string> {\r\n const authorityList: Array<string> = [];\r\n const flags: Array<string> = [];\r\n accessTokenCacheItems.forEach(element => {\r\n if (element.key.hasOwnProperty(property) && (flags.indexOf(element.key[property]) === -1)) {\r\n flags.push(element.key[property]);\r\n authorityList.push(element.key[property]);\r\n }\r\n });\r\n return authorityList;\r\n }\r\n\r\n /**\r\n * @hidden\r\n * Check if ADAL id_token exists and return if exists.\r\n *\r\n */\r\n private extractADALIdToken(): any {\r\n const adalIdToken = this.cacheStorage.getItem(Constants.adalIdToken);\r\n if (!Utils.isEmpty(adalIdToken)) {\r\n return Utils.extractIdToken(adalIdToken);\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * @hidden\r\n * Acquires access token using a hidden iframe.\r\n * @ignore\r\n */\r\n private renewToken(scopes: Array<string>, resolve: Function, reject: Function, account: Account, serverAuthenticationRequest: ServerRequestParameters): void {\r\n const scope = scopes.join(\" \").toLowerCase();\r\n this.logger.verbose(\"renewToken is called for scope:\" + scope);\r\n const frameHandle = this.addHiddenIFrame(\"msalRenewFrame\" + scope);\r\n\r\n this.updateCacheEntries(serverAuthenticationRequest, account);\r\n this.logger.verbose(\"Renew token Expected state: \" + serverAuthenticationRequest.state);\r\n\r\n // Build urlNavigate with \"prompt=none\" and navigate to URL in hidden iFrame\r\n let urlNavigate = Utils.urlRemoveQueryStringParameter(serverAuthenticationRequest.createNavigateUrl(scopes), Constants.prompt) + Constants.prompt_none;\r\n\r\n window.renewStates.push(serverAuthenticationRequest.state);\r\n window.requestType = Constants.renewToken;\r\n this.registerCallback(serverAuthenticationRequest.state, scope, resolve, reject);\r\n this.logger.infoPii(\"Navigate to:\" + urlNavigate);\r\n frameHandle.src = \"about:blank\";\r\n this.loadIframeTimeout(urlNavigate, \"msalRenewFrame\" + scope, scope);\r\n }\r\n\r\n /**\r\n * @hidden\r\n * Renews idtoken for app\"s own backend when clientId is passed as a single scope in the scopes array.\r\n * @ignore\r\n */\r\n private renewIdToken(scopes: Array<string>, resolve: Function, reject: Function, account: Account, serverAuthenticationRequest: ServerRequestParameters): void {\r\n\r\n this.logger.info(\"renewidToken is called\");\r\n const frameHandle = this.addHiddenIFrame(\"msalIdTokenFrame\");\r\n\r\n this.updateCacheEntries(serverAuthenticationRequest, account);\r\n\r\n this.logger.verbose(\"Renew Idtoken Expected state: \" + serverAuthenticationRequest.state);\r\n\r\n // Build urlNavigate with \"prompt=none\" and navigate to URL in hidden iFrame\r\n let urlNavigate = Utils.urlRemoveQueryStringParameter(serverAuthenticationRequest.createNavigateUrl(scopes), Constants.prompt) + Constants.prompt_none;\r\n\r\n if (this.silentLogin) {\r\n window.requestType = Constants.login;\r\n this.silentAuthenticationState = serverAuthenticationRequest.state;\r\n } else {\r\n window.requestType = Constants.renewToken;\r\n window.renewStates.push(serverAuthenticationRequest.state);\r\n }\r\n\r\n // note: scope here is clientId\r\n this.registerCallback(serverAuthenticationRequest.state, this.clientId, resolve, reject);\r\n this.logger.infoPii(\"Navigate to:\" + urlNavigate);\r\n frameHandle.src = \"about:blank\";\r\n this.loadIframeTimeout(urlNavigate, \"msalIdTokenFrame\", this.clientId);\r\n }\r\n\r\n /**\r\n * @hidden\r\n *\r\n * This method must be called for processing the response received from AAD. It extracts the hash, processes the token or error, saves it in the cache and calls the registered callbacks with the result.\r\n * @param {string} authority authority received in the redirect response from AAD.\r\n * @param {TokenResponse} requestInfo an object created from the redirect response from AAD comprising of the keys - parameters, requestType, stateMatch, stateResponse and valid.\r\n * @param {Account} account account object for which scopes are consented for. The default account is the logged in account.\r\n * @param {ClientInfo} clientInfo clientInfo received as part of the response comprising of fields uid and utid.\r\n * @param {IdToken} idToken idToken received as part of the response.\r\n * @ignore\r\n * @private\r\n */\r\n /* tslint:disable:no-string-literal */\r\n private saveAccessToken(response: AuthResponse, authority: string, parameters: any, clientInfo: string): AuthResponse {\r\n let scope: string;\r\n let accessTokenResponse = { ...response };\r\n const clientObj: ClientInfo = new ClientInfo(clientInfo);\r\n\r\n // if the response contains \"scope\"\r\n if (parameters.hasOwnProperty(\"scope\")) {\r\n // read the scopes\r\n scope = parameters[\"scope\"];\r\n const consentedScopes = scope.split(\" \");\r\n\r\n // retrieve all access tokens from the cache, remove the dup scores\r\n const accessTokenCacheItems = this.cacheStorage.getAllAccessTokens(this.clientId, authority);\r\n\r\n for (let i = 0; i < accessTokenCacheItems.length; i++) {\r\n const accessTokenCacheItem = accessTokenCacheItems[i];\r\n\r\n if (accessTokenCacheItem.key.homeAccountIdentifier === response.account.homeAccountIdentifier) {\r\n const cachedScopes = accessTokenCacheItem.key.scopes.split(\" \");\r\n if (Utils.isIntersectingScopes(cachedScopes, consentedScopes)) {\r\n this.cacheStorage.removeItem(JSON.stringify(accessTokenCacheItem.key));\r\n }\r\n }\r\n }\r\n\r\n // Generate and cache accessTokenKey and accessTokenValue\r\n const expiresIn = Utils.expiresIn(parameters[Constants.expiresIn]).toString();\r\n const accessTokenKey = new AccessTokenKey(authority, this.clientId, scope, clientObj.uid, clientObj.utid);\r\n const accessTokenValue = new AccessTokenValue(parameters[Constants.accessToken], response.idToken.rawIdToken, expiresIn, clientInfo);\r\n\r\n this.cacheStorage.setItem(JSON.stringify(accessTokenKey), JSON.stringify(accessTokenValue));\r\n\r\n accessTokenResponse.accessToken = parameters[Constants.accessToken];\r\n accessTokenResponse.scopes = consentedScopes;\r\n let exp = Number(expiresIn);\r\n if (exp) {\r\n accessTokenResponse.expiresOn = new Date((Utils.now() + exp) * 1000);\r\n } else {\r\n this.logger.error(\"Could not parse expiresIn parameter. Given value: \" + expiresIn);\r\n }\r\n }\r\n // if the response does not contain \"scope\" - scope is usually client_id and the token will be id_token\r\n else {\r\n scope = this.clientId;\r\n\r\n // Generate and cache accessTokenKey and accessTokenValue\r\n const accessTokenKey = new AccessTokenKey(authority, this.clientId, scope, clientObj.uid, clientObj.utid);\r\n\r\n const accessTokenValue = new AccessTokenValue(parameters[Constants.idToken], parameters[Constants.idToken], response.idToken.expiration, clientInfo);\r\n this.cacheStorage.setItem(JSON.stringify(accessTokenKey), JSON.stringify(accessTokenValue));\r\n accessTokenResponse.scopes = [scope];\r\n accessTokenResponse.accessToken = parameters[Constants.idToken];\r\n let exp = Number(response.idToken.expiration);\r\n if (exp) {\r\n accessTokenResponse.expiresOn = new Date(exp * 1000);\r\n } else {\r\n this.logger.error(\"Could not parse expiresIn parameter\");\r\n }\r\n }\r\n return accessTokenResponse;\r\n }\r\n\r\n /**\r\n * @hidden\r\n * Saves token or error received in the response from AAD in the cache. In case of id_token, it also creates the account object.\r\n * @ignore\r\n */\r\n protected saveTokenFromHash(hash: string, stateInfo: ResponseStateInfo): AuthResponse {\r\n this.logger.info(\"State status:\" + stateInfo.stateMatch + \"; Request type:\" + stateInfo.requestType);\r\n this.cacheStorage.setItem(Constants.msalError, \"\");\r\n this.cacheStorage.setItem(Constants.msalErrorDescription, \"\");\r\n\r\n let response : AuthResponse = {\r\n uniqueId: \"\",\r\n tenantId: \"\",\r\n tokenType: \"\",\r\n idToken: null,\r\n accessToken: null,\r\n scopes: [],\r\n expiresOn: null,\r\n account: null,\r\n accountState: \"\",\r\n };\r\n\r\n let error: AuthError;\r\n const hashParams = this.deserializeHash(hash);\r\n let authorityKey: string = \"\";\r\n let acquireTokenAccountKey: string = \"\";\r\n\r\n // If server returns an error\r\n if (hashParams.hasOwnProperty(Constants.errorDescription) || hashParams.hasOwnProperty(Constants.error)) {\r\n this.logger.infoPii(\"Error :\" + hashParams[Constants.error] + \"; Error description:\" + hashParams[Constants.errorDescription]);\r\n this.cacheStorage.setItem(Constants.msalError, hashParams[Constants.error]);\r\n this.cacheStorage.setItem(Constants.msalErrorDescription, hashParams[Constants.errorDescription]);\r\n\r\n // login\r\n if (stateInfo.requestType === Constants.login) {\r\n this.loginInProgress = false;\r\n this.cacheStorage.setItem(Constants.loginError, hashParams[Constants.errorDescription] + \":\" + hashParams[Constants.error]);\r\n authorityKey = Storage.generateAuthorityKey(stateInfo.state);\r\n }\r\n\r\n // acquireToken\r\n if (stateInfo.requestType === Constants.renewToken) {\r\n this.acquireTokenInProgress = false;\r\n authorityKey = Storage.generateAuthorityKey(stateInfo.state);\r\n\r\n const account: Account = this.getAccount();\r\n let accountId;\r\n\r\n if (account && !Utils.isEmpty(account.homeAccountIdentifier)) {\r\n accountId = account.homeAccountIdentifier;\r\n }\r\n else {\r\n accountId = Constants.no_account;\r\n }\r\n\r\n acquireTokenAccountKey = Storage.generateAcquireTokenAccountKey(accountId, stateInfo.state);\r\n }\r\n\r\n if (this.isInteractionRequired(hashParams[Constants.error]) || this.isInteractionRequired(hashParams[Constants.errorDescription])) {\r\n error = new InteractionRequiredAuthError(hashParams[Constants.error], hashParams[Constants.errorDescription]);\r\n } else {\r\n error = new ServerError(hashParams[Constants.error], hashParams[Constants.errorDescription]);\r\n }\r\n }\r\n // If the server returns \"Success\"\r\n else {\r\n // Verify the state from redirect and record tokens to storage if exists\r\n if (stateInfo.stateMatch) {\r\n this.logger.info(\"State is right\");\r\n if (hashParams.hasOwnProperty(Constants.sessionState)) {\r\n this.cacheStorage.setItem(Constants.msalSessionState, hashParams[Constants.sessionState]);\r\n }\r\n response.accountState = this.getAccountState(stateInfo.state);\r\n\r\n let clientInfo: string = \"\";\r\n\r\n // Process access_token\r\n if (hashParams.hasOwnProperty(Constants.accessToken)) {\r\n this.logger.info(\"Fragment has access token\");\r\n this.acquireTokenInProgress = false;\r\n\r\n // retrieve the id_token from response if present :\r\n if (hashParams.hasOwnProperty(Constants.idToken)) {\r\n response.idToken = new IdToken(hashParams[Constants.idToken]);\r\n } else {\r\n response = Utils.setResponseIdToken(response, new IdToken(this.cacheStorage.getItem(Constants.idTokenKey)));\r\n }\r\n\r\n // retrieve the authority from cache and replace with tenantID\r\n const authorityKey = Storage.generateAuthorityKey(stateInfo.state);\r\n let authority: string = this.cacheStorage.getItem(authorityKey, this.inCookie);\r\n\r\n if (!Utils.isEmpty(authority)) {\r\n authority = Utils.replaceTenantPath(authority, response.tenantId);\r\n }\r\n\r\n // retrieve client_info - if it is not found, generate the uid and utid from idToken\r\n if (hashParams.hasOwnProperty(Constants.clientInfo)) {\r\n clientInfo = hashParams[Constants.clientInfo];\r\n } else {\r\n this.logger.warning(\"ClientInfo not received in the response from AAD\");\r\n throw ClientAuthError.createClientInfoNotPopulatedError(\"ClientInfo not received in the response from the server\");\r\n }\r\n\r\n response.account = Account.createAccount(response.idToken, new ClientInfo(clientInfo));\r\n\r\n let accountKey: string;\r\n if (response.account && !Utils.isEmpty(response.account.homeAccountIdentifier)) {\r\n accountKey = response.account.homeAccountIdentifier;\r\n }\r\n else {\r\n accountKey = Constants.no_account;\r\n }\r\n\r\n acquireTokenAccountKey = Storage.generateAcquireTokenAccountKey(accountKey, stateInfo.state);\r\n const acquireTokenAccountKey_noaccount = Storage.generateAcquireTokenAccountKey(Constants.no_account, stateInfo.state);\r\n\r\n let cachedAccount: string = this.cacheStorage.getItem(acquireTokenAccountKey);\r\n let acquireTokenAccount: Account;\r\n\r\n // Check with the account in the Cache\r\n if (!Utils.isEmpty(cachedAccount)) {\r\n acquireTokenAccount = JSON.parse(cachedAccount);\r\n if (response.account && acquireTokenAccount && Utils.compareAccounts(response.account, acquireTokenAccount)) {\r\n response = this.saveAccessToken(response, authority, hashParams, clientInfo);\r\n this.logger.info(\"The user object received in the response is the same as the one passed in the acquireToken request\");\r\n }\r\n else {\r\n this.logger.warning(\r\n \"The account object created from the response is not the same as the one passed in the acquireToken request\");\r\n }\r\n }\r\n else if (!Utils.isEmpty(this.cacheStorage.getItem(acquireTokenAccountKey_noaccount))) {\r\n response = this.saveAccessToken(response, authority, hashParams, clientInfo);\r\n }\r\n }\r\n\r\n // Process id_token\r\n if (hashParams.hasOwnProperty(Constants.idToken)) {\r\n this.logger.info(\"Fragment has id token\");\r\n\r\n // login no longer in progress\r\n this.loginInProgress = false;\r\n response = Utils.setResponseIdToken(response, new IdToken(hashParams[Constants.idToken]));\r\n if (hashParams.hasOwnProperty(Constants.clientInfo)) {\r\n clientInfo = hashParams[Constants.clientInfo];\r\n } else {\r\n this.logger.warning(\"ClientInfo not received in the response from AAD\");\r\n }\r\n\r\n authorityKey = Storage.generateAuthorityKey(stateInfo.state);\r\n let authority: string = this.cacheStorage.getItem(authorityKey, this.inCookie);\r\n\r\n if (!Utils.isEmpty(authority)) {\r\n authority = Utils.replaceTenantPath(authority, response.idToken.tenantId);\r\n }\r\n\r\n this.account = Account.createAccount(response.idToken, new ClientInfo(clientInfo));\r\n response.account = this.account;\r\n\r\n if (response.idToken && response.idToken.nonce) {\r\n // check nonce integrity if idToken has nonce - throw an error if not matched\r\n if (response.idToken.nonce !== this.cacheStorage.getItem(Constants.nonceIdToken, this.inCookie)) {\r\n this.account = null;\r\n this.cacheStorage.setItem(Constants.loginError, \"Nonce Mismatch. Expected Nonce: \" + this.cacheStorage.getItem(Constants.nonceIdToken, this.inCookie) + \",\" + \"Actual Nonce: \" + response.idToken.nonce);\r\n this.logger.error(\"Nonce Mismatch.Expected Nonce: \" + this.cacheStorage.getItem(Constants.nonceIdToken, this.inCookie) + \",\" + \"Actual Nonce: \" + response.idToken.nonce);\r\n error = ClientAuthError.createNonceMismatchError(this.cacheStorage.getItem(Constants.nonceIdToken, this.inCookie), response.idToken.nonce);\r\n }\r\n // Save the token\r\n else {\r\n this.cacheStorage.setItem(Constants.idTokenKey, hashParams[Constants.idToken]);\r\n this.cacheStorage.setItem(Constants.msalClientInfo, clientInfo);\r\n\r\n // Save idToken as access token for app itself\r\n this.saveAccessToken(response, authority, hashParams, clientInfo);\r\n }\r\n } else {\r\n authorityKey = stateInfo.state;\r\n acquireTokenAccountKey = stateInfo.state;\r\n\r\n this.logger.error(\"Invalid id_token received in the response\");\r\n error = ClientAuthError.createInvalidIdTokenError(response.idToken);\r\n this.cacheStorage.setItem(Constants.msalError, error.errorCode);\r\n this.cacheStorage.setItem(Constants.msalErrorDescription, error.errorMessage);\r\n }\r\n }\r\n }\r\n // State mismatch - unexpected/invalid state\r\n else {\r\n authorityKey = stateInfo.state;\r\n acquireTokenAccountKey = stateInfo.state;\r\n\r\n const expectedState = this.cacheStorage.getItem(Constants.stateLogin, this.inCookie);\r\n this.logger.error(\"State Mismatch.Expected State: \" + expectedState + \",\" + \"Actual State: \" + stateInfo.state);\r\n error = ClientAuthError.createInvalidStateError(stateInfo.state, expectedState);\r\n this.cacheStorage.setItem(Constants.msalError, error.errorCode);\r\n this.cacheStorage.setItem(Constants.msalErrorDescription, error.errorMessage);\r\n }\r\n }\r\n\r\n this.cacheStorage.setItem(Constants.renewStatus + stateInfo.state, Constants.tokenRenewStatusCompleted);\r\n this.cacheStorage.removeAcquireTokenEntries(stateInfo.state);\r\n // this is required if navigateToLoginRequestUrl=false\r\n if (this.inCookie) {\r\n this.cacheStorage.setItemCookie(authorityKey, \"\", -1);\r\n this.cacheStorage.clearCookie();\r\n }\r\n if (error) {\r\n throw error;\r\n }\r\n\r\n if (!response) {\r\n throw AuthError.createUnexpectedError(\"Response is null\");\r\n }\r\n return response;\r\n }\r\n /* tslint:enable:no-string-literal */\r\n\r\n //#endregion\r\n\r\n //#region Account\r\n\r\n /**\r\n * Returns the signed in account\r\n * (the account object is created at the time of successful login)\r\n * or null when no state is found\r\n * @returns {@link Account} - the account object stored in MSAL\r\n */\r\n getAccount(): Account {\r\n // if a session already exists, get the account from the session\r\n if (this.account) {\r\n return this.account;\r\n }\r\n\r\n // frame is used to get idToken and populate the account for the given session\r\n const rawIdToken = this.cacheStorage.getItem(Constants.idTokenKey);\r\n const rawClientInfo = this.cacheStorage.getItem(Constants.msalClientInfo);\r\n\r\n if (!Utils.isEmpty(rawIdToken) && !Utils.isEmpty(rawClientInfo)) {\r\n const idToken = new IdToken(rawIdToken);\r\n const clientInfo = new ClientInfo(rawClientInfo);\r\n this.account = Account.createAccount(idToken, clientInfo);\r\n return this.account;\r\n }\r\n // if login not yet done, return null\r\n return null;\r\n }\r\n\r\n /**\r\n * @hidden\r\n *\r\n * Extracts state value from the accountState sent with the authentication request.\r\n * @returns {string} scope.\r\n * @ignore\r\n */\r\n getAccountState (state: string) {\r\n if (state) {\r\n const splitIndex = state.indexOf(\"|\");\r\n if (splitIndex > -1 && splitIndex + 1 < state.length) {\r\n return state.substring(splitIndex + 1);\r\n }\r\n }\r\n return state;\r\n }\r\n\r\n /**\r\n * Use to get a list of unique accounts in MSAL cache based on homeAccountIdentifier.\r\n *\r\n * @param {@link Array<Account>} Account - all unique accounts in MSAL cache.\r\n */\r\n getAllAccounts(): Array<Account> {\r\n const accounts: Array<Account> = [];\r\n const accessTokenCacheItems = this.cacheStorage.getAllAccessTokens(Constants.clientId, Constants.homeAccountIdentifier);\r\n\r\n for (let i = 0; i < accessTokenCacheItems.length; i++) {\r\n const idToken = new IdToken(accessTokenCacheItems[i].value.idToken);\r\n const clientInfo = new ClientInfo(accessTokenCacheItems[i].value.homeAccountIdentifier);\r\n const account: Account = Account.createAccount(idToken, clientInfo);\r\n accounts.push(account);\r\n }\r\n\r\n return this.getUniqueAccounts(accounts);\r\n }\r\n\r\n /**\r\n * @hidden\r\n *\r\n * Used to filter accounts based on homeAccountIdentifier\r\n * @param {Array<Account>} Accounts - accounts saved in the cache\r\n * @ignore\r\n */\r\n private getUniqueAccounts(accounts: Array<Account>): Array<Account> {\r\n if (!accounts || accounts.length <= 1) {\r\n return accounts;\r\n }\r\n\r\n const flags: Array<string> = [];\r\n const uniqueAccounts: Array<Account> = [];\r\n for (let index = 0; index < accounts.length; ++index) {\r\n if (accounts[index].homeAccountIdentifier && flags.indexOf(accounts[index].homeAccountIdentifier) === -1) {\r\n flags.push(accounts[index].homeAccountIdentifier);\r\n uniqueAccounts.push(accounts[index]);\r\n }\r\n }\r\n\r\n return uniqueAccounts;\r\n }\r\n\r\n //#endregion\r\n\r\n //#region Scopes (Extract to Scopes.ts)\r\n\r\n // Note: \"this\" dependency in this section is minimal.\r\n // If pCacheStorage is separated from the class object, or passed as a fn param, scopesUtils.ts can be created\r\n\r\n /**\r\n * @hidden\r\n *\r\n * Used to validate the scopes input parameter requested by the developer.\r\n * @param {Array<string>} scopes - Developer requested permissions. Not all scopes are guaranteed to be included in the access token returned.\r\n * @param {boolean} scopesRequired - Boolean indicating whether the scopes array is required or not\r\n * @ignore\r\n */\r\n private validateInputScope(scopes: Array<string>, scopesRequired: boolean): void {\r\n if (!scopes) {\r\n if (scopesRequired) {\r\n throw ClientConfigurationError.createScopesRequiredError(scopes);\r\n } else {\r\n return;\r\n }\r\n }\r\n\r\n // Check that scopes is an array object (also throws error if scopes == null)\r\n if (!Array.isArray(scopes)) {\r\n throw ClientConfigurationError.createScopesNonArrayError(scopes);\r\n }\r\n\r\n // Check that scopes is not an empty array\r\n if (scopes.length < 1) {\r\n throw ClientConfigurationError.createEmptyScopesArrayError(scopes.toString());\r\n }\r\n\r\n // Check that clientId is passed as single scope\r\n if (scopes.indexOf(this.clientId) > -1) {\r\n if (scopes.length > 1) {\r\n throw ClientConfigurationError.createClientIdSingleScopeError(scopes.toString());\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * @hidden\r\n *\r\n * Extracts scope value from the state sent with the authentication request.\r\n * @param {string} state\r\n * @returns {string} scope.\r\n * @ignore\r\n */\r\n private getScopeFromState(state: string): string {\r\n if (state) {\r\n const splitIndex = state.indexOf(\"|\");\r\n if (splitIndex > -1 && splitIndex + 1 < state.length) {\r\n return state.substring(splitIndex + 1);\r\n }\r\n }\r\n return \"\";\r\n }\r\n\r\n /**\r\n * @ignore\r\n * Appends extraScopesToConsent if passed\r\n * @param {@link AuthenticationParameters}\r\n */\r\n private appendScopes(request: AuthenticationParameters): Array<string> {\r\n\r\n let scopes: Array<string>;\r\n\r\n if (request && request.scopes) {\r\n if (request.extraScopesToConsent) {\r\n scopes = [...request.scopes, ...request.extraScopesToConsent];\r\n }\r\n else {\r\n scopes = request.scopes;\r\n }\r\n }\r\n\r\n return scopes;\r\n }\r\n\r\n //#endregion\r\n\r\n //#region Angular\r\n\r\n /**\r\n * @hidden\r\n *\r\n * Broadcast messages - Used only for Angular? *\r\n * @param eventName\r\n * @param data\r\n */\r\n private broadcast(eventName: string, data: string) {\r\n const evt = new CustomEvent(eventName, { detail: data });\r\n window.dispatchEvent(evt);\r\n }\r\n\r\n /**\r\n * @hidden\r\n *\r\n * Helper function to retrieve the cached token\r\n *\r\n * @param scopes\r\n * @param {@link Account} account\r\n * @param state\r\n * @return {@link AuthResponse} AuthResponse\r\n */\r\n protected getCachedTokenInternal(scopes : Array<string> , account: Account, state: string): AuthResponse {\r\n // Get the current session's account object\r\n const accountObject: Account = account || this.getAccount();\r\n if (!accountObject) {\r\n return null;\r\n }\r\n\r\n // Construct AuthenticationRequest based on response type\r\n const newAuthority = this.authorityInstance ? this.authorityInstance : AuthorityFactory.CreateInstance(this.authority, this.config.auth.validateAuthority);\r\n const responseType = this.getTokenType(accountObject, scopes, true);\r\n const serverAuthenticationRequest = new ServerRequestParameters(\r\n newAuthority,\r\n this.clientId,\r\n scopes,\r\n responseType,\r\n this.getRedirectUri(),\r\n state\r\n );\r\n\r\n // get cached token\r\n return this.getCachedToken(serverAuthenticationRequest, account);\r\n }\r\n\r\n /**\r\n * @hidden\r\n *\r\n * Get scopes for the Endpoint - Used in Angular to track protected and unprotected resources without interaction from the developer app\r\n *\r\n * @param endpoint\r\n */\r\n protected getScopesForEndpoint(endpoint: string) : Array<string> {\r\n // if user specified list of unprotectedResources, no need to send token to these endpoints, return null.\r\n if (this.config.framework.unprotectedResources.length > 0) {\r\n for (let i = 0; i < this.config.framework.unprotectedResources.length; i++) {\r\n if (endpoint.indexOf(this.config.framework.unprotectedResources[i]) > -1) {\r\n return null;\r\n }\r\n }\r\n }\r\n\r\n // process all protected resources and send the matched one\r\n if (this.config.framework.protectedResourceMap.size > 0) {\r\n for (let key of Array.from(this.config.framework.protectedResourceMap.keys())) {\r\n // configEndpoint is like /api/Todo requested endpoint can be /api/Todo/1\r\n if (endpoint.indexOf(key) > -1) {\r\n return this.config.framework.protectedResourceMap.get(key);\r\n }\r\n }\r\n }\r\n\r\n // default resource will be clientid if nothing specified\r\n // App will use idtoken for calls to itself\r\n // check if it's staring from http or https, needs to match with app host\r\n if (endpoint.indexOf(\"http://\") > -1 || endpoint.indexOf(\"https://\") > -1) {\r\n if (this.getHostFromUri(endpoint) === this.getHostFromUri(this.getRedirectUri())) {\r\n return new Array<string>(this.clientId);\r\n }\r\n } else {\r\n // in angular level, the url for $http interceptor call could be relative url,\r\n // if it's relative call, we'll treat it as app backend call.\r\n return new Array<string>(this.clientId);\r\n }\r\n\r\n // if not the app's own backend or not a domain listed in the endpoints structure\r\n return null;\r\n }\r\n\r\n /**\r\n * Return boolean flag to developer to help inform if login is in progress\r\n * @returns {boolean} true/false\r\n */\r\n public getLoginInProgress(): boolean {\r\n const pendingCallback = this.cacheStorage.getItem(Constants.urlHash);\r\n if (pendingCallback) {\r\n return true;\r\n }\r\n return this.loginInProgress;\r\n }\r\n\r\n /**\r\n * @hidden\r\n * @ignore\r\n *\r\n * @param loginInProgress\r\n */\r\n protected setloginInProgress(loginInProgress : boolean) {\r\n this.loginInProgress = loginInProgress;\r\n }\r\n\r\n /**\r\n * @hidden\r\n * @ignore\r\n *\r\n * returns the status of acquireTokenInProgress\r\n */\r\n protected getAcquireTokenInProgress(): boolean {\r\n return this.acquireTokenInProgress;\r\n }\r\n\r\n /**\r\n * @hidden\r\n * @ignore\r\n *\r\n * @param acquireTokenInProgress\r\n */\r\n protected setAcquireTokenInProgress(acquireTokenInProgress : boolean) {\r\n this.acquireTokenInProgress = acquireTokenInProgress;\r\n }\r\n\r\n /**\r\n * @hidden\r\n * @ignore\r\n *\r\n * returns the logger handle\r\n */\r\n protected getLogger() {\r\n return this.config.system.logger;\r\n }\r\n\r\n //#endregion\r\n\r\n //#region Getters and Setters\r\n\r\n /**\r\n *\r\n * Use to get the redirect uri configured in MSAL or null.\r\n * Evaluates redirectUri if its a function, otherwise simply returns its value.\r\n * @returns {string} redirect URL\r\n *\r\n */\r\n public getRedirectUri(): string {\r\n if (typeof this.config.auth.redirectUri === \"function\") {\r\n return this.config.auth.redirectUri();\r\n }\r\n return this.config.auth.redirectUri;\r\n }\r\n\r\n /**\r\n * Use to get the post logout redirect uri configured in MSAL or null.\r\n * Evaluates postLogoutredirectUri if its a function, otherwise simply returns its value.\r\n *\r\n * @returns {string} post logout redirect URL\r\n */\r\n public getPostLogoutRedirectUri(): string {\r\n if (typeof this.config.auth.postLogoutRedirectUri === \"function\") {\r\n return this.config.auth.postLogoutRedirectUri();\r\n }\r\n return this.config.auth.postLogoutRedirectUri;\r\n }\r\n\r\n /**\r\n * Use to get the current {@link Configuration} object in MSAL\r\n *\r\n * @returns {@link Configuration}\r\n */\r\n public getCurrentConfiguration(): Configuration {\r\n if (!this.config) {\r\n throw ClientConfigurationError.createNoSetConfigurationError();\r\n }\r\n return this.config;\r\n }\r\n\r\n //#endregion\r\n\r\n //#region String Util (Should be extracted to Utils.ts)\r\n\r\n /**\r\n * @hidden\r\n * @ignore\r\n *\r\n * Returns the anchor part(#) of the URL\r\n */\r\n private getHash(hash: string): string {\r\n if (hash.indexOf(\"#/\") > -1) {\r\n hash = hash.substring(hash.indexOf(\"#/\") + 2);\r\n } else if (hash.indexOf(\"#\") > -1) {\r\n hash = hash.substring(1);\r\n }\r\n\r\n return hash;\r\n }\r\n\r\n /**\r\n * @hidden\r\n * @ignore\r\n *\r\n * extract URI from the host\r\n *\r\n * @param {string} URI\r\n * @returns {string} host from the URI\r\n */\r\n private getHostFromUri(uri: string): string {\r\n // remove http:// or https:// from uri\r\n let extractedUri = String(uri).replace(/^(https?:)\\/\\//, \"\");\r\n extractedUri = extractedUri.split(\"/\")[0];\r\n return extractedUri;\r\n }\r\n\r\n /**\r\n * @hidden\r\n * @ignore\r\n *\r\n * Utils function to create the Authentication\r\n * @param {@link account} account object\r\n * @param scopes\r\n * @param silentCall\r\n *\r\n * @returns {string} token type: id_token or access_token\r\n *\r\n */\r\n private getTokenType(accountObject: Account, scopes: string[], silentCall: boolean): string {\r\n\r\n // if account is passed and matches the account object/or set to getAccount() from cache\r\n // if client-id is passed as scope, get id_token else token/id_token_token (in case no session exists)\r\n let tokenType: string;\r\n\r\n // acquireTokenSilent\r\n if (silentCall) {\r\n if (Utils.compareAccounts(accountObject, this.getAccount())) {\r\n tokenType = (scopes.indexOf(this.config.auth.clientId) > -1) ? ResponseTypes.id_token : ResponseTypes.token;\r\n }\r\n else {\r\n tokenType = (scopes.indexOf(this.config.auth.clientId) > -1) ? ResponseTypes.id_token : ResponseTypes.id_token_token;\r\n }\r\n\r\n return tokenType;\r\n }\r\n // all other cases\r\n else {\r\n if (!Utils.compareAccounts(accountObject, this.getAccount())) {\r\n tokenType = ResponseTypes.id_token_token;\r\n }\r\n else {\r\n tokenType = (scopes.indexOf(this.clientId) > -1) ? ResponseTypes.id_token : ResponseTypes.token;\r\n }\r\n\r\n return tokenType;\r\n }\r\n\r\n }\r\n\r\n /**\r\n * @hidden\r\n * @ignore\r\n *\r\n * Sets the cachekeys for and stores the account information in cache\r\n * @param account\r\n * @param state\r\n * @hidden\r\n */\r\n private setAccountCache(account: Account, state: string) {\r\n\r\n // Cache acquireTokenAccountKey\r\n let accountId = account ? this.getAccountId(account) : Constants.no_account;\r\n\r\n const acquireTokenAccountKey = Storage.generateAcquireTokenAccountKey(accountId, state);\r\n this.cacheStorage.setItem(acquireTokenAccountKey, JSON.stringify(account));\r\n }\r\n\r\n /**\r\n * @hidden\r\n * @ignore\r\n *\r\n * Sets the cacheKey for and stores the authority information in cache\r\n * @param state\r\n * @param authority\r\n * @hidden\r\n */\r\n private setAuthorityCache(state: string, authority: string) {\r\n // Cache authorityKey\r\n const authorityKey = Storage.generateAuthorityKey(state);\r\n this.cacheStorage.setItem(authorityKey, Utils.CanonicalizeUri(authority), this.inCookie);\r\n }\r\n\r\n /**\r\n * Updates account, authority, and nonce in cache\r\n * @param serverAuthenticationRequest\r\n * @param account\r\n * @hidden\r\n * @ignore\r\n */\r\n private updateCacheEntries(serverAuthenticationRequest: ServerRequestParameters, account: Account, loginStartPage?: any) {\r\n // Cache account and authority\r\n if (loginStartPage) {\r\n // Cache the state, nonce, and login request data\r\n this.cacheStorage.setItem(Constants.loginRequest, loginStartPage, this.inCookie);\r\n this.cacheStorage.setItem(Constants.loginError, \"\");\r\n\r\n this.cacheStorage.setItem(Constants.stateLogin, serverAuthenticationRequest.state, this.inCookie);\r\n this.cacheStorage.setItem(Constants.nonceIdToken, serverAuthenticationRequest.nonce, this.inCookie);\r\n\r\n this.cacheStorage.setItem(Constants.msalError, \"\");\r\n this.cacheStorage.setItem(Constants.msalErrorDescription, \"\");\r\n } else {\r\n this.setAccountCache(account, serverAuthenticationRequest.state);\r\n }\r\n // Cache authorityKey\r\n this.setAuthorityCache(serverAuthenticationRequest.state, serverAuthenticationRequest.authority);\r\n\r\n // Cache nonce\r\n this.cacheStorage.setItem(Constants.nonceIdToken, serverAuthenticationRequest.nonce, this.inCookie);\r\n }\r\n\r\n /**\r\n * Returns the unique identifier for the logged in account\r\n * @param account\r\n * @hidden\r\n * @ignore\r\n */\r\n private getAccountId(account: Account): any {\r\n //return `${account.accountIdentifier}` + Constants.resourceDelimiter + `${account.homeAccountIdentifier}`;\r\n let accountId: string;\r\n if (!Utils.isEmpty(account.homeAccountIdentifier)) {\r\n accountId = account.homeAccountIdentifier;\r\n }\r\n else {\r\n accountId = Constants.no_account;\r\n }\r\n\r\n return accountId;\r\n }\r\n\r\n /**\r\n * @hidden\r\n * @ignore\r\n *\r\n * Construct 'tokenRequest' from the available data in adalIdToken\r\n * @param extraQueryParameters\r\n * @hidden\r\n */\r\n private buildIDTokenRequest(request: AuthenticationParameters): AuthenticationParameters {\r\n\r\n let tokenRequest: AuthenticationParameters = {\r\n scopes: [this.clientId],\r\n authority: this.authority,\r\n account: this.getAccount(),\r\n extraQueryParameters: request.extraQueryParameters\r\n };\r\n\r\n return tokenRequest;\r\n }\r\n\r\n /**\r\n * @hidden\r\n * @ignore\r\n *\r\n * Utility to populate QueryParameters and ExtraQueryParameters to ServerRequestParamerers\r\n * @param request\r\n * @param serverAuthenticationRequest\r\n */\r\n private populateQueryParams(account: Account, request: AuthenticationParameters, serverAuthenticationRequest: ServerRequestParameters, adalIdTokenObject?: any): ServerRequestParameters {\r\n\r\n let queryParameters: QPDict = {};\r\n\r\n if (request) {\r\n // add the prompt parameter to serverRequestParameters if passed\r\n if (request.prompt) {\r\n this.validatePromptParameter(request.prompt);\r\n serverAuthenticationRequest.promptValue = request.prompt;\r\n }\r\n\r\n // Add claims challenge to serverRequestParameters if passed\r\n if (request.claimsRequest) {\r\n validateClaimsRequest(request);\r\n serverAuthenticationRequest.claimsValue = request.claimsRequest;\r\n }\r\n\r\n // if the developer provides one of these, give preference to developer choice\r\n if (Utils.isSSOParam(request)) {\r\n queryParameters = Utils.constructUnifiedCacheQueryParameter(request, null);\r\n }\r\n }\r\n\r\n if (adalIdTokenObject) {\r\n queryParameters = Utils.constructUnifiedCacheQueryParameter(null, adalIdTokenObject);\r\n }\r\n\r\n // adds sid/login_hint if not populated; populates domain_req, login_req and domain_hint\r\n this.logger.verbose(\"Calling addHint parameters\");\r\n queryParameters = this.addHintParameters(account, queryParameters, serverAuthenticationRequest);\r\n\r\n // sanity check for developer passed extraQueryParameters\r\n let eQParams: QPDict;\r\n if (request) {\r\n eQParams = this.sanitizeEQParams(request);\r\n }\r\n\r\n // Populate the extraQueryParameters to be sent to the server\r\n serverAuthenticationRequest.queryParameters = Utils.generateQueryParametersString(queryParameters);\r\n serverAuthenticationRequest.extraQueryParameters = Utils.generateQueryParametersString(eQParams);\r\n\r\n return serverAuthenticationRequest;\r\n }\r\n\r\n /**\r\n * @hidden\r\n * @ignore\r\n *\r\n * Utility to test if valid prompt value is passed in the request\r\n * @param request\r\n */\r\n private validatePromptParameter (prompt: string) {\r\n if (!([PromptState.LOGIN, PromptState.SELECT_ACCOUNT, PromptState.CONSENT, PromptState.NONE].indexOf(prompt) >= 0)) {\r\n throw ClientConfigurationError.createInvalidPromptError(prompt);\r\n }\r\n }\r\n\r\n /**\r\n * @hidden\r\n * @ignore\r\n\r\n * Removes unnecessary or duplicate query parameters from extraQueryParameters\r\n * @param request\r\n */\r\n private sanitizeEQParams(request: AuthenticationParameters) : QPDict {\r\n let eQParams : QPDict = request.extraQueryParameters;\r\n if (!eQParams) {\r\n return null;\r\n }\r\n if (request.claimsRequest) {\r\n this.logger.warning(\"Removed duplicate claims from extraQueryParameters. Please use either the claimsRequest field OR pass as extraQueryParameter - not both.\");\r\n delete eQParams[Constants.claims];\r\n }\r\n delete eQParams[SSOTypes.SID];\r\n delete eQParams[SSOTypes.LOGIN_HINT];\r\n return eQParams;\r\n }\r\n\r\n //#endregion\r\n}\r\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport * as msal from \"msal\";\nimport { AccessToken, TokenCredential, GetTokenOptions } from \"@azure/core-http\";\nimport { IdentityClient } from \"../client/identityClient\";\nimport { BrowserLoginStyle, InteractiveBrowserCredentialOptions } from \"./interactiveBrowserCredentialOptions\";\n\n/**\n * Enables authentication to Azure Active Directory inside of the web browser\n * using the interactive login flow, either via browser redirects or a popup\n * window.\n */\nexport class InteractiveBrowserCredential implements TokenCredential {\n private loginStyle: BrowserLoginStyle;\n private msalConfig: msal.Configuration;\n private msalObject: msal.UserAgentApplication;\n\n /**\n * Creates an instance of the InteractiveBrowserCredential with the\n * details needed to authenticate against Azure Active Directory with\n * a user identity.\n *\n * @param tenantId The Azure Active Directory tenant (directory) ID.\n * @param clientId The client (application) ID of an App Registration in the tenant.\n * @param options Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantId: string,\n clientId: string,\n options?: InteractiveBrowserCredentialOptions\n ) {\n options = { ...IdentityClient.getDefaultOptions(), ...options };\n\n this.loginStyle = options.loginStyle || \"popup\";\n if ([\"redirect\", \"popup\"].indexOf(this.loginStyle) === -1) {\n throw new Error(`Invalid loginStyle: ${options.loginStyle}`);\n }\n\n this.msalConfig = {\n auth: {\n clientId: clientId,\n authority: `${options.authorityHost}/${tenantId}`,\n ...options.redirectUri && { redirectUri: options.redirectUri},\n ...options.postLogoutRedirectUri && { redirectUri: options.postLogoutRedirectUri }\n },\n cache: {\n cacheLocation: \"localStorage\",\n storeAuthStateInCookie: true\n }\n };\n\n this.msalObject = new msal.UserAgentApplication(this.msalConfig);\n }\n\n private login(): Promise<msal.AuthResponse> {\n switch (this.loginStyle) {\n case \"redirect\": {\n const loginPromise = new Promise<msal.AuthResponse>((resolve, reject) => {\n this.msalObject.handleRedirectCallback(resolve, reject);\n });\n this.msalObject.loginRedirect();\n return loginPromise;\n }\n case \"popup\":\n return this.msalObject.loginPopup();\n }\n }\n\n private async acquireToken(authParams: msal.AuthenticationParameters): Promise<msal.AuthResponse | undefined> {\n let authResponse: msal.AuthResponse | undefined;\n try {\n authResponse = await this.msalObject.acquireTokenSilent(authParams);\n } catch (err) {\n if (err instanceof msal.AuthError) {\n switch (err.errorCode) {\n case \"consent_required\":\n case \"interaction_required\":\n case \"login_required\":\n break;\n default:\n throw err;\n }\n }\n }\n\n let authPromise: Promise<msal.AuthResponse> | undefined;\n if (authResponse === undefined) {\n switch (this.loginStyle) {\n case \"redirect\":\n authPromise = new Promise((resolve, reject) => {\n this.msalObject.handleRedirectCallback(resolve, reject);\n });\n this.msalObject.acquireTokenRedirect(authParams);\n break;\n case \"popup\":\n authPromise = this.msalObject.acquireTokenPopup(authParams);\n break;\n }\n\n authResponse = authPromise && await authPromise;\n }\n\n return authResponse;\n }\n\n /**\n *\n * @param scopes The list of scopes for which the token will have access.\n * @param options The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n async getToken(\n scopes: string | string[],\n options?: GetTokenOptions // eslint-disable-line @typescript-eslint/no-unused-vars\n ): Promise<AccessToken | null> {\n if (!this.msalObject.getAccount()) {\n await this.login();\n }\n\n const authResponse = await this.acquireToken({\n scopes: Array.isArray(scopes) ? scopes : scopes.split(',')\n });\n\n if (authResponse) {\n return {\n token: authResponse.accessToken,\n expiresOnTimestamp: authResponse.expiresOn.getTime()\n };\n } else {\n return null;\n }\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\nimport { TokenCredential, GetTokenOptions, AccessToken } from \"@azure/core-http\";\nimport { IdentityClientOptions } from \"../client/identityClient\";\n\nconst BrowserNotSupportedError = new Error(\"DeviceCodeCredential is not supported in the browser.\");\n\nexport class DeviceCodeCredential implements TokenCredential {\n constructor(\n tenantId: string,\n clientId: string,\n userPromptCallback: (details: any) => void,\n options?: IdentityClientOptions\n ) {\n throw BrowserNotSupportedError;\n }\n\n public getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n throw BrowserNotSupportedError;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport qs from \"qs\";\nimport { TokenCredential, GetTokenOptions, AccessToken } from \"@azure/core-http\";\nimport { IdentityClientOptions, IdentityClient } from \"../client/identityClient\";\n\n/**\n * Enables authentication to Azure Active Directory with a user's\n * username and password. This credential requires a high degree of\n * trust so you should only use it when other, more secure credential\n * types can't be used.\n */\nexport class UsernamePasswordCredential implements TokenCredential {\n private identityClient: IdentityClient;\n private tenantId: string;\n private clientId: string;\n private username: string;\n private password: string;\n\n /**\n * Creates an instance of the UsernamePasswordCredential with the details\n * needed to authenticate against Azure Active Directory with a username\n * and password.\n *\n * @param tenantIdOrName The Azure Active Directory tenant (directory) ID or name.\n * @param clientId The client (application) ID of an App Registration in the tenant.\n * @param username The user account's e-mail address (user name).\n * @param password The user account's account password\n * @param options Options for configuring the client which makes the authentication request.\n */\n constructor(\n tenantIdOrName: string,\n clientId: string,\n username: string,\n password: string,\n options?: IdentityClientOptions\n ) {\n this.identityClient = new IdentityClient(options);\n this.tenantId = tenantIdOrName;\n this.clientId = clientId;\n this.username = username;\n this.password = password;\n }\n\n /**\n * Authenticates with Azure Active Directory and returns an {@link AccessToken} if\n * successful. If authentication cannot be performed at this time, this method may\n * return null. If an error occurs during authentication, an {@link AuthenticationError}\n * containing failure details will be thrown.\n *\n * @param scopes The list of scopes for which the token will have access.\n * @param options The options used to configure any requests this\n * TokenCredential implementation might make.\n */\n public async getToken(\n scopes: string | string[],\n options?: GetTokenOptions\n ): Promise<AccessToken | null> {\n const webResource = this.identityClient.createWebResource({\n url: `${this.identityClient.authorityHost}/${this.tenantId}/oauth2/v2.0/token`,\n method: \"POST\",\n disableJsonStringifyOnBody: true,\n deserializationMapper: undefined,\n body: qs.stringify({\n response_type: \"token\",\n grant_type: \"password\",\n client_id: this.clientId,\n username: this.username,\n password: this.password,\n scope: typeof scopes === \"string\" ? scopes : scopes.join(\" \")\n }),\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/x-www-form-urlencoded\"\n },\n abortSignal: options && options.abortSignal\n });\n\n const tokenResponse = await this.identityClient.sendTokenRequest(webResource);\n return (tokenResponse && tokenResponse.accessToken) || null;\n }\n}\n","// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\nimport { TokenCredential } from \"@azure/core-http\";\nimport { DefaultAzureCredential } from \"./credentials/defaultAzureCredential\";\n\nexport { ChainedTokenCredential } from \"./credentials/chainedTokenCredential\";\nexport { IdentityClientOptions } from \"./client/identityClient\";\nexport { EnvironmentCredential } from \"./credentials/environmentCredential\";\nexport { ClientSecretCredential } from \"./credentials/clientSecretCredential\";\nexport { ClientCertificateCredential } from \"./credentials/clientCertificateCredential\";\nexport { InteractiveBrowserCredential } from \"./credentials/interactiveBrowserCredential\";\nexport { InteractiveBrowserCredentialOptions, BrowserLoginStyle } from \"./credentials/interactiveBrowserCredentialOptions\";\nexport { ManagedIdentityCredential } from \"./credentials/managedIdentityCredential\";\nexport { DeviceCodeCredential } from \"./credentials/deviceCodeCredential\";\nexport { DefaultAzureCredential } from \"./credentials/defaultAzureCredential\";\nexport { UsernamePasswordCredential } from \"./credentials/usernamePasswordCredential\";\nexport { AuthenticationError, AggregateAuthenticationError } from \"./client/errors\";\n\nexport { TokenCredential, GetTokenOptions, AccessToken } from \"@azure/core-http\";\n\nexport function getDefaultAzureCredential(): TokenCredential {\n return new DefaultAzureCredential();\n}\n"],"names":["extendStatics","d","b","Object","setPrototypeOf","__proto__","Array","p","hasOwnProperty","__extends","__","this","constructor","prototype","create","__assign","assign","t","s","i","n","arguments","length","call","apply","__decorate","decorators","target","key","desc","c","r","getOwnPropertyDescriptor","Reflect","decorate","defineProperty","__awaiter","thisArg","_arguments","P","generator","Promise","resolve","reject","fulfilled","value","step","next","e","rejected","result","done","then","__generator","body","f","y","g","_","label","sent","trys","ops","verb","throw","return","Symbol","iterator","v","op","TypeError","pop","push","isErrorResponse","errorResponse","error","error_description","AuthenticationError","Error","[object Object]","statusCode","errorBody","JSON","parse","super","stringify","name","AggregateAuthenticationError","errors","ChainedTokenCredential","sources","_sources","scopes","options","token","getToken","err","BrowserNotSupportedError","EnvironmentCredential","ManagedIdentityCredential","clientId","DefaultAzureCredential","identityClientOptions","undefined","has","isArray","hexTable","array","toString","toUpperCase","compactQueue","queue","item","obj","prop","compacted","j","arrayToObject","source","plainObjects","merge","allowPrototypes","concat","mergeTarget","forEach","targetItem","keys","reduce","acc","decode","str","decoder","charset","strWithoutPlus","replace","unescape","decodeURIComponent","encode","defaultEncoder","string","String","escape","$0","parseInt","slice","out","charCodeAt","charAt","compact","o","refs","val","indexOf","isRegExp","isBuffer","combine","a","percentTwenties","default","formatters","RFC1738","RFC3986","arrayPrefixGenerators","brackets","prefix","comma","indices","repeat","pushToArray","arr","valueOrArray","toISO","Date","toISOString","defaults","addQueryPrefix","allowDots","charsetSentinel","delimiter","encoder","utils","encodeValuesOnly","formatter","formats","serializeDate","date","skipNulls","strictNullHandling","object","generateArrayPrefix","filter","sort","join","objKeys","values","normalizeStringifyOptions","opts","format","arrayFormat","joined","arrayLimit","depth","ignoreQueryPrefix","interpretNumericEntities","parameterLimit","parseArrays","numberStr","fromCharCode","isoSentinel","parseValues","cleanStr","limit","Infinity","parts","split","skipIndex","part","bracketEqualsPos","pos","parseObject","chain","leaf","root","cleanRoot","index","isNaN","0","parseKeys","givenKey","child","segment","exec","parent","normalizeParseOptions","tempObj","newObj","getHeaderKey","headerName","toLowerCase","rawHeaders","_headersMap","set","HttpHeaders","headerValue","header","contains","headerKey","headers","headerNames","headersArray","headerValues","toJson","encodeByteArray","btoa","decodeString","byteString","atob","Uint8Array","getRandomValues","crypto","bind","window","msCrypto","rnds8","module","rnds","Math","random","byteToHex","substr","bytesToUuid","buf","offset","bth","v4","rng","ii","Constants","coreHttpVersion","HTTP","HTTPS","HTTP_PROXY","HTTPS_PROXY","HttpConstants","HttpVerbs","PUT","GET","DELETE","POST","MERGE","HEAD","PATCH","StatusCodes","TooManyRequests","HeaderConstants","AUTHORIZATION","AUTHORIZATION_SCHEME","RETRY_AFTER","USER_AGENT","isNode","process","version","versions","node","stripResponse","response","strippedResponse","bodyAsText","status","stripRequest","request","strippedRequest","clone","remove","isValidUuid","uuid","RegExp","test","generateUuid","uuidv4","delay","setTimeout","prepareXMLRootList","elementName","validateISODuration","isDuration","replaceAll","searchValue","replaceValue","modelMappers","isXML","Serializer","mapper","objectName","failValidation","constraintName","constraintValue","constraints","_a","ExclusiveMaximum","ExclusiveMinimum","InclusiveMaximum","InclusiveMinimum","MaxItems","MaxLength","MinItems","MinLength","MultipleOf","Pattern","UniqueItems","match","some","ar","payload","mapperType","type","serializedName","defaultValue","isConstant","required","nullable","validateConstraints","serializeBasicTypes","serializeEnumType","allowedValues","serializeDateTypes","serializeByteArrayType","serializeBase64UrlType","serializeSequenceType","serializeDictionaryType","serializeCompositeType","responseBody","xmlIsWrapped","deserializeCompositeType","parseFloat","unixTimeToDate","base64.decodeString","base64UrlToByteArray","deserializeSequenceType","deserializeDictionaryType","trimEnd","ch","len","bufferToBase64Url","buffer","base64.encodeByteArray","valueOf","splitSerializeName","classes","partialclass","subwords_1","_i","dateToUnixTime","floor","getTime","typeName","utils.isValidUuid","objectType","ArrayBuffer","isView","Blob","substring","toUTCString","utils.isDuration","serializer","elementType","element","tempArray","serialize","valueType","tempDictionary","resolveModelProperties","modelProps","modelProperties","className","modelMapper","getPolymorphicDiscriminatorRecursively","getPolymorphicMapper","_b","propertyMapper","readOnly","propName","parentObject","xmlName","xmlElementName","paths","paths_1","_c","pathName","propertyObjectName","toSerialize","polymorphicDiscriminator","clientName","serializedValue","xmlIsAttribute","$","additionalPropertiesMapper","additionalProperties","propNames","clientPropName","every","pn","isSpecialXmlProperty","propertyName","includes","instance","handledPropertyNames","headerCollectionPrefix","dictionary","startsWith","deserialize","unwrappedProperty","propertyInstance","res","paths_2","_d","isAdditionalProperty","responsePropName","_f","_e","polymorphicPropertyName","discriminatorName","discriminatorValue","uberParent","indexDiscriminator","polymorphicMapper","discriminators","getPolymorphicDiscriminatorSafely","strEnum","o_1","MapperType","url","method","query","streamResponseBody","withCredentials","abortSignal","timeout","onUploadProgress","onDownloadProgress","proxySettings","formData","WebResource","pathTemplate","validMethods","pathTemplate_1","pathParameters_1","baseUrl","url_1","endsWith","segments","pathParamName","pathParam","encodeURIComponent","skipUrlEncoding","queryParameters","queryParams","queryParamName","queryParam","get","disableClientRequestId","bodyIsStream","serializationMapper","mappers","disableJsonStringifyOnBody","operationSpec","shouldDeserialize","operationResponseGetter","message","code","_super","_this","RestError","tslib_1.__extends","XhrHttpClient","xhr","XMLHttpRequest","listener_1","abort","addEventListener","readyState","DONE","removeEventListener","addProgressListener","upload","requestForm_1","FormData","appendFormValue","append","formKey","formValue","contentType","open","setRequestHeader","responseType","send","HEADERS_RECEIVED","blobBody","rejectOnTerminalEvent","parseHeaders","responseText","HttpPipelineLogLevel","listener","rawEvent","loadedBytes","loaded","responseHeaders","headerLines_1","getAllResponseHeaders","trim","line","REQUEST_SEND_ERROR","REQUEST_ABORTED_ERROR","isTokenCredential","credential","signRequest","getPathStringFromParameter","parameter","getPathStringFromParameterPath","parameterPath","isStreamOperation","responses","operationResponse","bodyMapper","Stream","parser","DOMParser","parseXML","dom","parseFromString","throwIfError","domToObject","childNodes","errorNS","getElementsByTagName","namespaceURI","ignored","parserErrors","getElementsByTagNameNS","innerHTML","isElement","attributes","asElementWithAttributes","hasAttributes","childNodeCount","firstChildNode","onlyChildTextValue","nodeType","Node","TEXT_NODE","nodeValue","elementWithAttributes","attr","nodeName","childObject","doc","document","implementation","createDocument","XMLSerializer","stringifyXML","buildNode","rootName","serializeToString","buildAttributes","attrs","createAttribute","elem","createElement","textContent","obj_1","setNamedItem","_h","_g","appendChild","_nextPolicy","_options","BaseRequestPolicy","logLevel","shouldLog","log","_logger","RequestPolicyOptions","OFF","minimumLogLevel","deserializationPolicy","deserializationContentTypes","nextPolicy","DeserializationPolicy","defaultJsonContentTypes","defaultXmlContentTypes","jsonContentTypes","json","xmlContentTypes","xml","sendRequest","deserializeResponseBody","getOperationResponse","parsedResponse","shouldDeserializeResponse","expectedStatusCodes","hasNoExpectedStatusCodes","responseSpec","valueToDeserialize","parsedBody","Sequence","restError","utils.stripRequest","utils.stripResponse","httpMethod","headersMapper","parsedHeaders","defaultResponseSpec","initialErrorMessage","parsedErrorResponse","defaultResponseBodyMapper","internalError","defaultError","errorHandler","msg","errCode","PARSE_ERROR","text_1","contentComponents","map","component","catch","exponentialRetryPolicy","retryCount","retryInterval","minRetryInterval","maxRetryInterval","ExponentialRetryPolicy","DEFAULT_CLIENT_RETRY_INTERVAL","DEFAULT_CLIENT_RETRY_COUNT","DEFAULT_CLIENT_MAX_RETRY_INTERVAL","DEFAULT_CLIENT_MIN_RETRY_INTERVAL","isNumber","retry","shouldRetry","policy","retryData","updateRetryData","innerError","incrementDelta","pow","min","requestError","isAborted","aborted","utils.delay","generateClientRequestIdPolicy","requestIdHeaderName","GenerateClientRequestIdPolicy","_requestIdHeaderName","utils.generateUuid","getDefaultUserAgentKey","getPlatformSpecificData","navigator","oscpu","platform","getRuntimeInfo","getUserAgentString","telemetryInfo","keySeparator","valueSeparator","info","getDefaultUserAgentHeaderName","getDefaultUserAgentValue","runtimeInfo","platformSpecificData","userAgentPolicy","userAgentData","UserAgentPolicy","addUserAgentHeader","URLQuery","_rawQuery","parameterName","parameterValue","newValue","parameterStrings","parameterValue_1","parameterValueElement","text","currentState","currentCharacter","URLBuilder","scheme","_scheme","host","_host","port","_port","path","_path","currentPath","getPath","_query","queryParameterName","queryParameterValue","startState","tokenizer","URLTokenizer","current","tokenPath","any","setScheme","getScheme","setHost","getHost","setPort","getPort","setPath","setQuery","getQuery","URLToken","isAlphaNumericCharacter","character","characterCode","_text","state","_textLength","_currentState","_currentIndex","_currentToken","hasCurrentCharacter","nextScheme","nextSchemeOrHost","nextHost","nextPort","nextPath","nextQuery","readRemaining","getCurrentCharacter","nextCharacter","peekCharacters","charactersToPeek","endIndex","readWhile","condition","readWhileLetterOrDigit","readUntilCharacter","terminatingCharacters","schemeOrHost","redirectPolicy","maximumRetries","RedirectPolicy","maxRetries","handleRedirect","currentRetries","locationHeader","builder","rpRegistrationPolicy","retryTimeout","RPRegistrationPolicy","_retryTimeout","registerIfNeeded","rpName","checkRPNotRegisteredError","urlPrefix","extractSubscriptionUrl","registerRP","registrationStatus","getRequestEssentials","originalRequest","reuseUrlToo","reqOptions","matchRes","provider","postUrl","getUrl","getRegistrationStatus","registrationState","TokenRefreshBufferMs","tokenRefreshBufferMs","ExpiringAccessTokenCache","accessToken","cachedToken","now","expiresOnTimestamp","bearerTokenAuthenticationPolicy","tokenCache","BearerTokenAuthenticationPolicy","webResource","getCachedToken","setCachedToken","systemErrorRetryPolicy","SystemErrorRetryPolicy","QueryCollectionFormat","proxyNotSupportedInBrowser","getDefaultProxySettings","_proxyUrl","proxyPolicy","_proxySettings","ProxyPolicy","_request","throttlingRetryPolicy","ThrottlingRetryPolicy","_handleResponse","_defaultResponseHandler","httpRequest","httpResponse","retryAfterHeader","delayInMs","parseRetryAfterHeader","retryAfterInSeconds","Number","parseDateRetryAfterHeader","diff","credentials","requestPolicyFactories","bearerTokenPolicyFactory","serviceClient","_withCredentials","_httpClient","httpClient","DefaultHttpClient","_requestPolicyOptions","httpPipelineLogger","authPolicyFactory","baseUri","createDefaultRequestPolicyFactories","newRequestPolicyFactories","_requestPolicyFactories","ServiceClient","validateRequestProperties","prepare","httpPipeline","operationArguments","callback","requestUrl","appendPath","urlParameters","urlParameter","urlParameterValue","getOperationArgumentValueFromParameter","skipEncoding","queryParameter","collectionFormat","Multi","setQueryParameter","requestContentType","headerParameters","headerParameter","customHeaders","customHeaderName","serializeRequestBody","flattenResponse","cb","_response","requestBody","requestBodyParameterPathString","isStream","utils.prepareXMLRootList","formDataParameters","formDataParameter","formDataParameterValue","formDataParameterPropertyName","getValueOrFunctionResult","defaultValueCreator","factories","generateClientRequestIdHeader","clientRequestIdHeaderName","userAgentHeaderName","userAgentHeaderValue","userAgent","rpRegistrationRetryTimeout","noRetryPolicy","getOperationArgumentValueFromParameterPath","parameterMapper","propertySearchResult","getPropertyFromParameterPath","propertyFound","useDefaultValue","propertyValue","parameterPathString","propertyPath","propertyPathString","parameterPathPart","addOperationResponse","readableStreamBody","modelProperties_1","isPageableResponse","k","arrayResponse","DefaultAuthorityHost","IdentityClient","getDefaultOptions","authorityHost","requestOptions","expiresOnParser","expires_in","access_token","refreshToken","refresh_token","tenantId","clientSecret","refreshParams","grant_type","client_id","scope","client_secret","createWebResource","deserializationMapper","qs","Accept","Content-Type","sendTokenRequest","ClientSecretCredential","identityClient","response_type","tokenResponse","ClientCertificateCredential","certificatePath","_popUpWidth","width","_popUpHeight","height","CacheKeys","AUTHORITY","ACQUIRE_TOKEN_ACCOUNT","SSOTypes","ACCOUNT","SID","LOGIN_HINT","ID_TOKEN","DOMAIN_HINT","ORGANIZATIONS","CONSUMERS","ACCOUNT_ID","HOMEACCOUNT_ID","LOGIN_REQ","DOMAIN_REQ","PromptState","LOGIN","SELECT_ACCOUNT","CONSENT","NONE","Library","AuthErrorMessage","unexpectedError","errorCode","errorMessage","AuthError","errDesc","ClientAuthErrorMessage","multipleMatchingTokens","multipleCacheAuthorities","endpointResolutionError","popUpWindowError","tokenRenewalError","invalidIdToken","invalidStateError","nonceMismatchError","loginProgressError","acquireTokenProgressError","userCancelledError","callbackError","userLoginRequiredError","userDoesNotExistError","clientInfoDecodingError","clientInfoNotPopulatedError","nullOrEmptyIdToken","idTokenNotParsed","tokenEncodingError","ClientAuthError","errDetail","Utils","isEmpty","idToken","invalidState","actualState","invalidNonce","actualNonce","errorDesc","caughtError","invalidRawTokenString","caughtParsingError","incorrectlyEncodedToken","global","factory","self","_Base64","Base64","exports","eval","b64chars","b64tab","bin","l","cb_utob","cc","re_utob","utob","u","cb_encode","ccc","padlen","ord","_encode","from","urisafe","m0","encodeURI","re_btou","cb_btou","cccc","btou","cb_decode","chars","_atob","_decode","noConflict","VERSION","fromBase64","toBase64","__buffer__","noEnum","enumerable","writable","configurable","extendString","a1","a2","homeAccountIdentifier","num","hex","cryptoObj","decimalToHex","guidHolder","guidResponse","expires","round","jwtToken","matches","JWSPayload","JWSSig","encodedIdToken","decodedToken","decodeJwt","base64IdToken","base64Decoded","base64DecodeStringUrlSafe","input","chr1","chr2","chr3","enc1","enc2","enc3","enc4","keyStr","output","utf8Encode","utftext","codes","createTokenEncodingError","h1","h2","h3","h4","bits","c1","c2","c3","decoded","pl","search","cachedScopes","convertToLowerCase","location","href","urlObject","GetUrlComponents","pathArray","PathSegments","common","constructAuthorityUriFromObject","CanonicalizeUri","Protocol","HostNameAndPort","regEx","urlComponents","AbsolutePath","pathSegments","suffix","regex","idTokenObject","ssoType","ssoData","serverReqParam","account","sid","userName","loginHint","upn","addSSOParameter","ssoParam","homeAccountId","uid","utid","consumersUtid","paramsString","originalResponse","objectId","uniqueId","subject","authority","base64EncodeStringUrlSafe","expiresIn","redirectUri","authorityInstance","nonce","createNewGuid","correlationId","xClientSku","xClientVer","getLibraryVersion","ServerRequestParameters","CanonicalAuthority","createNavigationUrlString","authEndpoint","AuthorizationEndpoint","translateclientIdUsedInScope","parseScope","promptValue","claimsValue","extraQueryParameters","clientIdIndex","splice","scopeList","rawClientInfo","decodedClientInfo","clientInfo","createClientInfoDecodingError","ClientInfo","_uid","_utid","rawIdToken","createIdTokenNullOrEmptyError","decodedIdToken","extractIdToken","issuer","preferredName","expiration","homeObjectId","createIdTokenParsingError","ClientConfigurationErrorMessage","configurationNotSet","invalidCacheLocation","noStorageSupported","noRedirectCallbacksSet","invalidCallbackObject","scopesRequired","emptyScopes","nonArrayScopes","clientScope","invalidPrompt","invalidAuthorityType","authorityUriInsecure","authorityUriInvalidPath","unsupportedAuthorityValidation","b2cAuthorityUriInvalidPath","claimsRequestParsingError","ClientConfigurationError","givenCacheLocation","cacheLocationLocal","cacheLocationSession","callbackObject","scopesValue","claimsRequestParseError","cacheLocation","Storage","localStorageSupported","sessionStorageSupported","createNoStorageSupportedError","enableCookieStorage","setItem","setItemCookie","getItemCookie","getItem","removeItem","clear","accessTokenCacheItem","results","storage","AccessTokenCacheItem","splitKey","resourceDelimiter","state_1","tokenRenewalInProgress","renewStatus","stateLogin","stateAcquireToken","clearCookie","stateValue","tokenRenewStatusInProgress","msal","removeAcquireTokenEntries","cName","cValue","cookieStr","getCookieExpirationTime","cookie","ca","cookieLifeDays","today","nonceIdToken","loginRequest","accountId","accountIdentifier","environment","Account","XhrClient","enableCaching","onload","ev","handleError","jsonResponse","onerror","AuthorityType","validateAuthority","IsValidationEnabled","validateAsUri","Authority","CanonicalAuthorityUrlComponents","validateResolved","tenantDiscoveryResponse","Tenant","EndSessionEndpoint","Issuer","canonicalAuthority","canonicalAuthorityUrlComponents","components","openIdConfigurationEndpoint","sendRequestAsync","authorization_endpoint","end_session_endpoint","GetOpenIdConfigurationEndpointAsync","openIdConfigurationEndpointResponse","DiscoverEndpoints","AadAuthority","AadInstanceDiscoveryEndpoint","Aad","resultPromise","DefaultOpenIdConfigurationEndpoint","IsInTrustedHostList","AadInstanceDiscoveryEndpointUrl","tenant_discovery_endpoint","TrustedHostList","login.windows.net","login.chinacloudapi.cn","login.cloudgovapi.us","login.microsoftonline.com","login.microsoftonline.de","login.microsoftonline.us","B2cAuthority","B2C","AuthorityFactory","authorityUrl","Adfs","DetectAuthorityFromUrl","LogLevel","localCallback","Info","level","piiLoggingEnabled","Logger","logMessage","containsPii","timestamp","executeCallback","Warning","Verbose","FRAME_TIMEOUT","OFFSET","NAVIGATE_FRAME_WAIT","DEFAULT_AUTH_OPTIONS","getDefaultRedirectUri","postLogoutRedirectUri","navigateToLoginRequestUrl","DEFAULT_CACHE_OPTIONS","storeAuthStateInCookie","DEFAULT_SYSTEM_OPTIONS","logger","loadFrameTimeout","tokenRenewalOffsetSeconds","navigateFrameWait","DEFAULT_FRAMEWORK_OPTIONS","isAngular","unprotectedResources","protectedResourceMap","Map","buildConfiguration","auth","cache","system","framework","validateClaimsRequest","claimsRequest","createClaimsRequestParsingError","ServerErrorMessage","serverUnavailable","unknownServerError","ServerError","InteractionRequiredAuthErrorMessage","loginRequired","interactionRequired","consentRequired","InteractionRequiredAuthError","buildResponseStateOnly","tokenType","expiresOn","accountState","DEFAULT_AUTHORITY","ResponseTypes","id_token","id_token_token","resolveTokenOnlyIfOutOfIframe","propertyKey","descriptor","tokenAcquisitionMethod","args","isInIframe","configuration","config","redirectCallbacksSet","inCookie","loginInProgress","acquireTokenInProgress","cacheStorage","createInvalidCacheLocationConfigError","openedWindows","activeRenewals","renewStates","callbackMappedToRenewStates","promiseMappedToRenewStates","urlHash","hash","isCallback","handleAuthenticationResponse","UserAgentApplication","CreateInstance","authOrTokenCallback","errorReceivedCallback","createInvalidCallbackObjectError","tokenReceivedCallback","warning","authResponseCallback","cachedHash","processCallBack","authErr","createRedirectCallbacksNotSetError","redirectErrorHandler","createLoginInProgressError","appendScopes","validateInputScope","getAccount","isSSOParam","loginRedirectHelper","extractADALIdToken","tokenRequest","buildIDTokenRequest","silentLogin","acquireTokenSilent","redirectSuccessHandler","resolveEndpointsAsync","serverAuthenticationRequest","getRedirectUri","populateQueryParams","loginStartPage","angularLoginRequest","updateCacheEntries","urlNavigate","createNavigateUrl","response_mode_fragment","promptUser","createEndpointResolutionError","createAcquireTokenInProgressError","getAccountState","createUserLoginRequiredError","acquireTokenAuthority","getTokenType","getHash","parameters","errorDescription","loginPopupHelper","popUpWindow","openWindow","loginError","msalError","msalErrorDescription","setAuthorityCache","requestType","login","registerCallback","infoPii","close","renewToken","title","interval","popupWindow","openPopup","popUpWidth","popUpHeight","createPopupWindowError","pollTimer","setInterval","closed","createUserCancelledError","clearInterval","broadcast","popUpWindowLocation","winLeft","screenLeft","screenX","winTop","screenTop","screenY","innerWidth","documentElement","clientWidth","innerHeight","clientHeight","left","top_1","focus","adalIdToken","adalIdTokenObject","verbose","cacheResultResponse","userContainedClaims","renewIdToken","errorString","frameName","expectedState","loadFrame","createTokenRenewalTimeoutError","tokenRenewStatusCancelled","frameCheck","frameHandle","addHiddenIFrame","src","iframeId","adalFrame","getElementById","ifr","setAttribute","style","visibility","position","border","insertAdjacentHTML","frames","accountObj","qParams","serverReqParams","createUnexpectedError","clearCache","logout","getPostLogoutRedirectUri","accessTokenItems","getAllAccessTokens","resetCacheItems","stateInfo","parentCallback","getResponseState","saveTokenFromHash","createErrorInCallbackFunction","isPopup","isWindowOpenerMsal","opener","tokenResponseCallback","parentIsMsal","stateResponse","deserializeHash","unknown","stateMatch","silentAuthenticationState","statesInParentContext","tokenCacheItems","filteredItems","cacheItem","containsScope","createMultipleMatchingTokensInCacheError","authorityList","getUniqueAuthority","createMultipleAuthoritiesInCacheError","expired","IdToken","aState","setResponseIdToken","accessTokenCacheItems","property","flags","urlRemoveQueryStringParameter","prompt","prompt_none","loadIframeTimeout","accessTokenResponse","clientObj","consentedScopes","isIntersectingScopes","accessTokenKey","AccessTokenKey","accessTokenValue","AccessTokenValue","exp","hashParams","authorityKey","acquireTokenAccountKey","generateAuthorityKey","no_account","generateAcquireTokenAccountKey","isInteractionRequired","sessionState","msalSessionState","idTokenKey","authorityKey_1","replaceTenantPath","createClientInfoNotPopulatedError","createAccount","accountKey","acquireTokenAccountKey_noaccount","cachedAccount","acquireTokenAccount","saveAccessToken","compareAccounts","createNonceMismatchError","msalClientInfo","createInvalidIdTokenError","createInvalidStateError","tokenRenewStatusCompleted","splitIndex","accounts","getUniqueAccounts","uniqueAccounts","createScopesNonArrayError","createEmptyScopesArrayError","createClientIdSingleScopeError","createScopesRequiredError","extraScopesToConsent","eventName","data","evt","CustomEvent","detail","dispatchEvent","accountObject","newAuthority","endpoint","size","getHostFromUri","createNoSetConfigurationError","uri","extractedUri","silentCall","getAccountId","setAccountCache","eQParams","validatePromptParameter","constructUnifiedCacheQueryParameter","addHintParameters","sanitizeEQParams","generateQueryParametersString","createInvalidPromptError","claims","tslib_1.__decorate","InteractiveBrowserCredential","loginStyle","msalConfig","msalObject","msal.UserAgentApplication","loginPromise","handleRedirectCallback","loginRedirect","loginPopup","authParams","authResponse","authPromise","msal.AuthError","acquireTokenRedirect","acquireTokenPopup","acquireToken","DeviceCodeCredential","userPromptCallback","UsernamePasswordCredential","tenantIdOrName","username","password","getDefaultAzureCredential"],"mappings":"uOAgBA,IAAIA,cAAgB,SAASC,EAAGC,GAI5B,OAHAF,cAAgBG,OAAOC,gBAClB,CAAEC,UAAW,cAAgBC,OAAS,SAAUL,EAAGC,GAAKD,EAAEI,UAAYH,IACvE,SAAUD,EAAGC,GAAK,IAAK,IAAIK,KAAKL,EAAOA,EAAEM,eAAeD,KAAIN,EAAEM,GAAKL,EAAEK,MACpDN,EAAGC,IAGrB,SAASO,UAAUR,EAAGC,GAEzB,SAASQ,IAAOC,KAAKC,YAAcX,EADnCD,cAAcC,EAAGC,GAEjBD,EAAEY,UAAkB,OAANX,EAAaC,OAAOW,OAAOZ,IAAMQ,EAAGG,UAAYX,EAAEW,UAAW,IAAIH,GAG5E,IAAIK,SAAW,WAQlB,OAPAA,SAAWZ,OAAOa,QAAU,SAAkBC,GAC1C,IAAK,IAAIC,EAAGC,EAAI,EAAGC,EAAIC,UAAUC,OAAQH,EAAIC,EAAGD,IAE5C,IAAK,IAAIZ,KADTW,EAAIG,UAAUF,GACOhB,OAAOU,UAAUL,eAAee,KAAKL,EAAGX,KAAIU,EAAEV,GAAKW,EAAEX,IAE9E,OAAOU,IAEKO,MAAMb,KAAMU,YAezB,SAASI,WAAWC,EAAYC,EAAQC,EAAKC,GAChD,IAA2H5B,EAAvH6B,EAAIT,UAAUC,OAAQS,EAAID,EAAI,EAAIH,EAAkB,OAATE,EAAgBA,EAAO1B,OAAO6B,yBAAyBL,EAAQC,GAAOC,EACrH,GAAuB,iBAAZI,SAAoD,mBAArBA,QAAQC,SAAyBH,EAAIE,QAAQC,SAASR,EAAYC,EAAQC,EAAKC,QACpH,IAAK,IAAIV,EAAIO,EAAWJ,OAAS,EAAGH,GAAK,EAAGA,KAASlB,EAAIyB,EAAWP,MAAIY,GAAKD,EAAI,EAAI7B,EAAE8B,GAAKD,EAAI,E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