http.mjs 103 KB

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