a zip code crypto-currency system good for red ONLY

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255
  1. /**
  2. * @license Angular v5.2.11
  3. * (c) 2010-2018 Google, Inc. https://angular.io/
  4. * License: MIT
  5. */
  6. import { Inject, Injectable, InjectionToken, Injector, NgModule, PLATFORM_ID } from '@angular/core';
  7. import { of } from 'rxjs/observable/of';
  8. import { concatMap } from 'rxjs/operator/concatMap';
  9. import { filter } from 'rxjs/operator/filter';
  10. import { map } from 'rxjs/operator/map';
  11. import { DOCUMENT, ɵparseCookieValue } from '@angular/common';
  12. import { Observable } from 'rxjs/Observable';
  13. /**
  14. * @fileoverview added by tsickle
  15. * @suppress {checkTypes} checked by tsc
  16. */
  17. /**
  18. * @license
  19. * Copyright Google Inc. All Rights Reserved.
  20. *
  21. * Use of this source code is governed by an MIT-style license that can be
  22. * found in the LICENSE file at https://angular.io/license
  23. */
  24. /**
  25. * Transforms an `HttpRequest` into a stream of `HttpEvent`s, one of which will likely be a
  26. * `HttpResponse`.
  27. *
  28. * `HttpHandler` is injectable. When injected, the handler instance dispatches requests to the
  29. * first interceptor in the chain, which dispatches to the second, etc, eventually reaching the
  30. * `HttpBackend`.
  31. *
  32. * In an `HttpInterceptor`, the `HttpHandler` parameter is the next interceptor in the chain.
  33. *
  34. * \@stable
  35. * @abstract
  36. */
  37. class HttpHandler {
  38. }
  39. /**
  40. * A final `HttpHandler` which will dispatch the request via browser HTTP APIs to a backend.
  41. *
  42. * Interceptors sit between the `HttpClient` interface and the `HttpBackend`.
  43. *
  44. * When injected, `HttpBackend` dispatches requests directly to the backend, without going
  45. * through the interceptor chain.
  46. *
  47. * \@stable
  48. * @abstract
  49. */
  50. class HttpBackend {
  51. }
  52. /**
  53. * @fileoverview added by tsickle
  54. * @suppress {checkTypes} checked by tsc
  55. */
  56. /**
  57. * @license
  58. * Copyright Google Inc. All Rights Reserved.
  59. *
  60. * Use of this source code is governed by an MIT-style license that can be
  61. * found in the LICENSE file at https://angular.io/license
  62. */
  63. /**
  64. * @record
  65. */
  66. /**
  67. * Immutable set of Http headers, with lazy parsing.
  68. * \@stable
  69. */
  70. class HttpHeaders {
  71. /**
  72. * @param {?=} headers
  73. */
  74. constructor(headers) {
  75. /**
  76. * Internal map of lowercased header names to the normalized
  77. * form of the name (the form seen first).
  78. */
  79. this.normalizedNames = new Map();
  80. /**
  81. * Queued updates to be materialized the next initialization.
  82. */
  83. this.lazyUpdate = null;
  84. if (!headers) {
  85. this.headers = new Map();
  86. }
  87. else if (typeof headers === 'string') {
  88. this.lazyInit = () => {
  89. this.headers = new Map();
  90. headers.split('\n').forEach(line => {
  91. const /** @type {?} */ index = line.indexOf(':');
  92. if (index > 0) {
  93. const /** @type {?} */ name = line.slice(0, index);
  94. const /** @type {?} */ key = name.toLowerCase();
  95. const /** @type {?} */ value = line.slice(index + 1).trim();
  96. this.maybeSetNormalizedName(name, key);
  97. if (this.headers.has(key)) {
  98. /** @type {?} */ ((this.headers.get(key))).push(value);
  99. }
  100. else {
  101. this.headers.set(key, [value]);
  102. }
  103. }
  104. });
  105. };
  106. }
  107. else {
  108. this.lazyInit = () => {
  109. this.headers = new Map();
  110. Object.keys(headers).forEach(name => {
  111. let /** @type {?} */ values = headers[name];
  112. const /** @type {?} */ key = name.toLowerCase();
  113. if (typeof values === 'string') {
  114. values = [values];
  115. }
  116. if (values.length > 0) {
  117. this.headers.set(key, values);
  118. this.maybeSetNormalizedName(name, key);
  119. }
  120. });
  121. };
  122. }
  123. }
  124. /**
  125. * Checks for existence of header by given name.
  126. * @param {?} name
  127. * @return {?}
  128. */
  129. has(name) {
  130. this.init();
  131. return this.headers.has(name.toLowerCase());
  132. }
  133. /**
  134. * Returns first header that matches given name.
  135. * @param {?} name
  136. * @return {?}
  137. */
  138. get(name) {
  139. this.init();
  140. const /** @type {?} */ values = this.headers.get(name.toLowerCase());
  141. return values && values.length > 0 ? values[0] : null;
  142. }
  143. /**
  144. * Returns the names of the headers
  145. * @return {?}
  146. */
  147. keys() {
  148. this.init();
  149. return Array.from(this.normalizedNames.values());
  150. }
  151. /**
  152. * Returns list of header values for a given name.
  153. * @param {?} name
  154. * @return {?}
  155. */
  156. getAll(name) {
  157. this.init();
  158. return this.headers.get(name.toLowerCase()) || null;
  159. }
  160. /**
  161. * @param {?} name
  162. * @param {?} value
  163. * @return {?}
  164. */
  165. append(name, value) {
  166. return this.clone({ name, value, op: 'a' });
  167. }
  168. /**
  169. * @param {?} name
  170. * @param {?} value
  171. * @return {?}
  172. */
  173. set(name, value) {
  174. return this.clone({ name, value, op: 's' });
  175. }
  176. /**
  177. * @param {?} name
  178. * @param {?=} value
  179. * @return {?}
  180. */
  181. delete(name, value) {
  182. return this.clone({ name, value, op: 'd' });
  183. }
  184. /**
  185. * @param {?} name
  186. * @param {?} lcName
  187. * @return {?}
  188. */
  189. maybeSetNormalizedName(name, lcName) {
  190. if (!this.normalizedNames.has(lcName)) {
  191. this.normalizedNames.set(lcName, name);
  192. }
  193. }
  194. /**
  195. * @return {?}
  196. */
  197. init() {
  198. if (!!this.lazyInit) {
  199. if (this.lazyInit instanceof HttpHeaders) {
  200. this.copyFrom(this.lazyInit);
  201. }
  202. else {
  203. this.lazyInit();
  204. }
  205. this.lazyInit = null;
  206. if (!!this.lazyUpdate) {
  207. this.lazyUpdate.forEach(update => this.applyUpdate(update));
  208. this.lazyUpdate = null;
  209. }
  210. }
  211. }
  212. /**
  213. * @param {?} other
  214. * @return {?}
  215. */
  216. copyFrom(other) {
  217. other.init();
  218. Array.from(other.headers.keys()).forEach(key => {
  219. this.headers.set(key, /** @type {?} */ ((other.headers.get(key))));
  220. this.normalizedNames.set(key, /** @type {?} */ ((other.normalizedNames.get(key))));
  221. });
  222. }
  223. /**
  224. * @param {?} update
  225. * @return {?}
  226. */
  227. clone(update) {
  228. const /** @type {?} */ clone = new HttpHeaders();
  229. clone.lazyInit =
  230. (!!this.lazyInit && this.lazyInit instanceof HttpHeaders) ? this.lazyInit : this;
  231. clone.lazyUpdate = (this.lazyUpdate || []).concat([update]);
  232. return clone;
  233. }
  234. /**
  235. * @param {?} update
  236. * @return {?}
  237. */
  238. applyUpdate(update) {
  239. const /** @type {?} */ key = update.name.toLowerCase();
  240. switch (update.op) {
  241. case 'a':
  242. case 's':
  243. let /** @type {?} */ value = /** @type {?} */ ((update.value));
  244. if (typeof value === 'string') {
  245. value = [value];
  246. }
  247. if (value.length === 0) {
  248. return;
  249. }
  250. this.maybeSetNormalizedName(update.name, key);
  251. const /** @type {?} */ base = (update.op === 'a' ? this.headers.get(key) : undefined) || [];
  252. base.push(...value);
  253. this.headers.set(key, base);
  254. break;
  255. case 'd':
  256. const /** @type {?} */ toDelete = /** @type {?} */ (update.value);
  257. if (!toDelete) {
  258. this.headers.delete(key);
  259. this.normalizedNames.delete(key);
  260. }
  261. else {
  262. let /** @type {?} */ existing = this.headers.get(key);
  263. if (!existing) {
  264. return;
  265. }
  266. existing = existing.filter(value => toDelete.indexOf(value) === -1);
  267. if (existing.length === 0) {
  268. this.headers.delete(key);
  269. this.normalizedNames.delete(key);
  270. }
  271. else {
  272. this.headers.set(key, existing);
  273. }
  274. }
  275. break;
  276. }
  277. }
  278. /**
  279. * \@internal
  280. * @param {?} fn
  281. * @return {?}
  282. */
  283. forEach(fn) {
  284. this.init();
  285. Array.from(this.normalizedNames.keys())
  286. .forEach(key => fn(/** @type {?} */ ((this.normalizedNames.get(key))), /** @type {?} */ ((this.headers.get(key)))));
  287. }
  288. }
  289. /**
  290. * @fileoverview added by tsickle
  291. * @suppress {checkTypes} checked by tsc
  292. */
  293. /**
  294. * @license
  295. * Copyright Google Inc. All Rights Reserved.
  296. *
  297. * Use of this source code is governed by an MIT-style license that can be
  298. * found in the LICENSE file at https://angular.io/license
  299. */
  300. /**
  301. * A codec for encoding and decoding parameters in URLs.
  302. *
  303. * Used by `HttpParams`.
  304. *
  305. * \@stable
  306. *
  307. * @record
  308. */
  309. /**
  310. * A `HttpParameterCodec` that uses `encodeURIComponent` and `decodeURIComponent` to
  311. * serialize and parse URL parameter keys and values.
  312. *
  313. * \@stable
  314. */
  315. class HttpUrlEncodingCodec {
  316. /**
  317. * @param {?} k
  318. * @return {?}
  319. */
  320. encodeKey(k) { return standardEncoding(k); }
  321. /**
  322. * @param {?} v
  323. * @return {?}
  324. */
  325. encodeValue(v) { return standardEncoding(v); }
  326. /**
  327. * @param {?} k
  328. * @return {?}
  329. */
  330. decodeKey(k) { return decodeURIComponent(k); }
  331. /**
  332. * @param {?} v
  333. * @return {?}
  334. */
  335. decodeValue(v) { return decodeURIComponent(v); }
  336. }
  337. /**
  338. * @param {?} rawParams
  339. * @param {?} codec
  340. * @return {?}
  341. */
  342. function paramParser(rawParams, codec) {
  343. const /** @type {?} */ map$$1 = new Map();
  344. if (rawParams.length > 0) {
  345. const /** @type {?} */ params = rawParams.split('&');
  346. params.forEach((param) => {
  347. const /** @type {?} */ eqIdx = param.indexOf('=');
  348. const [key, val] = eqIdx == -1 ?
  349. [codec.decodeKey(param), ''] :
  350. [codec.decodeKey(param.slice(0, eqIdx)), codec.decodeValue(param.slice(eqIdx + 1))];
  351. const /** @type {?} */ list = map$$1.get(key) || [];
  352. list.push(val);
  353. map$$1.set(key, list);
  354. });
  355. }
  356. return map$$1;
  357. }
  358. /**
  359. * @param {?} v
  360. * @return {?}
  361. */
  362. function standardEncoding(v) {
  363. return encodeURIComponent(v)
  364. .replace(/%40/gi, '@')
  365. .replace(/%3A/gi, ':')
  366. .replace(/%24/gi, '$')
  367. .replace(/%2C/gi, ',')
  368. .replace(/%3B/gi, ';')
  369. .replace(/%2B/gi, '+')
  370. .replace(/%3D/gi, '=')
  371. .replace(/%3F/gi, '?')
  372. .replace(/%2F/gi, '/');
  373. }
  374. /**
  375. * An HTTP request/response body that represents serialized parameters,
  376. * per the MIME type `application/x-www-form-urlencoded`.
  377. *
  378. * This class is immutable - all mutation operations return a new instance.
  379. *
  380. * \@stable
  381. */
  382. class HttpParams {
  383. /**
  384. * @param {?=} options
  385. */
  386. constructor(options = /** @type {?} */ ({})) {
  387. this.updates = null;
  388. this.cloneFrom = null;
  389. this.encoder = options.encoder || new HttpUrlEncodingCodec();
  390. if (!!options.fromString) {
  391. if (!!options.fromObject) {
  392. throw new Error(`Cannot specify both fromString and fromObject.`);
  393. }
  394. this.map = paramParser(options.fromString, this.encoder);
  395. }
  396. else if (!!options.fromObject) {
  397. this.map = new Map();
  398. Object.keys(options.fromObject).forEach(key => {
  399. const /** @type {?} */ value = (/** @type {?} */ (options.fromObject))[key]; /** @type {?} */
  400. ((this.map)).set(key, Array.isArray(value) ? value : [value]);
  401. });
  402. }
  403. else {
  404. this.map = null;
  405. }
  406. }
  407. /**
  408. * Check whether the body has one or more values for the given parameter name.
  409. * @param {?} param
  410. * @return {?}
  411. */
  412. has(param) {
  413. this.init();
  414. return /** @type {?} */ ((this.map)).has(param);
  415. }
  416. /**
  417. * Get the first value for the given parameter name, or `null` if it's not present.
  418. * @param {?} param
  419. * @return {?}
  420. */
  421. get(param) {
  422. this.init();
  423. const /** @type {?} */ res = /** @type {?} */ ((this.map)).get(param);
  424. return !!res ? res[0] : null;
  425. }
  426. /**
  427. * Get all values for the given parameter name, or `null` if it's not present.
  428. * @param {?} param
  429. * @return {?}
  430. */
  431. getAll(param) {
  432. this.init();
  433. return /** @type {?} */ ((this.map)).get(param) || null;
  434. }
  435. /**
  436. * Get all the parameter names for this body.
  437. * @return {?}
  438. */
  439. keys() {
  440. this.init();
  441. return Array.from(/** @type {?} */ ((this.map)).keys());
  442. }
  443. /**
  444. * Construct a new body with an appended value for the given parameter name.
  445. * @param {?} param
  446. * @param {?} value
  447. * @return {?}
  448. */
  449. append(param, value) { return this.clone({ param, value, op: 'a' }); }
  450. /**
  451. * Construct a new body with a new value for the given parameter name.
  452. * @param {?} param
  453. * @param {?} value
  454. * @return {?}
  455. */
  456. set(param, value) { return this.clone({ param, value, op: 's' }); }
  457. /**
  458. * Construct a new body with either the given value for the given parameter
  459. * removed, if a value is given, or all values for the given parameter removed
  460. * if not.
  461. * @param {?} param
  462. * @param {?=} value
  463. * @return {?}
  464. */
  465. delete(param, value) { return this.clone({ param, value, op: 'd' }); }
  466. /**
  467. * Serialize the body to an encoded string, where key-value pairs (separated by `=`) are
  468. * separated by `&`s.
  469. * @return {?}
  470. */
  471. toString() {
  472. this.init();
  473. return this.keys()
  474. .map(key => {
  475. const /** @type {?} */ eKey = this.encoder.encodeKey(key);
  476. return /** @type {?} */ ((/** @type {?} */ ((this.map)).get(key))).map(value => eKey + '=' + this.encoder.encodeValue(value)).join('&');
  477. })
  478. .join('&');
  479. }
  480. /**
  481. * @param {?} update
  482. * @return {?}
  483. */
  484. clone(update) {
  485. const /** @type {?} */ clone = new HttpParams({ encoder: this.encoder });
  486. clone.cloneFrom = this.cloneFrom || this;
  487. clone.updates = (this.updates || []).concat([update]);
  488. return clone;
  489. }
  490. /**
  491. * @return {?}
  492. */
  493. init() {
  494. if (this.map === null) {
  495. this.map = new Map();
  496. }
  497. if (this.cloneFrom !== null) {
  498. this.cloneFrom.init();
  499. this.cloneFrom.keys().forEach(key => /** @type {?} */ ((this.map)).set(key, /** @type {?} */ ((/** @type {?} */ ((/** @type {?} */ ((this.cloneFrom)).map)).get(key))))); /** @type {?} */
  500. ((this.updates)).forEach(update => {
  501. switch (update.op) {
  502. case 'a':
  503. case 's':
  504. const /** @type {?} */ base = (update.op === 'a' ? /** @type {?} */ ((this.map)).get(update.param) : undefined) || [];
  505. base.push(/** @type {?} */ ((update.value))); /** @type {?} */
  506. ((this.map)).set(update.param, base);
  507. break;
  508. case 'd':
  509. if (update.value !== undefined) {
  510. let /** @type {?} */ base = /** @type {?} */ ((this.map)).get(update.param) || [];
  511. const /** @type {?} */ idx = base.indexOf(update.value);
  512. if (idx !== -1) {
  513. base.splice(idx, 1);
  514. }
  515. if (base.length > 0) {
  516. /** @type {?} */ ((this.map)).set(update.param, base);
  517. }
  518. else {
  519. /** @type {?} */ ((this.map)).delete(update.param);
  520. }
  521. }
  522. else {
  523. /** @type {?} */ ((this.map)).delete(update.param);
  524. break;
  525. }
  526. }
  527. });
  528. this.cloneFrom = null;
  529. }
  530. }
  531. }
  532. /**
  533. * @fileoverview added by tsickle
  534. * @suppress {checkTypes} checked by tsc
  535. */
  536. /**
  537. * @license
  538. * Copyright Google Inc. All Rights Reserved.
  539. *
  540. * Use of this source code is governed by an MIT-style license that can be
  541. * found in the LICENSE file at https://angular.io/license
  542. */
  543. /**
  544. * Determine whether the given HTTP method may include a body.
  545. * @param {?} method
  546. * @return {?}
  547. */
  548. function mightHaveBody(method) {
  549. switch (method) {
  550. case 'DELETE':
  551. case 'GET':
  552. case 'HEAD':
  553. case 'OPTIONS':
  554. case 'JSONP':
  555. return false;
  556. default:
  557. return true;
  558. }
  559. }
  560. /**
  561. * Safely assert whether the given value is an ArrayBuffer.
  562. *
  563. * In some execution environments ArrayBuffer is not defined.
  564. * @param {?} value
  565. * @return {?}
  566. */
  567. function isArrayBuffer(value) {
  568. return typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer;
  569. }
  570. /**
  571. * Safely assert whether the given value is a Blob.
  572. *
  573. * In some execution environments Blob is not defined.
  574. * @param {?} value
  575. * @return {?}
  576. */
  577. function isBlob(value) {
  578. return typeof Blob !== 'undefined' && value instanceof Blob;
  579. }
  580. /**
  581. * Safely assert whether the given value is a FormData instance.
  582. *
  583. * In some execution environments FormData is not defined.
  584. * @param {?} value
  585. * @return {?}
  586. */
  587. function isFormData(value) {
  588. return typeof FormData !== 'undefined' && value instanceof FormData;
  589. }
  590. /**
  591. * An outgoing HTTP request with an optional typed body.
  592. *
  593. * `HttpRequest` represents an outgoing request, including URL, method,
  594. * headers, body, and other request configuration options. Instances should be
  595. * assumed to be immutable. To modify a `HttpRequest`, the `clone`
  596. * method should be used.
  597. *
  598. * \@stable
  599. * @template T
  600. */
  601. class HttpRequest {
  602. /**
  603. * @param {?} method
  604. * @param {?} url
  605. * @param {?=} third
  606. * @param {?=} fourth
  607. */
  608. constructor(method, url, third, fourth) {
  609. this.url = url;
  610. /**
  611. * The request body, or `null` if one isn't set.
  612. *
  613. * Bodies are not enforced to be immutable, as they can include a reference to any
  614. * user-defined data type. However, interceptors should take care to preserve
  615. * idempotence by treating them as such.
  616. */
  617. this.body = null;
  618. /**
  619. * Whether this request should be made in a way that exposes progress events.
  620. *
  621. * Progress events are expensive (change detection runs on each event) and so
  622. * they should only be requested if the consumer intends to monitor them.
  623. */
  624. this.reportProgress = false;
  625. /**
  626. * Whether this request should be sent with outgoing credentials (cookies).
  627. */
  628. this.withCredentials = false;
  629. /**
  630. * The expected response type of the server.
  631. *
  632. * This is used to parse the response appropriately before returning it to
  633. * the requestee.
  634. */
  635. this.responseType = 'json';
  636. this.method = method.toUpperCase();
  637. // Next, need to figure out which argument holds the HttpRequestInit
  638. // options, if any.
  639. let /** @type {?} */ options;
  640. // Check whether a body argument is expected. The only valid way to omit
  641. // the body argument is to use a known no-body method like GET.
  642. if (mightHaveBody(this.method) || !!fourth) {
  643. // Body is the third argument, options are the fourth.
  644. this.body = (third !== undefined) ? /** @type {?} */ (third) : null;
  645. options = fourth;
  646. }
  647. else {
  648. // No body required, options are the third argument. The body stays null.
  649. options = /** @type {?} */ (third);
  650. }
  651. // If options have been passed, interpret them.
  652. if (options) {
  653. // Normalize reportProgress and withCredentials.
  654. this.reportProgress = !!options.reportProgress;
  655. this.withCredentials = !!options.withCredentials;
  656. // Override default response type of 'json' if one is provided.
  657. if (!!options.responseType) {
  658. this.responseType = options.responseType;
  659. }
  660. // Override headers if they're provided.
  661. if (!!options.headers) {
  662. this.headers = options.headers;
  663. }
  664. if (!!options.params) {
  665. this.params = options.params;
  666. }
  667. }
  668. // If no headers have been passed in, construct a new HttpHeaders instance.
  669. if (!this.headers) {
  670. this.headers = new HttpHeaders();
  671. }
  672. // If no parameters have been passed in, construct a new HttpUrlEncodedParams instance.
  673. if (!this.params) {
  674. this.params = new HttpParams();
  675. this.urlWithParams = url;
  676. }
  677. else {
  678. // Encode the parameters to a string in preparation for inclusion in the URL.
  679. const /** @type {?} */ params = this.params.toString();
  680. if (params.length === 0) {
  681. // No parameters, the visible URL is just the URL given at creation time.
  682. this.urlWithParams = url;
  683. }
  684. else {
  685. // Does the URL already have query parameters? Look for '?'.
  686. const /** @type {?} */ qIdx = url.indexOf('?');
  687. // There are 3 cases to handle:
  688. // 1) No existing parameters -> append '?' followed by params.
  689. // 2) '?' exists and is followed by existing query string ->
  690. // append '&' followed by params.
  691. // 3) '?' exists at the end of the url -> append params directly.
  692. // This basically amounts to determining the character, if any, with
  693. // which to join the URL and parameters.
  694. const /** @type {?} */ sep = qIdx === -1 ? '?' : (qIdx < url.length - 1 ? '&' : '');
  695. this.urlWithParams = url + sep + params;
  696. }
  697. }
  698. }
  699. /**
  700. * Transform the free-form body into a serialized format suitable for
  701. * transmission to the server.
  702. * @return {?}
  703. */
  704. serializeBody() {
  705. // If no body is present, no need to serialize it.
  706. if (this.body === null) {
  707. return null;
  708. }
  709. // Check whether the body is already in a serialized form. If so,
  710. // it can just be returned directly.
  711. if (isArrayBuffer(this.body) || isBlob(this.body) || isFormData(this.body) ||
  712. typeof this.body === 'string') {
  713. return this.body;
  714. }
  715. // Check whether the body is an instance of HttpUrlEncodedParams.
  716. if (this.body instanceof HttpParams) {
  717. return this.body.toString();
  718. }
  719. // Check whether the body is an object or array, and serialize with JSON if so.
  720. if (typeof this.body === 'object' || typeof this.body === 'boolean' ||
  721. Array.isArray(this.body)) {
  722. return JSON.stringify(this.body);
  723. }
  724. // Fall back on toString() for everything else.
  725. return (/** @type {?} */ (this.body)).toString();
  726. }
  727. /**
  728. * Examine the body and attempt to infer an appropriate MIME type
  729. * for it.
  730. *
  731. * If no such type can be inferred, this method will return `null`.
  732. * @return {?}
  733. */
  734. detectContentTypeHeader() {
  735. // An empty body has no content type.
  736. if (this.body === null) {
  737. return null;
  738. }
  739. // FormData bodies rely on the browser's content type assignment.
  740. if (isFormData(this.body)) {
  741. return null;
  742. }
  743. // Blobs usually have their own content type. If it doesn't, then
  744. // no type can be inferred.
  745. if (isBlob(this.body)) {
  746. return this.body.type || null;
  747. }
  748. // Array buffers have unknown contents and thus no type can be inferred.
  749. if (isArrayBuffer(this.body)) {
  750. return null;
  751. }
  752. // Technically, strings could be a form of JSON data, but it's safe enough
  753. // to assume they're plain strings.
  754. if (typeof this.body === 'string') {
  755. return 'text/plain';
  756. }
  757. // `HttpUrlEncodedParams` has its own content-type.
  758. if (this.body instanceof HttpParams) {
  759. return 'application/x-www-form-urlencoded;charset=UTF-8';
  760. }
  761. // Arrays, objects, and numbers will be encoded as JSON.
  762. if (typeof this.body === 'object' || typeof this.body === 'number' ||
  763. Array.isArray(this.body)) {
  764. return 'application/json';
  765. }
  766. // No type could be inferred.
  767. return null;
  768. }
  769. /**
  770. * @param {?=} update
  771. * @return {?}
  772. */
  773. clone(update = {}) {
  774. // For method, url, and responseType, take the current value unless
  775. // it is overridden in the update hash.
  776. const /** @type {?} */ method = update.method || this.method;
  777. const /** @type {?} */ url = update.url || this.url;
  778. const /** @type {?} */ responseType = update.responseType || this.responseType;
  779. // The body is somewhat special - a `null` value in update.body means
  780. // whatever current body is present is being overridden with an empty
  781. // body, whereas an `undefined` value in update.body implies no
  782. // override.
  783. const /** @type {?} */ body = (update.body !== undefined) ? update.body : this.body;
  784. // Carefully handle the boolean options to differentiate between
  785. // `false` and `undefined` in the update args.
  786. const /** @type {?} */ withCredentials = (update.withCredentials !== undefined) ? update.withCredentials : this.withCredentials;
  787. const /** @type {?} */ reportProgress = (update.reportProgress !== undefined) ? update.reportProgress : this.reportProgress;
  788. // Headers and params may be appended to if `setHeaders` or
  789. // `setParams` are used.
  790. let /** @type {?} */ headers = update.headers || this.headers;
  791. let /** @type {?} */ params = update.params || this.params;
  792. // Check whether the caller has asked to add headers.
  793. if (update.setHeaders !== undefined) {
  794. // Set every requested header.
  795. headers =
  796. Object.keys(update.setHeaders)
  797. .reduce((headers, name) => headers.set(name, /** @type {?} */ ((update.setHeaders))[name]), headers);
  798. }
  799. // Check whether the caller has asked to set params.
  800. if (update.setParams) {
  801. // Set every requested param.
  802. params = Object.keys(update.setParams)
  803. .reduce((params, param) => params.set(param, /** @type {?} */ ((update.setParams))[param]), params);
  804. }
  805. // Finally, construct the new HttpRequest using the pieces from above.
  806. return new HttpRequest(method, url, body, {
  807. params, headers, reportProgress, responseType, withCredentials,
  808. });
  809. }
  810. }
  811. /**
  812. * @fileoverview added by tsickle
  813. * @suppress {checkTypes} checked by tsc
  814. */
  815. /**
  816. * @license
  817. * Copyright Google Inc. All Rights Reserved.
  818. *
  819. * Use of this source code is governed by an MIT-style license that can be
  820. * found in the LICENSE file at https://angular.io/license
  821. */
  822. /** @enum {number} */
  823. const HttpEventType = {
  824. /**
  825. * The request was sent out over the wire.
  826. */
  827. Sent: 0,
  828. /**
  829. * An upload progress event was received.
  830. */
  831. UploadProgress: 1,
  832. /**
  833. * The response status code and headers were received.
  834. */
  835. ResponseHeader: 2,
  836. /**
  837. * A download progress event was received.
  838. */
  839. DownloadProgress: 3,
  840. /**
  841. * The full response including the body was received.
  842. */
  843. Response: 4,
  844. /**
  845. * A custom event from an interceptor or a backend.
  846. */
  847. User: 5,
  848. };
  849. HttpEventType[HttpEventType.Sent] = "Sent";
  850. HttpEventType[HttpEventType.UploadProgress] = "UploadProgress";
  851. HttpEventType[HttpEventType.ResponseHeader] = "ResponseHeader";
  852. HttpEventType[HttpEventType.DownloadProgress] = "DownloadProgress";
  853. HttpEventType[HttpEventType.Response] = "Response";
  854. HttpEventType[HttpEventType.User] = "User";
  855. /**
  856. * Base interface for progress events.
  857. *
  858. * \@stable
  859. * @record
  860. */
  861. /**
  862. * A download progress event.
  863. *
  864. * \@stable
  865. * @record
  866. */
  867. /**
  868. * An upload progress event.
  869. *
  870. * \@stable
  871. * @record
  872. */
  873. /**
  874. * An event indicating that the request was sent to the server. Useful
  875. * when a request may be retried multiple times, to distinguish between
  876. * retries on the final event stream.
  877. *
  878. * \@stable
  879. * @record
  880. */
  881. /**
  882. * A user-defined event.
  883. *
  884. * Grouping all custom events under this type ensures they will be handled
  885. * and forwarded by all implementations of interceptors.
  886. *
  887. * \@stable
  888. * @record
  889. * @template T
  890. */
  891. /**
  892. * An error that represents a failed attempt to JSON.parse text coming back
  893. * from the server.
  894. *
  895. * It bundles the Error object with the actual response body that failed to parse.
  896. *
  897. * \@stable
  898. * @record
  899. */
  900. /**
  901. * Base class for both `HttpResponse` and `HttpHeaderResponse`.
  902. *
  903. * \@stable
  904. * @abstract
  905. */
  906. class HttpResponseBase {
  907. /**
  908. * Super-constructor for all responses.
  909. *
  910. * The single parameter accepted is an initialization hash. Any properties
  911. * of the response passed there will override the default values.
  912. * @param {?} init
  913. * @param {?=} defaultStatus
  914. * @param {?=} defaultStatusText
  915. */
  916. constructor(init, defaultStatus = 200, defaultStatusText = 'OK') {
  917. // If the hash has values passed, use them to initialize the response.
  918. // Otherwise use the default values.
  919. this.headers = init.headers || new HttpHeaders();
  920. this.status = init.status !== undefined ? init.status : defaultStatus;
  921. this.statusText = init.statusText || defaultStatusText;
  922. this.url = init.url || null;
  923. // Cache the ok value to avoid defining a getter.
  924. this.ok = this.status >= 200 && this.status < 300;
  925. }
  926. }
  927. /**
  928. * A partial HTTP response which only includes the status and header data,
  929. * but no response body.
  930. *
  931. * `HttpHeaderResponse` is a `HttpEvent` available on the response
  932. * event stream, only when progress events are requested.
  933. *
  934. * \@stable
  935. */
  936. class HttpHeaderResponse extends HttpResponseBase {
  937. /**
  938. * Create a new `HttpHeaderResponse` with the given parameters.
  939. * @param {?=} init
  940. */
  941. constructor(init = {}) {
  942. super(init);
  943. this.type = HttpEventType.ResponseHeader;
  944. }
  945. /**
  946. * Copy this `HttpHeaderResponse`, overriding its contents with the
  947. * given parameter hash.
  948. * @param {?=} update
  949. * @return {?}
  950. */
  951. clone(update = {}) {
  952. // Perform a straightforward initialization of the new HttpHeaderResponse,
  953. // overriding the current parameters with new ones if given.
  954. return new HttpHeaderResponse({
  955. headers: update.headers || this.headers,
  956. status: update.status !== undefined ? update.status : this.status,
  957. statusText: update.statusText || this.statusText,
  958. url: update.url || this.url || undefined,
  959. });
  960. }
  961. }
  962. /**
  963. * A full HTTP response, including a typed response body (which may be `null`
  964. * if one was not returned).
  965. *
  966. * `HttpResponse` is a `HttpEvent` available on the response event
  967. * stream.
  968. *
  969. * \@stable
  970. * @template T
  971. */
  972. class HttpResponse extends HttpResponseBase {
  973. /**
  974. * Construct a new `HttpResponse`.
  975. * @param {?=} init
  976. */
  977. constructor(init = {}) {
  978. super(init);
  979. this.type = HttpEventType.Response;
  980. this.body = init.body !== undefined ? init.body : null;
  981. }
  982. /**
  983. * @param {?=} update
  984. * @return {?}
  985. */
  986. clone(update = {}) {
  987. return new HttpResponse({
  988. body: (update.body !== undefined) ? update.body : this.body,
  989. headers: update.headers || this.headers,
  990. status: (update.status !== undefined) ? update.status : this.status,
  991. statusText: update.statusText || this.statusText,
  992. url: update.url || this.url || undefined,
  993. });
  994. }
  995. }
  996. /**
  997. * A response that represents an error or failure, either from a
  998. * non-successful HTTP status, an error while executing the request,
  999. * or some other failure which occurred during the parsing of the response.
  1000. *
  1001. * Any error returned on the `Observable` response stream will be
  1002. * wrapped in an `HttpErrorResponse` to provide additional context about
  1003. * the state of the HTTP layer when the error occurred. The error property
  1004. * will contain either a wrapped Error object or the error response returned
  1005. * from the server.
  1006. *
  1007. * \@stable
  1008. */
  1009. class HttpErrorResponse extends HttpResponseBase {
  1010. /**
  1011. * @param {?} init
  1012. */
  1013. constructor(init) {
  1014. // Initialize with a default status of 0 / Unknown Error.
  1015. super(init, 0, 'Unknown Error');
  1016. this.name = 'HttpErrorResponse';
  1017. /**
  1018. * Errors are never okay, even when the status code is in the 2xx success range.
  1019. */
  1020. this.ok = false;
  1021. // If the response was successful, then this was a parse error. Otherwise, it was
  1022. // a protocol-level failure of some sort. Either the request failed in transit
  1023. // or the server returned an unsuccessful status code.
  1024. if (this.status >= 200 && this.status < 300) {
  1025. this.message = `Http failure during parsing for ${init.url || '(unknown url)'}`;
  1026. }
  1027. else {
  1028. this.message =
  1029. `Http failure response for ${init.url || '(unknown url)'}: ${init.status} ${init.statusText}`;
  1030. }
  1031. this.error = init.error || null;
  1032. }
  1033. }
  1034. /**
  1035. * @fileoverview added by tsickle
  1036. * @suppress {checkTypes} checked by tsc
  1037. */
  1038. /**
  1039. * @license
  1040. * Copyright Google Inc. All Rights Reserved.
  1041. *
  1042. * Use of this source code is governed by an MIT-style license that can be
  1043. * found in the LICENSE file at https://angular.io/license
  1044. */
  1045. /**
  1046. * Construct an instance of `HttpRequestOptions<T>` from a source `HttpMethodOptions` and
  1047. * the given `body`. Basically, this clones the object and adds the body.
  1048. * @template T
  1049. * @param {?} options
  1050. * @param {?} body
  1051. * @return {?}
  1052. */
  1053. function addBody(options, body) {
  1054. return {
  1055. body,
  1056. headers: options.headers,
  1057. observe: options.observe,
  1058. params: options.params,
  1059. reportProgress: options.reportProgress,
  1060. responseType: options.responseType,
  1061. withCredentials: options.withCredentials,
  1062. };
  1063. }
  1064. /**
  1065. * Perform HTTP requests.
  1066. *
  1067. * `HttpClient` is available as an injectable class, with methods to perform HTTP requests.
  1068. * Each request method has multiple signatures, and the return type varies according to which
  1069. * signature is called (mainly the values of `observe` and `responseType`).
  1070. *
  1071. * \@stable
  1072. */
  1073. class HttpClient {
  1074. /**
  1075. * @param {?} handler
  1076. */
  1077. constructor(handler) {
  1078. this.handler = handler;
  1079. }
  1080. /**
  1081. * Constructs an `Observable` for a particular HTTP request that, when subscribed,
  1082. * fires the request through the chain of registered interceptors and on to the
  1083. * server.
  1084. *
  1085. * This method can be called in one of two ways. Either an `HttpRequest`
  1086. * instance can be passed directly as the only parameter, or a method can be
  1087. * passed as the first parameter, a string URL as the second, and an
  1088. * options hash as the third.
  1089. *
  1090. * If a `HttpRequest` object is passed directly, an `Observable` of the
  1091. * raw `HttpEvent` stream will be returned.
  1092. *
  1093. * If a request is instead built by providing a URL, the options object
  1094. * determines the return type of `request()`. In addition to configuring
  1095. * request parameters such as the outgoing headers and/or the body, the options
  1096. * hash specifies two key pieces of information about the request: the
  1097. * `responseType` and what to `observe`.
  1098. *
  1099. * The `responseType` value determines how a successful response body will be
  1100. * parsed. If `responseType` is the default `json`, a type interface for the
  1101. * resulting object may be passed as a type parameter to `request()`.
  1102. *
  1103. * The `observe` value determines the return type of `request()`, based on what
  1104. * the consumer is interested in observing. A value of `events` will return an
  1105. * `Observable<HttpEvent>` representing the raw `HttpEvent` stream,
  1106. * including progress events by default. A value of `response` will return an
  1107. * `Observable<HttpResponse<T>>` where the `T` parameter of `HttpResponse`
  1108. * depends on the `responseType` and any optionally provided type parameter.
  1109. * A value of `body` will return an `Observable<T>` with the same `T` body type.
  1110. * @param {?} first
  1111. * @param {?=} url
  1112. * @param {?=} options
  1113. * @return {?}
  1114. */
  1115. request(first, url, options = {}) {
  1116. let /** @type {?} */ req;
  1117. // Firstly, check whether the primary argument is an instance of `HttpRequest`.
  1118. if (first instanceof HttpRequest) {
  1119. // It is. The other arguments must be undefined (per the signatures) and can be
  1120. // ignored.
  1121. req = /** @type {?} */ (first);
  1122. }
  1123. else {
  1124. // It's a string, so it represents a URL. Construct a request based on it,
  1125. // and incorporate the remaining arguments (assuming GET unless a method is
  1126. // provided.
  1127. // Figure out the headers.
  1128. let /** @type {?} */ headers = undefined;
  1129. if (options.headers instanceof HttpHeaders) {
  1130. headers = options.headers;
  1131. }
  1132. else {
  1133. headers = new HttpHeaders(options.headers);
  1134. }
  1135. // Sort out parameters.
  1136. let /** @type {?} */ params = undefined;
  1137. if (!!options.params) {
  1138. if (options.params instanceof HttpParams) {
  1139. params = options.params;
  1140. }
  1141. else {
  1142. params = new HttpParams({ fromObject: options.params });
  1143. }
  1144. }
  1145. // Construct the request.
  1146. req = new HttpRequest(first, /** @type {?} */ ((url)), (options.body !== undefined ? options.body : null), {
  1147. headers,
  1148. params,
  1149. reportProgress: options.reportProgress,
  1150. // By default, JSON is assumed to be returned for all calls.
  1151. responseType: options.responseType || 'json',
  1152. withCredentials: options.withCredentials,
  1153. });
  1154. }
  1155. // Start with an Observable.of() the initial request, and run the handler (which
  1156. // includes all interceptors) inside a concatMap(). This way, the handler runs
  1157. // inside an Observable chain, which causes interceptors to be re-run on every
  1158. // subscription (this also makes retries re-run the handler, including interceptors).
  1159. const /** @type {?} */ events$ = concatMap.call(of(req), (req) => this.handler.handle(req));
  1160. // If coming via the API signature which accepts a previously constructed HttpRequest,
  1161. // the only option is to get the event stream. Otherwise, return the event stream if
  1162. // that is what was requested.
  1163. if (first instanceof HttpRequest || options.observe === 'events') {
  1164. return events$;
  1165. }
  1166. // The requested stream contains either the full response or the body. In either
  1167. // case, the first step is to filter the event stream to extract a stream of
  1168. // responses(s).
  1169. const /** @type {?} */ res$ = filter.call(events$, (event) => event instanceof HttpResponse);
  1170. // Decide which stream to return.
  1171. switch (options.observe || 'body') {
  1172. case 'body':
  1173. // The requested stream is the body. Map the response stream to the response
  1174. // body. This could be done more simply, but a misbehaving interceptor might
  1175. // transform the response body into a different format and ignore the requested
  1176. // responseType. Guard against this by validating that the response is of the
  1177. // requested type.
  1178. switch (req.responseType) {
  1179. case 'arraybuffer':
  1180. return map.call(res$, (res) => {
  1181. // Validate that the body is an ArrayBuffer.
  1182. if (res.body !== null && !(res.body instanceof ArrayBuffer)) {
  1183. throw new Error('Response is not an ArrayBuffer.');
  1184. }
  1185. return res.body;
  1186. });
  1187. case 'blob':
  1188. return map.call(res$, (res) => {
  1189. // Validate that the body is a Blob.
  1190. if (res.body !== null && !(res.body instanceof Blob)) {
  1191. throw new Error('Response is not a Blob.');
  1192. }
  1193. return res.body;
  1194. });
  1195. case 'text':
  1196. return map.call(res$, (res) => {
  1197. // Validate that the body is a string.
  1198. if (res.body !== null && typeof res.body !== 'string') {
  1199. throw new Error('Response is not a string.');
  1200. }
  1201. return res.body;
  1202. });
  1203. case 'json':
  1204. default:
  1205. // No validation needed for JSON responses, as they can be of any type.
  1206. return map.call(res$, (res) => res.body);
  1207. }
  1208. case 'response':
  1209. // The response stream was requested directly, so return it.
  1210. return res$;
  1211. default:
  1212. // Guard against new future observe types being added.
  1213. throw new Error(`Unreachable: unhandled observe type ${options.observe}}`);
  1214. }
  1215. }
  1216. /**
  1217. * Constructs an `Observable` which, when subscribed, will cause the configured
  1218. * DELETE request to be executed on the server. See the individual overloads for
  1219. * details of `delete()`'s return type based on the provided options.
  1220. * @param {?} url
  1221. * @param {?=} options
  1222. * @return {?}
  1223. */
  1224. delete(url, options = {}) {
  1225. return this.request('DELETE', url, /** @type {?} */ (options));
  1226. }
  1227. /**
  1228. * Constructs an `Observable` which, when subscribed, will cause the configured
  1229. * GET request to be executed on the server. See the individual overloads for
  1230. * details of `get()`'s return type based on the provided options.
  1231. * @param {?} url
  1232. * @param {?=} options
  1233. * @return {?}
  1234. */
  1235. get(url, options = {}) {
  1236. return this.request('GET', url, /** @type {?} */ (options));
  1237. }
  1238. /**
  1239. * Constructs an `Observable` which, when subscribed, will cause the configured
  1240. * HEAD request to be executed on the server. See the individual overloads for
  1241. * details of `head()`'s return type based on the provided options.
  1242. * @param {?} url
  1243. * @param {?=} options
  1244. * @return {?}
  1245. */
  1246. head(url, options = {}) {
  1247. return this.request('HEAD', url, /** @type {?} */ (options));
  1248. }
  1249. /**
  1250. * Constructs an `Observable` which, when subscribed, will cause a request
  1251. * with the special method `JSONP` to be dispatched via the interceptor pipeline.
  1252. *
  1253. * A suitable interceptor must be installed (e.g. via the `HttpClientJsonpModule`).
  1254. * If no such interceptor is reached, then the `JSONP` request will likely be
  1255. * rejected by the configured backend.
  1256. * @template T
  1257. * @param {?} url
  1258. * @param {?} callbackParam
  1259. * @return {?}
  1260. */
  1261. jsonp(url, callbackParam) {
  1262. return this.request('JSONP', url, {
  1263. params: new HttpParams().append(callbackParam, 'JSONP_CALLBACK'),
  1264. observe: 'body',
  1265. responseType: 'json',
  1266. });
  1267. }
  1268. /**
  1269. * Constructs an `Observable` which, when subscribed, will cause the configured
  1270. * OPTIONS request to be executed on the server. See the individual overloads for
  1271. * details of `options()`'s return type based on the provided options.
  1272. * @param {?} url
  1273. * @param {?=} options
  1274. * @return {?}
  1275. */
  1276. options(url, options = {}) {
  1277. return this.request('OPTIONS', url, /** @type {?} */ (options));
  1278. }
  1279. /**
  1280. * Constructs an `Observable` which, when subscribed, will cause the configured
  1281. * PATCH request to be executed on the server. See the individual overloads for
  1282. * details of `patch()`'s return type based on the provided options.
  1283. * @param {?} url
  1284. * @param {?} body
  1285. * @param {?=} options
  1286. * @return {?}
  1287. */
  1288. patch(url, body, options = {}) {
  1289. return this.request('PATCH', url, addBody(options, body));
  1290. }
  1291. /**
  1292. * Constructs an `Observable` which, when subscribed, will cause the configured
  1293. * POST request to be executed on the server. See the individual overloads for
  1294. * details of `post()`'s return type based on the provided options.
  1295. * @param {?} url
  1296. * @param {?} body
  1297. * @param {?=} options
  1298. * @return {?}
  1299. */
  1300. post(url, body, options = {}) {
  1301. return this.request('POST', url, addBody(options, body));
  1302. }
  1303. /**
  1304. * Constructs an `Observable` which, when subscribed, will cause the configured
  1305. * POST request to be executed on the server. See the individual overloads for
  1306. * details of `post()`'s return type based on the provided options.
  1307. * @param {?} url
  1308. * @param {?} body
  1309. * @param {?=} options
  1310. * @return {?}
  1311. */
  1312. put(url, body, options = {}) {
  1313. return this.request('PUT', url, addBody(options, body));
  1314. }
  1315. }
  1316. HttpClient.decorators = [
  1317. { type: Injectable },
  1318. ];
  1319. /** @nocollapse */
  1320. HttpClient.ctorParameters = () => [
  1321. { type: HttpHandler, },
  1322. ];
  1323. /**
  1324. * @fileoverview added by tsickle
  1325. * @suppress {checkTypes} checked by tsc
  1326. */
  1327. /**
  1328. * @license
  1329. * Copyright Google Inc. All Rights Reserved.
  1330. *
  1331. * Use of this source code is governed by an MIT-style license that can be
  1332. * found in the LICENSE file at https://angular.io/license
  1333. */
  1334. /**
  1335. * Intercepts `HttpRequest` and handles them.
  1336. *
  1337. * Most interceptors will transform the outgoing request before passing it to the
  1338. * next interceptor in the chain, by calling `next.handle(transformedReq)`.
  1339. *
  1340. * In rare cases, interceptors may wish to completely handle a request themselves,
  1341. * and not delegate to the remainder of the chain. This behavior is allowed.
  1342. *
  1343. * \@stable
  1344. * @record
  1345. */
  1346. /**
  1347. * `HttpHandler` which applies an `HttpInterceptor` to an `HttpRequest`.
  1348. *
  1349. * \@stable
  1350. */
  1351. class HttpInterceptorHandler {
  1352. /**
  1353. * @param {?} next
  1354. * @param {?} interceptor
  1355. */
  1356. constructor(next, interceptor) {
  1357. this.next = next;
  1358. this.interceptor = interceptor;
  1359. }
  1360. /**
  1361. * @param {?} req
  1362. * @return {?}
  1363. */
  1364. handle(req) {
  1365. return this.interceptor.intercept(req, this.next);
  1366. }
  1367. }
  1368. /**
  1369. * A multi-provider token which represents the array of `HttpInterceptor`s that
  1370. * are registered.
  1371. *
  1372. * \@stable
  1373. */
  1374. const HTTP_INTERCEPTORS = new InjectionToken('HTTP_INTERCEPTORS');
  1375. class NoopInterceptor {
  1376. /**
  1377. * @param {?} req
  1378. * @param {?} next
  1379. * @return {?}
  1380. */
  1381. intercept(req, next) {
  1382. return next.handle(req);
  1383. }
  1384. }
  1385. NoopInterceptor.decorators = [
  1386. { type: Injectable },
  1387. ];
  1388. /** @nocollapse */
  1389. NoopInterceptor.ctorParameters = () => [];
  1390. /**
  1391. * @fileoverview added by tsickle
  1392. * @suppress {checkTypes} checked by tsc
  1393. */
  1394. /**
  1395. * @license
  1396. * Copyright Google Inc. All Rights Reserved.
  1397. *
  1398. * Use of this source code is governed by an MIT-style license that can be
  1399. * found in the LICENSE file at https://angular.io/license
  1400. */
  1401. // Every request made through JSONP needs a callback name that's unique across the
  1402. // whole page. Each request is assigned an id and the callback name is constructed
  1403. // from that. The next id to be assigned is tracked in a global variable here that
  1404. // is shared among all applications on the page.
  1405. let nextRequestId = 0;
  1406. // Error text given when a JSONP script is injected, but doesn't invoke the callback
  1407. // passed in its URL.
  1408. const JSONP_ERR_NO_CALLBACK = 'JSONP injected script did not invoke callback.';
  1409. // Error text given when a request is passed to the JsonpClientBackend that doesn't
  1410. // have a request method JSONP.
  1411. const JSONP_ERR_WRONG_METHOD = 'JSONP requests must use JSONP request method.';
  1412. const JSONP_ERR_WRONG_RESPONSE_TYPE = 'JSONP requests must use Json response type.';
  1413. /**
  1414. * DI token/abstract type representing a map of JSONP callbacks.
  1415. *
  1416. * In the browser, this should always be the `window` object.
  1417. *
  1418. * \@stable
  1419. * @abstract
  1420. */
  1421. class JsonpCallbackContext {
  1422. }
  1423. /**
  1424. * `HttpBackend` that only processes `HttpRequest` with the JSONP method,
  1425. * by performing JSONP style requests.
  1426. *
  1427. * \@stable
  1428. */
  1429. class JsonpClientBackend {
  1430. /**
  1431. * @param {?} callbackMap
  1432. * @param {?} document
  1433. */
  1434. constructor(callbackMap, document) {
  1435. this.callbackMap = callbackMap;
  1436. this.document = document;
  1437. }
  1438. /**
  1439. * Get the name of the next callback method, by incrementing the global `nextRequestId`.
  1440. * @return {?}
  1441. */
  1442. nextCallback() { return `ng_jsonp_callback_${nextRequestId++}`; }
  1443. /**
  1444. * Process a JSONP request and return an event stream of the results.
  1445. * @param {?} req
  1446. * @return {?}
  1447. */
  1448. handle(req) {
  1449. // Firstly, check both the method and response type. If either doesn't match
  1450. // then the request was improperly routed here and cannot be handled.
  1451. if (req.method !== 'JSONP') {
  1452. throw new Error(JSONP_ERR_WRONG_METHOD);
  1453. }
  1454. else if (req.responseType !== 'json') {
  1455. throw new Error(JSONP_ERR_WRONG_RESPONSE_TYPE);
  1456. }
  1457. // Everything else happens inside the Observable boundary.
  1458. return new Observable((observer) => {
  1459. // The first step to make a request is to generate the callback name, and replace the
  1460. // callback placeholder in the URL with the name. Care has to be taken here to ensure
  1461. // a trailing &, if matched, gets inserted back into the URL in the correct place.
  1462. const /** @type {?} */ callback = this.nextCallback();
  1463. const /** @type {?} */ url = req.urlWithParams.replace(/=JSONP_CALLBACK(&|$)/, `=${callback}$1`);
  1464. // Construct the <script> tag and point it at the URL.
  1465. const /** @type {?} */ node = this.document.createElement('script');
  1466. node.src = url;
  1467. // A JSONP request requires waiting for multiple callbacks. These variables
  1468. // are closed over and track state across those callbacks.
  1469. // The response object, if one has been received, or null otherwise.
  1470. let /** @type {?} */ body = null;
  1471. // Whether the response callback has been called.
  1472. let /** @type {?} */ finished = false;
  1473. // Whether the request has been cancelled (and thus any other callbacks)
  1474. // should be ignored.
  1475. let /** @type {?} */ cancelled = false;
  1476. // Set the response callback in this.callbackMap (which will be the window
  1477. // object in the browser. The script being loaded via the <script> tag will
  1478. // eventually call this callback.
  1479. this.callbackMap[callback] = (data) => {
  1480. // Data has been received from the JSONP script. Firstly, delete this callback.
  1481. delete this.callbackMap[callback];
  1482. // Next, make sure the request wasn't cancelled in the meantime.
  1483. if (cancelled) {
  1484. return;
  1485. }
  1486. // Set state to indicate data was received.
  1487. body = data;
  1488. finished = true;
  1489. };
  1490. // cleanup() is a utility closure that removes the <script> from the page and
  1491. // the response callback from the window. This logic is used in both the
  1492. // success, error, and cancellation paths, so it's extracted out for convenience.
  1493. const /** @type {?} */ cleanup = () => {
  1494. // Remove the <script> tag if it's still on the page.
  1495. if (node.parentNode) {
  1496. node.parentNode.removeChild(node);
  1497. }
  1498. // Remove the response callback from the callbackMap (window object in the
  1499. // browser).
  1500. delete this.callbackMap[callback];
  1501. };
  1502. // onLoad() is the success callback which runs after the response callback
  1503. // if the JSONP script loads successfully. The event itself is unimportant.
  1504. // If something went wrong, onLoad() may run without the response callback
  1505. // having been invoked.
  1506. const /** @type {?} */ onLoad = (event) => {
  1507. // Do nothing if the request has been cancelled.
  1508. if (cancelled) {
  1509. return;
  1510. }
  1511. // Cleanup the page.
  1512. cleanup();
  1513. // Check whether the response callback has run.
  1514. if (!finished) {
  1515. // It hasn't, something went wrong with the request. Return an error via
  1516. // the Observable error path. All JSONP errors have status 0.
  1517. observer.error(new HttpErrorResponse({
  1518. url,
  1519. status: 0,
  1520. statusText: 'JSONP Error',
  1521. error: new Error(JSONP_ERR_NO_CALLBACK),
  1522. }));
  1523. return;
  1524. }
  1525. // Success. body either contains the response body or null if none was
  1526. // returned.
  1527. observer.next(new HttpResponse({
  1528. body,
  1529. status: 200,
  1530. statusText: 'OK', url,
  1531. }));
  1532. // Complete the stream, the response is over.
  1533. observer.complete();
  1534. };
  1535. // onError() is the error callback, which runs if the script returned generates
  1536. // a Javascript error. It emits the error via the Observable error channel as
  1537. // a HttpErrorResponse.
  1538. const /** @type {?} */ onError = (error) => {
  1539. // If the request was already cancelled, no need to emit anything.
  1540. if (cancelled) {
  1541. return;
  1542. }
  1543. cleanup();
  1544. // Wrap the error in a HttpErrorResponse.
  1545. observer.error(new HttpErrorResponse({
  1546. error,
  1547. status: 0,
  1548. statusText: 'JSONP Error', url,
  1549. }));
  1550. };
  1551. // Subscribe to both the success (load) and error events on the <script> tag,
  1552. // and add it to the page.
  1553. node.addEventListener('load', onLoad);
  1554. node.addEventListener('error', onError);
  1555. this.document.body.appendChild(node);
  1556. // The request has now been successfully sent.
  1557. observer.next({ type: HttpEventType.Sent });
  1558. // Cancellation handler.
  1559. return () => {
  1560. // Track the cancellation so event listeners won't do anything even if already scheduled.
  1561. cancelled = true;
  1562. // Remove the event listeners so they won't run if the events later fire.
  1563. node.removeEventListener('load', onLoad);
  1564. node.removeEventListener('error', onError);
  1565. // And finally, clean up the page.
  1566. cleanup();
  1567. };
  1568. });
  1569. }
  1570. }
  1571. JsonpClientBackend.decorators = [
  1572. { type: Injectable },
  1573. ];
  1574. /** @nocollapse */
  1575. JsonpClientBackend.ctorParameters = () => [
  1576. { type: JsonpCallbackContext, },
  1577. { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] },] },
  1578. ];
  1579. /**
  1580. * An `HttpInterceptor` which identifies requests with the method JSONP and
  1581. * shifts them to the `JsonpClientBackend`.
  1582. *
  1583. * \@stable
  1584. */
  1585. class JsonpInterceptor {
  1586. /**
  1587. * @param {?} jsonp
  1588. */
  1589. constructor(jsonp) {
  1590. this.jsonp = jsonp;
  1591. }
  1592. /**
  1593. * @param {?} req
  1594. * @param {?} next
  1595. * @return {?}
  1596. */
  1597. intercept(req, next) {
  1598. if (req.method === 'JSONP') {
  1599. return this.jsonp.handle(/** @type {?} */ (req));
  1600. }
  1601. // Fall through for normal HTTP requests.
  1602. return next.handle(req);
  1603. }
  1604. }
  1605. JsonpInterceptor.decorators = [
  1606. { type: Injectable },
  1607. ];
  1608. /** @nocollapse */
  1609. JsonpInterceptor.ctorParameters = () => [
  1610. { type: JsonpClientBackend, },
  1611. ];
  1612. /**
  1613. * @fileoverview added by tsickle
  1614. * @suppress {checkTypes} checked by tsc
  1615. */
  1616. /**
  1617. * @license
  1618. * Copyright Google Inc. All Rights Reserved.
  1619. *
  1620. * Use of this source code is governed by an MIT-style license that can be
  1621. * found in the LICENSE file at https://angular.io/license
  1622. */
  1623. const XSSI_PREFIX = /^\)\]\}',?\n/;
  1624. /**
  1625. * Determine an appropriate URL for the response, by checking either
  1626. * XMLHttpRequest.responseURL or the X-Request-URL header.
  1627. * @param {?} xhr
  1628. * @return {?}
  1629. */
  1630. function getResponseUrl(xhr) {
  1631. if ('responseURL' in xhr && xhr.responseURL) {
  1632. return xhr.responseURL;
  1633. }
  1634. if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
  1635. return xhr.getResponseHeader('X-Request-URL');
  1636. }
  1637. return null;
  1638. }
  1639. /**
  1640. * A wrapper around the `XMLHttpRequest` constructor.
  1641. *
  1642. * \@stable
  1643. * @abstract
  1644. */
  1645. class XhrFactory {
  1646. }
  1647. /**
  1648. * A factory for \@{link HttpXhrBackend} that uses the `XMLHttpRequest` browser API.
  1649. *
  1650. * \@stable
  1651. */
  1652. class BrowserXhr {
  1653. constructor() { }
  1654. /**
  1655. * @return {?}
  1656. */
  1657. build() { return /** @type {?} */ ((new XMLHttpRequest())); }
  1658. }
  1659. BrowserXhr.decorators = [
  1660. { type: Injectable },
  1661. ];
  1662. /** @nocollapse */
  1663. BrowserXhr.ctorParameters = () => [];
  1664. /**
  1665. * An `HttpBackend` which uses the XMLHttpRequest API to send
  1666. * requests to a backend server.
  1667. *
  1668. * \@stable
  1669. */
  1670. class HttpXhrBackend {
  1671. /**
  1672. * @param {?} xhrFactory
  1673. */
  1674. constructor(xhrFactory) {
  1675. this.xhrFactory = xhrFactory;
  1676. }
  1677. /**
  1678. * Process a request and return a stream of response events.
  1679. * @param {?} req
  1680. * @return {?}
  1681. */
  1682. handle(req) {
  1683. // Quick check to give a better error message when a user attempts to use
  1684. // HttpClient.jsonp() without installing the JsonpClientModule
  1685. if (req.method === 'JSONP') {
  1686. throw new Error(`Attempted to construct Jsonp request without JsonpClientModule installed.`);
  1687. }
  1688. // Everything happens on Observable subscription.
  1689. return new Observable((observer) => {
  1690. // Start by setting up the XHR object with request method, URL, and withCredentials flag.
  1691. const /** @type {?} */ xhr = this.xhrFactory.build();
  1692. xhr.open(req.method, req.urlWithParams);
  1693. if (!!req.withCredentials) {
  1694. xhr.withCredentials = true;
  1695. }
  1696. // Add all the requested headers.
  1697. req.headers.forEach((name, values) => xhr.setRequestHeader(name, values.join(',')));
  1698. // Add an Accept header if one isn't present already.
  1699. if (!req.headers.has('Accept')) {
  1700. xhr.setRequestHeader('Accept', 'application/json, text/plain, */*');
  1701. }
  1702. // Auto-detect the Content-Type header if one isn't present already.
  1703. if (!req.headers.has('Content-Type')) {
  1704. const /** @type {?} */ detectedType = req.detectContentTypeHeader();
  1705. // Sometimes Content-Type detection fails.
  1706. if (detectedType !== null) {
  1707. xhr.setRequestHeader('Content-Type', detectedType);
  1708. }
  1709. }
  1710. // Set the responseType if one was requested.
  1711. if (req.responseType) {
  1712. const /** @type {?} */ responseType = req.responseType.toLowerCase();
  1713. // JSON responses need to be processed as text. This is because if the server
  1714. // returns an XSSI-prefixed JSON response, the browser will fail to parse it,
  1715. // xhr.response will be null, and xhr.responseText cannot be accessed to
  1716. // retrieve the prefixed JSON data in order to strip the prefix. Thus, all JSON
  1717. // is parsed by first requesting text and then applying JSON.parse.
  1718. xhr.responseType = /** @type {?} */ (((responseType !== 'json') ? responseType : 'text'));
  1719. }
  1720. // Serialize the request body if one is present. If not, this will be set to null.
  1721. const /** @type {?} */ reqBody = req.serializeBody();
  1722. // If progress events are enabled, response headers will be delivered
  1723. // in two events - the HttpHeaderResponse event and the full HttpResponse
  1724. // event. However, since response headers don't change in between these
  1725. // two events, it doesn't make sense to parse them twice. So headerResponse
  1726. // caches the data extracted from the response whenever it's first parsed,
  1727. // to ensure parsing isn't duplicated.
  1728. let /** @type {?} */ headerResponse = null;
  1729. // partialFromXhr extracts the HttpHeaderResponse from the current XMLHttpRequest
  1730. // state, and memoizes it into headerResponse.
  1731. const /** @type {?} */ partialFromXhr = () => {
  1732. if (headerResponse !== null) {
  1733. return headerResponse;
  1734. }
  1735. // Read status and normalize an IE9 bug (http://bugs.jquery.com/ticket/1450).
  1736. const /** @type {?} */ status = xhr.status === 1223 ? 204 : xhr.status;
  1737. const /** @type {?} */ statusText = xhr.statusText || 'OK';
  1738. // Parse headers from XMLHttpRequest - this step is lazy.
  1739. const /** @type {?} */ headers = new HttpHeaders(xhr.getAllResponseHeaders());
  1740. // Read the response URL from the XMLHttpResponse instance and fall back on the
  1741. // request URL.
  1742. const /** @type {?} */ url = getResponseUrl(xhr) || req.url;
  1743. // Construct the HttpHeaderResponse and memoize it.
  1744. headerResponse = new HttpHeaderResponse({ headers, status, statusText, url });
  1745. return headerResponse;
  1746. };
  1747. // Next, a few closures are defined for the various events which XMLHttpRequest can
  1748. // emit. This allows them to be unregistered as event listeners later.
  1749. // First up is the load event, which represents a response being fully available.
  1750. const /** @type {?} */ onLoad = () => {
  1751. // Read response state from the memoized partial data.
  1752. let { headers, status, statusText, url } = partialFromXhr();
  1753. // The body will be read out if present.
  1754. let /** @type {?} */ body = null;
  1755. if (status !== 204) {
  1756. // Use XMLHttpRequest.response if set, responseText otherwise.
  1757. body = (typeof xhr.response === 'undefined') ? xhr.responseText : xhr.response;
  1758. }
  1759. // Normalize another potential bug (this one comes from CORS).
  1760. if (status === 0) {
  1761. status = !!body ? 200 : 0;
  1762. }
  1763. // ok determines whether the response will be transmitted on the event or
  1764. // error channel. Unsuccessful status codes (not 2xx) will always be errors,
  1765. // but a successful status code can still result in an error if the user
  1766. // asked for JSON data and the body cannot be parsed as such.
  1767. let /** @type {?} */ ok = status >= 200 && status < 300;
  1768. // Check whether the body needs to be parsed as JSON (in many cases the browser
  1769. // will have done that already).
  1770. if (req.responseType === 'json' && typeof body === 'string') {
  1771. // Save the original body, before attempting XSSI prefix stripping.
  1772. const /** @type {?} */ originalBody = body;
  1773. body = body.replace(XSSI_PREFIX, '');
  1774. try {
  1775. // Attempt the parse. If it fails, a parse error should be delivered to the user.
  1776. body = body !== '' ? JSON.parse(body) : null;
  1777. }
  1778. catch (/** @type {?} */ error) {
  1779. // Since the JSON.parse failed, it's reasonable to assume this might not have been a
  1780. // JSON response. Restore the original body (including any XSSI prefix) to deliver
  1781. // a better error response.
  1782. body = originalBody;
  1783. // If this was an error request to begin with, leave it as a string, it probably
  1784. // just isn't JSON. Otherwise, deliver the parsing error to the user.
  1785. if (ok) {
  1786. // Even though the response status was 2xx, this is still an error.
  1787. ok = false;
  1788. // The parse error contains the text of the body that failed to parse.
  1789. body = /** @type {?} */ ({ error, text: body });
  1790. }
  1791. }
  1792. }
  1793. if (ok) {
  1794. // A successful response is delivered on the event stream.
  1795. observer.next(new HttpResponse({
  1796. body,
  1797. headers,
  1798. status,
  1799. statusText,
  1800. url: url || undefined,
  1801. }));
  1802. // The full body has been received and delivered, no further events
  1803. // are possible. This request is complete.
  1804. observer.complete();
  1805. }
  1806. else {
  1807. // An unsuccessful request is delivered on the error channel.
  1808. observer.error(new HttpErrorResponse({
  1809. // The error in this case is the response body (error from the server).
  1810. error: body,
  1811. headers,
  1812. status,
  1813. statusText,
  1814. url: url || undefined,
  1815. }));
  1816. }
  1817. };
  1818. // The onError callback is called when something goes wrong at the network level.
  1819. // Connection timeout, DNS error, offline, etc. These are actual errors, and are
  1820. // transmitted on the error channel.
  1821. const /** @type {?} */ onError = (error) => {
  1822. const /** @type {?} */ res = new HttpErrorResponse({
  1823. error,
  1824. status: xhr.status || 0,
  1825. statusText: xhr.statusText || 'Unknown Error',
  1826. });
  1827. observer.error(res);
  1828. };
  1829. // The sentHeaders flag tracks whether the HttpResponseHeaders event
  1830. // has been sent on the stream. This is necessary to track if progress
  1831. // is enabled since the event will be sent on only the first download
  1832. // progerss event.
  1833. let /** @type {?} */ sentHeaders = false;
  1834. // The download progress event handler, which is only registered if
  1835. // progress events are enabled.
  1836. const /** @type {?} */ onDownProgress = (event) => {
  1837. // Send the HttpResponseHeaders event if it hasn't been sent already.
  1838. if (!sentHeaders) {
  1839. observer.next(partialFromXhr());
  1840. sentHeaders = true;
  1841. }
  1842. // Start building the download progress event to deliver on the response
  1843. // event stream.
  1844. let /** @type {?} */ progressEvent = {
  1845. type: HttpEventType.DownloadProgress,
  1846. loaded: event.loaded,
  1847. };
  1848. // Set the total number of bytes in the event if it's available.
  1849. if (event.lengthComputable) {
  1850. progressEvent.total = event.total;
  1851. }
  1852. // If the request was for text content and a partial response is
  1853. // available on XMLHttpRequest, include it in the progress event
  1854. // to allow for streaming reads.
  1855. if (req.responseType === 'text' && !!xhr.responseText) {
  1856. progressEvent.partialText = xhr.responseText;
  1857. }
  1858. // Finally, fire the event.
  1859. observer.next(progressEvent);
  1860. };
  1861. // The upload progress event handler, which is only registered if
  1862. // progress events are enabled.
  1863. const /** @type {?} */ onUpProgress = (event) => {
  1864. // Upload progress events are simpler. Begin building the progress
  1865. // event.
  1866. let /** @type {?} */ progress = {
  1867. type: HttpEventType.UploadProgress,
  1868. loaded: event.loaded,
  1869. };
  1870. // If the total number of bytes being uploaded is available, include
  1871. // it.
  1872. if (event.lengthComputable) {
  1873. progress.total = event.total;
  1874. }
  1875. // Send the event.
  1876. observer.next(progress);
  1877. };
  1878. // By default, register for load and error events.
  1879. xhr.addEventListener('load', onLoad);
  1880. xhr.addEventListener('error', onError);
  1881. // Progress events are only enabled if requested.
  1882. if (req.reportProgress) {
  1883. // Download progress is always enabled if requested.
  1884. xhr.addEventListener('progress', onDownProgress);
  1885. // Upload progress depends on whether there is a body to upload.
  1886. if (reqBody !== null && xhr.upload) {
  1887. xhr.upload.addEventListener('progress', onUpProgress);
  1888. }
  1889. }
  1890. // Fire the request, and notify the event stream that it was fired.
  1891. xhr.send(reqBody);
  1892. observer.next({ type: HttpEventType.Sent });
  1893. // This is the return from the Observable function, which is the
  1894. // request cancellation handler.
  1895. return () => {
  1896. // On a cancellation, remove all registered event listeners.
  1897. xhr.removeEventListener('error', onError);
  1898. xhr.removeEventListener('load', onLoad);
  1899. if (req.reportProgress) {
  1900. xhr.removeEventListener('progress', onDownProgress);
  1901. if (reqBody !== null && xhr.upload) {
  1902. xhr.upload.removeEventListener('progress', onUpProgress);
  1903. }
  1904. }
  1905. // Finally, abort the in-flight request.
  1906. xhr.abort();
  1907. };
  1908. });
  1909. }
  1910. }
  1911. HttpXhrBackend.decorators = [
  1912. { type: Injectable },
  1913. ];
  1914. /** @nocollapse */
  1915. HttpXhrBackend.ctorParameters = () => [
  1916. { type: XhrFactory, },
  1917. ];
  1918. /**
  1919. * @fileoverview added by tsickle
  1920. * @suppress {checkTypes} checked by tsc
  1921. */
  1922. /**
  1923. * @license
  1924. * Copyright Google Inc. All Rights Reserved.
  1925. *
  1926. * Use of this source code is governed by an MIT-style license that can be
  1927. * found in the LICENSE file at https://angular.io/license
  1928. */
  1929. const XSRF_COOKIE_NAME = new InjectionToken('XSRF_COOKIE_NAME');
  1930. const XSRF_HEADER_NAME = new InjectionToken('XSRF_HEADER_NAME');
  1931. /**
  1932. * Retrieves the current XSRF token to use with the next outgoing request.
  1933. *
  1934. * \@stable
  1935. * @abstract
  1936. */
  1937. class HttpXsrfTokenExtractor {
  1938. }
  1939. /**
  1940. * `HttpXsrfTokenExtractor` which retrieves the token from a cookie.
  1941. */
  1942. class HttpXsrfCookieExtractor {
  1943. /**
  1944. * @param {?} doc
  1945. * @param {?} platform
  1946. * @param {?} cookieName
  1947. */
  1948. constructor(doc, platform, cookieName) {
  1949. this.doc = doc;
  1950. this.platform = platform;
  1951. this.cookieName = cookieName;
  1952. this.lastCookieString = '';
  1953. this.lastToken = null;
  1954. /**
  1955. * \@internal for testing
  1956. */
  1957. this.parseCount = 0;
  1958. }
  1959. /**
  1960. * @return {?}
  1961. */
  1962. getToken() {
  1963. if (this.platform === 'server') {
  1964. return null;
  1965. }
  1966. const /** @type {?} */ cookieString = this.doc.cookie || '';
  1967. if (cookieString !== this.lastCookieString) {
  1968. this.parseCount++;
  1969. this.lastToken = ɵparseCookieValue(cookieString, this.cookieName);
  1970. this.lastCookieString = cookieString;
  1971. }
  1972. return this.lastToken;
  1973. }
  1974. }
  1975. HttpXsrfCookieExtractor.decorators = [
  1976. { type: Injectable },
  1977. ];
  1978. /** @nocollapse */
  1979. HttpXsrfCookieExtractor.ctorParameters = () => [
  1980. { type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] },] },
  1981. { type: undefined, decorators: [{ type: Inject, args: [PLATFORM_ID,] },] },
  1982. { type: undefined, decorators: [{ type: Inject, args: [XSRF_COOKIE_NAME,] },] },
  1983. ];
  1984. /**
  1985. * `HttpInterceptor` which adds an XSRF token to eligible outgoing requests.
  1986. */
  1987. class HttpXsrfInterceptor {
  1988. /**
  1989. * @param {?} tokenService
  1990. * @param {?} headerName
  1991. */
  1992. constructor(tokenService, headerName) {
  1993. this.tokenService = tokenService;
  1994. this.headerName = headerName;
  1995. }
  1996. /**
  1997. * @param {?} req
  1998. * @param {?} next
  1999. * @return {?}
  2000. */
  2001. intercept(req, next) {
  2002. const /** @type {?} */ lcUrl = req.url.toLowerCase();
  2003. // Skip both non-mutating requests and absolute URLs.
  2004. // Non-mutating requests don't require a token, and absolute URLs require special handling
  2005. // anyway as the cookie set
  2006. // on our origin is not the same as the token expected by another origin.
  2007. if (req.method === 'GET' || req.method === 'HEAD' || lcUrl.startsWith('http://') ||
  2008. lcUrl.startsWith('https://')) {
  2009. return next.handle(req);
  2010. }
  2011. const /** @type {?} */ token = this.tokenService.getToken();
  2012. // Be careful not to overwrite an existing header of the same name.
  2013. if (token !== null && !req.headers.has(this.headerName)) {
  2014. req = req.clone({ headers: req.headers.set(this.headerName, token) });
  2015. }
  2016. return next.handle(req);
  2017. }
  2018. }
  2019. HttpXsrfInterceptor.decorators = [
  2020. { type: Injectable },
  2021. ];
  2022. /** @nocollapse */
  2023. HttpXsrfInterceptor.ctorParameters = () => [
  2024. { type: HttpXsrfTokenExtractor, },
  2025. { type: undefined, decorators: [{ type: Inject, args: [XSRF_HEADER_NAME,] },] },
  2026. ];
  2027. /**
  2028. * @fileoverview added by tsickle
  2029. * @suppress {checkTypes} checked by tsc
  2030. */
  2031. /**
  2032. * @license
  2033. * Copyright Google Inc. All Rights Reserved.
  2034. *
  2035. * Use of this source code is governed by an MIT-style license that can be
  2036. * found in the LICENSE file at https://angular.io/license
  2037. */
  2038. /**
  2039. * An `HttpHandler` that applies a bunch of `HttpInterceptor`s
  2040. * to a request before passing it to the given `HttpBackend`.
  2041. *
  2042. * The interceptors are loaded lazily from the injector, to allow
  2043. * interceptors to themselves inject classes depending indirectly
  2044. * on `HttpInterceptingHandler` itself.
  2045. */
  2046. class HttpInterceptingHandler {
  2047. /**
  2048. * @param {?} backend
  2049. * @param {?} injector
  2050. */
  2051. constructor(backend, injector) {
  2052. this.backend = backend;
  2053. this.injector = injector;
  2054. this.chain = null;
  2055. }
  2056. /**
  2057. * @param {?} req
  2058. * @return {?}
  2059. */
  2060. handle(req) {
  2061. if (this.chain === null) {
  2062. const /** @type {?} */ interceptors = this.injector.get(HTTP_INTERCEPTORS, []);
  2063. this.chain = interceptors.reduceRight((next, interceptor) => new HttpInterceptorHandler(next, interceptor), this.backend);
  2064. }
  2065. return this.chain.handle(req);
  2066. }
  2067. }
  2068. HttpInterceptingHandler.decorators = [
  2069. { type: Injectable },
  2070. ];
  2071. /** @nocollapse */
  2072. HttpInterceptingHandler.ctorParameters = () => [
  2073. { type: HttpBackend, },
  2074. { type: Injector, },
  2075. ];
  2076. /**
  2077. * Constructs an `HttpHandler` that applies a bunch of `HttpInterceptor`s
  2078. * to a request before passing it to the given `HttpBackend`.
  2079. *
  2080. * Meant to be used as a factory function within `HttpClientModule`.
  2081. *
  2082. * \@stable
  2083. * @param {?} backend
  2084. * @param {?=} interceptors
  2085. * @return {?}
  2086. */
  2087. function interceptingHandler(backend, interceptors = []) {
  2088. if (!interceptors) {
  2089. return backend;
  2090. }
  2091. return interceptors.reduceRight((next, interceptor) => new HttpInterceptorHandler(next, interceptor), backend);
  2092. }
  2093. /**
  2094. * Factory function that determines where to store JSONP callbacks.
  2095. *
  2096. * Ordinarily JSONP callbacks are stored on the `window` object, but this may not exist
  2097. * in test environments. In that case, callbacks are stored on an anonymous object instead.
  2098. *
  2099. * \@stable
  2100. * @return {?}
  2101. */
  2102. function jsonpCallbackContext() {
  2103. if (typeof window === 'object') {
  2104. return window;
  2105. }
  2106. return {};
  2107. }
  2108. /**
  2109. * `NgModule` which adds XSRF protection support to outgoing requests.
  2110. *
  2111. * Provided the server supports a cookie-based XSRF protection system, this
  2112. * module can be used directly to configure XSRF protection with the correct
  2113. * cookie and header names.
  2114. *
  2115. * If no such names are provided, the default is to use `X-XSRF-TOKEN` for
  2116. * the header name and `XSRF-TOKEN` for the cookie name.
  2117. *
  2118. * \@stable
  2119. */
  2120. class HttpClientXsrfModule {
  2121. /**
  2122. * Disable the default XSRF protection.
  2123. * @return {?}
  2124. */
  2125. static disable() {
  2126. return {
  2127. ngModule: HttpClientXsrfModule,
  2128. providers: [
  2129. { provide: HttpXsrfInterceptor, useClass: NoopInterceptor },
  2130. ],
  2131. };
  2132. }
  2133. /**
  2134. * Configure XSRF protection to use the given cookie name or header name,
  2135. * or the default names (as described above) if not provided.
  2136. * @param {?=} options
  2137. * @return {?}
  2138. */
  2139. static withOptions(options = {}) {
  2140. return {
  2141. ngModule: HttpClientXsrfModule,
  2142. providers: [
  2143. options.cookieName ? { provide: XSRF_COOKIE_NAME, useValue: options.cookieName } : [],
  2144. options.headerName ? { provide: XSRF_HEADER_NAME, useValue: options.headerName } : [],
  2145. ],
  2146. };
  2147. }
  2148. }
  2149. HttpClientXsrfModule.decorators = [
  2150. { type: NgModule, args: [{
  2151. providers: [
  2152. HttpXsrfInterceptor,
  2153. { provide: HTTP_INTERCEPTORS, useExisting: HttpXsrfInterceptor, multi: true },
  2154. { provide: HttpXsrfTokenExtractor, useClass: HttpXsrfCookieExtractor },
  2155. { provide: XSRF_COOKIE_NAME, useValue: 'XSRF-TOKEN' },
  2156. { provide: XSRF_HEADER_NAME, useValue: 'X-XSRF-TOKEN' },
  2157. ],
  2158. },] },
  2159. ];
  2160. /** @nocollapse */
  2161. HttpClientXsrfModule.ctorParameters = () => [];
  2162. /**
  2163. * `NgModule` which provides the `HttpClient` and associated services.
  2164. *
  2165. * Interceptors can be added to the chain behind `HttpClient` by binding them
  2166. * to the multiprovider for `HTTP_INTERCEPTORS`.
  2167. *
  2168. * \@stable
  2169. */
  2170. class HttpClientModule {
  2171. }
  2172. HttpClientModule.decorators = [
  2173. { type: NgModule, args: [{
  2174. imports: [
  2175. HttpClientXsrfModule.withOptions({
  2176. cookieName: 'XSRF-TOKEN',
  2177. headerName: 'X-XSRF-TOKEN',
  2178. }),
  2179. ],
  2180. providers: [
  2181. HttpClient,
  2182. { provide: HttpHandler, useClass: HttpInterceptingHandler },
  2183. HttpXhrBackend,
  2184. { provide: HttpBackend, useExisting: HttpXhrBackend },
  2185. BrowserXhr,
  2186. { provide: XhrFactory, useExisting: BrowserXhr },
  2187. ],
  2188. },] },
  2189. ];
  2190. /** @nocollapse */
  2191. HttpClientModule.ctorParameters = () => [];
  2192. /**
  2193. * `NgModule` which enables JSONP support in `HttpClient`.
  2194. *
  2195. * Without this module, Jsonp requests will reach the backend
  2196. * with method JSONP, where they'll be rejected.
  2197. *
  2198. * \@stable
  2199. */
  2200. class HttpClientJsonpModule {
  2201. }
  2202. HttpClientJsonpModule.decorators = [
  2203. { type: NgModule, args: [{
  2204. providers: [
  2205. JsonpClientBackend,
  2206. { provide: JsonpCallbackContext, useFactory: jsonpCallbackContext },
  2207. { provide: HTTP_INTERCEPTORS, useClass: JsonpInterceptor, multi: true },
  2208. ],
  2209. },] },
  2210. ];
  2211. /** @nocollapse */
  2212. HttpClientJsonpModule.ctorParameters = () => [];
  2213. /**
  2214. * @fileoverview added by tsickle
  2215. * @suppress {checkTypes} checked by tsc
  2216. */
  2217. /**
  2218. * @license
  2219. * Copyright Google Inc. All Rights Reserved.
  2220. *
  2221. * Use of this source code is governed by an MIT-style license that can be
  2222. * found in the LICENSE file at https://angular.io/license
  2223. */
  2224. /**
  2225. * @fileoverview added by tsickle
  2226. * @suppress {checkTypes} checked by tsc
  2227. */
  2228. /**
  2229. * Generated bundle index. Do not edit.
  2230. */
  2231. export { HttpBackend, HttpHandler, HttpClient, HttpHeaders, HTTP_INTERCEPTORS, JsonpClientBackend, JsonpInterceptor, HttpClientJsonpModule, HttpClientModule, HttpClientXsrfModule, interceptingHandler as ɵinterceptingHandler, HttpParams, HttpUrlEncodingCodec, HttpRequest, HttpErrorResponse, HttpEventType, HttpHeaderResponse, HttpResponse, HttpResponseBase, HttpXhrBackend, XhrFactory, HttpXsrfTokenExtractor, NoopInterceptor as ɵa, JsonpCallbackContext as ɵb, HttpInterceptingHandler as ɵc, jsonpCallbackContext as ɵd, BrowserXhr as ɵe, HttpXsrfCookieExtractor as ɵh, HttpXsrfInterceptor as ɵi, XSRF_COOKIE_NAME as ɵf, XSRF_HEADER_NAME as ɵg };
  2232. //# sourceMappingURL=http.js.map