UNPKG

217 kBJavaScriptView Raw
1/** @license ms-rest-js
2 * Copyright (c) Microsoft Corporation. All rights reserved.
3 * Licensed under the MIT License. See License.txt and ThirdPartyNotices.txt in the project root for license information.
4 */
5'use strict';
6
7Object.defineProperty(exports, '__esModule', { value: true });
8
9function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
10
11var uuid = require('uuid');
12var tslib = require('tslib');
13var tough = require('tough-cookie');
14var http = require('http');
15var https = require('https');
16var node_fetch = _interopDefault(require('node-fetch'));
17var FormData = _interopDefault(require('form-data'));
18var stream = require('stream');
19var tunnel = require('tunnel');
20var xml2js = require('xml2js');
21var os = require('os');
22
23// Copyright (c) Microsoft Corporation. All rights reserved.
24// Licensed under the MIT License. See License.txt in the project root for license information.
25/**
26 * A collection of HttpHeaders that can be sent with a HTTP request.
27 */
28function getHeaderKey(headerName) {
29 return headerName.toLowerCase();
30}
31function isHttpHeadersLike(object) {
32 if (!object || typeof object !== "object") {
33 return false;
34 }
35 if (typeof object.rawHeaders === "function" &&
36 typeof object.clone === "function" &&
37 typeof object.get === "function" &&
38 typeof object.set === "function" &&
39 typeof object.contains === "function" &&
40 typeof object.remove === "function" &&
41 typeof object.headersArray === "function" &&
42 typeof object.headerValues === "function" &&
43 typeof object.headerNames === "function" &&
44 typeof object.toJson === "function") {
45 return true;
46 }
47 return false;
48}
49/**
50 * A collection of HTTP header key/value pairs.
51 */
52var HttpHeaders = /** @class */ (function () {
53 function HttpHeaders(rawHeaders) {
54 this._headersMap = {};
55 if (rawHeaders) {
56 for (var headerName in rawHeaders) {
57 this.set(headerName, rawHeaders[headerName]);
58 }
59 }
60 }
61 /**
62 * Set a header in this collection with the provided name and value. The name is
63 * case-insensitive.
64 * @param headerName The name of the header to set. This value is case-insensitive.
65 * @param headerValue The value of the header to set.
66 */
67 HttpHeaders.prototype.set = function (headerName, headerValue) {
68 this._headersMap[getHeaderKey(headerName)] = {
69 name: headerName,
70 value: headerValue.toString(),
71 };
72 };
73 /**
74 * Get the header value for the provided header name, or undefined if no header exists in this
75 * collection with the provided name.
76 * @param headerName The name of the header.
77 */
78 HttpHeaders.prototype.get = function (headerName) {
79 var header = this._headersMap[getHeaderKey(headerName)];
80 return !header ? undefined : header.value;
81 };
82 /**
83 * Get whether or not this header collection contains a header entry for the provided header name.
84 */
85 HttpHeaders.prototype.contains = function (headerName) {
86 return !!this._headersMap[getHeaderKey(headerName)];
87 };
88 /**
89 * Remove the header with the provided headerName. Return whether or not the header existed and
90 * was removed.
91 * @param headerName The name of the header to remove.
92 */
93 HttpHeaders.prototype.remove = function (headerName) {
94 var result = this.contains(headerName);
95 delete this._headersMap[getHeaderKey(headerName)];
96 return result;
97 };
98 /**
99 * Get the headers that are contained this collection as an object.
100 */
101 HttpHeaders.prototype.rawHeaders = function () {
102 var result = {};
103 for (var headerKey in this._headersMap) {
104 var header = this._headersMap[headerKey];
105 result[header.name.toLowerCase()] = header.value;
106 }
107 return result;
108 };
109 /**
110 * Get the headers that are contained in this collection as an array.
111 */
112 HttpHeaders.prototype.headersArray = function () {
113 var headers = [];
114 for (var headerKey in this._headersMap) {
115 headers.push(this._headersMap[headerKey]);
116 }
117 return headers;
118 };
119 /**
120 * Get the header names that are contained in this collection.
121 */
122 HttpHeaders.prototype.headerNames = function () {
123 var headerNames = [];
124 var headers = this.headersArray();
125 for (var i = 0; i < headers.length; ++i) {
126 headerNames.push(headers[i].name);
127 }
128 return headerNames;
129 };
130 /**
131 * Get the header names that are contained in this collection.
132 */
133 HttpHeaders.prototype.headerValues = function () {
134 var headerValues = [];
135 var headers = this.headersArray();
136 for (var i = 0; i < headers.length; ++i) {
137 headerValues.push(headers[i].value);
138 }
139 return headerValues;
140 };
141 /**
142 * Get the JSON object representation of this HTTP header collection.
143 */
144 HttpHeaders.prototype.toJson = function () {
145 return this.rawHeaders();
146 };
147 /**
148 * Get the string representation of this HTTP header collection.
149 */
150 HttpHeaders.prototype.toString = function () {
151 return JSON.stringify(this.toJson());
152 };
153 /**
154 * Create a deep clone/copy of this HttpHeaders collection.
155 */
156 HttpHeaders.prototype.clone = function () {
157 return new HttpHeaders(this.rawHeaders());
158 };
159 return HttpHeaders;
160}());
161
162// Copyright (c) Microsoft Corporation. All rights reserved.
163// Licensed under the MIT License. See License.txt in the project root for license information.
164/**
165 * Encodes a string in base64 format.
166 * @param value the string to encode
167 */
168function encodeString(value) {
169 return Buffer.from(value).toString("base64");
170}
171/**
172 * Encodes a byte array in base64 format.
173 * @param value the Uint8Aray to encode
174 */
175function encodeByteArray(value) {
176 // Buffer.from accepts <ArrayBuffer> | <SharedArrayBuffer>-- the TypeScript definition is off here
177 // https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length
178 var bufferValue = value instanceof Buffer ? value : Buffer.from(value.buffer);
179 return bufferValue.toString("base64");
180}
181/**
182 * Decodes a base64 string into a byte array.
183 * @param value the base64 string to decode
184 */
185function decodeString(value) {
186 return Buffer.from(value, "base64");
187}
188
189// Copyright (c) Microsoft Corporation. All rights reserved.
190// Licensed under the MIT License. See License.txt in the project root for license information.
191var Constants = {
192 /**
193 * The ms-rest version
194 * @const
195 * @type {string}
196 */
197 msRestVersion: "2.6.1",
198 /**
199 * Specifies HTTP.
200 *
201 * @const
202 * @type {string}
203 */
204 HTTP: "http:",
205 /**
206 * Specifies HTTPS.
207 *
208 * @const
209 * @type {string}
210 */
211 HTTPS: "https:",
212 /**
213 * Specifies HTTP Proxy.
214 *
215 * @const
216 * @type {string}
217 */
218 HTTP_PROXY: "HTTP_PROXY",
219 /**
220 * Specifies HTTPS Proxy.
221 *
222 * @const
223 * @type {string}
224 */
225 HTTPS_PROXY: "HTTPS_PROXY",
226 /**
227 * Specifies NO Proxy.
228 */
229 NO_PROXY: "NO_PROXY",
230 /**
231 * Specifies ALL Proxy.
232 */
233 ALL_PROXY: "ALL_PROXY",
234 HttpConstants: {
235 /**
236 * Http Verbs
237 *
238 * @const
239 * @enum {string}
240 */
241 HttpVerbs: {
242 PUT: "PUT",
243 GET: "GET",
244 DELETE: "DELETE",
245 POST: "POST",
246 MERGE: "MERGE",
247 HEAD: "HEAD",
248 PATCH: "PATCH",
249 },
250 StatusCodes: {
251 TooManyRequests: 429,
252 },
253 },
254 /**
255 * Defines constants for use with HTTP headers.
256 */
257 HeaderConstants: {
258 /**
259 * The Authorization header.
260 *
261 * @const
262 * @type {string}
263 */
264 AUTHORIZATION: "authorization",
265 AUTHORIZATION_SCHEME: "Bearer",
266 /**
267 * The Retry-After response-header field can be used with a 503 (Service
268 * Unavailable) or 349 (Too Many Requests) responses to indicate how long
269 * the service is expected to be unavailable to the requesting client.
270 *
271 * @const
272 * @type {string}
273 */
274 RETRY_AFTER: "Retry-After",
275 /**
276 * The UserAgent header.
277 *
278 * @const
279 * @type {string}
280 */
281 USER_AGENT: "User-Agent",
282 },
283};
284
285// Copyright (c) Microsoft Corporation. All rights reserved.
286/**
287 * A constant that indicates whether the environment is node.js or browser based.
288 */
289var isNode = typeof process !== "undefined" &&
290 !!process.version &&
291 !!process.versions &&
292 !!process.versions.node;
293/**
294 * Encodes an URI.
295 *
296 * @param {string} uri The URI to be encoded.
297 * @return {string} The encoded URI.
298 */
299function encodeUri(uri) {
300 return encodeURIComponent(uri)
301 .replace(/!/g, "%21")
302 .replace(/"/g, "%27")
303 .replace(/\(/g, "%28")
304 .replace(/\)/g, "%29")
305 .replace(/\*/g, "%2A");
306}
307/**
308 * Returns a stripped version of the Http Response which only contains body,
309 * headers and the status.
310 *
311 * @param {HttpOperationResponse} response The Http Response
312 *
313 * @return {object} The stripped version of Http Response.
314 */
315function stripResponse(response) {
316 var strippedResponse = {};
317 strippedResponse.body = response.bodyAsText;
318 strippedResponse.headers = response.headers;
319 strippedResponse.status = response.status;
320 return strippedResponse;
321}
322/**
323 * Returns a stripped version of the Http Request that does not contain the
324 * Authorization header.
325 *
326 * @param {WebResource} request The Http Request object
327 *
328 * @return {WebResource} The stripped version of Http Request.
329 */
330function stripRequest(request) {
331 var strippedRequest = request.clone();
332 if (strippedRequest.headers) {
333 strippedRequest.headers.remove("authorization");
334 }
335 return strippedRequest;
336}
337/**
338 * Validates the given uuid as a string
339 *
340 * @param {string} uuid The uuid as a string that needs to be validated
341 *
342 * @return {boolean} True if the uuid is valid; false otherwise.
343 */
344function isValidUuid(uuid) {
345 var validUuidRegex = new RegExp("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", "ig");
346 return validUuidRegex.test(uuid);
347}
348/**
349 * Generated UUID
350 *
351 * @return {string} RFC4122 v4 UUID.
352 */
353function generateUuid() {
354 return uuid.v4();
355}
356/**
357 * Executes an array of promises sequentially. Inspiration of this method is here:
358 * https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html. An awesome blog on promises!
359 *
360 * @param {Array} promiseFactories An array of promise factories(A function that return a promise)
361 *
362 * @param {any} [kickstart] Input to the first promise that is used to kickstart the promise chain.
363 * If not provided then the promise chain starts with undefined.
364 *
365 * @return A chain of resolved or rejected promises
366 */
367function executePromisesSequentially(promiseFactories, kickstart) {
368 var result = Promise.resolve(kickstart);
369 promiseFactories.forEach(function (promiseFactory) {
370 result = result.then(promiseFactory);
371 });
372 return result;
373}
374/**
375 * A wrapper for setTimeout that resolves a promise after t milliseconds.
376 * @param {number} t The number of milliseconds to be delayed.
377 * @param {T} value The value to be resolved with after a timeout of t milliseconds.
378 * @returns {Promise<T>} Resolved promise
379 */
380function delay(t, value) {
381 return new Promise(function (resolve) { return setTimeout(function () { return resolve(value); }, t); });
382}
383/**
384 * Converts a Promise to a callback.
385 * @param {Promise<any>} promise The Promise to be converted to a callback
386 * @returns {Function} A function that takes the callback (cb: Function): void
387 * @deprecated generated code should instead depend on responseToBody
388 */
389function promiseToCallback(promise) {
390 if (typeof promise.then !== "function") {
391 throw new Error("The provided input is not a Promise.");
392 }
393 return function (cb) {
394 promise.then(function (data) {
395 cb(undefined, data);
396 }, function (err) {
397 cb(err);
398 });
399 };
400}
401/**
402 * Converts a Promise to a service callback.
403 * @param {Promise<HttpOperationResponse>} promise - The Promise of HttpOperationResponse to be converted to a service callback
404 * @returns {Function} A function that takes the service callback (cb: ServiceCallback<T>): void
405 */
406function promiseToServiceCallback(promise) {
407 if (typeof promise.then !== "function") {
408 throw new Error("The provided input is not a Promise.");
409 }
410 return function (cb) {
411 promise.then(function (data) {
412 process.nextTick(cb, undefined, data.parsedBody, data.request, data);
413 }, function (err) {
414 process.nextTick(cb, err);
415 });
416 };
417}
418function prepareXMLRootList(obj, elementName) {
419 var _a;
420 if (!Array.isArray(obj)) {
421 obj = [obj];
422 }
423 return _a = {}, _a[elementName] = obj, _a;
424}
425/**
426 * Applies the properties on the prototype of sourceCtors to the prototype of targetCtor
427 * @param {object} targetCtor The target object on which the properties need to be applied.
428 * @param {Array<object>} sourceCtors An array of source objects from which the properties need to be taken.
429 */
430function applyMixins(targetCtor, sourceCtors) {
431 sourceCtors.forEach(function (sourceCtors) {
432 Object.getOwnPropertyNames(sourceCtors.prototype).forEach(function (name) {
433 targetCtor.prototype[name] = sourceCtors.prototype[name];
434 });
435 });
436}
437var validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
438/**
439 * Indicates whether the given string is in ISO 8601 format.
440 * @param {string} value The value to be validated for ISO 8601 duration format.
441 * @return {boolean} `true` if valid, `false` otherwise.
442 */
443function isDuration(value) {
444 return validateISODuration.test(value);
445}
446/**
447 * Replace all of the instances of searchValue in value with the provided replaceValue.
448 * @param {string | undefined} value The value to search and replace in.
449 * @param {string} searchValue The value to search for in the value argument.
450 * @param {string} replaceValue The value to replace searchValue with in the value argument.
451 * @returns {string | undefined} The value where each instance of searchValue was replaced with replacedValue.
452 */
453function replaceAll(value, searchValue, replaceValue) {
454 return !value || !searchValue ? value : value.split(searchValue).join(replaceValue || "");
455}
456/**
457 * Determines whether the given enity is a basic/primitive type
458 * (string, number, boolean, null, undefined).
459 * @param value Any entity
460 * @return boolean - true is it is primitive type, false otherwise.
461 */
462function isPrimitiveType(value) {
463 return (typeof value !== "object" && typeof value !== "function") || value === null;
464}
465
466// Copyright (c) Microsoft Corporation. All rights reserved.
467var Serializer = /** @class */ (function () {
468 function Serializer(modelMappers, isXML) {
469 if (modelMappers === void 0) { modelMappers = {}; }
470 this.modelMappers = modelMappers;
471 this.isXML = isXML;
472 }
473 Serializer.prototype.validateConstraints = function (mapper, value, objectName) {
474 var failValidation = function (constraintName, constraintValue) {
475 throw new Error("\"" + objectName + "\" with value \"" + value + "\" should satisfy the constraint \"" + constraintName + "\": " + constraintValue + ".");
476 };
477 if (mapper.constraints && value != undefined) {
478 var _a = mapper.constraints, ExclusiveMaximum = _a.ExclusiveMaximum, ExclusiveMinimum = _a.ExclusiveMinimum, InclusiveMaximum = _a.InclusiveMaximum, InclusiveMinimum = _a.InclusiveMinimum, MaxItems = _a.MaxItems, MaxLength = _a.MaxLength, MinItems = _a.MinItems, MinLength = _a.MinLength, MultipleOf = _a.MultipleOf, Pattern = _a.Pattern, UniqueItems = _a.UniqueItems;
479 if (ExclusiveMaximum != undefined && value >= ExclusiveMaximum) {
480 failValidation("ExclusiveMaximum", ExclusiveMaximum);
481 }
482 if (ExclusiveMinimum != undefined && value <= ExclusiveMinimum) {
483 failValidation("ExclusiveMinimum", ExclusiveMinimum);
484 }
485 if (InclusiveMaximum != undefined && value > InclusiveMaximum) {
486 failValidation("InclusiveMaximum", InclusiveMaximum);
487 }
488 if (InclusiveMinimum != undefined && value < InclusiveMinimum) {
489 failValidation("InclusiveMinimum", InclusiveMinimum);
490 }
491 if (MaxItems != undefined && value.length > MaxItems) {
492 failValidation("MaxItems", MaxItems);
493 }
494 if (MaxLength != undefined && value.length > MaxLength) {
495 failValidation("MaxLength", MaxLength);
496 }
497 if (MinItems != undefined && value.length < MinItems) {
498 failValidation("MinItems", MinItems);
499 }
500 if (MinLength != undefined && value.length < MinLength) {
501 failValidation("MinLength", MinLength);
502 }
503 if (MultipleOf != undefined && value % MultipleOf !== 0) {
504 failValidation("MultipleOf", MultipleOf);
505 }
506 if (Pattern) {
507 var pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern;
508 if (typeof value !== "string" || value.match(pattern) === null) {
509 failValidation("Pattern", Pattern);
510 }
511 }
512 if (UniqueItems &&
513 value.some(function (item, i, ar) { return ar.indexOf(item) !== i; })) {
514 failValidation("UniqueItems", UniqueItems);
515 }
516 }
517 };
518 /**
519 * Serialize the given object based on its metadata defined in the mapper
520 *
521 * @param {Mapper} mapper The mapper which defines the metadata of the serializable object
522 *
523 * @param {object|string|Array|number|boolean|Date|stream} object A valid Javascript object to be serialized
524 *
525 * @param {string} objectName Name of the serialized object
526 *
527 * @returns {object|string|Array|number|boolean|Date|stream} A valid serialized Javascript object
528 */
529 Serializer.prototype.serialize = function (mapper, object, objectName) {
530 var payload = {};
531 var mapperType = mapper.type.name;
532 if (!objectName) {
533 objectName = mapper.serializedName;
534 }
535 if (mapperType.match(/^Sequence$/gi) !== null) {
536 payload = [];
537 }
538 if (mapper.isConstant) {
539 object = mapper.defaultValue;
540 }
541 // This table of allowed values should help explain
542 // the mapper.required and mapper.nullable properties.
543 // X means "neither undefined or null are allowed".
544 // || required
545 // || true | false
546 // nullable || ==========================
547 // true || null | undefined/null
548 // false || X | undefined
549 // undefined || X | undefined/null
550 var required = mapper.required, nullable = mapper.nullable;
551 if (required && nullable && object === undefined) {
552 throw new Error(objectName + " cannot be undefined.");
553 }
554 if (required && !nullable && object == undefined) {
555 throw new Error(objectName + " cannot be null or undefined.");
556 }
557 if (!required && nullable === false && object === null) {
558 throw new Error(objectName + " cannot be null.");
559 }
560 if (object == undefined) {
561 payload = object;
562 }
563 else {
564 // Validate Constraints if any
565 this.validateConstraints(mapper, object, objectName);
566 if (mapperType.match(/^any$/gi) !== null) {
567 payload = object;
568 }
569 else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/gi) !== null) {
570 payload = serializeBasicTypes(mapperType, objectName, object);
571 }
572 else if (mapperType.match(/^Enum$/gi) !== null) {
573 var enumMapper = mapper;
574 payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object);
575 }
576 else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/gi) !== null) {
577 payload = serializeDateTypes(mapperType, object, objectName);
578 }
579 else if (mapperType.match(/^ByteArray$/gi) !== null) {
580 payload = serializeByteArrayType(objectName, object);
581 }
582 else if (mapperType.match(/^Base64Url$/gi) !== null) {
583 payload = serializeBase64UrlType(objectName, object);
584 }
585 else if (mapperType.match(/^Sequence$/gi) !== null) {
586 payload = serializeSequenceType(this, mapper, object, objectName);
587 }
588 else if (mapperType.match(/^Dictionary$/gi) !== null) {
589 payload = serializeDictionaryType(this, mapper, object, objectName);
590 }
591 else if (mapperType.match(/^Composite$/gi) !== null) {
592 payload = serializeCompositeType(this, mapper, object, objectName);
593 }
594 }
595 return payload;
596 };
597 /**
598 * Deserialize the given object based on its metadata defined in the mapper
599 *
600 * @param {object} mapper The mapper which defines the metadata of the serializable object
601 *
602 * @param {object|string|Array|number|boolean|Date|stream} responseBody A valid Javascript entity to be deserialized
603 *
604 * @param {string} objectName Name of the deserialized object
605 *
606 * @returns {object|string|Array|number|boolean|Date|stream} A valid deserialized Javascript object
607 */
608 Serializer.prototype.deserialize = function (mapper, responseBody, objectName) {
609 if (responseBody == undefined) {
610 if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) {
611 // Edge case for empty XML non-wrapped lists. xml2js can't distinguish
612 // between the list being empty versus being missing,
613 // so let's do the more user-friendly thing and return an empty list.
614 responseBody = [];
615 }
616 // specifically check for undefined as default value can be a falsey value `0, "", false, null`
617 if (mapper.defaultValue !== undefined) {
618 responseBody = mapper.defaultValue;
619 }
620 return responseBody;
621 }
622 var payload;
623 var mapperType = mapper.type.name;
624 if (!objectName) {
625 objectName = mapper.serializedName;
626 }
627 if (mapperType.match(/^Composite$/gi) !== null) {
628 payload = deserializeCompositeType(this, mapper, responseBody, objectName);
629 }
630 else {
631 if (this.isXML) {
632 /**
633 * If the mapper specifies this as a non-composite type value but the responseBody contains
634 * both header ("$") and body ("_") properties, then just reduce the responseBody value to
635 * the body ("_") property.
636 */
637 if (responseBody["$"] != undefined && responseBody["_"] != undefined) {
638 responseBody = responseBody["_"];
639 }
640 }
641 if (mapperType.match(/^Number$/gi) !== null) {
642 payload = parseFloat(responseBody);
643 if (isNaN(payload)) {
644 payload = responseBody;
645 }
646 }
647 else if (mapperType.match(/^Boolean$/gi) !== null) {
648 if (responseBody === "true") {
649 payload = true;
650 }
651 else if (responseBody === "false") {
652 payload = false;
653 }
654 else {
655 payload = responseBody;
656 }
657 }
658 else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/gi) !== null) {
659 payload = responseBody;
660 }
661 else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/gi) !== null) {
662 payload = new Date(responseBody);
663 }
664 else if (mapperType.match(/^UnixTime$/gi) !== null) {
665 payload = unixTimeToDate(responseBody);
666 }
667 else if (mapperType.match(/^ByteArray$/gi) !== null) {
668 payload = decodeString(responseBody);
669 }
670 else if (mapperType.match(/^Base64Url$/gi) !== null) {
671 payload = base64UrlToByteArray(responseBody);
672 }
673 else if (mapperType.match(/^Sequence$/gi) !== null) {
674 payload = deserializeSequenceType(this, mapper, responseBody, objectName);
675 }
676 else if (mapperType.match(/^Dictionary$/gi) !== null) {
677 payload = deserializeDictionaryType(this, mapper, responseBody, objectName);
678 }
679 }
680 if (mapper.isConstant) {
681 payload = mapper.defaultValue;
682 }
683 return payload;
684 };
685 return Serializer;
686}());
687function trimEnd(str, ch) {
688 var len = str.length;
689 while (len - 1 >= 0 && str[len - 1] === ch) {
690 --len;
691 }
692 return str.substr(0, len);
693}
694function bufferToBase64Url(buffer) {
695 if (!buffer) {
696 return undefined;
697 }
698 if (!(buffer instanceof Uint8Array)) {
699 throw new Error("Please provide an input of type Uint8Array for converting to Base64Url.");
700 }
701 // Uint8Array to Base64.
702 var str = encodeByteArray(buffer);
703 // Base64 to Base64Url.
704 return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_");
705}
706function base64UrlToByteArray(str) {
707 if (!str) {
708 return undefined;
709 }
710 if (str && typeof str.valueOf() !== "string") {
711 throw new Error("Please provide an input of type string for converting to Uint8Array");
712 }
713 // Base64Url to Base64.
714 str = str.replace(/\-/g, "+").replace(/\_/g, "/");
715 // Base64 to Uint8Array.
716 return decodeString(str);
717}
718function splitSerializeName(prop) {
719 var classes = [];
720 var partialclass = "";
721 if (prop) {
722 var subwords = prop.split(".");
723 for (var _i = 0, subwords_1 = subwords; _i < subwords_1.length; _i++) {
724 var item = subwords_1[_i];
725 if (item.charAt(item.length - 1) === "\\") {
726 partialclass += item.substr(0, item.length - 1) + ".";
727 }
728 else {
729 partialclass += item;
730 classes.push(partialclass);
731 partialclass = "";
732 }
733 }
734 }
735 return classes;
736}
737function dateToUnixTime(d) {
738 if (!d) {
739 return undefined;
740 }
741 if (typeof d.valueOf() === "string") {
742 d = new Date(d);
743 }
744 return Math.floor(d.getTime() / 1000);
745}
746function unixTimeToDate(n) {
747 if (!n) {
748 return undefined;
749 }
750 return new Date(n * 1000);
751}
752function serializeBasicTypes(typeName, objectName, value) {
753 if (value !== null && value !== undefined) {
754 if (typeName.match(/^Number$/gi) !== null) {
755 if (typeof value !== "number") {
756 throw new Error(objectName + " with value " + value + " must be of type number.");
757 }
758 }
759 else if (typeName.match(/^String$/gi) !== null) {
760 if (typeof value.valueOf() !== "string") {
761 throw new Error(objectName + " with value \"" + value + "\" must be of type string.");
762 }
763 }
764 else if (typeName.match(/^Uuid$/gi) !== null) {
765 if (!(typeof value.valueOf() === "string" && isValidUuid(value))) {
766 throw new Error(objectName + " with value \"" + value + "\" must be of type string and a valid uuid.");
767 }
768 }
769 else if (typeName.match(/^Boolean$/gi) !== null) {
770 if (typeof value !== "boolean") {
771 throw new Error(objectName + " with value " + value + " must be of type boolean.");
772 }
773 }
774 else if (typeName.match(/^Stream$/gi) !== null) {
775 var objectType = typeof value;
776 if (objectType !== "string" &&
777 objectType !== "function" &&
778 !(value instanceof ArrayBuffer) &&
779 !ArrayBuffer.isView(value) &&
780 !(typeof Blob === "function" && value instanceof Blob)) {
781 throw new Error(objectName + " must be a string, Blob, ArrayBuffer, ArrayBufferView, or a function returning NodeJS.ReadableStream.");
782 }
783 }
784 }
785 return value;
786}
787function serializeEnumType(objectName, allowedValues, value) {
788 if (!allowedValues) {
789 throw new Error("Please provide a set of allowedValues to validate " + objectName + " as an Enum Type.");
790 }
791 var isPresent = allowedValues.some(function (item) {
792 if (typeof item.valueOf() === "string") {
793 return item.toLowerCase() === value.toLowerCase();
794 }
795 return item === value;
796 });
797 if (!isPresent) {
798 throw new Error(value + " is not a valid value for " + objectName + ". The valid values are: " + JSON.stringify(allowedValues) + ".");
799 }
800 return value;
801}
802function serializeByteArrayType(objectName, value) {
803 if (value != undefined) {
804 if (!(value instanceof Uint8Array)) {
805 throw new Error(objectName + " must be of type Uint8Array.");
806 }
807 value = encodeByteArray(value);
808 }
809 return value;
810}
811function serializeBase64UrlType(objectName, value) {
812 if (value != undefined) {
813 if (!(value instanceof Uint8Array)) {
814 throw new Error(objectName + " must be of type Uint8Array.");
815 }
816 value = bufferToBase64Url(value);
817 }
818 return value;
819}
820function serializeDateTypes(typeName, value, objectName) {
821 if (value != undefined) {
822 if (typeName.match(/^Date$/gi) !== null) {
823 if (!(value instanceof Date ||
824 (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
825 throw new Error(objectName + " must be an instanceof Date or a string in ISO8601 format.");
826 }
827 value =
828 value instanceof Date
829 ? value.toISOString().substring(0, 10)
830 : new Date(value).toISOString().substring(0, 10);
831 }
832 else if (typeName.match(/^DateTime$/gi) !== null) {
833 if (!(value instanceof Date ||
834 (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
835 throw new Error(objectName + " must be an instanceof Date or a string in ISO8601 format.");
836 }
837 value = value instanceof Date ? value.toISOString() : new Date(value).toISOString();
838 }
839 else if (typeName.match(/^DateTimeRfc1123$/gi) !== null) {
840 if (!(value instanceof Date ||
841 (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
842 throw new Error(objectName + " must be an instanceof Date or a string in RFC-1123 format.");
843 }
844 value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString();
845 }
846 else if (typeName.match(/^UnixTime$/gi) !== null) {
847 if (!(value instanceof Date ||
848 (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
849 throw new Error(objectName + " must be an instanceof Date or a string in RFC-1123/ISO8601 format " +
850 "for it to be serialized in UnixTime/Epoch format.");
851 }
852 value = dateToUnixTime(value);
853 }
854 else if (typeName.match(/^TimeSpan$/gi) !== null) {
855 if (!isDuration(value)) {
856 throw new Error(objectName + " must be a string in ISO 8601 format. Instead was \"" + value + "\".");
857 }
858 value = value;
859 }
860 }
861 return value;
862}
863function serializeSequenceType(serializer, mapper, object, objectName) {
864 if (!Array.isArray(object)) {
865 throw new Error(objectName + " must be of type Array.");
866 }
867 var elementType = mapper.type.element;
868 if (!elementType || typeof elementType !== "object") {
869 throw new Error("element\" metadata for an Array must be defined in the " +
870 ("mapper and it must of type \"object\" in " + objectName + "."));
871 }
872 var tempArray = [];
873 for (var i = 0; i < object.length; i++) {
874 tempArray[i] = serializer.serialize(elementType, object[i], objectName);
875 }
876 return tempArray;
877}
878function serializeDictionaryType(serializer, mapper, object, objectName) {
879 if (typeof object !== "object") {
880 throw new Error(objectName + " must be of type object.");
881 }
882 var valueType = mapper.type.value;
883 if (!valueType || typeof valueType !== "object") {
884 throw new Error("\"value\" metadata for a Dictionary must be defined in the " +
885 ("mapper and it must of type \"object\" in " + objectName + "."));
886 }
887 var tempDictionary = {};
888 for (var _i = 0, _a = Object.keys(object); _i < _a.length; _i++) {
889 var key = _a[_i];
890 tempDictionary[key] = serializer.serialize(valueType, object[key], objectName + "." + key);
891 }
892 return tempDictionary;
893}
894/**
895 * Resolves a composite mapper's modelProperties.
896 * @param serializer the serializer containing the entire set of mappers
897 * @param mapper the composite mapper to resolve
898 */
899function resolveModelProperties(serializer, mapper, objectName) {
900 var modelProps = mapper.type.modelProperties;
901 if (!modelProps) {
902 var className = mapper.type.className;
903 if (!className) {
904 throw new Error("Class name for model \"" + objectName + "\" is not provided in the mapper \"" + JSON.stringify(mapper, undefined, 2) + "\".");
905 }
906 var modelMapper = serializer.modelMappers[className];
907 if (!modelMapper) {
908 throw new Error("mapper() cannot be null or undefined for model \"" + className + "\".");
909 }
910 modelProps = modelMapper.type.modelProperties;
911 if (!modelProps) {
912 throw new Error("modelProperties cannot be null or undefined in the " +
913 ("mapper \"" + JSON.stringify(modelMapper) + "\" of type \"" + className + "\" for object \"" + objectName + "\"."));
914 }
915 }
916 return modelProps;
917}
918function serializeCompositeType(serializer, mapper, object, objectName) {
919 var _a;
920 if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
921 mapper = getPolymorphicMapper(serializer, mapper, object, "clientName");
922 }
923 if (object != undefined) {
924 var payload = {};
925 var modelProps = resolveModelProperties(serializer, mapper, objectName);
926 for (var _i = 0, _b = Object.keys(modelProps); _i < _b.length; _i++) {
927 var key = _b[_i];
928 var propertyMapper = modelProps[key];
929 if (propertyMapper.readOnly) {
930 continue;
931 }
932 var propName = void 0;
933 var parentObject = payload;
934 if (serializer.isXML) {
935 if (propertyMapper.xmlIsWrapped) {
936 propName = propertyMapper.xmlName;
937 }
938 else {
939 propName = propertyMapper.xmlElementName || propertyMapper.xmlName;
940 }
941 }
942 else {
943 var paths = splitSerializeName(propertyMapper.serializedName);
944 propName = paths.pop();
945 for (var _c = 0, paths_1 = paths; _c < paths_1.length; _c++) {
946 var pathName = paths_1[_c];
947 var childObject = parentObject[pathName];
948 if (childObject == undefined && object[key] != undefined) {
949 parentObject[pathName] = {};
950 }
951 parentObject = parentObject[pathName];
952 }
953 }
954 if (parentObject != undefined) {
955 var propertyObjectName = propertyMapper.serializedName !== ""
956 ? objectName + "." + propertyMapper.serializedName
957 : objectName;
958 var toSerialize = object[key];
959 var polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
960 if (polymorphicDiscriminator &&
961 polymorphicDiscriminator.clientName === key &&
962 toSerialize == undefined) {
963 toSerialize = mapper.serializedName;
964 }
965 var serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName);
966 if (serializedValue !== undefined && propName != undefined) {
967 if (propertyMapper.xmlIsAttribute) {
968 // $ is the key attributes are kept under in xml2js.
969 // This keeps things simple while preventing name collision
970 // with names in user documents.
971 parentObject.$ = parentObject.$ || {};
972 parentObject.$[propName] = serializedValue;
973 }
974 else if (propertyMapper.xmlIsWrapped) {
975 parentObject[propName] = (_a = {}, _a[propertyMapper.xmlElementName] = serializedValue, _a);
976 }
977 else {
978 parentObject[propName] = serializedValue;
979 }
980 }
981 }
982 }
983 var additionalPropertiesMapper = mapper.type.additionalProperties;
984 if (additionalPropertiesMapper) {
985 var propNames = Object.keys(modelProps);
986 var _loop_1 = function (clientPropName) {
987 var isAdditionalProperty = propNames.every(function (pn) { return pn !== clientPropName; });
988 if (isAdditionalProperty) {
989 payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]');
990 }
991 };
992 for (var clientPropName in object) {
993 _loop_1(clientPropName);
994 }
995 }
996 return payload;
997 }
998 return object;
999}
1000function isSpecialXmlProperty(propertyName) {
1001 return ["$", "_"].includes(propertyName);
1002}
1003function deserializeCompositeType(serializer, mapper, responseBody, objectName) {
1004 if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
1005 mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName");
1006 }
1007 var modelProps = resolveModelProperties(serializer, mapper, objectName);
1008 var instance = {};
1009 var handledPropertyNames = [];
1010 for (var _i = 0, _a = Object.keys(modelProps); _i < _a.length; _i++) {
1011 var key = _a[_i];
1012 var propertyMapper = modelProps[key];
1013 var paths = splitSerializeName(modelProps[key].serializedName);
1014 handledPropertyNames.push(paths[0]);
1015 var serializedName = propertyMapper.serializedName, xmlName = propertyMapper.xmlName, xmlElementName = propertyMapper.xmlElementName;
1016 var propertyObjectName = objectName;
1017 if (serializedName !== "" && serializedName !== undefined) {
1018 propertyObjectName = objectName + "." + serializedName;
1019 }
1020 var headerCollectionPrefix = propertyMapper.headerCollectionPrefix;
1021 if (headerCollectionPrefix) {
1022 var dictionary = {};
1023 for (var _b = 0, _c = Object.keys(responseBody); _b < _c.length; _b++) {
1024 var headerKey = _c[_b];
1025 if (headerKey.startsWith(headerCollectionPrefix)) {
1026 dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName);
1027 }
1028 handledPropertyNames.push(headerKey);
1029 }
1030 instance[key] = dictionary;
1031 }
1032 else if (serializer.isXML) {
1033 if (propertyMapper.xmlIsAttribute && responseBody.$) {
1034 instance[key] = serializer.deserialize(propertyMapper, responseBody.$[xmlName], propertyObjectName);
1035 }
1036 else {
1037 var propertyName = xmlElementName || xmlName || serializedName;
1038 var unwrappedProperty = responseBody[propertyName];
1039 if (propertyMapper.xmlIsWrapped) {
1040 unwrappedProperty = responseBody[xmlName];
1041 unwrappedProperty = unwrappedProperty && unwrappedProperty[xmlElementName];
1042 var isEmptyWrappedList = unwrappedProperty === undefined;
1043 if (isEmptyWrappedList) {
1044 unwrappedProperty = [];
1045 }
1046 }
1047 instance[key] = serializer.deserialize(propertyMapper, unwrappedProperty, propertyObjectName);
1048 }
1049 }
1050 else {
1051 // deserialize the property if it is present in the provided responseBody instance
1052 var propertyInstance = void 0;
1053 var res = responseBody;
1054 // traversing the object step by step.
1055 for (var _d = 0, paths_2 = paths; _d < paths_2.length; _d++) {
1056 var item = paths_2[_d];
1057 if (!res)
1058 break;
1059 res = res[item];
1060 }
1061 propertyInstance = res;
1062 var polymorphicDiscriminator = mapper.type.polymorphicDiscriminator;
1063 // checking that the model property name (key)(ex: "fishtype") and the
1064 // clientName of the polymorphicDiscriminator {metadata} (ex: "fishtype")
1065 // instead of the serializedName of the polymorphicDiscriminator (ex: "fish.type")
1066 // is a better approach. The generator is not consistent with escaping '\.' in the
1067 // serializedName of the property (ex: "fish\.type") that is marked as polymorphic discriminator
1068 // and the serializedName of the metadata polymorphicDiscriminator (ex: "fish.type"). However,
1069 // the clientName transformation of the polymorphicDiscriminator (ex: "fishtype") and
1070 // the transformation of model property name (ex: "fishtype") is done consistently.
1071 // Hence, it is a safer bet to rely on the clientName of the polymorphicDiscriminator.
1072 if (polymorphicDiscriminator &&
1073 key === polymorphicDiscriminator.clientName &&
1074 propertyInstance == undefined) {
1075 propertyInstance = mapper.serializedName;
1076 }
1077 var serializedValue = void 0;
1078 // paging
1079 if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") {
1080 propertyInstance = responseBody[key];
1081 var arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName);
1082 // Copy over any properties that have already been added into the instance, where they do
1083 // not exist on the newly de-serialized array
1084 for (var _e = 0, _f = Object.entries(instance); _e < _f.length; _e++) {
1085 var _g = _f[_e], key_1 = _g[0], value = _g[1];
1086 if (!arrayInstance.hasOwnProperty(key_1)) {
1087 arrayInstance[key_1] = value;
1088 }
1089 }
1090 instance = arrayInstance;
1091 }
1092 else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) {
1093 serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName);
1094 instance[key] = serializedValue;
1095 }
1096 }
1097 }
1098 var additionalPropertiesMapper = mapper.type.additionalProperties;
1099 if (additionalPropertiesMapper) {
1100 var isAdditionalProperty = function (responsePropName) {
1101 for (var clientPropName in modelProps) {
1102 var paths = splitSerializeName(modelProps[clientPropName].serializedName);
1103 if (paths[0] === responsePropName) {
1104 return false;
1105 }
1106 }
1107 return true;
1108 };
1109 for (var responsePropName in responseBody) {
1110 if (isAdditionalProperty(responsePropName)) {
1111 instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]');
1112 }
1113 }
1114 }
1115 else if (responseBody) {
1116 for (var _h = 0, _j = Object.keys(responseBody); _h < _j.length; _h++) {
1117 var key = _j[_h];
1118 if (instance[key] === undefined &&
1119 !handledPropertyNames.includes(key) &&
1120 !isSpecialXmlProperty(key)) {
1121 instance[key] = responseBody[key];
1122 }
1123 }
1124 }
1125 return instance;
1126}
1127function deserializeDictionaryType(serializer, mapper, responseBody, objectName) {
1128 /*jshint validthis: true */
1129 var value = mapper.type.value;
1130 if (!value || typeof value !== "object") {
1131 throw new Error("\"value\" metadata for a Dictionary must be defined in the " +
1132 ("mapper and it must of type \"object\" in " + objectName));
1133 }
1134 if (responseBody) {
1135 var tempDictionary = {};
1136 for (var _i = 0, _a = Object.keys(responseBody); _i < _a.length; _i++) {
1137 var key = _a[_i];
1138 tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName);
1139 }
1140 return tempDictionary;
1141 }
1142 return responseBody;
1143}
1144function deserializeSequenceType(serializer, mapper, responseBody, objectName) {
1145 /*jshint validthis: true */
1146 var element = mapper.type.element;
1147 if (!element || typeof element !== "object") {
1148 throw new Error("element\" metadata for an Array must be defined in the " +
1149 ("mapper and it must of type \"object\" in " + objectName));
1150 }
1151 if (responseBody) {
1152 if (!Array.isArray(responseBody)) {
1153 // xml2js will interpret a single element array as just the element, so force it to be an array
1154 responseBody = [responseBody];
1155 }
1156 var tempArray = [];
1157 for (var i = 0; i < responseBody.length; i++) {
1158 tempArray[i] = serializer.deserialize(element, responseBody[i], objectName + "[" + i + "]");
1159 }
1160 return tempArray;
1161 }
1162 return responseBody;
1163}
1164function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) {
1165 var polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
1166 if (polymorphicDiscriminator) {
1167 var discriminatorName = polymorphicDiscriminator[polymorphicPropertyName];
1168 if (discriminatorName != undefined) {
1169 var discriminatorValue = object[discriminatorName];
1170 if (discriminatorValue != undefined) {
1171 var typeName = mapper.type.uberParent || mapper.type.className;
1172 var indexDiscriminator = discriminatorValue === typeName
1173 ? discriminatorValue
1174 : typeName + "." + discriminatorValue;
1175 var polymorphicMapper = serializer.modelMappers.discriminators[indexDiscriminator];
1176 if (polymorphicMapper) {
1177 mapper = polymorphicMapper;
1178 }
1179 }
1180 }
1181 }
1182 return mapper;
1183}
1184function getPolymorphicDiscriminatorRecursively(serializer, mapper) {
1185 return (mapper.type.polymorphicDiscriminator ||
1186 getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) ||
1187 getPolymorphicDiscriminatorSafely(serializer, mapper.type.className));
1188}
1189function getPolymorphicDiscriminatorSafely(serializer, typeName) {
1190 return (typeName &&
1191 serializer.modelMappers[typeName] &&
1192 serializer.modelMappers[typeName].type.polymorphicDiscriminator);
1193}
1194// TODO: why is this here?
1195function serializeObject(toSerialize) {
1196 if (toSerialize == undefined)
1197 return undefined;
1198 if (toSerialize instanceof Uint8Array) {
1199 toSerialize = encodeByteArray(toSerialize);
1200 return toSerialize;
1201 }
1202 else if (toSerialize instanceof Date) {
1203 return toSerialize.toISOString();
1204 }
1205 else if (Array.isArray(toSerialize)) {
1206 var array = [];
1207 for (var i = 0; i < toSerialize.length; i++) {
1208 array.push(serializeObject(toSerialize[i]));
1209 }
1210 return array;
1211 }
1212 else if (typeof toSerialize === "object") {
1213 var dictionary = {};
1214 for (var property in toSerialize) {
1215 dictionary[property] = serializeObject(toSerialize[property]);
1216 }
1217 return dictionary;
1218 }
1219 return toSerialize;
1220}
1221/**
1222 * Utility function to create a K:V from a list of strings
1223 */
1224function strEnum(o) {
1225 var result = {};
1226 for (var _i = 0, o_1 = o; _i < o_1.length; _i++) {
1227 var key = o_1[_i];
1228 result[key] = key;
1229 }
1230 return result;
1231}
1232var MapperType = strEnum([
1233 "Base64Url",
1234 "Boolean",
1235 "ByteArray",
1236 "Composite",
1237 "Date",
1238 "DateTime",
1239 "DateTimeRfc1123",
1240 "Dictionary",
1241 "Enum",
1242 "Number",
1243 "Object",
1244 "Sequence",
1245 "String",
1246 "Stream",
1247 "TimeSpan",
1248 "UnixTime",
1249]);
1250
1251// Copyright (c) Microsoft Corporation. All rights reserved.
1252function isWebResourceLike(object) {
1253 if (typeof object !== "object") {
1254 return false;
1255 }
1256 if (typeof object.url === "string" &&
1257 typeof object.method === "string" &&
1258 typeof object.headers === "object" &&
1259 isHttpHeadersLike(object.headers) &&
1260 typeof object.validateRequestProperties === "function" &&
1261 typeof object.prepare === "function" &&
1262 typeof object.clone === "function") {
1263 return true;
1264 }
1265 return false;
1266}
1267/**
1268 * Creates a new WebResource object.
1269 *
1270 * This class provides an abstraction over a REST call by being library / implementation agnostic and wrapping the necessary
1271 * properties to initiate a request.
1272 *
1273 * @constructor
1274 */
1275var WebResource = /** @class */ (function () {
1276 function WebResource(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings, keepAlive, agentSettings, redirectLimit) {
1277 this.streamResponseBody = streamResponseBody;
1278 this.url = url || "";
1279 this.method = method || "GET";
1280 this.headers = isHttpHeadersLike(headers) ? headers : new HttpHeaders(headers);
1281 this.body = body;
1282 this.query = query;
1283 this.formData = undefined;
1284 this.withCredentials = withCredentials || false;
1285 this.abortSignal = abortSignal;
1286 this.timeout = timeout || 0;
1287 this.onUploadProgress = onUploadProgress;
1288 this.onDownloadProgress = onDownloadProgress;
1289 this.proxySettings = proxySettings;
1290 this.keepAlive = keepAlive;
1291 this.agentSettings = agentSettings;
1292 this.redirectLimit = redirectLimit;
1293 }
1294 /**
1295 * Validates that the required properties such as method, url, headers["Content-Type"],
1296 * headers["accept-language"] are defined. It will throw an error if one of the above
1297 * mentioned properties are not defined.
1298 */
1299 WebResource.prototype.validateRequestProperties = function () {
1300 if (!this.method) {
1301 throw new Error("WebResource.method is required.");
1302 }
1303 if (!this.url) {
1304 throw new Error("WebResource.url is required.");
1305 }
1306 };
1307 /**
1308 * Prepares the request.
1309 * @param {RequestPrepareOptions} options Options to provide for preparing the request.
1310 * @returns {WebResource} Returns the prepared WebResource (HTTP Request) object that needs to be given to the request pipeline.
1311 */
1312 WebResource.prototype.prepare = function (options) {
1313 if (!options) {
1314 throw new Error("options object is required");
1315 }
1316 if (options.method == undefined || typeof options.method.valueOf() !== "string") {
1317 throw new Error("options.method must be a string.");
1318 }
1319 if (options.url && options.pathTemplate) {
1320 throw new Error("options.url and options.pathTemplate are mutually exclusive. Please provide exactly one of them.");
1321 }
1322 if ((options.pathTemplate == undefined || typeof options.pathTemplate.valueOf() !== "string") &&
1323 (options.url == undefined || typeof options.url.valueOf() !== "string")) {
1324 throw new Error("Please provide exactly one of options.pathTemplate or options.url.");
1325 }
1326 // set the url if it is provided.
1327 if (options.url) {
1328 if (typeof options.url !== "string") {
1329 throw new Error('options.url must be of type "string".');
1330 }
1331 this.url = options.url;
1332 }
1333 // set the method
1334 if (options.method) {
1335 var validMethods = ["GET", "PUT", "HEAD", "DELETE", "OPTIONS", "POST", "PATCH", "TRACE"];
1336 if (validMethods.indexOf(options.method.toUpperCase()) === -1) {
1337 throw new Error('The provided method "' +
1338 options.method +
1339 '" is invalid. Supported HTTP methods are: ' +
1340 JSON.stringify(validMethods));
1341 }
1342 }
1343 this.method = options.method.toUpperCase();
1344 // construct the url if path template is provided
1345 if (options.pathTemplate) {
1346 var pathTemplate_1 = options.pathTemplate, pathParameters_1 = options.pathParameters;
1347 if (typeof pathTemplate_1 !== "string") {
1348 throw new Error('options.pathTemplate must be of type "string".');
1349 }
1350 if (!options.baseUrl) {
1351 options.baseUrl = "https://management.azure.com";
1352 }
1353 var baseUrl = options.baseUrl;
1354 var url_1 = baseUrl +
1355 (baseUrl.endsWith("/") ? "" : "/") +
1356 (pathTemplate_1.startsWith("/") ? pathTemplate_1.slice(1) : pathTemplate_1);
1357 var segments = url_1.match(/({\w*\s*\w*})/gi);
1358 if (segments && segments.length) {
1359 if (!pathParameters_1) {
1360 throw new Error("pathTemplate: " + pathTemplate_1 + " has been provided. Hence, options.pathParameters must also be provided.");
1361 }
1362 segments.forEach(function (item) {
1363 var pathParamName = item.slice(1, -1);
1364 var pathParam = pathParameters_1[pathParamName];
1365 if (pathParam === null ||
1366 pathParam === undefined ||
1367 !(typeof pathParam === "string" || typeof pathParam === "object")) {
1368 throw new Error("pathTemplate: " + pathTemplate_1 + " contains the path parameter " + pathParamName +
1369 (" however, it is not present in " + pathParameters_1 + " - " + JSON.stringify(pathParameters_1, undefined, 2) + ".") +
1370 ("The value of the path parameter can either be a \"string\" of the form { " + pathParamName + ": \"some sample value\" } or ") +
1371 ("it can be an \"object\" of the form { \"" + pathParamName + "\": { value: \"some sample value\", skipUrlEncoding: true } }."));
1372 }
1373 if (typeof pathParam.valueOf() === "string") {
1374 url_1 = url_1.replace(item, encodeURIComponent(pathParam));
1375 }
1376 if (typeof pathParam.valueOf() === "object") {
1377 if (!pathParam.value) {
1378 throw new Error("options.pathParameters[" + pathParamName + "] is of type \"object\" but it does not contain a \"value\" property.");
1379 }
1380 if (pathParam.skipUrlEncoding) {
1381 url_1 = url_1.replace(item, pathParam.value);
1382 }
1383 else {
1384 url_1 = url_1.replace(item, encodeURIComponent(pathParam.value));
1385 }
1386 }
1387 });
1388 }
1389 this.url = url_1;
1390 }
1391 // append query parameters to the url if they are provided. They can be provided with pathTemplate or url option.
1392 if (options.queryParameters) {
1393 var queryParameters = options.queryParameters;
1394 if (typeof queryParameters !== "object") {
1395 throw new Error("options.queryParameters must be of type object. It should be a JSON object " +
1396 "of \"query-parameter-name\" as the key and the \"query-parameter-value\" as the value. " +
1397 "The \"query-parameter-value\" may be fo type \"string\" or an \"object\" of the form { value: \"query-parameter-value\", skipUrlEncoding: true }.");
1398 }
1399 // append question mark if it is not present in the url
1400 if (this.url && this.url.indexOf("?") === -1) {
1401 this.url += "?";
1402 }
1403 // construct queryString
1404 var queryParams = [];
1405 // We need to populate this.query as a dictionary if the request is being used for Sway's validateRequest().
1406 this.query = {};
1407 for (var queryParamName in queryParameters) {
1408 var queryParam = queryParameters[queryParamName];
1409 if (queryParam) {
1410 if (typeof queryParam === "string") {
1411 queryParams.push(queryParamName + "=" + encodeURIComponent(queryParam));
1412 this.query[queryParamName] = encodeURIComponent(queryParam);
1413 }
1414 else if (typeof queryParam === "object") {
1415 if (!queryParam.value) {
1416 throw new Error("options.queryParameters[" + queryParamName + "] is of type \"object\" but it does not contain a \"value\" property.");
1417 }
1418 if (queryParam.skipUrlEncoding) {
1419 queryParams.push(queryParamName + "=" + queryParam.value);
1420 this.query[queryParamName] = queryParam.value;
1421 }
1422 else {
1423 queryParams.push(queryParamName + "=" + encodeURIComponent(queryParam.value));
1424 this.query[queryParamName] = encodeURIComponent(queryParam.value);
1425 }
1426 }
1427 }
1428 } // end-of-for
1429 // append the queryString
1430 this.url += queryParams.join("&");
1431 }
1432 // add headers to the request if they are provided
1433 if (options.headers) {
1434 var headers = options.headers;
1435 for (var _i = 0, _a = Object.keys(options.headers); _i < _a.length; _i++) {
1436 var headerName = _a[_i];
1437 this.headers.set(headerName, headers[headerName]);
1438 }
1439 }
1440 // ensure accept-language is set correctly
1441 if (!this.headers.get("accept-language")) {
1442 this.headers.set("accept-language", "en-US");
1443 }
1444 // ensure the request-id is set correctly
1445 if (!this.headers.get("x-ms-client-request-id") && !options.disableClientRequestId) {
1446 this.headers.set("x-ms-client-request-id", generateUuid());
1447 }
1448 // default
1449 if (!this.headers.get("Content-Type")) {
1450 this.headers.set("Content-Type", "application/json; charset=utf-8");
1451 }
1452 // set the request body. request.js automatically sets the Content-Length request header, so we need not set it explicilty
1453 this.body = options.body;
1454 if (options.body != undefined) {
1455 // body as a stream special case. set the body as-is and check for some special request headers specific to sending a stream.
1456 if (options.bodyIsStream) {
1457 if (!this.headers.get("Transfer-Encoding")) {
1458 this.headers.set("Transfer-Encoding", "chunked");
1459 }
1460 if (this.headers.get("Content-Type") !== "application/octet-stream") {
1461 this.headers.set("Content-Type", "application/octet-stream");
1462 }
1463 }
1464 else {
1465 if (options.serializationMapper) {
1466 this.body = new Serializer(options.mappers).serialize(options.serializationMapper, options.body, "requestBody");
1467 }
1468 if (!options.disableJsonStringifyOnBody) {
1469 this.body = JSON.stringify(options.body);
1470 }
1471 }
1472 }
1473 this.abortSignal = options.abortSignal;
1474 this.onDownloadProgress = options.onDownloadProgress;
1475 this.onUploadProgress = options.onUploadProgress;
1476 this.redirectLimit = options.redirectLimit;
1477 this.streamResponseBody = options.streamResponseBody;
1478 return this;
1479 };
1480 /**
1481 * Clone this WebResource HTTP request object.
1482 * @returns {WebResource} The clone of this WebResource HTTP request object.
1483 */
1484 WebResource.prototype.clone = function () {
1485 var result = new WebResource(this.url, this.method, this.body, this.query, this.headers && this.headers.clone(), this.streamResponseBody, this.withCredentials, this.abortSignal, this.timeout, this.onUploadProgress, this.onDownloadProgress, this.proxySettings, this.keepAlive, this.agentSettings, this.redirectLimit);
1486 if (this.formData) {
1487 result.formData = this.formData;
1488 }
1489 if (this.operationSpec) {
1490 result.operationSpec = this.operationSpec;
1491 }
1492 if (this.shouldDeserialize) {
1493 result.shouldDeserialize = this.shouldDeserialize;
1494 }
1495 if (this.operationResponseGetter) {
1496 result.operationResponseGetter = this.operationResponseGetter;
1497 }
1498 return result;
1499 };
1500 return WebResource;
1501}());
1502
1503/**
1504 * @author Toru Nagashima <https://github.com/mysticatea>
1505 * @copyright 2015 Toru Nagashima. All rights reserved.
1506 * See LICENSE file in root directory for full license.
1507 */
1508/**
1509 * @typedef {object} PrivateData
1510 * @property {EventTarget} eventTarget The event target.
1511 * @property {{type:string}} event The original event object.
1512 * @property {number} eventPhase The current event phase.
1513 * @property {EventTarget|null} currentTarget The current event target.
1514 * @property {boolean} canceled The flag to prevent default.
1515 * @property {boolean} stopped The flag to stop propagation.
1516 * @property {boolean} immediateStopped The flag to stop propagation immediately.
1517 * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null.
1518 * @property {number} timeStamp The unix time.
1519 * @private
1520 */
1521
1522/**
1523 * Private data for event wrappers.
1524 * @type {WeakMap<Event, PrivateData>}
1525 * @private
1526 */
1527const privateData = new WeakMap();
1528
1529/**
1530 * Cache for wrapper classes.
1531 * @type {WeakMap<Object, Function>}
1532 * @private
1533 */
1534const wrappers = new WeakMap();
1535
1536/**
1537 * Get private data.
1538 * @param {Event} event The event object to get private data.
1539 * @returns {PrivateData} The private data of the event.
1540 * @private
1541 */
1542function pd(event) {
1543 const retv = privateData.get(event);
1544 console.assert(
1545 retv != null,
1546 "'this' is expected an Event object, but got",
1547 event
1548 );
1549 return retv
1550}
1551
1552/**
1553 * https://dom.spec.whatwg.org/#set-the-canceled-flag
1554 * @param data {PrivateData} private data.
1555 */
1556function setCancelFlag(data) {
1557 if (data.passiveListener != null) {
1558 if (
1559 typeof console !== "undefined" &&
1560 typeof console.error === "function"
1561 ) {
1562 console.error(
1563 "Unable to preventDefault inside passive event listener invocation.",
1564 data.passiveListener
1565 );
1566 }
1567 return
1568 }
1569 if (!data.event.cancelable) {
1570 return
1571 }
1572
1573 data.canceled = true;
1574 if (typeof data.event.preventDefault === "function") {
1575 data.event.preventDefault();
1576 }
1577}
1578
1579/**
1580 * @see https://dom.spec.whatwg.org/#interface-event
1581 * @private
1582 */
1583/**
1584 * The event wrapper.
1585 * @constructor
1586 * @param {EventTarget} eventTarget The event target of this dispatching.
1587 * @param {Event|{type:string}} event The original event to wrap.
1588 */
1589function Event(eventTarget, event) {
1590 privateData.set(this, {
1591 eventTarget,
1592 event,
1593 eventPhase: 2,
1594 currentTarget: eventTarget,
1595 canceled: false,
1596 stopped: false,
1597 immediateStopped: false,
1598 passiveListener: null,
1599 timeStamp: event.timeStamp || Date.now(),
1600 });
1601
1602 // https://heycam.github.io/webidl/#Unforgeable
1603 Object.defineProperty(this, "isTrusted", { value: false, enumerable: true });
1604
1605 // Define accessors
1606 const keys = Object.keys(event);
1607 for (let i = 0; i < keys.length; ++i) {
1608 const key = keys[i];
1609 if (!(key in this)) {
1610 Object.defineProperty(this, key, defineRedirectDescriptor(key));
1611 }
1612 }
1613}
1614
1615// Should be enumerable, but class methods are not enumerable.
1616Event.prototype = {
1617 /**
1618 * The type of this event.
1619 * @type {string}
1620 */
1621 get type() {
1622 return pd(this).event.type
1623 },
1624
1625 /**
1626 * The target of this event.
1627 * @type {EventTarget}
1628 */
1629 get target() {
1630 return pd(this).eventTarget
1631 },
1632
1633 /**
1634 * The target of this event.
1635 * @type {EventTarget}
1636 */
1637 get currentTarget() {
1638 return pd(this).currentTarget
1639 },
1640
1641 /**
1642 * @returns {EventTarget[]} The composed path of this event.
1643 */
1644 composedPath() {
1645 const currentTarget = pd(this).currentTarget;
1646 if (currentTarget == null) {
1647 return []
1648 }
1649 return [currentTarget]
1650 },
1651
1652 /**
1653 * Constant of NONE.
1654 * @type {number}
1655 */
1656 get NONE() {
1657 return 0
1658 },
1659
1660 /**
1661 * Constant of CAPTURING_PHASE.
1662 * @type {number}
1663 */
1664 get CAPTURING_PHASE() {
1665 return 1
1666 },
1667
1668 /**
1669 * Constant of AT_TARGET.
1670 * @type {number}
1671 */
1672 get AT_TARGET() {
1673 return 2
1674 },
1675
1676 /**
1677 * Constant of BUBBLING_PHASE.
1678 * @type {number}
1679 */
1680 get BUBBLING_PHASE() {
1681 return 3
1682 },
1683
1684 /**
1685 * The target of this event.
1686 * @type {number}
1687 */
1688 get eventPhase() {
1689 return pd(this).eventPhase
1690 },
1691
1692 /**
1693 * Stop event bubbling.
1694 * @returns {void}
1695 */
1696 stopPropagation() {
1697 const data = pd(this);
1698
1699 data.stopped = true;
1700 if (typeof data.event.stopPropagation === "function") {
1701 data.event.stopPropagation();
1702 }
1703 },
1704
1705 /**
1706 * Stop event bubbling.
1707 * @returns {void}
1708 */
1709 stopImmediatePropagation() {
1710 const data = pd(this);
1711
1712 data.stopped = true;
1713 data.immediateStopped = true;
1714 if (typeof data.event.stopImmediatePropagation === "function") {
1715 data.event.stopImmediatePropagation();
1716 }
1717 },
1718
1719 /**
1720 * The flag to be bubbling.
1721 * @type {boolean}
1722 */
1723 get bubbles() {
1724 return Boolean(pd(this).event.bubbles)
1725 },
1726
1727 /**
1728 * The flag to be cancelable.
1729 * @type {boolean}
1730 */
1731 get cancelable() {
1732 return Boolean(pd(this).event.cancelable)
1733 },
1734
1735 /**
1736 * Cancel this event.
1737 * @returns {void}
1738 */
1739 preventDefault() {
1740 setCancelFlag(pd(this));
1741 },
1742
1743 /**
1744 * The flag to indicate cancellation state.
1745 * @type {boolean}
1746 */
1747 get defaultPrevented() {
1748 return pd(this).canceled
1749 },
1750
1751 /**
1752 * The flag to be composed.
1753 * @type {boolean}
1754 */
1755 get composed() {
1756 return Boolean(pd(this).event.composed)
1757 },
1758
1759 /**
1760 * The unix time of this event.
1761 * @type {number}
1762 */
1763 get timeStamp() {
1764 return pd(this).timeStamp
1765 },
1766
1767 /**
1768 * The target of this event.
1769 * @type {EventTarget}
1770 * @deprecated
1771 */
1772 get srcElement() {
1773 return pd(this).eventTarget
1774 },
1775
1776 /**
1777 * The flag to stop event bubbling.
1778 * @type {boolean}
1779 * @deprecated
1780 */
1781 get cancelBubble() {
1782 return pd(this).stopped
1783 },
1784 set cancelBubble(value) {
1785 if (!value) {
1786 return
1787 }
1788 const data = pd(this);
1789
1790 data.stopped = true;
1791 if (typeof data.event.cancelBubble === "boolean") {
1792 data.event.cancelBubble = true;
1793 }
1794 },
1795
1796 /**
1797 * The flag to indicate cancellation state.
1798 * @type {boolean}
1799 * @deprecated
1800 */
1801 get returnValue() {
1802 return !pd(this).canceled
1803 },
1804 set returnValue(value) {
1805 if (!value) {
1806 setCancelFlag(pd(this));
1807 }
1808 },
1809
1810 /**
1811 * Initialize this event object. But do nothing under event dispatching.
1812 * @param {string} type The event type.
1813 * @param {boolean} [bubbles=false] The flag to be possible to bubble up.
1814 * @param {boolean} [cancelable=false] The flag to be possible to cancel.
1815 * @deprecated
1816 */
1817 initEvent() {
1818 // Do nothing.
1819 },
1820};
1821
1822// `constructor` is not enumerable.
1823Object.defineProperty(Event.prototype, "constructor", {
1824 value: Event,
1825 configurable: true,
1826 writable: true,
1827});
1828
1829// Ensure `event instanceof window.Event` is `true`.
1830if (typeof window !== "undefined" && typeof window.Event !== "undefined") {
1831 Object.setPrototypeOf(Event.prototype, window.Event.prototype);
1832
1833 // Make association for wrappers.
1834 wrappers.set(window.Event.prototype, Event);
1835}
1836
1837/**
1838 * Get the property descriptor to redirect a given property.
1839 * @param {string} key Property name to define property descriptor.
1840 * @returns {PropertyDescriptor} The property descriptor to redirect the property.
1841 * @private
1842 */
1843function defineRedirectDescriptor(key) {
1844 return {
1845 get() {
1846 return pd(this).event[key]
1847 },
1848 set(value) {
1849 pd(this).event[key] = value;
1850 },
1851 configurable: true,
1852 enumerable: true,
1853 }
1854}
1855
1856/**
1857 * Get the property descriptor to call a given method property.
1858 * @param {string} key Property name to define property descriptor.
1859 * @returns {PropertyDescriptor} The property descriptor to call the method property.
1860 * @private
1861 */
1862function defineCallDescriptor(key) {
1863 return {
1864 value() {
1865 const event = pd(this).event;
1866 return event[key].apply(event, arguments)
1867 },
1868 configurable: true,
1869 enumerable: true,
1870 }
1871}
1872
1873/**
1874 * Define new wrapper class.
1875 * @param {Function} BaseEvent The base wrapper class.
1876 * @param {Object} proto The prototype of the original event.
1877 * @returns {Function} The defined wrapper class.
1878 * @private
1879 */
1880function defineWrapper(BaseEvent, proto) {
1881 const keys = Object.keys(proto);
1882 if (keys.length === 0) {
1883 return BaseEvent
1884 }
1885
1886 /** CustomEvent */
1887 function CustomEvent(eventTarget, event) {
1888 BaseEvent.call(this, eventTarget, event);
1889 }
1890
1891 CustomEvent.prototype = Object.create(BaseEvent.prototype, {
1892 constructor: { value: CustomEvent, configurable: true, writable: true },
1893 });
1894
1895 // Define accessors.
1896 for (let i = 0; i < keys.length; ++i) {
1897 const key = keys[i];
1898 if (!(key in BaseEvent.prototype)) {
1899 const descriptor = Object.getOwnPropertyDescriptor(proto, key);
1900 const isFunc = typeof descriptor.value === "function";
1901 Object.defineProperty(
1902 CustomEvent.prototype,
1903 key,
1904 isFunc
1905 ? defineCallDescriptor(key)
1906 : defineRedirectDescriptor(key)
1907 );
1908 }
1909 }
1910
1911 return CustomEvent
1912}
1913
1914/**
1915 * Get the wrapper class of a given prototype.
1916 * @param {Object} proto The prototype of the original event to get its wrapper.
1917 * @returns {Function} The wrapper class.
1918 * @private
1919 */
1920function getWrapper(proto) {
1921 if (proto == null || proto === Object.prototype) {
1922 return Event
1923 }
1924
1925 let wrapper = wrappers.get(proto);
1926 if (wrapper == null) {
1927 wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto);
1928 wrappers.set(proto, wrapper);
1929 }
1930 return wrapper
1931}
1932
1933/**
1934 * Wrap a given event to management a dispatching.
1935 * @param {EventTarget} eventTarget The event target of this dispatching.
1936 * @param {Object} event The event to wrap.
1937 * @returns {Event} The wrapper instance.
1938 * @private
1939 */
1940function wrapEvent(eventTarget, event) {
1941 const Wrapper = getWrapper(Object.getPrototypeOf(event));
1942 return new Wrapper(eventTarget, event)
1943}
1944
1945/**
1946 * Get the immediateStopped flag of a given event.
1947 * @param {Event} event The event to get.
1948 * @returns {boolean} The flag to stop propagation immediately.
1949 * @private
1950 */
1951function isStopped(event) {
1952 return pd(event).immediateStopped
1953}
1954
1955/**
1956 * Set the current event phase of a given event.
1957 * @param {Event} event The event to set current target.
1958 * @param {number} eventPhase New event phase.
1959 * @returns {void}
1960 * @private
1961 */
1962function setEventPhase(event, eventPhase) {
1963 pd(event).eventPhase = eventPhase;
1964}
1965
1966/**
1967 * Set the current target of a given event.
1968 * @param {Event} event The event to set current target.
1969 * @param {EventTarget|null} currentTarget New current target.
1970 * @returns {void}
1971 * @private
1972 */
1973function setCurrentTarget(event, currentTarget) {
1974 pd(event).currentTarget = currentTarget;
1975}
1976
1977/**
1978 * Set a passive listener of a given event.
1979 * @param {Event} event The event to set current target.
1980 * @param {Function|null} passiveListener New passive listener.
1981 * @returns {void}
1982 * @private
1983 */
1984function setPassiveListener(event, passiveListener) {
1985 pd(event).passiveListener = passiveListener;
1986}
1987
1988/**
1989 * @typedef {object} ListenerNode
1990 * @property {Function} listener
1991 * @property {1|2|3} listenerType
1992 * @property {boolean} passive
1993 * @property {boolean} once
1994 * @property {ListenerNode|null} next
1995 * @private
1996 */
1997
1998/**
1999 * @type {WeakMap<object, Map<string, ListenerNode>>}
2000 * @private
2001 */
2002const listenersMap = new WeakMap();
2003
2004// Listener types
2005const CAPTURE = 1;
2006const BUBBLE = 2;
2007const ATTRIBUTE = 3;
2008
2009/**
2010 * Check whether a given value is an object or not.
2011 * @param {any} x The value to check.
2012 * @returns {boolean} `true` if the value is an object.
2013 */
2014function isObject(x) {
2015 return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax
2016}
2017
2018/**
2019 * Get listeners.
2020 * @param {EventTarget} eventTarget The event target to get.
2021 * @returns {Map<string, ListenerNode>} The listeners.
2022 * @private
2023 */
2024function getListeners(eventTarget) {
2025 const listeners = listenersMap.get(eventTarget);
2026 if (listeners == null) {
2027 throw new TypeError(
2028 "'this' is expected an EventTarget object, but got another value."
2029 )
2030 }
2031 return listeners
2032}
2033
2034/**
2035 * Get the property descriptor for the event attribute of a given event.
2036 * @param {string} eventName The event name to get property descriptor.
2037 * @returns {PropertyDescriptor} The property descriptor.
2038 * @private
2039 */
2040function defineEventAttributeDescriptor(eventName) {
2041 return {
2042 get() {
2043 const listeners = getListeners(this);
2044 let node = listeners.get(eventName);
2045 while (node != null) {
2046 if (node.listenerType === ATTRIBUTE) {
2047 return node.listener
2048 }
2049 node = node.next;
2050 }
2051 return null
2052 },
2053
2054 set(listener) {
2055 if (typeof listener !== "function" && !isObject(listener)) {
2056 listener = null; // eslint-disable-line no-param-reassign
2057 }
2058 const listeners = getListeners(this);
2059
2060 // Traverse to the tail while removing old value.
2061 let prev = null;
2062 let node = listeners.get(eventName);
2063 while (node != null) {
2064 if (node.listenerType === ATTRIBUTE) {
2065 // Remove old value.
2066 if (prev !== null) {
2067 prev.next = node.next;
2068 } else if (node.next !== null) {
2069 listeners.set(eventName, node.next);
2070 } else {
2071 listeners.delete(eventName);
2072 }
2073 } else {
2074 prev = node;
2075 }
2076
2077 node = node.next;
2078 }
2079
2080 // Add new value.
2081 if (listener !== null) {
2082 const newNode = {
2083 listener,
2084 listenerType: ATTRIBUTE,
2085 passive: false,
2086 once: false,
2087 next: null,
2088 };
2089 if (prev === null) {
2090 listeners.set(eventName, newNode);
2091 } else {
2092 prev.next = newNode;
2093 }
2094 }
2095 },
2096 configurable: true,
2097 enumerable: true,
2098 }
2099}
2100
2101/**
2102 * Define an event attribute (e.g. `eventTarget.onclick`).
2103 * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite.
2104 * @param {string} eventName The event name to define.
2105 * @returns {void}
2106 */
2107function defineEventAttribute(eventTargetPrototype, eventName) {
2108 Object.defineProperty(
2109 eventTargetPrototype,
2110 `on${eventName}`,
2111 defineEventAttributeDescriptor(eventName)
2112 );
2113}
2114
2115/**
2116 * Define a custom EventTarget with event attributes.
2117 * @param {string[]} eventNames Event names for event attributes.
2118 * @returns {EventTarget} The custom EventTarget.
2119 * @private
2120 */
2121function defineCustomEventTarget(eventNames) {
2122 /** CustomEventTarget */
2123 function CustomEventTarget() {
2124 EventTarget.call(this);
2125 }
2126
2127 CustomEventTarget.prototype = Object.create(EventTarget.prototype, {
2128 constructor: {
2129 value: CustomEventTarget,
2130 configurable: true,
2131 writable: true,
2132 },
2133 });
2134
2135 for (let i = 0; i < eventNames.length; ++i) {
2136 defineEventAttribute(CustomEventTarget.prototype, eventNames[i]);
2137 }
2138
2139 return CustomEventTarget
2140}
2141
2142/**
2143 * EventTarget.
2144 *
2145 * - This is constructor if no arguments.
2146 * - This is a function which returns a CustomEventTarget constructor if there are arguments.
2147 *
2148 * For example:
2149 *
2150 * class A extends EventTarget {}
2151 * class B extends EventTarget("message") {}
2152 * class C extends EventTarget("message", "error") {}
2153 * class D extends EventTarget(["message", "error"]) {}
2154 */
2155function EventTarget() {
2156 /*eslint-disable consistent-return */
2157 if (this instanceof EventTarget) {
2158 listenersMap.set(this, new Map());
2159 return
2160 }
2161 if (arguments.length === 1 && Array.isArray(arguments[0])) {
2162 return defineCustomEventTarget(arguments[0])
2163 }
2164 if (arguments.length > 0) {
2165 const types = new Array(arguments.length);
2166 for (let i = 0; i < arguments.length; ++i) {
2167 types[i] = arguments[i];
2168 }
2169 return defineCustomEventTarget(types)
2170 }
2171 throw new TypeError("Cannot call a class as a function")
2172 /*eslint-enable consistent-return */
2173}
2174
2175// Should be enumerable, but class methods are not enumerable.
2176EventTarget.prototype = {
2177 /**
2178 * Add a given listener to this event target.
2179 * @param {string} eventName The event name to add.
2180 * @param {Function} listener The listener to add.
2181 * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.
2182 * @returns {void}
2183 */
2184 addEventListener(eventName, listener, options) {
2185 if (listener == null) {
2186 return
2187 }
2188 if (typeof listener !== "function" && !isObject(listener)) {
2189 throw new TypeError("'listener' should be a function or an object.")
2190 }
2191
2192 const listeners = getListeners(this);
2193 const optionsIsObj = isObject(options);
2194 const capture = optionsIsObj
2195 ? Boolean(options.capture)
2196 : Boolean(options);
2197 const listenerType = capture ? CAPTURE : BUBBLE;
2198 const newNode = {
2199 listener,
2200 listenerType,
2201 passive: optionsIsObj && Boolean(options.passive),
2202 once: optionsIsObj && Boolean(options.once),
2203 next: null,
2204 };
2205
2206 // Set it as the first node if the first node is null.
2207 let node = listeners.get(eventName);
2208 if (node === undefined) {
2209 listeners.set(eventName, newNode);
2210 return
2211 }
2212
2213 // Traverse to the tail while checking duplication..
2214 let prev = null;
2215 while (node != null) {
2216 if (
2217 node.listener === listener &&
2218 node.listenerType === listenerType
2219 ) {
2220 // Should ignore duplication.
2221 return
2222 }
2223 prev = node;
2224 node = node.next;
2225 }
2226
2227 // Add it.
2228 prev.next = newNode;
2229 },
2230
2231 /**
2232 * Remove a given listener from this event target.
2233 * @param {string} eventName The event name to remove.
2234 * @param {Function} listener The listener to remove.
2235 * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.
2236 * @returns {void}
2237 */
2238 removeEventListener(eventName, listener, options) {
2239 if (listener == null) {
2240 return
2241 }
2242
2243 const listeners = getListeners(this);
2244 const capture = isObject(options)
2245 ? Boolean(options.capture)
2246 : Boolean(options);
2247 const listenerType = capture ? CAPTURE : BUBBLE;
2248
2249 let prev = null;
2250 let node = listeners.get(eventName);
2251 while (node != null) {
2252 if (
2253 node.listener === listener &&
2254 node.listenerType === listenerType
2255 ) {
2256 if (prev !== null) {
2257 prev.next = node.next;
2258 } else if (node.next !== null) {
2259 listeners.set(eventName, node.next);
2260 } else {
2261 listeners.delete(eventName);
2262 }
2263 return
2264 }
2265
2266 prev = node;
2267 node = node.next;
2268 }
2269 },
2270
2271 /**
2272 * Dispatch a given event.
2273 * @param {Event|{type:string}} event The event to dispatch.
2274 * @returns {boolean} `false` if canceled.
2275 */
2276 dispatchEvent(event) {
2277 if (event == null || typeof event.type !== "string") {
2278 throw new TypeError('"event.type" should be a string.')
2279 }
2280
2281 // If listeners aren't registered, terminate.
2282 const listeners = getListeners(this);
2283 const eventName = event.type;
2284 let node = listeners.get(eventName);
2285 if (node == null) {
2286 return true
2287 }
2288
2289 // Since we cannot rewrite several properties, so wrap object.
2290 const wrappedEvent = wrapEvent(this, event);
2291
2292 // This doesn't process capturing phase and bubbling phase.
2293 // This isn't participating in a tree.
2294 let prev = null;
2295 while (node != null) {
2296 // Remove this listener if it's once
2297 if (node.once) {
2298 if (prev !== null) {
2299 prev.next = node.next;
2300 } else if (node.next !== null) {
2301 listeners.set(eventName, node.next);
2302 } else {
2303 listeners.delete(eventName);
2304 }
2305 } else {
2306 prev = node;
2307 }
2308
2309 // Call this listener
2310 setPassiveListener(
2311 wrappedEvent,
2312 node.passive ? node.listener : null
2313 );
2314 if (typeof node.listener === "function") {
2315 try {
2316 node.listener.call(this, wrappedEvent);
2317 } catch (err) {
2318 if (
2319 typeof console !== "undefined" &&
2320 typeof console.error === "function"
2321 ) {
2322 console.error(err);
2323 }
2324 }
2325 } else if (
2326 node.listenerType !== ATTRIBUTE &&
2327 typeof node.listener.handleEvent === "function"
2328 ) {
2329 node.listener.handleEvent(wrappedEvent);
2330 }
2331
2332 // Break if `event.stopImmediatePropagation` was called.
2333 if (isStopped(wrappedEvent)) {
2334 break
2335 }
2336
2337 node = node.next;
2338 }
2339 setPassiveListener(wrappedEvent, null);
2340 setEventPhase(wrappedEvent, 0);
2341 setCurrentTarget(wrappedEvent, null);
2342
2343 return !wrappedEvent.defaultPrevented
2344 },
2345};
2346
2347// `constructor` is not enumerable.
2348Object.defineProperty(EventTarget.prototype, "constructor", {
2349 value: EventTarget,
2350 configurable: true,
2351 writable: true,
2352});
2353
2354// Ensure `eventTarget instanceof window.EventTarget` is `true`.
2355if (
2356 typeof window !== "undefined" &&
2357 typeof window.EventTarget !== "undefined"
2358) {
2359 Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype);
2360}
2361
2362/**
2363 * @author Toru Nagashima <https://github.com/mysticatea>
2364 * See LICENSE file in root directory for full license.
2365 */
2366
2367/**
2368 * The signal class.
2369 * @see https://dom.spec.whatwg.org/#abortsignal
2370 */
2371class AbortSignal extends EventTarget {
2372 /**
2373 * AbortSignal cannot be constructed directly.
2374 */
2375 constructor() {
2376 super();
2377 throw new TypeError("AbortSignal cannot be constructed directly");
2378 }
2379 /**
2380 * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise.
2381 */
2382 get aborted() {
2383 const aborted = abortedFlags.get(this);
2384 if (typeof aborted !== "boolean") {
2385 throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`);
2386 }
2387 return aborted;
2388 }
2389}
2390defineEventAttribute(AbortSignal.prototype, "abort");
2391/**
2392 * Create an AbortSignal object.
2393 */
2394function createAbortSignal() {
2395 const signal = Object.create(AbortSignal.prototype);
2396 EventTarget.call(signal);
2397 abortedFlags.set(signal, false);
2398 return signal;
2399}
2400/**
2401 * Abort a given signal.
2402 */
2403function abortSignal(signal) {
2404 if (abortedFlags.get(signal) !== false) {
2405 return;
2406 }
2407 abortedFlags.set(signal, true);
2408 signal.dispatchEvent({ type: "abort" });
2409}
2410/**
2411 * Aborted flag for each instances.
2412 */
2413const abortedFlags = new WeakMap();
2414// Properties should be enumerable.
2415Object.defineProperties(AbortSignal.prototype, {
2416 aborted: { enumerable: true },
2417});
2418// `toString()` should return `"[object AbortSignal]"`
2419if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") {
2420 Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, {
2421 configurable: true,
2422 value: "AbortSignal",
2423 });
2424}
2425
2426/**
2427 * The AbortController.
2428 * @see https://dom.spec.whatwg.org/#abortcontroller
2429 */
2430class AbortController {
2431 /**
2432 * Initialize this controller.
2433 */
2434 constructor() {
2435 signals.set(this, createAbortSignal());
2436 }
2437 /**
2438 * Returns the `AbortSignal` object associated with this object.
2439 */
2440 get signal() {
2441 return getSignal(this);
2442 }
2443 /**
2444 * Abort and signal to any observers that the associated activity is to be aborted.
2445 */
2446 abort() {
2447 abortSignal(getSignal(this));
2448 }
2449}
2450/**
2451 * Associated signals.
2452 */
2453const signals = new WeakMap();
2454/**
2455 * Get the associated signal of a given controller.
2456 */
2457function getSignal(controller) {
2458 const signal = signals.get(controller);
2459 if (signal == null) {
2460 throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`);
2461 }
2462 return signal;
2463}
2464// Properties should be enumerable.
2465Object.defineProperties(AbortController.prototype, {
2466 signal: { enumerable: true },
2467 abort: { enumerable: true },
2468});
2469if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") {
2470 Object.defineProperty(AbortController.prototype, Symbol.toStringTag, {
2471 configurable: true,
2472 value: "AbortController",
2473 });
2474}
2475
2476// Copyright (c) Microsoft Corporation. All rights reserved.
2477var RestError = /** @class */ (function (_super) {
2478 tslib.__extends(RestError, _super);
2479 function RestError(message, code, statusCode, request, response, body) {
2480 var _this = _super.call(this, message) || this;
2481 _this.code = code;
2482 _this.statusCode = statusCode;
2483 _this.request = request;
2484 _this.response = response;
2485 _this.body = body;
2486 Object.setPrototypeOf(_this, RestError.prototype);
2487 return _this;
2488 }
2489 RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR";
2490 RestError.REQUEST_ABORTED_ERROR = "REQUEST_ABORTED_ERROR";
2491 RestError.PARSE_ERROR = "PARSE_ERROR";
2492 return RestError;
2493}(Error));
2494
2495// Copyright (c) Microsoft Corporation. All rights reserved.
2496var FetchHttpClient = /** @class */ (function () {
2497 function FetchHttpClient() {
2498 }
2499 FetchHttpClient.prototype.sendRequest = function (httpRequest) {
2500 return tslib.__awaiter(this, void 0, void 0, function () {
2501 var abortController, abortListener, formData, requestForm_1, appendFormValue, _i, _a, formKey, formValue, j, contentType, body, loadedBytes_1, uploadReportStream, platformSpecificRequestInit, requestInit, operationResponse, response, headers, _b, _c, onDownloadProgress_1, responseBody, loadedBytes_2, downloadReportStream, length_1, error_1, fetchError, uploadStreamDone, downloadStreamDone;
2502 return tslib.__generator(this, function (_d) {
2503 switch (_d.label) {
2504 case 0:
2505 if (!httpRequest && typeof httpRequest !== "object") {
2506 throw new Error("'httpRequest' (WebResource) cannot be null or undefined and must be of type object.");
2507 }
2508 abortController = new AbortController();
2509 if (httpRequest.abortSignal) {
2510 if (httpRequest.abortSignal.aborted) {
2511 throw new RestError("The request was aborted", RestError.REQUEST_ABORTED_ERROR, undefined, httpRequest);
2512 }
2513 abortListener = function (event) {
2514 if (event.type === "abort") {
2515 abortController.abort();
2516 }
2517 };
2518 httpRequest.abortSignal.addEventListener("abort", abortListener);
2519 }
2520 if (httpRequest.timeout) {
2521 setTimeout(function () {
2522 abortController.abort();
2523 }, httpRequest.timeout);
2524 }
2525 if (httpRequest.formData) {
2526 formData = httpRequest.formData;
2527 requestForm_1 = new FormData();
2528 appendFormValue = function (key, value) {
2529 // value function probably returns a stream so we can provide a fresh stream on each retry
2530 if (typeof value === "function") {
2531 value = value();
2532 }
2533 if (value && value.hasOwnProperty("value") && value.hasOwnProperty("options")) {
2534 requestForm_1.append(key, value.value, value.options);
2535 }
2536 else {
2537 requestForm_1.append(key, value);
2538 }
2539 };
2540 for (_i = 0, _a = Object.keys(formData); _i < _a.length; _i++) {
2541 formKey = _a[_i];
2542 formValue = formData[formKey];
2543 if (Array.isArray(formValue)) {
2544 for (j = 0; j < formValue.length; j++) {
2545 appendFormValue(formKey, formValue[j]);
2546 }
2547 }
2548 else {
2549 appendFormValue(formKey, formValue);
2550 }
2551 }
2552 httpRequest.body = requestForm_1;
2553 httpRequest.formData = undefined;
2554 contentType = httpRequest.headers.get("Content-Type");
2555 if (contentType && contentType.indexOf("multipart/form-data") !== -1) {
2556 if (typeof requestForm_1.getBoundary === "function") {
2557 httpRequest.headers.set("Content-Type", "multipart/form-data; boundary=" + requestForm_1.getBoundary());
2558 }
2559 else {
2560 // browser will automatically apply a suitable content-type header
2561 httpRequest.headers.remove("Content-Type");
2562 }
2563 }
2564 }
2565 body = httpRequest.body
2566 ? typeof httpRequest.body === "function"
2567 ? httpRequest.body()
2568 : httpRequest.body
2569 : undefined;
2570 if (httpRequest.onUploadProgress && httpRequest.body) {
2571 loadedBytes_1 = 0;
2572 uploadReportStream = new stream.Transform({
2573 transform: function (chunk, _encoding, callback) {
2574 loadedBytes_1 += chunk.length;
2575 httpRequest.onUploadProgress({ loadedBytes: loadedBytes_1 });
2576 callback(undefined, chunk);
2577 },
2578 });
2579 if (isReadableStream(body)) {
2580 body.pipe(uploadReportStream);
2581 }
2582 else {
2583 uploadReportStream.end(body);
2584 }
2585 body = uploadReportStream;
2586 }
2587 return [4 /*yield*/, this.prepareRequest(httpRequest)];
2588 case 1:
2589 platformSpecificRequestInit = _d.sent();
2590 requestInit = tslib.__assign({ body: body, headers: httpRequest.headers.rawHeaders(), method: httpRequest.method, signal: abortController.signal, redirect: "manual" }, platformSpecificRequestInit);
2591 _d.label = 2;
2592 case 2:
2593 _d.trys.push([2, 8, 9, 10]);
2594 return [4 /*yield*/, this.fetch(httpRequest.url, requestInit)];
2595 case 3:
2596 response = _d.sent();
2597 headers = parseHeaders(response.headers);
2598 _b = {
2599 headers: headers,
2600 request: httpRequest,
2601 status: response.status,
2602 readableStreamBody: httpRequest.streamResponseBody
2603 ? response.body
2604 : undefined
2605 };
2606 if (!!httpRequest.streamResponseBody) return [3 /*break*/, 5];
2607 return [4 /*yield*/, response.text()];
2608 case 4:
2609 _c = _d.sent();
2610 return [3 /*break*/, 6];
2611 case 5:
2612 _c = undefined;
2613 _d.label = 6;
2614 case 6:
2615 operationResponse = (_b.bodyAsText = _c,
2616 _b.redirected = response.redirected,
2617 _b.url = response.url,
2618 _b);
2619 onDownloadProgress_1 = httpRequest.onDownloadProgress;
2620 if (onDownloadProgress_1) {
2621 responseBody = response.body || undefined;
2622 if (isReadableStream(responseBody)) {
2623 loadedBytes_2 = 0;
2624 downloadReportStream = new stream.Transform({
2625 transform: function (chunk, _encoding, callback) {
2626 loadedBytes_2 += chunk.length;
2627 onDownloadProgress_1({ loadedBytes: loadedBytes_2 });
2628 callback(undefined, chunk);
2629 },
2630 });
2631 responseBody.pipe(downloadReportStream);
2632 operationResponse.readableStreamBody = downloadReportStream;
2633 }
2634 else {
2635 length_1 = parseInt(headers.get("Content-Length")) || undefined;
2636 if (length_1) {
2637 // Calling callback for non-stream response for consistency with browser
2638 onDownloadProgress_1({ loadedBytes: length_1 });
2639 }
2640 }
2641 }
2642 return [4 /*yield*/, this.processRequest(operationResponse)];
2643 case 7:
2644 _d.sent();
2645 return [2 /*return*/, operationResponse];
2646 case 8:
2647 error_1 = _d.sent();
2648 fetchError = error_1;
2649 if (fetchError.code === "ENOTFOUND") {
2650 throw new RestError(fetchError.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest);
2651 }
2652 else if (fetchError.type === "aborted") {
2653 throw new RestError("The request was aborted", RestError.REQUEST_ABORTED_ERROR, undefined, httpRequest);
2654 }
2655 throw fetchError;
2656 case 9:
2657 // clean up event listener
2658 if (httpRequest.abortSignal && abortListener) {
2659 uploadStreamDone = Promise.resolve();
2660 if (isReadableStream(body)) {
2661 uploadStreamDone = isStreamComplete(body);
2662 }
2663 downloadStreamDone = Promise.resolve();
2664 if (isReadableStream(operationResponse === null || operationResponse === void 0 ? void 0 : operationResponse.readableStreamBody)) {
2665 downloadStreamDone = isStreamComplete(operationResponse.readableStreamBody);
2666 }
2667 Promise.all([uploadStreamDone, downloadStreamDone])
2668 .then(function () {
2669 var _a;
2670 (_a = httpRequest.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener);
2671 return;
2672 })
2673 .catch(function (_e) { });
2674 }
2675 return [7 /*endfinally*/];
2676 case 10: return [2 /*return*/];
2677 }
2678 });
2679 });
2680 };
2681 return FetchHttpClient;
2682}());
2683function isReadableStream(body) {
2684 return body && typeof body.pipe === "function";
2685}
2686function isStreamComplete(stream) {
2687 return new Promise(function (resolve) {
2688 stream.on("close", resolve);
2689 stream.on("end", resolve);
2690 stream.on("error", resolve);
2691 });
2692}
2693function parseHeaders(headers) {
2694 var httpHeaders = new HttpHeaders();
2695 headers.forEach(function (value, key) {
2696 httpHeaders.set(key, value);
2697 });
2698 return httpHeaders;
2699}
2700
2701// Copyright (c) Microsoft Corporation. All rights reserved.
2702/**
2703 * A class that handles the query portion of a URLBuilder.
2704 */
2705var URLQuery = /** @class */ (function () {
2706 function URLQuery() {
2707 this._rawQuery = {};
2708 }
2709 /**
2710 * Get whether or not there any query parameters in this URLQuery.
2711 */
2712 URLQuery.prototype.any = function () {
2713 return Object.keys(this._rawQuery).length > 0;
2714 };
2715 /**
2716 * Set a query parameter with the provided name and value. If the parameterValue is undefined or
2717 * empty, then this will attempt to remove an existing query parameter with the provided
2718 * parameterName.
2719 */
2720 URLQuery.prototype.set = function (parameterName, parameterValue) {
2721 if (parameterName) {
2722 if (parameterValue != undefined) {
2723 var newValue = Array.isArray(parameterValue) ? parameterValue : parameterValue.toString();
2724 this._rawQuery[parameterName] = newValue;
2725 }
2726 else {
2727 delete this._rawQuery[parameterName];
2728 }
2729 }
2730 };
2731 /**
2732 * Get the value of the query parameter with the provided name. If no parameter exists with the
2733 * provided parameter name, then undefined will be returned.
2734 */
2735 URLQuery.prototype.get = function (parameterName) {
2736 return parameterName ? this._rawQuery[parameterName] : undefined;
2737 };
2738 /**
2739 * Get the string representation of this query. The return value will not start with a "?".
2740 */
2741 URLQuery.prototype.toString = function () {
2742 var result = "";
2743 for (var parameterName in this._rawQuery) {
2744 if (result) {
2745 result += "&";
2746 }
2747 var parameterValue = this._rawQuery[parameterName];
2748 if (Array.isArray(parameterValue)) {
2749 var parameterStrings = [];
2750 for (var _i = 0, parameterValue_1 = parameterValue; _i < parameterValue_1.length; _i++) {
2751 var parameterValueElement = parameterValue_1[_i];
2752 parameterStrings.push(parameterName + "=" + parameterValueElement);
2753 }
2754 result += parameterStrings.join("&");
2755 }
2756 else {
2757 result += parameterName + "=" + parameterValue;
2758 }
2759 }
2760 return result;
2761 };
2762 /**
2763 * Parse a URLQuery from the provided text.
2764 */
2765 URLQuery.parse = function (text) {
2766 var result = new URLQuery();
2767 if (text) {
2768 if (text.startsWith("?")) {
2769 text = text.substring(1);
2770 }
2771 var currentState = "ParameterName";
2772 var parameterName = "";
2773 var parameterValue = "";
2774 for (var i = 0; i < text.length; ++i) {
2775 var currentCharacter = text[i];
2776 switch (currentState) {
2777 case "ParameterName":
2778 switch (currentCharacter) {
2779 case "=":
2780 currentState = "ParameterValue";
2781 break;
2782 case "&":
2783 parameterName = "";
2784 parameterValue = "";
2785 break;
2786 default:
2787 parameterName += currentCharacter;
2788 break;
2789 }
2790 break;
2791 case "ParameterValue":
2792 switch (currentCharacter) {
2793 case "&":
2794 result.set(parameterName, parameterValue);
2795 parameterName = "";
2796 parameterValue = "";
2797 currentState = "ParameterName";
2798 break;
2799 default:
2800 parameterValue += currentCharacter;
2801 break;
2802 }
2803 break;
2804 default:
2805 throw new Error("Unrecognized URLQuery parse state: " + currentState);
2806 }
2807 }
2808 if (currentState === "ParameterValue") {
2809 result.set(parameterName, parameterValue);
2810 }
2811 }
2812 return result;
2813 };
2814 return URLQuery;
2815}());
2816/**
2817 * A class that handles creating, modifying, and parsing URLs.
2818 */
2819var URLBuilder = /** @class */ (function () {
2820 function URLBuilder() {
2821 }
2822 /**
2823 * Set the scheme/protocol for this URL. If the provided scheme contains other parts of a URL
2824 * (such as a host, port, path, or query), those parts will be added to this URL as well.
2825 */
2826 URLBuilder.prototype.setScheme = function (scheme) {
2827 if (!scheme) {
2828 this._scheme = undefined;
2829 }
2830 else {
2831 this.set(scheme, "SCHEME");
2832 }
2833 };
2834 /**
2835 * Get the scheme that has been set in this URL.
2836 */
2837 URLBuilder.prototype.getScheme = function () {
2838 return this._scheme;
2839 };
2840 /**
2841 * Set the host for this URL. If the provided host contains other parts of a URL (such as a
2842 * port, path, or query), those parts will be added to this URL as well.
2843 */
2844 URLBuilder.prototype.setHost = function (host) {
2845 if (!host) {
2846 this._host = undefined;
2847 }
2848 else {
2849 this.set(host, "SCHEME_OR_HOST");
2850 }
2851 };
2852 /**
2853 * Get the host that has been set in this URL.
2854 */
2855 URLBuilder.prototype.getHost = function () {
2856 return this._host;
2857 };
2858 /**
2859 * Set the port for this URL. If the provided port contains other parts of a URL (such as a
2860 * path or query), those parts will be added to this URL as well.
2861 */
2862 URLBuilder.prototype.setPort = function (port) {
2863 if (port == undefined || port === "") {
2864 this._port = undefined;
2865 }
2866 else {
2867 this.set(port.toString(), "PORT");
2868 }
2869 };
2870 /**
2871 * Get the port that has been set in this URL.
2872 */
2873 URLBuilder.prototype.getPort = function () {
2874 return this._port;
2875 };
2876 /**
2877 * Set the path for this URL. If the provided path contains a query, then it will be added to
2878 * this URL as well.
2879 */
2880 URLBuilder.prototype.setPath = function (path) {
2881 if (!path) {
2882 this._path = undefined;
2883 }
2884 else {
2885 var schemeIndex = path.indexOf("://");
2886 if (schemeIndex !== -1) {
2887 var schemeStart = path.lastIndexOf("/", schemeIndex);
2888 // Make sure to only grab the URL part of the path before setting the state back to SCHEME
2889 // this will handle cases such as "/a/b/c/https://microsoft.com" => "https://microsoft.com"
2890 this.set(schemeStart === -1 ? path : path.substr(schemeStart + 1), "SCHEME");
2891 }
2892 else {
2893 this.set(path, "PATH");
2894 }
2895 }
2896 };
2897 /**
2898 * Append the provided path to this URL's existing path. If the provided path contains a query,
2899 * then it will be added to this URL as well.
2900 */
2901 URLBuilder.prototype.appendPath = function (path) {
2902 if (path) {
2903 var currentPath = this.getPath();
2904 if (currentPath) {
2905 if (!currentPath.endsWith("/")) {
2906 currentPath += "/";
2907 }
2908 if (path.startsWith("/")) {
2909 path = path.substring(1);
2910 }
2911 path = currentPath + path;
2912 }
2913 this.set(path, "PATH");
2914 }
2915 };
2916 /**
2917 * Get the path that has been set in this URL.
2918 */
2919 URLBuilder.prototype.getPath = function () {
2920 return this._path;
2921 };
2922 /**
2923 * Set the query in this URL.
2924 */
2925 URLBuilder.prototype.setQuery = function (query) {
2926 if (!query) {
2927 this._query = undefined;
2928 }
2929 else {
2930 this._query = URLQuery.parse(query);
2931 }
2932 };
2933 /**
2934 * Set a query parameter with the provided name and value in this URL's query. If the provided
2935 * query parameter value is undefined or empty, then the query parameter will be removed if it
2936 * existed.
2937 */
2938 URLBuilder.prototype.setQueryParameter = function (queryParameterName, queryParameterValue) {
2939 if (queryParameterName) {
2940 if (!this._query) {
2941 this._query = new URLQuery();
2942 }
2943 this._query.set(queryParameterName, queryParameterValue);
2944 }
2945 };
2946 /**
2947 * Get the value of the query parameter with the provided query parameter name. If no query
2948 * parameter exists with the provided name, then undefined will be returned.
2949 */
2950 URLBuilder.prototype.getQueryParameterValue = function (queryParameterName) {
2951 return this._query ? this._query.get(queryParameterName) : undefined;
2952 };
2953 /**
2954 * Get the query in this URL.
2955 */
2956 URLBuilder.prototype.getQuery = function () {
2957 return this._query ? this._query.toString() : undefined;
2958 };
2959 /**
2960 * Set the parts of this URL by parsing the provided text using the provided startState.
2961 */
2962 URLBuilder.prototype.set = function (text, startState) {
2963 var tokenizer = new URLTokenizer(text, startState);
2964 while (tokenizer.next()) {
2965 var token = tokenizer.current();
2966 if (token) {
2967 switch (token.type) {
2968 case "SCHEME":
2969 this._scheme = token.text || undefined;
2970 break;
2971 case "HOST":
2972 this._host = token.text || undefined;
2973 break;
2974 case "PORT":
2975 this._port = token.text || undefined;
2976 break;
2977 case "PATH":
2978 var tokenPath = token.text || undefined;
2979 if (!this._path || this._path === "/" || tokenPath !== "/") {
2980 this._path = tokenPath;
2981 }
2982 break;
2983 case "QUERY":
2984 this._query = URLQuery.parse(token.text);
2985 break;
2986 default:
2987 throw new Error("Unrecognized URLTokenType: " + token.type);
2988 }
2989 }
2990 }
2991 };
2992 URLBuilder.prototype.toString = function () {
2993 var result = "";
2994 if (this._scheme) {
2995 result += this._scheme + "://";
2996 }
2997 if (this._host) {
2998 result += this._host;
2999 }
3000 if (this._port) {
3001 result += ":" + this._port;
3002 }
3003 if (this._path) {
3004 if (!this._path.startsWith("/")) {
3005 result += "/";
3006 }
3007 result += this._path;
3008 }
3009 if (this._query && this._query.any()) {
3010 result += "?" + this._query.toString();
3011 }
3012 return result;
3013 };
3014 /**
3015 * If the provided searchValue is found in this URLBuilder, then replace it with the provided
3016 * replaceValue.
3017 */
3018 URLBuilder.prototype.replaceAll = function (searchValue, replaceValue) {
3019 if (searchValue) {
3020 this.setScheme(replaceAll(this.getScheme(), searchValue, replaceValue));
3021 this.setHost(replaceAll(this.getHost(), searchValue, replaceValue));
3022 this.setPort(replaceAll(this.getPort(), searchValue, replaceValue));
3023 this.setPath(replaceAll(this.getPath(), searchValue, replaceValue));
3024 this.setQuery(replaceAll(this.getQuery(), searchValue, replaceValue));
3025 }
3026 };
3027 URLBuilder.parse = function (text) {
3028 var result = new URLBuilder();
3029 result.set(text, "SCHEME_OR_HOST");
3030 return result;
3031 };
3032 return URLBuilder;
3033}());
3034var URLToken = /** @class */ (function () {
3035 function URLToken(text, type) {
3036 this.text = text;
3037 this.type = type;
3038 }
3039 URLToken.scheme = function (text) {
3040 return new URLToken(text, "SCHEME");
3041 };
3042 URLToken.host = function (text) {
3043 return new URLToken(text, "HOST");
3044 };
3045 URLToken.port = function (text) {
3046 return new URLToken(text, "PORT");
3047 };
3048 URLToken.path = function (text) {
3049 return new URLToken(text, "PATH");
3050 };
3051 URLToken.query = function (text) {
3052 return new URLToken(text, "QUERY");
3053 };
3054 return URLToken;
3055}());
3056/**
3057 * Get whether or not the provided character (single character string) is an alphanumeric (letter or
3058 * digit) character.
3059 */
3060function isAlphaNumericCharacter(character) {
3061 var characterCode = character.charCodeAt(0);
3062 return ((48 /* '0' */ <= characterCode && characterCode <= 57) /* '9' */ ||
3063 (65 /* 'A' */ <= characterCode && characterCode <= 90) /* 'Z' */ ||
3064 (97 /* 'a' */ <= characterCode && characterCode <= 122) /* 'z' */);
3065}
3066/**
3067 * A class that tokenizes URL strings.
3068 */
3069var URLTokenizer = /** @class */ (function () {
3070 function URLTokenizer(_text, state) {
3071 this._text = _text;
3072 this._textLength = _text ? _text.length : 0;
3073 this._currentState = state != undefined ? state : "SCHEME_OR_HOST";
3074 this._currentIndex = 0;
3075 }
3076 /**
3077 * Get the current URLToken this URLTokenizer is pointing at, or undefined if the URLTokenizer
3078 * hasn't started or has finished tokenizing.
3079 */
3080 URLTokenizer.prototype.current = function () {
3081 return this._currentToken;
3082 };
3083 /**
3084 * Advance to the next URLToken and return whether or not a URLToken was found.
3085 */
3086 URLTokenizer.prototype.next = function () {
3087 if (!hasCurrentCharacter(this)) {
3088 this._currentToken = undefined;
3089 }
3090 else {
3091 switch (this._currentState) {
3092 case "SCHEME":
3093 nextScheme(this);
3094 break;
3095 case "SCHEME_OR_HOST":
3096 nextSchemeOrHost(this);
3097 break;
3098 case "HOST":
3099 nextHost(this);
3100 break;
3101 case "PORT":
3102 nextPort(this);
3103 break;
3104 case "PATH":
3105 nextPath(this);
3106 break;
3107 case "QUERY":
3108 nextQuery(this);
3109 break;
3110 default:
3111 throw new Error("Unrecognized URLTokenizerState: " + this._currentState);
3112 }
3113 }
3114 return !!this._currentToken;
3115 };
3116 return URLTokenizer;
3117}());
3118/**
3119 * Read the remaining characters from this Tokenizer's character stream.
3120 */
3121function readRemaining(tokenizer) {
3122 var result = "";
3123 if (tokenizer._currentIndex < tokenizer._textLength) {
3124 result = tokenizer._text.substring(tokenizer._currentIndex);
3125 tokenizer._currentIndex = tokenizer._textLength;
3126 }
3127 return result;
3128}
3129/**
3130 * Whether or not this URLTokenizer has a current character.
3131 */
3132function hasCurrentCharacter(tokenizer) {
3133 return tokenizer._currentIndex < tokenizer._textLength;
3134}
3135/**
3136 * Get the character in the text string at the current index.
3137 */
3138function getCurrentCharacter(tokenizer) {
3139 return tokenizer._text[tokenizer._currentIndex];
3140}
3141/**
3142 * Advance to the character in text that is "step" characters ahead. If no step value is provided,
3143 * then step will default to 1.
3144 */
3145function nextCharacter(tokenizer, step) {
3146 if (hasCurrentCharacter(tokenizer)) {
3147 if (!step) {
3148 step = 1;
3149 }
3150 tokenizer._currentIndex += step;
3151 }
3152}
3153/**
3154 * Starting with the current character, peek "charactersToPeek" number of characters ahead in this
3155 * Tokenizer's stream of characters.
3156 */
3157function peekCharacters(tokenizer, charactersToPeek) {
3158 var endIndex = tokenizer._currentIndex + charactersToPeek;
3159 if (tokenizer._textLength < endIndex) {
3160 endIndex = tokenizer._textLength;
3161 }
3162 return tokenizer._text.substring(tokenizer._currentIndex, endIndex);
3163}
3164/**
3165 * Read characters from this Tokenizer until the end of the stream or until the provided condition
3166 * is false when provided the current character.
3167 */
3168function readWhile(tokenizer, condition) {
3169 var result = "";
3170 while (hasCurrentCharacter(tokenizer)) {
3171 var currentCharacter = getCurrentCharacter(tokenizer);
3172 if (!condition(currentCharacter)) {
3173 break;
3174 }
3175 else {
3176 result += currentCharacter;
3177 nextCharacter(tokenizer);
3178 }
3179 }
3180 return result;
3181}
3182/**
3183 * Read characters from this Tokenizer until a non-alphanumeric character or the end of the
3184 * character stream is reached.
3185 */
3186function readWhileLetterOrDigit(tokenizer) {
3187 return readWhile(tokenizer, function (character) { return isAlphaNumericCharacter(character); });
3188}
3189/**
3190 * Read characters from this Tokenizer until one of the provided terminating characters is read or
3191 * the end of the character stream is reached.
3192 */
3193function readUntilCharacter(tokenizer) {
3194 var terminatingCharacters = [];
3195 for (var _i = 1; _i < arguments.length; _i++) {
3196 terminatingCharacters[_i - 1] = arguments[_i];
3197 }
3198 return readWhile(tokenizer, function (character) { return terminatingCharacters.indexOf(character) === -1; });
3199}
3200function nextScheme(tokenizer) {
3201 var scheme = readWhileLetterOrDigit(tokenizer);
3202 tokenizer._currentToken = URLToken.scheme(scheme);
3203 if (!hasCurrentCharacter(tokenizer)) {
3204 tokenizer._currentState = "DONE";
3205 }
3206 else {
3207 tokenizer._currentState = "HOST";
3208 }
3209}
3210function nextSchemeOrHost(tokenizer) {
3211 var schemeOrHost = readUntilCharacter(tokenizer, ":", "/", "?");
3212 if (!hasCurrentCharacter(tokenizer)) {
3213 tokenizer._currentToken = URLToken.host(schemeOrHost);
3214 tokenizer._currentState = "DONE";
3215 }
3216 else if (getCurrentCharacter(tokenizer) === ":") {
3217 if (peekCharacters(tokenizer, 3) === "://") {
3218 tokenizer._currentToken = URLToken.scheme(schemeOrHost);
3219 tokenizer._currentState = "HOST";
3220 }
3221 else {
3222 tokenizer._currentToken = URLToken.host(schemeOrHost);
3223 tokenizer._currentState = "PORT";
3224 }
3225 }
3226 else {
3227 tokenizer._currentToken = URLToken.host(schemeOrHost);
3228 if (getCurrentCharacter(tokenizer) === "/") {
3229 tokenizer._currentState = "PATH";
3230 }
3231 else {
3232 tokenizer._currentState = "QUERY";
3233 }
3234 }
3235}
3236function nextHost(tokenizer) {
3237 if (peekCharacters(tokenizer, 3) === "://") {
3238 nextCharacter(tokenizer, 3);
3239 }
3240 var host = readUntilCharacter(tokenizer, ":", "/", "?");
3241 tokenizer._currentToken = URLToken.host(host);
3242 if (!hasCurrentCharacter(tokenizer)) {
3243 tokenizer._currentState = "DONE";
3244 }
3245 else if (getCurrentCharacter(tokenizer) === ":") {
3246 tokenizer._currentState = "PORT";
3247 }
3248 else if (getCurrentCharacter(tokenizer) === "/") {
3249 tokenizer._currentState = "PATH";
3250 }
3251 else {
3252 tokenizer._currentState = "QUERY";
3253 }
3254}
3255function nextPort(tokenizer) {
3256 if (getCurrentCharacter(tokenizer) === ":") {
3257 nextCharacter(tokenizer);
3258 }
3259 var port = readUntilCharacter(tokenizer, "/", "?");
3260 tokenizer._currentToken = URLToken.port(port);
3261 if (!hasCurrentCharacter(tokenizer)) {
3262 tokenizer._currentState = "DONE";
3263 }
3264 else if (getCurrentCharacter(tokenizer) === "/") {
3265 tokenizer._currentState = "PATH";
3266 }
3267 else {
3268 tokenizer._currentState = "QUERY";
3269 }
3270}
3271function nextPath(tokenizer) {
3272 var path = readUntilCharacter(tokenizer, "?");
3273 tokenizer._currentToken = URLToken.path(path);
3274 if (!hasCurrentCharacter(tokenizer)) {
3275 tokenizer._currentState = "DONE";
3276 }
3277 else {
3278 tokenizer._currentState = "QUERY";
3279 }
3280}
3281function nextQuery(tokenizer) {
3282 if (getCurrentCharacter(tokenizer) === "?") {
3283 nextCharacter(tokenizer);
3284 }
3285 var query = readRemaining(tokenizer);
3286 tokenizer._currentToken = URLToken.query(query);
3287 tokenizer._currentState = "DONE";
3288}
3289
3290// Copyright (c) Microsoft Corporation. All rights reserved.
3291function createProxyAgent(requestUrl, proxySettings, headers) {
3292 var tunnelOptions = {
3293 proxy: {
3294 host: URLBuilder.parse(proxySettings.host).getHost(),
3295 port: proxySettings.port,
3296 headers: (headers && headers.rawHeaders()) || {},
3297 },
3298 };
3299 if (proxySettings.username && proxySettings.password) {
3300 tunnelOptions.proxy.proxyAuth = proxySettings.username + ":" + proxySettings.password;
3301 }
3302 else if (proxySettings.username) {
3303 tunnelOptions.proxy.proxyAuth = "" + proxySettings.username;
3304 }
3305 var requestScheme = URLBuilder.parse(requestUrl).getScheme() || "";
3306 var isRequestHttps = requestScheme.toLowerCase() === "https";
3307 var proxyScheme = URLBuilder.parse(proxySettings.host).getScheme() || "";
3308 var isProxyHttps = proxyScheme.toLowerCase() === "https";
3309 var proxyAgent = {
3310 isHttps: isRequestHttps,
3311 agent: createTunnel(isRequestHttps, isProxyHttps, tunnelOptions),
3312 };
3313 return proxyAgent;
3314}
3315function createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) {
3316 if (isRequestHttps && isProxyHttps) {
3317 return tunnel.httpsOverHttps(tunnelOptions);
3318 }
3319 else if (isRequestHttps && !isProxyHttps) {
3320 return tunnel.httpsOverHttp(tunnelOptions);
3321 }
3322 else if (!isRequestHttps && isProxyHttps) {
3323 return tunnel.httpOverHttps(tunnelOptions);
3324 }
3325 else {
3326 return tunnel.httpOverHttp(tunnelOptions);
3327 }
3328}
3329
3330// Copyright (c) Microsoft Corporation. All rights reserved.
3331var NodeFetchHttpClient = /** @class */ (function (_super) {
3332 tslib.__extends(NodeFetchHttpClient, _super);
3333 function NodeFetchHttpClient() {
3334 var _this = _super !== null && _super.apply(this, arguments) || this;
3335 _this.cookieJar = new tough.CookieJar(undefined, { looseMode: true });
3336 return _this;
3337 }
3338 NodeFetchHttpClient.prototype.fetch = function (input, init) {
3339 return tslib.__awaiter(this, void 0, void 0, function () {
3340 return tslib.__generator(this, function (_a) {
3341 return [2 /*return*/, node_fetch(input, init)];
3342 });
3343 });
3344 };
3345 NodeFetchHttpClient.prototype.prepareRequest = function (httpRequest) {
3346 return tslib.__awaiter(this, void 0, void 0, function () {
3347 var requestInit, cookieString, _a, httpAgent, httpsAgent, tunnel, options, agent;
3348 var _this = this;
3349 return tslib.__generator(this, function (_b) {
3350 switch (_b.label) {
3351 case 0:
3352 requestInit = {};
3353 if (!(this.cookieJar && !httpRequest.headers.get("Cookie"))) return [3 /*break*/, 2];
3354 return [4 /*yield*/, new Promise(function (resolve, reject) {
3355 _this.cookieJar.getCookieString(httpRequest.url, function (err, cookie) {
3356 if (err) {
3357 reject(err);
3358 }
3359 else {
3360 resolve(cookie);
3361 }
3362 });
3363 })];
3364 case 1:
3365 cookieString = _b.sent();
3366 httpRequest.headers.set("Cookie", cookieString);
3367 _b.label = 2;
3368 case 2:
3369 if (httpRequest.agentSettings) {
3370 _a = httpRequest.agentSettings, httpAgent = _a.http, httpsAgent = _a.https;
3371 if (httpsAgent && httpRequest.url.startsWith("https")) {
3372 requestInit.agent = httpsAgent;
3373 }
3374 else if (httpAgent) {
3375 requestInit.agent = httpAgent;
3376 }
3377 }
3378 else if (httpRequest.proxySettings) {
3379 tunnel = createProxyAgent(httpRequest.url, httpRequest.proxySettings, httpRequest.headers);
3380 requestInit.agent = tunnel.agent;
3381 }
3382 if (httpRequest.keepAlive === true) {
3383 if (requestInit.agent) {
3384 requestInit.agent.keepAlive = true;
3385 }
3386 else {
3387 options = { keepAlive: true };
3388 agent = httpRequest.url.startsWith("https")
3389 ? new https.Agent(options)
3390 : new http.Agent(options);
3391 requestInit.agent = agent;
3392 }
3393 }
3394 return [2 /*return*/, requestInit];
3395 }
3396 });
3397 });
3398 };
3399 NodeFetchHttpClient.prototype.processRequest = function (operationResponse) {
3400 return tslib.__awaiter(this, void 0, void 0, function () {
3401 var setCookieHeader_1;
3402 var _this = this;
3403 return tslib.__generator(this, function (_a) {
3404 switch (_a.label) {
3405 case 0:
3406 if (!this.cookieJar) return [3 /*break*/, 2];
3407 setCookieHeader_1 = operationResponse.headers.get("Set-Cookie");
3408 if (!(setCookieHeader_1 != undefined)) return [3 /*break*/, 2];
3409 return [4 /*yield*/, new Promise(function (resolve, reject) {
3410 _this.cookieJar.setCookie(setCookieHeader_1, operationResponse.request.url, { ignoreError: true }, function (err) {
3411 if (err) {
3412 reject(err);
3413 }
3414 else {
3415 resolve();
3416 }
3417 });
3418 })];
3419 case 1:
3420 _a.sent();
3421 _a.label = 2;
3422 case 2: return [2 /*return*/];
3423 }
3424 });
3425 });
3426 };
3427 return NodeFetchHttpClient;
3428}(FetchHttpClient));
3429
3430// Copyright (c) Microsoft Corporation. All rights reserved.
3431(function (HttpPipelineLogLevel) {
3432 /**
3433 * A log level that indicates that no logs will be logged.
3434 */
3435 HttpPipelineLogLevel[HttpPipelineLogLevel["OFF"] = 0] = "OFF";
3436 /**
3437 * An error log.
3438 */
3439 HttpPipelineLogLevel[HttpPipelineLogLevel["ERROR"] = 1] = "ERROR";
3440 /**
3441 * A warning log.
3442 */
3443 HttpPipelineLogLevel[HttpPipelineLogLevel["WARNING"] = 2] = "WARNING";
3444 /**
3445 * An information log.
3446 */
3447 HttpPipelineLogLevel[HttpPipelineLogLevel["INFO"] = 3] = "INFO";
3448})(exports.HttpPipelineLogLevel || (exports.HttpPipelineLogLevel = {}));
3449
3450// Copyright (c) Microsoft Corporation.
3451// Licensed under the MIT license.
3452/**
3453 * Tests an object to determine whether it implements TokenCredential.
3454 *
3455 * @param credential - The assumed TokenCredential to be tested.
3456 */
3457function isTokenCredential(credential) {
3458 // Check for an object with a 'getToken' function and possibly with
3459 // a 'signRequest' function. We do this check to make sure that
3460 // a ServiceClientCredentials implementor (like TokenClientCredentials
3461 // in ms-rest-nodeauth) doesn't get mistaken for a TokenCredential if
3462 // it doesn't actually implement TokenCredential also.
3463 const castCredential = credential;
3464 return (castCredential &&
3465 typeof castCredential.getToken === "function" &&
3466 (castCredential.signRequest === undefined || castCredential.getToken.length > 0));
3467}
3468
3469// Copyright (c) Microsoft Corporation. All rights reserved.
3470// Licensed under the MIT License. See License.txt in the project root for license information.
3471/**
3472 * Get the path to this parameter's value as a dotted string (a.b.c).
3473 * @param parameter The parameter to get the path string for.
3474 * @returns The path to this parameter's value as a dotted string.
3475 */
3476function getPathStringFromParameter(parameter) {
3477 return getPathStringFromParameterPath(parameter.parameterPath, parameter.mapper);
3478}
3479function getPathStringFromParameterPath(parameterPath, mapper) {
3480 var result;
3481 if (typeof parameterPath === "string") {
3482 result = parameterPath;
3483 }
3484 else if (Array.isArray(parameterPath)) {
3485 result = parameterPath.join(".");
3486 }
3487 else {
3488 result = mapper.serializedName;
3489 }
3490 return result;
3491}
3492
3493// Copyright (c) Microsoft Corporation. All rights reserved.
3494function isStreamOperation(operationSpec) {
3495 var result = false;
3496 for (var statusCode in operationSpec.responses) {
3497 var operationResponse = operationSpec.responses[statusCode];
3498 if (operationResponse.bodyMapper &&
3499 operationResponse.bodyMapper.type.name === MapperType.Stream) {
3500 result = true;
3501 break;
3502 }
3503 }
3504 return result;
3505}
3506
3507// Copyright (c) Microsoft Corporation. All rights reserved.
3508function stringifyXML(obj, opts) {
3509 var builder = new xml2js.Builder({
3510 rootName: (opts || {}).rootName,
3511 renderOpts: {
3512 pretty: false,
3513 },
3514 });
3515 return builder.buildObject(obj);
3516}
3517function parseXML(str) {
3518 var xmlParser = new xml2js.Parser({
3519 explicitArray: false,
3520 explicitCharkey: false,
3521 explicitRoot: false,
3522 });
3523 return new Promise(function (resolve, reject) {
3524 if (!str) {
3525 reject(new Error("Document is empty"));
3526 }
3527 else {
3528 xmlParser.parseString(str, function (err, res) {
3529 if (err) {
3530 reject(err);
3531 }
3532 else {
3533 resolve(res);
3534 }
3535 });
3536 }
3537 });
3538}
3539
3540// Copyright (c) Microsoft Corporation. All rights reserved.
3541var BaseRequestPolicy = /** @class */ (function () {
3542 function BaseRequestPolicy(_nextPolicy, _options) {
3543 this._nextPolicy = _nextPolicy;
3544 this._options = _options;
3545 }
3546 /**
3547 * Get whether or not a log with the provided log level should be logged.
3548 * @param logLevel The log level of the log that will be logged.
3549 * @returns Whether or not a log with the provided log level should be logged.
3550 */
3551 BaseRequestPolicy.prototype.shouldLog = function (logLevel) {
3552 return this._options.shouldLog(logLevel);
3553 };
3554 /**
3555 * Attempt to log the provided message to the provided logger. If no logger was provided or if
3556 * the log level does not meat the logger's threshold, then nothing will be logged.
3557 * @param logLevel The log level of this log.
3558 * @param message The message of this log.
3559 */
3560 BaseRequestPolicy.prototype.log = function (logLevel, message) {
3561 this._options.log(logLevel, message);
3562 };
3563 return BaseRequestPolicy;
3564}());
3565/**
3566 * Optional properties that can be used when creating a RequestPolicy.
3567 */
3568var RequestPolicyOptions = /** @class */ (function () {
3569 function RequestPolicyOptions(_logger) {
3570 this._logger = _logger;
3571 }
3572 /**
3573 * Get whether or not a log with the provided log level should be logged.
3574 * @param logLevel The log level of the log that will be logged.
3575 * @returns Whether or not a log with the provided log level should be logged.
3576 */
3577 RequestPolicyOptions.prototype.shouldLog = function (logLevel) {
3578 return (!!this._logger &&
3579 logLevel !== exports.HttpPipelineLogLevel.OFF &&
3580 logLevel <= this._logger.minimumLogLevel);
3581 };
3582 /**
3583 * Attempt to log the provided message to the provided logger. If no logger was provided or if
3584 * the log level does not meat the logger's threshold, then nothing will be logged.
3585 * @param logLevel The log level of this log.
3586 * @param message The message of this log.
3587 */
3588 RequestPolicyOptions.prototype.log = function (logLevel, message) {
3589 if (this._logger && this.shouldLog(logLevel)) {
3590 this._logger.log(logLevel, message);
3591 }
3592 };
3593 return RequestPolicyOptions;
3594}());
3595
3596// Copyright (c) Microsoft Corporation. All rights reserved.
3597/**
3598 * Create a new serialization RequestPolicyCreator that will serialized HTTP request bodies as they
3599 * pass through the HTTP pipeline.
3600 */
3601function deserializationPolicy(deserializationContentTypes) {
3602 return {
3603 create: function (nextPolicy, options) {
3604 return new DeserializationPolicy(nextPolicy, deserializationContentTypes, options);
3605 },
3606 };
3607}
3608var defaultJsonContentTypes = ["application/json", "text/json"];
3609var defaultXmlContentTypes = ["application/xml", "application/atom+xml"];
3610/**
3611 * A RequestPolicy that will deserialize HTTP response bodies and headers as they pass through the
3612 * HTTP pipeline.
3613 */
3614var DeserializationPolicy = /** @class */ (function (_super) {
3615 tslib.__extends(DeserializationPolicy, _super);
3616 function DeserializationPolicy(nextPolicy, deserializationContentTypes, options) {
3617 var _this = _super.call(this, nextPolicy, options) || this;
3618 _this.jsonContentTypes =
3619 (deserializationContentTypes && deserializationContentTypes.json) || defaultJsonContentTypes;
3620 _this.xmlContentTypes =
3621 (deserializationContentTypes && deserializationContentTypes.xml) || defaultXmlContentTypes;
3622 return _this;
3623 }
3624 DeserializationPolicy.prototype.sendRequest = function (request) {
3625 return tslib.__awaiter(this, void 0, void 0, function () {
3626 var _this = this;
3627 return tslib.__generator(this, function (_a) {
3628 return [2 /*return*/, this._nextPolicy
3629 .sendRequest(request)
3630 .then(function (response) {
3631 return deserializeResponseBody(_this.jsonContentTypes, _this.xmlContentTypes, response);
3632 })];
3633 });
3634 });
3635 };
3636 return DeserializationPolicy;
3637}(BaseRequestPolicy));
3638function getOperationResponse(parsedResponse) {
3639 var result;
3640 var request = parsedResponse.request;
3641 var operationSpec = request.operationSpec;
3642 if (operationSpec) {
3643 var operationResponseGetter = request.operationResponseGetter;
3644 if (!operationResponseGetter) {
3645 result = operationSpec.responses[parsedResponse.status];
3646 }
3647 else {
3648 result = operationResponseGetter(operationSpec, parsedResponse);
3649 }
3650 }
3651 return result;
3652}
3653function shouldDeserializeResponse(parsedResponse) {
3654 var shouldDeserialize = parsedResponse.request.shouldDeserialize;
3655 var result;
3656 if (shouldDeserialize === undefined) {
3657 result = true;
3658 }
3659 else if (typeof shouldDeserialize === "boolean") {
3660 result = shouldDeserialize;
3661 }
3662 else {
3663 result = shouldDeserialize(parsedResponse);
3664 }
3665 return result;
3666}
3667function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response) {
3668 return parse(jsonContentTypes, xmlContentTypes, response).then(function (parsedResponse) {
3669 var shouldDeserialize = shouldDeserializeResponse(parsedResponse);
3670 if (shouldDeserialize) {
3671 var operationSpec = parsedResponse.request.operationSpec;
3672 if (operationSpec && operationSpec.responses) {
3673 var statusCode = parsedResponse.status;
3674 var expectedStatusCodes = Object.keys(operationSpec.responses);
3675 var hasNoExpectedStatusCodes = expectedStatusCodes.length === 0 ||
3676 (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default");
3677 var responseSpec = getOperationResponse(parsedResponse);
3678 var isExpectedStatusCode = hasNoExpectedStatusCodes
3679 ? 200 <= statusCode && statusCode < 300
3680 : !!responseSpec;
3681 if (!isExpectedStatusCode) {
3682 var defaultResponseSpec = operationSpec.responses.default;
3683 if (defaultResponseSpec) {
3684 var initialErrorMessage = isStreamOperation(operationSpec)
3685 ? "Unexpected status code: " + statusCode
3686 : parsedResponse.bodyAsText;
3687 var error = new RestError(initialErrorMessage);
3688 error.statusCode = statusCode;
3689 error.request = stripRequest(parsedResponse.request);
3690 error.response = stripResponse(parsedResponse);
3691 var parsedErrorResponse = parsedResponse.parsedBody;
3692 try {
3693 if (parsedErrorResponse) {
3694 var defaultResponseBodyMapper = defaultResponseSpec.bodyMapper;
3695 if (defaultResponseBodyMapper &&
3696 defaultResponseBodyMapper.serializedName === "CloudError") {
3697 if (parsedErrorResponse.error) {
3698 parsedErrorResponse = parsedErrorResponse.error;
3699 }
3700 if (parsedErrorResponse.code) {
3701 error.code = parsedErrorResponse.code;
3702 }
3703 if (parsedErrorResponse.message) {
3704 error.message = parsedErrorResponse.message;
3705 }
3706 }
3707 else {
3708 var internalError = parsedErrorResponse;
3709 if (parsedErrorResponse.error) {
3710 internalError = parsedErrorResponse.error;
3711 }
3712 error.code = internalError.code;
3713 if (internalError.message) {
3714 error.message = internalError.message;
3715 }
3716 }
3717 if (defaultResponseBodyMapper) {
3718 var valueToDeserialize = parsedErrorResponse;
3719 if (operationSpec.isXML &&
3720 defaultResponseBodyMapper.type.name === MapperType.Sequence) {
3721 valueToDeserialize =
3722 typeof parsedErrorResponse === "object"
3723 ? parsedErrorResponse[defaultResponseBodyMapper.xmlElementName]
3724 : [];
3725 }
3726 error.body = operationSpec.serializer.deserialize(defaultResponseBodyMapper, valueToDeserialize, "error.body");
3727 }
3728 }
3729 }
3730 catch (defaultError) {
3731 error.message = "Error \"" + defaultError.message + "\" occurred in deserializing the responseBody - \"" + parsedResponse.bodyAsText + "\" for the default response.";
3732 }
3733 return Promise.reject(error);
3734 }
3735 }
3736 else if (responseSpec) {
3737 if (responseSpec.bodyMapper) {
3738 var valueToDeserialize = parsedResponse.parsedBody;
3739 if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperType.Sequence) {
3740 valueToDeserialize =
3741 typeof valueToDeserialize === "object"
3742 ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName]
3743 : [];
3744 }
3745 try {
3746 parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody");
3747 }
3748 catch (error) {
3749 var restError = new RestError("Error " + error + " occurred in deserializing the responseBody - " + parsedResponse.bodyAsText);
3750 restError.request = stripRequest(parsedResponse.request);
3751 restError.response = stripResponse(parsedResponse);
3752 return Promise.reject(restError);
3753 }
3754 }
3755 else if (operationSpec.httpMethod === "HEAD") {
3756 // head methods never have a body, but we return a boolean to indicate presence/absence of the resource
3757 parsedResponse.parsedBody = response.status >= 200 && response.status < 300;
3758 }
3759 if (responseSpec.headersMapper) {
3760 parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders");
3761 }
3762 }
3763 }
3764 }
3765 return Promise.resolve(parsedResponse);
3766 });
3767}
3768function parse(jsonContentTypes, xmlContentTypes, operationResponse) {
3769 var errorHandler = function (err) {
3770 var msg = "Error \"" + err + "\" occurred while parsing the response body - " + operationResponse.bodyAsText + ".";
3771 var errCode = err.code || RestError.PARSE_ERROR;
3772 var e = new RestError(msg, errCode, operationResponse.status, operationResponse.request, operationResponse, operationResponse.bodyAsText);
3773 return Promise.reject(e);
3774 };
3775 if (!operationResponse.request.streamResponseBody && operationResponse.bodyAsText) {
3776 var text_1 = operationResponse.bodyAsText;
3777 var contentType = operationResponse.headers.get("Content-Type") || "";
3778 var contentComponents = !contentType
3779 ? []
3780 : contentType.split(";").map(function (component) { return component.toLowerCase(); });
3781 if (contentComponents.length === 0 ||
3782 contentComponents.some(function (component) { return jsonContentTypes.indexOf(component) !== -1; })) {
3783 return new Promise(function (resolve) {
3784 operationResponse.parsedBody = JSON.parse(text_1);
3785 resolve(operationResponse);
3786 }).catch(errorHandler);
3787 }
3788 else if (contentComponents.some(function (component) { return xmlContentTypes.indexOf(component) !== -1; })) {
3789 return parseXML(text_1)
3790 .then(function (body) {
3791 operationResponse.parsedBody = body;
3792 return operationResponse;
3793 })
3794 .catch(errorHandler);
3795 }
3796 }
3797 return Promise.resolve(operationResponse);
3798}
3799
3800// Copyright (c) Microsoft Corporation. All rights reserved.
3801function exponentialRetryPolicy(retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
3802 return {
3803 create: function (nextPolicy, options) {
3804 return new ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval);
3805 },
3806 };
3807}
3808var DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30;
3809var DEFAULT_CLIENT_RETRY_COUNT = 3;
3810var DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90;
3811var DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3;
3812/**
3813 * @class
3814 * Instantiates a new "ExponentialRetryPolicyFilter" instance.
3815 */
3816var ExponentialRetryPolicy = /** @class */ (function (_super) {
3817 tslib.__extends(ExponentialRetryPolicy, _super);
3818 /**
3819 * @constructor
3820 * @param {RequestPolicy} nextPolicy The next RequestPolicy in the pipeline chain.
3821 * @param {RequestPolicyOptionsLike} options The options for this RequestPolicy.
3822 * @param {number} [retryCount] The client retry count.
3823 * @param {number} [retryInterval] The client retry interval, in milliseconds.
3824 * @param {number} [minRetryInterval] The minimum retry interval, in milliseconds.
3825 * @param {number} [maxRetryInterval] The maximum retry interval, in milliseconds.
3826 */
3827 function ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
3828 var _this = _super.call(this, nextPolicy, options) || this;
3829 function isNumber(n) {
3830 return typeof n === "number";
3831 }
3832 _this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT;
3833 _this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL;
3834 _this.minRetryInterval = isNumber(minRetryInterval)
3835 ? minRetryInterval
3836 : DEFAULT_CLIENT_MIN_RETRY_INTERVAL;
3837 _this.maxRetryInterval = isNumber(maxRetryInterval)
3838 ? maxRetryInterval
3839 : DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
3840 return _this;
3841 }
3842 ExponentialRetryPolicy.prototype.sendRequest = function (request) {
3843 var _this = this;
3844 return this._nextPolicy
3845 .sendRequest(request.clone())
3846 .then(function (response) { return retry(_this, request, response); })
3847 .catch(function (error) { return retry(_this, request, error.response, undefined, error); });
3848 };
3849 return ExponentialRetryPolicy;
3850}(BaseRequestPolicy));
3851/**
3852 * Determines if the operation should be retried and how long to wait until the next retry.
3853 *
3854 * @param {ExponentialRetryPolicy} policy The ExponentialRetryPolicy that this function is being called against.
3855 * @param {number} statusCode The HTTP status code.
3856 * @param {RetryData} retryData The retry data.
3857 * @return {boolean} True if the operation qualifies for a retry; false otherwise.
3858 */
3859function shouldRetry(policy, statusCode, retryData) {
3860 if (statusCode == undefined ||
3861 (statusCode < 500 && statusCode !== 408) ||
3862 statusCode === 501 ||
3863 statusCode === 505) {
3864 return false;
3865 }
3866 var currentCount;
3867 if (!retryData) {
3868 throw new Error("retryData for the ExponentialRetryPolicyFilter cannot be null.");
3869 }
3870 else {
3871 currentCount = retryData && retryData.retryCount;
3872 }
3873 return currentCount < policy.retryCount;
3874}
3875/**
3876 * Updates the retry data for the next attempt.
3877 *
3878 * @param {ExponentialRetryPolicy} policy The ExponentialRetryPolicy that this function is being called against.
3879 * @param {RetryData} retryData The retry data.
3880 * @param {RetryError} [err] The operation"s error, if any.
3881 */
3882function updateRetryData(policy, retryData, err) {
3883 if (!retryData) {
3884 retryData = {
3885 retryCount: 0,
3886 retryInterval: 0,
3887 };
3888 }
3889 if (err) {
3890 if (retryData.error) {
3891 err.innerError = retryData.error;
3892 }
3893 retryData.error = err;
3894 }
3895 // Adjust retry count
3896 retryData.retryCount++;
3897 // Adjust retry interval
3898 var incrementDelta = Math.pow(2, retryData.retryCount) - 1;
3899 var boundedRandDelta = policy.retryInterval * 0.8 +
3900 Math.floor(Math.random() * (policy.retryInterval * 1.2 - policy.retryInterval * 0.8));
3901 incrementDelta *= boundedRandDelta;
3902 retryData.retryInterval = Math.min(policy.minRetryInterval + incrementDelta, policy.maxRetryInterval);
3903 return retryData;
3904}
3905function retry(policy, request, response, retryData, requestError) {
3906 retryData = updateRetryData(policy, retryData, requestError);
3907 var isAborted = request.abortSignal && request.abortSignal.aborted;
3908 if (!isAborted && shouldRetry(policy, response && response.status, retryData)) {
3909 return delay(retryData.retryInterval)
3910 .then(function () { return policy._nextPolicy.sendRequest(request.clone()); })
3911 .then(function (res) { return retry(policy, request, res, retryData, undefined); })
3912 .catch(function (err) { return retry(policy, request, response, retryData, err); });
3913 }
3914 else if (isAborted || requestError || !response) {
3915 // If the operation failed in the end, return all errors instead of just the last one
3916 var err = retryData.error ||
3917 new RestError("Failed to send the request.", RestError.REQUEST_SEND_ERROR, response && response.status, response && response.request, response);
3918 return Promise.reject(err);
3919 }
3920 else {
3921 return Promise.resolve(response);
3922 }
3923}
3924
3925// Copyright (c) Microsoft Corporation. All rights reserved.
3926function generateClientRequestIdPolicy(requestIdHeaderName) {
3927 if (requestIdHeaderName === void 0) { requestIdHeaderName = "x-ms-client-request-id"; }
3928 return {
3929 create: function (nextPolicy, options) {
3930 return new GenerateClientRequestIdPolicy(nextPolicy, options, requestIdHeaderName);
3931 },
3932 };
3933}
3934var GenerateClientRequestIdPolicy = /** @class */ (function (_super) {
3935 tslib.__extends(GenerateClientRequestIdPolicy, _super);
3936 function GenerateClientRequestIdPolicy(nextPolicy, options, _requestIdHeaderName) {
3937 var _this = _super.call(this, nextPolicy, options) || this;
3938 _this._requestIdHeaderName = _requestIdHeaderName;
3939 return _this;
3940 }
3941 GenerateClientRequestIdPolicy.prototype.sendRequest = function (request) {
3942 if (!request.headers.contains(this._requestIdHeaderName)) {
3943 request.headers.set(this._requestIdHeaderName, generateUuid());
3944 }
3945 return this._nextPolicy.sendRequest(request);
3946 };
3947 return GenerateClientRequestIdPolicy;
3948}(BaseRequestPolicy));
3949
3950// Copyright (c) Microsoft Corporation. All rights reserved.
3951function getDefaultUserAgentKey() {
3952 return Constants.HeaderConstants.USER_AGENT;
3953}
3954function getPlatformSpecificData() {
3955 var runtimeInfo = {
3956 key: "Node",
3957 value: process.version,
3958 };
3959 var osInfo = {
3960 key: "OS",
3961 value: "(" + os.arch() + "-" + os.type() + "-" + os.release() + ")",
3962 };
3963 return [runtimeInfo, osInfo];
3964}
3965
3966// Copyright (c) Microsoft Corporation. All rights reserved.
3967function getRuntimeInfo() {
3968 var msRestRuntime = {
3969 key: "ms-rest-js",
3970 value: Constants.msRestVersion,
3971 };
3972 return [msRestRuntime];
3973}
3974function getUserAgentString(telemetryInfo, keySeparator, valueSeparator) {
3975 if (keySeparator === void 0) { keySeparator = " "; }
3976 if (valueSeparator === void 0) { valueSeparator = "/"; }
3977 return telemetryInfo
3978 .map(function (info) {
3979 var value = info.value ? "" + valueSeparator + info.value : "";
3980 return "" + info.key + value;
3981 })
3982 .join(keySeparator);
3983}
3984var getDefaultUserAgentHeaderName = getDefaultUserAgentKey;
3985function getDefaultUserAgentValue() {
3986 var runtimeInfo = getRuntimeInfo();
3987 var platformSpecificData = getPlatformSpecificData();
3988 var userAgent = getUserAgentString(runtimeInfo.concat(platformSpecificData));
3989 return userAgent;
3990}
3991function userAgentPolicy(userAgentData) {
3992 var key = !userAgentData || userAgentData.key == undefined ? getDefaultUserAgentKey() : userAgentData.key;
3993 var value = !userAgentData || userAgentData.value == undefined
3994 ? getDefaultUserAgentValue()
3995 : userAgentData.value;
3996 return {
3997 create: function (nextPolicy, options) {
3998 return new UserAgentPolicy(nextPolicy, options, key, value);
3999 },
4000 };
4001}
4002var UserAgentPolicy = /** @class */ (function (_super) {
4003 tslib.__extends(UserAgentPolicy, _super);
4004 function UserAgentPolicy(_nextPolicy, _options, headerKey, headerValue) {
4005 var _this = _super.call(this, _nextPolicy, _options) || this;
4006 _this._nextPolicy = _nextPolicy;
4007 _this._options = _options;
4008 _this.headerKey = headerKey;
4009 _this.headerValue = headerValue;
4010 return _this;
4011 }
4012 UserAgentPolicy.prototype.sendRequest = function (request) {
4013 this.addUserAgentHeader(request);
4014 return this._nextPolicy.sendRequest(request);
4015 };
4016 UserAgentPolicy.prototype.addUserAgentHeader = function (request) {
4017 if (!request.headers) {
4018 request.headers = new HttpHeaders();
4019 }
4020 if (!request.headers.get(this.headerKey) && this.headerValue) {
4021 request.headers.set(this.headerKey, this.headerValue);
4022 }
4023 };
4024 return UserAgentPolicy;
4025}(BaseRequestPolicy));
4026
4027// Copyright (c) Microsoft Corporation. All rights reserved.
4028var DefaultRedirectOptions = {
4029 handleRedirects: true,
4030 maxRetries: 20,
4031};
4032function redirectPolicy(maximumRetries) {
4033 if (maximumRetries === void 0) { maximumRetries = 20; }
4034 return {
4035 create: function (nextPolicy, options) {
4036 return new RedirectPolicy(nextPolicy, options, maximumRetries);
4037 },
4038 };
4039}
4040var RedirectPolicy = /** @class */ (function (_super) {
4041 tslib.__extends(RedirectPolicy, _super);
4042 function RedirectPolicy(nextPolicy, options, maxRetries) {
4043 if (maxRetries === void 0) { maxRetries = 20; }
4044 var _this = _super.call(this, nextPolicy, options) || this;
4045 _this.maxRetries = maxRetries;
4046 return _this;
4047 }
4048 RedirectPolicy.prototype.sendRequest = function (request) {
4049 var _this = this;
4050 return this._nextPolicy
4051 .sendRequest(request)
4052 .then(function (response) { return handleRedirect(_this, response, 0); });
4053 };
4054 return RedirectPolicy;
4055}(BaseRequestPolicy));
4056function handleRedirect(policy, response, currentRetries) {
4057 var request = response.request, status = response.status;
4058 var locationHeader = response.headers.get("location");
4059 if (locationHeader &&
4060 (status === 300 ||
4061 (status === 301 && ["GET", "HEAD"].includes(request.method)) ||
4062 (status === 302 && ["GET", "POST", "HEAD"].includes(request.method)) ||
4063 (status === 303 && "POST" === request.method) ||
4064 status === 307) &&
4065 ((request.redirectLimit !== undefined && currentRetries < request.redirectLimit) ||
4066 (request.redirectLimit === undefined && currentRetries < policy.maxRetries))) {
4067 var builder = URLBuilder.parse(request.url);
4068 builder.setPath(locationHeader);
4069 request.url = builder.toString();
4070 // POST request with Status code 302 and 303 should be converted into a
4071 // redirected GET request if the redirect url is present in the location header
4072 // reference: https://tools.ietf.org/html/rfc7231#page-57 && https://fetch.spec.whatwg.org/#http-redirect-fetch
4073 if ((status === 302 || status === 303) && request.method === "POST") {
4074 request.method = "GET";
4075 delete request.body;
4076 }
4077 return policy._nextPolicy
4078 .sendRequest(request)
4079 .then(function (res) { return handleRedirect(policy, res, currentRetries + 1); })
4080 .then(function (res) { return recordRedirect(res, request.url); });
4081 }
4082 return Promise.resolve(response);
4083}
4084function recordRedirect(response, redirect) {
4085 // This is called as the recursive calls to handleRedirect() unwind,
4086 // only record the deepest/last redirect
4087 if (!response.redirected) {
4088 response.redirected = true;
4089 response.url = redirect;
4090 }
4091 return response;
4092}
4093
4094function rpRegistrationPolicy(retryTimeout) {
4095 if (retryTimeout === void 0) { retryTimeout = 30; }
4096 return {
4097 create: function (nextPolicy, options) {
4098 return new RPRegistrationPolicy(nextPolicy, options, retryTimeout);
4099 },
4100 };
4101}
4102var RPRegistrationPolicy = /** @class */ (function (_super) {
4103 tslib.__extends(RPRegistrationPolicy, _super);
4104 function RPRegistrationPolicy(nextPolicy, options, _retryTimeout) {
4105 if (_retryTimeout === void 0) { _retryTimeout = 30; }
4106 var _this = _super.call(this, nextPolicy, options) || this;
4107 _this._retryTimeout = _retryTimeout;
4108 return _this;
4109 }
4110 RPRegistrationPolicy.prototype.sendRequest = function (request) {
4111 var _this = this;
4112 return this._nextPolicy
4113 .sendRequest(request.clone())
4114 .then(function (response) { return registerIfNeeded(_this, request, response); });
4115 };
4116 return RPRegistrationPolicy;
4117}(BaseRequestPolicy));
4118function registerIfNeeded(policy, request, response) {
4119 if (response.status === 409) {
4120 var rpName = checkRPNotRegisteredError(response.bodyAsText);
4121 if (rpName) {
4122 var urlPrefix = extractSubscriptionUrl(request.url);
4123 return (registerRP(policy, urlPrefix, rpName, request)
4124 // Autoregistration of ${provider} failed for some reason. We will not return this error
4125 // instead will return the initial response with 409 status code back to the user.
4126 // do nothing here as we are returning the original response at the end of this method.
4127 .catch(function () { return false; })
4128 .then(function (registrationStatus) {
4129 if (registrationStatus) {
4130 // Retry the original request. We have to change the x-ms-client-request-id
4131 // otherwise Azure endpoint will return the initial 409 (cached) response.
4132 request.headers.set("x-ms-client-request-id", generateUuid());
4133 return policy._nextPolicy.sendRequest(request.clone());
4134 }
4135 return response;
4136 }));
4137 }
4138 }
4139 return Promise.resolve(response);
4140}
4141/**
4142 * Reuses the headers of the original request and url (if specified).
4143 * @param {WebResourceLike} originalRequest The original request
4144 * @param {boolean} reuseUrlToo Should the url from the original request be reused as well. Default false.
4145 * @returns {object} A new request object with desired headers.
4146 */
4147function getRequestEssentials(originalRequest, reuseUrlToo) {
4148 if (reuseUrlToo === void 0) { reuseUrlToo = false; }
4149 var reqOptions = originalRequest.clone();
4150 if (reuseUrlToo) {
4151 reqOptions.url = originalRequest.url;
4152 }
4153 // We have to change the x-ms-client-request-id otherwise Azure endpoint
4154 // will return the initial 409 (cached) response.
4155 reqOptions.headers.set("x-ms-client-request-id", generateUuid());
4156 // Set content-type to application/json
4157 reqOptions.headers.set("Content-Type", "application/json; charset=utf-8");
4158 return reqOptions;
4159}
4160/**
4161 * Validates the error code and message associated with 409 response status code. If it matches to that of
4162 * RP not registered then it returns the name of the RP else returns undefined.
4163 * @param {string} body The response body received after making the original request.
4164 * @returns {string} The name of the RP if condition is satisfied else undefined.
4165 */
4166function checkRPNotRegisteredError(body) {
4167 var result, responseBody;
4168 if (body) {
4169 try {
4170 responseBody = JSON.parse(body);
4171 }
4172 catch (err) {
4173 // do nothing;
4174 }
4175 if (responseBody &&
4176 responseBody.error &&
4177 responseBody.error.message &&
4178 responseBody.error.code &&
4179 responseBody.error.code === "MissingSubscriptionRegistration") {
4180 var matchRes = responseBody.error.message.match(/.*'(.*)'/i);
4181 if (matchRes) {
4182 result = matchRes.pop();
4183 }
4184 }
4185 }
4186 return result;
4187}
4188/**
4189 * Extracts the first part of the URL, just after subscription:
4190 * https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/
4191 * @param {string} url The original request url
4192 * @returns {string} The url prefix as explained above.
4193 */
4194function extractSubscriptionUrl(url) {
4195 var result;
4196 var matchRes = url.match(/.*\/subscriptions\/[a-f0-9-]+\//gi);
4197 if (matchRes && matchRes[0]) {
4198 result = matchRes[0];
4199 }
4200 else {
4201 throw new Error("Unable to extract subscriptionId from the given url - " + url + ".");
4202 }
4203 return result;
4204}
4205/**
4206 * Registers the given provider.
4207 * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against.
4208 * @param {string} urlPrefix https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/
4209 * @param {string} provider The provider name to be registered.
4210 * @param {WebResourceLike} originalRequest The original request sent by the user that returned a 409 response
4211 * with a message that the provider is not registered.
4212 * @param {registrationCallback} callback The callback that handles the RP registration
4213 */
4214function registerRP(policy, urlPrefix, provider, originalRequest) {
4215 var postUrl = urlPrefix + "providers/" + provider + "/register?api-version=2016-02-01";
4216 var getUrl = urlPrefix + "providers/" + provider + "?api-version=2016-02-01";
4217 var reqOptions = getRequestEssentials(originalRequest);
4218 reqOptions.method = "POST";
4219 reqOptions.url = postUrl;
4220 return policy._nextPolicy.sendRequest(reqOptions).then(function (response) {
4221 if (response.status !== 200) {
4222 throw new Error("Autoregistration of " + provider + " failed. Please try registering manually.");
4223 }
4224 return getRegistrationStatus(policy, getUrl, originalRequest);
4225 });
4226}
4227/**
4228 * Polls the registration status of the provider that was registered. Polling happens at an interval of 30 seconds.
4229 * Polling will happen till the registrationState property of the response body is "Registered".
4230 * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against.
4231 * @param {string} url The request url for polling
4232 * @param {WebResourceLike} originalRequest The original request sent by the user that returned a 409 response
4233 * with a message that the provider is not registered.
4234 * @returns {Promise<boolean>} True if RP Registration is successful.
4235 */
4236function getRegistrationStatus(policy, url, originalRequest) {
4237 var reqOptions = getRequestEssentials(originalRequest);
4238 reqOptions.url = url;
4239 reqOptions.method = "GET";
4240 return policy._nextPolicy.sendRequest(reqOptions).then(function (res) {
4241 var obj = res.parsedBody;
4242 if (res.parsedBody && obj.registrationState && obj.registrationState === "Registered") {
4243 return true;
4244 }
4245 else {
4246 return delay(policy._retryTimeout * 1000)
4247 .then(function () { return getRegistrationStatus(policy, url, originalRequest); });
4248 }
4249 });
4250}
4251
4252// Copyright (c) Microsoft Corporation. All rights reserved.
4253function signingPolicy(authenticationProvider) {
4254 return {
4255 create: function (nextPolicy, options) {
4256 return new SigningPolicy(nextPolicy, options, authenticationProvider);
4257 },
4258 };
4259}
4260var SigningPolicy = /** @class */ (function (_super) {
4261 tslib.__extends(SigningPolicy, _super);
4262 function SigningPolicy(nextPolicy, options, authenticationProvider) {
4263 var _this = _super.call(this, nextPolicy, options) || this;
4264 _this.authenticationProvider = authenticationProvider;
4265 return _this;
4266 }
4267 SigningPolicy.prototype.signRequest = function (request) {
4268 return this.authenticationProvider.signRequest(request);
4269 };
4270 SigningPolicy.prototype.sendRequest = function (request) {
4271 var _this = this;
4272 return this.signRequest(request).then(function (nextRequest) {
4273 return _this._nextPolicy.sendRequest(nextRequest);
4274 });
4275 };
4276 return SigningPolicy;
4277}(BaseRequestPolicy));
4278
4279// Copyright (c) Microsoft Corporation. All rights reserved.
4280function systemErrorRetryPolicy(retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
4281 return {
4282 create: function (nextPolicy, options) {
4283 return new SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval);
4284 },
4285 };
4286}
4287/**
4288 * @class
4289 * Instantiates a new "ExponentialRetryPolicyFilter" instance.
4290 *
4291 * @constructor
4292 * @param {number} retryCount The client retry count.
4293 * @param {number} retryInterval The client retry interval, in milliseconds.
4294 * @param {number} minRetryInterval The minimum retry interval, in milliseconds.
4295 * @param {number} maxRetryInterval The maximum retry interval, in milliseconds.
4296 */
4297var SystemErrorRetryPolicy = /** @class */ (function (_super) {
4298 tslib.__extends(SystemErrorRetryPolicy, _super);
4299 function SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
4300 var _this = _super.call(this, nextPolicy, options) || this;
4301 _this.DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30;
4302 _this.DEFAULT_CLIENT_RETRY_COUNT = 3;
4303 _this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90;
4304 _this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3;
4305 _this.retryCount = typeof retryCount === "number" ? retryCount : _this.DEFAULT_CLIENT_RETRY_COUNT;
4306 _this.retryInterval =
4307 typeof retryInterval === "number" ? retryInterval : _this.DEFAULT_CLIENT_RETRY_INTERVAL;
4308 _this.minRetryInterval =
4309 typeof minRetryInterval === "number"
4310 ? minRetryInterval
4311 : _this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL;
4312 _this.maxRetryInterval =
4313 typeof maxRetryInterval === "number"
4314 ? maxRetryInterval
4315 : _this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
4316 return _this;
4317 }
4318 SystemErrorRetryPolicy.prototype.sendRequest = function (request) {
4319 var _this = this;
4320 return this._nextPolicy
4321 .sendRequest(request.clone())
4322 .catch(function (error) { return retry$1(_this, request, error.response, error); });
4323 };
4324 return SystemErrorRetryPolicy;
4325}(BaseRequestPolicy));
4326/**
4327 * Determines if the operation should be retried and how long to wait until the next retry.
4328 *
4329 * @param {number} statusCode The HTTP status code.
4330 * @param {RetryData} retryData The retry data.
4331 * @return {boolean} True if the operation qualifies for a retry; false otherwise.
4332 */
4333function shouldRetry$1(policy, retryData) {
4334 var currentCount;
4335 if (!retryData) {
4336 throw new Error("retryData for the SystemErrorRetryPolicyFilter cannot be null.");
4337 }
4338 else {
4339 currentCount = retryData && retryData.retryCount;
4340 }
4341 return currentCount < policy.retryCount;
4342}
4343/**
4344 * Updates the retry data for the next attempt.
4345 *
4346 * @param {RetryData} retryData The retry data.
4347 * @param {object} err The operation"s error, if any.
4348 */
4349function updateRetryData$1(policy, retryData, err) {
4350 if (!retryData) {
4351 retryData = {
4352 retryCount: 0,
4353 retryInterval: 0,
4354 };
4355 }
4356 if (err) {
4357 if (retryData.error) {
4358 err.innerError = retryData.error;
4359 }
4360 retryData.error = err;
4361 }
4362 // Adjust retry count
4363 retryData.retryCount++;
4364 // Adjust retry interval
4365 var incrementDelta = Math.pow(2, retryData.retryCount) - 1;
4366 var boundedRandDelta = policy.retryInterval * 0.8 + Math.floor(Math.random() * (policy.retryInterval * 0.4));
4367 incrementDelta *= boundedRandDelta;
4368 retryData.retryInterval = Math.min(policy.minRetryInterval + incrementDelta, policy.maxRetryInterval);
4369 return retryData;
4370}
4371function retry$1(policy, request, operationResponse, err, retryData) {
4372 return tslib.__awaiter(this, void 0, void 0, function () {
4373 var error_1;
4374 return tslib.__generator(this, function (_a) {
4375 switch (_a.label) {
4376 case 0:
4377 retryData = updateRetryData$1(policy, retryData, err);
4378 if (!(err &&
4379 err.code &&
4380 shouldRetry$1(policy, retryData) &&
4381 (err.code === "ETIMEDOUT" ||
4382 err.code === "ESOCKETTIMEDOUT" ||
4383 err.code === "ECONNREFUSED" ||
4384 err.code === "ECONNRESET" ||
4385 err.code === "ENOENT"))) return [3 /*break*/, 5];
4386 _a.label = 1;
4387 case 1:
4388 _a.trys.push([1, 3, , 4]);
4389 return [4 /*yield*/, delay(retryData.retryInterval)];
4390 case 2:
4391 _a.sent();
4392 return [2 /*return*/, policy._nextPolicy.sendRequest(request.clone())];
4393 case 3:
4394 error_1 = _a.sent();
4395 return [2 /*return*/, retry$1(policy, request, operationResponse, error_1, retryData)];
4396 case 4: return [3 /*break*/, 6];
4397 case 5:
4398 if (err) {
4399 // If the operation failed in the end, return all errors instead of just the last one
4400 return [2 /*return*/, Promise.reject(retryData.error)];
4401 }
4402 return [2 /*return*/, operationResponse];
4403 case 6: return [2 /*return*/];
4404 }
4405 });
4406 });
4407}
4408
4409// Copyright (c) Microsoft Corporation. All rights reserved.
4410(function (QueryCollectionFormat) {
4411 QueryCollectionFormat["Csv"] = ",";
4412 QueryCollectionFormat["Ssv"] = " ";
4413 QueryCollectionFormat["Tsv"] = "\t";
4414 QueryCollectionFormat["Pipes"] = "|";
4415 QueryCollectionFormat["Multi"] = "Multi";
4416})(exports.QueryCollectionFormat || (exports.QueryCollectionFormat = {}));
4417
4418// Copyright (c) Microsoft Corporation. All rights reserved.
4419function agentPolicy(agentSettings) {
4420 return {
4421 create: function (nextPolicy, options) {
4422 return new AgentPolicy(nextPolicy, options, agentSettings);
4423 },
4424 };
4425}
4426var AgentPolicy = /** @class */ (function (_super) {
4427 tslib.__extends(AgentPolicy, _super);
4428 function AgentPolicy(nextPolicy, options, agentSettings) {
4429 var _this = _super.call(this, nextPolicy, options) || this;
4430 _this.agentSettings = agentSettings;
4431 return _this;
4432 }
4433 AgentPolicy.prototype.sendRequest = function (request) {
4434 if (!request.agentSettings) {
4435 request.agentSettings = this.agentSettings;
4436 }
4437 return this._nextPolicy.sendRequest(request);
4438 };
4439 return AgentPolicy;
4440}(BaseRequestPolicy));
4441
4442// Copyright (c) Microsoft Corporation. All rights reserved.
4443/**
4444 * @internal
4445 */
4446var noProxyList = loadNoProxy();
4447var byPassedList = new Map();
4448/**
4449 * @internal
4450 */
4451function getEnvironmentValue(name) {
4452 if (process.env[name]) {
4453 return process.env[name];
4454 }
4455 else if (process.env[name.toLowerCase()]) {
4456 return process.env[name.toLowerCase()];
4457 }
4458 return undefined;
4459}
4460function loadEnvironmentProxyValue() {
4461 if (!process) {
4462 return undefined;
4463 }
4464 var httpsProxy = getEnvironmentValue(Constants.HTTPS_PROXY);
4465 var allProxy = getEnvironmentValue(Constants.ALL_PROXY);
4466 var httpProxy = getEnvironmentValue(Constants.HTTP_PROXY);
4467 return httpsProxy || allProxy || httpProxy;
4468}
4469// Check whether the host of a given `uri` is in the noProxyList.
4470// If there's a match, any request sent to the same host won't have the proxy settings set.
4471// This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210
4472function isBypassed(uri) {
4473 if (noProxyList.length === 0) {
4474 return false;
4475 }
4476 var host = URLBuilder.parse(uri).getHost();
4477 if (byPassedList.has(host)) {
4478 return byPassedList.get(host);
4479 }
4480 var isBypassedFlag = false;
4481 for (var _i = 0, noProxyList_1 = noProxyList; _i < noProxyList_1.length; _i++) {
4482 var pattern = noProxyList_1[_i];
4483 if (pattern[0] === ".") {
4484 // This should match either domain it self or any subdomain or host
4485 // .foo.com will match foo.com it self or *.foo.com
4486 if (host.endsWith(pattern)) {
4487 isBypassedFlag = true;
4488 }
4489 else {
4490 if (host.length === pattern.length - 1 && host === pattern.slice(1)) {
4491 isBypassedFlag = true;
4492 }
4493 }
4494 }
4495 else {
4496 if (host === pattern) {
4497 isBypassedFlag = true;
4498 }
4499 }
4500 }
4501 byPassedList.set(host, isBypassedFlag);
4502 return isBypassedFlag;
4503}
4504/**
4505 * @internal
4506 */
4507function loadNoProxy() {
4508 var noProxy = getEnvironmentValue(Constants.NO_PROXY);
4509 if (noProxy) {
4510 return noProxy
4511 .split(",")
4512 .map(function (item) { return item.trim(); })
4513 .filter(function (item) { return item.length; });
4514 }
4515 return [];
4516}
4517/**
4518 * @internal
4519 */
4520function extractAuthFromUrl(url) {
4521 var atIndex = url.indexOf("@");
4522 if (atIndex === -1) {
4523 return { urlWithoutAuth: url };
4524 }
4525 var schemeIndex = url.indexOf("://");
4526 var authStart = schemeIndex !== -1 ? schemeIndex + 3 : 0;
4527 var auth = url.substring(authStart, atIndex);
4528 var colonIndex = auth.indexOf(":");
4529 var hasPassword = colonIndex !== -1;
4530 var username = hasPassword ? auth.substring(0, colonIndex) : auth;
4531 var password = hasPassword ? auth.substring(colonIndex + 1) : undefined;
4532 var urlWithoutAuth = url.substring(0, authStart) + url.substring(atIndex + 1);
4533 return {
4534 username: username,
4535 password: password,
4536 urlWithoutAuth: urlWithoutAuth,
4537 };
4538}
4539function getDefaultProxySettings(proxyUrl) {
4540 if (!proxyUrl) {
4541 proxyUrl = loadEnvironmentProxyValue();
4542 if (!proxyUrl) {
4543 return undefined;
4544 }
4545 }
4546 var _a = extractAuthFromUrl(proxyUrl), username = _a.username, password = _a.password, urlWithoutAuth = _a.urlWithoutAuth;
4547 var parsedUrl = URLBuilder.parse(urlWithoutAuth);
4548 var schema = parsedUrl.getScheme() ? parsedUrl.getScheme() + "://" : "";
4549 return {
4550 host: schema + parsedUrl.getHost(),
4551 port: Number.parseInt(parsedUrl.getPort() || "80"),
4552 username: username,
4553 password: password,
4554 };
4555}
4556function proxyPolicy(proxySettings) {
4557 if (!proxySettings) {
4558 proxySettings = getDefaultProxySettings();
4559 }
4560 return {
4561 create: function (nextPolicy, options) {
4562 return new ProxyPolicy(nextPolicy, options, proxySettings);
4563 },
4564 };
4565}
4566var ProxyPolicy = /** @class */ (function (_super) {
4567 tslib.__extends(ProxyPolicy, _super);
4568 function ProxyPolicy(nextPolicy, options, proxySettings) {
4569 var _this = _super.call(this, nextPolicy, options) || this;
4570 _this.proxySettings = proxySettings;
4571 return _this;
4572 }
4573 ProxyPolicy.prototype.sendRequest = function (request) {
4574 if (!request.proxySettings && !isBypassed(request.url)) {
4575 request.proxySettings = this.proxySettings;
4576 }
4577 return this._nextPolicy.sendRequest(request);
4578 };
4579 return ProxyPolicy;
4580}(BaseRequestPolicy));
4581
4582// Copyright (c) Microsoft Corporation. All rights reserved.
4583var StatusCodes = Constants.HttpConstants.StatusCodes;
4584var DEFAULT_RETRY_COUNT = 3;
4585function throttlingRetryPolicy(maxRetries) {
4586 if (maxRetries === void 0) { maxRetries = DEFAULT_RETRY_COUNT; }
4587 return {
4588 create: function (nextPolicy, options) {
4589 return new ThrottlingRetryPolicy(nextPolicy, options, maxRetries);
4590 },
4591 };
4592}
4593/**
4594 * To learn more, please refer to
4595 * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits,
4596 * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and
4597 * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors
4598 */
4599var ThrottlingRetryPolicy = /** @class */ (function (_super) {
4600 tslib.__extends(ThrottlingRetryPolicy, _super);
4601 function ThrottlingRetryPolicy(nextPolicy, options, retryLimit) {
4602 var _this = _super.call(this, nextPolicy, options) || this;
4603 _this.retryLimit = retryLimit;
4604 return _this;
4605 }
4606 ThrottlingRetryPolicy.prototype.sendRequest = function (httpRequest) {
4607 return tslib.__awaiter(this, void 0, void 0, function () {
4608 var _this = this;
4609 return tslib.__generator(this, function (_a) {
4610 return [2 /*return*/, this._nextPolicy.sendRequest(httpRequest.clone()).then(function (response) {
4611 return _this.retry(httpRequest, response, 0);
4612 })];
4613 });
4614 });
4615 };
4616 ThrottlingRetryPolicy.prototype.retry = function (httpRequest, httpResponse, retryCount) {
4617 return tslib.__awaiter(this, void 0, void 0, function () {
4618 var retryAfterHeader, delayInMs, res;
4619 return tslib.__generator(this, function (_a) {
4620 switch (_a.label) {
4621 case 0:
4622 if (httpResponse.status !== StatusCodes.TooManyRequests) {
4623 return [2 /*return*/, httpResponse];
4624 }
4625 retryAfterHeader = httpResponse.headers.get(Constants.HeaderConstants.RETRY_AFTER);
4626 if (!(retryAfterHeader && retryCount < this.retryLimit)) return [3 /*break*/, 3];
4627 delayInMs = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader);
4628 if (!delayInMs) return [3 /*break*/, 3];
4629 return [4 /*yield*/, delay(delayInMs)];
4630 case 1:
4631 _a.sent();
4632 return [4 /*yield*/, this._nextPolicy.sendRequest(httpRequest)];
4633 case 2:
4634 res = _a.sent();
4635 return [2 /*return*/, this.retry(httpRequest, res, retryCount + 1)];
4636 case 3: return [2 /*return*/, httpResponse];
4637 }
4638 });
4639 });
4640 };
4641 ThrottlingRetryPolicy.parseRetryAfterHeader = function (headerValue) {
4642 var retryAfterInSeconds = Number(headerValue);
4643 if (Number.isNaN(retryAfterInSeconds)) {
4644 return ThrottlingRetryPolicy.parseDateRetryAfterHeader(headerValue);
4645 }
4646 else {
4647 return retryAfterInSeconds * 1000;
4648 }
4649 };
4650 ThrottlingRetryPolicy.parseDateRetryAfterHeader = function (headerValue) {
4651 try {
4652 var now = Date.now();
4653 var date = Date.parse(headerValue);
4654 var diff = date - now;
4655 return Number.isNaN(diff) ? undefined : diff;
4656 }
4657 catch (error) {
4658 return undefined;
4659 }
4660 };
4661 return ThrottlingRetryPolicy;
4662}(BaseRequestPolicy));
4663
4664// Copyright (c) Microsoft Corporation. All rights reserved.
4665var DEFAULT_AUTHORIZATION_SCHEME = "Bearer";
4666/**
4667 * Resource manager endpoints to match in order to specify a valid scope to the AzureIdentityCredentialAdapter.
4668 */
4669var azureResourceManagerEndpoints = [
4670 "https://management.windows.net",
4671 "https://management.chinacloudapi.cn",
4672 "https://management.usgovcloudapi.net",
4673 "https://management.cloudapi.de",
4674];
4675/**
4676 * This class provides a simple extension to use {@link TokenCredential} from `@azure/identity` library to
4677 * use with legacy Azure SDKs that accept {@link ServiceClientCredentials} family of credentials for authentication.
4678 */
4679var AzureIdentityCredentialAdapter = /** @class */ (function () {
4680 function AzureIdentityCredentialAdapter(azureTokenCredential, scopes) {
4681 if (scopes === void 0) { scopes = "https://management.azure.com/.default"; }
4682 this.azureTokenCredential = azureTokenCredential;
4683 this.scopes = scopes;
4684 }
4685 AzureIdentityCredentialAdapter.prototype.getToken = function () {
4686 return tslib.__awaiter(this, void 0, void 0, function () {
4687 var accessToken, result;
4688 return tslib.__generator(this, function (_a) {
4689 switch (_a.label) {
4690 case 0: return [4 /*yield*/, this.azureTokenCredential.getToken(this.scopes)];
4691 case 1:
4692 accessToken = _a.sent();
4693 if (accessToken !== null) {
4694 result = {
4695 accessToken: accessToken.token,
4696 tokenType: DEFAULT_AUTHORIZATION_SCHEME,
4697 expiresOn: accessToken.expiresOnTimestamp,
4698 };
4699 return [2 /*return*/, result];
4700 }
4701 else {
4702 throw new Error("Could find token for scope");
4703 }
4704 }
4705 });
4706 });
4707 };
4708 AzureIdentityCredentialAdapter.prototype.signRequest = function (webResource) {
4709 return tslib.__awaiter(this, void 0, void 0, function () {
4710 var tokenResponse;
4711 return tslib.__generator(this, function (_a) {
4712 switch (_a.label) {
4713 case 0: return [4 /*yield*/, this.getToken()];
4714 case 1:
4715 tokenResponse = _a.sent();
4716 webResource.headers.set(Constants.HeaderConstants.AUTHORIZATION, tokenResponse.tokenType + " " + tokenResponse.accessToken);
4717 return [2 /*return*/, Promise.resolve(webResource)];
4718 }
4719 });
4720 });
4721 };
4722 return AzureIdentityCredentialAdapter;
4723}());
4724
4725// Copyright (c) Microsoft Corporation. All rights reserved.
4726/**
4727 * @class
4728 * Initializes a new instance of the ServiceClient.
4729 */
4730var ServiceClient = /** @class */ (function () {
4731 /**
4732 * The ServiceClient constructor
4733 * @constructor
4734 * @param {ServiceClientCredentials} [credentials] The credentials object used for authentication.
4735 * @param {ServiceClientOptions} [options] The service client options that govern the behavior of the client.
4736 */
4737 function ServiceClient(credentials, options) {
4738 if (!options) {
4739 options = {};
4740 }
4741 if (options.baseUri) {
4742 this.baseUri = options.baseUri;
4743 }
4744 var serviceClientCredentials;
4745 if (isTokenCredential(credentials)) {
4746 var scope = undefined;
4747 if ((options === null || options === void 0 ? void 0 : options.baseUri) && azureResourceManagerEndpoints.includes(options === null || options === void 0 ? void 0 : options.baseUri)) {
4748 scope = options.baseUri + "/.default";
4749 }
4750 serviceClientCredentials = new AzureIdentityCredentialAdapter(credentials, scope);
4751 }
4752 else {
4753 serviceClientCredentials = credentials;
4754 }
4755 if (serviceClientCredentials && !serviceClientCredentials.signRequest) {
4756 throw new Error("credentials argument needs to implement signRequest method");
4757 }
4758 this._withCredentials = options.withCredentials || false;
4759 this._httpClient = options.httpClient || new NodeFetchHttpClient();
4760 this._requestPolicyOptions = new RequestPolicyOptions(options.httpPipelineLogger);
4761 var requestPolicyFactories;
4762 if (Array.isArray(options.requestPolicyFactories)) {
4763 requestPolicyFactories = options.requestPolicyFactories;
4764 }
4765 else {
4766 requestPolicyFactories = createDefaultRequestPolicyFactories(serviceClientCredentials, options);
4767 if (options.requestPolicyFactories) {
4768 var newRequestPolicyFactories = options.requestPolicyFactories(requestPolicyFactories);
4769 if (newRequestPolicyFactories) {
4770 requestPolicyFactories = newRequestPolicyFactories;
4771 }
4772 }
4773 }
4774 this._requestPolicyFactories = requestPolicyFactories;
4775 }
4776 /**
4777 * Send the provided httpRequest.
4778 */
4779 ServiceClient.prototype.sendRequest = function (options) {
4780 if (options === null || options === undefined || typeof options !== "object") {
4781 throw new Error("options cannot be null or undefined and it must be of type object.");
4782 }
4783 var httpRequest;
4784 try {
4785 if (isWebResourceLike(options)) {
4786 options.validateRequestProperties();
4787 httpRequest = options;
4788 }
4789 else {
4790 httpRequest = new WebResource();
4791 httpRequest = httpRequest.prepare(options);
4792 }
4793 }
4794 catch (error) {
4795 return Promise.reject(error);
4796 }
4797 var httpPipeline = this._httpClient;
4798 if (this._requestPolicyFactories && this._requestPolicyFactories.length > 0) {
4799 for (var i = this._requestPolicyFactories.length - 1; i >= 0; --i) {
4800 httpPipeline = this._requestPolicyFactories[i].create(httpPipeline, this._requestPolicyOptions);
4801 }
4802 }
4803 return httpPipeline.sendRequest(httpRequest);
4804 };
4805 /**
4806 * Send an HTTP request that is populated using the provided OperationSpec.
4807 * @param {OperationArguments} operationArguments The arguments that the HTTP request's templated values will be populated from.
4808 * @param {OperationSpec} operationSpec The OperationSpec to use to populate the httpRequest.
4809 * @param {ServiceCallback} callback The callback to call when the response is received.
4810 */
4811 ServiceClient.prototype.sendOperationRequest = function (operationArguments, operationSpec, callback) {
4812 if (typeof operationArguments.options === "function") {
4813 callback = operationArguments.options;
4814 operationArguments.options = undefined;
4815 }
4816 var httpRequest = new WebResource();
4817 var result;
4818 try {
4819 var baseUri = operationSpec.baseUrl || this.baseUri;
4820 if (!baseUri) {
4821 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.");
4822 }
4823 httpRequest.method = operationSpec.httpMethod;
4824 httpRequest.operationSpec = operationSpec;
4825 var requestUrl = URLBuilder.parse(baseUri);
4826 if (operationSpec.path) {
4827 requestUrl.appendPath(operationSpec.path);
4828 }
4829 if (operationSpec.urlParameters && operationSpec.urlParameters.length > 0) {
4830 for (var _i = 0, _a = operationSpec.urlParameters; _i < _a.length; _i++) {
4831 var urlParameter = _a[_i];
4832 var urlParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, urlParameter, operationSpec.serializer);
4833 urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, getPathStringFromParameter(urlParameter));
4834 if (!urlParameter.skipEncoding) {
4835 urlParameterValue = encodeURIComponent(urlParameterValue);
4836 }
4837 requestUrl.replaceAll("{" + (urlParameter.mapper.serializedName || getPathStringFromParameter(urlParameter)) + "}", urlParameterValue);
4838 }
4839 }
4840 if (operationSpec.queryParameters && operationSpec.queryParameters.length > 0) {
4841 for (var _b = 0, _c = operationSpec.queryParameters; _b < _c.length; _b++) {
4842 var queryParameter = _c[_b];
4843 var queryParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, queryParameter, operationSpec.serializer);
4844 if (queryParameterValue != undefined) {
4845 queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter));
4846 if (queryParameter.collectionFormat != undefined) {
4847 if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Multi) {
4848 if (queryParameterValue.length === 0) {
4849 queryParameterValue = "";
4850 }
4851 else {
4852 for (var index in queryParameterValue) {
4853 var item = queryParameterValue[index];
4854 queryParameterValue[index] = item == undefined ? "" : item.toString();
4855 }
4856 }
4857 }
4858 else if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Ssv ||
4859 queryParameter.collectionFormat === exports.QueryCollectionFormat.Tsv) {
4860 queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat);
4861 }
4862 }
4863 if (!queryParameter.skipEncoding) {
4864 if (Array.isArray(queryParameterValue)) {
4865 for (var index in queryParameterValue) {
4866 if (queryParameterValue[index] !== undefined &&
4867 queryParameterValue[index] !== null) {
4868 queryParameterValue[index] = encodeURIComponent(queryParameterValue[index]);
4869 }
4870 }
4871 }
4872 else {
4873 queryParameterValue = encodeURIComponent(queryParameterValue);
4874 }
4875 }
4876 if (queryParameter.collectionFormat != undefined &&
4877 queryParameter.collectionFormat !== exports.QueryCollectionFormat.Multi &&
4878 queryParameter.collectionFormat !== exports.QueryCollectionFormat.Ssv &&
4879 queryParameter.collectionFormat !== exports.QueryCollectionFormat.Tsv) {
4880 queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat);
4881 }
4882 requestUrl.setQueryParameter(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue);
4883 }
4884 }
4885 }
4886 httpRequest.url = requestUrl.toString();
4887 var contentType = operationSpec.contentType || this.requestContentType;
4888 if (contentType) {
4889 httpRequest.headers.set("Content-Type", contentType);
4890 }
4891 if (operationSpec.headerParameters) {
4892 for (var _d = 0, _e = operationSpec.headerParameters; _d < _e.length; _d++) {
4893 var headerParameter = _e[_d];
4894 var headerValue = getOperationArgumentValueFromParameter(this, operationArguments, headerParameter, operationSpec.serializer);
4895 if (headerValue != undefined) {
4896 headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter));
4897 var headerCollectionPrefix = headerParameter.mapper
4898 .headerCollectionPrefix;
4899 if (headerCollectionPrefix) {
4900 for (var _f = 0, _g = Object.keys(headerValue); _f < _g.length; _f++) {
4901 var key = _g[_f];
4902 httpRequest.headers.set(headerCollectionPrefix + key, headerValue[key]);
4903 }
4904 }
4905 else {
4906 httpRequest.headers.set(headerParameter.mapper.serializedName ||
4907 getPathStringFromParameter(headerParameter), headerValue);
4908 }
4909 }
4910 }
4911 }
4912 var options = operationArguments.options;
4913 if (options) {
4914 if (options.customHeaders) {
4915 for (var customHeaderName in options.customHeaders) {
4916 httpRequest.headers.set(customHeaderName, options.customHeaders[customHeaderName]);
4917 }
4918 }
4919 if (options.abortSignal) {
4920 httpRequest.abortSignal = options.abortSignal;
4921 }
4922 if (options.timeout) {
4923 httpRequest.timeout = options.timeout;
4924 }
4925 if (options.onUploadProgress) {
4926 httpRequest.onUploadProgress = options.onUploadProgress;
4927 }
4928 if (options.onDownloadProgress) {
4929 httpRequest.onDownloadProgress = options.onDownloadProgress;
4930 }
4931 }
4932 httpRequest.withCredentials = this._withCredentials;
4933 serializeRequestBody(this, httpRequest, operationArguments, operationSpec);
4934 if (httpRequest.streamResponseBody == undefined) {
4935 httpRequest.streamResponseBody = isStreamOperation(operationSpec);
4936 }
4937 result = this.sendRequest(httpRequest).then(function (res) {
4938 return flattenResponse(res, operationSpec.responses[res.status]);
4939 });
4940 }
4941 catch (error) {
4942 result = Promise.reject(error);
4943 }
4944 var cb = callback;
4945 if (cb) {
4946 result
4947 // tslint:disable-next-line:no-null-keyword
4948 .then(function (res) { return cb(null, res._response.parsedBody, res._response.request, res._response); })
4949 .catch(function (err) { return cb(err); });
4950 }
4951 return result;
4952 };
4953 return ServiceClient;
4954}());
4955function serializeRequestBody(serviceClient, httpRequest, operationArguments, operationSpec) {
4956 if (operationSpec.requestBody && operationSpec.requestBody.mapper) {
4957 httpRequest.body = getOperationArgumentValueFromParameter(serviceClient, operationArguments, operationSpec.requestBody, operationSpec.serializer);
4958 var bodyMapper = operationSpec.requestBody.mapper;
4959 var required = bodyMapper.required, xmlName = bodyMapper.xmlName, xmlElementName = bodyMapper.xmlElementName, serializedName = bodyMapper.serializedName;
4960 var typeName = bodyMapper.type.name;
4961 try {
4962 if (httpRequest.body != undefined || required) {
4963 var requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody);
4964 httpRequest.body = operationSpec.serializer.serialize(bodyMapper, httpRequest.body, requestBodyParameterPathString);
4965 var isStream = typeName === MapperType.Stream;
4966 if (operationSpec.isXML) {
4967 if (typeName === MapperType.Sequence) {
4968 httpRequest.body = stringifyXML(prepareXMLRootList(httpRequest.body, xmlElementName || xmlName || serializedName), { rootName: xmlName || serializedName });
4969 }
4970 else if (!isStream) {
4971 httpRequest.body = stringifyXML(httpRequest.body, {
4972 rootName: xmlName || serializedName,
4973 });
4974 }
4975 }
4976 else if (!isStream) {
4977 httpRequest.body = JSON.stringify(httpRequest.body);
4978 }
4979 }
4980 }
4981 catch (error) {
4982 throw new Error("Error \"" + error.message + "\" occurred in serializing the payload - " + JSON.stringify(serializedName, undefined, " ") + ".");
4983 }
4984 }
4985 else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) {
4986 httpRequest.formData = {};
4987 for (var _i = 0, _a = operationSpec.formDataParameters; _i < _a.length; _i++) {
4988 var formDataParameter = _a[_i];
4989 var formDataParameterValue = getOperationArgumentValueFromParameter(serviceClient, operationArguments, formDataParameter, operationSpec.serializer);
4990 if (formDataParameterValue != undefined) {
4991 var formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter);
4992 httpRequest.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter));
4993 }
4994 }
4995 }
4996}
4997function isRequestPolicyFactory(instance) {
4998 return typeof instance.create === "function";
4999}
5000function getValueOrFunctionResult(value, defaultValueCreator) {
5001 var result;
5002 if (typeof value === "string") {
5003 result = value;
5004 }
5005 else {
5006 result = defaultValueCreator();
5007 if (typeof value === "function") {
5008 result = value(result);
5009 }
5010 }
5011 return result;
5012}
5013function createDefaultRequestPolicyFactories(credentials, options) {
5014 var factories = [];
5015 if (options.generateClientRequestIdHeader) {
5016 factories.push(generateClientRequestIdPolicy(options.clientRequestIdHeaderName));
5017 }
5018 if (credentials) {
5019 if (isRequestPolicyFactory(credentials)) {
5020 factories.push(credentials);
5021 }
5022 else {
5023 factories.push(signingPolicy(credentials));
5024 }
5025 }
5026 var userAgentHeaderName = getValueOrFunctionResult(options.userAgentHeaderName, getDefaultUserAgentHeaderName);
5027 var userAgentHeaderValue = getValueOrFunctionResult(options.userAgent, getDefaultUserAgentValue);
5028 if (userAgentHeaderName && userAgentHeaderValue) {
5029 factories.push(userAgentPolicy({ key: userAgentHeaderName, value: userAgentHeaderValue }));
5030 }
5031 var redirectOptions = tslib.__assign(tslib.__assign({}, DefaultRedirectOptions), options.redirectOptions);
5032 if (redirectOptions.handleRedirects) {
5033 factories.push(redirectPolicy(redirectOptions.maxRetries));
5034 }
5035 factories.push(rpRegistrationPolicy(options.rpRegistrationRetryTimeout));
5036 if (!options.noRetryPolicy) {
5037 factories.push(exponentialRetryPolicy());
5038 factories.push(systemErrorRetryPolicy());
5039 factories.push(throttlingRetryPolicy());
5040 }
5041 factories.push(deserializationPolicy(options.deserializationContentTypes));
5042 var proxySettings = options.proxySettings || getDefaultProxySettings();
5043 if (proxySettings) {
5044 factories.push(proxyPolicy(proxySettings));
5045 }
5046 if (options.agentSettings) {
5047 factories.push(agentPolicy(options.agentSettings));
5048 }
5049 return factories;
5050}
5051function getOperationArgumentValueFromParameter(serviceClient, operationArguments, parameter, serializer) {
5052 return getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameter.parameterPath, parameter.mapper, serializer);
5053}
5054function getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, serializer) {
5055 var value;
5056 if (typeof parameterPath === "string") {
5057 parameterPath = [parameterPath];
5058 }
5059 if (Array.isArray(parameterPath)) {
5060 if (parameterPath.length > 0) {
5061 if (parameterMapper.isConstant) {
5062 value = parameterMapper.defaultValue;
5063 }
5064 else {
5065 var propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath);
5066 if (!propertySearchResult.propertyFound) {
5067 propertySearchResult = getPropertyFromParameterPath(serviceClient, parameterPath);
5068 }
5069 var useDefaultValue = false;
5070 if (!propertySearchResult.propertyFound) {
5071 useDefaultValue =
5072 parameterMapper.required ||
5073 (parameterPath[0] === "options" && parameterPath.length === 2);
5074 }
5075 value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue;
5076 }
5077 // Serialize just for validation purposes.
5078 var parameterPathString = getPathStringFromParameterPath(parameterPath, parameterMapper);
5079 serializer.serialize(parameterMapper, value, parameterPathString);
5080 }
5081 }
5082 else {
5083 if (parameterMapper.required) {
5084 value = {};
5085 }
5086 for (var propertyName in parameterPath) {
5087 var propertyMapper = parameterMapper.type.modelProperties[propertyName];
5088 var propertyPath = parameterPath[propertyName];
5089 var propertyValue = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, propertyPath, propertyMapper, serializer);
5090 // Serialize just for validation purposes.
5091 var propertyPathString = getPathStringFromParameterPath(propertyPath, propertyMapper);
5092 serializer.serialize(propertyMapper, propertyValue, propertyPathString);
5093 if (propertyValue !== undefined) {
5094 if (!value) {
5095 value = {};
5096 }
5097 value[propertyName] = propertyValue;
5098 }
5099 }
5100 }
5101 return value;
5102}
5103function getPropertyFromParameterPath(parent, parameterPath) {
5104 var result = { propertyFound: false };
5105 var i = 0;
5106 for (; i < parameterPath.length; ++i) {
5107 var parameterPathPart = parameterPath[i];
5108 // Make sure to check inherited properties too, so don't use hasOwnProperty().
5109 if (parent != undefined && parameterPathPart in parent) {
5110 parent = parent[parameterPathPart];
5111 }
5112 else {
5113 break;
5114 }
5115 }
5116 if (i === parameterPath.length) {
5117 result.propertyValue = parent;
5118 result.propertyFound = true;
5119 }
5120 return result;
5121}
5122function flattenResponse(_response, responseSpec) {
5123 var parsedHeaders = _response.parsedHeaders;
5124 var bodyMapper = responseSpec && responseSpec.bodyMapper;
5125 var addOperationResponse = function (obj) {
5126 return Object.defineProperty(obj, "_response", {
5127 value: _response,
5128 });
5129 };
5130 if (bodyMapper) {
5131 var typeName = bodyMapper.type.name;
5132 if (typeName === "Stream") {
5133 return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), { blobBody: _response.blobBody, readableStreamBody: _response.readableStreamBody }));
5134 }
5135 var modelProperties_1 = (typeName === "Composite" && bodyMapper.type.modelProperties) || {};
5136 var isPageableResponse = Object.keys(modelProperties_1).some(function (k) { return modelProperties_1[k].serializedName === ""; });
5137 if (typeName === "Sequence" || isPageableResponse) {
5138 // We're expecting a sequece(array) make sure that the response body is in the
5139 // correct format, if not make it an empty array []
5140 var parsedBody = Array.isArray(_response.parsedBody) ? _response.parsedBody : [];
5141 var arrayResponse = tslib.__spreadArrays(parsedBody);
5142 for (var _i = 0, _a = Object.keys(modelProperties_1); _i < _a.length; _i++) {
5143 var key = _a[_i];
5144 if (modelProperties_1[key].serializedName) {
5145 arrayResponse[key] = _response.parsedBody[key];
5146 }
5147 }
5148 if (parsedHeaders) {
5149 for (var _b = 0, _c = Object.keys(parsedHeaders); _b < _c.length; _b++) {
5150 var key = _c[_b];
5151 arrayResponse[key] = parsedHeaders[key];
5152 }
5153 }
5154 addOperationResponse(arrayResponse);
5155 return arrayResponse;
5156 }
5157 if (typeName === "Composite" || typeName === "Dictionary") {
5158 return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), _response.parsedBody));
5159 }
5160 }
5161 if (bodyMapper ||
5162 _response.request.method === "HEAD" ||
5163 isPrimitiveType(_response.parsedBody)) {
5164 // primitive body types and HEAD booleans
5165 return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), { body: _response.parsedBody }));
5166 }
5167 return addOperationResponse(tslib.__assign(tslib.__assign({}, parsedHeaders), _response.parsedBody));
5168}
5169
5170// Copyright (c) Microsoft Corporation. All rights reserved.
5171function logPolicy(logger) {
5172 if (logger === void 0) { logger = console.log; }
5173 return {
5174 create: function (nextPolicy, options) {
5175 return new LogPolicy(nextPolicy, options, logger);
5176 },
5177 };
5178}
5179var LogPolicy = /** @class */ (function (_super) {
5180 tslib.__extends(LogPolicy, _super);
5181 function LogPolicy(nextPolicy, options, logger) {
5182 if (logger === void 0) { logger = console.log; }
5183 var _this = _super.call(this, nextPolicy, options) || this;
5184 _this.logger = logger;
5185 return _this;
5186 }
5187 LogPolicy.prototype.sendRequest = function (request) {
5188 var _this = this;
5189 return this._nextPolicy.sendRequest(request).then(function (response) { return logResponse(_this, response); });
5190 };
5191 return LogPolicy;
5192}(BaseRequestPolicy));
5193function logResponse(policy, response) {
5194 policy.logger(">> Request: " + JSON.stringify(response.request, undefined, 2));
5195 policy.logger(">> Response status code: " + response.status);
5196 var responseBody = response.bodyAsText;
5197 policy.logger(">> Body: " + responseBody);
5198 return Promise.resolve(response);
5199}
5200
5201// Copyright (c) Microsoft Corporation. All rights reserved.
5202var HeaderConstants = Constants.HeaderConstants;
5203var DEFAULT_AUTHORIZATION_SCHEME$1 = "Bearer";
5204/**
5205 * A credentials object that uses a token string and a authorzation scheme to authenticate.
5206 */
5207var TokenCredentials = /** @class */ (function () {
5208 /**
5209 * Creates a new TokenCredentials object.
5210 *
5211 * @constructor
5212 * @param {string} token The token.
5213 * @param {string} [authorizationScheme] The authorization scheme.
5214 */
5215 function TokenCredentials(token, authorizationScheme) {
5216 if (authorizationScheme === void 0) { authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$1; }
5217 this.authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$1;
5218 if (!token) {
5219 throw new Error("token cannot be null or undefined.");
5220 }
5221 this.token = token;
5222 this.authorizationScheme = authorizationScheme;
5223 }
5224 /**
5225 * Signs a request with the Authentication header.
5226 *
5227 * @param {WebResourceLike} webResource The WebResourceLike to be signed.
5228 * @return {Promise<WebResourceLike>} The signed request object.
5229 */
5230 TokenCredentials.prototype.signRequest = function (webResource) {
5231 if (!webResource.headers)
5232 webResource.headers = new HttpHeaders();
5233 webResource.headers.set(HeaderConstants.AUTHORIZATION, this.authorizationScheme + " " + this.token);
5234 return Promise.resolve(webResource);
5235 };
5236 return TokenCredentials;
5237}());
5238
5239// Copyright (c) Microsoft Corporation. All rights reserved.
5240var HeaderConstants$1 = Constants.HeaderConstants;
5241var DEFAULT_AUTHORIZATION_SCHEME$2 = "Basic";
5242var BasicAuthenticationCredentials = /** @class */ (function () {
5243 /**
5244 * Creates a new BasicAuthenticationCredentials object.
5245 *
5246 * @constructor
5247 * @param {string} userName User name.
5248 * @param {string} password Password.
5249 * @param {string} [authorizationScheme] The authorization scheme.
5250 */
5251 function BasicAuthenticationCredentials(userName, password, authorizationScheme) {
5252 if (authorizationScheme === void 0) { authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$2; }
5253 this.authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$2;
5254 if (userName === null || userName === undefined || typeof userName.valueOf() !== "string") {
5255 throw new Error("userName cannot be null or undefined and must be of type string.");
5256 }
5257 if (password === null || password === undefined || typeof password.valueOf() !== "string") {
5258 throw new Error("password cannot be null or undefined and must be of type string.");
5259 }
5260 this.userName = userName;
5261 this.password = password;
5262 this.authorizationScheme = authorizationScheme;
5263 }
5264 /**
5265 * Signs a request with the Authentication header.
5266 *
5267 * @param {WebResourceLike} webResource The WebResourceLike to be signed.
5268 * @returns {Promise<WebResourceLike>} The signed request object.
5269 */
5270 BasicAuthenticationCredentials.prototype.signRequest = function (webResource) {
5271 var credentials = this.userName + ":" + this.password;
5272 var encodedCredentials = this.authorizationScheme + " " + encodeString(credentials);
5273 if (!webResource.headers)
5274 webResource.headers = new HttpHeaders();
5275 webResource.headers.set(HeaderConstants$1.AUTHORIZATION, encodedCredentials);
5276 return Promise.resolve(webResource);
5277 };
5278 return BasicAuthenticationCredentials;
5279}());
5280
5281// Copyright (c) Microsoft Corporation. All rights reserved.
5282/**
5283 * Authenticates to a service using an API key.
5284 */
5285var ApiKeyCredentials = /** @class */ (function () {
5286 /**
5287 * @constructor
5288 * @param {object} options Specifies the options to be provided for auth. Either header or query needs to be provided.
5289 */
5290 function ApiKeyCredentials(options) {
5291 if (!options || (options && !options.inHeader && !options.inQuery)) {
5292 throw new Error("options cannot be null or undefined. Either \"inHeader\" or \"inQuery\" property of the options object needs to be provided.");
5293 }
5294 this.inHeader = options.inHeader;
5295 this.inQuery = options.inQuery;
5296 }
5297 /**
5298 * Signs a request with the values provided in the inHeader and inQuery parameter.
5299 *
5300 * @param {WebResource} webResource The WebResource to be signed.
5301 * @returns {Promise<WebResource>} The signed request object.
5302 */
5303 ApiKeyCredentials.prototype.signRequest = function (webResource) {
5304 if (!webResource) {
5305 return Promise.reject(new Error("webResource cannot be null or undefined and must be of type \"object\"."));
5306 }
5307 if (this.inHeader) {
5308 if (!webResource.headers) {
5309 webResource.headers = new HttpHeaders();
5310 }
5311 for (var headerName in this.inHeader) {
5312 webResource.headers.set(headerName, this.inHeader[headerName]);
5313 }
5314 }
5315 if (this.inQuery) {
5316 if (!webResource.url) {
5317 return Promise.reject(new Error("url cannot be null in the request object."));
5318 }
5319 if (webResource.url.indexOf("?") < 0) {
5320 webResource.url += "?";
5321 }
5322 for (var key in this.inQuery) {
5323 if (!webResource.url.endsWith("?")) {
5324 webResource.url += "&";
5325 }
5326 webResource.url += key + "=" + this.inQuery[key];
5327 }
5328 }
5329 return Promise.resolve(webResource);
5330 };
5331 return ApiKeyCredentials;
5332}());
5333
5334// Copyright (c) Microsoft Corporation. All rights reserved.
5335var TopicCredentials = /** @class */ (function (_super) {
5336 tslib.__extends(TopicCredentials, _super);
5337 /**
5338 * Creates a new EventGrid TopicCredentials object.
5339 *
5340 * @constructor
5341 * @param {string} topicKey The EventGrid topic key
5342 */
5343 function TopicCredentials(topicKey) {
5344 var _this = this;
5345 if (!topicKey || (topicKey && typeof topicKey !== "string")) {
5346 throw new Error("topicKey cannot be null or undefined and must be of type string.");
5347 }
5348 var options = {
5349 inHeader: {
5350 "aeg-sas-key": topicKey,
5351 },
5352 };
5353 _this = _super.call(this, options) || this;
5354 return _this;
5355 }
5356 return TopicCredentials;
5357}(ApiKeyCredentials));
5358
5359// Copyright (c) Microsoft Corporation. All rights reserved.
5360var DomainCredentials = /** @class */ (function (_super) {
5361 tslib.__extends(DomainCredentials, _super);
5362 /**
5363 * Creates a new EventGrid DomainCredentials object.
5364 *
5365 * @constructor
5366 * @param {string} domainKey The EventGrid domain key
5367 */
5368 function DomainCredentials(domainKey) {
5369 var _this = this;
5370 if (!domainKey || (domainKey && typeof domainKey !== "string")) {
5371 throw new Error("domainKey cannot be null or undefined and must be of type string.");
5372 }
5373 var options = {
5374 inHeader: {
5375 "aeg-sas-key": domainKey,
5376 },
5377 };
5378 _this = _super.call(this, options) || this;
5379 return _this;
5380 }
5381 return DomainCredentials;
5382}(ApiKeyCredentials));
5383
5384exports.ApiKeyCredentials = ApiKeyCredentials;
5385exports.AzureIdentityCredentialAdapter = AzureIdentityCredentialAdapter;
5386exports.BaseRequestPolicy = BaseRequestPolicy;
5387exports.BasicAuthenticationCredentials = BasicAuthenticationCredentials;
5388exports.Constants = Constants;
5389exports.DefaultHttpClient = NodeFetchHttpClient;
5390exports.DomainCredentials = DomainCredentials;
5391exports.HttpHeaders = HttpHeaders;
5392exports.MapperType = MapperType;
5393exports.RequestPolicyOptions = RequestPolicyOptions;
5394exports.RestError = RestError;
5395exports.Serializer = Serializer;
5396exports.ServiceClient = ServiceClient;
5397exports.TokenCredentials = TokenCredentials;
5398exports.TopicCredentials = TopicCredentials;
5399exports.URLBuilder = URLBuilder;
5400exports.URLQuery = URLQuery;
5401exports.WebResource = WebResource;
5402exports.agentPolicy = agentPolicy;
5403exports.applyMixins = applyMixins;
5404exports.delay = delay;
5405exports.deserializationPolicy = deserializationPolicy;
5406exports.deserializeResponseBody = deserializeResponseBody;
5407exports.encodeUri = encodeUri;
5408exports.executePromisesSequentially = executePromisesSequentially;
5409exports.exponentialRetryPolicy = exponentialRetryPolicy;
5410exports.flattenResponse = flattenResponse;
5411exports.generateClientRequestIdPolicy = generateClientRequestIdPolicy;
5412exports.generateUuid = generateUuid;
5413exports.getDefaultProxySettings = getDefaultProxySettings;
5414exports.getDefaultUserAgentValue = getDefaultUserAgentValue;
5415exports.isDuration = isDuration;
5416exports.isNode = isNode;
5417exports.isValidUuid = isValidUuid;
5418exports.logPolicy = logPolicy;
5419exports.promiseToCallback = promiseToCallback;
5420exports.promiseToServiceCallback = promiseToServiceCallback;
5421exports.proxyPolicy = proxyPolicy;
5422exports.redirectPolicy = redirectPolicy;
5423exports.serializeObject = serializeObject;
5424exports.signingPolicy = signingPolicy;
5425exports.stripRequest = stripRequest;
5426exports.stripResponse = stripResponse;
5427exports.systemErrorRetryPolicy = systemErrorRetryPolicy;
5428exports.throttlingRetryPolicy = throttlingRetryPolicy;
5429exports.userAgentPolicy = userAgentPolicy;
5430//# sourceMappingURL=msRest.node.js.map