msRest.browser.js 183 KB

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