msRest.node.js 166 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941
  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. Object.defineProperty(exports, '__esModule', { value: true });
  7. function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
  8. var uuidv4 = _interopDefault(require('uuid/v4'));
  9. var axios = _interopDefault(require('axios'));
  10. var stream = require('stream');
  11. var FormData = _interopDefault(require('form-data'));
  12. var tough = require('tough-cookie');
  13. var tunnel = require('tunnel');
  14. var xml2js = require('xml2js');
  15. var os = require('os');
  16. var tslib_1 = require('tslib');
  17. // Copyright (c) Microsoft Corporation. All rights reserved.
  18. // Licensed under the MIT License. See License.txt in the project root for license information.
  19. /**
  20. * A collection of HttpHeaders that can be sent with a HTTP request.
  21. */
  22. function getHeaderKey(headerName) {
  23. return headerName.toLowerCase();
  24. }
  25. /**
  26. * A collection of HTTP header key/value pairs.
  27. */
  28. var HttpHeaders = /** @class */ (function () {
  29. function HttpHeaders(rawHeaders) {
  30. this._headersMap = {};
  31. if (rawHeaders) {
  32. for (var headerName in rawHeaders) {
  33. this.set(headerName, rawHeaders[headerName]);
  34. }
  35. }
  36. }
  37. /**
  38. * Set a header in this collection with the provided name and value. The name is
  39. * case-insensitive.
  40. * @param headerName The name of the header to set. This value is case-insensitive.
  41. * @param headerValue The value of the header to set.
  42. */
  43. HttpHeaders.prototype.set = function (headerName, headerValue) {
  44. this._headersMap[getHeaderKey(headerName)] = { name: headerName, value: headerValue.toString() };
  45. };
  46. /**
  47. * Get the header value for the provided header name, or undefined if no header exists in this
  48. * collection with the provided name.
  49. * @param headerName The name of the header.
  50. */
  51. HttpHeaders.prototype.get = function (headerName) {
  52. var header = this._headersMap[getHeaderKey(headerName)];
  53. return !header ? undefined : header.value;
  54. };
  55. /**
  56. * Get whether or not this header collection contains a header entry for the provided header name.
  57. */
  58. HttpHeaders.prototype.contains = function (headerName) {
  59. return !!this._headersMap[getHeaderKey(headerName)];
  60. };
  61. /**
  62. * Remove the header with the provided headerName. Return whether or not the header existed and
  63. * was removed.
  64. * @param headerName The name of the header to remove.
  65. */
  66. HttpHeaders.prototype.remove = function (headerName) {
  67. var result = this.contains(headerName);
  68. delete this._headersMap[getHeaderKey(headerName)];
  69. return result;
  70. };
  71. /**
  72. * Get the headers that are contained this collection as an object.
  73. */
  74. HttpHeaders.prototype.rawHeaders = function () {
  75. var result = {};
  76. for (var headerKey in this._headersMap) {
  77. var header = this._headersMap[headerKey];
  78. result[header.name.toLowerCase()] = header.value;
  79. }
  80. return result;
  81. };
  82. /**
  83. * Get the headers that are contained in this collection as an array.
  84. */
  85. HttpHeaders.prototype.headersArray = function () {
  86. var headers = [];
  87. for (var headerKey in this._headersMap) {
  88. headers.push(this._headersMap[headerKey]);
  89. }
  90. return headers;
  91. };
  92. /**
  93. * Get the header names that are contained in this collection.
  94. */
  95. HttpHeaders.prototype.headerNames = function () {
  96. var headerNames = [];
  97. var headers = this.headersArray();
  98. for (var i = 0; i < headers.length; ++i) {
  99. headerNames.push(headers[i].name);
  100. }
  101. return headerNames;
  102. };
  103. /**
  104. * Get the header names that are contained in this collection.
  105. */
  106. HttpHeaders.prototype.headerValues = function () {
  107. var headerValues = [];
  108. var headers = this.headersArray();
  109. for (var i = 0; i < headers.length; ++i) {
  110. headerValues.push(headers[i].value);
  111. }
  112. return headerValues;
  113. };
  114. /**
  115. * Get the JSON object representation of this HTTP header collection.
  116. */
  117. HttpHeaders.prototype.toJson = function () {
  118. return this.rawHeaders();
  119. };
  120. /**
  121. * Get the string representation of this HTTP header collection.
  122. */
  123. HttpHeaders.prototype.toString = function () {
  124. return JSON.stringify(this.toJson());
  125. };
  126. /**
  127. * Create a deep clone/copy of this HttpHeaders collection.
  128. */
  129. HttpHeaders.prototype.clone = function () {
  130. return new HttpHeaders(this.rawHeaders());
  131. };
  132. return HttpHeaders;
  133. }());
  134. // Copyright (c) Microsoft Corporation. All rights reserved.
  135. // Licensed under the MIT License. See License.txt in the project root for license information.
  136. /**
  137. * Encodes a string in base64 format.
  138. * @param value the string to encode
  139. */
  140. function encodeString(value) {
  141. return Buffer.from(value).toString("base64");
  142. }
  143. /**
  144. * Encodes a byte array in base64 format.
  145. * @param value the Uint8Aray to encode
  146. */
  147. function encodeByteArray(value) {
  148. // Buffer.from accepts <ArrayBuffer> | <SharedArrayBuffer>-- the TypeScript definition is off here
  149. // https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length
  150. var bufferValue = (value instanceof Buffer) ? value : Buffer.from(value.buffer);
  151. return bufferValue.toString("base64");
  152. }
  153. /**
  154. * Decodes a base64 string into a byte array.
  155. * @param value the base64 string to decode
  156. */
  157. function decodeString(value) {
  158. return Buffer.from(value, "base64");
  159. }
  160. // Copyright (c) Microsoft Corporation. All rights reserved.
  161. // Licensed under the MIT License. See License.txt in the project root for license information.
  162. var Constants = {
  163. /**
  164. * The ms-rest version
  165. * @const
  166. * @type {string}
  167. */
  168. msRestVersion: "1.8.13",
  169. /**
  170. * Specifies HTTP.
  171. *
  172. * @const
  173. * @type {string}
  174. */
  175. HTTP: "http:",
  176. /**
  177. * Specifies HTTPS.
  178. *
  179. * @const
  180. * @type {string}
  181. */
  182. HTTPS: "https:",
  183. /**
  184. * Specifies HTTP Proxy.
  185. *
  186. * @const
  187. * @type {string}
  188. */
  189. HTTP_PROXY: "HTTP_PROXY",
  190. /**
  191. * Specifies HTTPS Proxy.
  192. *
  193. * @const
  194. * @type {string}
  195. */
  196. HTTPS_PROXY: "HTTPS_PROXY",
  197. HttpConstants: {
  198. /**
  199. * Http Verbs
  200. *
  201. * @const
  202. * @enum {string}
  203. */
  204. HttpVerbs: {
  205. PUT: "PUT",
  206. GET: "GET",
  207. DELETE: "DELETE",
  208. POST: "POST",
  209. MERGE: "MERGE",
  210. HEAD: "HEAD",
  211. PATCH: "PATCH"
  212. },
  213. StatusCodes: {
  214. TooManyRequests: 429
  215. }
  216. },
  217. /**
  218. * Defines constants for use with HTTP headers.
  219. */
  220. HeaderConstants: {
  221. /**
  222. * The Authorization header.
  223. *
  224. * @const
  225. * @type {string}
  226. */
  227. AUTHORIZATION: "authorization",
  228. AUTHORIZATION_SCHEME: "Bearer",
  229. /**
  230. * The Retry-After response-header field can be used with a 503 (Service
  231. * Unavailable) or 349 (Too Many Requests) responses to indicate how long
  232. * the service is expected to be unavailable to the requesting client.
  233. *
  234. * @const
  235. * @type {string}
  236. */
  237. RETRY_AFTER: "Retry-After",
  238. /**
  239. * The UserAgent header.
  240. *
  241. * @const
  242. * @type {string}
  243. */
  244. USER_AGENT: "User-Agent"
  245. }
  246. };
  247. // Copyright (c) Microsoft Corporation. All rights reserved.
  248. /**
  249. * A constant that indicates whether the environment is node.js or browser based.
  250. */
  251. var isNode = (typeof process !== "undefined") && !!process.version && !!process.versions && !!process.versions.node;
  252. /**
  253. * Encodes an URI.
  254. *
  255. * @param {string} uri The URI to be encoded.
  256. * @return {string} The encoded URI.
  257. */
  258. function encodeUri(uri) {
  259. return encodeURIComponent(uri)
  260. .replace(/!/g, "%21")
  261. .replace(/"/g, "%27")
  262. .replace(/\(/g, "%28")
  263. .replace(/\)/g, "%29")
  264. .replace(/\*/g, "%2A");
  265. }
  266. /**
  267. * Returns a stripped version of the Http Response which only contains body,
  268. * headers and the status.
  269. *
  270. * @param {HttpOperationResponse} response The Http Response
  271. *
  272. * @return {object} The stripped version of Http Response.
  273. */
  274. function stripResponse(response) {
  275. var strippedResponse = {};
  276. strippedResponse.body = response.bodyAsText;
  277. strippedResponse.headers = response.headers;
  278. strippedResponse.status = response.status;
  279. return strippedResponse;
  280. }
  281. /**
  282. * Returns a stripped version of the Http Request that does not contain the
  283. * Authorization header.
  284. *
  285. * @param {WebResource} request The Http Request object
  286. *
  287. * @return {WebResource} The stripped version of Http Request.
  288. */
  289. function stripRequest(request) {
  290. var strippedRequest = request.clone();
  291. if (strippedRequest.headers) {
  292. strippedRequest.headers.remove("authorization");
  293. }
  294. return strippedRequest;
  295. }
  296. /**
  297. * Validates the given uuid as a string
  298. *
  299. * @param {string} uuid The uuid as a string that needs to be validated
  300. *
  301. * @return {boolean} True if the uuid is valid; false otherwise.
  302. */
  303. function isValidUuid(uuid) {
  304. 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");
  305. return validUuidRegex.test(uuid);
  306. }
  307. /**
  308. * Generated UUID
  309. *
  310. * @return {string} RFC4122 v4 UUID.
  311. */
  312. function generateUuid() {
  313. return uuidv4();
  314. }
  315. /**
  316. * Executes an array of promises sequentially. Inspiration of this method is here:
  317. * https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html. An awesome blog on promises!
  318. *
  319. * @param {Array} promiseFactories An array of promise factories(A function that return a promise)
  320. *
  321. * @param {any} [kickstart] Input to the first promise that is used to kickstart the promise chain.
  322. * If not provided then the promise chain starts with undefined.
  323. *
  324. * @return A chain of resolved or rejected promises
  325. */
  326. function executePromisesSequentially(promiseFactories, kickstart) {
  327. var result = Promise.resolve(kickstart);
  328. promiseFactories.forEach(function (promiseFactory) {
  329. result = result.then(promiseFactory);
  330. });
  331. return result;
  332. }
  333. /**
  334. * A wrapper for setTimeout that resolves a promise after t milliseconds.
  335. * @param {number} t The number of milliseconds to be delayed.
  336. * @param {T} value The value to be resolved with after a timeout of t milliseconds.
  337. * @returns {Promise<T>} Resolved promise
  338. */
  339. function delay(t, value) {
  340. return new Promise(function (resolve) { return setTimeout(function () { return resolve(value); }, t); });
  341. }
  342. /**
  343. * Converts a Promise to a callback.
  344. * @param {Promise<any>} promise The Promise to be converted to a callback
  345. * @returns {Function} A function that takes the callback (cb: Function): void
  346. * @deprecated generated code should instead depend on responseToBody
  347. */
  348. function promiseToCallback(promise) {
  349. if (typeof promise.then !== "function") {
  350. throw new Error("The provided input is not a Promise.");
  351. }
  352. return function (cb) {
  353. promise.then(function (data) {
  354. cb(undefined, data);
  355. }, function (err) {
  356. cb(err);
  357. });
  358. };
  359. }
  360. /**
  361. * Converts a Promise to a service callback.
  362. * @param {Promise<HttpOperationResponse>} promise - The Promise of HttpOperationResponse to be converted to a service callback
  363. * @returns {Function} A function that takes the service callback (cb: ServiceCallback<T>): void
  364. */
  365. function promiseToServiceCallback(promise) {
  366. if (typeof promise.then !== "function") {
  367. throw new Error("The provided input is not a Promise.");
  368. }
  369. return function (cb) {
  370. promise.then(function (data) {
  371. process.nextTick(cb, undefined, data.parsedBody, data.request, data);
  372. }, function (err) {
  373. process.nextTick(cb, err);
  374. });
  375. };
  376. }
  377. function prepareXMLRootList(obj, elementName) {
  378. var _a;
  379. if (!Array.isArray(obj)) {
  380. obj = [obj];
  381. }
  382. return _a = {}, _a[elementName] = obj, _a;
  383. }
  384. /**
  385. * Applies the properties on the prototype of sourceCtors to the prototype of targetCtor
  386. * @param {object} targetCtor The target object on which the properties need to be applied.
  387. * @param {Array<object>} sourceCtors An array of source objects from which the properties need to be taken.
  388. */
  389. function applyMixins(targetCtor, sourceCtors) {
  390. sourceCtors.forEach(function (sourceCtors) {
  391. Object.getOwnPropertyNames(sourceCtors.prototype).forEach(function (name) {
  392. targetCtor.prototype[name] = sourceCtors.prototype[name];
  393. });
  394. });
  395. }
  396. var validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;
  397. /**
  398. * Indicates whether the given string is in ISO 8601 format.
  399. * @param {string} value The value to be validated for ISO 8601 duration format.
  400. * @return {boolean} `true` if valid, `false` otherwise.
  401. */
  402. function isDuration(value) {
  403. return validateISODuration.test(value);
  404. }
  405. /**
  406. * Replace all of the instances of searchValue in value with the provided replaceValue.
  407. * @param {string | undefined} value The value to search and replace in.
  408. * @param {string} searchValue The value to search for in the value argument.
  409. * @param {string} replaceValue The value to replace searchValue with in the value argument.
  410. * @returns {string | undefined} The value where each instance of searchValue was replaced with replacedValue.
  411. */
  412. function replaceAll(value, searchValue, replaceValue) {
  413. return !value || !searchValue ? value : value.split(searchValue).join(replaceValue || "");
  414. }
  415. // Copyright (c) Microsoft Corporation. All rights reserved.
  416. var Serializer = /** @class */ (function () {
  417. function Serializer(modelMappers, isXML) {
  418. if (modelMappers === void 0) { modelMappers = {}; }
  419. this.modelMappers = modelMappers;
  420. this.isXML = isXML;
  421. }
  422. Serializer.prototype.validateConstraints = function (mapper, value, objectName) {
  423. var failValidation = function (constraintName, constraintValue) {
  424. throw new Error("\"" + objectName + "\" with value \"" + value + "\" should satisfy the constraint \"" + constraintName + "\": " + constraintValue + ".");
  425. };
  426. if (mapper.constraints && (value != undefined)) {
  427. 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;
  428. if (ExclusiveMaximum != undefined && value >= ExclusiveMaximum) {
  429. failValidation("ExclusiveMaximum", ExclusiveMaximum);
  430. }
  431. if (ExclusiveMinimum != undefined && value <= ExclusiveMinimum) {
  432. failValidation("ExclusiveMinimum", ExclusiveMinimum);
  433. }
  434. if (InclusiveMaximum != undefined && value > InclusiveMaximum) {
  435. failValidation("InclusiveMaximum", InclusiveMaximum);
  436. }
  437. if (InclusiveMinimum != undefined && value < InclusiveMinimum) {
  438. failValidation("InclusiveMinimum", InclusiveMinimum);
  439. }
  440. if (MaxItems != undefined && value.length > MaxItems) {
  441. failValidation("MaxItems", MaxItems);
  442. }
  443. if (MaxLength != undefined && value.length > MaxLength) {
  444. failValidation("MaxLength", MaxLength);
  445. }
  446. if (MinItems != undefined && value.length < MinItems) {
  447. failValidation("MinItems", MinItems);
  448. }
  449. if (MinLength != undefined && value.length < MinLength) {
  450. failValidation("MinLength", MinLength);
  451. }
  452. if (MultipleOf != undefined && value % MultipleOf !== 0) {
  453. failValidation("MultipleOf", MultipleOf);
  454. }
  455. if (Pattern && value.match(Pattern) === null) {
  456. failValidation("Pattern", Pattern);
  457. }
  458. if (UniqueItems && value.some(function (item, i, ar) { return ar.indexOf(item) !== i; })) {
  459. failValidation("UniqueItems", UniqueItems);
  460. }
  461. }
  462. };
  463. /**
  464. * Serialize the given object based on its metadata defined in the mapper
  465. *
  466. * @param {Mapper} mapper The mapper which defines the metadata of the serializable object
  467. *
  468. * @param {object|string|Array|number|boolean|Date|stream} object A valid Javascript object to be serialized
  469. *
  470. * @param {string} objectName Name of the serialized object
  471. *
  472. * @returns {object|string|Array|number|boolean|Date|stream} A valid serialized Javascript object
  473. */
  474. Serializer.prototype.serialize = function (mapper, object, objectName) {
  475. var payload = {};
  476. var mapperType = mapper.type.name;
  477. if (!objectName) {
  478. objectName = mapper.serializedName;
  479. }
  480. if (mapperType.match(/^Sequence$/ig) !== null) {
  481. payload = [];
  482. }
  483. if (object == undefined && (mapper.defaultValue != undefined || mapper.isConstant)) {
  484. object = mapper.defaultValue;
  485. }
  486. // This table of allowed values should help explain
  487. // the mapper.required and mapper.nullable properties.
  488. // X means "neither undefined or null are allowed".
  489. // || required
  490. // || true | false
  491. // nullable || ==========================
  492. // true || null | undefined/null
  493. // false || X | undefined
  494. // undefined || X | undefined/null
  495. var required = mapper.required, nullable = mapper.nullable;
  496. if (required && nullable && object === undefined) {
  497. throw new Error(objectName + " cannot be undefined.");
  498. }
  499. if (required && !nullable && object == undefined) {
  500. throw new Error(objectName + " cannot be null or undefined.");
  501. }
  502. if (!required && nullable === false && object === null) {
  503. throw new Error(objectName + " cannot be null.");
  504. }
  505. if (object == undefined) {
  506. payload = object;
  507. }
  508. else {
  509. // Validate Constraints if any
  510. this.validateConstraints(mapper, object, objectName);
  511. if (mapperType.match(/^any$/ig) !== null) {
  512. payload = object;
  513. }
  514. else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/ig) !== null) {
  515. payload = serializeBasicTypes(mapperType, objectName, object);
  516. }
  517. else if (mapperType.match(/^Enum$/ig) !== null) {
  518. var enumMapper = mapper;
  519. payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object);
  520. }
  521. else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/ig) !== null) {
  522. payload = serializeDateTypes(mapperType, object, objectName);
  523. }
  524. else if (mapperType.match(/^ByteArray$/ig) !== null) {
  525. payload = serializeByteArrayType(objectName, object);
  526. }
  527. else if (mapperType.match(/^Base64Url$/ig) !== null) {
  528. payload = serializeBase64UrlType(objectName, object);
  529. }
  530. else if (mapperType.match(/^Sequence$/ig) !== null) {
  531. payload = serializeSequenceType(this, mapper, object, objectName);
  532. }
  533. else if (mapperType.match(/^Dictionary$/ig) !== null) {
  534. payload = serializeDictionaryType(this, mapper, object, objectName);
  535. }
  536. else if (mapperType.match(/^Composite$/ig) !== null) {
  537. payload = serializeCompositeType(this, mapper, object, objectName);
  538. }
  539. }
  540. return payload;
  541. };
  542. /**
  543. * Deserialize the given object based on its metadata defined in the mapper
  544. *
  545. * @param {object} mapper The mapper which defines the metadata of the serializable object
  546. *
  547. * @param {object|string|Array|number|boolean|Date|stream} responseBody A valid Javascript entity to be deserialized
  548. *
  549. * @param {string} objectName Name of the deserialized object
  550. *
  551. * @returns {object|string|Array|number|boolean|Date|stream} A valid deserialized Javascript object
  552. */
  553. Serializer.prototype.deserialize = function (mapper, responseBody, objectName) {
  554. if (responseBody == undefined) {
  555. if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) {
  556. // Edge case for empty XML non-wrapped lists. xml2js can't distinguish
  557. // between the list being empty versus being missing,
  558. // so let's do the more user-friendly thing and return an empty list.
  559. responseBody = [];
  560. }
  561. return responseBody;
  562. }
  563. var payload;
  564. var mapperType = mapper.type.name;
  565. if (!objectName) {
  566. objectName = mapper.serializedName;
  567. }
  568. if (mapperType.match(/^Composite$/ig) !== null) {
  569. payload = deserializeCompositeType(this, mapper, responseBody, objectName);
  570. }
  571. else {
  572. if (this.isXML) {
  573. /**
  574. * If the mapper specifies this as a non-composite type value but the responseBody contains
  575. * both header ("$") and body ("_") properties, then just reduce the responseBody value to
  576. * the body ("_") property.
  577. */
  578. if (responseBody["$"] != undefined && responseBody["_"] != undefined) {
  579. responseBody = responseBody["_"];
  580. }
  581. }
  582. if (mapperType.match(/^Number$/ig) !== null) {
  583. payload = parseFloat(responseBody);
  584. if (isNaN(payload)) {
  585. payload = responseBody;
  586. }
  587. }
  588. else if (mapperType.match(/^Boolean$/ig) !== null) {
  589. if (responseBody === "true") {
  590. payload = true;
  591. }
  592. else if (responseBody === "false") {
  593. payload = false;
  594. }
  595. else {
  596. payload = responseBody;
  597. }
  598. }
  599. else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/ig) !== null) {
  600. payload = responseBody;
  601. }
  602. else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/ig) !== null) {
  603. payload = new Date(responseBody);
  604. }
  605. else if (mapperType.match(/^UnixTime$/ig) !== null) {
  606. payload = unixTimeToDate(responseBody);
  607. }
  608. else if (mapperType.match(/^ByteArray$/ig) !== null) {
  609. payload = decodeString(responseBody);
  610. }
  611. else if (mapperType.match(/^Base64Url$/ig) !== null) {
  612. payload = base64UrlToByteArray(responseBody);
  613. }
  614. else if (mapperType.match(/^Sequence$/ig) !== null) {
  615. payload = deserializeSequenceType(this, mapper, responseBody, objectName);
  616. }
  617. else if (mapperType.match(/^Dictionary$/ig) !== null) {
  618. payload = deserializeDictionaryType(this, mapper, responseBody, objectName);
  619. }
  620. }
  621. if (mapper.isConstant) {
  622. payload = mapper.defaultValue;
  623. }
  624. return payload;
  625. };
  626. return Serializer;
  627. }());
  628. function trimEnd(str, ch) {
  629. var len = str.length;
  630. while ((len - 1) >= 0 && str[len - 1] === ch) {
  631. --len;
  632. }
  633. return str.substr(0, len);
  634. }
  635. function bufferToBase64Url(buffer) {
  636. if (!buffer) {
  637. return undefined;
  638. }
  639. if (!(buffer instanceof Uint8Array)) {
  640. throw new Error("Please provide an input of type Uint8Array for converting to Base64Url.");
  641. }
  642. // Uint8Array to Base64.
  643. var str = encodeByteArray(buffer);
  644. // Base64 to Base64Url.
  645. return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_");
  646. }
  647. function base64UrlToByteArray(str) {
  648. if (!str) {
  649. return undefined;
  650. }
  651. if (str && typeof str.valueOf() !== "string") {
  652. throw new Error("Please provide an input of type string for converting to Uint8Array");
  653. }
  654. // Base64Url to Base64.
  655. str = str.replace(/\-/g, "+").replace(/\_/g, "/");
  656. // Base64 to Uint8Array.
  657. return decodeString(str);
  658. }
  659. function splitSerializeName(prop) {
  660. var classes = [];
  661. var partialclass = "";
  662. if (prop) {
  663. var subwords = prop.split(".");
  664. for (var _i = 0, subwords_1 = subwords; _i < subwords_1.length; _i++) {
  665. var item = subwords_1[_i];
  666. if (item.charAt(item.length - 1) === "\\") {
  667. partialclass += item.substr(0, item.length - 1) + ".";
  668. }
  669. else {
  670. partialclass += item;
  671. classes.push(partialclass);
  672. partialclass = "";
  673. }
  674. }
  675. }
  676. return classes;
  677. }
  678. function dateToUnixTime(d) {
  679. if (!d) {
  680. return undefined;
  681. }
  682. if (typeof d.valueOf() === "string") {
  683. d = new Date(d);
  684. }
  685. return Math.floor(d.getTime() / 1000);
  686. }
  687. function unixTimeToDate(n) {
  688. if (!n) {
  689. return undefined;
  690. }
  691. return new Date(n * 1000);
  692. }
  693. function serializeBasicTypes(typeName, objectName, value) {
  694. if (value !== null && value !== undefined) {
  695. if (typeName.match(/^Number$/ig) !== null) {
  696. if (typeof value !== "number") {
  697. throw new Error(objectName + " with value " + value + " must be of type number.");
  698. }
  699. }
  700. else if (typeName.match(/^String$/ig) !== null) {
  701. if (typeof value.valueOf() !== "string") {
  702. throw new Error(objectName + " with value \"" + value + "\" must be of type string.");
  703. }
  704. }
  705. else if (typeName.match(/^Uuid$/ig) !== null) {
  706. if (!(typeof value.valueOf() === "string" && isValidUuid(value))) {
  707. throw new Error(objectName + " with value \"" + value + "\" must be of type string and a valid uuid.");
  708. }
  709. }
  710. else if (typeName.match(/^Boolean$/ig) !== null) {
  711. if (typeof value !== "boolean") {
  712. throw new Error(objectName + " with value " + value + " must be of type boolean.");
  713. }
  714. }
  715. else if (typeName.match(/^Stream$/ig) !== null) {
  716. var objectType = typeof value;
  717. if (objectType !== "string" &&
  718. objectType !== "function" &&
  719. !(value instanceof ArrayBuffer) &&
  720. !ArrayBuffer.isView(value) &&
  721. !(typeof Blob === "function" && value instanceof Blob)) {
  722. throw new Error(objectName + " must be a string, Blob, ArrayBuffer, ArrayBufferView, or a function returning NodeJS.ReadableStream.");
  723. }
  724. }
  725. }
  726. return value;
  727. }
  728. function serializeEnumType(objectName, allowedValues, value) {
  729. if (!allowedValues) {
  730. throw new Error("Please provide a set of allowedValues to validate " + objectName + " as an Enum Type.");
  731. }
  732. var isPresent = allowedValues.some(function (item) {
  733. if (typeof item.valueOf() === "string") {
  734. return item.toLowerCase() === value.toLowerCase();
  735. }
  736. return item === value;
  737. });
  738. if (!isPresent) {
  739. throw new Error(value + " is not a valid value for " + objectName + ". The valid values are: " + JSON.stringify(allowedValues) + ".");
  740. }
  741. return value;
  742. }
  743. function serializeByteArrayType(objectName, value) {
  744. if (value != undefined) {
  745. if (!(value instanceof Uint8Array)) {
  746. throw new Error(objectName + " must be of type Uint8Array.");
  747. }
  748. value = encodeByteArray(value);
  749. }
  750. return value;
  751. }
  752. function serializeBase64UrlType(objectName, value) {
  753. if (value != undefined) {
  754. if (!(value instanceof Uint8Array)) {
  755. throw new Error(objectName + " must be of type Uint8Array.");
  756. }
  757. value = bufferToBase64Url(value);
  758. }
  759. return value;
  760. }
  761. function serializeDateTypes(typeName, value, objectName) {
  762. if (value != undefined) {
  763. if (typeName.match(/^Date$/ig) !== null) {
  764. if (!(value instanceof Date ||
  765. (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
  766. throw new Error(objectName + " must be an instanceof Date or a string in ISO8601 format.");
  767. }
  768. value = (value instanceof Date) ? value.toISOString().substring(0, 10) : new Date(value).toISOString().substring(0, 10);
  769. }
  770. else if (typeName.match(/^DateTime$/ig) !== null) {
  771. if (!(value instanceof Date ||
  772. (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
  773. throw new Error(objectName + " must be an instanceof Date or a string in ISO8601 format.");
  774. }
  775. value = (value instanceof Date) ? value.toISOString() : new Date(value).toISOString();
  776. }
  777. else if (typeName.match(/^DateTimeRfc1123$/ig) !== null) {
  778. if (!(value instanceof Date ||
  779. (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
  780. throw new Error(objectName + " must be an instanceof Date or a string in RFC-1123 format.");
  781. }
  782. value = (value instanceof Date) ? value.toUTCString() : new Date(value).toUTCString();
  783. }
  784. else if (typeName.match(/^UnixTime$/ig) !== null) {
  785. if (!(value instanceof Date ||
  786. (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) {
  787. throw new Error(objectName + " must be an instanceof Date or a string in RFC-1123/ISO8601 format " +
  788. "for it to be serialized in UnixTime/Epoch format.");
  789. }
  790. value = dateToUnixTime(value);
  791. }
  792. else if (typeName.match(/^TimeSpan$/ig) !== null) {
  793. if (!isDuration(value)) {
  794. throw new Error(objectName + " must be a string in ISO 8601 format. Instead was \"" + value + "\".");
  795. }
  796. value = value;
  797. }
  798. }
  799. return value;
  800. }
  801. function serializeSequenceType(serializer, mapper, object, objectName) {
  802. if (!Array.isArray(object)) {
  803. throw new Error(objectName + " must be of type Array.");
  804. }
  805. var elementType = mapper.type.element;
  806. if (!elementType || typeof elementType !== "object") {
  807. throw new Error("element\" metadata for an Array must be defined in the " +
  808. ("mapper and it must of type \"object\" in " + objectName + "."));
  809. }
  810. var tempArray = [];
  811. for (var i = 0; i < object.length; i++) {
  812. tempArray[i] = serializer.serialize(elementType, object[i], objectName);
  813. }
  814. return tempArray;
  815. }
  816. function serializeDictionaryType(serializer, mapper, object, objectName) {
  817. if (typeof object !== "object") {
  818. throw new Error(objectName + " must be of type object.");
  819. }
  820. var valueType = mapper.type.value;
  821. if (!valueType || typeof valueType !== "object") {
  822. throw new Error("\"value\" metadata for a Dictionary must be defined in the " +
  823. ("mapper and it must of type \"object\" in " + objectName + "."));
  824. }
  825. var tempDictionary = {};
  826. for (var _i = 0, _a = Object.keys(object); _i < _a.length; _i++) {
  827. var key = _a[_i];
  828. tempDictionary[key] = serializer.serialize(valueType, object[key], objectName + "." + key);
  829. }
  830. return tempDictionary;
  831. }
  832. /**
  833. * Resolves a composite mapper's modelProperties.
  834. * @param serializer the serializer containing the entire set of mappers
  835. * @param mapper the composite mapper to resolve
  836. */
  837. function resolveModelProperties(serializer, mapper, objectName) {
  838. var modelProps = mapper.type.modelProperties;
  839. if (!modelProps) {
  840. var className = mapper.type.className;
  841. if (!className) {
  842. throw new Error("Class name for model \"" + objectName + "\" is not provided in the mapper \"" + JSON.stringify(mapper, undefined, 2) + "\".");
  843. }
  844. var modelMapper = serializer.modelMappers[className];
  845. if (!modelMapper) {
  846. throw new Error("mapper() cannot be null or undefined for model \"" + className + "\".");
  847. }
  848. modelProps = modelMapper.type.modelProperties;
  849. if (!modelProps) {
  850. throw new Error("modelProperties cannot be null or undefined in the " +
  851. ("mapper \"" + JSON.stringify(modelMapper) + "\" of type \"" + className + "\" for object \"" + objectName + "\"."));
  852. }
  853. }
  854. return modelProps;
  855. }
  856. function serializeCompositeType(serializer, mapper, object, objectName) {
  857. var _a;
  858. if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
  859. mapper = getPolymorphicMapper(serializer, mapper, object, "clientName");
  860. }
  861. if (object != undefined) {
  862. var payload = {};
  863. var modelProps = resolveModelProperties(serializer, mapper, objectName);
  864. for (var _i = 0, _b = Object.keys(modelProps); _i < _b.length; _i++) {
  865. var key = _b[_i];
  866. var propertyMapper = modelProps[key];
  867. if (propertyMapper.readOnly) {
  868. continue;
  869. }
  870. var propName = void 0;
  871. var parentObject = payload;
  872. if (serializer.isXML) {
  873. if (propertyMapper.xmlIsWrapped) {
  874. propName = propertyMapper.xmlName;
  875. }
  876. else {
  877. propName = propertyMapper.xmlElementName || propertyMapper.xmlName;
  878. }
  879. }
  880. else {
  881. var paths = splitSerializeName(propertyMapper.serializedName);
  882. propName = paths.pop();
  883. for (var _c = 0, paths_1 = paths; _c < paths_1.length; _c++) {
  884. var pathName = paths_1[_c];
  885. var childObject = parentObject[pathName];
  886. if ((childObject == undefined) && (object[key] != undefined)) {
  887. parentObject[pathName] = {};
  888. }
  889. parentObject = parentObject[pathName];
  890. }
  891. }
  892. if (parentObject != undefined) {
  893. var propertyObjectName = propertyMapper.serializedName !== ""
  894. ? objectName + "." + propertyMapper.serializedName
  895. : objectName;
  896. var toSerialize = object[key];
  897. var polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
  898. if (polymorphicDiscriminator && polymorphicDiscriminator.clientName === key && toSerialize == undefined) {
  899. toSerialize = mapper.serializedName;
  900. }
  901. var serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName);
  902. if (serializedValue !== undefined && propName != undefined) {
  903. if (propertyMapper.xmlIsAttribute) {
  904. // $ is the key attributes are kept under in xml2js.
  905. // This keeps things simple while preventing name collision
  906. // with names in user documents.
  907. parentObject.$ = parentObject.$ || {};
  908. parentObject.$[propName] = serializedValue;
  909. }
  910. else if (propertyMapper.xmlIsWrapped) {
  911. parentObject[propName] = (_a = {}, _a[propertyMapper.xmlElementName] = serializedValue, _a);
  912. }
  913. else {
  914. parentObject[propName] = serializedValue;
  915. }
  916. }
  917. }
  918. }
  919. var additionalPropertiesMapper = mapper.type.additionalProperties;
  920. if (additionalPropertiesMapper) {
  921. var propNames = Object.keys(modelProps);
  922. var _loop_1 = function (clientPropName) {
  923. var isAdditionalProperty = propNames.every(function (pn) { return pn !== clientPropName; });
  924. if (isAdditionalProperty) {
  925. payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]');
  926. }
  927. };
  928. for (var clientPropName in object) {
  929. _loop_1(clientPropName);
  930. }
  931. }
  932. return payload;
  933. }
  934. return object;
  935. }
  936. function isSpecialXmlProperty(propertyName) {
  937. return ["$", "_"].includes(propertyName);
  938. }
  939. function deserializeCompositeType(serializer, mapper, responseBody, objectName) {
  940. if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) {
  941. mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName");
  942. }
  943. var modelProps = resolveModelProperties(serializer, mapper, objectName);
  944. var instance = {};
  945. var handledPropertyNames = [];
  946. for (var _i = 0, _a = Object.keys(modelProps); _i < _a.length; _i++) {
  947. var key = _a[_i];
  948. var propertyMapper = modelProps[key];
  949. var paths = splitSerializeName(modelProps[key].serializedName);
  950. handledPropertyNames.push(paths[0]);
  951. var serializedName = propertyMapper.serializedName, xmlName = propertyMapper.xmlName, xmlElementName = propertyMapper.xmlElementName;
  952. var propertyObjectName = objectName;
  953. if (serializedName !== "" && serializedName !== undefined) {
  954. propertyObjectName = objectName + "." + serializedName;
  955. }
  956. var headerCollectionPrefix = propertyMapper.headerCollectionPrefix;
  957. if (headerCollectionPrefix) {
  958. var dictionary = {};
  959. for (var _b = 0, _c = Object.keys(responseBody); _b < _c.length; _b++) {
  960. var headerKey = _c[_b];
  961. if (headerKey.startsWith(headerCollectionPrefix)) {
  962. dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName);
  963. }
  964. handledPropertyNames.push(headerKey);
  965. }
  966. instance[key] = dictionary;
  967. }
  968. else if (serializer.isXML) {
  969. if (propertyMapper.xmlIsAttribute && responseBody.$) {
  970. instance[key] = serializer.deserialize(propertyMapper, responseBody.$[xmlName], propertyObjectName);
  971. }
  972. else {
  973. var propertyName = xmlElementName || xmlName || serializedName;
  974. var unwrappedProperty = responseBody[propertyName];
  975. if (propertyMapper.xmlIsWrapped) {
  976. unwrappedProperty = responseBody[xmlName];
  977. unwrappedProperty = unwrappedProperty && unwrappedProperty[xmlElementName];
  978. var isEmptyWrappedList = unwrappedProperty === undefined;
  979. if (isEmptyWrappedList) {
  980. unwrappedProperty = [];
  981. }
  982. }
  983. instance[key] = serializer.deserialize(propertyMapper, unwrappedProperty, propertyObjectName);
  984. }
  985. }
  986. else {
  987. // deserialize the property if it is present in the provided responseBody instance
  988. var propertyInstance = void 0;
  989. var res = responseBody;
  990. // traversing the object step by step.
  991. for (var _d = 0, paths_2 = paths; _d < paths_2.length; _d++) {
  992. var item = paths_2[_d];
  993. if (!res)
  994. break;
  995. res = res[item];
  996. }
  997. propertyInstance = res;
  998. var polymorphicDiscriminator = mapper.type.polymorphicDiscriminator;
  999. if (polymorphicDiscriminator && propertyMapper.serializedName === polymorphicDiscriminator.serializedName && propertyInstance == undefined) {
  1000. propertyInstance = mapper.serializedName;
  1001. }
  1002. var serializedValue = void 0;
  1003. // paging
  1004. if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") {
  1005. propertyInstance = responseBody[key];
  1006. instance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName);
  1007. }
  1008. else if (propertyInstance !== undefined) {
  1009. serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName);
  1010. instance[key] = serializedValue;
  1011. }
  1012. }
  1013. }
  1014. var additionalPropertiesMapper = mapper.type.additionalProperties;
  1015. if (additionalPropertiesMapper) {
  1016. var isAdditionalProperty = function (responsePropName) {
  1017. for (var clientPropName in modelProps) {
  1018. var paths = splitSerializeName(modelProps[clientPropName].serializedName);
  1019. if (paths[0] === responsePropName) {
  1020. return false;
  1021. }
  1022. }
  1023. return true;
  1024. };
  1025. for (var responsePropName in responseBody) {
  1026. if (isAdditionalProperty(responsePropName)) {
  1027. instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]');
  1028. }
  1029. }
  1030. }
  1031. else if (responseBody) {
  1032. for (var _e = 0, _f = Object.keys(responseBody); _e < _f.length; _e++) {
  1033. var key = _f[_e];
  1034. if (instance[key] === undefined && !handledPropertyNames.includes(key) && !isSpecialXmlProperty(key)) {
  1035. instance[key] = responseBody[key];
  1036. }
  1037. }
  1038. }
  1039. return instance;
  1040. }
  1041. function deserializeDictionaryType(serializer, mapper, responseBody, objectName) {
  1042. /*jshint validthis: true */
  1043. var value = mapper.type.value;
  1044. if (!value || typeof value !== "object") {
  1045. throw new Error("\"value\" metadata for a Dictionary must be defined in the " +
  1046. ("mapper and it must of type \"object\" in " + objectName));
  1047. }
  1048. if (responseBody) {
  1049. var tempDictionary = {};
  1050. for (var _i = 0, _a = Object.keys(responseBody); _i < _a.length; _i++) {
  1051. var key = _a[_i];
  1052. tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName);
  1053. }
  1054. return tempDictionary;
  1055. }
  1056. return responseBody;
  1057. }
  1058. function deserializeSequenceType(serializer, mapper, responseBody, objectName) {
  1059. /*jshint validthis: true */
  1060. var element = mapper.type.element;
  1061. if (!element || typeof element !== "object") {
  1062. throw new Error("element\" metadata for an Array must be defined in the " +
  1063. ("mapper and it must of type \"object\" in " + objectName));
  1064. }
  1065. if (responseBody) {
  1066. if (!Array.isArray(responseBody)) {
  1067. // xml2js will interpret a single element array as just the element, so force it to be an array
  1068. responseBody = [responseBody];
  1069. }
  1070. var tempArray = [];
  1071. for (var i = 0; i < responseBody.length; i++) {
  1072. tempArray[i] = serializer.deserialize(element, responseBody[i], objectName + "[" + i + "]");
  1073. }
  1074. return tempArray;
  1075. }
  1076. return responseBody;
  1077. }
  1078. function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) {
  1079. var polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper);
  1080. if (polymorphicDiscriminator) {
  1081. var discriminatorName = polymorphicDiscriminator[polymorphicPropertyName];
  1082. if (discriminatorName != undefined) {
  1083. var discriminatorValue = object[discriminatorName];
  1084. if (discriminatorValue != undefined) {
  1085. var typeName = mapper.type.uberParent || mapper.type.className;
  1086. var indexDiscriminator = discriminatorValue === typeName
  1087. ? discriminatorValue
  1088. : typeName + "." + discriminatorValue;
  1089. var polymorphicMapper = serializer.modelMappers.discriminators[indexDiscriminator];
  1090. if (polymorphicMapper) {
  1091. mapper = polymorphicMapper;
  1092. }
  1093. }
  1094. }
  1095. }
  1096. return mapper;
  1097. }
  1098. function getPolymorphicDiscriminatorRecursively(serializer, mapper) {
  1099. return mapper.type.polymorphicDiscriminator
  1100. || getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent)
  1101. || getPolymorphicDiscriminatorSafely(serializer, mapper.type.className);
  1102. }
  1103. function getPolymorphicDiscriminatorSafely(serializer, typeName) {
  1104. return (typeName && serializer.modelMappers[typeName] && serializer.modelMappers[typeName].type.polymorphicDiscriminator);
  1105. }
  1106. // TODO: why is this here?
  1107. function serializeObject(toSerialize) {
  1108. if (toSerialize == undefined)
  1109. return undefined;
  1110. if (toSerialize instanceof Uint8Array) {
  1111. toSerialize = encodeByteArray(toSerialize);
  1112. return toSerialize;
  1113. }
  1114. else if (toSerialize instanceof Date) {
  1115. return toSerialize.toISOString();
  1116. }
  1117. else if (Array.isArray(toSerialize)) {
  1118. var array = [];
  1119. for (var i = 0; i < toSerialize.length; i++) {
  1120. array.push(serializeObject(toSerialize[i]));
  1121. }
  1122. return array;
  1123. }
  1124. else if (typeof toSerialize === "object") {
  1125. var dictionary = {};
  1126. for (var property in toSerialize) {
  1127. dictionary[property] = serializeObject(toSerialize[property]);
  1128. }
  1129. return dictionary;
  1130. }
  1131. return toSerialize;
  1132. }
  1133. /**
  1134. * Utility function to create a K:V from a list of strings
  1135. */
  1136. function strEnum(o) {
  1137. var result = {};
  1138. for (var _i = 0, o_1 = o; _i < o_1.length; _i++) {
  1139. var key = o_1[_i];
  1140. result[key] = key;
  1141. }
  1142. return result;
  1143. }
  1144. var MapperType = strEnum([
  1145. "Base64Url",
  1146. "Boolean",
  1147. "ByteArray",
  1148. "Composite",
  1149. "Date",
  1150. "DateTime",
  1151. "DateTimeRfc1123",
  1152. "Dictionary",
  1153. "Enum",
  1154. "Number",
  1155. "Object",
  1156. "Sequence",
  1157. "String",
  1158. "Stream",
  1159. "TimeSpan",
  1160. "UnixTime"
  1161. ]);
  1162. // Copyright (c) Microsoft Corporation. All rights reserved.
  1163. /**
  1164. * Creates a new WebResource object.
  1165. *
  1166. * This class provides an abstraction over a REST call by being library / implementation agnostic and wrapping the necessary
  1167. * properties to initiate a request.
  1168. *
  1169. * @constructor
  1170. */
  1171. var WebResource = /** @class */ (function () {
  1172. function WebResource(url, method, body, query, headers, streamResponseBody, withCredentials, abortSignal, timeout, onUploadProgress, onDownloadProgress, proxySettings) {
  1173. this.streamResponseBody = streamResponseBody;
  1174. this.url = url || "";
  1175. this.method = method || "GET";
  1176. this.headers = (headers instanceof HttpHeaders ? headers : new HttpHeaders(headers));
  1177. this.body = body;
  1178. this.query = query;
  1179. this.formData = undefined;
  1180. this.withCredentials = withCredentials || false;
  1181. this.abortSignal = abortSignal;
  1182. this.timeout = timeout || 0;
  1183. this.onUploadProgress = onUploadProgress;
  1184. this.onDownloadProgress = onDownloadProgress;
  1185. this.proxySettings = proxySettings;
  1186. }
  1187. /**
  1188. * Validates that the required properties such as method, url, headers["Content-Type"],
  1189. * headers["accept-language"] are defined. It will throw an error if one of the above
  1190. * mentioned properties are not defined.
  1191. */
  1192. WebResource.prototype.validateRequestProperties = function () {
  1193. if (!this.method) {
  1194. throw new Error("WebResource.method is required.");
  1195. }
  1196. if (!this.url) {
  1197. throw new Error("WebResource.url is required.");
  1198. }
  1199. };
  1200. /**
  1201. * Prepares the request.
  1202. * @param {RequestPrepareOptions} options Options to provide for preparing the request.
  1203. * @returns {WebResource} Returns the prepared WebResource (HTTP Request) object that needs to be given to the request pipeline.
  1204. */
  1205. WebResource.prototype.prepare = function (options) {
  1206. if (!options) {
  1207. throw new Error("options object is required");
  1208. }
  1209. if (options.method == undefined || typeof options.method.valueOf() !== "string") {
  1210. throw new Error("options.method must be a string.");
  1211. }
  1212. if (options.url && options.pathTemplate) {
  1213. throw new Error("options.url and options.pathTemplate are mutually exclusive. Please provide exactly one of them.");
  1214. }
  1215. if ((options.pathTemplate == undefined || typeof options.pathTemplate.valueOf() !== "string") && (options.url == undefined || typeof options.url.valueOf() !== "string")) {
  1216. throw new Error("Please provide exactly one of options.pathTemplate or options.url.");
  1217. }
  1218. // set the url if it is provided.
  1219. if (options.url) {
  1220. if (typeof options.url !== "string") {
  1221. throw new Error("options.url must be of type \"string\".");
  1222. }
  1223. this.url = options.url;
  1224. }
  1225. // set the method
  1226. if (options.method) {
  1227. var validMethods = ["GET", "PUT", "HEAD", "DELETE", "OPTIONS", "POST", "PATCH", "TRACE"];
  1228. if (validMethods.indexOf(options.method.toUpperCase()) === -1) {
  1229. throw new Error("The provided method \"" + options.method + "\" is invalid. Supported HTTP methods are: " + JSON.stringify(validMethods));
  1230. }
  1231. }
  1232. this.method = options.method.toUpperCase();
  1233. // construct the url if path template is provided
  1234. if (options.pathTemplate) {
  1235. var pathTemplate_1 = options.pathTemplate, pathParameters_1 = options.pathParameters;
  1236. if (typeof pathTemplate_1 !== "string") {
  1237. throw new Error("options.pathTemplate must be of type \"string\".");
  1238. }
  1239. if (!options.baseUrl) {
  1240. options.baseUrl = "https://management.azure.com";
  1241. }
  1242. var baseUrl = options.baseUrl;
  1243. var url_1 = baseUrl + (baseUrl.endsWith("/") ? "" : "/") + (pathTemplate_1.startsWith("/") ? pathTemplate_1.slice(1) : pathTemplate_1);
  1244. var segments = url_1.match(/({\w*\s*\w*})/ig);
  1245. if (segments && segments.length) {
  1246. if (!pathParameters_1) {
  1247. throw new Error("pathTemplate: " + pathTemplate_1 + " has been provided. Hence, options.pathParameters must also be provided.");
  1248. }
  1249. segments.forEach(function (item) {
  1250. var pathParamName = item.slice(1, -1);
  1251. var pathParam = pathParameters_1[pathParamName];
  1252. if (pathParam === null || pathParam === undefined || !(typeof pathParam === "string" || typeof pathParam === "object")) {
  1253. throw new Error("pathTemplate: " + pathTemplate_1 + " contains the path parameter " + pathParamName +
  1254. (" however, it is not present in " + pathParameters_1 + " - " + JSON.stringify(pathParameters_1, undefined, 2) + ".") +
  1255. ("The value of the path parameter can either be a \"string\" of the form { " + pathParamName + ": \"some sample value\" } or ") +
  1256. ("it can be an \"object\" of the form { \"" + pathParamName + "\": { value: \"some sample value\", skipUrlEncoding: true } }."));
  1257. }
  1258. if (typeof pathParam.valueOf() === "string") {
  1259. url_1 = url_1.replace(item, encodeURIComponent(pathParam));
  1260. }
  1261. if (typeof pathParam.valueOf() === "object") {
  1262. if (!pathParam.value) {
  1263. throw new Error("options.pathParameters[" + pathParamName + "] is of type \"object\" but it does not contain a \"value\" property.");
  1264. }
  1265. if (pathParam.skipUrlEncoding) {
  1266. url_1 = url_1.replace(item, pathParam.value);
  1267. }
  1268. else {
  1269. url_1 = url_1.replace(item, encodeURIComponent(pathParam.value));
  1270. }
  1271. }
  1272. });
  1273. }
  1274. this.url = url_1;
  1275. }
  1276. // append query parameters to the url if they are provided. They can be provided with pathTemplate or url option.
  1277. if (options.queryParameters) {
  1278. var queryParameters = options.queryParameters;
  1279. if (typeof queryParameters !== "object") {
  1280. throw new Error("options.queryParameters must be of type object. It should be a JSON object " +
  1281. "of \"query-parameter-name\" as the key and the \"query-parameter-value\" as the value. " +
  1282. "The \"query-parameter-value\" may be fo type \"string\" or an \"object\" of the form { value: \"query-parameter-value\", skipUrlEncoding: true }.");
  1283. }
  1284. // append question mark if it is not present in the url
  1285. if (this.url && this.url.indexOf("?") === -1) {
  1286. this.url += "?";
  1287. }
  1288. // construct queryString
  1289. var queryParams = [];
  1290. // We need to populate this.query as a dictionary if the request is being used for Sway's validateRequest().
  1291. this.query = {};
  1292. for (var queryParamName in queryParameters) {
  1293. var queryParam = queryParameters[queryParamName];
  1294. if (queryParam) {
  1295. if (typeof queryParam === "string") {
  1296. queryParams.push(queryParamName + "=" + encodeURIComponent(queryParam));
  1297. this.query[queryParamName] = encodeURIComponent(queryParam);
  1298. }
  1299. else if (typeof queryParam === "object") {
  1300. if (!queryParam.value) {
  1301. throw new Error("options.queryParameters[" + queryParamName + "] is of type \"object\" but it does not contain a \"value\" property.");
  1302. }
  1303. if (queryParam.skipUrlEncoding) {
  1304. queryParams.push(queryParamName + "=" + queryParam.value);
  1305. this.query[queryParamName] = queryParam.value;
  1306. }
  1307. else {
  1308. queryParams.push(queryParamName + "=" + encodeURIComponent(queryParam.value));
  1309. this.query[queryParamName] = encodeURIComponent(queryParam.value);
  1310. }
  1311. }
  1312. }
  1313. } // end-of-for
  1314. // append the queryString
  1315. this.url += queryParams.join("&");
  1316. }
  1317. // add headers to the request if they are provided
  1318. if (options.headers) {
  1319. var headers = options.headers;
  1320. for (var _i = 0, _a = Object.keys(options.headers); _i < _a.length; _i++) {
  1321. var headerName = _a[_i];
  1322. this.headers.set(headerName, headers[headerName]);
  1323. }
  1324. }
  1325. // ensure accept-language is set correctly
  1326. if (!this.headers.get("accept-language")) {
  1327. this.headers.set("accept-language", "en-US");
  1328. }
  1329. // ensure the request-id is set correctly
  1330. if (!this.headers.get("x-ms-client-request-id") && !options.disableClientRequestId) {
  1331. this.headers.set("x-ms-client-request-id", generateUuid());
  1332. }
  1333. // default
  1334. if (!this.headers.get("Content-Type")) {
  1335. this.headers.set("Content-Type", "application/json; charset=utf-8");
  1336. }
  1337. // set the request body. request.js automatically sets the Content-Length request header, so we need not set it explicilty
  1338. this.body = options.body;
  1339. if (options.body != undefined) {
  1340. // body as a stream special case. set the body as-is and check for some special request headers specific to sending a stream.
  1341. if (options.bodyIsStream) {
  1342. if (!this.headers.get("Transfer-Encoding")) {
  1343. this.headers.set("Transfer-Encoding", "chunked");
  1344. }
  1345. if (this.headers.get("Content-Type") !== "application/octet-stream") {
  1346. this.headers.set("Content-Type", "application/octet-stream");
  1347. }
  1348. }
  1349. else {
  1350. if (options.serializationMapper) {
  1351. this.body = new Serializer(options.mappers).serialize(options.serializationMapper, options.body, "requestBody");
  1352. }
  1353. if (!options.disableJsonStringifyOnBody) {
  1354. this.body = JSON.stringify(options.body);
  1355. }
  1356. }
  1357. }
  1358. this.abortSignal = options.abortSignal;
  1359. this.onDownloadProgress = options.onDownloadProgress;
  1360. this.onUploadProgress = options.onUploadProgress;
  1361. return this;
  1362. };
  1363. /**
  1364. * Clone this WebResource HTTP request object.
  1365. * @returns {WebResource} The clone of this WebResource HTTP request object.
  1366. */
  1367. WebResource.prototype.clone = function () {
  1368. 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);
  1369. if (this.formData) {
  1370. result.formData = this.formData;
  1371. }
  1372. if (this.operationSpec) {
  1373. result.operationSpec = this.operationSpec;
  1374. }
  1375. if (this.shouldDeserialize) {
  1376. result.shouldDeserialize = this.shouldDeserialize;
  1377. }
  1378. if (this.operationResponseGetter) {
  1379. result.operationResponseGetter = this.operationResponseGetter;
  1380. }
  1381. return result;
  1382. };
  1383. return WebResource;
  1384. }());
  1385. // Copyright (c) Microsoft Corporation. All rights reserved.
  1386. var RestError = /** @class */ (function (_super) {
  1387. tslib_1.__extends(RestError, _super);
  1388. function RestError(message, code, statusCode, request, response, body) {
  1389. var _this = _super.call(this, message) || this;
  1390. _this.code = code;
  1391. _this.statusCode = statusCode;
  1392. _this.request = request;
  1393. _this.response = response;
  1394. _this.body = body;
  1395. Object.setPrototypeOf(_this, RestError.prototype);
  1396. return _this;
  1397. }
  1398. RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR";
  1399. RestError.REQUEST_ABORTED_ERROR = "REQUEST_ABORTED_ERROR";
  1400. RestError.PARSE_ERROR = "PARSE_ERROR";
  1401. return RestError;
  1402. }(Error));
  1403. // Copyright (c) Microsoft Corporation. All rights reserved.
  1404. /**
  1405. * A class that handles the query portion of a URLBuilder.
  1406. */
  1407. var URLQuery = /** @class */ (function () {
  1408. function URLQuery() {
  1409. this._rawQuery = {};
  1410. }
  1411. /**
  1412. * Get whether or not there any query parameters in this URLQuery.
  1413. */
  1414. URLQuery.prototype.any = function () {
  1415. return Object.keys(this._rawQuery).length > 0;
  1416. };
  1417. /**
  1418. * Set a query parameter with the provided name and value. If the parameterValue is undefined or
  1419. * empty, then this will attempt to remove an existing query parameter with the provided
  1420. * parameterName.
  1421. */
  1422. URLQuery.prototype.set = function (parameterName, parameterValue) {
  1423. if (parameterName) {
  1424. if (parameterValue != undefined) {
  1425. var newValue = Array.isArray(parameterValue) ? parameterValue : parameterValue.toString();
  1426. this._rawQuery[parameterName] = newValue;
  1427. }
  1428. else {
  1429. delete this._rawQuery[parameterName];
  1430. }
  1431. }
  1432. };
  1433. /**
  1434. * Get the value of the query parameter with the provided name. If no parameter exists with the
  1435. * provided parameter name, then undefined will be returned.
  1436. */
  1437. URLQuery.prototype.get = function (parameterName) {
  1438. return parameterName ? this._rawQuery[parameterName] : undefined;
  1439. };
  1440. /**
  1441. * Get the string representation of this query. The return value will not start with a "?".
  1442. */
  1443. URLQuery.prototype.toString = function () {
  1444. var result = "";
  1445. for (var parameterName in this._rawQuery) {
  1446. if (result) {
  1447. result += "&";
  1448. }
  1449. var parameterValue = this._rawQuery[parameterName];
  1450. if (Array.isArray(parameterValue)) {
  1451. var parameterStrings = [];
  1452. for (var _i = 0, parameterValue_1 = parameterValue; _i < parameterValue_1.length; _i++) {
  1453. var parameterValueElement = parameterValue_1[_i];
  1454. parameterStrings.push(parameterName + "=" + parameterValueElement);
  1455. }
  1456. result += parameterStrings.join("&");
  1457. }
  1458. else {
  1459. result += parameterName + "=" + parameterValue;
  1460. }
  1461. }
  1462. return result;
  1463. };
  1464. /**
  1465. * Parse a URLQuery from the provided text.
  1466. */
  1467. URLQuery.parse = function (text) {
  1468. var result = new URLQuery();
  1469. if (text) {
  1470. if (text.startsWith("?")) {
  1471. text = text.substring(1);
  1472. }
  1473. var currentState = "ParameterName";
  1474. var parameterName = "";
  1475. var parameterValue = "";
  1476. for (var i = 0; i < text.length; ++i) {
  1477. var currentCharacter = text[i];
  1478. switch (currentState) {
  1479. case "ParameterName":
  1480. switch (currentCharacter) {
  1481. case "=":
  1482. currentState = "ParameterValue";
  1483. break;
  1484. case "&":
  1485. parameterName = "";
  1486. parameterValue = "";
  1487. break;
  1488. default:
  1489. parameterName += currentCharacter;
  1490. break;
  1491. }
  1492. break;
  1493. case "ParameterValue":
  1494. switch (currentCharacter) {
  1495. case "=":
  1496. parameterName = "";
  1497. parameterValue = "";
  1498. currentState = "Invalid";
  1499. break;
  1500. case "&":
  1501. result.set(parameterName, parameterValue);
  1502. parameterName = "";
  1503. parameterValue = "";
  1504. currentState = "ParameterName";
  1505. break;
  1506. default:
  1507. parameterValue += currentCharacter;
  1508. break;
  1509. }
  1510. break;
  1511. case "Invalid":
  1512. if (currentCharacter === "&") {
  1513. currentState = "ParameterName";
  1514. }
  1515. break;
  1516. default:
  1517. throw new Error("Unrecognized URLQuery parse state: " + currentState);
  1518. }
  1519. }
  1520. if (currentState === "ParameterValue") {
  1521. result.set(parameterName, parameterValue);
  1522. }
  1523. }
  1524. return result;
  1525. };
  1526. return URLQuery;
  1527. }());
  1528. /**
  1529. * A class that handles creating, modifying, and parsing URLs.
  1530. */
  1531. var URLBuilder = /** @class */ (function () {
  1532. function URLBuilder() {
  1533. }
  1534. /**
  1535. * Set the scheme/protocol for this URL. If the provided scheme contains other parts of a URL
  1536. * (such as a host, port, path, or query), those parts will be added to this URL as well.
  1537. */
  1538. URLBuilder.prototype.setScheme = function (scheme) {
  1539. if (!scheme) {
  1540. this._scheme = undefined;
  1541. }
  1542. else {
  1543. this.set(scheme, "SCHEME");
  1544. }
  1545. };
  1546. /**
  1547. * Get the scheme that has been set in this URL.
  1548. */
  1549. URLBuilder.prototype.getScheme = function () {
  1550. return this._scheme;
  1551. };
  1552. /**
  1553. * Set the host for this URL. If the provided host contains other parts of a URL (such as a
  1554. * port, path, or query), those parts will be added to this URL as well.
  1555. */
  1556. URLBuilder.prototype.setHost = function (host) {
  1557. if (!host) {
  1558. this._host = undefined;
  1559. }
  1560. else {
  1561. this.set(host, "SCHEME_OR_HOST");
  1562. }
  1563. };
  1564. /**
  1565. * Get the host that has been set in this URL.
  1566. */
  1567. URLBuilder.prototype.getHost = function () {
  1568. return this._host;
  1569. };
  1570. /**
  1571. * Set the port for this URL. If the provided port contains other parts of a URL (such as a
  1572. * path or query), those parts will be added to this URL as well.
  1573. */
  1574. URLBuilder.prototype.setPort = function (port) {
  1575. if (port == undefined || port === "") {
  1576. this._port = undefined;
  1577. }
  1578. else {
  1579. this.set(port.toString(), "PORT");
  1580. }
  1581. };
  1582. /**
  1583. * Get the port that has been set in this URL.
  1584. */
  1585. URLBuilder.prototype.getPort = function () {
  1586. return this._port;
  1587. };
  1588. /**
  1589. * Set the path for this URL. If the provided path contains a query, then it will be added to
  1590. * this URL as well.
  1591. */
  1592. URLBuilder.prototype.setPath = function (path) {
  1593. if (!path) {
  1594. this._path = undefined;
  1595. }
  1596. else {
  1597. if (path.indexOf("://") !== -1) {
  1598. this.set(path, "SCHEME");
  1599. }
  1600. else {
  1601. this.set(path, "PATH");
  1602. }
  1603. }
  1604. };
  1605. /**
  1606. * Append the provided path to this URL's existing path. If the provided path contains a query,
  1607. * then it will be added to this URL as well.
  1608. */
  1609. URLBuilder.prototype.appendPath = function (path) {
  1610. if (path) {
  1611. var currentPath = this.getPath();
  1612. if (currentPath) {
  1613. if (!currentPath.endsWith("/")) {
  1614. currentPath += "/";
  1615. }
  1616. if (path.startsWith("/")) {
  1617. path = path.substring(1);
  1618. }
  1619. path = currentPath + path;
  1620. }
  1621. this.set(path, "PATH");
  1622. }
  1623. };
  1624. /**
  1625. * Get the path that has been set in this URL.
  1626. */
  1627. URLBuilder.prototype.getPath = function () {
  1628. return this._path;
  1629. };
  1630. /**
  1631. * Set the query in this URL.
  1632. */
  1633. URLBuilder.prototype.setQuery = function (query) {
  1634. if (!query) {
  1635. this._query = undefined;
  1636. }
  1637. else {
  1638. this._query = URLQuery.parse(query);
  1639. }
  1640. };
  1641. /**
  1642. * Set a query parameter with the provided name and value in this URL's query. If the provided
  1643. * query parameter value is undefined or empty, then the query parameter will be removed if it
  1644. * existed.
  1645. */
  1646. URLBuilder.prototype.setQueryParameter = function (queryParameterName, queryParameterValue) {
  1647. if (queryParameterName) {
  1648. if (!this._query) {
  1649. this._query = new URLQuery();
  1650. }
  1651. this._query.set(queryParameterName, queryParameterValue);
  1652. }
  1653. };
  1654. /**
  1655. * Get the value of the query parameter with the provided query parameter name. If no query
  1656. * parameter exists with the provided name, then undefined will be returned.
  1657. */
  1658. URLBuilder.prototype.getQueryParameterValue = function (queryParameterName) {
  1659. return this._query ? this._query.get(queryParameterName) : undefined;
  1660. };
  1661. /**
  1662. * Get the query in this URL.
  1663. */
  1664. URLBuilder.prototype.getQuery = function () {
  1665. return this._query ? this._query.toString() : undefined;
  1666. };
  1667. /**
  1668. * Set the parts of this URL by parsing the provided text using the provided startState.
  1669. */
  1670. URLBuilder.prototype.set = function (text, startState) {
  1671. var tokenizer = new URLTokenizer(text, startState);
  1672. while (tokenizer.next()) {
  1673. var token = tokenizer.current();
  1674. if (token) {
  1675. switch (token.type) {
  1676. case "SCHEME":
  1677. this._scheme = token.text || undefined;
  1678. break;
  1679. case "HOST":
  1680. this._host = token.text || undefined;
  1681. break;
  1682. case "PORT":
  1683. this._port = token.text || undefined;
  1684. break;
  1685. case "PATH":
  1686. var tokenPath = token.text || undefined;
  1687. if (!this._path || this._path === "/" || tokenPath !== "/") {
  1688. this._path = tokenPath;
  1689. }
  1690. break;
  1691. case "QUERY":
  1692. this._query = URLQuery.parse(token.text);
  1693. break;
  1694. default:
  1695. throw new Error("Unrecognized URLTokenType: " + token.type);
  1696. }
  1697. }
  1698. }
  1699. };
  1700. URLBuilder.prototype.toString = function () {
  1701. var result = "";
  1702. if (this._scheme) {
  1703. result += this._scheme + "://";
  1704. }
  1705. if (this._host) {
  1706. result += this._host;
  1707. }
  1708. if (this._port) {
  1709. result += ":" + this._port;
  1710. }
  1711. if (this._path) {
  1712. if (!this._path.startsWith("/")) {
  1713. result += "/";
  1714. }
  1715. result += this._path;
  1716. }
  1717. if (this._query && this._query.any()) {
  1718. result += "?" + this._query.toString();
  1719. }
  1720. return result;
  1721. };
  1722. /**
  1723. * If the provided searchValue is found in this URLBuilder, then replace it with the provided
  1724. * replaceValue.
  1725. */
  1726. URLBuilder.prototype.replaceAll = function (searchValue, replaceValue) {
  1727. if (searchValue) {
  1728. this.setScheme(replaceAll(this.getScheme(), searchValue, replaceValue));
  1729. this.setHost(replaceAll(this.getHost(), searchValue, replaceValue));
  1730. this.setPort(replaceAll(this.getPort(), searchValue, replaceValue));
  1731. this.setPath(replaceAll(this.getPath(), searchValue, replaceValue));
  1732. this.setQuery(replaceAll(this.getQuery(), searchValue, replaceValue));
  1733. }
  1734. };
  1735. URLBuilder.parse = function (text) {
  1736. var result = new URLBuilder();
  1737. result.set(text, "SCHEME_OR_HOST");
  1738. return result;
  1739. };
  1740. return URLBuilder;
  1741. }());
  1742. var URLToken = /** @class */ (function () {
  1743. function URLToken(text, type) {
  1744. this.text = text;
  1745. this.type = type;
  1746. }
  1747. URLToken.scheme = function (text) {
  1748. return new URLToken(text, "SCHEME");
  1749. };
  1750. URLToken.host = function (text) {
  1751. return new URLToken(text, "HOST");
  1752. };
  1753. URLToken.port = function (text) {
  1754. return new URLToken(text, "PORT");
  1755. };
  1756. URLToken.path = function (text) {
  1757. return new URLToken(text, "PATH");
  1758. };
  1759. URLToken.query = function (text) {
  1760. return new URLToken(text, "QUERY");
  1761. };
  1762. return URLToken;
  1763. }());
  1764. /**
  1765. * Get whether or not the provided character (single character string) is an alphanumeric (letter or
  1766. * digit) character.
  1767. */
  1768. function isAlphaNumericCharacter(character) {
  1769. var characterCode = character.charCodeAt(0);
  1770. return (48 /* '0' */ <= characterCode && characterCode <= 57 /* '9' */) ||
  1771. (65 /* 'A' */ <= characterCode && characterCode <= 90 /* 'Z' */) ||
  1772. (97 /* 'a' */ <= characterCode && characterCode <= 122 /* 'z' */);
  1773. }
  1774. /**
  1775. * A class that tokenizes URL strings.
  1776. */
  1777. var URLTokenizer = /** @class */ (function () {
  1778. function URLTokenizer(_text, state) {
  1779. this._text = _text;
  1780. this._textLength = _text ? _text.length : 0;
  1781. this._currentState = state != undefined ? state : "SCHEME_OR_HOST";
  1782. this._currentIndex = 0;
  1783. }
  1784. /**
  1785. * Get the current URLToken this URLTokenizer is pointing at, or undefined if the URLTokenizer
  1786. * hasn't started or has finished tokenizing.
  1787. */
  1788. URLTokenizer.prototype.current = function () {
  1789. return this._currentToken;
  1790. };
  1791. /**
  1792. * Advance to the next URLToken and return whether or not a URLToken was found.
  1793. */
  1794. URLTokenizer.prototype.next = function () {
  1795. if (!hasCurrentCharacter(this)) {
  1796. this._currentToken = undefined;
  1797. }
  1798. else {
  1799. switch (this._currentState) {
  1800. case "SCHEME":
  1801. nextScheme(this);
  1802. break;
  1803. case "SCHEME_OR_HOST":
  1804. nextSchemeOrHost(this);
  1805. break;
  1806. case "HOST":
  1807. nextHost(this);
  1808. break;
  1809. case "PORT":
  1810. nextPort(this);
  1811. break;
  1812. case "PATH":
  1813. nextPath(this);
  1814. break;
  1815. case "QUERY":
  1816. nextQuery(this);
  1817. break;
  1818. default:
  1819. throw new Error("Unrecognized URLTokenizerState: " + this._currentState);
  1820. }
  1821. }
  1822. return !!this._currentToken;
  1823. };
  1824. return URLTokenizer;
  1825. }());
  1826. /**
  1827. * Read the remaining characters from this Tokenizer's character stream.
  1828. */
  1829. function readRemaining(tokenizer) {
  1830. var result = "";
  1831. if (tokenizer._currentIndex < tokenizer._textLength) {
  1832. result = tokenizer._text.substring(tokenizer._currentIndex);
  1833. tokenizer._currentIndex = tokenizer._textLength;
  1834. }
  1835. return result;
  1836. }
  1837. /**
  1838. * Whether or not this URLTokenizer has a current character.
  1839. */
  1840. function hasCurrentCharacter(tokenizer) {
  1841. return tokenizer._currentIndex < tokenizer._textLength;
  1842. }
  1843. /**
  1844. * Get the character in the text string at the current index.
  1845. */
  1846. function getCurrentCharacter(tokenizer) {
  1847. return tokenizer._text[tokenizer._currentIndex];
  1848. }
  1849. /**
  1850. * Advance to the character in text that is "step" characters ahead. If no step value is provided,
  1851. * then step will default to 1.
  1852. */
  1853. function nextCharacter(tokenizer, step) {
  1854. if (hasCurrentCharacter(tokenizer)) {
  1855. if (!step) {
  1856. step = 1;
  1857. }
  1858. tokenizer._currentIndex += step;
  1859. }
  1860. }
  1861. /**
  1862. * Starting with the current character, peek "charactersToPeek" number of characters ahead in this
  1863. * Tokenizer's stream of characters.
  1864. */
  1865. function peekCharacters(tokenizer, charactersToPeek) {
  1866. var endIndex = tokenizer._currentIndex + charactersToPeek;
  1867. if (tokenizer._textLength < endIndex) {
  1868. endIndex = tokenizer._textLength;
  1869. }
  1870. return tokenizer._text.substring(tokenizer._currentIndex, endIndex);
  1871. }
  1872. /**
  1873. * Read characters from this Tokenizer until the end of the stream or until the provided condition
  1874. * is false when provided the current character.
  1875. */
  1876. function readWhile(tokenizer, condition) {
  1877. var result = "";
  1878. while (hasCurrentCharacter(tokenizer)) {
  1879. var currentCharacter = getCurrentCharacter(tokenizer);
  1880. if (!condition(currentCharacter)) {
  1881. break;
  1882. }
  1883. else {
  1884. result += currentCharacter;
  1885. nextCharacter(tokenizer);
  1886. }
  1887. }
  1888. return result;
  1889. }
  1890. /**
  1891. * Read characters from this Tokenizer until a non-alphanumeric character or the end of the
  1892. * character stream is reached.
  1893. */
  1894. function readWhileLetterOrDigit(tokenizer) {
  1895. return readWhile(tokenizer, function (character) { return isAlphaNumericCharacter(character); });
  1896. }
  1897. /**
  1898. * Read characters from this Tokenizer until one of the provided terminating characters is read or
  1899. * the end of the character stream is reached.
  1900. */
  1901. function readUntilCharacter(tokenizer) {
  1902. var terminatingCharacters = [];
  1903. for (var _i = 1; _i < arguments.length; _i++) {
  1904. terminatingCharacters[_i - 1] = arguments[_i];
  1905. }
  1906. return readWhile(tokenizer, function (character) { return terminatingCharacters.indexOf(character) === -1; });
  1907. }
  1908. function nextScheme(tokenizer) {
  1909. var scheme = readWhileLetterOrDigit(tokenizer);
  1910. tokenizer._currentToken = URLToken.scheme(scheme);
  1911. if (!hasCurrentCharacter(tokenizer)) {
  1912. tokenizer._currentState = "DONE";
  1913. }
  1914. else {
  1915. tokenizer._currentState = "HOST";
  1916. }
  1917. }
  1918. function nextSchemeOrHost(tokenizer) {
  1919. var schemeOrHost = readUntilCharacter(tokenizer, ":", "/", "?");
  1920. if (!hasCurrentCharacter(tokenizer)) {
  1921. tokenizer._currentToken = URLToken.host(schemeOrHost);
  1922. tokenizer._currentState = "DONE";
  1923. }
  1924. else if (getCurrentCharacter(tokenizer) === ":") {
  1925. if (peekCharacters(tokenizer, 3) === "://") {
  1926. tokenizer._currentToken = URLToken.scheme(schemeOrHost);
  1927. tokenizer._currentState = "HOST";
  1928. }
  1929. else {
  1930. tokenizer._currentToken = URLToken.host(schemeOrHost);
  1931. tokenizer._currentState = "PORT";
  1932. }
  1933. }
  1934. else {
  1935. tokenizer._currentToken = URLToken.host(schemeOrHost);
  1936. if (getCurrentCharacter(tokenizer) === "/") {
  1937. tokenizer._currentState = "PATH";
  1938. }
  1939. else {
  1940. tokenizer._currentState = "QUERY";
  1941. }
  1942. }
  1943. }
  1944. function nextHost(tokenizer) {
  1945. if (peekCharacters(tokenizer, 3) === "://") {
  1946. nextCharacter(tokenizer, 3);
  1947. }
  1948. var host = readUntilCharacter(tokenizer, ":", "/", "?");
  1949. tokenizer._currentToken = URLToken.host(host);
  1950. if (!hasCurrentCharacter(tokenizer)) {
  1951. tokenizer._currentState = "DONE";
  1952. }
  1953. else if (getCurrentCharacter(tokenizer) === ":") {
  1954. tokenizer._currentState = "PORT";
  1955. }
  1956. else if (getCurrentCharacter(tokenizer) === "/") {
  1957. tokenizer._currentState = "PATH";
  1958. }
  1959. else {
  1960. tokenizer._currentState = "QUERY";
  1961. }
  1962. }
  1963. function nextPort(tokenizer) {
  1964. if (getCurrentCharacter(tokenizer) === ":") {
  1965. nextCharacter(tokenizer);
  1966. }
  1967. var port = readUntilCharacter(tokenizer, "/", "?");
  1968. tokenizer._currentToken = URLToken.port(port);
  1969. if (!hasCurrentCharacter(tokenizer)) {
  1970. tokenizer._currentState = "DONE";
  1971. }
  1972. else if (getCurrentCharacter(tokenizer) === "/") {
  1973. tokenizer._currentState = "PATH";
  1974. }
  1975. else {
  1976. tokenizer._currentState = "QUERY";
  1977. }
  1978. }
  1979. function nextPath(tokenizer) {
  1980. var path = readUntilCharacter(tokenizer, "?");
  1981. tokenizer._currentToken = URLToken.path(path);
  1982. if (!hasCurrentCharacter(tokenizer)) {
  1983. tokenizer._currentState = "DONE";
  1984. }
  1985. else {
  1986. tokenizer._currentState = "QUERY";
  1987. }
  1988. }
  1989. function nextQuery(tokenizer) {
  1990. if (getCurrentCharacter(tokenizer) === "?") {
  1991. nextCharacter(tokenizer);
  1992. }
  1993. var query = readRemaining(tokenizer);
  1994. tokenizer._currentToken = URLToken.query(query);
  1995. tokenizer._currentState = "DONE";
  1996. }
  1997. // Copyright (c) Microsoft Corporation. All rights reserved.
  1998. /**
  1999. * A HttpClient implementation that uses axios to send HTTP requests.
  2000. */
  2001. var AxiosHttpClient = /** @class */ (function () {
  2002. function AxiosHttpClient() {
  2003. this.cookieJar = new tough.CookieJar();
  2004. }
  2005. AxiosHttpClient.prototype.sendRequest = function (httpRequest) {
  2006. return tslib_1.__awaiter(this, void 0, void 0, function () {
  2007. var formData, requestForm_1, appendFormValue, _i, _a, formKey, formValue, j, contentType, cookieString, abortSignal, abortListener, cancelToken, rawHeaders, httpRequestBody, axiosBody, onUploadProgress, loadedBytes_1, uploadReportStream, res, config, agent, err_1, axiosErr, headers, onDownloadProgress, responseBody, loadedBytes_2, downloadReportStream, length_1, operationResponse, setCookieHeader_1;
  2008. var _this = this;
  2009. return tslib_1.__generator(this, function (_b) {
  2010. switch (_b.label) {
  2011. case 0:
  2012. if (typeof httpRequest !== "object") {
  2013. throw new Error("httpRequest (WebResource) cannot be null or undefined and must be of type object.");
  2014. }
  2015. if (httpRequest.formData) {
  2016. formData = httpRequest.formData;
  2017. requestForm_1 = new FormData();
  2018. appendFormValue = function (key, value) {
  2019. // value function probably returns a stream so we can provide a fresh stream on each retry
  2020. if (typeof value === "function") {
  2021. value = value();
  2022. }
  2023. if (value && value.hasOwnProperty("value") && value.hasOwnProperty("options")) {
  2024. requestForm_1.append(key, value.value, value.options);
  2025. }
  2026. else {
  2027. requestForm_1.append(key, value);
  2028. }
  2029. };
  2030. for (_i = 0, _a = Object.keys(formData); _i < _a.length; _i++) {
  2031. formKey = _a[_i];
  2032. formValue = formData[formKey];
  2033. if (Array.isArray(formValue)) {
  2034. for (j = 0; j < formValue.length; j++) {
  2035. appendFormValue(formKey, formValue[j]);
  2036. }
  2037. }
  2038. else {
  2039. appendFormValue(formKey, formValue);
  2040. }
  2041. }
  2042. httpRequest.body = requestForm_1;
  2043. httpRequest.formData = undefined;
  2044. contentType = httpRequest.headers.get("Content-Type");
  2045. if (contentType && contentType.indexOf("multipart/form-data") !== -1) {
  2046. if (typeof requestForm_1.getBoundary === "function") {
  2047. httpRequest.headers.set("Content-Type", "multipart/form-data; boundary=" + requestForm_1.getBoundary());
  2048. }
  2049. else {
  2050. // browser will automatically apply a suitable content-type header
  2051. httpRequest.headers.remove("Content-Type");
  2052. }
  2053. }
  2054. }
  2055. if (!(this.cookieJar && !httpRequest.headers.get("Cookie"))) return [3 /*break*/, 2];
  2056. return [4 /*yield*/, new Promise(function (resolve, reject) {
  2057. _this.cookieJar.getCookieString(httpRequest.url, function (err, cookie) {
  2058. if (err) {
  2059. reject(err);
  2060. }
  2061. else {
  2062. resolve(cookie);
  2063. }
  2064. });
  2065. })];
  2066. case 1:
  2067. cookieString = _b.sent();
  2068. httpRequest.headers.set("Cookie", cookieString);
  2069. _b.label = 2;
  2070. case 2:
  2071. abortSignal = httpRequest.abortSignal;
  2072. if (abortSignal && abortSignal.aborted) {
  2073. throw new RestError("The request was aborted", RestError.REQUEST_ABORTED_ERROR, undefined, httpRequest);
  2074. }
  2075. cancelToken = abortSignal && new axios.CancelToken(function (canceler) {
  2076. abortListener = function () { return canceler(); };
  2077. abortSignal.addEventListener("abort", abortListener);
  2078. });
  2079. rawHeaders = httpRequest.headers.rawHeaders();
  2080. httpRequestBody = httpRequest.body;
  2081. axiosBody =
  2082. // Workaround for https://github.com/axios/axios/issues/755
  2083. // tslint:disable-next-line:no-null-keyword
  2084. typeof httpRequestBody === "undefined" ? null :
  2085. typeof httpRequestBody === "function" ? httpRequestBody() :
  2086. httpRequestBody;
  2087. onUploadProgress = httpRequest.onUploadProgress;
  2088. if (onUploadProgress && axiosBody) {
  2089. loadedBytes_1 = 0;
  2090. uploadReportStream = new stream.Transform({
  2091. transform: function (chunk, _encoding, callback) {
  2092. loadedBytes_1 += chunk.length;
  2093. onUploadProgress({ loadedBytes: loadedBytes_1 });
  2094. callback(undefined, chunk);
  2095. }
  2096. });
  2097. if (isReadableStream(axiosBody)) {
  2098. axiosBody.pipe(uploadReportStream);
  2099. }
  2100. else {
  2101. uploadReportStream.end(axiosBody);
  2102. }
  2103. axiosBody = uploadReportStream;
  2104. }
  2105. _b.label = 3;
  2106. case 3:
  2107. _b.trys.push([3, 5, 6, 7]);
  2108. config = {
  2109. method: httpRequest.method,
  2110. url: httpRequest.url,
  2111. headers: rawHeaders,
  2112. data: axiosBody,
  2113. transformResponse: function (data) { return data; },
  2114. validateStatus: function () { return true; },
  2115. // Workaround for https://github.com/axios/axios/issues/1362
  2116. maxContentLength: Infinity,
  2117. responseType: httpRequest.streamResponseBody ? "stream" : "text",
  2118. cancelToken: cancelToken,
  2119. timeout: httpRequest.timeout,
  2120. proxy: false
  2121. };
  2122. if (httpRequest.proxySettings) {
  2123. agent = createProxyAgent(httpRequest.url, httpRequest.proxySettings, httpRequest.headers);
  2124. if (agent.isHttps) {
  2125. config.httpsAgent = agent.agent;
  2126. }
  2127. else {
  2128. config.httpAgent = agent.agent;
  2129. }
  2130. }
  2131. // This hack is still required with 0.19.0 version of axios since axios tries to merge the
  2132. // Content-Type header from it's config["<method name>"] where the method name is lower-case,
  2133. // into the request header. It could be possible that the Content-Type header is not present
  2134. // in the original request and this would create problems while creating the signature for
  2135. // storage data plane sdks.
  2136. axios.interceptors.request.use(function (config) { return (tslib_1.__assign({}, config, { method: config.method && config.method.toUpperCase() })); });
  2137. return [4 /*yield*/, axios.request(config)];
  2138. case 4:
  2139. res = _b.sent();
  2140. return [3 /*break*/, 7];
  2141. case 5:
  2142. err_1 = _b.sent();
  2143. if (err_1 instanceof axios.Cancel) {
  2144. throw new RestError(err_1.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest);
  2145. }
  2146. else {
  2147. axiosErr = err_1;
  2148. throw new RestError(axiosErr.message, RestError.REQUEST_SEND_ERROR, undefined, httpRequest);
  2149. }
  2150. return [3 /*break*/, 7];
  2151. case 6:
  2152. if (abortSignal && abortListener) {
  2153. abortSignal.removeEventListener("abort", abortListener);
  2154. }
  2155. return [7 /*endfinally*/];
  2156. case 7:
  2157. headers = new HttpHeaders(res.headers);
  2158. onDownloadProgress = httpRequest.onDownloadProgress;
  2159. responseBody = res.data;
  2160. if (onDownloadProgress) {
  2161. if (isReadableStream(responseBody)) {
  2162. loadedBytes_2 = 0;
  2163. downloadReportStream = new stream.Transform({
  2164. transform: function (chunk, _encoding, callback) {
  2165. loadedBytes_2 += chunk.length;
  2166. onDownloadProgress({ loadedBytes: loadedBytes_2 });
  2167. callback(undefined, chunk);
  2168. }
  2169. });
  2170. responseBody.pipe(downloadReportStream);
  2171. responseBody = downloadReportStream;
  2172. }
  2173. else {
  2174. length_1 = parseInt(headers.get("Content-Length")) || responseBody.length || undefined;
  2175. if (length_1) {
  2176. // Calling callback for non-stream response for consistency with browser
  2177. onDownloadProgress({ loadedBytes: length_1 });
  2178. }
  2179. }
  2180. }
  2181. operationResponse = {
  2182. request: httpRequest,
  2183. status: res.status,
  2184. headers: headers,
  2185. readableStreamBody: httpRequest.streamResponseBody ? responseBody : undefined,
  2186. bodyAsText: httpRequest.streamResponseBody ? undefined : responseBody
  2187. };
  2188. if (!this.cookieJar) return [3 /*break*/, 9];
  2189. setCookieHeader_1 = operationResponse.headers.get("Set-Cookie");
  2190. if (!(setCookieHeader_1 != undefined)) return [3 /*break*/, 9];
  2191. return [4 /*yield*/, new Promise(function (resolve, reject) {
  2192. _this.cookieJar.setCookie(setCookieHeader_1, httpRequest.url, function (err) {
  2193. if (err) {
  2194. reject(err);
  2195. }
  2196. else {
  2197. resolve();
  2198. }
  2199. });
  2200. })];
  2201. case 8:
  2202. _b.sent();
  2203. _b.label = 9;
  2204. case 9: return [2 /*return*/, operationResponse];
  2205. }
  2206. });
  2207. });
  2208. };
  2209. return AxiosHttpClient;
  2210. }());
  2211. function isReadableStream(body) {
  2212. return typeof body.pipe === "function";
  2213. }
  2214. function createProxyAgent(requestUrl, proxySettings, headers) {
  2215. var tunnelOptions = {
  2216. proxy: {
  2217. host: URLBuilder.parse(proxySettings.host).getHost(),
  2218. port: proxySettings.port,
  2219. headers: (headers && headers.rawHeaders()) || {}
  2220. }
  2221. };
  2222. if ((proxySettings.username && proxySettings.password)) {
  2223. tunnelOptions.proxy.proxyAuth = proxySettings.username + ":" + proxySettings.password;
  2224. }
  2225. var requestScheme = URLBuilder.parse(requestUrl).getScheme() || "";
  2226. var isRequestHttps = requestScheme.toLowerCase() === "https";
  2227. var proxyScheme = URLBuilder.parse(proxySettings.host).getScheme() || "";
  2228. var isProxyHttps = proxyScheme.toLowerCase() === "https";
  2229. var proxyAgent = {
  2230. isHttps: isRequestHttps,
  2231. agent: createTunnel(isRequestHttps, isProxyHttps, tunnelOptions)
  2232. };
  2233. return proxyAgent;
  2234. }
  2235. function createTunnel(isRequestHttps, isProxyHttps, tunnelOptions) {
  2236. if (isRequestHttps && isProxyHttps) {
  2237. return tunnel.httpsOverHttps(tunnelOptions);
  2238. }
  2239. else if (isRequestHttps && !isProxyHttps) {
  2240. return tunnel.httpsOverHttp(tunnelOptions);
  2241. }
  2242. else if (!isRequestHttps && isProxyHttps) {
  2243. return tunnel.httpOverHttps(tunnelOptions);
  2244. }
  2245. else {
  2246. return tunnel.httpOverHttp(tunnelOptions);
  2247. }
  2248. }
  2249. // Copyright (c) Microsoft Corporation. All rights reserved.
  2250. // Copyright (c) Microsoft Corporation. All rights reserved.
  2251. (function (HttpPipelineLogLevel) {
  2252. /**
  2253. * A log level that indicates that no logs will be logged.
  2254. */
  2255. HttpPipelineLogLevel[HttpPipelineLogLevel["OFF"] = 0] = "OFF";
  2256. /**
  2257. * An error log.
  2258. */
  2259. HttpPipelineLogLevel[HttpPipelineLogLevel["ERROR"] = 1] = "ERROR";
  2260. /**
  2261. * A warning log.
  2262. */
  2263. HttpPipelineLogLevel[HttpPipelineLogLevel["WARNING"] = 2] = "WARNING";
  2264. /**
  2265. * An information log.
  2266. */
  2267. HttpPipelineLogLevel[HttpPipelineLogLevel["INFO"] = 3] = "INFO";
  2268. })(exports.HttpPipelineLogLevel || (exports.HttpPipelineLogLevel = {}));
  2269. // Copyright (c) Microsoft Corporation. All rights reserved.
  2270. // Licensed under the MIT License. See License.txt in the project root for license information.
  2271. /**
  2272. * Get the path to this parameter's value as a dotted string (a.b.c).
  2273. * @param parameter The parameter to get the path string for.
  2274. * @returns The path to this parameter's value as a dotted string.
  2275. */
  2276. function getPathStringFromParameter(parameter) {
  2277. return getPathStringFromParameterPath(parameter.parameterPath, parameter.mapper);
  2278. }
  2279. function getPathStringFromParameterPath(parameterPath, mapper) {
  2280. var result;
  2281. if (typeof parameterPath === "string") {
  2282. result = parameterPath;
  2283. }
  2284. else if (Array.isArray(parameterPath)) {
  2285. result = parameterPath.join(".");
  2286. }
  2287. else {
  2288. result = mapper.serializedName;
  2289. }
  2290. return result;
  2291. }
  2292. // Copyright (c) Microsoft Corporation. All rights reserved.
  2293. function isStreamOperation(operationSpec) {
  2294. var result = false;
  2295. for (var statusCode in operationSpec.responses) {
  2296. var operationResponse = operationSpec.responses[statusCode];
  2297. if (operationResponse.bodyMapper && operationResponse.bodyMapper.type.name === MapperType.Stream) {
  2298. result = true;
  2299. break;
  2300. }
  2301. }
  2302. return result;
  2303. }
  2304. // Copyright (c) Microsoft Corporation. All rights reserved.
  2305. function stringifyXML(obj, opts) {
  2306. var builder = new xml2js.Builder({
  2307. explicitArray: false,
  2308. explicitCharkey: false,
  2309. rootName: (opts || {}).rootName,
  2310. renderOpts: {
  2311. pretty: false
  2312. }
  2313. });
  2314. return builder.buildObject(obj);
  2315. }
  2316. function parseXML(str) {
  2317. var xmlParser = new xml2js.Parser({
  2318. explicitArray: false,
  2319. explicitCharkey: false,
  2320. explicitRoot: false
  2321. });
  2322. return new Promise(function (resolve, reject) {
  2323. if (!str) {
  2324. reject(new Error("Document is empty"));
  2325. }
  2326. else {
  2327. xmlParser.parseString(str, function (err, res) {
  2328. if (err) {
  2329. reject(err);
  2330. }
  2331. else {
  2332. resolve(res);
  2333. }
  2334. });
  2335. }
  2336. });
  2337. }
  2338. // Copyright (c) Microsoft Corporation. All rights reserved.
  2339. var BaseRequestPolicy = /** @class */ (function () {
  2340. function BaseRequestPolicy(_nextPolicy, _options) {
  2341. this._nextPolicy = _nextPolicy;
  2342. this._options = _options;
  2343. }
  2344. /**
  2345. * Get whether or not a log with the provided log level should be logged.
  2346. * @param logLevel The log level of the log that will be logged.
  2347. * @returns Whether or not a log with the provided log level should be logged.
  2348. */
  2349. BaseRequestPolicy.prototype.shouldLog = function (logLevel) {
  2350. return this._options.shouldLog(logLevel);
  2351. };
  2352. /**
  2353. * Attempt to log the provided message to the provided logger. If no logger was provided or if
  2354. * the log level does not meat the logger's threshold, then nothing will be logged.
  2355. * @param logLevel The log level of this log.
  2356. * @param message The message of this log.
  2357. */
  2358. BaseRequestPolicy.prototype.log = function (logLevel, message) {
  2359. this._options.log(logLevel, message);
  2360. };
  2361. return BaseRequestPolicy;
  2362. }());
  2363. /**
  2364. * Optional properties that can be used when creating a RequestPolicy.
  2365. */
  2366. var RequestPolicyOptions = /** @class */ (function () {
  2367. function RequestPolicyOptions(_logger) {
  2368. this._logger = _logger;
  2369. }
  2370. /**
  2371. * Get whether or not a log with the provided log level should be logged.
  2372. * @param logLevel The log level of the log that will be logged.
  2373. * @returns Whether or not a log with the provided log level should be logged.
  2374. */
  2375. RequestPolicyOptions.prototype.shouldLog = function (logLevel) {
  2376. return !!this._logger &&
  2377. logLevel !== exports.HttpPipelineLogLevel.OFF &&
  2378. logLevel <= this._logger.minimumLogLevel;
  2379. };
  2380. /**
  2381. * Attempt to log the provided message to the provided logger. If no logger was provided or if
  2382. * the log level does not meat the logger's threshold, then nothing will be logged.
  2383. * @param logLevel The log level of this log.
  2384. * @param message The message of this log.
  2385. */
  2386. RequestPolicyOptions.prototype.log = function (logLevel, message) {
  2387. if (this._logger && this.shouldLog(logLevel)) {
  2388. this._logger.log(logLevel, message);
  2389. }
  2390. };
  2391. return RequestPolicyOptions;
  2392. }());
  2393. // Copyright (c) Microsoft Corporation. All rights reserved.
  2394. /**
  2395. * Create a new serialization RequestPolicyCreator that will serialized HTTP request bodies as they
  2396. * pass through the HTTP pipeline.
  2397. */
  2398. function deserializationPolicy(deserializationContentTypes) {
  2399. return {
  2400. create: function (nextPolicy, options) {
  2401. return new DeserializationPolicy(nextPolicy, deserializationContentTypes, options);
  2402. }
  2403. };
  2404. }
  2405. var defaultJsonContentTypes = ["application/json", "text/json"];
  2406. var defaultXmlContentTypes = ["application/xml", "application/atom+xml"];
  2407. /**
  2408. * A RequestPolicy that will deserialize HTTP response bodies and headers as they pass through the
  2409. * HTTP pipeline.
  2410. */
  2411. var DeserializationPolicy = /** @class */ (function (_super) {
  2412. tslib_1.__extends(DeserializationPolicy, _super);
  2413. function DeserializationPolicy(nextPolicy, deserializationContentTypes, options) {
  2414. var _this = _super.call(this, nextPolicy, options) || this;
  2415. _this.jsonContentTypes = deserializationContentTypes && deserializationContentTypes.json || defaultJsonContentTypes;
  2416. _this.xmlContentTypes = deserializationContentTypes && deserializationContentTypes.xml || defaultXmlContentTypes;
  2417. return _this;
  2418. }
  2419. DeserializationPolicy.prototype.sendRequest = function (request) {
  2420. return tslib_1.__awaiter(this, void 0, void 0, function () {
  2421. var _this = this;
  2422. return tslib_1.__generator(this, function (_a) {
  2423. return [2 /*return*/, this._nextPolicy.sendRequest(request).then(function (response) { return deserializeResponseBody(_this.jsonContentTypes, _this.xmlContentTypes, response); })];
  2424. });
  2425. });
  2426. };
  2427. return DeserializationPolicy;
  2428. }(BaseRequestPolicy));
  2429. function getOperationResponse(parsedResponse) {
  2430. var result;
  2431. var request = parsedResponse.request;
  2432. var operationSpec = request.operationSpec;
  2433. if (operationSpec) {
  2434. var operationResponseGetter = request.operationResponseGetter;
  2435. if (!operationResponseGetter) {
  2436. result = operationSpec.responses[parsedResponse.status];
  2437. }
  2438. else {
  2439. result = operationResponseGetter(operationSpec, parsedResponse);
  2440. }
  2441. }
  2442. return result;
  2443. }
  2444. function shouldDeserializeResponse(parsedResponse) {
  2445. var shouldDeserialize = parsedResponse.request.shouldDeserialize;
  2446. var result;
  2447. if (shouldDeserialize === undefined) {
  2448. result = true;
  2449. }
  2450. else if (typeof shouldDeserialize === "boolean") {
  2451. result = shouldDeserialize;
  2452. }
  2453. else {
  2454. result = shouldDeserialize(parsedResponse);
  2455. }
  2456. return result;
  2457. }
  2458. function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response) {
  2459. return parse(jsonContentTypes, xmlContentTypes, response).then(function (parsedResponse) {
  2460. var shouldDeserialize = shouldDeserializeResponse(parsedResponse);
  2461. if (shouldDeserialize) {
  2462. var operationSpec = parsedResponse.request.operationSpec;
  2463. if (operationSpec && operationSpec.responses) {
  2464. var statusCode = parsedResponse.status;
  2465. var expectedStatusCodes = Object.keys(operationSpec.responses);
  2466. var hasNoExpectedStatusCodes = (expectedStatusCodes.length === 0 || (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default"));
  2467. var responseSpec = getOperationResponse(parsedResponse);
  2468. var isExpectedStatusCode = hasNoExpectedStatusCodes ? (200 <= statusCode && statusCode < 300) : !!responseSpec;
  2469. if (!isExpectedStatusCode) {
  2470. var defaultResponseSpec = operationSpec.responses.default;
  2471. if (defaultResponseSpec) {
  2472. var initialErrorMessage = isStreamOperation(operationSpec)
  2473. ? "Unexpected status code: " + statusCode
  2474. : parsedResponse.bodyAsText;
  2475. var error = new RestError(initialErrorMessage);
  2476. error.statusCode = statusCode;
  2477. error.request = stripRequest(parsedResponse.request);
  2478. error.response = stripResponse(parsedResponse);
  2479. var parsedErrorResponse = parsedResponse.parsedBody;
  2480. try {
  2481. if (parsedErrorResponse) {
  2482. var defaultResponseBodyMapper = defaultResponseSpec.bodyMapper;
  2483. if (defaultResponseBodyMapper && defaultResponseBodyMapper.serializedName === "CloudError") {
  2484. if (parsedErrorResponse.error) {
  2485. parsedErrorResponse = parsedErrorResponse.error;
  2486. }
  2487. if (parsedErrorResponse.code) {
  2488. error.code = parsedErrorResponse.code;
  2489. }
  2490. if (parsedErrorResponse.message) {
  2491. error.message = parsedErrorResponse.message;
  2492. }
  2493. }
  2494. else {
  2495. var internalError = parsedErrorResponse;
  2496. if (parsedErrorResponse.error) {
  2497. internalError = parsedErrorResponse.error;
  2498. }
  2499. error.code = internalError.code;
  2500. if (internalError.message) {
  2501. error.message = internalError.message;
  2502. }
  2503. }
  2504. if (defaultResponseBodyMapper) {
  2505. var valueToDeserialize = parsedErrorResponse;
  2506. if (operationSpec.isXML && defaultResponseBodyMapper.type.name === MapperType.Sequence) {
  2507. valueToDeserialize = typeof parsedErrorResponse === "object"
  2508. ? parsedErrorResponse[defaultResponseBodyMapper.xmlElementName]
  2509. : [];
  2510. }
  2511. error.body = operationSpec.serializer.deserialize(defaultResponseBodyMapper, valueToDeserialize, "error.body");
  2512. }
  2513. }
  2514. }
  2515. catch (defaultError) {
  2516. error.message = "Error \"" + defaultError.message + "\" occurred in deserializing the responseBody - \"" + parsedResponse.bodyAsText + "\" for the default response.";
  2517. }
  2518. return Promise.reject(error);
  2519. }
  2520. }
  2521. else if (responseSpec) {
  2522. if (responseSpec.bodyMapper) {
  2523. var valueToDeserialize = parsedResponse.parsedBody;
  2524. if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperType.Sequence) {
  2525. valueToDeserialize = typeof valueToDeserialize === "object" ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName] : [];
  2526. }
  2527. try {
  2528. parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody");
  2529. }
  2530. catch (error) {
  2531. var restError = new RestError("Error " + error + " occurred in deserializing the responseBody - " + parsedResponse.bodyAsText);
  2532. restError.request = stripRequest(parsedResponse.request);
  2533. restError.response = stripResponse(parsedResponse);
  2534. return Promise.reject(restError);
  2535. }
  2536. }
  2537. else if (operationSpec.httpMethod === "HEAD") {
  2538. // head methods never have a body, but we return a boolean to indicate presence/absence of the resource
  2539. parsedResponse.parsedBody = response.status >= 200 && response.status < 300;
  2540. }
  2541. if (responseSpec.headersMapper) {
  2542. parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.rawHeaders(), "operationRes.parsedHeaders");
  2543. }
  2544. }
  2545. }
  2546. }
  2547. return Promise.resolve(parsedResponse);
  2548. });
  2549. }
  2550. function parse(jsonContentTypes, xmlContentTypes, operationResponse) {
  2551. var errorHandler = function (err) {
  2552. var msg = "Error \"" + err + "\" occurred while parsing the response body - " + operationResponse.bodyAsText + ".";
  2553. var errCode = err.code || RestError.PARSE_ERROR;
  2554. var e = new RestError(msg, errCode, operationResponse.status, operationResponse.request, operationResponse, operationResponse.bodyAsText);
  2555. return Promise.reject(e);
  2556. };
  2557. if (!operationResponse.request.streamResponseBody && operationResponse.bodyAsText) {
  2558. var text_1 = operationResponse.bodyAsText;
  2559. var contentType = operationResponse.headers.get("Content-Type") || "";
  2560. var contentComponents = !contentType ? [] : contentType.split(";").map(function (component) { return component.toLowerCase(); });
  2561. if (contentComponents.length === 0 || contentComponents.some(function (component) { return jsonContentTypes.indexOf(component) !== -1; })) {
  2562. return new Promise(function (resolve) {
  2563. operationResponse.parsedBody = JSON.parse(text_1);
  2564. resolve(operationResponse);
  2565. }).catch(errorHandler);
  2566. }
  2567. else if (contentComponents.some(function (component) { return xmlContentTypes.indexOf(component) !== -1; })) {
  2568. return parseXML(text_1)
  2569. .then(function (body) {
  2570. operationResponse.parsedBody = body;
  2571. return operationResponse;
  2572. })
  2573. .catch(errorHandler);
  2574. }
  2575. }
  2576. return Promise.resolve(operationResponse);
  2577. }
  2578. // Copyright (c) Microsoft Corporation. All rights reserved.
  2579. function exponentialRetryPolicy(retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
  2580. return {
  2581. create: function (nextPolicy, options) {
  2582. return new ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval);
  2583. }
  2584. };
  2585. }
  2586. var DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30;
  2587. var DEFAULT_CLIENT_RETRY_COUNT = 3;
  2588. var DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90;
  2589. var DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3;
  2590. /**
  2591. * @class
  2592. * Instantiates a new "ExponentialRetryPolicyFilter" instance.
  2593. */
  2594. var ExponentialRetryPolicy = /** @class */ (function (_super) {
  2595. tslib_1.__extends(ExponentialRetryPolicy, _super);
  2596. /**
  2597. * @constructor
  2598. * @param {RequestPolicy} nextPolicy The next RequestPolicy in the pipeline chain.
  2599. * @param {RequestPolicyOptions} options The options for this RequestPolicy.
  2600. * @param {number} [retryCount] The client retry count.
  2601. * @param {number} [retryInterval] The client retry interval, in milliseconds.
  2602. * @param {number} [minRetryInterval] The minimum retry interval, in milliseconds.
  2603. * @param {number} [maxRetryInterval] The maximum retry interval, in milliseconds.
  2604. */
  2605. function ExponentialRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
  2606. var _this = _super.call(this, nextPolicy, options) || this;
  2607. function isNumber(n) { return typeof n === "number"; }
  2608. _this.retryCount = isNumber(retryCount) ? retryCount : DEFAULT_CLIENT_RETRY_COUNT;
  2609. _this.retryInterval = isNumber(retryInterval) ? retryInterval : DEFAULT_CLIENT_RETRY_INTERVAL;
  2610. _this.minRetryInterval = isNumber(minRetryInterval) ? minRetryInterval : DEFAULT_CLIENT_MIN_RETRY_INTERVAL;
  2611. _this.maxRetryInterval = isNumber(maxRetryInterval) ? maxRetryInterval : DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
  2612. return _this;
  2613. }
  2614. ExponentialRetryPolicy.prototype.sendRequest = function (request) {
  2615. var _this = this;
  2616. return this._nextPolicy.sendRequest(request.clone())
  2617. .then(function (response) { return retry(_this, request, response); })
  2618. .catch(function (error) { return retry(_this, request, error.response, undefined, error); });
  2619. };
  2620. return ExponentialRetryPolicy;
  2621. }(BaseRequestPolicy));
  2622. /**
  2623. * Determines if the operation should be retried and how long to wait until the next retry.
  2624. *
  2625. * @param {ExponentialRetryPolicy} policy The ExponentialRetryPolicy that this function is being called against.
  2626. * @param {number} statusCode The HTTP status code.
  2627. * @param {RetryData} retryData The retry data.
  2628. * @return {boolean} True if the operation qualifies for a retry; false otherwise.
  2629. */
  2630. function shouldRetry(policy, statusCode, retryData) {
  2631. if (statusCode == undefined || (statusCode < 500 && statusCode !== 408) || statusCode === 501 || statusCode === 505) {
  2632. return false;
  2633. }
  2634. var currentCount;
  2635. if (!retryData) {
  2636. throw new Error("retryData for the ExponentialRetryPolicyFilter cannot be null.");
  2637. }
  2638. else {
  2639. currentCount = (retryData && retryData.retryCount);
  2640. }
  2641. return (currentCount < policy.retryCount);
  2642. }
  2643. /**
  2644. * Updates the retry data for the next attempt.
  2645. *
  2646. * @param {ExponentialRetryPolicy} policy The ExponentialRetryPolicy that this function is being called against.
  2647. * @param {RetryData} retryData The retry data.
  2648. * @param {RetryError} [err] The operation"s error, if any.
  2649. */
  2650. function updateRetryData(policy, retryData, err) {
  2651. if (!retryData) {
  2652. retryData = {
  2653. retryCount: 0,
  2654. retryInterval: 0
  2655. };
  2656. }
  2657. if (err) {
  2658. if (retryData.error) {
  2659. err.innerError = retryData.error;
  2660. }
  2661. retryData.error = err;
  2662. }
  2663. // Adjust retry count
  2664. retryData.retryCount++;
  2665. // Adjust retry interval
  2666. var incrementDelta = Math.pow(2, retryData.retryCount) - 1;
  2667. var boundedRandDelta = policy.retryInterval * 0.8 +
  2668. Math.floor(Math.random() * (policy.retryInterval * 1.2 - policy.retryInterval * 0.8));
  2669. incrementDelta *= boundedRandDelta;
  2670. retryData.retryInterval = Math.min(policy.minRetryInterval + incrementDelta, policy.maxRetryInterval);
  2671. return retryData;
  2672. }
  2673. function retry(policy, request, response, retryData, requestError) {
  2674. retryData = updateRetryData(policy, retryData, requestError);
  2675. var isAborted = request.abortSignal && request.abortSignal.aborted;
  2676. if (!isAborted && shouldRetry(policy, response && response.status, retryData)) {
  2677. return delay(retryData.retryInterval)
  2678. .then(function () { return policy._nextPolicy.sendRequest(request.clone()); })
  2679. .then(function (res) { return retry(policy, request, res, retryData, undefined); })
  2680. .catch(function (err) { return retry(policy, request, response, retryData, err); });
  2681. }
  2682. else if (isAborted || requestError || !response) {
  2683. // If the operation failed in the end, return all errors instead of just the last one
  2684. var err = retryData.error ||
  2685. new RestError("Failed to send the request.", RestError.REQUEST_SEND_ERROR, response && response.status, response && response.request, response);
  2686. return Promise.reject(err);
  2687. }
  2688. else {
  2689. return Promise.resolve(response);
  2690. }
  2691. }
  2692. // Copyright (c) Microsoft Corporation. All rights reserved.
  2693. function generateClientRequestIdPolicy(requestIdHeaderName) {
  2694. if (requestIdHeaderName === void 0) { requestIdHeaderName = "x-ms-client-request-id"; }
  2695. return {
  2696. create: function (nextPolicy, options) {
  2697. return new GenerateClientRequestIdPolicy(nextPolicy, options, requestIdHeaderName);
  2698. }
  2699. };
  2700. }
  2701. var GenerateClientRequestIdPolicy = /** @class */ (function (_super) {
  2702. tslib_1.__extends(GenerateClientRequestIdPolicy, _super);
  2703. function GenerateClientRequestIdPolicy(nextPolicy, options, _requestIdHeaderName) {
  2704. var _this = _super.call(this, nextPolicy, options) || this;
  2705. _this._requestIdHeaderName = _requestIdHeaderName;
  2706. return _this;
  2707. }
  2708. GenerateClientRequestIdPolicy.prototype.sendRequest = function (request) {
  2709. if (!request.headers.contains(this._requestIdHeaderName)) {
  2710. request.headers.set(this._requestIdHeaderName, generateUuid());
  2711. }
  2712. return this._nextPolicy.sendRequest(request);
  2713. };
  2714. return GenerateClientRequestIdPolicy;
  2715. }(BaseRequestPolicy));
  2716. // Copyright (c) Microsoft Corporation. All rights reserved.
  2717. function getDefaultUserAgentKey() {
  2718. return Constants.HeaderConstants.USER_AGENT;
  2719. }
  2720. function getPlatformSpecificData() {
  2721. var runtimeInfo = {
  2722. key: "Node",
  2723. value: process.version
  2724. };
  2725. var osInfo = {
  2726. key: "OS",
  2727. value: "(" + os.arch() + "-" + os.type() + "-" + os.release() + ")"
  2728. };
  2729. return [runtimeInfo, osInfo];
  2730. }
  2731. // Copyright (c) Microsoft Corporation. All rights reserved.
  2732. function getRuntimeInfo() {
  2733. var msRestRuntime = {
  2734. key: "ms-rest-js",
  2735. value: Constants.msRestVersion
  2736. };
  2737. return [msRestRuntime];
  2738. }
  2739. function getUserAgentString(telemetryInfo, keySeparator, valueSeparator) {
  2740. if (keySeparator === void 0) { keySeparator = " "; }
  2741. if (valueSeparator === void 0) { valueSeparator = "/"; }
  2742. return telemetryInfo.map(function (info) {
  2743. var value = info.value ? "" + valueSeparator + info.value : "";
  2744. return "" + info.key + value;
  2745. }).join(keySeparator);
  2746. }
  2747. var getDefaultUserAgentHeaderName = getDefaultUserAgentKey;
  2748. function getDefaultUserAgentValue() {
  2749. var runtimeInfo = getRuntimeInfo();
  2750. var platformSpecificData = getPlatformSpecificData();
  2751. var userAgent = getUserAgentString(runtimeInfo.concat(platformSpecificData));
  2752. return userAgent;
  2753. }
  2754. function userAgentPolicy(userAgentData) {
  2755. var key = (!userAgentData || userAgentData.key == undefined) ? getDefaultUserAgentKey() : userAgentData.key;
  2756. var value = (!userAgentData || userAgentData.value == undefined) ? getDefaultUserAgentValue() : userAgentData.value;
  2757. return {
  2758. create: function (nextPolicy, options) {
  2759. return new UserAgentPolicy(nextPolicy, options, key, value);
  2760. }
  2761. };
  2762. }
  2763. var UserAgentPolicy = /** @class */ (function (_super) {
  2764. tslib_1.__extends(UserAgentPolicy, _super);
  2765. function UserAgentPolicy(_nextPolicy, _options, headerKey, headerValue) {
  2766. var _this = _super.call(this, _nextPolicy, _options) || this;
  2767. _this._nextPolicy = _nextPolicy;
  2768. _this._options = _options;
  2769. _this.headerKey = headerKey;
  2770. _this.headerValue = headerValue;
  2771. return _this;
  2772. }
  2773. UserAgentPolicy.prototype.sendRequest = function (request) {
  2774. this.addUserAgentHeader(request);
  2775. return this._nextPolicy.sendRequest(request);
  2776. };
  2777. UserAgentPolicy.prototype.addUserAgentHeader = function (request) {
  2778. if (!request.headers) {
  2779. request.headers = new HttpHeaders();
  2780. }
  2781. if (!request.headers.get(this.headerKey) && this.headerValue) {
  2782. request.headers.set(this.headerKey, this.headerValue);
  2783. }
  2784. };
  2785. return UserAgentPolicy;
  2786. }(BaseRequestPolicy));
  2787. // Copyright (c) Microsoft Corporation. All rights reserved.
  2788. function redirectPolicy(maximumRetries) {
  2789. if (maximumRetries === void 0) { maximumRetries = 20; }
  2790. return {
  2791. create: function (nextPolicy, options) {
  2792. return new RedirectPolicy(nextPolicy, options, maximumRetries);
  2793. }
  2794. };
  2795. }
  2796. var RedirectPolicy = /** @class */ (function (_super) {
  2797. tslib_1.__extends(RedirectPolicy, _super);
  2798. function RedirectPolicy(nextPolicy, options, maxRetries) {
  2799. if (maxRetries === void 0) { maxRetries = 20; }
  2800. var _this = _super.call(this, nextPolicy, options) || this;
  2801. _this.maxRetries = maxRetries;
  2802. return _this;
  2803. }
  2804. RedirectPolicy.prototype.sendRequest = function (request) {
  2805. var _this = this;
  2806. return this._nextPolicy.sendRequest(request).then(function (response) { return handleRedirect(_this, response, 0); });
  2807. };
  2808. return RedirectPolicy;
  2809. }(BaseRequestPolicy));
  2810. function handleRedirect(policy, response, currentRetries) {
  2811. var request = response.request, status = response.status;
  2812. var locationHeader = response.headers.get("location");
  2813. if (locationHeader &&
  2814. (status === 300 || status === 307 || (status === 303 && request.method === "POST")) &&
  2815. (!policy.maxRetries || currentRetries < policy.maxRetries)) {
  2816. var builder = URLBuilder.parse(request.url);
  2817. builder.setPath(locationHeader);
  2818. request.url = builder.toString();
  2819. // POST request with Status code 303 should be converted into a
  2820. // redirected GET request if the redirect url is present in the location header
  2821. if (status === 303) {
  2822. request.method = "GET";
  2823. }
  2824. return policy._nextPolicy.sendRequest(request)
  2825. .then(function (res) { return handleRedirect(policy, res, currentRetries + 1); });
  2826. }
  2827. return Promise.resolve(response);
  2828. }
  2829. function rpRegistrationPolicy(retryTimeout) {
  2830. if (retryTimeout === void 0) { retryTimeout = 30; }
  2831. return {
  2832. create: function (nextPolicy, options) {
  2833. return new RPRegistrationPolicy(nextPolicy, options, retryTimeout);
  2834. }
  2835. };
  2836. }
  2837. var RPRegistrationPolicy = /** @class */ (function (_super) {
  2838. tslib_1.__extends(RPRegistrationPolicy, _super);
  2839. function RPRegistrationPolicy(nextPolicy, options, _retryTimeout) {
  2840. if (_retryTimeout === void 0) { _retryTimeout = 30; }
  2841. var _this = _super.call(this, nextPolicy, options) || this;
  2842. _this._retryTimeout = _retryTimeout;
  2843. return _this;
  2844. }
  2845. RPRegistrationPolicy.prototype.sendRequest = function (request) {
  2846. var _this = this;
  2847. return this._nextPolicy.sendRequest(request.clone())
  2848. .then(function (response) { return registerIfNeeded(_this, request, response); });
  2849. };
  2850. return RPRegistrationPolicy;
  2851. }(BaseRequestPolicy));
  2852. function registerIfNeeded(policy, request, response) {
  2853. if (response.status === 409) {
  2854. var rpName = checkRPNotRegisteredError(response.bodyAsText);
  2855. if (rpName) {
  2856. var urlPrefix = extractSubscriptionUrl(request.url);
  2857. return registerRP(policy, urlPrefix, rpName, request)
  2858. // Autoregistration of ${provider} failed for some reason. We will not return this error
  2859. // instead will return the initial response with 409 status code back to the user.
  2860. // do nothing here as we are returning the original response at the end of this method.
  2861. .catch(function () { return false; })
  2862. .then(function (registrationStatus) {
  2863. if (registrationStatus) {
  2864. // Retry the original request. We have to change the x-ms-client-request-id
  2865. // otherwise Azure endpoint will return the initial 409 (cached) response.
  2866. request.headers.set("x-ms-client-request-id", generateUuid());
  2867. return policy._nextPolicy.sendRequest(request.clone());
  2868. }
  2869. return response;
  2870. });
  2871. }
  2872. }
  2873. return Promise.resolve(response);
  2874. }
  2875. /**
  2876. * Reuses the headers of the original request and url (if specified).
  2877. * @param {WebResource} originalRequest The original request
  2878. * @param {boolean} reuseUrlToo Should the url from the original request be reused as well. Default false.
  2879. * @returns {object} A new request object with desired headers.
  2880. */
  2881. function getRequestEssentials(originalRequest, reuseUrlToo) {
  2882. if (reuseUrlToo === void 0) { reuseUrlToo = false; }
  2883. var reqOptions = originalRequest.clone();
  2884. if (reuseUrlToo) {
  2885. reqOptions.url = originalRequest.url;
  2886. }
  2887. // We have to change the x-ms-client-request-id otherwise Azure endpoint
  2888. // will return the initial 409 (cached) response.
  2889. reqOptions.headers.set("x-ms-client-request-id", generateUuid());
  2890. // Set content-type to application/json
  2891. reqOptions.headers.set("Content-Type", "application/json; charset=utf-8");
  2892. return reqOptions;
  2893. }
  2894. /**
  2895. * Validates the error code and message associated with 409 response status code. If it matches to that of
  2896. * RP not registered then it returns the name of the RP else returns undefined.
  2897. * @param {string} body The response body received after making the original request.
  2898. * @returns {string} The name of the RP if condition is satisfied else undefined.
  2899. */
  2900. function checkRPNotRegisteredError(body) {
  2901. var result, responseBody;
  2902. if (body) {
  2903. try {
  2904. responseBody = JSON.parse(body);
  2905. }
  2906. catch (err) {
  2907. // do nothing;
  2908. }
  2909. if (responseBody && responseBody.error && responseBody.error.message &&
  2910. responseBody.error.code && responseBody.error.code === "MissingSubscriptionRegistration") {
  2911. var matchRes = responseBody.error.message.match(/.*'(.*)'/i);
  2912. if (matchRes) {
  2913. result = matchRes.pop();
  2914. }
  2915. }
  2916. }
  2917. return result;
  2918. }
  2919. /**
  2920. * Extracts the first part of the URL, just after subscription:
  2921. * https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/
  2922. * @param {string} url The original request url
  2923. * @returns {string} The url prefix as explained above.
  2924. */
  2925. function extractSubscriptionUrl(url) {
  2926. var result;
  2927. var matchRes = url.match(/.*\/subscriptions\/[a-f0-9-]+\//ig);
  2928. if (matchRes && matchRes[0]) {
  2929. result = matchRes[0];
  2930. }
  2931. else {
  2932. throw new Error("Unable to extract subscriptionId from the given url - " + url + ".");
  2933. }
  2934. return result;
  2935. }
  2936. /**
  2937. * Registers the given provider.
  2938. * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against.
  2939. * @param {string} urlPrefix https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/
  2940. * @param {string} provider The provider name to be registered.
  2941. * @param {WebResource} originalRequest The original request sent by the user that returned a 409 response
  2942. * with a message that the provider is not registered.
  2943. * @param {registrationCallback} callback The callback that handles the RP registration
  2944. */
  2945. function registerRP(policy, urlPrefix, provider, originalRequest) {
  2946. var postUrl = urlPrefix + "providers/" + provider + "/register?api-version=2016-02-01";
  2947. var getUrl = urlPrefix + "providers/" + provider + "?api-version=2016-02-01";
  2948. var reqOptions = getRequestEssentials(originalRequest);
  2949. reqOptions.method = "POST";
  2950. reqOptions.url = postUrl;
  2951. return policy._nextPolicy.sendRequest(reqOptions)
  2952. .then(function (response) {
  2953. if (response.status !== 200) {
  2954. throw new Error("Autoregistration of " + provider + " failed. Please try registering manually.");
  2955. }
  2956. return getRegistrationStatus(policy, getUrl, originalRequest);
  2957. });
  2958. }
  2959. /**
  2960. * Polls the registration status of the provider that was registered. Polling happens at an interval of 30 seconds.
  2961. * Polling will happen till the registrationState property of the response body is "Registered".
  2962. * @param {RPRegistrationPolicy} policy The RPRegistrationPolicy this function is being called against.
  2963. * @param {string} url The request url for polling
  2964. * @param {WebResource} originalRequest The original request sent by the user that returned a 409 response
  2965. * with a message that the provider is not registered.
  2966. * @returns {Promise<boolean>} True if RP Registration is successful.
  2967. */
  2968. function getRegistrationStatus(policy, url, originalRequest) {
  2969. var reqOptions = getRequestEssentials(originalRequest);
  2970. reqOptions.url = url;
  2971. reqOptions.method = "GET";
  2972. return policy._nextPolicy.sendRequest(reqOptions).then(function (res) {
  2973. var obj = res.parsedBody;
  2974. if (res.parsedBody && obj.registrationState && obj.registrationState === "Registered") {
  2975. return true;
  2976. }
  2977. else {
  2978. return delay(policy._retryTimeout * 1000).then(function () { return getRegistrationStatus(policy, url, originalRequest); });
  2979. }
  2980. });
  2981. }
  2982. // Copyright (c) Microsoft Corporation. All rights reserved.
  2983. function signingPolicy(authenticationProvider) {
  2984. return {
  2985. create: function (nextPolicy, options) {
  2986. return new SigningPolicy(nextPolicy, options, authenticationProvider);
  2987. }
  2988. };
  2989. }
  2990. var SigningPolicy = /** @class */ (function (_super) {
  2991. tslib_1.__extends(SigningPolicy, _super);
  2992. function SigningPolicy(nextPolicy, options, authenticationProvider) {
  2993. var _this = _super.call(this, nextPolicy, options) || this;
  2994. _this.authenticationProvider = authenticationProvider;
  2995. return _this;
  2996. }
  2997. SigningPolicy.prototype.signRequest = function (request) {
  2998. return this.authenticationProvider.signRequest(request);
  2999. };
  3000. SigningPolicy.prototype.sendRequest = function (request) {
  3001. var _this = this;
  3002. return this.signRequest(request).then(function (nextRequest) { return _this._nextPolicy.sendRequest(nextRequest); });
  3003. };
  3004. return SigningPolicy;
  3005. }(BaseRequestPolicy));
  3006. // Copyright (c) Microsoft Corporation. All rights reserved.
  3007. function systemErrorRetryPolicy(retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
  3008. return {
  3009. create: function (nextPolicy, options) {
  3010. return new SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval);
  3011. }
  3012. };
  3013. }
  3014. /**
  3015. * @class
  3016. * Instantiates a new "ExponentialRetryPolicyFilter" instance.
  3017. *
  3018. * @constructor
  3019. * @param {number} retryCount The client retry count.
  3020. * @param {number} retryInterval The client retry interval, in milliseconds.
  3021. * @param {number} minRetryInterval The minimum retry interval, in milliseconds.
  3022. * @param {number} maxRetryInterval The maximum retry interval, in milliseconds.
  3023. */
  3024. var SystemErrorRetryPolicy = /** @class */ (function (_super) {
  3025. tslib_1.__extends(SystemErrorRetryPolicy, _super);
  3026. function SystemErrorRetryPolicy(nextPolicy, options, retryCount, retryInterval, minRetryInterval, maxRetryInterval) {
  3027. var _this = _super.call(this, nextPolicy, options) || this;
  3028. _this.DEFAULT_CLIENT_RETRY_INTERVAL = 1000 * 30;
  3029. _this.DEFAULT_CLIENT_RETRY_COUNT = 3;
  3030. _this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 90;
  3031. _this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL = 1000 * 3;
  3032. _this.retryCount = typeof retryCount === "number" ? retryCount : _this.DEFAULT_CLIENT_RETRY_COUNT;
  3033. _this.retryInterval = typeof retryInterval === "number" ? retryInterval : _this.DEFAULT_CLIENT_RETRY_INTERVAL;
  3034. _this.minRetryInterval = typeof minRetryInterval === "number" ? minRetryInterval : _this.DEFAULT_CLIENT_MIN_RETRY_INTERVAL;
  3035. _this.maxRetryInterval = typeof maxRetryInterval === "number" ? maxRetryInterval : _this.DEFAULT_CLIENT_MAX_RETRY_INTERVAL;
  3036. return _this;
  3037. }
  3038. SystemErrorRetryPolicy.prototype.sendRequest = function (request) {
  3039. var _this = this;
  3040. return this._nextPolicy.sendRequest(request.clone()).then(function (response) { return retry$1(_this, request, response); });
  3041. };
  3042. return SystemErrorRetryPolicy;
  3043. }(BaseRequestPolicy));
  3044. /**
  3045. * Determines if the operation should be retried and how long to wait until the next retry.
  3046. *
  3047. * @param {number} statusCode The HTTP status code.
  3048. * @param {RetryData} retryData The retry data.
  3049. * @return {boolean} True if the operation qualifies for a retry; false otherwise.
  3050. */
  3051. function shouldRetry$1(policy, retryData) {
  3052. var currentCount;
  3053. if (!retryData) {
  3054. throw new Error("retryData for the SystemErrorRetryPolicyFilter cannot be null.");
  3055. }
  3056. else {
  3057. currentCount = (retryData && retryData.retryCount);
  3058. }
  3059. return (currentCount < policy.retryCount);
  3060. }
  3061. /**
  3062. * Updates the retry data for the next attempt.
  3063. *
  3064. * @param {RetryData} retryData The retry data.
  3065. * @param {object} err The operation"s error, if any.
  3066. */
  3067. function updateRetryData$1(policy, retryData, err) {
  3068. if (!retryData) {
  3069. retryData = {
  3070. retryCount: 0,
  3071. retryInterval: 0
  3072. };
  3073. }
  3074. if (err) {
  3075. if (retryData.error) {
  3076. err.innerError = retryData.error;
  3077. }
  3078. retryData.error = err;
  3079. }
  3080. // Adjust retry count
  3081. retryData.retryCount++;
  3082. // Adjust retry interval
  3083. var incrementDelta = Math.pow(2, retryData.retryCount) - 1;
  3084. var boundedRandDelta = policy.retryInterval * 0.8 +
  3085. Math.floor(Math.random() * (policy.retryInterval * 1.2 - policy.retryInterval * 0.8));
  3086. incrementDelta *= boundedRandDelta;
  3087. retryData.retryInterval = Math.min(policy.minRetryInterval + incrementDelta, policy.maxRetryInterval);
  3088. return retryData;
  3089. }
  3090. function retry$1(policy, request, operationResponse, retryData, err) {
  3091. retryData = updateRetryData$1(policy, retryData, err);
  3092. if (err && err.code && shouldRetry$1(policy, retryData) &&
  3093. (err.code === "ETIMEDOUT" || err.code === "ESOCKETTIMEDOUT" || err.code === "ECONNREFUSED" ||
  3094. err.code === "ECONNRESET" || err.code === "ENOENT")) {
  3095. // If previous operation ended with an error and the policy allows a retry, do that
  3096. return delay(retryData.retryInterval)
  3097. .then(function () { return policy._nextPolicy.sendRequest(request.clone()); })
  3098. .then(function (res) { return retry$1(policy, request, res, retryData, err); })
  3099. .catch(function (err) { return retry$1(policy, request, operationResponse, retryData, err); });
  3100. }
  3101. else {
  3102. if (err != undefined) {
  3103. // If the operation failed in the end, return all errors instead of just the last one
  3104. err = retryData.error;
  3105. return Promise.reject(err);
  3106. }
  3107. return Promise.resolve(operationResponse);
  3108. }
  3109. }
  3110. // Copyright (c) Microsoft Corporation. All rights reserved.
  3111. (function (QueryCollectionFormat) {
  3112. QueryCollectionFormat["Csv"] = ",";
  3113. QueryCollectionFormat["Ssv"] = " ";
  3114. QueryCollectionFormat["Tsv"] = "\t";
  3115. QueryCollectionFormat["Pipes"] = "|";
  3116. QueryCollectionFormat["Multi"] = "Multi";
  3117. })(exports.QueryCollectionFormat || (exports.QueryCollectionFormat = {}));
  3118. // Copyright (c) Microsoft Corporation. All rights reserved.
  3119. function loadEnvironmentProxyValue() {
  3120. if (!process) {
  3121. return undefined;
  3122. }
  3123. if (process.env[Constants.HTTPS_PROXY]) {
  3124. return process.env[Constants.HTTPS_PROXY];
  3125. }
  3126. else if (process.env[Constants.HTTPS_PROXY.toLowerCase()]) {
  3127. return process.env[Constants.HTTPS_PROXY.toLowerCase()];
  3128. }
  3129. else if (process.env[Constants.HTTP_PROXY]) {
  3130. return process.env[Constants.HTTP_PROXY];
  3131. }
  3132. else if (process.env[Constants.HTTP_PROXY.toLowerCase()]) {
  3133. return process.env[Constants.HTTP_PROXY.toLowerCase()];
  3134. }
  3135. return undefined;
  3136. }
  3137. function getDefaultProxySettings(proxyUrl) {
  3138. if (!proxyUrl) {
  3139. proxyUrl = loadEnvironmentProxyValue();
  3140. if (!proxyUrl) {
  3141. return undefined;
  3142. }
  3143. }
  3144. var parsedUrl = URLBuilder.parse(proxyUrl);
  3145. return {
  3146. host: parsedUrl.getScheme() + "://" + parsedUrl.getHost(),
  3147. port: Number.parseInt(parsedUrl.getPort() || "80")
  3148. };
  3149. }
  3150. function proxyPolicy(proxySettings) {
  3151. return {
  3152. create: function (nextPolicy, options) {
  3153. return new ProxyPolicy(nextPolicy, options, proxySettings);
  3154. }
  3155. };
  3156. }
  3157. var ProxyPolicy = /** @class */ (function (_super) {
  3158. tslib_1.__extends(ProxyPolicy, _super);
  3159. function ProxyPolicy(nextPolicy, options, proxySettings) {
  3160. var _this = _super.call(this, nextPolicy, options) || this;
  3161. _this.proxySettings = proxySettings;
  3162. return _this;
  3163. }
  3164. ProxyPolicy.prototype.sendRequest = function (request) {
  3165. if (!request.proxySettings) {
  3166. request.proxySettings = this.proxySettings;
  3167. }
  3168. return this._nextPolicy.sendRequest(request);
  3169. };
  3170. return ProxyPolicy;
  3171. }(BaseRequestPolicy));
  3172. // Copyright (c) Microsoft Corporation. All rights reserved.
  3173. var StatusCodes = Constants.HttpConstants.StatusCodes;
  3174. function throttlingRetryPolicy() {
  3175. return {
  3176. create: function (nextPolicy, options) {
  3177. return new ThrottlingRetryPolicy(nextPolicy, options);
  3178. }
  3179. };
  3180. }
  3181. /**
  3182. * To learn more, please refer to
  3183. * https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-manager-request-limits,
  3184. * https://docs.microsoft.com/en-us/azure/azure-subscription-service-limits and
  3185. * https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/troubleshooting-throttling-errors
  3186. */
  3187. var ThrottlingRetryPolicy = /** @class */ (function (_super) {
  3188. tslib_1.__extends(ThrottlingRetryPolicy, _super);
  3189. function ThrottlingRetryPolicy(nextPolicy, options, _handleResponse) {
  3190. var _this = _super.call(this, nextPolicy, options) || this;
  3191. _this._handleResponse = _handleResponse || _this._defaultResponseHandler;
  3192. return _this;
  3193. }
  3194. ThrottlingRetryPolicy.prototype.sendRequest = function (httpRequest) {
  3195. return tslib_1.__awaiter(this, void 0, void 0, function () {
  3196. var _this = this;
  3197. return tslib_1.__generator(this, function (_a) {
  3198. return [2 /*return*/, this._nextPolicy.sendRequest(httpRequest.clone()).then(function (response) {
  3199. if (response.status !== StatusCodes.TooManyRequests) {
  3200. return response;
  3201. }
  3202. else {
  3203. return _this._handleResponse(httpRequest, response);
  3204. }
  3205. })];
  3206. });
  3207. });
  3208. };
  3209. ThrottlingRetryPolicy.prototype._defaultResponseHandler = function (httpRequest, httpResponse) {
  3210. return tslib_1.__awaiter(this, void 0, void 0, function () {
  3211. var retryAfterHeader, delayInMs;
  3212. var _this = this;
  3213. return tslib_1.__generator(this, function (_a) {
  3214. retryAfterHeader = httpResponse.headers.get(Constants.HeaderConstants.RETRY_AFTER);
  3215. if (retryAfterHeader) {
  3216. delayInMs = ThrottlingRetryPolicy.parseRetryAfterHeader(retryAfterHeader);
  3217. if (delayInMs) {
  3218. return [2 /*return*/, delay(delayInMs).then(function (_) { return _this._nextPolicy.sendRequest(httpRequest); })];
  3219. }
  3220. }
  3221. return [2 /*return*/, httpResponse];
  3222. });
  3223. });
  3224. };
  3225. ThrottlingRetryPolicy.parseRetryAfterHeader = function (headerValue) {
  3226. var retryAfterInSeconds = Number(headerValue);
  3227. if (Number.isNaN(retryAfterInSeconds)) {
  3228. return ThrottlingRetryPolicy.parseDateRetryAfterHeader(headerValue);
  3229. }
  3230. else {
  3231. return retryAfterInSeconds * 1000;
  3232. }
  3233. };
  3234. ThrottlingRetryPolicy.parseDateRetryAfterHeader = function (headerValue) {
  3235. try {
  3236. var now = Date.now();
  3237. var date = Date.parse(headerValue);
  3238. var diff = date - now;
  3239. return Number.isNaN(diff) ? undefined : diff;
  3240. }
  3241. catch (error) {
  3242. return undefined;
  3243. }
  3244. };
  3245. return ThrottlingRetryPolicy;
  3246. }(BaseRequestPolicy));
  3247. // Copyright (c) Microsoft Corporation. All rights reserved.
  3248. /**
  3249. * @class
  3250. * Initializes a new instance of the ServiceClient.
  3251. */
  3252. var ServiceClient = /** @class */ (function () {
  3253. /**
  3254. * The ServiceClient constructor
  3255. * @constructor
  3256. * @param {ServiceClientCredentials} [credentials] The credentials object used for authentication.
  3257. * @param {ServiceClientOptions} [options] The service client options that govern the behavior of the client.
  3258. */
  3259. function ServiceClient(credentials, options) {
  3260. if (!options) {
  3261. options = {};
  3262. }
  3263. if (credentials && !credentials.signRequest) {
  3264. throw new Error("credentials argument needs to implement signRequest method");
  3265. }
  3266. this._withCredentials = options.withCredentials || false;
  3267. this._httpClient = options.httpClient || new AxiosHttpClient();
  3268. this._requestPolicyOptions = new RequestPolicyOptions(options.httpPipelineLogger);
  3269. var requestPolicyFactories;
  3270. if (Array.isArray(options.requestPolicyFactories)) {
  3271. requestPolicyFactories = options.requestPolicyFactories;
  3272. }
  3273. else {
  3274. requestPolicyFactories = createDefaultRequestPolicyFactories(credentials, options);
  3275. if (options.requestPolicyFactories) {
  3276. var newRequestPolicyFactories = options.requestPolicyFactories(requestPolicyFactories);
  3277. if (newRequestPolicyFactories) {
  3278. requestPolicyFactories = newRequestPolicyFactories;
  3279. }
  3280. }
  3281. }
  3282. this._requestPolicyFactories = requestPolicyFactories;
  3283. }
  3284. /**
  3285. * Send the provided httpRequest.
  3286. */
  3287. ServiceClient.prototype.sendRequest = function (options) {
  3288. if (options === null || options === undefined || typeof options !== "object") {
  3289. throw new Error("options cannot be null or undefined and it must be of type object.");
  3290. }
  3291. var httpRequest;
  3292. try {
  3293. if (options instanceof WebResource) {
  3294. options.validateRequestProperties();
  3295. httpRequest = options;
  3296. }
  3297. else {
  3298. httpRequest = new WebResource();
  3299. httpRequest = httpRequest.prepare(options);
  3300. }
  3301. }
  3302. catch (error) {
  3303. return Promise.reject(error);
  3304. }
  3305. var httpPipeline = this._httpClient;
  3306. if (this._requestPolicyFactories && this._requestPolicyFactories.length > 0) {
  3307. for (var i = this._requestPolicyFactories.length - 1; i >= 0; --i) {
  3308. httpPipeline = this._requestPolicyFactories[i].create(httpPipeline, this._requestPolicyOptions);
  3309. }
  3310. }
  3311. return httpPipeline.sendRequest(httpRequest);
  3312. };
  3313. /**
  3314. * Send an HTTP request that is populated using the provided OperationSpec.
  3315. * @param {OperationArguments} operationArguments The arguments that the HTTP request's templated values will be populated from.
  3316. * @param {OperationSpec} operationSpec The OperationSpec to use to populate the httpRequest.
  3317. * @param {ServiceCallback} callback The callback to call when the response is received.
  3318. */
  3319. ServiceClient.prototype.sendOperationRequest = function (operationArguments, operationSpec, callback) {
  3320. if (typeof operationArguments.options === "function") {
  3321. callback = operationArguments.options;
  3322. operationArguments.options = undefined;
  3323. }
  3324. var httpRequest = new WebResource();
  3325. var result;
  3326. try {
  3327. var baseUri = operationSpec.baseUrl || this.baseUri;
  3328. if (!baseUri) {
  3329. 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.");
  3330. }
  3331. httpRequest.method = operationSpec.httpMethod;
  3332. httpRequest.operationSpec = operationSpec;
  3333. var requestUrl = URLBuilder.parse(baseUri);
  3334. if (operationSpec.path) {
  3335. requestUrl.appendPath(operationSpec.path);
  3336. }
  3337. if (operationSpec.urlParameters && operationSpec.urlParameters.length > 0) {
  3338. for (var _i = 0, _a = operationSpec.urlParameters; _i < _a.length; _i++) {
  3339. var urlParameter = _a[_i];
  3340. var urlParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, urlParameter, operationSpec.serializer);
  3341. urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, getPathStringFromParameter(urlParameter));
  3342. if (!urlParameter.skipEncoding) {
  3343. urlParameterValue = encodeURIComponent(urlParameterValue);
  3344. }
  3345. requestUrl.replaceAll("{" + (urlParameter.mapper.serializedName || getPathStringFromParameter(urlParameter)) + "}", urlParameterValue);
  3346. }
  3347. }
  3348. if (operationSpec.queryParameters && operationSpec.queryParameters.length > 0) {
  3349. for (var _b = 0, _c = operationSpec.queryParameters; _b < _c.length; _b++) {
  3350. var queryParameter = _c[_b];
  3351. var queryParameterValue = getOperationArgumentValueFromParameter(this, operationArguments, queryParameter, operationSpec.serializer);
  3352. if (queryParameterValue != undefined) {
  3353. queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter));
  3354. if (queryParameter.collectionFormat != undefined) {
  3355. if (queryParameter.collectionFormat === exports.QueryCollectionFormat.Multi) {
  3356. if (queryParameterValue.length === 0) {
  3357. queryParameterValue = "";
  3358. }
  3359. else {
  3360. for (var index in queryParameterValue) {
  3361. var item = queryParameterValue[index];
  3362. queryParameterValue[index] = item == undefined ? "" : item.toString();
  3363. }
  3364. }
  3365. }
  3366. else {
  3367. queryParameterValue = queryParameterValue.join(queryParameter.collectionFormat);
  3368. }
  3369. }
  3370. if (!queryParameter.skipEncoding) {
  3371. if (Array.isArray(queryParameterValue)) {
  3372. for (var index in queryParameterValue) {
  3373. queryParameterValue[index] = encodeURIComponent(queryParameterValue[index]);
  3374. }
  3375. }
  3376. else {
  3377. queryParameterValue = encodeURIComponent(queryParameterValue);
  3378. }
  3379. }
  3380. requestUrl.setQueryParameter(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue);
  3381. }
  3382. }
  3383. }
  3384. httpRequest.url = requestUrl.toString();
  3385. var contentType = operationSpec.contentType || this.requestContentType;
  3386. if (contentType) {
  3387. httpRequest.headers.set("Content-Type", contentType);
  3388. }
  3389. if (operationSpec.headerParameters) {
  3390. for (var _d = 0, _e = operationSpec.headerParameters; _d < _e.length; _d++) {
  3391. var headerParameter = _e[_d];
  3392. var headerValue = getOperationArgumentValueFromParameter(this, operationArguments, headerParameter, operationSpec.serializer);
  3393. if (headerValue != undefined) {
  3394. headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter));
  3395. var headerCollectionPrefix = headerParameter.mapper.headerCollectionPrefix;
  3396. if (headerCollectionPrefix) {
  3397. for (var _f = 0, _g = Object.keys(headerValue); _f < _g.length; _f++) {
  3398. var key = _g[_f];
  3399. httpRequest.headers.set(headerCollectionPrefix + key, headerValue[key]);
  3400. }
  3401. }
  3402. else {
  3403. httpRequest.headers.set(headerParameter.mapper.serializedName || getPathStringFromParameter(headerParameter), headerValue);
  3404. }
  3405. }
  3406. }
  3407. }
  3408. var options = operationArguments.options;
  3409. if (options) {
  3410. if (options.customHeaders) {
  3411. for (var customHeaderName in options.customHeaders) {
  3412. httpRequest.headers.set(customHeaderName, options.customHeaders[customHeaderName]);
  3413. }
  3414. }
  3415. if (options.abortSignal) {
  3416. httpRequest.abortSignal = options.abortSignal;
  3417. }
  3418. if (options.timeout) {
  3419. httpRequest.timeout = options.timeout;
  3420. }
  3421. if (options.onUploadProgress) {
  3422. httpRequest.onUploadProgress = options.onUploadProgress;
  3423. }
  3424. if (options.onDownloadProgress) {
  3425. httpRequest.onDownloadProgress = options.onDownloadProgress;
  3426. }
  3427. }
  3428. httpRequest.withCredentials = this._withCredentials;
  3429. serializeRequestBody(this, httpRequest, operationArguments, operationSpec);
  3430. if (httpRequest.streamResponseBody == undefined) {
  3431. httpRequest.streamResponseBody = isStreamOperation(operationSpec);
  3432. }
  3433. result = this.sendRequest(httpRequest)
  3434. .then(function (res) { return flattenResponse(res, operationSpec.responses[res.status]); });
  3435. }
  3436. catch (error) {
  3437. result = Promise.reject(error);
  3438. }
  3439. var cb = callback;
  3440. if (cb) {
  3441. result
  3442. // tslint:disable-next-line:no-null-keyword
  3443. .then(function (res) { return cb(null, res._response.parsedBody, res._response.request, res._response); })
  3444. .catch(function (err) { return cb(err); });
  3445. }
  3446. return result;
  3447. };
  3448. return ServiceClient;
  3449. }());
  3450. function serializeRequestBody(serviceClient, httpRequest, operationArguments, operationSpec) {
  3451. if (operationSpec.requestBody && operationSpec.requestBody.mapper) {
  3452. httpRequest.body = getOperationArgumentValueFromParameter(serviceClient, operationArguments, operationSpec.requestBody, operationSpec.serializer);
  3453. var bodyMapper = operationSpec.requestBody.mapper;
  3454. var required = bodyMapper.required, xmlName = bodyMapper.xmlName, xmlElementName = bodyMapper.xmlElementName, serializedName = bodyMapper.serializedName;
  3455. var typeName = bodyMapper.type.name;
  3456. try {
  3457. if (httpRequest.body != undefined || required) {
  3458. var requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody);
  3459. httpRequest.body = operationSpec.serializer.serialize(bodyMapper, httpRequest.body, requestBodyParameterPathString);
  3460. var isStream = typeName === MapperType.Stream;
  3461. if (operationSpec.isXML) {
  3462. if (typeName === MapperType.Sequence) {
  3463. httpRequest.body = stringifyXML(prepareXMLRootList(httpRequest.body, xmlElementName || xmlName || serializedName), { rootName: xmlName || serializedName });
  3464. }
  3465. else if (!isStream) {
  3466. httpRequest.body = stringifyXML(httpRequest.body, { rootName: xmlName || serializedName });
  3467. }
  3468. }
  3469. else if (!isStream) {
  3470. httpRequest.body = JSON.stringify(httpRequest.body);
  3471. }
  3472. }
  3473. }
  3474. catch (error) {
  3475. throw new Error("Error \"" + error.message + "\" occurred in serializing the payload - " + JSON.stringify(serializedName, undefined, " ") + ".");
  3476. }
  3477. }
  3478. else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) {
  3479. httpRequest.formData = {};
  3480. for (var _i = 0, _a = operationSpec.formDataParameters; _i < _a.length; _i++) {
  3481. var formDataParameter = _a[_i];
  3482. var formDataParameterValue = getOperationArgumentValueFromParameter(serviceClient, operationArguments, formDataParameter, operationSpec.serializer);
  3483. if (formDataParameterValue != undefined) {
  3484. var formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter);
  3485. httpRequest.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter));
  3486. }
  3487. }
  3488. }
  3489. }
  3490. function isRequestPolicyFactory(instance) {
  3491. return typeof instance.create === "function";
  3492. }
  3493. function getValueOrFunctionResult(value, defaultValueCreator) {
  3494. var result;
  3495. if (typeof value === "string") {
  3496. result = value;
  3497. }
  3498. else {
  3499. result = defaultValueCreator();
  3500. if (typeof value === "function") {
  3501. result = value(result);
  3502. }
  3503. }
  3504. return result;
  3505. }
  3506. function createDefaultRequestPolicyFactories(credentials, options) {
  3507. var factories = [];
  3508. if (options.generateClientRequestIdHeader) {
  3509. factories.push(generateClientRequestIdPolicy(options.clientRequestIdHeaderName));
  3510. }
  3511. if (credentials) {
  3512. if (isRequestPolicyFactory(credentials)) {
  3513. factories.push(credentials);
  3514. }
  3515. else {
  3516. factories.push(signingPolicy(credentials));
  3517. }
  3518. }
  3519. var userAgentHeaderName = getValueOrFunctionResult(options.userAgentHeaderName, getDefaultUserAgentHeaderName);
  3520. var userAgentHeaderValue = getValueOrFunctionResult(options.userAgent, getDefaultUserAgentValue);
  3521. if (userAgentHeaderName && userAgentHeaderValue) {
  3522. factories.push(userAgentPolicy({ key: userAgentHeaderName, value: userAgentHeaderValue }));
  3523. }
  3524. factories.push(redirectPolicy());
  3525. factories.push(rpRegistrationPolicy(options.rpRegistrationRetryTimeout));
  3526. if (!options.noRetryPolicy) {
  3527. factories.push(exponentialRetryPolicy());
  3528. factories.push(systemErrorRetryPolicy());
  3529. factories.push(throttlingRetryPolicy());
  3530. }
  3531. factories.push(deserializationPolicy(options.deserializationContentTypes));
  3532. var proxySettings = options.proxySettings || getDefaultProxySettings();
  3533. if (proxySettings) {
  3534. factories.push(proxyPolicy(proxySettings));
  3535. }
  3536. return factories;
  3537. }
  3538. function getOperationArgumentValueFromParameter(serviceClient, operationArguments, parameter, serializer) {
  3539. return getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameter.parameterPath, parameter.mapper, serializer);
  3540. }
  3541. function getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, parameterPath, parameterMapper, serializer) {
  3542. var value;
  3543. if (typeof parameterPath === "string") {
  3544. parameterPath = [parameterPath];
  3545. }
  3546. if (Array.isArray(parameterPath)) {
  3547. if (parameterPath.length > 0) {
  3548. if (parameterMapper.isConstant) {
  3549. value = parameterMapper.defaultValue;
  3550. }
  3551. else {
  3552. var propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath);
  3553. if (!propertySearchResult.propertyFound) {
  3554. propertySearchResult = getPropertyFromParameterPath(serviceClient, parameterPath);
  3555. }
  3556. var useDefaultValue = false;
  3557. if (!propertySearchResult.propertyFound) {
  3558. useDefaultValue = parameterMapper.required || (parameterPath[0] === "options" && parameterPath.length === 2);
  3559. }
  3560. value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue;
  3561. }
  3562. // Serialize just for validation purposes.
  3563. var parameterPathString = getPathStringFromParameterPath(parameterPath, parameterMapper);
  3564. serializer.serialize(parameterMapper, value, parameterPathString);
  3565. }
  3566. }
  3567. else {
  3568. if (parameterMapper.required) {
  3569. value = {};
  3570. }
  3571. for (var propertyName in parameterPath) {
  3572. var propertyMapper = parameterMapper.type.modelProperties[propertyName];
  3573. var propertyPath = parameterPath[propertyName];
  3574. var propertyValue = getOperationArgumentValueFromParameterPath(serviceClient, operationArguments, propertyPath, propertyMapper, serializer);
  3575. // Serialize just for validation purposes.
  3576. var propertyPathString = getPathStringFromParameterPath(propertyPath, propertyMapper);
  3577. serializer.serialize(propertyMapper, propertyValue, propertyPathString);
  3578. if (propertyValue !== undefined) {
  3579. if (!value) {
  3580. value = {};
  3581. }
  3582. value[propertyName] = propertyValue;
  3583. }
  3584. }
  3585. }
  3586. return value;
  3587. }
  3588. function getPropertyFromParameterPath(parent, parameterPath) {
  3589. var result = { propertyFound: false };
  3590. var i = 0;
  3591. for (; i < parameterPath.length; ++i) {
  3592. var parameterPathPart = parameterPath[i];
  3593. // Make sure to check inherited properties too, so don't use hasOwnProperty().
  3594. if (parent != undefined && parameterPathPart in parent) {
  3595. parent = parent[parameterPathPart];
  3596. }
  3597. else {
  3598. break;
  3599. }
  3600. }
  3601. if (i === parameterPath.length) {
  3602. result.propertyValue = parent;
  3603. result.propertyFound = true;
  3604. }
  3605. return result;
  3606. }
  3607. function flattenResponse(_response, responseSpec) {
  3608. var parsedHeaders = _response.parsedHeaders;
  3609. var bodyMapper = responseSpec && responseSpec.bodyMapper;
  3610. var addOperationResponse = function (obj) {
  3611. return Object.defineProperty(obj, "_response", {
  3612. value: _response
  3613. });
  3614. };
  3615. if (bodyMapper) {
  3616. var typeName = bodyMapper.type.name;
  3617. if (typeName === "Stream") {
  3618. return addOperationResponse(tslib_1.__assign({}, parsedHeaders, { blobBody: _response.blobBody, readableStreamBody: _response.readableStreamBody }));
  3619. }
  3620. var modelProperties_1 = typeName === "Composite" && bodyMapper.type.modelProperties || {};
  3621. var isPageableResponse = Object.keys(modelProperties_1).some(function (k) { return modelProperties_1[k].serializedName === ""; });
  3622. if (typeName === "Sequence" || isPageableResponse) {
  3623. var arrayResponse = (_response.parsedBody || []).slice();
  3624. for (var _i = 0, _a = Object.keys(modelProperties_1); _i < _a.length; _i++) {
  3625. var key = _a[_i];
  3626. if (modelProperties_1[key].serializedName) {
  3627. arrayResponse[key] = _response.parsedBody[key];
  3628. }
  3629. }
  3630. if (parsedHeaders) {
  3631. for (var _b = 0, _c = Object.keys(parsedHeaders); _b < _c.length; _b++) {
  3632. var key = _c[_b];
  3633. arrayResponse[key] = parsedHeaders[key];
  3634. }
  3635. }
  3636. addOperationResponse(arrayResponse);
  3637. return arrayResponse;
  3638. }
  3639. if (typeName === "Composite" || typeName === "Dictionary") {
  3640. return addOperationResponse(tslib_1.__assign({}, parsedHeaders, _response.parsedBody));
  3641. }
  3642. }
  3643. if (bodyMapper || _response.request.method === "HEAD") {
  3644. // primitive body types and HEAD booleans
  3645. return addOperationResponse(tslib_1.__assign({}, parsedHeaders, { body: _response.parsedBody }));
  3646. }
  3647. return addOperationResponse(tslib_1.__assign({}, parsedHeaders, _response.parsedBody));
  3648. }
  3649. // Copyright (c) Microsoft Corporation. All rights reserved.
  3650. function logPolicy(logger) {
  3651. if (logger === void 0) { logger = console.log; }
  3652. return {
  3653. create: function (nextPolicy, options) {
  3654. return new LogPolicy(nextPolicy, options, logger);
  3655. }
  3656. };
  3657. }
  3658. var LogPolicy = /** @class */ (function (_super) {
  3659. tslib_1.__extends(LogPolicy, _super);
  3660. function LogPolicy(nextPolicy, options, logger) {
  3661. if (logger === void 0) { logger = console.log; }
  3662. var _this = _super.call(this, nextPolicy, options) || this;
  3663. _this.logger = logger;
  3664. return _this;
  3665. }
  3666. LogPolicy.prototype.sendRequest = function (request) {
  3667. var _this = this;
  3668. return this._nextPolicy.sendRequest(request).then(function (response) { return logResponse(_this, response); });
  3669. };
  3670. return LogPolicy;
  3671. }(BaseRequestPolicy));
  3672. function logResponse(policy, response) {
  3673. policy.logger(">> Request: " + JSON.stringify(response.request, undefined, 2));
  3674. policy.logger(">> Response status code: " + response.status);
  3675. var responseBody = response.bodyAsText;
  3676. policy.logger(">> Body: " + responseBody);
  3677. return Promise.resolve(response);
  3678. }
  3679. // Copyright (c) Microsoft Corporation. All rights reserved.
  3680. var HeaderConstants = Constants.HeaderConstants;
  3681. var DEFAULT_AUTHORIZATION_SCHEME = "Bearer";
  3682. /**
  3683. * A credentials object that uses a token string and a authorzation scheme to authenticate.
  3684. */
  3685. var TokenCredentials = /** @class */ (function () {
  3686. /**
  3687. * Creates a new TokenCredentials object.
  3688. *
  3689. * @constructor
  3690. * @param {string} token The token.
  3691. * @param {string} [authorizationScheme] The authorization scheme.
  3692. */
  3693. function TokenCredentials(token, authorizationScheme) {
  3694. if (authorizationScheme === void 0) { authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME; }
  3695. this.authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME;
  3696. if (!token) {
  3697. throw new Error("token cannot be null or undefined.");
  3698. }
  3699. this.token = token;
  3700. this.authorizationScheme = authorizationScheme;
  3701. }
  3702. /**
  3703. * Signs a request with the Authentication header.
  3704. *
  3705. * @param {WebResource} webResource The WebResource to be signed.
  3706. * @return {Promise<WebResource>} The signed request object.
  3707. */
  3708. TokenCredentials.prototype.signRequest = function (webResource) {
  3709. if (!webResource.headers)
  3710. webResource.headers = new HttpHeaders();
  3711. webResource.headers.set(HeaderConstants.AUTHORIZATION, this.authorizationScheme + " " + this.token);
  3712. return Promise.resolve(webResource);
  3713. };
  3714. return TokenCredentials;
  3715. }());
  3716. // Copyright (c) Microsoft Corporation. All rights reserved.
  3717. var HeaderConstants$1 = Constants.HeaderConstants;
  3718. var DEFAULT_AUTHORIZATION_SCHEME$1 = "Basic";
  3719. var BasicAuthenticationCredentials = /** @class */ (function () {
  3720. /**
  3721. * Creates a new BasicAuthenticationCredentials object.
  3722. *
  3723. * @constructor
  3724. * @param {string} userName User name.
  3725. * @param {string} password Password.
  3726. * @param {string} [authorizationScheme] The authorization scheme.
  3727. */
  3728. function BasicAuthenticationCredentials(userName, password, authorizationScheme) {
  3729. if (authorizationScheme === void 0) { authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$1; }
  3730. this.authorizationScheme = DEFAULT_AUTHORIZATION_SCHEME$1;
  3731. if (userName === null || userName === undefined || typeof userName.valueOf() !== "string") {
  3732. throw new Error("userName cannot be null or undefined and must be of type string.");
  3733. }
  3734. if (password === null || password === undefined || typeof password.valueOf() !== "string") {
  3735. throw new Error("password cannot be null or undefined and must be of type string.");
  3736. }
  3737. this.userName = userName;
  3738. this.password = password;
  3739. this.authorizationScheme = authorizationScheme;
  3740. }
  3741. /**
  3742. * Signs a request with the Authentication header.
  3743. *
  3744. * @param {WebResource} webResource The WebResource to be signed.
  3745. * @returns {Promise<WebResource>} The signed request object.
  3746. */
  3747. BasicAuthenticationCredentials.prototype.signRequest = function (webResource) {
  3748. var credentials = this.userName + ":" + this.password;
  3749. var encodedCredentials = this.authorizationScheme + " " + encodeString(credentials);
  3750. if (!webResource.headers)
  3751. webResource.headers = new HttpHeaders();
  3752. webResource.headers.set(HeaderConstants$1.AUTHORIZATION, encodedCredentials);
  3753. return Promise.resolve(webResource);
  3754. };
  3755. return BasicAuthenticationCredentials;
  3756. }());
  3757. // Copyright (c) Microsoft Corporation. All rights reserved.
  3758. /**
  3759. * Authenticates to a service using an API key.
  3760. */
  3761. var ApiKeyCredentials = /** @class */ (function () {
  3762. /**
  3763. * @constructor
  3764. * @param {object} options Specifies the options to be provided for auth. Either header or query needs to be provided.
  3765. */
  3766. function ApiKeyCredentials(options) {
  3767. if (!options || (options && !options.inHeader && !options.inQuery)) {
  3768. throw new Error("options cannot be null or undefined. Either \"inHeader\" or \"inQuery\" property of the options object needs to be provided.");
  3769. }
  3770. this.inHeader = options.inHeader;
  3771. this.inQuery = options.inQuery;
  3772. }
  3773. /**
  3774. * Signs a request with the values provided in the inHeader and inQuery parameter.
  3775. *
  3776. * @param {WebResource} webResource The WebResource to be signed.
  3777. * @returns {Promise<WebResource>} The signed request object.
  3778. */
  3779. ApiKeyCredentials.prototype.signRequest = function (webResource) {
  3780. if (!webResource) {
  3781. return Promise.reject(new Error("webResource cannot be null or undefined and must be of type \"object\"."));
  3782. }
  3783. if (this.inHeader) {
  3784. if (!webResource.headers) {
  3785. webResource.headers = new HttpHeaders();
  3786. }
  3787. for (var headerName in this.inHeader) {
  3788. webResource.headers.set(headerName, this.inHeader[headerName]);
  3789. }
  3790. }
  3791. if (this.inQuery) {
  3792. if (!webResource.url) {
  3793. return Promise.reject(new Error("url cannot be null in the request object."));
  3794. }
  3795. if (webResource.url.indexOf("?") < 0) {
  3796. webResource.url += "?";
  3797. }
  3798. for (var key in this.inQuery) {
  3799. if (!webResource.url.endsWith("?")) {
  3800. webResource.url += "&";
  3801. }
  3802. webResource.url += key + "=" + this.inQuery[key];
  3803. }
  3804. }
  3805. return Promise.resolve(webResource);
  3806. };
  3807. return ApiKeyCredentials;
  3808. }());
  3809. // Copyright (c) Microsoft Corporation. All rights reserved.
  3810. var TopicCredentials = /** @class */ (function (_super) {
  3811. tslib_1.__extends(TopicCredentials, _super);
  3812. /**
  3813. * Creates a new EventGrid TopicCredentials object.
  3814. *
  3815. * @constructor
  3816. * @param {string} topicKey The EventGrid topic key
  3817. */
  3818. function TopicCredentials(topicKey) {
  3819. var _this = this;
  3820. if (!topicKey || (topicKey && typeof topicKey !== "string")) {
  3821. throw new Error("topicKey cannot be null or undefined and must be of type string.");
  3822. }
  3823. var options = {
  3824. inHeader: {
  3825. "aeg-sas-key": topicKey
  3826. }
  3827. };
  3828. _this = _super.call(this, options) || this;
  3829. return _this;
  3830. }
  3831. return TopicCredentials;
  3832. }(ApiKeyCredentials));
  3833. // Copyright (c) Microsoft Corporation. All rights reserved.
  3834. var DomainCredentials = /** @class */ (function (_super) {
  3835. tslib_1.__extends(DomainCredentials, _super);
  3836. /**
  3837. * Creates a new EventGrid DomainCredentials object.
  3838. *
  3839. * @constructor
  3840. * @param {string} domainKey The EventGrid domain key
  3841. */
  3842. function DomainCredentials(domainKey) {
  3843. var _this = this;
  3844. if (!domainKey || (domainKey && typeof domainKey !== "string")) {
  3845. throw new Error("domainKey cannot be null or undefined and must be of type string.");
  3846. }
  3847. var options = {
  3848. inHeader: {
  3849. "aeg-sas-key": domainKey
  3850. }
  3851. };
  3852. _this = _super.call(this, options) || this;
  3853. return _this;
  3854. }
  3855. return DomainCredentials;
  3856. }(ApiKeyCredentials));
  3857. // Copyright (c) Microsoft Corporation. All rights reserved.
  3858. exports.WebResource = WebResource;
  3859. exports.DefaultHttpClient = AxiosHttpClient;
  3860. exports.HttpHeaders = HttpHeaders;
  3861. exports.RestError = RestError;
  3862. exports.ServiceClient = ServiceClient;
  3863. exports.flattenResponse = flattenResponse;
  3864. exports.Constants = Constants;
  3865. exports.logPolicy = logPolicy;
  3866. exports.BaseRequestPolicy = BaseRequestPolicy;
  3867. exports.RequestPolicyOptions = RequestPolicyOptions;
  3868. exports.generateClientRequestIdPolicy = generateClientRequestIdPolicy;
  3869. exports.exponentialRetryPolicy = exponentialRetryPolicy;
  3870. exports.systemErrorRetryPolicy = systemErrorRetryPolicy;
  3871. exports.throttlingRetryPolicy = throttlingRetryPolicy;
  3872. exports.getDefaultProxySettings = getDefaultProxySettings;
  3873. exports.proxyPolicy = proxyPolicy;
  3874. exports.redirectPolicy = redirectPolicy;
  3875. exports.signingPolicy = signingPolicy;
  3876. exports.userAgentPolicy = userAgentPolicy;
  3877. exports.getDefaultUserAgentValue = getDefaultUserAgentValue;
  3878. exports.deserializationPolicy = deserializationPolicy;
  3879. exports.deserializeResponseBody = deserializeResponseBody;
  3880. exports.MapperType = MapperType;
  3881. exports.Serializer = Serializer;
  3882. exports.serializeObject = serializeObject;
  3883. exports.stripRequest = stripRequest;
  3884. exports.stripResponse = stripResponse;
  3885. exports.delay = delay;
  3886. exports.executePromisesSequentially = executePromisesSequentially;
  3887. exports.generateUuid = generateUuid;
  3888. exports.encodeUri = encodeUri;
  3889. exports.promiseToCallback = promiseToCallback;
  3890. exports.promiseToServiceCallback = promiseToServiceCallback;
  3891. exports.isValidUuid = isValidUuid;
  3892. exports.applyMixins = applyMixins;
  3893. exports.isNode = isNode;
  3894. exports.isDuration = isDuration;
  3895. exports.URLBuilder = URLBuilder;
  3896. exports.URLQuery = URLQuery;
  3897. exports.TokenCredentials = TokenCredentials;
  3898. exports.BasicAuthenticationCredentials = BasicAuthenticationCredentials;
  3899. exports.ApiKeyCredentials = ApiKeyCredentials;
  3900. exports.TopicCredentials = TopicCredentials;
  3901. exports.DomainCredentials = DomainCredentials;
  3902. //# sourceMappingURL=msRest.node.js.map