http.mjs 114 KB

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