_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/packages/common/http/test/request_spec.ts_0_7742
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {HttpContext} from '@angular/common/http/src/context'; import {HttpHeaders} from '@angular/common/http/src/headers'; import {HttpParams} from '@angular/common/http/src/params'; import {HttpRequest} from '@angular/common/http/src/request'; const TEST_URL = 'https://angular.io/'; const TEST_STRING = `I'm a body!`; describe('HttpRequest', () => { describe('constructor', () => { it('initializes url', () => { const req = new HttpRequest('', TEST_URL, null); expect(req.url).toBe(TEST_URL); }); it("doesn't require a body for body-less methods", () => { let req = new HttpRequest('GET', TEST_URL); expect(req.method).toBe('GET'); expect(req.body).toBeNull(); req = new HttpRequest('HEAD', TEST_URL); expect(req.method).toBe('HEAD'); expect(req.body).toBeNull(); req = new HttpRequest('JSONP', TEST_URL); expect(req.method).toBe('JSONP'); expect(req.body).toBeNull(); req = new HttpRequest('OPTIONS', TEST_URL); expect(req.method).toBe('OPTIONS'); expect(req.body).toBeNull(); }); it('accepts a string request method', () => { const req = new HttpRequest('TEST', TEST_URL, null); expect(req.method).toBe('TEST'); }); it('accepts a string body', () => { const req = new HttpRequest('POST', TEST_URL, TEST_STRING); expect(req.body).toBe(TEST_STRING); }); it('accepts an object body', () => { const req = new HttpRequest('POST', TEST_URL, {data: TEST_STRING}); expect(req.body).toEqual({data: TEST_STRING}); }); it('creates default headers if not passed', () => { const req = new HttpRequest('GET', TEST_URL); expect(req.headers instanceof HttpHeaders).toBeTruthy(); }); it('uses the provided headers if passed', () => { const headers = new HttpHeaders(); const req = new HttpRequest('GET', TEST_URL, {headers}); expect(req.headers).toBe(headers); }); it('uses the provided context if passed', () => { const context = new HttpContext(); const req = new HttpRequest('GET', TEST_URL, {context}); expect(req.context).toBe(context); }); it('defaults to Json', () => { const req = new HttpRequest('GET', TEST_URL); expect(req.responseType).toBe('json'); }); }); describe('clone() copies the request', () => { const headers = new HttpHeaders({ 'Test': 'Test header', }); const context = new HttpContext(); const req = new HttpRequest('POST', TEST_URL, 'test body', { headers, context, reportProgress: true, responseType: 'text', withCredentials: true, transferCache: true, }); it('in the base case', () => { const clone = req.clone(); expect(clone.method).toBe('POST'); expect(clone.responseType).toBe('text'); expect(clone.url).toBe(TEST_URL); // Headers should be the same, as the headers are sealed. expect(clone.headers).toBe(headers); expect(clone.headers.get('Test')).toBe('Test header'); expect(clone.context).toBe(context); expect(clone.transferCache).toBe(true); }); it('and updates the url', () => { expect(req.clone({url: '/changed'}).url).toBe('/changed'); }); it('and updates the method', () => { expect(req.clone({method: 'PUT'}).method).toBe('PUT'); }); it('and updates the body', () => { expect(req.clone({body: 'changed body'}).body).toBe('changed body'); }); it('and updates the context', () => { const newContext = new HttpContext(); expect(req.clone({context: newContext}).context).toBe(newContext); }); it('and updates the transferCache', () => { expect(req.clone({transferCache: false}).transferCache).toBe(false); }); }); describe('content type detection', () => { const baseReq = new HttpRequest('POST', '/test', null); it('handles a null body', () => { expect(baseReq.detectContentTypeHeader()).toBeNull(); }); it("doesn't associate a content type with ArrayBuffers", () => { const req = baseReq.clone({body: new ArrayBuffer(4)}); expect(req.detectContentTypeHeader()).toBeNull(); }); it('handles strings as text', () => { const req = baseReq.clone({body: 'hello world'}); expect(req.detectContentTypeHeader()).toBe('text/plain'); }); it('handles arrays as json', () => { const req = baseReq.clone({body: ['a', 'b']}); expect(req.detectContentTypeHeader()).toBe('application/json'); }); it('handles numbers as json', () => { const req = baseReq.clone({body: 314159}); expect(req.detectContentTypeHeader()).toBe('application/json'); }); it('handles objects as json', () => { const req = baseReq.clone({body: {data: 'test data'}}); expect(req.detectContentTypeHeader()).toBe('application/json'); }); it('handles boolean as json', () => { const req = baseReq.clone({body: true}); expect(req.detectContentTypeHeader()).toBe('application/json'); }); }); describe('body serialization', () => { const baseReq = new HttpRequest('POST', '/test', null); it('handles a null body', () => { expect(baseReq.serializeBody()).toBeNull(); }); it('passes ArrayBuffers through', () => { const body = new ArrayBuffer(4); expect(baseReq.clone({body}).serializeBody()).toBe(body); }); it('passes URLSearchParams through', () => { const body = new URLSearchParams('foo=1&bar=2'); expect(baseReq.clone({body}).serializeBody()).toBe(body); }); it('passes strings through', () => { const body = 'hello world'; expect(baseReq.clone({body}).serializeBody()).toBe(body); }); it('serializes arrays as json', () => { expect(baseReq.clone({body: ['a', 'b']}).serializeBody()).toBe('["a","b"]'); }); it('handles numbers as json', () => { expect(baseReq.clone({body: 314159}).serializeBody()).toBe('314159'); }); it('handles objects as json', () => { const req = baseReq.clone({body: {data: 'test data'}}); expect(req.serializeBody()).toBe('{"data":"test data"}'); }); it('serializes parameters as urlencoded', () => { const params = new HttpParams().append('first', 'value').append('second', 'other'); const withParams = baseReq.clone({body: params}); expect(withParams.serializeBody()).toEqual('first=value&second=other'); expect(withParams.detectContentTypeHeader()).toEqual( 'application/x-www-form-urlencoded;charset=UTF-8', ); }); }); describe('parameter handling', () => { const baseReq = new HttpRequest('GET', '/test', null); const params = new HttpParams({fromString: 'test=true'}); it('appends parameters to a base URL', () => { const req = baseReq.clone({params}); expect(req.urlWithParams).toEqual('/test?test=true'); }); it('appends parameters to a URL with an empty query string', () => { const req = baseReq.clone({params, url: '/test?'}); expect(req.urlWithParams).toEqual('/test?test=true'); }); it('appends parameters to a URL with a query string', () => { const req = baseReq.clone({params, url: '/test?other=false'}); expect(req.urlWithParams).toEqual('/test?other=false&test=true'); }); it('sets parameters via setParams', () => { const req = baseReq.clone({setParams: {'test': 'false'}}); expect(req.urlWithParams).toEqual('/test?test=false'); }); }); });
{ "end_byte": 7742, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/test/request_spec.ts" }
angular/packages/common/http/test/headers_spec.ts_0_6996
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {HttpHeaders} from '@angular/common/http/src/headers'; describe('HttpHeaders', () => { describe('initialization', () => { it('should conform to spec', () => { const httpHeaders = { 'Content-Type': 'image/jpeg', 'Accept-Charset': 'utf-8', 'X-My-Custom-Header': 'Zeke are cool', }; const secondHeaders = new HttpHeaders(httpHeaders); expect(secondHeaders.get('Content-Type')).toEqual('image/jpeg'); }); it('should merge values in provided dictionary', () => { const headers = new HttpHeaders({'foo': 'bar'}); expect(headers.get('foo')).toEqual('bar'); expect(headers.getAll('foo')).toEqual(['bar']); }); it('should lazily append values', () => { const src = new HttpHeaders(); const a = src.append('foo', 'a'); const b = a.append('foo', 'b'); const c = b.append('foo', 'c'); expect(src.getAll('foo')).toBeNull(); expect(a.getAll('foo')).toEqual(['a']); expect(b.getAll('foo')).toEqual(['a', 'b']); expect(c.getAll('foo')).toEqual(['a', 'b', 'c']); }); it('should keep the last value when initialized from an object', () => { const headers = new HttpHeaders({ 'foo': 'first', 'fOo': 'second', }); expect(headers.getAll('foo')).toEqual(['second']); }); it('should keep all values when initialized from a Headers object with duplicate headers', () => { const standardHeaders = new Headers([ ['Set-Cookie', 'cookie1=foo'], ['Set-Cookie', 'cookie2=bar'], ]); const headers = new HttpHeaders(standardHeaders); expect(headers.getAll('Set-Cookie')).toEqual(['cookie1=foo', 'cookie2=bar']); }); it('should throw an error when null is passed as header', () => { // Note: the `strictNullChecks` set to `false` in TS config would make `null` // valid value within the headers object, thus this test verifies this scenario. const headers = new HttpHeaders({foo: null!}); expect(() => headers.get('foo')).toThrowError( 'Unexpected value of the `foo` header provided. ' + 'Expecting either a string, a number or an array, but got: `null`.', ); }); it('should throw an error when undefined is passed as header', () => { // Note: the `strictNullChecks` set to `false` in TS config would make `undefined` // valid value within the headers object, thus this test verifies this scenario. const headers = new HttpHeaders({bar: undefined!}); expect(() => headers.get('bar')).toThrowError( 'Unexpected value of the `bar` header provided. ' + 'Expecting either a string, a number or an array, but got: `undefined`.', ); }); it('should not throw an error when a number is passed as header', () => { const headers = new HttpHeaders({'Content-Length': 100}); const value = headers.get('Content-Length'); expect(value).toEqual('100'); }); it('should not throw an error when a numerical array is passed as header', () => { const headers = new HttpHeaders({'some-key': [123]}); const value = headers.get('some-key'); expect(value).toEqual('123'); }); it('should not throw an error when an array of strings is passed as header', () => { const headers = new HttpHeaders({'some-key': ['myValue']}); const value = headers.get('some-key'); expect(value).toEqual('myValue'); }); }); describe('.set()', () => { it('should clear all values and re-set for the provided key', () => { const headers = new HttpHeaders({'foo': 'bar'}); expect(headers.get('foo')).toEqual('bar'); const second = headers.set('foo', 'baz'); expect(second.get('foo')).toEqual('baz'); const third = headers.set('fOO', 'bat'); expect(third.get('foo')).toEqual('bat'); }); it('should preserve the case of the first call', () => { const headers = new HttpHeaders(); const second = headers.set('fOo', 'baz'); const third = second.set('foo', 'bat'); expect(third.keys()).toEqual(['fOo']); }); }); describe('.get()', () => { it('should be case insensitive', () => { const headers = new HttpHeaders({'foo': 'baz'}); expect(headers.get('foo')).toEqual('baz'); expect(headers.get('FOO')).toEqual('baz'); }); it('should return null if the header is not present', () => { const headers = new HttpHeaders({bar: []}); expect(headers.get('bar')).toEqual(null); expect(headers.get('foo')).toEqual(null); }); }); describe('.getAll()', () => { it('should be case insensitive', () => { const headers = new HttpHeaders({foo: ['bar', 'baz']}); expect(headers.getAll('foo')).toEqual(['bar', 'baz']); expect(headers.getAll('FOO')).toEqual(['bar', 'baz']); }); it('should return null if the header is not present', () => { const headers = new HttpHeaders(); expect(headers.getAll('foo')).toEqual(null); }); }); describe('.delete', () => { it('should be case insensitive', () => { const headers = new HttpHeaders({'foo': 'baz'}); expect(headers.has('foo')).toEqual(true); const second = headers.delete('foo'); expect(second.has('foo')).toEqual(false); const third = second.set('foo', 'baz'); expect(third.has('foo')).toEqual(true); const fourth = third.delete('FOO'); expect(fourth.has('foo')).toEqual(false); }); }); describe('.append', () => { it('should append a value to the list', () => { const headers = new HttpHeaders(); const second = headers.append('foo', 'bar'); const third = second.append('foo', 'baz'); expect(third.get('foo')).toEqual('bar'); expect(third.getAll('foo')).toEqual(['bar', 'baz']); }); it('should preserve the case of the first call', () => { const headers = new HttpHeaders(); const second = headers.append('FOO', 'bar'); const third = second.append('foo', 'baz'); expect(third.keys()).toEqual(['FOO']); }); }); describe('response header strings', () => { it('should be parsed by the constructor', () => { const response = `Date: Fri, 20 Nov 2015 01:45:26 GMT\n` + `Content-Type: application/json; charset=utf-8\n` + `Transfer-Encoding: chunked\n` + `Connection: keep-alive`; const headers = new HttpHeaders(response); expect(headers.get('Date')).toEqual('Fri, 20 Nov 2015 01:45:26 GMT'); expect(headers.get('Content-Type')).toEqual('application/json; charset=utf-8'); expect(headers.get('Transfer-Encoding')).toEqual('chunked'); expect(headers.get('Connection')).toEqual('keep-alive'); }); }); });
{ "end_byte": 6996, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/test/headers_spec.ts" }
angular/packages/common/http/test/xhr_spec.ts_0_7730
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {HttpRequest} from '@angular/common/http/src/request'; import { HttpDownloadProgressEvent, HttpErrorResponse, HttpEvent, HttpEventType, HttpHeaderResponse, HttpResponse, HttpResponseBase, HttpStatusCode, HttpUploadProgressEvent, } from '@angular/common/http/src/response'; import {HttpXhrBackend} from '@angular/common/http/src/xhr'; import {Observable} from 'rxjs'; import {toArray} from 'rxjs/operators'; import {MockXhrFactory} from './xhr_mock'; function trackEvents(obs: Observable<HttpEvent<any>>): HttpEvent<any>[] { const events: HttpEvent<any>[] = []; obs.subscribe( (event) => events.push(event), (err) => events.push(err), ); return events; } const TEST_POST = new HttpRequest('POST', '/test', 'some body', { responseType: 'text', }); const TEST_POST_WITH_JSON_BODY = new HttpRequest( 'POST', '/test', {'some': 'body'}, { responseType: 'text', }, ); const XSSI_PREFIX = ")]}'\n"; describe('XhrBackend', () => { let factory: MockXhrFactory = null!; let backend: HttpXhrBackend = null!; beforeEach(() => { factory = new MockXhrFactory(); backend = new HttpXhrBackend(factory); }); it('emits status immediately', () => { const events = trackEvents(backend.handle(TEST_POST)); expect(events.length).toBe(1); expect(events[0].type).toBe(HttpEventType.Sent); }); it('sets method, url, and responseType correctly', () => { backend.handle(TEST_POST).subscribe(); expect(factory.mock.method).toBe('POST'); expect(factory.mock.responseType).toBe('text'); expect(factory.mock.url).toBe('/test'); }); it('sets outgoing body correctly', () => { backend.handle(TEST_POST).subscribe(); expect(factory.mock.body).toBe('some body'); }); it('sets outgoing body correctly when request payload is json', () => { backend.handle(TEST_POST_WITH_JSON_BODY).subscribe(); expect(factory.mock.body).toBe('{"some":"body"}'); }); it('sets outgoing headers, including default headers', () => { const post = TEST_POST.clone({ setHeaders: { 'Test': 'Test header', }, }); backend.handle(post).subscribe(); expect(factory.mock.mockHeaders).toEqual({ 'Test': 'Test header', 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'text/plain', }); }); it('sets outgoing headers, including overriding defaults', () => { const setHeaders = { 'Test': 'Test header', 'Accept': 'text/html', 'Content-Type': 'text/css', }; backend.handle(TEST_POST.clone({setHeaders})).subscribe(); expect(factory.mock.mockHeaders).toEqual(setHeaders); }); it('passes withCredentials through', () => { backend.handle(TEST_POST.clone({withCredentials: true})).subscribe(); expect(factory.mock.withCredentials).toBe(true); }); it('handles a text response', () => { const events = trackEvents(backend.handle(TEST_POST)); factory.mock.mockFlush(HttpStatusCode.Ok, 'OK', 'some response'); expect(events.length).toBe(2); expect(events[1].type).toBe(HttpEventType.Response); expect(events[1] instanceof HttpResponse).toBeTruthy(); const res = events[1] as HttpResponse<string>; expect(res.body).toBe('some response'); expect(res.status).toBe(HttpStatusCode.Ok); expect(res.statusText).toBe('OK'); }); it('handles a json response', () => { const events = trackEvents(backend.handle(TEST_POST.clone({responseType: 'json'}))); factory.mock.mockFlush(HttpStatusCode.Ok, 'OK', JSON.stringify({data: 'some data'})); expect(events.length).toBe(2); const res = events[1] as HttpResponse<{data: string}>; expect(res.body!.data).toBe('some data'); }); it('handles a blank json response', () => { const events = trackEvents(backend.handle(TEST_POST.clone({responseType: 'json'}))); factory.mock.mockFlush(HttpStatusCode.Ok, 'OK', ''); expect(events.length).toBe(2); const res = events[1] as HttpResponse<{data: string}>; expect(res.body).toBeNull(); }); it('handles a json error response', () => { const events = trackEvents(backend.handle(TEST_POST.clone({responseType: 'json'}))); factory.mock.mockFlush( HttpStatusCode.InternalServerError, 'Error', JSON.stringify({data: 'some data'}), ); expect(events.length).toBe(2); const res = events[1] as any as HttpErrorResponse; expect(res.error!.data).toBe('some data'); }); it('handles a json error response with XSSI prefix', () => { const events = trackEvents(backend.handle(TEST_POST.clone({responseType: 'json'}))); factory.mock.mockFlush( HttpStatusCode.InternalServerError, 'Error', XSSI_PREFIX + JSON.stringify({data: 'some data'}), ); expect(events.length).toBe(2); const res = events[1] as any as HttpErrorResponse; expect(res.error!.data).toBe('some data'); }); it('handles a json string response', () => { const events = trackEvents(backend.handle(TEST_POST.clone({responseType: 'json'}))); expect(factory.mock.responseType).toEqual('text'); factory.mock.mockFlush(HttpStatusCode.Ok, 'OK', JSON.stringify('this is a string')); expect(events.length).toBe(2); const res = events[1] as HttpResponse<string>; expect(res.body).toEqual('this is a string'); }); it('handles a json response with an XSSI prefix', () => { const events = trackEvents(backend.handle(TEST_POST.clone({responseType: 'json'}))); factory.mock.mockFlush( HttpStatusCode.Ok, 'OK', XSSI_PREFIX + JSON.stringify({data: 'some data'}), ); expect(events.length).toBe(2); const res = events[1] as HttpResponse<{data: string}>; expect(res.body!.data).toBe('some data'); }); it('emits unsuccessful responses via the error path', (done) => { backend.handle(TEST_POST).subscribe(undefined, (err: HttpErrorResponse) => { expect(err instanceof HttpErrorResponse).toBe(true); expect(err.error).toBe('this is the error'); done(); }); factory.mock.mockFlush(HttpStatusCode.BadRequest, 'Bad Request', 'this is the error'); }); it('emits real errors via the error path', (done) => { backend.handle(TEST_POST).subscribe(undefined, (err: HttpErrorResponse) => { expect(err instanceof HttpErrorResponse).toBe(true); expect(err.error instanceof Error).toBeTrue(); expect(err.url).toBe('/test'); done(); }); factory.mock.mockErrorEvent(new Error('blah')); }); it('emits timeout if the request times out', (done) => { backend.handle(TEST_POST).subscribe({ error: (error: HttpErrorResponse) => { expect(error instanceof HttpErrorResponse).toBeTrue(); expect(error.error instanceof Error).toBeTrue(); expect(error.url).toBe('/test'); done(); }, }); factory.mock.mockTimeoutEvent(new Error('timeout')); }); it('avoids abort a request when fetch operation is completed', (done) => { const abort = jasmine.createSpy('abort'); backend .handle(TEST_POST) .toPromise() .then(() => { expect(abort).not.toHaveBeenCalled(); done(); }); factory.mock.abort = abort; factory.mock.mockFlush(HttpStatusCode.Ok, 'OK', 'Done'); }); it('emits an error when browser cancels a request', (done) => { backend.handle(TEST_POST).subscribe(undefined, (err: HttpErrorResponse) => { expect(err instanceof HttpErrorResponse).toBe(true); done(); }); factory.mock.mockAbortEvent(); });
{ "end_byte": 7730, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/test/xhr_spec.ts" }
angular/packages/common/http/test/xhr_spec.ts_7733_16182
describe('progress events', () => { it('are emitted for download progress', (done) => { backend .handle(TEST_POST.clone({reportProgress: true})) .pipe(toArray()) .subscribe((events) => { expect(events.map((event) => event.type)).toEqual([ HttpEventType.Sent, HttpEventType.ResponseHeader, HttpEventType.DownloadProgress, HttpEventType.DownloadProgress, HttpEventType.Response, ]); const [progress1, progress2, response] = [ events[2] as HttpDownloadProgressEvent, events[3] as HttpDownloadProgressEvent, events[4] as HttpResponse<string>, ]; expect(progress1.partialText).toBe('down'); expect(progress1.loaded).toBe(100); expect(progress1.total).toBe(300); expect(progress2.partialText).toBe('download'); expect(progress2.loaded).toBe(200); expect(progress2.total).toBe(300); expect(response.body).toBe('downloaded'); done(); }); factory.mock.responseText = 'down'; factory.mock.mockDownloadProgressEvent(100, 300); factory.mock.responseText = 'download'; factory.mock.mockDownloadProgressEvent(200, 300); factory.mock.mockFlush(HttpStatusCode.Ok, 'OK', 'downloaded'); }); it('are emitted for upload progress', (done) => { backend .handle(TEST_POST.clone({reportProgress: true})) .pipe(toArray()) .subscribe((events) => { expect(events.map((event) => event.type)).toEqual([ HttpEventType.Sent, HttpEventType.UploadProgress, HttpEventType.UploadProgress, HttpEventType.Response, ]); const [progress1, progress2] = [ events[1] as HttpUploadProgressEvent, events[2] as HttpUploadProgressEvent, ]; expect(progress1.loaded).toBe(100); expect(progress1.total).toBe(300); expect(progress2.loaded).toBe(200); expect(progress2.total).toBe(300); done(); }); factory.mock.mockUploadProgressEvent(100, 300); factory.mock.mockUploadProgressEvent(200, 300); factory.mock.mockFlush(HttpStatusCode.Ok, 'OK', 'Done'); }); it('are emitted when both upload and download progress are available', (done) => { backend .handle(TEST_POST.clone({reportProgress: true})) .pipe(toArray()) .subscribe((events) => { expect(events.map((event) => event.type)).toEqual([ HttpEventType.Sent, HttpEventType.UploadProgress, HttpEventType.ResponseHeader, HttpEventType.DownloadProgress, HttpEventType.Response, ]); done(); }); factory.mock.mockUploadProgressEvent(100, 300); factory.mock.mockDownloadProgressEvent(200, 300); factory.mock.mockFlush(HttpStatusCode.Ok, 'OK', 'Done'); }); it('are emitted even if length is not computable', (done) => { backend .handle(TEST_POST.clone({reportProgress: true})) .pipe(toArray()) .subscribe((events) => { expect(events.map((event) => event.type)).toEqual([ HttpEventType.Sent, HttpEventType.UploadProgress, HttpEventType.ResponseHeader, HttpEventType.DownloadProgress, HttpEventType.Response, ]); done(); }); factory.mock.mockUploadProgressEvent(100); factory.mock.mockDownloadProgressEvent(200); factory.mock.mockFlush(HttpStatusCode.Ok, 'OK', 'Done'); }); it('include ResponseHeader with headers and status', (done) => { backend .handle(TEST_POST.clone({reportProgress: true})) .pipe(toArray()) .subscribe((events) => { expect(events.map((event) => event.type)).toEqual([ HttpEventType.Sent, HttpEventType.ResponseHeader, HttpEventType.DownloadProgress, HttpEventType.Response, ]); const partial = events[1] as HttpHeaderResponse; expect(partial.headers.get('Content-Type')).toEqual('text/plain'); expect(partial.headers.get('Test')).toEqual('Test header'); done(); }); factory.mock.mockResponseHeaders = 'Test: Test header\nContent-Type: text/plain\n'; factory.mock.mockDownloadProgressEvent(200); factory.mock.mockFlush(HttpStatusCode.Ok, 'OK', 'Done'); }); it('are unsubscribed along with the main request', () => { const sub = backend.handle(TEST_POST.clone({reportProgress: true})).subscribe(); expect(factory.mock.listeners.progress).not.toBeUndefined(); sub.unsubscribe(); expect(factory.mock.listeners.progress).toBeUndefined(); }); it('do not cause headers to be re-parsed on main response', (done) => { backend .handle(TEST_POST.clone({reportProgress: true})) .pipe(toArray()) .subscribe((events) => { events .filter( (event) => event.type === HttpEventType.Response || event.type === HttpEventType.ResponseHeader, ) .map((event) => event as HttpResponseBase) .forEach((event) => { expect(event.status).toBe(HttpStatusCode.NonAuthoritativeInformation); expect(event.headers.get('Test')).toEqual('This is a test'); }); done(); }); factory.mock.mockResponseHeaders = 'Test: This is a test\n'; factory.mock.status = HttpStatusCode.NonAuthoritativeInformation; factory.mock.mockDownloadProgressEvent(100, 300); factory.mock.mockResponseHeaders = 'Test: should never be read\n'; factory.mock.mockFlush(HttpStatusCode.NonAuthoritativeInformation, 'OK', 'Testing 1 2 3'); }); }); describe('gets response URL', () => { it('from XHR.responsesURL', (done) => { backend .handle(TEST_POST) .pipe(toArray()) .subscribe((events) => { expect(events.length).toBe(2); expect(events[1].type).toBe(HttpEventType.Response); const response = events[1] as HttpResponse<string>; expect(response.url).toBe('/response/url'); done(); }); factory.mock.responseURL = '/response/url'; factory.mock.mockFlush(HttpStatusCode.Ok, 'OK', 'Test'); }); it('from X-Request-URL header if XHR.responseURL is not present', (done) => { backend .handle(TEST_POST) .pipe(toArray()) .subscribe((events) => { expect(events.length).toBe(2); expect(events[1].type).toBe(HttpEventType.Response); const response = events[1] as HttpResponse<string>; expect(response.url).toBe('/response/url'); done(); }); factory.mock.mockResponseHeaders = 'X-Request-URL: /response/url\n'; factory.mock.mockFlush(HttpStatusCode.Ok, 'OK', 'Test'); }); it('falls back on Request.url if neither are available', (done) => { backend .handle(TEST_POST) .pipe(toArray()) .subscribe((events) => { expect(events.length).toBe(2); expect(events[1].type).toBe(HttpEventType.Response); const response = events[1] as HttpResponse<string>; expect(response.url).toBe('/test'); done(); }); factory.mock.mockFlush(HttpStatusCode.Ok, 'OK', 'Test'); }); }); describe('corrects for quirks', () => { it('by normalizing 0 status to 200 if a body is present', (done) => { backend .handle(TEST_POST) .pipe(toArray()) .subscribe((events) => { expect(events.length).toBe(2); expect(events[1].type).toBe(HttpEventType.Response); const response = events[1] as HttpResponse<string>; expect(response.status).toBe(HttpStatusCode.Ok); done(); }); factory.mock.mockFlush(0, 'CORS 0 status', 'Test'); }); it('by leaving 0 status as 0 if a body is not present', (done) => { backend .handle(TEST_POST) .pipe(toArray()) .subscribe(undefined, (error: HttpErrorResponse) => { expect(error.status).toBe(0); done(); }); factory.mock.mockFlush(0, 'CORS 0 status'); }); }); });
{ "end_byte": 16182, "start_byte": 7733, "url": "https://github.com/angular/angular/blob/main/packages/common/http/test/xhr_spec.ts" }
angular/packages/common/http/test/response_spec.ts_0_3056
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {HttpHeaders} from '@angular/common/http/src/headers'; import {HttpResponse, HttpStatusCode} from '@angular/common/http/src/response'; describe('HttpResponse', () => { describe('constructor()', () => { it('fully constructs responses', () => { const resp = new HttpResponse({ body: 'test body', headers: new HttpHeaders({ 'Test': 'Test header', }), status: HttpStatusCode.Created, statusText: 'Created', url: '/test', }); expect(resp.body).toBe('test body'); expect(resp.headers instanceof HttpHeaders).toBeTruthy(); expect(resp.headers.get('Test')).toBe('Test header'); expect(resp.status).toBe(HttpStatusCode.Created); expect(resp.statusText).toBe('Created'); expect(resp.url).toBe('/test'); }); it('uses defaults if no args passed', () => { const resp = new HttpResponse({}); expect(resp.headers).not.toBeNull(); expect(resp.status).toBe(HttpStatusCode.Ok); expect(resp.statusText).toBe('OK'); expect(resp.body).toBeNull(); expect(resp.ok).toBeTruthy(); expect(resp.url).toBeNull(); }); it('accepts a falsy body', () => { expect(new HttpResponse({body: false}).body).toEqual(false); expect(new HttpResponse({body: 0}).body).toEqual(0); }); }); it('.ok is determined by status', () => { const good = new HttpResponse({status: 200}); const alsoGood = new HttpResponse({status: 299}); const badHigh = new HttpResponse({status: 300}); const badLow = new HttpResponse({status: 199}); expect(good.ok).toBe(true); expect(alsoGood.ok).toBe(true); expect(badHigh.ok).toBe(false); expect(badLow.ok).toBe(false); }); describe('.clone()', () => { it('copies the original when given no arguments', () => { const clone = new HttpResponse({ body: 'test', status: HttpStatusCode.Created, statusText: 'created', url: '/test', }).clone(); expect(clone.body).toBe('test'); expect(clone.status).toBe(HttpStatusCode.Created); expect(clone.statusText).toBe('created'); expect(clone.url).toBe('/test'); expect(clone.headers).not.toBeNull(); }); it('overrides the original', () => { const orig = new HttpResponse({ body: 'test', status: HttpStatusCode.Created, statusText: 'created', url: '/test', }); const clone = orig.clone({ body: {data: 'test'}, status: HttpStatusCode.Ok, statusText: 'Okay', url: '/bar', }); expect(clone.body).toEqual({data: 'test'}); expect(clone.status).toBe(HttpStatusCode.Ok); expect(clone.statusText).toBe('Okay'); expect(clone.url).toBe('/bar'); expect(clone.headers).toBe(orig.headers); }); }); });
{ "end_byte": 3056, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/test/response_spec.ts" }
angular/packages/common/http/test/BUILD.bazel_0_1141
load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library") load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test") circular_dependency_test( name = "circular_deps_test", entry_point = "angular/packages/common/http/index.mjs", deps = ["//packages/common/http"], ) ts_library( name = "test_lib", testonly = True, srcs = glob( ["**/*.ts"], ), # Visible to //:saucelabs_unit_tests_poc target visibility = ["//:__pkg__"], deps = [ "//packages/common", "//packages/common/http", "//packages/common/http/testing", "//packages/core", "//packages/core/testing", "//packages/private/testing", "@npm//rxjs", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node"], flaky = True, # TODO: figure out why one of the transferCache tests is flaky deps = [ ":test_lib", ], ) karma_web_test_suite( name = "test_web", flaky = True, # TODO: figure out why one of the transferCache tests is flaky deps = [ ":test_lib", ], )
{ "end_byte": 1141, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/test/BUILD.bazel" }
angular/packages/common/http/test/provider_spec.ts_0_1836
/** * @license * Copyright Google LLC All Rights Reserved.sonpCallbackContext * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {DOCUMENT, XhrFactory} from '@angular/common'; import { FetchBackend, HTTP_INTERCEPTORS, HttpBackend, HttpClient, HttpClientModule, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse, HttpXhrBackend, JsonpClientBackend, } from '@angular/common/http'; import { HttpClientTestingModule, HttpTestingController, provideHttpClientTesting, } from '@angular/common/http/testing'; import { ApplicationRef, createEnvironmentInjector, EnvironmentInjector, inject, InjectionToken, PLATFORM_ID, Provider, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {EMPTY, Observable, from} from 'rxjs'; import {HttpInterceptorFn, resetFetchBackendWarningFlag} from '../src/interceptor'; import { HttpFeature, HttpFeatureKind, provideHttpClient, withFetch, withInterceptors, withInterceptorsFromDi, withJsonpSupport, withNoXsrfProtection, withRequestsMadeViaParent, withXsrfConfiguration, } from '../src/provider'; describe('without provideHttpClientTesting', () => { it('should contribute to stability', async () => { TestBed.configureTestingModule({ providers: [ provideHttpClient(withInterceptors([() => from(Promise.resolve(new HttpResponse()))])), ], }); let stable = false; TestBed.inject(ApplicationRef).isStable.subscribe((v) => { stable = v; }); expect(stable).toBe(true); TestBed.inject(HttpClient).get('/test', {responseType: 'text'}).subscribe(); expect(stable).toBe(false); await Promise.resolve(); expect(stable).toBe(true); }); });
{ "end_byte": 1836, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/test/provider_spec.ts" }
angular/packages/common/http/test/provider_spec.ts_1838_11185
describe('provideHttpClient', () => { beforeEach(() => { setCookie(''); TestBed.resetTestingModule(); }); afterEach(() => { let controller: HttpTestingController; try { controller = TestBed.inject(HttpTestingController); } catch (err) { // A failure here means that TestBed wasn't successfully configured. Some tests intentionally // test configuration errors and therefore exit without setting up TestBed for HTTP, so just // exit here without performing verification on the `HttpTestingController` in that case. return; } controller.verify(); }); it('should configure HttpClient', () => { TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()], }); TestBed.inject(HttpClient).get('/test', {responseType: 'text'}).subscribe(); TestBed.inject(HttpTestingController).expectOne('/test').flush(''); }); it('should not contribute to stability', () => { TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()], }); let stable = false; TestBed.inject(ApplicationRef).isStable.subscribe((v) => { stable = v; }); expect(stable).toBe(true); TestBed.inject(HttpClient).get('/test', {responseType: 'text'}).subscribe(); expect(stable).toBe(true); TestBed.inject(HttpTestingController).expectOne('/test').flush(''); expect(stable).toBe(true); }); it('should not use legacy interceptors by default', () => { TestBed.configureTestingModule({ providers: [ provideHttpClient(), provideLegacyInterceptor('legacy'), provideHttpClientTesting(), ], }); TestBed.inject(HttpClient).get('/test', {responseType: 'text'}).subscribe(); const req = TestBed.inject(HttpTestingController).expectOne('/test'); expect(req.request.headers.has('X-Tag')).toBeFalse(); req.flush(''); }); it('withInterceptorsFromDi() should enable legacy interceptors', () => { TestBed.configureTestingModule({ providers: [ provideHttpClient(withInterceptorsFromDi()), provideLegacyInterceptor('alpha'), provideLegacyInterceptor('beta'), provideHttpClientTesting(), ], }); TestBed.inject(HttpClient).get('/test', {responseType: 'text'}).subscribe(); const req = TestBed.inject(HttpTestingController).expectOne('/test'); expect(req.request.headers.get('X-Tag')).toEqual('alpha,beta'); req.flush(''); }); describe('interceptor functions', () => { it('should allow configuring interceptors', () => { TestBed.configureTestingModule({ providers: [ provideHttpClient( withInterceptors([ makeLiteralTagInterceptorFn('alpha'), makeLiteralTagInterceptorFn('beta'), ]), ), provideHttpClientTesting(), ], }); TestBed.inject(HttpClient).get('/test', {responseType: 'text'}).subscribe(); const req = TestBed.inject(HttpTestingController).expectOne('/test'); expect(req.request.headers.get('X-Tag')).toEqual('alpha,beta'); req.flush(''); }); it('should accept multiple separate interceptor configs', () => { TestBed.configureTestingModule({ providers: [ provideHttpClient( withInterceptors([makeLiteralTagInterceptorFn('alpha')]), withInterceptors([makeLiteralTagInterceptorFn('beta')]), ), provideHttpClientTesting(), ], }); TestBed.inject(HttpClient).get('/test', {responseType: 'text'}).subscribe(); const req = TestBed.inject(HttpTestingController).expectOne('/test'); expect(req.request.headers.get('X-Tag')).toEqual('alpha,beta'); req.flush(''); }); it('should allow injection from an interceptor context', () => { const ALPHA = new InjectionToken<string>('alpha', { providedIn: 'root', factory: () => 'alpha', }); const BETA = new InjectionToken<string>('beta', {providedIn: 'root', factory: () => 'beta'}); TestBed.configureTestingModule({ providers: [ provideHttpClient( withInterceptors([makeTokenTagInterceptorFn(ALPHA), makeTokenTagInterceptorFn(BETA)]), ), provideHttpClientTesting(), ], }); TestBed.inject(HttpClient).get('/test', {responseType: 'text'}).subscribe(); const req = TestBed.inject(HttpTestingController).expectOne('/test'); expect(req.request.headers.get('X-Tag')).toEqual('alpha,beta'); req.flush(''); }); it('should allow combination with legacy interceptors, before the legacy stack', () => { TestBed.configureTestingModule({ providers: [ provideHttpClient( withInterceptors([makeLiteralTagInterceptorFn('functional')]), withInterceptorsFromDi(), ), provideHttpClientTesting(), provideLegacyInterceptor('legacy'), ], }); TestBed.inject(HttpClient).get('/test', {responseType: 'text'}).subscribe(); const req = TestBed.inject(HttpTestingController).expectOne('/test'); expect(req.request.headers.get('X-Tag')).toEqual('functional,legacy'); req.flush(''); }); it('should allow combination with legacy interceptors, after the legacy stack', () => { TestBed.configureTestingModule({ providers: [ provideHttpClient( withInterceptorsFromDi(), withInterceptors([makeLiteralTagInterceptorFn('functional')]), ), provideHttpClientTesting(), provideLegacyInterceptor('legacy'), ], }); TestBed.inject(HttpClient).get('/test', {responseType: 'text'}).subscribe(); const req = TestBed.inject(HttpTestingController).expectOne('/test'); expect(req.request.headers.get('X-Tag')).toEqual('legacy,functional'); req.flush(''); }); }); describe('xsrf protection', () => { it('should enable xsrf protection by default', () => { TestBed.configureTestingModule({ providers: [ provideHttpClient(), provideHttpClientTesting(), {provide: PLATFORM_ID, useValue: 'test'}, ], }); setXsrfToken('abcdefg'); TestBed.inject(HttpClient).post('/test', '', {responseType: 'text'}).subscribe(); const req = TestBed.inject(HttpTestingController).expectOne('/test'); expect(req.request.headers.get('X-XSRF-TOKEN')).toEqual('abcdefg'); req.flush(''); }); it('withXsrfConfiguration() should allow customization of xsrf config', () => { TestBed.configureTestingModule({ providers: [ provideHttpClient( withXsrfConfiguration({ cookieName: 'XSRF-CUSTOM-COOKIE', headerName: 'X-Custom-Xsrf-Header', }), ), provideHttpClientTesting(), {provide: PLATFORM_ID, useValue: 'test'}, ], }); setCookie('XSRF-CUSTOM-COOKIE=abcdefg'); TestBed.inject(HttpClient).post('/test', '', {responseType: 'text'}).subscribe(); const req = TestBed.inject(HttpTestingController).expectOne('/test'); expect(req.request.headers.get('X-Custom-Xsrf-Header')).toEqual('abcdefg'); req.flush(''); }); it('withNoXsrfProtection() should disable xsrf protection', () => { TestBed.configureTestingModule({ providers: [ provideHttpClient(withNoXsrfProtection()), provideHttpClientTesting(), {provide: PLATFORM_ID, useValue: 'test'}, ], }); setXsrfToken('abcdefg'); TestBed.inject(HttpClient).post('/test', '', {responseType: 'text'}).subscribe(); const req = TestBed.inject(HttpTestingController).expectOne('/test'); expect(req.request.headers.has('X-Custom-Xsrf-Header')).toBeFalse(); req.flush(''); }); it('should error if withXsrfConfiguration() and withNoXsrfProtection() are combined', () => { expect(() => { TestBed.configureTestingModule({ providers: [ provideHttpClient(withNoXsrfProtection(), withXsrfConfiguration({})), provideHttpClientTesting(), {provide: PLATFORM_ID, useValue: 'test'}, ], }); }).toThrow(); }); }); describe('JSONP support', () => { it('should not be enabled by default', () => { TestBed.configureTestingModule({ providers: [provideHttpClient(), provideHttpClientTesting()], }); TestBed.inject(HttpClient).jsonp('/test', 'callback').subscribe(); // Because no JSONP interceptor should be registered, this request should go to the testing // backend. TestBed.inject(HttpTestingController).expectOne('/test?callback=JSONP_CALLBACK').flush(''); }); it('should be enabled when using withJsonpSupport()', () => { TestBed.configureTestingModule({ providers: [ provideHttpClient(withJsonpSupport()), provideHttpClientTesting(), FAKE_JSONP_BACKEND_PROVIDER, ], }); TestBed.inject(HttpClient).jsonp('/test', 'callback').subscribe(); TestBed.inject(HttpTestingController).expectNone('/test?callback=JSONP_CALLBACK'); }); });
{ "end_byte": 11185, "start_byte": 1838, "url": "https://github.com/angular/angular/blob/main/packages/common/http/test/provider_spec.ts" }
angular/packages/common/http/test/provider_spec.ts_11189_20623
describe('withRequestsMadeViaParent()', () => { for (const backend of ['fetch', 'xhr']) { describe(`given '${backend}' backend`, () => { const commonHttpFeatures: HttpFeature<HttpFeatureKind>[] = []; if (backend === 'fetch') { commonHttpFeatures.push(withFetch()); } it('should have independent HTTP setups if not explicitly specified', async () => { TestBed.configureTestingModule({ providers: [provideHttpClient(...commonHttpFeatures), provideHttpClientTesting()], }); const child = createEnvironmentInjector( [ provideHttpClient(), { provide: XhrFactory, useValue: { build: () => { throw new Error('Request reached the "backend".'); }, }, }, ], TestBed.inject(EnvironmentInjector), ); // Because `child` is an entirely independent HTTP context, it is not connected to the // HTTP testing backend from the parent injector, and requests attempted via the child's // `HttpClient` will fail. await expectAsync(child.get(HttpClient).get('/test').toPromise()).toBeRejected(); }); it('should connect child to parent configuration if specified', () => { TestBed.configureTestingModule({ providers: [provideHttpClient(...commonHttpFeatures), provideHttpClientTesting()], }); const child = createEnvironmentInjector( [provideHttpClient(withRequestsMadeViaParent())], TestBed.inject(EnvironmentInjector), ); // `child` is now to the parent HTTP context and therefore the testing backend, and so a // request made via its `HttpClient` can be made. child.get(HttpClient).get('/test', {responseType: 'text'}).subscribe(); const req = TestBed.inject(HttpTestingController).expectOne('/test'); req.flush(''); }); it('should include interceptors from both parent and child contexts', () => { TestBed.configureTestingModule({ providers: [ provideHttpClient( ...commonHttpFeatures, withInterceptors([makeLiteralTagInterceptorFn('parent')]), ), provideHttpClientTesting(), ], }); const child = createEnvironmentInjector( [ provideHttpClient( withRequestsMadeViaParent(), withInterceptors([makeLiteralTagInterceptorFn('child')]), ), ], TestBed.inject(EnvironmentInjector), ); child.get(HttpClient).get('/test', {responseType: 'text'}).subscribe(); const req = TestBed.inject(HttpTestingController).expectOne('/test'); expect(req.request.headers.get('X-Tag')).toEqual('child,parent'); req.flush(''); }); it('should be able to connect to a legacy-provided HttpClient context', () => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [provideLegacyInterceptor('parent')], }); const child = createEnvironmentInjector( [ provideHttpClient( ...commonHttpFeatures, withRequestsMadeViaParent(), withInterceptors([makeLiteralTagInterceptorFn('child')]), ), ], TestBed.inject(EnvironmentInjector), ); child.get(HttpClient).get('/test', {responseType: 'text'}).subscribe(); const req = TestBed.inject(HttpTestingController).expectOne('/test'); expect(req.request.headers.get('X-Tag')).toEqual('child,parent'); req.flush(''); }); }); } }); describe('compatibility with Http NgModules', () => { it('should function when configuring HTTP both ways in the same injector', () => { TestBed.configureTestingModule({ imports: [HttpClientModule], providers: [ provideHttpClient(), // Interceptor support from HttpClientModule should be functional provideLegacyInterceptor('alpha'), provideLegacyInterceptor('beta'), provideHttpClientTesting(), ], }); TestBed.inject(HttpClient).get('/test', {responseType: 'text'}).subscribe(); const req = TestBed.inject(HttpTestingController).expectOne('/test'); expect(req.request.headers.get('X-Tag')).toEqual('alpha,beta'); req.flush(''); }); }); describe('fetch support', () => { it('withFetch', () => { resetFetchBackendWarningFlag(); const consoleWarnSpy = spyOn(console, 'warn'); TestBed.resetTestingModule(); TestBed.configureTestingModule({ providers: [ // Setting this flag to verify that there are no // `console.warn` produced for cases when `fetch` // is enabled and we are running in a browser. {provide: PLATFORM_ID, useValue: 'browser'}, provideHttpClient(withFetch()), ], }); const fetchBackend = TestBed.inject(HttpBackend); expect(fetchBackend).toBeInstanceOf(FetchBackend); // Make sure there are no warnings produced. expect(consoleWarnSpy.calls.count()).toBe(0); }); it(`'withFetch' should not override provided backend`, () => { class CustomBackendExtends extends HttpXhrBackend {} TestBed.resetTestingModule(); TestBed.configureTestingModule({ providers: [ provideHttpClient(withFetch()), {provide: HttpBackend, useClass: CustomBackendExtends}, ], }); const backend = TestBed.inject(HttpBackend); expect(backend).toBeInstanceOf(CustomBackendExtends); }); it(`fetch API should be used in child when 'withFetch' was used in parent injector`, () => { TestBed.configureTestingModule({ providers: [provideHttpClient(withFetch()), provideHttpClientTesting()], }); const child = createEnvironmentInjector( [provideHttpClient()], TestBed.inject(EnvironmentInjector), ); const backend = child.get(HttpBackend); expect(backend).toBeInstanceOf(FetchBackend); }); it('should not warn if fetch is not configured when running in a browser', () => { resetFetchBackendWarningFlag(); const consoleWarnSpy = spyOn(console, 'warn'); TestBed.resetTestingModule(); TestBed.configureTestingModule({ providers: [ // Setting this flag to verify that there are no // `console.warn` produced for cases when `fetch` // is enabled and we are running in a browser. {provide: PLATFORM_ID, useValue: 'browser'}, provideHttpClient(), ], }); TestBed.inject(HttpHandler); // Make sure there are no warnings produced. expect(consoleWarnSpy.calls.count()).toBe(0); }); it('should warn during SSR if fetch is not configured', () => { resetFetchBackendWarningFlag(); const consoleWarnSpy = spyOn(console, 'warn'); TestBed.resetTestingModule(); TestBed.configureTestingModule({ providers: [ // Setting this flag to verify that there is a // `console.warn` produced in case `fetch` is not // enabled while running code on the server. {provide: PLATFORM_ID, useValue: 'server'}, provideHttpClient(), ], }); TestBed.inject(HttpHandler); expect(consoleWarnSpy.calls.count()).toBe(1); expect(consoleWarnSpy.calls.argsFor(0)[0]).toContain( 'NG02801: Angular detected that `HttpClient` is not configured to use `fetch` APIs.', ); }); }); }); function setXsrfToken(token: string): void { setCookie(`XSRF-TOKEN=${token}`); } function setCookie(cookie: string): void { Object.defineProperty(TestBed.inject(DOCUMENT), 'cookie', { get: () => cookie, configurable: true, }); } function provideLegacyInterceptor(tag: string): Provider { class LegacyTagInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(addTagToRequest(req, tag)); } } const token = new InjectionToken(`LegacyTagInterceptor[${tag}]`, { providedIn: 'root', factory: () => new LegacyTagInterceptor(), }); return { provide: HTTP_INTERCEPTORS, useExisting: token, multi: true, }; } function makeLiteralTagInterceptorFn(tag: string): HttpInterceptorFn { return (req, next) => next(addTagToRequest(req, tag)); } function makeTokenTagInterceptorFn(tag: InjectionToken<string>): HttpInterceptorFn { return (req, next) => next(addTagToRequest(req, inject(tag))); } function addTagToRequest(req: HttpRequest<unknown>, tag: string): HttpRequest<unknown> { const prevTagHeader = req.headers.get('X-Tag') ?? ''; const tagHeader = prevTagHeader.length > 0 ? prevTagHeader + ',' + tag : tag; return req.clone({ setHeaders: { 'X-Tag': tagHeader, }, }); } const FAKE_JSONP_BACKEND_PROVIDER = { provide: JsonpClientBackend, useValue: { handle: (req: HttpRequest<never>) => EMPTY, }, };
{ "end_byte": 20623, "start_byte": 11189, "url": "https://github.com/angular/angular/blob/main/packages/common/http/test/provider_spec.ts" }
angular/packages/common/http/test/jsonp_mock.ts_0_1699
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export class MockScriptElement { constructor(public ownerDocument: MockDocument) {} listeners: { load?: (event: Event) => void; error?: (err: Error) => void; } = {}; addEventListener(event: 'load' | 'error', handler: Function): void { this.listeners[event] = handler as any; } removeEventListener(event: 'load' | 'error'): void { delete this.listeners[event]; } remove() { this.ownerDocument.removeNode(this); } } export class MockDocument { // TODO(issue/24571): remove '!'. mock!: MockScriptElement | null; readonly body: any = this; implementation = { createHTMLDocument: () => new MockDocument(), }; createElement(tag: 'script'): HTMLScriptElement { return new MockScriptElement(this) as any as HTMLScriptElement; } appendChild(node: any): void { this.mock = node; } removeNode(node: any): void { if (this.mock === node) { this.mock = null; } } adoptNode(node: any) { node.ownerDocument = this; } mockLoad(): void { // Mimic behavior described by // https://html.spec.whatwg.org/multipage/scripting.html#execute-the-script-block if (this.mock!.ownerDocument === this) { this.mock!.listeners.load!(null as any); } } mockError(err: Error) { // Mimic behavior described by // https://html.spec.whatwg.org/multipage/scripting.html#execute-the-script-block if (this.mock!.ownerDocument === this) { this.mock!.listeners.error!(err); } } }
{ "end_byte": 1699, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/test/jsonp_mock.ts" }
angular/packages/common/http/testing/PACKAGE.md_0_57
Supplies a testing module for the Angular HTTP subsystem.
{ "end_byte": 57, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/testing/PACKAGE.md" }
angular/packages/common/http/testing/BUILD.bazel_0_812
load("//tools:defaults.bzl", "ng_module") load("//adev/shared-docs/pipeline/api-gen:generate_api_docs.bzl", "generate_api_docs") package(default_visibility = ["//visibility:public"]) exports_files(["package.json"]) ng_module( name = "testing", srcs = glob( [ "*.ts", "src/**/*.ts", ], ), deps = [ "//packages/common/http", "//packages/core", "@npm//rxjs", ], ) filegroup( name = "files_for_docgen", srcs = glob([ "*.ts", "src/**/*.ts", ]) + ["PACKAGE.md"], ) generate_api_docs( name = "http_testing_docs", srcs = [ ":files_for_docgen", "//packages:common_files_and_deps_for_docs", ], entry_point = ":index.ts", module_name = "@angular/common/http/testing", )
{ "end_byte": 812, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/testing/BUILD.bazel" }
angular/packages/common/http/testing/index.ts_0_234
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export * from './public_api';
{ "end_byte": 234, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/testing/index.ts" }
angular/packages/common/http/testing/public_api.ts_0_421
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export {HttpTestingController, RequestMatch} from './src/api'; export {HttpClientTestingModule} from './src/module'; export {provideHttpClientTesting} from './src/provider'; export {TestRequest} from './src/request';
{ "end_byte": 421, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/testing/public_api.ts" }
angular/packages/common/http/testing/test/request_spec.ts_0_3258
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {HttpClient} from '@angular/common/http'; import {HttpClientTestingBackend} from '@angular/common/http/testing/src/backend'; describe('HttpClient TestRequest', () => { it('accepts a null body', () => { const mock = new HttpClientTestingBackend(); const client = new HttpClient(mock); let resp: any; client.post('/some-url', {test: 'test'}).subscribe((body) => { resp = body; }); const req = mock.expectOne('/some-url'); req.flush(null); expect(resp).toBeNull(); }); it('throws if no request matches', () => { const mock = new HttpClientTestingBackend(); const client = new HttpClient(mock); let resp: any; client.get('/some-other-url').subscribe((body) => { resp = body; }); try { // expect different URL mock.expectOne('/some-url').flush(null); fail(); } catch (error) { expect((error as Error).message).toBe( 'Expected one matching request for criteria "Match URL: /some-url", found none.' + ' Requests received are: GET /some-other-url.', ); } }); it('throws if no request matches the exact parameters', () => { const mock = new HttpClientTestingBackend(); const client = new HttpClient(mock); let resp: any; const params = {query: 'hello'}; client.get('/some-url', {params}).subscribe((body) => { resp = body; }); try { // expect different query parameters mock.expectOne('/some-url?query=world').flush(null); fail(); } catch (error) { expect((error as Error).message).toBe( 'Expected one matching request for criteria "Match URL: /some-url?query=world", found none.' + ' Requests received are: GET /some-url?query=hello.', ); } }); it('throws if no request matches with several requests received', () => { const mock = new HttpClientTestingBackend(); const client = new HttpClient(mock); let resp: any; client.get('/some-other-url?query=world').subscribe((body) => { resp = body; }); client.post('/and-another-url', {}).subscribe((body) => { resp = body; }); try { // expect different URL mock.expectOne('/some-url').flush(null); fail(); } catch (error) { expect((error as Error).message).toBe( 'Expected one matching request for criteria "Match URL: /some-url", found none.' + ' Requests received are: GET /some-other-url?query=world, POST /and-another-url.', ); } }); it('throws if there are open requests when verify is called', () => { const mock = new HttpClientTestingBackend(); const client = new HttpClient(mock); client.get('/some-other-url?query=world').subscribe(); client.post('/and-another-url', {}).subscribe(); try { mock.verify(); fail(); } catch (error) { expect((error as any).message).toBe( 'Expected no open requests, found 2:' + ' GET /some-other-url?query=world, POST /and-another-url', ); } }); });
{ "end_byte": 3258, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/testing/test/request_spec.ts" }
angular/packages/common/http/testing/test/BUILD.bazel_0_864
load("//tools:defaults.bzl", "jasmine_node_test", "karma_web_test_suite", "ts_library") load("//tools/circular_dependency_test:index.bzl", "circular_dependency_test") circular_dependency_test( name = "circular_deps_test", entry_point = "angular/packages/common/http/testing/index.mjs", deps = ["//packages/common/http/testing"], ) ts_library( name = "test_lib", testonly = True, srcs = glob( ["**/*.ts"], ), # Visible to //:saucelabs_unit_tests_poc target visibility = ["//:__pkg__"], deps = [ "//packages/common/http", "//packages/common/http/testing", "@npm//rxjs", ], ) jasmine_node_test( name = "test", bootstrap = ["//tools/testing:node"], deps = [ ":test_lib", ], ) karma_web_test_suite( name = "test_web", deps = [ ":test_lib", ], )
{ "end_byte": 864, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/testing/test/BUILD.bazel" }
angular/packages/common/http/testing/src/module.ts_0_751
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {HttpClientModule} from '@angular/common/http'; import {NgModule} from '@angular/core'; import {provideHttpClientTesting} from './provider'; /** * Configures `HttpClientTestingBackend` as the `HttpBackend` used by `HttpClient`. * * Inject `HttpTestingController` to expect and flush requests in your tests. * * @publicApi * * @deprecated Add `provideHttpClientTesting()` to your providers instead. */ @NgModule({ imports: [HttpClientModule], providers: [provideHttpClientTesting()], }) export class HttpClientTestingModule {}
{ "end_byte": 751, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/testing/src/module.ts" }
angular/packages/common/http/testing/src/api.ts_0_4033
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {HttpRequest} from '@angular/common/http'; import {TestRequest} from './request'; /** * Defines a matcher for requests based on URL, method, or both. * * @publicApi */ export interface RequestMatch { method?: string; url?: string; } /** * Controller to be injected into tests, that allows for mocking and flushing * of requests. * * @publicApi */ export abstract class HttpTestingController { /** * Search for requests that match the given parameter, without any expectations. */ abstract match( match: string | RequestMatch | ((req: HttpRequest<any>) => boolean), ): TestRequest[]; /** * Expect that a single request has been made which matches the given URL, and return its * mock. * * If no such request has been made, or more than one such request has been made, fail with an * error message including the given request description, if any. */ abstract expectOne(url: string, description?: string): TestRequest; /** * Expect that a single request has been made which matches the given parameters, and return * its mock. * * If no such request has been made, or more than one such request has been made, fail with an * error message including the given request description, if any. */ abstract expectOne(params: RequestMatch, description?: string): TestRequest; /** * Expect that a single request has been made which matches the given predicate function, and * return its mock. * * If no such request has been made, or more than one such request has been made, fail with an * error message including the given request description, if any. */ abstract expectOne( matchFn: (req: HttpRequest<any>) => boolean, description?: string, ): TestRequest; /** * Expect that a single request has been made which matches the given condition, and return * its mock. * * If no such request has been made, or more than one such request has been made, fail with an * error message including the given request description, if any. */ abstract expectOne( match: string | RequestMatch | ((req: HttpRequest<any>) => boolean), description?: string, ): TestRequest; /** * Expect that no requests have been made which match the given URL. * * If a matching request has been made, fail with an error message including the given request * description, if any. */ abstract expectNone(url: string, description?: string): void; /** * Expect that no requests have been made which match the given parameters. * * If a matching request has been made, fail with an error message including the given request * description, if any. */ abstract expectNone(params: RequestMatch, description?: string): void; /** * Expect that no requests have been made which match the given predicate function. * * If a matching request has been made, fail with an error message including the given request * description, if any. */ abstract expectNone(matchFn: (req: HttpRequest<any>) => boolean, description?: string): void; /** * Expect that no requests have been made which match the given condition. * * If a matching request has been made, fail with an error message including the given request * description, if any. */ abstract expectNone( match: string | RequestMatch | ((req: HttpRequest<any>) => boolean), description?: string, ): void; /** * Verify that no unmatched requests are outstanding. * * If any requests are outstanding, fail with an error message indicating which requests were not * handled. * * If `ignoreCancelled` is not set (the default), `verify()` will also fail if cancelled requests * were not explicitly matched. */ abstract verify(opts?: {ignoreCancelled?: boolean}): void; }
{ "end_byte": 4033, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/testing/src/api.ts" }
angular/packages/common/http/testing/src/request.ts_0_7612
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { HttpErrorResponse, HttpEvent, HttpHeaders, HttpRequest, HttpResponse, HttpStatusCode, } from '@angular/common/http'; import {Observer} from 'rxjs'; /** * Type that describes options that can be used to create an error * in `TestRequest`. */ type TestRequestErrorOptions = { headers?: HttpHeaders | {[name: string]: string | string[]}; status?: number; statusText?: string; }; /** * A mock requests that was received and is ready to be answered. * * This interface allows access to the underlying `HttpRequest`, and allows * responding with `HttpEvent`s or `HttpErrorResponse`s. * * @publicApi */ export class TestRequest { /** * Whether the request was cancelled after it was sent. */ get cancelled(): boolean { return this._cancelled; } /** * @internal set by `HttpClientTestingBackend` */ _cancelled = false; constructor( public request: HttpRequest<any>, private observer: Observer<HttpEvent<any>>, ) {} /** * Resolve the request by returning a body plus additional HTTP information (such as response * headers) if provided. * If the request specifies an expected body type, the body is converted into the requested type. * Otherwise, the body is converted to `JSON` by default. * * Both successful and unsuccessful responses can be delivered via `flush()`. */ flush( body: | ArrayBuffer | Blob | boolean | string | number | Object | (boolean | string | number | Object | null)[] | null, opts: { headers?: HttpHeaders | {[name: string]: string | string[]}; status?: number; statusText?: string; } = {}, ): void { if (this.cancelled) { throw new Error(`Cannot flush a cancelled request.`); } const url = this.request.urlWithParams; const headers = opts.headers instanceof HttpHeaders ? opts.headers : new HttpHeaders(opts.headers); body = _maybeConvertBody(this.request.responseType, body); let statusText: string | undefined = opts.statusText; let status: number = opts.status !== undefined ? opts.status : HttpStatusCode.Ok; if (opts.status === undefined) { if (body === null) { status = HttpStatusCode.NoContent; statusText ||= 'No Content'; } else { statusText ||= 'OK'; } } if (statusText === undefined) { throw new Error('statusText is required when setting a custom status.'); } if (status >= 200 && status < 300) { this.observer.next(new HttpResponse<any>({body, headers, status, statusText, url})); this.observer.complete(); } else { this.observer.error(new HttpErrorResponse({error: body, headers, status, statusText, url})); } } /** * Resolve the request by returning an `ErrorEvent` (e.g. simulating a network failure). * @deprecated Http requests never emit an `ErrorEvent`. Please specify a `ProgressEvent`. */ error(error: ErrorEvent, opts?: TestRequestErrorOptions): void; /** * Resolve the request by returning an `ProgressEvent` (e.g. simulating a network failure). */ error(error: ProgressEvent, opts?: TestRequestErrorOptions): void; error(error: ProgressEvent | ErrorEvent, opts: TestRequestErrorOptions = {}): void { if (this.cancelled) { throw new Error(`Cannot return an error for a cancelled request.`); } if (opts.status && opts.status >= 200 && opts.status < 300) { throw new Error(`error() called with a successful status.`); } const headers = opts.headers instanceof HttpHeaders ? opts.headers : new HttpHeaders(opts.headers); this.observer.error( new HttpErrorResponse({ error, headers, status: opts.status || 0, statusText: opts.statusText || '', url: this.request.urlWithParams, }), ); } /** * Deliver an arbitrary `HttpEvent` (such as a progress event) on the response stream for this * request. */ event(event: HttpEvent<any>): void { if (this.cancelled) { throw new Error(`Cannot send events to a cancelled request.`); } this.observer.next(event); } } /** * Helper function to convert a response body to an ArrayBuffer. */ function _toArrayBufferBody( body: ArrayBuffer | Blob | string | number | Object | (string | number | Object | null)[], ): ArrayBuffer { if (typeof ArrayBuffer === 'undefined') { throw new Error('ArrayBuffer responses are not supported on this platform.'); } if (body instanceof ArrayBuffer) { return body; } throw new Error('Automatic conversion to ArrayBuffer is not supported for response type.'); } /** * Helper function to convert a response body to a Blob. */ function _toBlob( body: ArrayBuffer | Blob | string | number | Object | (string | number | Object | null)[], ): Blob { if (typeof Blob === 'undefined') { throw new Error('Blob responses are not supported on this platform.'); } if (body instanceof Blob) { return body; } if (ArrayBuffer && body instanceof ArrayBuffer) { return new Blob([body]); } throw new Error('Automatic conversion to Blob is not supported for response type.'); } /** * Helper function to convert a response body to JSON data. */ function _toJsonBody( body: | ArrayBuffer | Blob | boolean | string | number | Object | (boolean | string | number | Object | null)[], format: string = 'JSON', ): Object | string | number | (Object | string | number)[] { if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) { throw new Error(`Automatic conversion to ${format} is not supported for ArrayBuffers.`); } if (typeof Blob !== 'undefined' && body instanceof Blob) { throw new Error(`Automatic conversion to ${format} is not supported for Blobs.`); } if ( typeof body === 'string' || typeof body === 'number' || typeof body === 'object' || typeof body === 'boolean' || Array.isArray(body) ) { return body; } throw new Error(`Automatic conversion to ${format} is not supported for response type.`); } /** * Helper function to convert a response body to a string. */ function _toTextBody( body: ArrayBuffer | Blob | string | number | Object | (string | number | Object | null)[], ): string { if (typeof body === 'string') { return body; } if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) { throw new Error('Automatic conversion to text is not supported for ArrayBuffers.'); } if (typeof Blob !== 'undefined' && body instanceof Blob) { throw new Error('Automatic conversion to text is not supported for Blobs.'); } return JSON.stringify(_toJsonBody(body, 'text')); } /** * Convert a response body to the requested type. */ function _maybeConvertBody( responseType: string, body: ArrayBuffer | Blob | string | number | Object | (string | number | Object | null)[] | null, ): ArrayBuffer | Blob | string | number | Object | (string | number | Object | null)[] | null { if (body === null) { return null; } switch (responseType) { case 'arraybuffer': return _toArrayBufferBody(body); case 'blob': return _toBlob(body); case 'json': return _toJsonBody(body); case 'text': return _toTextBody(body); default: throw new Error(`Unsupported responseType: ${responseType}`); } }
{ "end_byte": 7612, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/testing/src/request.ts" }
angular/packages/common/http/testing/src/provider.ts_0_746
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {HttpBackend, ɵREQUESTS_CONTRIBUTE_TO_STABILITY} from '@angular/common/http'; import {Provider} from '@angular/core'; import {HttpTestingController} from './api'; import {HttpClientTestingBackend} from './backend'; export function provideHttpClientTesting(): Provider[] { return [ HttpClientTestingBackend, {provide: HttpBackend, useExisting: HttpClientTestingBackend}, {provide: HttpTestingController, useExisting: HttpClientTestingBackend}, {provide: ɵREQUESTS_CONTRIBUTE_TO_STABILITY, useValue: false}, ]; }
{ "end_byte": 746, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/testing/src/provider.ts" }
angular/packages/common/http/testing/src/backend.ts_0_5597
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {HttpBackend, HttpEvent, HttpEventType, HttpRequest} from '@angular/common/http'; import {Injectable} from '@angular/core'; import {Observable, Observer} from 'rxjs'; import {HttpTestingController, RequestMatch} from './api'; import {TestRequest} from './request'; /** * A testing backend for `HttpClient` which both acts as an `HttpBackend` * and as the `HttpTestingController`. * * `HttpClientTestingBackend` works by keeping a list of all open requests. * As requests come in, they're added to the list. Users can assert that specific * requests were made and then flush them. In the end, a verify() method asserts * that no unexpected requests were made. * * */ @Injectable() export class HttpClientTestingBackend implements HttpBackend, HttpTestingController { /** * List of pending requests which have not yet been expected. */ private open: TestRequest[] = []; /** * Handle an incoming request by queueing it in the list of open requests. */ handle(req: HttpRequest<any>): Observable<HttpEvent<any>> { return new Observable((observer: Observer<any>) => { const testReq = new TestRequest(req, observer); this.open.push(testReq); observer.next({type: HttpEventType.Sent} as HttpEvent<any>); return () => { testReq._cancelled = true; }; }); } /** * Helper function to search for requests in the list of open requests. */ private _match( match: string | RequestMatch | ((req: HttpRequest<any>) => boolean), ): TestRequest[] { if (typeof match === 'string') { return this.open.filter((testReq) => testReq.request.urlWithParams === match); } else if (typeof match === 'function') { return this.open.filter((testReq) => match(testReq.request)); } else { return this.open.filter( (testReq) => (!match.method || testReq.request.method === match.method.toUpperCase()) && (!match.url || testReq.request.urlWithParams === match.url), ); } } /** * Search for requests in the list of open requests, and return all that match * without asserting anything about the number of matches. */ match(match: string | RequestMatch | ((req: HttpRequest<any>) => boolean)): TestRequest[] { const results = this._match(match); results.forEach((result) => { const index = this.open.indexOf(result); if (index !== -1) { this.open.splice(index, 1); } }); return results; } /** * Expect that a single outstanding request matches the given matcher, and return * it. * * Requests returned through this API will no longer be in the list of open requests, * and thus will not match twice. */ expectOne( match: string | RequestMatch | ((req: HttpRequest<any>) => boolean), description?: string, ): TestRequest { description ||= this.descriptionFromMatcher(match); const matches = this.match(match); if (matches.length > 1) { throw new Error( `Expected one matching request for criteria "${description}", found ${matches.length} requests.`, ); } if (matches.length === 0) { let message = `Expected one matching request for criteria "${description}", found none.`; if (this.open.length > 0) { // Show the methods and URLs of open requests in the error, for convenience. const requests = this.open.map(describeRequest).join(', '); message += ` Requests received are: ${requests}.`; } throw new Error(message); } return matches[0]; } /** * Expect that no outstanding requests match the given matcher, and throw an error * if any do. */ expectNone( match: string | RequestMatch | ((req: HttpRequest<any>) => boolean), description?: string, ): void { description ||= this.descriptionFromMatcher(match); const matches = this.match(match); if (matches.length > 0) { throw new Error( `Expected zero matching requests for criteria "${description}", found ${matches.length}.`, ); } } /** * Validate that there are no outstanding requests. */ verify(opts: {ignoreCancelled?: boolean} = {}): void { let open = this.open; // It's possible that some requests may be cancelled, and this is expected. // The user can ask to ignore open requests which have been cancelled. if (opts.ignoreCancelled) { open = open.filter((testReq) => !testReq.cancelled); } if (open.length > 0) { // Show the methods and URLs of open requests in the error, for convenience. const requests = open.map(describeRequest).join(', '); throw new Error(`Expected no open requests, found ${open.length}: ${requests}`); } } private descriptionFromMatcher( matcher: string | RequestMatch | ((req: HttpRequest<any>) => boolean), ): string { if (typeof matcher === 'string') { return `Match URL: ${matcher}`; } else if (typeof matcher === 'object') { const method = matcher.method || '(any)'; const url = matcher.url || '(any)'; return `Match method: ${method}, URL: ${url}`; } else { return `Match by function: ${matcher.name}`; } } } function describeRequest(testRequest: TestRequest): string { const url = testRequest.request.urlWithParams; const method = testRequest.request.method; return `${method} ${url}`; }
{ "end_byte": 5597, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/testing/src/backend.ts" }
angular/packages/common/http/src/transfer_cache.ts_0_8578
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { APP_BOOTSTRAP_LISTENER, ApplicationRef, inject, InjectionToken, makeStateKey, PLATFORM_ID, Provider, StateKey, TransferState, ɵformatRuntimeError as formatRuntimeError, ɵperformanceMarkFeature as performanceMarkFeature, ɵtruncateMiddle as truncateMiddle, ɵwhenStable as whenStable, ɵRuntimeError as RuntimeError, } from '@angular/core'; import {isPlatformServer} from '@angular/common'; import {Observable, of} from 'rxjs'; import {tap} from 'rxjs/operators'; import {RuntimeErrorCode} from './errors'; import {HttpHeaders} from './headers'; import {HTTP_ROOT_INTERCEPTOR_FNS, HttpHandlerFn} from './interceptor'; import {HttpRequest} from './request'; import {HttpEvent, HttpResponse} from './response'; import {HttpParams} from './params'; /** * Options to configure how TransferCache should be used to cache requests made via HttpClient. * * @param includeHeaders Specifies which headers should be included into cached responses. No * headers are included by default. * @param filter A function that receives a request as an argument and returns a boolean to indicate * whether a request should be included into the cache. * @param includePostRequests Enables caching for POST requests. By default, only GET and HEAD * requests are cached. This option can be enabled if POST requests are used to retrieve data * (for example using GraphQL). * @param includeRequestsWithAuthHeaders Enables caching of requests containing either `Authorization` * or `Proxy-Authorization` headers. By default, these requests are excluded from caching. * * @publicApi */ export type HttpTransferCacheOptions = { includeHeaders?: string[]; filter?: (req: HttpRequest<unknown>) => boolean; includePostRequests?: boolean; includeRequestsWithAuthHeaders?: boolean; }; /** * If your application uses different HTTP origins to make API calls (via `HttpClient`) on the server and * on the client, the `HTTP_TRANSFER_CACHE_ORIGIN_MAP` token allows you to establish a mapping * between those origins, so that `HttpTransferCache` feature can recognize those requests as the same * ones and reuse the data cached on the server during hydration on the client. * * **Important note**: the `HTTP_TRANSFER_CACHE_ORIGIN_MAP` token should *only* be provided in * the *server* code of your application (typically in the `app.server.config.ts` script). Angular throws an * error if it detects that the token is defined while running on the client. * * @usageNotes * * When the same API endpoint is accessed via `http://internal-domain.com:8080` on the server and * via `https://external-domain.com` on the client, you can use the following configuration: * ```typescript * // in app.server.config.ts * { * provide: HTTP_TRANSFER_CACHE_ORIGIN_MAP, * useValue: { * 'http://internal-domain.com:8080': 'https://external-domain.com' * } * } * ``` * * @publicApi */ export const HTTP_TRANSFER_CACHE_ORIGIN_MAP = new InjectionToken<Record<string, string>>( ngDevMode ? 'HTTP_TRANSFER_CACHE_ORIGIN_MAP' : '', ); /** * Keys within cached response data structure. */ export const BODY = 'b'; export const HEADERS = 'h'; export const STATUS = 's'; export const STATUS_TEXT = 'st'; export const REQ_URL = 'u'; export const RESPONSE_TYPE = 'rt'; interface TransferHttpResponse { /** body */ [BODY]: any; /** headers */ [HEADERS]: Record<string, string[]>; /** status */ [STATUS]?: number; /** statusText */ [STATUS_TEXT]?: string; /** url */ [REQ_URL]?: string; /** responseType */ [RESPONSE_TYPE]?: HttpRequest<unknown>['responseType']; } interface CacheOptions extends HttpTransferCacheOptions { isCacheActive: boolean; } const CACHE_OPTIONS = new InjectionToken<CacheOptions>( ngDevMode ? 'HTTP_TRANSFER_STATE_CACHE_OPTIONS' : '', ); /** * A list of allowed HTTP methods to cache. */ const ALLOWED_METHODS = ['GET', 'HEAD']; export function transferCacheInterceptorFn( req: HttpRequest<unknown>, next: HttpHandlerFn, ): Observable<HttpEvent<unknown>> { const {isCacheActive, ...globalOptions} = inject(CACHE_OPTIONS); const {transferCache: requestOptions, method: requestMethod} = req; // In the following situations we do not want to cache the request if ( !isCacheActive || requestOptions === false || // POST requests are allowed either globally or at request level (requestMethod === 'POST' && !globalOptions.includePostRequests && !requestOptions) || (requestMethod !== 'POST' && !ALLOWED_METHODS.includes(requestMethod)) || // Do not cache request that require authorization when includeRequestsWithAuthHeaders is falsey (!globalOptions.includeRequestsWithAuthHeaders && hasAuthHeaders(req)) || globalOptions.filter?.(req) === false ) { return next(req); } const transferState = inject(TransferState); const originMap: Record<string, string> | null = inject(HTTP_TRANSFER_CACHE_ORIGIN_MAP, { optional: true, }); const isServer = isPlatformServer(inject(PLATFORM_ID)); if (originMap && !isServer) { throw new RuntimeError( RuntimeErrorCode.HTTP_ORIGIN_MAP_USED_IN_CLIENT, ngDevMode && 'Angular detected that the `HTTP_TRANSFER_CACHE_ORIGIN_MAP` token is configured and ' + 'present in the client side code. Please ensure that this token is only provided in the ' + 'server code of the application.', ); } const requestUrl = isServer && originMap ? mapRequestOriginUrl(req.url, originMap) : req.url; const storeKey = makeCacheKey(req, requestUrl); const response = transferState.get(storeKey, null); let headersToInclude = globalOptions.includeHeaders; if (typeof requestOptions === 'object' && requestOptions.includeHeaders) { // Request-specific config takes precedence over the global config. headersToInclude = requestOptions.includeHeaders; } if (response) { const { [BODY]: undecodedBody, [RESPONSE_TYPE]: responseType, [HEADERS]: httpHeaders, [STATUS]: status, [STATUS_TEXT]: statusText, [REQ_URL]: url, } = response; // Request found in cache. Respond using it. let body: ArrayBuffer | Blob | string | undefined = undecodedBody; switch (responseType) { case 'arraybuffer': body = new TextEncoder().encode(undecodedBody).buffer; break; case 'blob': body = new Blob([undecodedBody]); break; } // We want to warn users accessing a header provided from the cache // That HttpTransferCache alters the headers // The warning will be logged a single time by HttpHeaders instance let headers = new HttpHeaders(httpHeaders); if (typeof ngDevMode === 'undefined' || ngDevMode) { // Append extra logic in dev mode to produce a warning when a header // that was not transferred to the client is accessed in the code via `get` // and `has` calls. headers = appendMissingHeadersDetection(req.url, headers, headersToInclude ?? []); } return of( new HttpResponse({ body, headers, status, statusText, url, }), ); } // Request not found in cache. Make the request and cache it if on the server. return next(req).pipe( tap((event: HttpEvent<unknown>) => { if (event instanceof HttpResponse && isServer) { transferState.set<TransferHttpResponse>(storeKey, { [BODY]: event.body, [HEADERS]: getFilteredHeaders(event.headers, headersToInclude), [STATUS]: event.status, [STATUS_TEXT]: event.statusText, [REQ_URL]: requestUrl, [RESPONSE_TYPE]: req.responseType, }); } }), ); } /** @returns true when the requests contains autorization related headers. */ function hasAuthHeaders(req: HttpRequest<unknown>): boolean { return req.headers.has('authorization') || req.headers.has('proxy-authorization'); } function getFilteredHeaders( headers: HttpHeaders, includeHeaders: string[] | undefined, ): Record<string, string[]> { if (!includeHeaders) { return {}; } const headersMap: Record<string, string[]> = {}; for (const key of includeHeaders) { const values = headers.getAll(key); if (values !== null) { headersMap[key] = values; } } return headersMap; } fun
{ "end_byte": 8578, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/transfer_cache.ts" }
angular/packages/common/http/src/transfer_cache.ts_8580_14025
ion sortAndConcatParams(params: HttpParams | URLSearchParams): string { return [...params.keys()] .sort() .map((k) => `${k}=${params.getAll(k)}`) .join('&'); } function makeCacheKey( request: HttpRequest<any>, mappedRequestUrl: string, ): StateKey<TransferHttpResponse> { // make the params encoded same as a url so it's easy to identify const {params, method, responseType} = request; const encodedParams = sortAndConcatParams(params); let serializedBody = request.serializeBody(); if (serializedBody instanceof URLSearchParams) { serializedBody = sortAndConcatParams(serializedBody); } else if (typeof serializedBody !== 'string') { serializedBody = ''; } const key = [method, responseType, mappedRequestUrl, serializedBody, encodedParams].join('|'); const hash = generateHash(key); return makeStateKey(hash); } /** * A method that returns a hash representation of a string using a variant of DJB2 hash * algorithm. * * This is the same hashing logic that is used to generate component ids. */ function generateHash(value: string): string { let hash = 0; for (const char of value) { hash = (Math.imul(31, hash) + char.charCodeAt(0)) << 0; } // Force positive number hash. // 2147483647 = equivalent of Integer.MAX_VALUE. hash += 2147483647 + 1; return hash.toString(); } /** * Returns the DI providers needed to enable HTTP transfer cache. * * By default, when using server rendering, requests are performed twice: once on the server and * other one on the browser. * * When these providers are added, requests performed on the server are cached and reused during the * bootstrapping of the application in the browser thus avoiding duplicate requests and reducing * load time. * */ export function withHttpTransferCache(cacheOptions: HttpTransferCacheOptions): Provider[] { return [ { provide: CACHE_OPTIONS, useFactory: (): CacheOptions => { performanceMarkFeature('NgHttpTransferCache'); return {isCacheActive: true, ...cacheOptions}; }, }, { provide: HTTP_ROOT_INTERCEPTOR_FNS, useValue: transferCacheInterceptorFn, multi: true, deps: [TransferState, CACHE_OPTIONS], }, { provide: APP_BOOTSTRAP_LISTENER, multi: true, useFactory: () => { const appRef = inject(ApplicationRef); const cacheState = inject(CACHE_OPTIONS); return () => { whenStable(appRef).then(() => { cacheState.isCacheActive = false; }); }; }, }, ]; } /** * This function will add a proxy to an HttpHeader to intercept calls to get/has * and log a warning if the header entry requested has been removed */ function appendMissingHeadersDetection( url: string, headers: HttpHeaders, headersToInclude: string[], ): HttpHeaders { const warningProduced = new Set(); return new Proxy<HttpHeaders>(headers, { get(target: HttpHeaders, prop: keyof HttpHeaders): unknown { const value = Reflect.get(target, prop); const methods: Set<keyof HttpHeaders> = new Set(['get', 'has', 'getAll']); if (typeof value !== 'function' || !methods.has(prop)) { return value; } return (headerName: string) => { // We log when the key has been removed and a warning hasn't been produced for the header const key = (prop + ':' + headerName).toLowerCase(); // e.g. `get:cache-control` if (!headersToInclude.includes(headerName) && !warningProduced.has(key)) { warningProduced.add(key); const truncatedUrl = truncateMiddle(url); // TODO: create Error guide for this warning console.warn( formatRuntimeError( RuntimeErrorCode.HEADERS_ALTERED_BY_TRANSFER_CACHE, `Angular detected that the \`${headerName}\` header is accessed, but the value of the header ` + `was not transferred from the server to the client by the HttpTransferCache. ` + `To include the value of the \`${headerName}\` header for the \`${truncatedUrl}\` request, ` + `use the \`includeHeaders\` list. The \`includeHeaders\` can be defined either ` + `on a request level by adding the \`transferCache\` parameter, or on an application ` + `level by adding the \`httpCacheTransfer.includeHeaders\` argument to the ` + `\`provideClientHydration()\` call. `, ), ); } // invoking the original method return (value as Function).apply(target, [headerName]); }; }, }); } function mapRequestOriginUrl(url: string, originMap: Record<string, string>): string { const origin = new URL(url, 'resolve://').origin; const mappedOrigin = originMap[origin]; if (!mappedOrigin) { return url; } if (typeof ngDevMode === 'undefined' || ngDevMode) { verifyMappedOrigin(mappedOrigin); } return url.replace(origin, mappedOrigin); } function verifyMappedOrigin(url: string): void { if (new URL(url, 'resolve://').pathname !== '/') { throw new RuntimeError( RuntimeErrorCode.HTTP_ORIGIN_MAP_CONTAINS_PATH, 'Angular detected a URL with a path segment in the value provided for the ' + `\`HTTP_TRANSFER_CACHE_ORIGIN_MAP\` token: ${url}. The map should only contain origins ` + 'without any other segments.', ); } }
{ "end_byte": 14025, "start_byte": 8580, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/transfer_cache.ts" }
angular/packages/common/http/src/headers.ts_0_8662
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ interface Update { name: string; value?: string | string[]; op: 'a' | 's' | 'd'; } /** * Represents the header configuration options for an HTTP request. * Instances are immutable. Modifying methods return a cloned * instance with the change. The original object is never changed. * * @publicApi */ export class HttpHeaders { /** * Internal map of lowercase header names to values. */ // TODO(issue/24571): remove '!'. private headers!: Map<string, string[]>; /** * Internal map of lowercased header names to the normalized * form of the name (the form seen first). */ private normalizedNames: Map<string, string> = new Map(); /** * Complete the lazy initialization of this object (needed before reading). */ private lazyInit!: HttpHeaders | Function | null; /** * Queued updates to be materialized the next initialization. */ private lazyUpdate: Update[] | null = null; /** Constructs a new HTTP header object with the given values.*/ constructor( headers?: string | {[name: string]: string | number | (string | number)[]} | Headers, ) { if (!headers) { this.headers = new Map<string, string[]>(); } else if (typeof headers === 'string') { this.lazyInit = () => { this.headers = new Map<string, string[]>(); headers.split('\n').forEach((line) => { const index = line.indexOf(':'); if (index > 0) { const name = line.slice(0, index); const value = line.slice(index + 1).trim(); this.addHeaderEntry(name, value); } }); }; } else if (typeof Headers !== 'undefined' && headers instanceof Headers) { this.headers = new Map<string, string[]>(); headers.forEach((value: string, name: string) => { this.addHeaderEntry(name, value); }); } else { this.lazyInit = () => { if (typeof ngDevMode === 'undefined' || ngDevMode) { assertValidHeaders(headers); } this.headers = new Map<string, string[]>(); Object.entries(headers).forEach(([name, values]) => { this.setHeaderEntries(name, values); }); }; } } /** * Checks for existence of a given header. * * @param name The header name to check for existence. * * @returns True if the header exists, false otherwise. */ has(name: string): boolean { this.init(); return this.headers.has(name.toLowerCase()); } /** * Retrieves the first value of a given header. * * @param name The header name. * * @returns The value string if the header exists, null otherwise */ get(name: string): string | null { this.init(); const values = this.headers.get(name.toLowerCase()); return values && values.length > 0 ? values[0] : null; } /** * Retrieves the names of the headers. * * @returns A list of header names. */ keys(): string[] { this.init(); return Array.from(this.normalizedNames.values()); } /** * Retrieves a list of values for a given header. * * @param name The header name from which to retrieve values. * * @returns A string of values if the header exists, null otherwise. */ getAll(name: string): string[] | null { this.init(); return this.headers.get(name.toLowerCase()) || null; } /** * Appends a new value to the existing set of values for a header * and returns them in a clone of the original instance. * * @param name The header name for which to append the values. * @param value The value to append. * * @returns A clone of the HTTP headers object with the value appended to the given header. */ append(name: string, value: string | string[]): HttpHeaders { return this.clone({name, value, op: 'a'}); } /** * Sets or modifies a value for a given header in a clone of the original instance. * If the header already exists, its value is replaced with the given value * in the returned object. * * @param name The header name. * @param value The value or values to set or override for the given header. * * @returns A clone of the HTTP headers object with the newly set header value. */ set(name: string, value: string | string[]): HttpHeaders { return this.clone({name, value, op: 's'}); } /** * Deletes values for a given header in a clone of the original instance. * * @param name The header name. * @param value The value or values to delete for the given header. * * @returns A clone of the HTTP headers object with the given value deleted. */ delete(name: string, value?: string | string[]): HttpHeaders { return this.clone({name, value, op: 'd'}); } private maybeSetNormalizedName(name: string, lcName: string): void { if (!this.normalizedNames.has(lcName)) { this.normalizedNames.set(lcName, name); } } private init(): void { if (!!this.lazyInit) { if (this.lazyInit instanceof HttpHeaders) { this.copyFrom(this.lazyInit); } else { this.lazyInit(); } this.lazyInit = null; if (!!this.lazyUpdate) { this.lazyUpdate.forEach((update) => this.applyUpdate(update)); this.lazyUpdate = null; } } } private copyFrom(other: HttpHeaders) { other.init(); Array.from(other.headers.keys()).forEach((key) => { this.headers.set(key, other.headers.get(key)!); this.normalizedNames.set(key, other.normalizedNames.get(key)!); }); } private clone(update: Update): HttpHeaders { const clone = new HttpHeaders(); clone.lazyInit = !!this.lazyInit && this.lazyInit instanceof HttpHeaders ? this.lazyInit : this; clone.lazyUpdate = (this.lazyUpdate || []).concat([update]); return clone; } private applyUpdate(update: Update): void { const key = update.name.toLowerCase(); switch (update.op) { case 'a': case 's': let value = update.value!; if (typeof value === 'string') { value = [value]; } if (value.length === 0) { return; } this.maybeSetNormalizedName(update.name, key); const base = (update.op === 'a' ? this.headers.get(key) : undefined) || []; base.push(...value); this.headers.set(key, base); break; case 'd': const toDelete = update.value as string | undefined; if (!toDelete) { this.headers.delete(key); this.normalizedNames.delete(key); } else { let existing = this.headers.get(key); if (!existing) { return; } existing = existing.filter((value) => toDelete.indexOf(value) === -1); if (existing.length === 0) { this.headers.delete(key); this.normalizedNames.delete(key); } else { this.headers.set(key, existing); } } break; } } private addHeaderEntry(name: string, value: string) { const key = name.toLowerCase(); this.maybeSetNormalizedName(name, key); if (this.headers.has(key)) { this.headers.get(key)!.push(value); } else { this.headers.set(key, [value]); } } private setHeaderEntries(name: string, values: any) { const headerValues = (Array.isArray(values) ? values : [values]).map((value) => value.toString(), ); const key = name.toLowerCase(); this.headers.set(key, headerValues); this.maybeSetNormalizedName(name, key); } /** * @internal */ forEach(fn: (name: string, values: string[]) => void) { this.init(); Array.from(this.normalizedNames.keys()).forEach((key) => fn(this.normalizedNames.get(key)!, this.headers.get(key)!), ); } } /** * Verifies that the headers object has the right shape: the values * must be either strings, numbers or arrays. Throws an error if an invalid * header value is present. */ function assertValidHeaders( headers: Record<string, unknown> | Headers, ): asserts headers is Record<string, string | string[] | number | number[]> { for (const [key, value] of Object.entries(headers)) { if (!(typeof value === 'string' || typeof value === 'number') && !Array.isArray(value)) { throw new Error( `Unexpected value of the \`${key}\` header provided. ` + `Expecting either a string, a number or an array, but got: \`${value}\`.`, ); } } }
{ "end_byte": 8662, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/headers.ts" }
angular/packages/common/http/src/module.ts_0_3392
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {ModuleWithProviders, NgModule} from '@angular/core'; import {HTTP_INTERCEPTORS} from './interceptor'; import { provideHttpClient, withInterceptorsFromDi, withJsonpSupport, withNoXsrfProtection, withXsrfConfiguration, } from './provider'; import { HttpXsrfCookieExtractor, HttpXsrfInterceptor, HttpXsrfTokenExtractor, XSRF_DEFAULT_COOKIE_NAME, XSRF_DEFAULT_HEADER_NAME, XSRF_ENABLED, } from './xsrf'; /** * Configures XSRF protection support for outgoing requests. * * For a server that supports a cookie-based XSRF protection system, * use directly to configure XSRF protection with the correct * cookie and header names. * * If no names are supplied, the default cookie name is `XSRF-TOKEN` * and the default header name is `X-XSRF-TOKEN`. * * @publicApi * @deprecated Use withXsrfConfiguration({cookieName: 'XSRF-TOKEN', headerName: 'X-XSRF-TOKEN'}) as * providers instead or `withNoXsrfProtection` if you want to disabled XSRF protection. */ @NgModule({ providers: [ HttpXsrfInterceptor, {provide: HTTP_INTERCEPTORS, useExisting: HttpXsrfInterceptor, multi: true}, {provide: HttpXsrfTokenExtractor, useClass: HttpXsrfCookieExtractor}, withXsrfConfiguration({ cookieName: XSRF_DEFAULT_COOKIE_NAME, headerName: XSRF_DEFAULT_HEADER_NAME, }).ɵproviders, {provide: XSRF_ENABLED, useValue: true}, ], }) export class HttpClientXsrfModule { /** * Disable the default XSRF protection. */ static disable(): ModuleWithProviders<HttpClientXsrfModule> { return { ngModule: HttpClientXsrfModule, providers: [withNoXsrfProtection().ɵproviders], }; } /** * Configure XSRF protection. * @param options An object that can specify either or both * cookie name or header name. * - Cookie name default is `XSRF-TOKEN`. * - Header name default is `X-XSRF-TOKEN`. * */ static withOptions( options: { cookieName?: string; headerName?: string; } = {}, ): ModuleWithProviders<HttpClientXsrfModule> { return { ngModule: HttpClientXsrfModule, providers: withXsrfConfiguration(options).ɵproviders, }; } } /** * Configures the dependency injector for `HttpClient` * with supporting services for XSRF. Automatically imported by `HttpClientModule`. * * You can add interceptors to the chain behind `HttpClient` by binding them to the * multiprovider for built-in DI token `HTTP_INTERCEPTORS`. * * @publicApi * @deprecated use `provideHttpClient(withInterceptorsFromDi())` as providers instead */ @NgModule({ /** * Configures the dependency injector where it is imported * with supporting services for HTTP communications. */ providers: [provideHttpClient(withInterceptorsFromDi())], }) export class HttpClientModule {} /** * Configures the dependency injector for `HttpClient` * with supporting services for JSONP. * Without this module, Jsonp requests reach the backend * with method JSONP, where they are rejected. * * @publicApi * @deprecated `withJsonpSupport()` as providers instead */ @NgModule({ providers: [withJsonpSupport().ɵproviders], }) export class HttpClientJsonpModule {}
{ "end_byte": 3392, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/module.ts" }
angular/packages/common/http/src/errors.ts_0_568
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * The list of error codes used in runtime code of the `common/http` package. * Reserved error code range: 2800-2899. */ export const enum RuntimeErrorCode { MISSING_JSONP_MODULE = -2800, NOT_USING_FETCH_BACKEND_IN_SSR = 2801, HEADERS_ALTERED_BY_TRANSFER_CACHE = 2802, HTTP_ORIGIN_MAP_USED_IN_CLIENT = 2803, HTTP_ORIGIN_MAP_CONTAINS_PATH = 2804, }
{ "end_byte": 568, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/errors.ts" }
angular/packages/common/http/src/interceptor.ts_0_8500
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {isPlatformServer} from '@angular/common'; import { EnvironmentInjector, inject, Injectable, InjectionToken, PLATFORM_ID, runInInjectionContext, ɵConsole as Console, ɵformatRuntimeError as formatRuntimeError, ɵPendingTasks as PendingTasks, } from '@angular/core'; import {Observable} from 'rxjs'; import {finalize} from 'rxjs/operators'; import {HttpBackend, HttpHandler} from './backend'; import {RuntimeErrorCode} from './errors'; import {FetchBackend} from './fetch'; import {HttpRequest} from './request'; import {HttpEvent} from './response'; /** * Intercepts and handles an `HttpRequest` or `HttpResponse`. * * Most interceptors transform the outgoing request before passing it to the * next interceptor in the chain, by calling `next.handle(transformedReq)`. * An interceptor may transform the * response event stream as well, by applying additional RxJS operators on the stream * returned by `next.handle()`. * * More rarely, an interceptor may handle the request entirely, * and compose a new event stream instead of invoking `next.handle()`. This is an * acceptable behavior, but keep in mind that further interceptors will be skipped entirely. * * It is also rare but valid for an interceptor to return multiple responses on the * event stream for a single request. * * @publicApi * * @see [HTTP Guide](guide/http/interceptors) * @see {@link HttpInterceptorFn} * * @usageNotes * * To use the same instance of `HttpInterceptors` for the entire app, import the `HttpClientModule` * only in your `AppModule`, and add the interceptors to the root application injector. * If you import `HttpClientModule` multiple times across different modules (for example, in lazy * loading modules), each import creates a new copy of the `HttpClientModule`, which overwrites the * interceptors provided in the root module. */ export interface HttpInterceptor { /** * Identifies and handles a given HTTP request. * @param req The outgoing request object to handle. * @param next The next interceptor in the chain, or the backend * if no interceptors remain in the chain. * @returns An observable of the event stream. */ intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>; } /** * Represents the next interceptor in an interceptor chain, or the real backend if there are no * further interceptors. * * Most interceptors will delegate to this function, and either modify the outgoing request or the * response when it arrives. Within the scope of the current request, however, this function may be * called any number of times, for any number of downstream requests. Such downstream requests need * not be to the same URL or even the same origin as the current request. It is also valid to not * call the downstream handler at all, and process the current request entirely within the * interceptor. * * This function should only be called within the scope of the request that's currently being * intercepted. Once that request is complete, this downstream handler function should not be * called. * * @publicApi * * @see [HTTP Guide](guide/http/interceptors) */ export type HttpHandlerFn = (req: HttpRequest<unknown>) => Observable<HttpEvent<unknown>>; /** * An interceptor for HTTP requests made via `HttpClient`. * * `HttpInterceptorFn`s are middleware functions which `HttpClient` calls when a request is made. * These functions have the opportunity to modify the outgoing request or any response that comes * back, as well as block, redirect, or otherwise change the request or response semantics. * * An `HttpHandlerFn` representing the next interceptor (or the backend which will make a real HTTP * request) is provided. Most interceptors will delegate to this function, but that is not required * (see `HttpHandlerFn` for more details). * * `HttpInterceptorFn`s are executed in an [injection context](guide/di/dependency-injection-context). * They have access to `inject()` via the `EnvironmentInjector` from which they were configured. * * @see [HTTP Guide](guide/http/interceptors) * @see {@link withInterceptors} * * @usageNotes * Here is a noop interceptor that passes the request through without modifying it: * ```typescript * export const noopInterceptor: HttpInterceptorFn = (req: HttpRequest<unknown>, next: * HttpHandlerFn) => { * return next(modifiedReq); * }; * ``` * * If you want to alter a request, clone it first and modify the clone before passing it to the * `next()` handler function. * * Here is a basic interceptor that adds a bearer token to the headers * ```typescript * export const authenticationInterceptor: HttpInterceptorFn = (req: HttpRequest<unknown>, next: * HttpHandlerFn) => { * const userToken = 'MY_TOKEN'; const modifiedReq = req.clone({ * headers: req.headers.set('Authorization', `Bearer ${userToken}`), * }); * * return next(modifiedReq); * }; * ``` */ export type HttpInterceptorFn = ( req: HttpRequest<unknown>, next: HttpHandlerFn, ) => Observable<HttpEvent<unknown>>; /** * Function which invokes an HTTP interceptor chain. * * Each interceptor in the interceptor chain is turned into a `ChainedInterceptorFn` which closes * over the rest of the chain (represented by another `ChainedInterceptorFn`). The last such * function in the chain will instead delegate to the `finalHandlerFn`, which is passed down when * the chain is invoked. * * This pattern allows for a chain of many interceptors to be composed and wrapped in a single * `HttpInterceptorFn`, which is a useful abstraction for including different kinds of interceptors * (e.g. legacy class-based interceptors) in the same chain. */ type ChainedInterceptorFn<RequestT> = ( req: HttpRequest<RequestT>, finalHandlerFn: HttpHandlerFn, ) => Observable<HttpEvent<RequestT>>; function interceptorChainEndFn( req: HttpRequest<any>, finalHandlerFn: HttpHandlerFn, ): Observable<HttpEvent<any>> { return finalHandlerFn(req); } /** * Constructs a `ChainedInterceptorFn` which adapts a legacy `HttpInterceptor` to the * `ChainedInterceptorFn` interface. */ function adaptLegacyInterceptorToChain( chainTailFn: ChainedInterceptorFn<any>, interceptor: HttpInterceptor, ): ChainedInterceptorFn<any> { return (initialRequest, finalHandlerFn) => interceptor.intercept(initialRequest, { handle: (downstreamRequest) => chainTailFn(downstreamRequest, finalHandlerFn), }); } /** * Constructs a `ChainedInterceptorFn` which wraps and invokes a functional interceptor in the given * injector. */ function chainedInterceptorFn( chainTailFn: ChainedInterceptorFn<unknown>, interceptorFn: HttpInterceptorFn, injector: EnvironmentInjector, ): ChainedInterceptorFn<unknown> { return (initialRequest, finalHandlerFn) => runInInjectionContext(injector, () => interceptorFn(initialRequest, (downstreamRequest) => chainTailFn(downstreamRequest, finalHandlerFn), ), ); } /** * A multi-provider token that represents the array of registered * `HttpInterceptor` objects. * * @publicApi */ export const HTTP_INTERCEPTORS = new InjectionToken<readonly HttpInterceptor[]>( ngDevMode ? 'HTTP_INTERCEPTORS' : '', ); /** * A multi-provided token of `HttpInterceptorFn`s. */ export const HTTP_INTERCEPTOR_FNS = new InjectionToken<readonly HttpInterceptorFn[]>( ngDevMode ? 'HTTP_INTERCEPTOR_FNS' : '', ); /** * A multi-provided token of `HttpInterceptorFn`s that are only set in root. */ export const HTTP_ROOT_INTERCEPTOR_FNS = new InjectionToken<readonly HttpInterceptorFn[]>( ngDevMode ? 'HTTP_ROOT_INTERCEPTOR_FNS' : '', ); // TODO(atscott): We need a larger discussion about stability and what should contribute to stability. // Should the whole interceptor chain contribute to stability or just the backend request #55075? // Should HttpClient contribute to stability automatically at all? export const REQUESTS_CONTRIBUTE_TO_STABILITY = new InjectionToken<boolean>( ngDevMode ? 'REQUESTS_CONTRIBUTE_TO_STABILITY' : '', {providedIn: 'root', factory: () => true}, ); /** * Creates an `HttpInterceptorFn` which lazily initializes an interceptor chain from the legacy * class-based interceptors and runs the request through it. */ ex
{ "end_byte": 8500, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/interceptor.ts" }
angular/packages/common/http/src/interceptor.ts_8501_12476
ort function legacyInterceptorFnFactory(): HttpInterceptorFn { let chain: ChainedInterceptorFn<any> | null = null; return (req, handler) => { if (chain === null) { const interceptors = inject(HTTP_INTERCEPTORS, {optional: true}) ?? []; // Note: interceptors are wrapped right-to-left so that final execution order is // left-to-right. That is, if `interceptors` is the array `[a, b, c]`, we want to // produce a chain that is conceptually `c(b(a(end)))`, which we build from the inside // out. chain = interceptors.reduceRight( adaptLegacyInterceptorToChain, interceptorChainEndFn as ChainedInterceptorFn<any>, ); } const pendingTasks = inject(PendingTasks); const contributeToStability = inject(REQUESTS_CONTRIBUTE_TO_STABILITY); if (contributeToStability) { const taskId = pendingTasks.add(); return chain(req, handler).pipe(finalize(() => pendingTasks.remove(taskId))); } else { return chain(req, handler); } }; } let fetchBackendWarningDisplayed = false; /** Internal function to reset the flag in tests */ export function resetFetchBackendWarningFlag() { fetchBackendWarningDisplayed = false; } @Injectable() export class HttpInterceptorHandler extends HttpHandler { private chain: ChainedInterceptorFn<unknown> | null = null; private readonly pendingTasks = inject(PendingTasks); private readonly contributeToStability = inject(REQUESTS_CONTRIBUTE_TO_STABILITY); constructor( private backend: HttpBackend, private injector: EnvironmentInjector, ) { super(); // We strongly recommend using fetch backend for HTTP calls when SSR is used // for an application. The logic below checks if that's the case and produces // a warning otherwise. if ((typeof ngDevMode === 'undefined' || ngDevMode) && !fetchBackendWarningDisplayed) { const isServer = isPlatformServer(injector.get(PLATFORM_ID)); if (isServer && !(this.backend instanceof FetchBackend)) { fetchBackendWarningDisplayed = true; injector .get(Console) .warn( formatRuntimeError( RuntimeErrorCode.NOT_USING_FETCH_BACKEND_IN_SSR, 'Angular detected that `HttpClient` is not configured ' + "to use `fetch` APIs. It's strongly recommended to " + 'enable `fetch` for applications that use Server-Side Rendering ' + 'for better performance and compatibility. ' + 'To enable `fetch`, add the `withFetch()` to the `provideHttpClient()` ' + 'call at the root of the application.', ), ); } } } override handle(initialRequest: HttpRequest<any>): Observable<HttpEvent<any>> { if (this.chain === null) { const dedupedInterceptorFns = Array.from( new Set([ ...this.injector.get(HTTP_INTERCEPTOR_FNS), ...this.injector.get(HTTP_ROOT_INTERCEPTOR_FNS, []), ]), ); // Note: interceptors are wrapped right-to-left so that final execution order is // left-to-right. That is, if `dedupedInterceptorFns` is the array `[a, b, c]`, we want to // produce a chain that is conceptually `c(b(a(end)))`, which we build from the inside // out. this.chain = dedupedInterceptorFns.reduceRight( (nextSequencedFn, interceptorFn) => chainedInterceptorFn(nextSequencedFn, interceptorFn, this.injector), interceptorChainEndFn as ChainedInterceptorFn<unknown>, ); } if (this.contributeToStability) { const taskId = this.pendingTasks.add(); return this.chain(initialRequest, (downstreamRequest) => this.backend.handle(downstreamRequest), ).pipe(finalize(() => this.pendingTasks.remove(taskId))); } else { return this.chain(initialRequest, (downstreamRequest) => this.backend.handle(downstreamRequest), ); } } }
{ "end_byte": 12476, "start_byte": 8501, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/interceptor.ts" }
angular/packages/common/http/src/xhr.ts_0_2768
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {XhrFactory} from '@angular/common'; import {Injectable, ɵRuntimeError as RuntimeError} from '@angular/core'; import {from, Observable, Observer, of} from 'rxjs'; import {switchMap} from 'rxjs/operators'; import {HttpBackend} from './backend'; import {RuntimeErrorCode} from './errors'; import {HttpHeaders} from './headers'; import {HttpRequest} from './request'; import { HTTP_STATUS_CODE_NO_CONTENT, HTTP_STATUS_CODE_OK, HttpDownloadProgressEvent, HttpErrorResponse, HttpEvent, HttpEventType, HttpHeaderResponse, HttpJsonParseError, HttpResponse, HttpUploadProgressEvent, } from './response'; const XSSI_PREFIX = /^\)\]\}',?\n/; /** * Determine an appropriate URL for the response, by checking either * XMLHttpRequest.responseURL or the X-Request-URL header. */ function getResponseUrl(xhr: any): string | null { if ('responseURL' in xhr && xhr.responseURL) { return xhr.responseURL; } if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) { return xhr.getResponseHeader('X-Request-URL'); } return null; } /** * Uses `XMLHttpRequest` to send requests to a backend server. * @see {@link HttpHandler} * @see {@link JsonpClientBackend} * * @publicApi */ @Injectable() export class HttpXhrBackend implements HttpBackend { constructor(private xhrFactory: XhrFactory) {} /** * Processes a request and returns a stream of response events. * @param req The request object. * @returns An observable of the response events. */ handle(req: HttpRequest<any>): Observable<HttpEvent<any>> { // Quick check to give a better error message when a user attempts to use // HttpClient.jsonp() without installing the HttpClientJsonpModule if (req.method === 'JSONP') { throw new RuntimeError( RuntimeErrorCode.MISSING_JSONP_MODULE, (typeof ngDevMode === 'undefined' || ngDevMode) && `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.`, ); } // Check whether this factory has a special function to load an XHR implementation // for various non-browser environments. We currently limit it to only `ServerXhr` // class, which needs to load an XHR implementation. const xhrFactory: XhrFactory & {ɵloadImpl?: () => Promise<void>} = this.xhrFactory; const source: Observable<void | null> = xhrFactory.ɵloadImpl ? from(xhrFactory.ɵloadImpl()) : of(null);
{ "end_byte": 2768, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/xhr.ts" }
angular/packages/common/http/src/xhr.ts_2774_13233
rn source.pipe( switchMap(() => { // Everything happens on Observable subscription. return new Observable((observer: Observer<HttpEvent<any>>) => { // Start by setting up the XHR object with request method, URL, and withCredentials // flag. const xhr = xhrFactory.build(); xhr.open(req.method, req.urlWithParams); if (req.withCredentials) { xhr.withCredentials = true; } // Add all the requested headers. req.headers.forEach((name, values) => xhr.setRequestHeader(name, values.join(','))); // Add an Accept header if one isn't present already. if (!req.headers.has('Accept')) { xhr.setRequestHeader('Accept', 'application/json, text/plain, */*'); } // Auto-detect the Content-Type header if one isn't present already. if (!req.headers.has('Content-Type')) { const detectedType = req.detectContentTypeHeader(); // Sometimes Content-Type detection fails. if (detectedType !== null) { xhr.setRequestHeader('Content-Type', detectedType); } } // Set the responseType if one was requested. if (req.responseType) { const responseType = req.responseType.toLowerCase(); // JSON responses need to be processed as text. This is because if the server // returns an XSSI-prefixed JSON response, the browser will fail to parse it, // xhr.response will be null, and xhr.responseText cannot be accessed to // retrieve the prefixed JSON data in order to strip the prefix. Thus, all JSON // is parsed by first requesting text and then applying JSON.parse. xhr.responseType = (responseType !== 'json' ? responseType : 'text') as any; } // Serialize the request body if one is present. If not, this will be set to null. const reqBody = req.serializeBody(); // If progress events are enabled, response headers will be delivered // in two events - the HttpHeaderResponse event and the full HttpResponse // event. However, since response headers don't change in between these // two events, it doesn't make sense to parse them twice. So headerResponse // caches the data extracted from the response whenever it's first parsed, // to ensure parsing isn't duplicated. let headerResponse: HttpHeaderResponse | null = null; // partialFromXhr extracts the HttpHeaderResponse from the current XMLHttpRequest // state, and memoizes it into headerResponse. const partialFromXhr = (): HttpHeaderResponse => { if (headerResponse !== null) { return headerResponse; } const statusText = xhr.statusText || 'OK'; // Parse headers from XMLHttpRequest - this step is lazy. const headers = new HttpHeaders(xhr.getAllResponseHeaders()); // Read the response URL from the XMLHttpResponse instance and fall back on the // request URL. const url = getResponseUrl(xhr) || req.url; // Construct the HttpHeaderResponse and memoize it. headerResponse = new HttpHeaderResponse({headers, status: xhr.status, statusText, url}); return headerResponse; }; // Next, a few closures are defined for the various events which XMLHttpRequest can // emit. This allows them to be unregistered as event listeners later. // First up is the load event, which represents a response being fully available. const onLoad = () => { // Read response state from the memoized partial data. let {headers, status, statusText, url} = partialFromXhr(); // The body will be read out if present. let body: any | null = null; if (status !== HTTP_STATUS_CODE_NO_CONTENT) { // Use XMLHttpRequest.response if set, responseText otherwise. body = typeof xhr.response === 'undefined' ? xhr.responseText : xhr.response; } // Normalize another potential bug (this one comes from CORS). if (status === 0) { status = !!body ? HTTP_STATUS_CODE_OK : 0; } // ok determines whether the response will be transmitted on the event or // error channel. Unsuccessful status codes (not 2xx) will always be errors, // but a successful status code can still result in an error if the user // asked for JSON data and the body cannot be parsed as such. let ok = status >= 200 && status < 300; // Check whether the body needs to be parsed as JSON (in many cases the browser // will have done that already). if (req.responseType === 'json' && typeof body === 'string') { // Save the original body, before attempting XSSI prefix stripping. const originalBody = body; body = body.replace(XSSI_PREFIX, ''); try { // Attempt the parse. If it fails, a parse error should be delivered to the // user. body = body !== '' ? JSON.parse(body) : null; } catch (error) { // Since the JSON.parse failed, it's reasonable to assume this might not have // been a JSON response. Restore the original body (including any XSSI prefix) // to deliver a better error response. body = originalBody; // If this was an error request to begin with, leave it as a string, it // probably just isn't JSON. Otherwise, deliver the parsing error to the user. if (ok) { // Even though the response status was 2xx, this is still an error. ok = false; // The parse error contains the text of the body that failed to parse. body = {error, text: body} as HttpJsonParseError; } } } if (ok) { // A successful response is delivered on the event stream. observer.next( new HttpResponse({ body, headers, status, statusText, url: url || undefined, }), ); // The full body has been received and delivered, no further events // are possible. This request is complete. observer.complete(); } else { // An unsuccessful request is delivered on the error channel. observer.error( new HttpErrorResponse({ // The error in this case is the response body (error from the server). error: body, headers, status, statusText, url: url || undefined, }), ); } }; // The onError callback is called when something goes wrong at the network level. // Connection timeout, DNS error, offline, etc. These are actual errors, and are // transmitted on the error channel. const onError = (error: ProgressEvent) => { const {url} = partialFromXhr(); const res = new HttpErrorResponse({ error, status: xhr.status || 0, statusText: xhr.statusText || 'Unknown Error', url: url || undefined, }); observer.error(res); }; // The sentHeaders flag tracks whether the HttpResponseHeaders event // has been sent on the stream. This is necessary to track if progress // is enabled since the event will be sent on only the first download // progress event. let sentHeaders = false; // The download progress event handler, which is only registered if // progress events are enabled. const onDownProgress = (event: ProgressEvent) => { // Send the HttpResponseHeaders event if it hasn't been sent already. if (!sentHeaders) { observer.next(partialFromXhr()); sentHeaders = true; } // Start building the download progress event to deliver on the response // event stream. let progressEvent: HttpDownloadProgressEvent = { type: HttpEventType.DownloadProgress, loaded: event.loaded, }; // Set the total number of bytes in the event if it's available. if (event.lengthComputable) { progressEvent.total = event.total; } // If the request was for text content and a partial response is // available on XMLHttpRequest, include it in the progress event // to allow for streaming reads. if (req.responseType === 'text' && !!xhr.responseText) { progressEvent.partialText = xhr.responseText; } // Finally, fire the event. observer.next(progressEvent); }; // The upload progress event handler, which is only registered if // progress events are enabled. const onUpProgress = (event: ProgressEvent) => { // Upload progress events are simpler. Begin building the progress // event. let progress: HttpUploadProgressEvent = { type: HttpEventType.UploadProgress, loaded: event.loaded, }; // If the total number of bytes being uploaded is available, include // it. if (event.lengthComputable) { progress.total = event.total; } // Send the event. observer.next(progress); }; // By default, register for load and error events. xhr.addEventListener('load', onLoad); xhr.addEventListener('error', onError); xhr.addEventListener('timeout', onError); xhr.addEventListener('abort', onError); // Progress events are only enabled if requested.
{ "end_byte": 13233, "start_byte": 2774, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/xhr.ts" }
angular/packages/common/http/src/xhr.ts_13244_14669
req.reportProgress) { // Download progress is always enabled if requested. xhr.addEventListener('progress', onDownProgress); // Upload progress depends on whether there is a body to upload. if (reqBody !== null && xhr.upload) { xhr.upload.addEventListener('progress', onUpProgress); } } // Fire the request, and notify the event stream that it was fired. xhr.send(reqBody!); observer.next({type: HttpEventType.Sent}); // This is the return from the Observable function, which is the // request cancellation handler. return () => { // On a cancellation, remove all registered event listeners. xhr.removeEventListener('error', onError); xhr.removeEventListener('abort', onError); xhr.removeEventListener('load', onLoad); xhr.removeEventListener('timeout', onError); if (req.reportProgress) { xhr.removeEventListener('progress', onDownProgress); if (reqBody !== null && xhr.upload) { xhr.upload.removeEventListener('progress', onUpProgress); } } // Finally, abort the in-flight request. if (xhr.readyState !== xhr.DONE) { xhr.abort(); } }; }); }), ); } }
{ "end_byte": 14669, "start_byte": 13244, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/xhr.ts" }
angular/packages/common/http/src/context.ts_0_2954
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * A token used to manipulate and access values stored in `HttpContext`. * * @publicApi */ export class HttpContextToken<T> { constructor(public readonly defaultValue: () => T) {} } /** * Http context stores arbitrary user defined values and ensures type safety without * actually knowing the types. It is backed by a `Map` and guarantees that keys do not clash. * * This context is mutable and is shared between cloned requests unless explicitly specified. * * @usageNotes * * ### Usage Example * * ```typescript * // inside cache.interceptors.ts * export const IS_CACHE_ENABLED = new HttpContextToken<boolean>(() => false); * * export class CacheInterceptor implements HttpInterceptor { * * intercept(req: HttpRequest<any>, delegate: HttpHandler): Observable<HttpEvent<any>> { * if (req.context.get(IS_CACHE_ENABLED) === true) { * return ...; * } * return delegate.handle(req); * } * } * * // inside a service * * this.httpClient.get('/api/weather', { * context: new HttpContext().set(IS_CACHE_ENABLED, true) * }).subscribe(...); * ``` * * @publicApi */ export class HttpContext { private readonly map = new Map<HttpContextToken<unknown>, unknown>(); /** * Store a value in the context. If a value is already present it will be overwritten. * * @param token The reference to an instance of `HttpContextToken`. * @param value The value to store. * * @returns A reference to itself for easy chaining. */ set<T>(token: HttpContextToken<T>, value: T): HttpContext { this.map.set(token, value); return this; } /** * Retrieve the value associated with the given token. * * @param token The reference to an instance of `HttpContextToken`. * * @returns The stored value or default if one is defined. */ get<T>(token: HttpContextToken<T>): T { if (!this.map.has(token)) { this.map.set(token, token.defaultValue()); } return this.map.get(token) as T; } /** * Delete the value associated with the given token. * * @param token The reference to an instance of `HttpContextToken`. * * @returns A reference to itself for easy chaining. */ delete(token: HttpContextToken<unknown>): HttpContext { this.map.delete(token); return this; } /** * Checks for existence of a given token. * * @param token The reference to an instance of `HttpContextToken`. * * @returns True if the token exists, false otherwise. */ has(token: HttpContextToken<unknown>): boolean { return this.map.has(token); } /** * @returns a list of tokens currently stored in the context. */ keys(): IterableIterator<HttpContextToken<unknown>> { return this.map.keys(); } }
{ "end_byte": 2954, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/context.ts" }
angular/packages/common/http/src/private_export.ts_0_371
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export { HTTP_ROOT_INTERCEPTOR_FNS as ɵHTTP_ROOT_INTERCEPTOR_FNS, REQUESTS_CONTRIBUTE_TO_STABILITY as ɵREQUESTS_CONTRIBUTE_TO_STABILITY, } from './interceptor';
{ "end_byte": 371, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/private_export.ts" }
angular/packages/common/http/src/jsonp.ts_0_9179
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {DOCUMENT} from '@angular/common'; import { EnvironmentInjector, Inject, inject, Injectable, runInInjectionContext, } from '@angular/core'; import {Observable, Observer} from 'rxjs'; import {HttpBackend, HttpHandler} from './backend'; import {HttpHandlerFn} from './interceptor'; import {HttpRequest} from './request'; import { HTTP_STATUS_CODE_OK, HttpErrorResponse, HttpEvent, HttpEventType, HttpResponse, } from './response'; // Every request made through JSONP needs a callback name that's unique across the // whole page. Each request is assigned an id and the callback name is constructed // from that. The next id to be assigned is tracked in a global variable here that // is shared among all applications on the page. let nextRequestId: number = 0; /** * When a pending <script> is unsubscribed we'll move it to this document, so it won't be * executed. */ let foreignDocument: Document | undefined; // Error text given when a JSONP script is injected, but doesn't invoke the callback // passed in its URL. export const JSONP_ERR_NO_CALLBACK = 'JSONP injected script did not invoke callback.'; // Error text given when a request is passed to the JsonpClientBackend that doesn't // have a request method JSONP. export const JSONP_ERR_WRONG_METHOD = 'JSONP requests must use JSONP request method.'; export const JSONP_ERR_WRONG_RESPONSE_TYPE = 'JSONP requests must use Json response type.'; // Error text given when a request is passed to the JsonpClientBackend that has // headers set export const JSONP_ERR_HEADERS_NOT_SUPPORTED = 'JSONP requests do not support headers.'; /** * DI token/abstract type representing a map of JSONP callbacks. * * In the browser, this should always be the `window` object. * * */ export abstract class JsonpCallbackContext { [key: string]: (data: any) => void; } /** * Factory function that determines where to store JSONP callbacks. * * Ordinarily JSONP callbacks are stored on the `window` object, but this may not exist * in test environments. In that case, callbacks are stored on an anonymous object instead. * * */ export function jsonpCallbackContext(): Object { if (typeof window === 'object') { return window; } return {}; } /** * Processes an `HttpRequest` with the JSONP method, * by performing JSONP style requests. * @see {@link HttpHandler} * @see {@link HttpXhrBackend} * * @publicApi */ @Injectable() export class JsonpClientBackend implements HttpBackend { /** * A resolved promise that can be used to schedule microtasks in the event handlers. */ private readonly resolvedPromise = Promise.resolve(); constructor( private callbackMap: JsonpCallbackContext, @Inject(DOCUMENT) private document: any, ) {} /** * Get the name of the next callback method, by incrementing the global `nextRequestId`. */ private nextCallback(): string { return `ng_jsonp_callback_${nextRequestId++}`; } /** * Processes a JSONP request and returns an event stream of the results. * @param req The request object. * @returns An observable of the response events. * */ handle(req: HttpRequest<never>): Observable<HttpEvent<any>> { // Firstly, check both the method and response type. If either doesn't match // then the request was improperly routed here and cannot be handled. if (req.method !== 'JSONP') { throw new Error(JSONP_ERR_WRONG_METHOD); } else if (req.responseType !== 'json') { throw new Error(JSONP_ERR_WRONG_RESPONSE_TYPE); } // Check the request headers. JSONP doesn't support headers and // cannot set any that were supplied. if (req.headers.keys().length > 0) { throw new Error(JSONP_ERR_HEADERS_NOT_SUPPORTED); } // Everything else happens inside the Observable boundary. return new Observable<HttpEvent<any>>((observer: Observer<HttpEvent<any>>) => { // The first step to make a request is to generate the callback name, and replace the // callback placeholder in the URL with the name. Care has to be taken here to ensure // a trailing &, if matched, gets inserted back into the URL in the correct place. const callback = this.nextCallback(); const url = req.urlWithParams.replace(/=JSONP_CALLBACK(&|$)/, `=${callback}$1`); // Construct the <script> tag and point it at the URL. const node = this.document.createElement('script'); node.src = url; // A JSONP request requires waiting for multiple callbacks. These variables // are closed over and track state across those callbacks. // The response object, if one has been received, or null otherwise. let body: any | null = null; // Whether the response callback has been called. let finished: boolean = false; // Set the response callback in this.callbackMap (which will be the window // object in the browser. The script being loaded via the <script> tag will // eventually call this callback. this.callbackMap[callback] = (data?: any) => { // Data has been received from the JSONP script. Firstly, delete this callback. delete this.callbackMap[callback]; // Set state to indicate data was received. body = data; finished = true; }; // cleanup() is a utility closure that removes the <script> from the page and // the response callback from the window. This logic is used in both the // success, error, and cancellation paths, so it's extracted out for convenience. const cleanup = () => { node.removeEventListener('load', onLoad); node.removeEventListener('error', onError); // Remove the <script> tag if it's still on the page. node.remove(); // Remove the response callback from the callbackMap (window object in the // browser). delete this.callbackMap[callback]; }; // onLoad() is the success callback which runs after the response callback // if the JSONP script loads successfully. The event itself is unimportant. // If something went wrong, onLoad() may run without the response callback // having been invoked. const onLoad = (event: Event) => { // We wrap it in an extra Promise, to ensure the microtask // is scheduled after the loaded endpoint has executed any potential microtask itself, // which is not guaranteed in Internet Explorer and EdgeHTML. See issue #39496 this.resolvedPromise.then(() => { // Cleanup the page. cleanup(); // Check whether the response callback has run. if (!finished) { // It hasn't, something went wrong with the request. Return an error via // the Observable error path. All JSONP errors have status 0. observer.error( new HttpErrorResponse({ url, status: 0, statusText: 'JSONP Error', error: new Error(JSONP_ERR_NO_CALLBACK), }), ); return; } // Success. body either contains the response body or null if none was // returned. observer.next( new HttpResponse({ body, status: HTTP_STATUS_CODE_OK, statusText: 'OK', url, }), ); // Complete the stream, the response is over. observer.complete(); }); }; // onError() is the error callback, which runs if the script returned generates // a Javascript error. It emits the error via the Observable error channel as // a HttpErrorResponse. const onError: any = (error: Error) => { cleanup(); // Wrap the error in a HttpErrorResponse. observer.error( new HttpErrorResponse({ error, status: 0, statusText: 'JSONP Error', url, }), ); }; // Subscribe to both the success (load) and error events on the <script> tag, // and add it to the page. node.addEventListener('load', onLoad); node.addEventListener('error', onError); this.document.body.appendChild(node); // The request has now been successfully sent. observer.next({type: HttpEventType.Sent}); // Cancellation handler. return () => { if (!finished) { this.removeListeners(node); } // And finally, clean up the page. cleanup(); }; }); } private removeListeners(script: HTMLScriptElement): void { // Issue #34818 // Changing <script>'s ownerDocument will prevent it from execution. // https://html.spec.whatwg.org/multipage/scripting.html#execute-the-script-block foreignDocument ??= (this.document.implementation as DOMImplementation).createHTMLDocument(); foreignDocument.adoptNode(script); } }
{ "end_byte": 9179, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/jsonp.ts" }
angular/packages/common/http/src/jsonp.ts_9181_10384
/** * Identifies requests with the method JSONP and shifts them to the `JsonpClientBackend`. */ export function jsonpInterceptorFn( req: HttpRequest<unknown>, next: HttpHandlerFn, ): Observable<HttpEvent<unknown>> { if (req.method === 'JSONP') { return inject(JsonpClientBackend).handle(req as HttpRequest<never>); } // Fall through for normal HTTP requests. return next(req); } /** * Identifies requests with the method JSONP and * shifts them to the `JsonpClientBackend`. * * @see {@link HttpInterceptor} * * @publicApi */ @Injectable() export class JsonpInterceptor { constructor(private injector: EnvironmentInjector) {} /** * Identifies and handles a given JSONP request. * @param initialRequest The outgoing request object to handle. * @param next The next interceptor in the chain, or the backend * if no interceptors remain in the chain. * @returns An observable of the event stream. */ intercept(initialRequest: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return runInInjectionContext(this.injector, () => jsonpInterceptorFn(initialRequest, (downstreamRequest) => next.handle(downstreamRequest)), ); } }
{ "end_byte": 10384, "start_byte": 9181, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/jsonp.ts" }
angular/packages/common/http/src/response.ts_0_8132
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {HttpHeaders} from './headers'; /** * Type enumeration for the different kinds of `HttpEvent`. * * @publicApi */ export enum HttpEventType { /** * The request was sent out over the wire. */ Sent, /** * An upload progress event was received. * * Note: The `FetchBackend` doesn't support progress report on uploads. */ UploadProgress, /** * The response status code and headers were received. */ ResponseHeader, /** * A download progress event was received. */ DownloadProgress, /** * The full response including the body was received. */ Response, /** * A custom event from an interceptor or a backend. */ User, } /** * Base interface for progress events. * * @publicApi */ export interface HttpProgressEvent { /** * Progress event type is either upload or download. */ type: HttpEventType.DownloadProgress | HttpEventType.UploadProgress; /** * Number of bytes uploaded or downloaded. */ loaded: number; /** * Total number of bytes to upload or download. Depending on the request or * response, this may not be computable and thus may not be present. */ total?: number; } /** * A download progress event. * * @publicApi */ export interface HttpDownloadProgressEvent extends HttpProgressEvent { type: HttpEventType.DownloadProgress; /** * The partial response body as downloaded so far. * * Only present if the responseType was `text`. */ partialText?: string; } /** * An upload progress event. * * Note: The `FetchBackend` doesn't support progress report on uploads. * * @publicApi */ export interface HttpUploadProgressEvent extends HttpProgressEvent { type: HttpEventType.UploadProgress; } /** * An event indicating that the request was sent to the server. Useful * when a request may be retried multiple times, to distinguish between * retries on the final event stream. * * @publicApi */ export interface HttpSentEvent { type: HttpEventType.Sent; } /** * A user-defined event. * * Grouping all custom events under this type ensures they will be handled * and forwarded by all implementations of interceptors. * * @publicApi */ export interface HttpUserEvent<T> { type: HttpEventType.User; } /** * An error that represents a failed attempt to JSON.parse text coming back * from the server. * * It bundles the Error object with the actual response body that failed to parse. * * */ export interface HttpJsonParseError { error: Error; text: string; } /** * Union type for all possible events on the response stream. * * Typed according to the expected type of the response. * * @publicApi */ export type HttpEvent<T> = | HttpSentEvent | HttpHeaderResponse | HttpResponse<T> | HttpProgressEvent | HttpUserEvent<T>; /** * Base class for both `HttpResponse` and `HttpHeaderResponse`. * * @publicApi */ export abstract class HttpResponseBase { /** * All response headers. */ readonly headers: HttpHeaders; /** * Response status code. */ readonly status: number; /** * Textual description of response status code, defaults to OK. * * Do not depend on this. */ readonly statusText: string; /** * URL of the resource retrieved, or null if not available. */ readonly url: string | null; /** * Whether the status code falls in the 2xx range. */ readonly ok: boolean; /** * Type of the response, narrowed to either the full response or the header. */ // TODO(issue/24571): remove '!'. readonly type!: HttpEventType.Response | HttpEventType.ResponseHeader; /** * Super-constructor for all responses. * * The single parameter accepted is an initialization hash. Any properties * of the response passed there will override the default values. */ constructor( init: { headers?: HttpHeaders; status?: number; statusText?: string; url?: string; }, defaultStatus: number = 200, defaultStatusText: string = 'OK', ) { // If the hash has values passed, use them to initialize the response. // Otherwise use the default values. this.headers = init.headers || new HttpHeaders(); this.status = init.status !== undefined ? init.status : defaultStatus; this.statusText = init.statusText || defaultStatusText; this.url = init.url || null; // Cache the ok value to avoid defining a getter. this.ok = this.status >= 200 && this.status < 300; } } /** * A partial HTTP response which only includes the status and header data, * but no response body. * * `HttpHeaderResponse` is a `HttpEvent` available on the response * event stream, only when progress events are requested. * * @publicApi */ export class HttpHeaderResponse extends HttpResponseBase { /** * Create a new `HttpHeaderResponse` with the given parameters. */ constructor( init: { headers?: HttpHeaders; status?: number; statusText?: string; url?: string; } = {}, ) { super(init); } override readonly type: HttpEventType.ResponseHeader = HttpEventType.ResponseHeader; /** * Copy this `HttpHeaderResponse`, overriding its contents with the * given parameter hash. */ clone( update: {headers?: HttpHeaders; status?: number; statusText?: string; url?: string} = {}, ): HttpHeaderResponse { // Perform a straightforward initialization of the new HttpHeaderResponse, // overriding the current parameters with new ones if given. return new HttpHeaderResponse({ headers: update.headers || this.headers, status: update.status !== undefined ? update.status : this.status, statusText: update.statusText || this.statusText, url: update.url || this.url || undefined, }); } } /** * A full HTTP response, including a typed response body (which may be `null` * if one was not returned). * * `HttpResponse` is a `HttpEvent` available on the response event * stream. * * @publicApi */ export class HttpResponse<T> extends HttpResponseBase { /** * The response body, or `null` if one was not returned. */ readonly body: T | null; /** * Construct a new `HttpResponse`. */ constructor( init: { body?: T | null; headers?: HttpHeaders; status?: number; statusText?: string; url?: string; } = {}, ) { super(init); this.body = init.body !== undefined ? init.body : null; } override readonly type: HttpEventType.Response = HttpEventType.Response; clone(): HttpResponse<T>; clone(update: { headers?: HttpHeaders; status?: number; statusText?: string; url?: string; }): HttpResponse<T>; clone<V>(update: { body?: V | null; headers?: HttpHeaders; status?: number; statusText?: string; url?: string; }): HttpResponse<V>; clone( update: { body?: any | null; headers?: HttpHeaders; status?: number; statusText?: string; url?: string; } = {}, ): HttpResponse<any> { return new HttpResponse<any>({ body: update.body !== undefined ? update.body : this.body, headers: update.headers || this.headers, status: update.status !== undefined ? update.status : this.status, statusText: update.statusText || this.statusText, url: update.url || this.url || undefined, }); } } /** * A response that represents an error or failure, either from a * non-successful HTTP status, an error while executing the request, * or some other failure which occurred during the parsing of the response. * * Any error returned on the `Observable` response stream will be * wrapped in an `HttpErrorResponse` to provide additional context about * the state of the HTTP layer when the error occurred. The error property * will contain either a wrapped Error object or the error response returned * from the server. * * @publicApi */
{ "end_byte": 8132, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/response.ts" }
angular/packages/common/http/src/response.ts_8133_11178
export class HttpErrorResponse extends HttpResponseBase implements Error { readonly name = 'HttpErrorResponse'; readonly message: string; readonly error: any | null; /** * Errors are never okay, even when the status code is in the 2xx success range. */ override readonly ok = false; constructor(init: { error?: any; headers?: HttpHeaders; status?: number; statusText?: string; url?: string; }) { // Initialize with a default status of 0 / Unknown Error. super(init, 0, 'Unknown Error'); // If the response was successful, then this was a parse error. Otherwise, it was // a protocol-level failure of some sort. Either the request failed in transit // or the server returned an unsuccessful status code. if (this.status >= 200 && this.status < 300) { this.message = `Http failure during parsing for ${init.url || '(unknown url)'}`; } else { this.message = `Http failure response for ${init.url || '(unknown url)'}: ${init.status} ${ init.statusText }`; } this.error = init.error || null; } } /** * We use these constant to prevent pulling the whole HttpStatusCode enum * Those are the only ones referenced directly by the framework */ export const HTTP_STATUS_CODE_OK = 200; export const HTTP_STATUS_CODE_NO_CONTENT = 204; /** * Http status codes. * As per https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml * @publicApi */ export enum HttpStatusCode { Continue = 100, SwitchingProtocols = 101, Processing = 102, EarlyHints = 103, Ok = HTTP_STATUS_CODE_OK, Created = 201, Accepted = 202, NonAuthoritativeInformation = 203, NoContent = HTTP_STATUS_CODE_NO_CONTENT, ResetContent = 205, PartialContent = 206, MultiStatus = 207, AlreadyReported = 208, ImUsed = 226, MultipleChoices = 300, MovedPermanently = 301, Found = 302, SeeOther = 303, NotModified = 304, UseProxy = 305, Unused = 306, TemporaryRedirect = 307, PermanentRedirect = 308, BadRequest = 400, Unauthorized = 401, PaymentRequired = 402, Forbidden = 403, NotFound = 404, MethodNotAllowed = 405, NotAcceptable = 406, ProxyAuthenticationRequired = 407, RequestTimeout = 408, Conflict = 409, Gone = 410, LengthRequired = 411, PreconditionFailed = 412, PayloadTooLarge = 413, UriTooLong = 414, UnsupportedMediaType = 415, RangeNotSatisfiable = 416, ExpectationFailed = 417, ImATeapot = 418, MisdirectedRequest = 421, UnprocessableEntity = 422, Locked = 423, FailedDependency = 424, TooEarly = 425, UpgradeRequired = 426, PreconditionRequired = 428, TooManyRequests = 429, RequestHeaderFieldsTooLarge = 431, UnavailableForLegalReasons = 451, InternalServerError = 500, NotImplemented = 501, BadGateway = 502, ServiceUnavailable = 503, GatewayTimeout = 504, HttpVersionNotSupported = 505, VariantAlsoNegotiates = 506, InsufficientStorage = 507, LoopDetected = 508, NotExtended = 510, NetworkAuthenticationRequired = 511, }
{ "end_byte": 11178, "start_byte": 8133, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/response.ts" }
angular/packages/common/http/src/request.ts_0_2412
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {HttpContext} from './context'; import {HttpHeaders} from './headers'; import {HttpParams} from './params'; /** * Construction interface for `HttpRequest`s. * * All values are optional and will override default values if provided. */ interface HttpRequestInit { headers?: HttpHeaders; context?: HttpContext; reportProgress?: boolean; params?: HttpParams; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; } /** * Determine whether the given HTTP method may include a body. */ function mightHaveBody(method: string): boolean { switch (method) { case 'DELETE': case 'GET': case 'HEAD': case 'OPTIONS': case 'JSONP': return false; default: return true; } } /** * Safely assert whether the given value is an ArrayBuffer. * * In some execution environments ArrayBuffer is not defined. */ function isArrayBuffer(value: any): value is ArrayBuffer { return typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer; } /** * Safely assert whether the given value is a Blob. * * In some execution environments Blob is not defined. */ function isBlob(value: any): value is Blob { return typeof Blob !== 'undefined' && value instanceof Blob; } /** * Safely assert whether the given value is a FormData instance. * * In some execution environments FormData is not defined. */ function isFormData(value: any): value is FormData { return typeof FormData !== 'undefined' && value instanceof FormData; } /** * Safely assert whether the given value is a URLSearchParams instance. * * In some execution environments URLSearchParams is not defined. */ function isUrlSearchParams(value: any): value is URLSearchParams { return typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams; } /** * An outgoing HTTP request with an optional typed body. * * `HttpRequest` represents an outgoing request, including URL, method, * headers, body, and other request configuration options. Instances should be * assumed to be immutable. To modify a `HttpRequest`, the `clone` * method should be used. * * @publicApi */
{ "end_byte": 2412, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/request.ts" }
angular/packages/common/http/src/request.ts_2413_11235
export class HttpRequest<T> { /** * The request body, or `null` if one isn't set. * * Bodies are not enforced to be immutable, as they can include a reference to any * user-defined data type. However, interceptors should take care to preserve * idempotence by treating them as such. */ readonly body: T | null = null; /** * Outgoing headers for this request. */ // TODO(issue/24571): remove '!'. readonly headers!: HttpHeaders; /** * Shared and mutable context that can be used by interceptors */ readonly context!: HttpContext; /** * Whether this request should be made in a way that exposes progress events. * * Progress events are expensive (change detection runs on each event) and so * they should only be requested if the consumer intends to monitor them. * * Note: The `FetchBackend` doesn't support progress report on uploads. */ readonly reportProgress: boolean = false; /** * Whether this request should be sent with outgoing credentials (cookies). */ readonly withCredentials: boolean = false; /** * The expected response type of the server. * * This is used to parse the response appropriately before returning it to * the requestee. */ readonly responseType: 'arraybuffer' | 'blob' | 'json' | 'text' = 'json'; /** * The outgoing HTTP request method. */ readonly method: string; /** * Outgoing URL parameters. * * To pass a string representation of HTTP parameters in the URL-query-string format, * the `HttpParamsOptions`' `fromString` may be used. For example: * * ``` * new HttpParams({fromString: 'angular=awesome'}) * ``` */ // TODO(issue/24571): remove '!'. readonly params!: HttpParams; /** * The outgoing URL with all URL parameters set. */ readonly urlWithParams: string; /** * The HttpTransferCache option for the request */ readonly transferCache?: {includeHeaders?: string[]} | boolean; constructor( method: 'GET' | 'HEAD', url: string, init?: { headers?: HttpHeaders; context?: HttpContext; reportProgress?: boolean; params?: HttpParams; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'; withCredentials?: boolean; /** * This property accepts either a boolean to enable/disable transferring cache for eligible * requests performed using `HttpClient`, or an object, which allows to configure cache * parameters, such as which headers should be included (no headers are included by default). * * Setting this property will override the options passed to `provideClientHydration()` for this * particular request */ transferCache?: {includeHeaders?: string[]} | boolean; }, ); constructor( method: 'DELETE' | 'JSONP' | 'OPTIONS', url: string, init?: { headers?: HttpHeaders; context?: HttpContext; reportProgress?: boolean; params?: HttpParams; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'; withCredentials?: boolean; }, ); constructor( method: 'POST', url: string, body: T | null, init?: { headers?: HttpHeaders; context?: HttpContext; reportProgress?: boolean; params?: HttpParams; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'; withCredentials?: boolean; /** * This property accepts either a boolean to enable/disable transferring cache for eligible * requests performed using `HttpClient`, or an object, which allows to configure cache * parameters, such as which headers should be included (no headers are included by default). * * Setting this property will override the options passed to `provideClientHydration()` for this * particular request */ transferCache?: {includeHeaders?: string[]} | boolean; }, ); constructor( method: 'PUT' | 'PATCH', url: string, body: T | null, init?: { headers?: HttpHeaders; context?: HttpContext; reportProgress?: boolean; params?: HttpParams; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'; withCredentials?: boolean; }, ); constructor( method: string, url: string, body: T | null, init?: { headers?: HttpHeaders; context?: HttpContext; reportProgress?: boolean; params?: HttpParams; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'; withCredentials?: boolean; /** * This property accepts either a boolean to enable/disable transferring cache for eligible * requests performed using `HttpClient`, or an object, which allows to configure cache * parameters, such as which headers should be included (no headers are included by default). * * Setting this property will override the options passed to `provideClientHydration()` for this * particular request */ transferCache?: {includeHeaders?: string[]} | boolean; }, ); constructor( method: string, readonly url: string, third?: | T | { headers?: HttpHeaders; context?: HttpContext; reportProgress?: boolean; params?: HttpParams; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; } | null, fourth?: { headers?: HttpHeaders; context?: HttpContext; reportProgress?: boolean; params?: HttpParams; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ) { this.method = method.toUpperCase(); // Next, need to figure out which argument holds the HttpRequestInit // options, if any. let options: HttpRequestInit | undefined; // Check whether a body argument is expected. The only valid way to omit // the body argument is to use a known no-body method like GET. if (mightHaveBody(this.method) || !!fourth) { // Body is the third argument, options are the fourth. this.body = third !== undefined ? (third as T) : null; options = fourth; } else { // No body required, options are the third argument. The body stays null. options = third as HttpRequestInit; } // If options have been passed, interpret them. if (options) { // Normalize reportProgress and withCredentials. this.reportProgress = !!options.reportProgress; this.withCredentials = !!options.withCredentials; // Override default response type of 'json' if one is provided. if (!!options.responseType) { this.responseType = options.responseType; } // Override headers if they're provided. if (!!options.headers) { this.headers = options.headers; } if (!!options.context) { this.context = options.context; } if (!!options.params) { this.params = options.params; } // We do want to assign transferCache even if it's falsy (false is valid value) this.transferCache = options.transferCache; } // If no headers have been passed in, construct a new HttpHeaders instance. this.headers ??= new HttpHeaders(); // If no context have been passed in, construct a new HttpContext instance. this.context ??= new HttpContext(); // If no parameters have been passed in, construct a new HttpUrlEncodedParams instance. if (!this.params) { this.params = new HttpParams(); this.urlWithParams = url; } else { // Encode the parameters to a string in preparation for inclusion in the URL. const params = this.params.toString(); if (params.length === 0) { // No parameters, the visible URL is just the URL given at creation time. this.urlWithParams = url; } else { // Does the URL already have query parameters? Look for '?'. const qIdx = url.indexOf('?'); // There are 3 cases to handle: // 1) No existing parameters -> append '?' followed by params. // 2) '?' exists and is followed by existing query string -> // append '&' followed by params. // 3) '?' exists at the end of the url -> append params directly. // This basically amounts to determining the character, if any, with // which to join the URL and parameters. const sep: string = qIdx === -1 ? '?' : qIdx < url.length - 1 ? '&' : ''; this.urlWithParams = url + sep + params; } } } /** * Transform the free-form body into a serialized format suitable for * transmission to the server. */
{ "end_byte": 11235, "start_byte": 2413, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/request.ts" }
angular/packages/common/http/src/request.ts_11238_17274
serializeBody(): ArrayBuffer | Blob | FormData | URLSearchParams | string | null { // If no body is present, no need to serialize it. if (this.body === null) { return null; } // Check whether the body is already in a serialized form. If so, // it can just be returned directly. if ( typeof this.body === 'string' || isArrayBuffer(this.body) || isBlob(this.body) || isFormData(this.body) || isUrlSearchParams(this.body) ) { return this.body; } // Check whether the body is an instance of HttpUrlEncodedParams. if (this.body instanceof HttpParams) { return this.body.toString(); } // Check whether the body is an object or array, and serialize with JSON if so. if ( typeof this.body === 'object' || typeof this.body === 'boolean' || Array.isArray(this.body) ) { return JSON.stringify(this.body); } // Fall back on toString() for everything else. return (this.body as any).toString(); } /** * Examine the body and attempt to infer an appropriate MIME type * for it. * * If no such type can be inferred, this method will return `null`. */ detectContentTypeHeader(): string | null { // An empty body has no content type. if (this.body === null) { return null; } // FormData bodies rely on the browser's content type assignment. if (isFormData(this.body)) { return null; } // Blobs usually have their own content type. If it doesn't, then // no type can be inferred. if (isBlob(this.body)) { return this.body.type || null; } // Array buffers have unknown contents and thus no type can be inferred. if (isArrayBuffer(this.body)) { return null; } // Technically, strings could be a form of JSON data, but it's safe enough // to assume they're plain strings. if (typeof this.body === 'string') { return 'text/plain'; } // `HttpUrlEncodedParams` has its own content-type. if (this.body instanceof HttpParams) { return 'application/x-www-form-urlencoded;charset=UTF-8'; } // Arrays, objects, boolean and numbers will be encoded as JSON. if ( typeof this.body === 'object' || typeof this.body === 'number' || typeof this.body === 'boolean' ) { return 'application/json'; } // No type could be inferred. return null; } clone(): HttpRequest<T>; clone(update: { headers?: HttpHeaders; context?: HttpContext; reportProgress?: boolean; params?: HttpParams; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; body?: T | null; method?: string; url?: string; setHeaders?: {[name: string]: string | string[]}; setParams?: {[param: string]: string}; }): HttpRequest<T>; clone<V>(update: { headers?: HttpHeaders; context?: HttpContext; reportProgress?: boolean; params?: HttpParams; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; body?: V | null; method?: string; url?: string; setHeaders?: {[name: string]: string | string[]}; setParams?: {[param: string]: string}; }): HttpRequest<V>; clone( update: { headers?: HttpHeaders; context?: HttpContext; reportProgress?: boolean; params?: HttpParams; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; body?: any | null; method?: string; url?: string; setHeaders?: {[name: string]: string | string[]}; setParams?: {[param: string]: string}; } = {}, ): HttpRequest<any> { // For method, url, and responseType, take the current value unless // it is overridden in the update hash. const method = update.method || this.method; const url = update.url || this.url; const responseType = update.responseType || this.responseType; // Carefully handle the transferCache to differentiate between // `false` and `undefined` in the update args. const transferCache = update.transferCache ?? this.transferCache; // The body is somewhat special - a `null` value in update.body means // whatever current body is present is being overridden with an empty // body, whereas an `undefined` value in update.body implies no // override. const body = update.body !== undefined ? update.body : this.body; // Carefully handle the boolean options to differentiate between // `false` and `undefined` in the update args. const withCredentials = update.withCredentials ?? this.withCredentials; const reportProgress = update.reportProgress ?? this.reportProgress; // Headers and params may be appended to if `setHeaders` or // `setParams` are used. let headers = update.headers || this.headers; let params = update.params || this.params; // Pass on context if needed const context = update.context ?? this.context; // Check whether the caller has asked to add headers. if (update.setHeaders !== undefined) { // Set every requested header. headers = Object.keys(update.setHeaders).reduce( (headers, name) => headers.set(name, update.setHeaders![name]), headers, ); } // Check whether the caller has asked to set params. if (update.setParams) { // Set every requested param. params = Object.keys(update.setParams).reduce( (params, param) => params.set(param, update.setParams![param]), params, ); } // Finally, construct the new HttpRequest using the pieces from above. return new HttpRequest(method, url, body, { params, headers, context, reportProgress, responseType, withCredentials, transferCache, }); } }
{ "end_byte": 17274, "start_byte": 11238, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/request.ts" }
angular/packages/common/http/src/client.ts_0_3632
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Injectable} from '@angular/core'; import {Observable, of} from 'rxjs'; import {concatMap, filter, map} from 'rxjs/operators'; import {HttpHandler} from './backend'; import {HttpContext} from './context'; import {HttpHeaders} from './headers'; import {HttpParams, HttpParamsOptions} from './params'; import {HttpRequest} from './request'; import {HttpEvent, HttpResponse} from './response'; /** * Constructs an instance of `HttpRequestOptions<T>` from a source `HttpMethodOptions` and * the given `body`. This function clones the object and adds the body. * * Note that the `responseType` *options* value is a String that identifies the * single data type of the response. * A single overload version of the method handles each response type. * The value of `responseType` cannot be a union, as the combined signature could imply. * */ function addBody<T>( options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body' | 'events' | 'response'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, body: T | null, ): any { return { body, headers: options.headers, context: options.context, observe: options.observe, params: options.params, reportProgress: options.reportProgress, responseType: options.responseType, withCredentials: options.withCredentials, transferCache: options.transferCache, }; } /** * Performs HTTP requests. * This service is available as an injectable class, with methods to perform HTTP requests. * Each request method has multiple signatures, and the return type varies based on * the signature that is called (mainly the values of `observe` and `responseType`). * * Note that the `responseType` *options* value is a String that identifies the * single data type of the response. * A single overload version of the method handles each response type. * The value of `responseType` cannot be a union, as the combined signature could imply. * TODO(adev): review * @usageNotes * * ### HTTP Request Example * * ``` * // GET heroes whose name contains search term * searchHeroes(term: string): observable<Hero[]>{ * * const params = new HttpParams({fromString: 'name=term'}); * return this.httpClient.request('GET', this.heroesUrl, {responseType:'json', params}); * } * ``` * * Alternatively, the parameter string can be used without invoking HttpParams * by directly joining to the URL. * ``` * this.httpClient.request('GET', this.heroesUrl + '?' + 'name=term', {responseType:'json'}); * ``` * * * ### JSONP Example * ``` * requestJsonp(url, callback = 'callback') { * return this.httpClient.jsonp(this.heroesURL, callback); * } * ``` * * ### PATCH Example * ``` * // PATCH one of the heroes' name * patchHero (id: number, heroName: string): Observable<{}> { * const url = `${this.heroesUrl}/${id}`; // PATCH api/heroes/42 * return this.httpClient.patch(url, {name: heroName}, httpOptions) * .pipe(catchError(this.handleError('patchHero'))); * } * ``` * * @see [HTTP Guide](guide/http) * @see [HTTP Request](api/common/http/HttpRequest) * * @publicApi */
{ "end_byte": 3632, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/client.ts" }
angular/packages/common/http/src/client.ts_3633_11598
@Injectable() export class HttpClient { constructor(private handler: HttpHandler) {} /** * Sends an `HttpRequest` and returns a stream of `HttpEvent`s. * * @return An `Observable` of the response, with the response body as a stream of `HttpEvent`s. */ request<R>(req: HttpRequest<any>): Observable<HttpEvent<R>>; /** * Constructs a request that interprets the body as an `ArrayBuffer` and returns the response in * an `ArrayBuffer`. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * * @return An `Observable` of the response, with the response body as an `ArrayBuffer`. */ request( method: string, url: string, options: { body?: any; headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<ArrayBuffer>; /** * Constructs a request that interprets the body as a blob and returns * the response as a blob. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body of type `Blob`. */ request( method: string, url: string, options: { body?: any; headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<Blob>; /** * Constructs a request that interprets the body as a text string and * returns a string value. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body of type string. */ request( method: string, url: string, options: { body?: any; headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<string>; /** * Constructs a request that interprets the body as an `ArrayBuffer` and returns the * the full event stream. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body as an array of `HttpEvent`s for * the request. */ request( method: string, url: string, options: { body?: any; headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; observe: 'events'; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpEvent<ArrayBuffer>>; /** * Constructs a request that interprets the body as a `Blob` and returns * the full event stream. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, * with the response body of type `Blob`. */ request( method: string, url: string, options: { body?: any; headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpEvent<Blob>>; /** * Constructs a request which interprets the body as a text string and returns the full event * stream. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, * with the response body of type string. */ request( method: string, url: string, options: { body?: any; headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpEvent<string>>; /** * Constructs a request which interprets the body as a JavaScript object and returns the full * event stream. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, * with the response body of type `Object`. */ request( method: string, url: string, options: { body?: any; headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; reportProgress?: boolean; observe: 'events'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; responseType?: 'json'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpEvent<any>>; /** * Constructs a request which interprets the body as a JavaScript object and returns the full * event stream. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, * with the response body of type `R`. */ request<R>( method: string, url: string, options: { body?: any; headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; reportProgress?: boolean; observe: 'events'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; responseType?: 'json'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpEvent<R>>; /** * Constructs a request which interprets the body as an `ArrayBuffer` * and returns the full `HttpResponse`. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse`, with the response body as an `ArrayBuffer`. */
{ "end_byte": 11598, "start_byte": 3633, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/client.ts" }
angular/packages/common/http/src/client.ts_11601_19922
request( method: string, url: string, options: { body?: any; headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpResponse<ArrayBuffer>>; /** * Constructs a request which interprets the body as a `Blob` and returns the full `HttpResponse`. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse`, with the response body of type `Blob`. */ request( method: string, url: string, options: { body?: any; headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpResponse<Blob>>; /** * Constructs a request which interprets the body as a text stream and returns the full * `HttpResponse`. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the HTTP response, with the response body of type string. */ request( method: string, url: string, options: { body?: any; headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpResponse<string>>; /** * Constructs a request which interprets the body as a JavaScript object and returns the full * `HttpResponse`. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the full `HttpResponse`, * with the response body of type `Object`. */ request( method: string, url: string, options: { body?: any; headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; reportProgress?: boolean; observe: 'response'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; responseType?: 'json'; withCredentials?: boolean; }, ): Observable<HttpResponse<Object>>; /** * Constructs a request which interprets the body as a JavaScript object and returns * the full `HttpResponse` with the response body in the requested type. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the full `HttpResponse`, with the response body of type `R`. */ request<R>( method: string, url: string, options: { body?: any; headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; reportProgress?: boolean; observe: 'response'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; responseType?: 'json'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpResponse<R>>; /** * Constructs a request which interprets the body as a JavaScript object and returns the full * `HttpResponse` as a JavaScript object. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse`, with the response body of type `Object`. */ request( method: string, url: string, options?: { body?: any; headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; responseType?: 'json'; reportProgress?: boolean; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<Object>; /** * Constructs a request which interprets the body as a JavaScript object * with the response body of the requested type. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse`, with the response body of type `R`. */ request<R>( method: string, url: string, options?: { body?: any; headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; responseType?: 'json'; reportProgress?: boolean; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<R>; /** * Constructs a request where response type and requested observable are not known statically. * * @param method The HTTP method. * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the requested response, with body of type `any`. */ request( method: string, url: string, options?: { body?: any; headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; observe?: 'body' | 'events' | 'response'; reportProgress?: boolean; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<any>; /** * Constructs an observable for a generic HTTP request that, when subscribed, * fires the request through the chain of registered interceptors and on to the * server. * * You can pass an `HttpRequest` directly as the only parameter. In this case, * the call returns an observable of the raw `HttpEvent` stream. * * Alternatively you can pass an HTTP method as the first parameter, * a URL string as the second, and an options hash containing the request body as the third. * See `addBody()`. In this case, the specified `responseType` and `observe` options determine the * type of returned observable. * * The `responseType` value determines how a successful response body is parsed. * * If `responseType` is the default `json`, you can pass a type interface for the resulting * object as a type parameter to the call. * * The `observe` value determines the return type, according to what you are interested in * observing. * * An `observe` value of events returns an observable of the raw `HttpEvent` stream, including * progress events by default. * * An `observe` value of response returns an observable of `HttpResponse<T>`, * where the `T` parameter depends on the `responseType` and any optionally provided type * parameter. * * An `observe` value of body returns an observable of `<T>` with the same `T` body type. * */
{ "end_byte": 19922, "start_byte": 11601, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/client.ts" }
angular/packages/common/http/src/client.ts_19925_28837
request( first: string | HttpRequest<any>, url?: string, options: { body?: any; headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body' | 'events' | 'response'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; } = {}, ): Observable<any> { let req: HttpRequest<any>; // First, check whether the primary argument is an instance of `HttpRequest`. if (first instanceof HttpRequest) { // It is. The other arguments must be undefined (per the signatures) and can be // ignored. req = first; } else { // It's a string, so it represents a URL. Construct a request based on it, // and incorporate the remaining arguments (assuming `GET` unless a method is // provided. // Figure out the headers. let headers: HttpHeaders | undefined = undefined; if (options.headers instanceof HttpHeaders) { headers = options.headers; } else { headers = new HttpHeaders(options.headers); } // Sort out parameters. let params: HttpParams | undefined = undefined; if (!!options.params) { if (options.params instanceof HttpParams) { params = options.params; } else { params = new HttpParams({fromObject: options.params} as HttpParamsOptions); } } // Construct the request. req = new HttpRequest(first, url!, options.body !== undefined ? options.body : null, { headers, context: options.context, params, reportProgress: options.reportProgress, // By default, JSON is assumed to be returned for all calls. responseType: options.responseType || 'json', withCredentials: options.withCredentials, transferCache: options.transferCache, }); } // Start with an Observable.of() the initial request, and run the handler (which // includes all interceptors) inside a concatMap(). This way, the handler runs // inside an Observable chain, which causes interceptors to be re-run on every // subscription (this also makes retries re-run the handler, including interceptors). const events$: Observable<HttpEvent<any>> = of(req).pipe( concatMap((req: HttpRequest<any>) => this.handler.handle(req)), ); // If coming via the API signature which accepts a previously constructed HttpRequest, // the only option is to get the event stream. Otherwise, return the event stream if // that is what was requested. if (first instanceof HttpRequest || options.observe === 'events') { return events$; } // The requested stream contains either the full response or the body. In either // case, the first step is to filter the event stream to extract a stream of // responses(s). const res$: Observable<HttpResponse<any>> = <Observable<HttpResponse<any>>>( events$.pipe(filter((event: HttpEvent<any>) => event instanceof HttpResponse)) ); // Decide which stream to return. switch (options.observe || 'body') { case 'body': // The requested stream is the body. Map the response stream to the response // body. This could be done more simply, but a misbehaving interceptor might // transform the response body into a different format and ignore the requested // responseType. Guard against this by validating that the response is of the // requested type. switch (req.responseType) { case 'arraybuffer': return res$.pipe( map((res: HttpResponse<any>) => { // Validate that the body is an ArrayBuffer. if (res.body !== null && !(res.body instanceof ArrayBuffer)) { throw new Error('Response is not an ArrayBuffer.'); } return res.body; }), ); case 'blob': return res$.pipe( map((res: HttpResponse<any>) => { // Validate that the body is a Blob. if (res.body !== null && !(res.body instanceof Blob)) { throw new Error('Response is not a Blob.'); } return res.body; }), ); case 'text': return res$.pipe( map((res: HttpResponse<any>) => { // Validate that the body is a string. if (res.body !== null && typeof res.body !== 'string') { throw new Error('Response is not a string.'); } return res.body; }), ); case 'json': default: // No validation needed for JSON responses, as they can be of any type. return res$.pipe(map((res: HttpResponse<any>) => res.body)); } case 'response': // The response stream was requested directly, so return it. return res$; default: // Guard against new future observe types being added. throw new Error(`Unreachable: unhandled observe type ${options.observe}}`); } } /** * Constructs a `DELETE` request that interprets the body as an `ArrayBuffer` * and returns the response as an `ArrayBuffer`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response body as an `ArrayBuffer`. */ delete( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; body?: any | null; }, ): Observable<ArrayBuffer>; /** * Constructs a `DELETE` request that interprets the body as a `Blob` and returns * the response as a `Blob`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response body as a `Blob`. */ delete( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; body?: any | null; }, ): Observable<Blob>; /** * Constructs a `DELETE` request that interprets the body as a text string and returns * a string. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body of type string. */ delete( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; body?: any | null; }, ): Observable<string>; /** * Constructs a `DELETE` request that interprets the body as an `ArrayBuffer` * and returns the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, * with response body as an `ArrayBuffer`. */ delete( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; body?: any | null; }, ): Observable<HttpEvent<ArrayBuffer>>; /** * Constructs a `DELETE` request that interprets the body as a `Blob` * and returns the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all the `HttpEvent`s for the request, with the response body as a * `Blob`. */
{ "end_byte": 28837, "start_byte": 19925, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/client.ts" }
angular/packages/common/http/src/client.ts_28840_36871
delete( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; body?: any | null; }, ): Observable<HttpEvent<Blob>>; /** * Constructs a `DELETE` request that interprets the body as a text string * and returns the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, with the response * body of type string. */ delete( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; body?: any | null; }, ): Observable<HttpEvent<string>>; /** * Constructs a `DELETE` request that interprets the body as JSON * and returns the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, with response body of * type `Object`. */ delete( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; body?: any | null; }, ): Observable<HttpEvent<Object>>; /** * Constructs a `DELETE`request that interprets the body as JSON * and returns the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all the `HttpEvent`s for the request, with a response * body in the requested type. */ delete<T>( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | (string | number | boolean)[]}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; body?: any | null; }, ): Observable<HttpEvent<T>>; /** * Constructs a `DELETE` request that interprets the body as an `ArrayBuffer` and returns * the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the full `HttpResponse`, with the response body as an `ArrayBuffer`. */ delete( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; body?: any | null; }, ): Observable<HttpResponse<ArrayBuffer>>; /** * Constructs a `DELETE` request that interprets the body as a `Blob` and returns the full * `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse`, with the response body of type `Blob`. */ delete( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; body?: any | null; }, ): Observable<HttpResponse<Blob>>; /** * Constructs a `DELETE` request that interprets the body as a text stream and * returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the full `HttpResponse`, with the response body of type string. */ delete( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; body?: any | null; }, ): Observable<HttpResponse<string>>; /** * Constructs a `DELETE` request the interprets the body as a JavaScript object and returns * the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse`, with the response body of type `Object`. * */ delete( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; body?: any | null; }, ): Observable<HttpResponse<Object>>; /** * Constructs a `DELETE` request that interprets the body as JSON * and returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse`, with the response body of the requested type. */ delete<T>( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; body?: any | null; }, ): Observable<HttpResponse<T>>; /** * Constructs a `DELETE` request that interprets the body as JSON and * returns the response body as an object parsed from JSON. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body of type `Object`. */ delete( url: string, options?: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; body?: any | null; }, ): Observable<Object>; /** * Constructs a DELETE request that interprets the body as JSON and returns * the response in a given type. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse`, with response body in the requested type. */
{ "end_byte": 36871, "start_byte": 28840, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/client.ts" }
angular/packages/common/http/src/client.ts_36874_45127
delete<T>( url: string, options?: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; body?: any | null; }, ): Observable<T>; /** * Constructs an observable that, when subscribed, causes the configured * `DELETE` request to execute on the server. See the individual overloads for * details on the return type. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * */ delete( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body' | 'events' | 'response'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'; withCredentials?: boolean; body?: any | null; } = {}, ): Observable<any> { return this.request<any>('DELETE', url, options as any); } /** * Constructs a `GET` request that interprets the body as an `ArrayBuffer` and returns the * response in an `ArrayBuffer`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body as an `ArrayBuffer`. */ get( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<ArrayBuffer>; /** * Constructs a `GET` request that interprets the body as a `Blob` * and returns the response as a `Blob`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body as a `Blob`. */ get( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<Blob>; /** * Constructs a `GET` request that interprets the body as a text string * and returns the response as a string value. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body of type string. */ get( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<string>; /** * Constructs a `GET` request that interprets the body as an `ArrayBuffer` and returns * the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, with the response * body as an `ArrayBuffer`. */ get( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpEvent<ArrayBuffer>>; /** * Constructs a `GET` request that interprets the body as a `Blob` and * returns the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body as a `Blob`. */ get( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpEvent<Blob>>; /** * Constructs a `GET` request that interprets the body as a text string and returns * the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body of type string. */ get( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpEvent<string>>; /** * Constructs a `GET` request that interprets the body as JSON * and returns the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body of type `Object`. */ get( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpEvent<Object>>; /** * Constructs a `GET` request that interprets the body as JSON and returns the full * event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with a response body in the requested type. */ get<T>( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpEvent<T>>; /** * Constructs a `GET` request that interprets the body as an `ArrayBuffer` and * returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body as an `ArrayBuffer`. */
{ "end_byte": 45127, "start_byte": 36874, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/client.ts" }
angular/packages/common/http/src/client.ts_45130_53430
get( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpResponse<ArrayBuffer>>; /** * Constructs a `GET` request that interprets the body as a `Blob` and * returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body as a `Blob`. */ get( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpResponse<Blob>>; /** * Constructs a `GET` request that interprets the body as a text stream and * returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body of type string. */ get( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpResponse<string>>; /** * Constructs a `GET` request that interprets the body as JSON and * returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the full `HttpResponse`, * with the response body of type `Object`. */ get( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpResponse<Object>>; /** * Constructs a `GET` request that interprets the body as JSON and * returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the full `HttpResponse` for the request, * with a response body in the requested type. */ get<T>( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpResponse<T>>; /** * Constructs a `GET` request that interprets the body as JSON and * returns the response body as an object parsed from JSON. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * * @return An `Observable` of the response body as a JavaScript object. */ get( url: string, options?: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<Object>; /** * Constructs a `GET` request that interprets the body as JSON and returns * the response body in a given type. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse`, with a response body in the requested type. */ get<T>( url: string, options?: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<T>; /** * Constructs an observable that, when subscribed, causes the configured * `GET` request to execute on the server. See the individual overloads for * details on the return type. */ get( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body' | 'events' | 'response'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; } = {}, ): Observable<any> { return this.request<any>('GET', url, options as any); } /** * Constructs a `HEAD` request that interprets the body as an `ArrayBuffer` and * returns the response as an `ArrayBuffer`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body as an `ArrayBuffer`. */ head( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<ArrayBuffer>; /** * Constructs a `HEAD` request that interprets the body as a `Blob` and returns * the response as a `Blob`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body as a `Blob`. */ head( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<Blob>; /** * Constructs a `HEAD` request that interprets the body as a text string and returns the response * as a string value. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body of type string. */
{ "end_byte": 53430, "start_byte": 45130, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/client.ts" }
angular/packages/common/http/src/client.ts_53433_61553
head( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<string>; /** * Constructs a `HEAD` request that interprets the body as an `ArrayBuffer` * and returns the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, * with the response body as an `ArrayBuffer`. */ head( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpEvent<ArrayBuffer>>; /** * Constructs a `HEAD` request that interprets the body as a `Blob` and * returns the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, * with the response body as a `Blob`. */ head( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpEvent<Blob>>; /** * Constructs a `HEAD` request that interprets the body as a text string * and returns the full event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, with the response body of type * string. */ head( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpEvent<string>>; /** * Constructs a `HEAD` request that interprets the body as JSON * and returns the full HTTP event stream. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of all `HttpEvent`s for the request, with a response body of * type `Object`. */ head( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpEvent<Object>>; /** * Constructs a `HEAD` request that interprets the body as JSON and * returns the full event stream. * * @return An `Observable` of all the `HttpEvent`s for the request, * with a response body in the requested type. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. */ head<T>( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpEvent<T>>; /** * Constructs a `HEAD` request that interprets the body as an `ArrayBuffer` * and returns the full HTTP response. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body as an `ArrayBuffer`. */ head( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpResponse<ArrayBuffer>>; /** * Constructs a `HEAD` request that interprets the body as a `Blob` and returns * the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body as a blob. */ head( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpResponse<Blob>>; /** * Constructs a `HEAD` request that interprets the body as text stream * and returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body of type string. */ head( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpResponse<string>>; /** * Constructs a `HEAD` request that interprets the body as JSON and * returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body of type `Object`. */ head( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpResponse<Object>>;
{ "end_byte": 61553, "start_byte": 53433, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/client.ts" }
angular/packages/common/http/src/client.ts_61557_69707
/** * Constructs a `HEAD` request that interprets the body as JSON * and returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse` for the request, * with a response body of the requested type. */ head<T>( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpResponse<T>>; /** * Constructs a `HEAD` request that interprets the body as JSON and * returns the response body as an object parsed from JSON. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the response, with the response body as an object parsed from JSON. */ head( url: string, options?: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<Object>; /** * Constructs a `HEAD` request that interprets the body as JSON and returns * the response in a given type. * * @param url The endpoint URL. * @param options The HTTP options to send with the request. * * @return An `Observable` of the `HttpResponse` for the request, * with a response body of the given type. */ head<T>( url: string, options?: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<T>; /** * Constructs an observable that, when subscribed, causes the configured * `HEAD` request to execute on the server. The `HEAD` method returns * meta information about the resource without transferring the * resource itself. See the individual overloads for * details on the return type. */ head( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body' | 'events' | 'response'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; } = {}, ): Observable<any> { return this.request<any>('HEAD', url, options as any); } /** * Constructs a `JSONP` request for the given URL and name of the callback parameter. * * @param url The resource URL. * @param callbackParam The callback function name. * * @return An `Observable` of the response object, with response body as an object. */ jsonp(url: string, callbackParam: string): Observable<Object>; /** * Constructs a `JSONP` request for the given URL and name of the callback parameter. * * @param url The resource URL. * @param callbackParam The callback function name. * * You must install a suitable interceptor, such as one provided by `HttpClientJsonpModule`. * If no such interceptor is reached, * then the `JSONP` request can be rejected by the configured backend. * * @return An `Observable` of the response object, with response body in the requested type. */ jsonp<T>(url: string, callbackParam: string): Observable<T>; /** * Constructs an `Observable` that, when subscribed, causes a request with the special method * `JSONP` to be dispatched via the interceptor pipeline. * The [JSONP pattern](https://en.wikipedia.org/wiki/JSONP) works around limitations of certain * API endpoints that don't support newer, * and preferable [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) protocol. * JSONP treats the endpoint API as a JavaScript file and tricks the browser to process the * requests even if the API endpoint is not located on the same domain (origin) as the client-side * application making the request. * The endpoint API must support JSONP callback for JSONP requests to work. * The resource API returns the JSON response wrapped in a callback function. * You can pass the callback function name as one of the query parameters. * Note that JSONP requests can only be used with `GET` requests. * * @param url The resource URL. * @param callbackParam The callback function name. * */ jsonp<T>(url: string, callbackParam: string): Observable<T> { return this.request<any>('JSONP', url, { params: new HttpParams().append(callbackParam, 'JSONP_CALLBACK'), observe: 'body', responseType: 'json', }); } /** * Constructs an `OPTIONS` request that interprets the body as an * `ArrayBuffer` and returns the response as an `ArrayBuffer`. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of the response, with the response body as an `ArrayBuffer`. */ options( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; }, ): Observable<ArrayBuffer>; /** * Constructs an `OPTIONS` request that interprets the body as a `Blob` and returns * the response as a `Blob`. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of the response, with the response body as a `Blob`. */ options( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; }, ): Observable<Blob>; /** * Constructs an `OPTIONS` request that interprets the body as a text string and * returns a string value. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of the response, with the response body of type string. */ options( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; }, ): Observable<string>; /** * Constructs an `OPTIONS` request that interprets the body as an `ArrayBuffer` * and returns the full event stream. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of all `HttpEvent`s for the request, * with the response body as an `ArrayBuffer`. */
{ "end_byte": 69707, "start_byte": 61557, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/client.ts" }
angular/packages/common/http/src/client.ts_69710_78057
options( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; }, ): Observable<HttpEvent<ArrayBuffer>>; /** * Constructs an `OPTIONS` request that interprets the body as a `Blob` and * returns the full event stream. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of all `HttpEvent`s for the request, * with the response body as a `Blob`. */ options( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; }, ): Observable<HttpEvent<Blob>>; /** * Constructs an `OPTIONS` request that interprets the body as a text string * and returns the full event stream. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of all the `HttpEvent`s for the request, * with the response body of type string. */ options( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; }, ): Observable<HttpEvent<string>>; /** * Constructs an `OPTIONS` request that interprets the body as JSON * and returns the full event stream. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of all the `HttpEvent`s for the request with the response * body of type `Object`. */ options( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }, ): Observable<HttpEvent<Object>>; /** * Constructs an `OPTIONS` request that interprets the body as JSON and * returns the full event stream. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of all the `HttpEvent`s for the request, * with a response body in the requested type. */ options<T>( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }, ): Observable<HttpEvent<T>>; /** * Constructs an `OPTIONS` request that interprets the body as an `ArrayBuffer` * and returns the full HTTP response. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body as an `ArrayBuffer`. */ options( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; }, ): Observable<HttpResponse<ArrayBuffer>>; /** * Constructs an `OPTIONS` request that interprets the body as a `Blob` * and returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body as a `Blob`. */ options( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; }, ): Observable<HttpResponse<Blob>>; /** * Constructs an `OPTIONS` request that interprets the body as text stream * and returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body of type string. */ options( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; }, ): Observable<HttpResponse<string>>; /** * Constructs an `OPTIONS` request that interprets the body as JSON * and returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body of type `Object`. */ options( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }, ): Observable<HttpResponse<Object>>; /** * Constructs an `OPTIONS` request that interprets the body as JSON and * returns the full `HttpResponse`. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse` for the request, * with a response body in the requested type. */ options<T>( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }, ): Observable<HttpResponse<T>>; /** * Constructs an `OPTIONS` request that interprets the body as JSON and returns the * response body as an object parsed from JSON. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of the response, with the response body as an object parsed from JSON. */ options( url: string, options?: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }, ): Observable<Object>; /** * Constructs an `OPTIONS` request that interprets the body as JSON and returns the * response in a given type. * * @param url The endpoint URL. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse`, with a response body of the given type. */
{ "end_byte": 78057, "start_byte": 69710, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/client.ts" }
angular/packages/common/http/src/client.ts_78060_86214
options<T>( url: string, options?: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }, ): Observable<T>; /** * Constructs an `Observable` that, when subscribed, causes the configured * `OPTIONS` request to execute on the server. This method allows the client * to determine the supported HTTP methods and other capabilities of an endpoint, * without implying a resource action. See the individual overloads for * details on the return type. */ options( url: string, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body' | 'events' | 'response'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'; withCredentials?: boolean; } = {}, ): Observable<any> { return this.request<any>('OPTIONS', url, options as any); } /** * Constructs a `PATCH` request that interprets the body as an `ArrayBuffer` and returns * the response as an `ArrayBuffer`. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of the response, with the response body as an `ArrayBuffer`. */ patch( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; }, ): Observable<ArrayBuffer>; /** * Constructs a `PATCH` request that interprets the body as a `Blob` and returns the response * as a `Blob`. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of the response, with the response body as a `Blob`. */ patch( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; }, ): Observable<Blob>; /** * Constructs a `PATCH` request that interprets the body as a text string and * returns the response as a string value. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of the response, with a response body of type string. */ patch( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; }, ): Observable<string>; /** * Constructs a `PATCH` request that interprets the body as an `ArrayBuffer` and * returns the full event stream. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of all the `HttpEvent`s for the request, * with the response body as an `ArrayBuffer`. */ patch( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; }, ): Observable<HttpEvent<ArrayBuffer>>; /** * Constructs a `PATCH` request that interprets the body as a `Blob` * and returns the full event stream. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of all the `HttpEvent`s for the request, with the * response body as `Blob`. */ patch( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; }, ): Observable<HttpEvent<Blob>>; /** * Constructs a `PATCH` request that interprets the body as a text string and * returns the full event stream. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of all the `HttpEvent`s for the request, with a * response body of type string. */ patch( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; }, ): Observable<HttpEvent<string>>; /** * Constructs a `PATCH` request that interprets the body as JSON * and returns the full event stream. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of all the `HttpEvent`s for the request, * with a response body of type `Object`. */ patch( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }, ): Observable<HttpEvent<Object>>; /** * Constructs a `PATCH` request that interprets the body as JSON * and returns the full event stream. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of all the `HttpEvent`s for the request, * with a response body in the requested type. */ patch<T>( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }, ): Observable<HttpEvent<T>>; /** * Constructs a `PATCH` request that interprets the body as an `ArrayBuffer` * and returns the full `HttpResponse`. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body as an `ArrayBuffer`. */
{ "end_byte": 86214, "start_byte": 78060, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/client.ts" }
angular/packages/common/http/src/client.ts_86217_94388
patch( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; }, ): Observable<HttpResponse<ArrayBuffer>>; /** * Constructs a `PATCH` request that interprets the body as a `Blob` and returns the full * `HttpResponse`. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse` for the request, * with the response body as a `Blob`. */ patch( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; }, ): Observable<HttpResponse<Blob>>; /** * Constructs a `PATCH` request that interprets the body as a text stream and returns the * full `HttpResponse`. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse` for the request, * with a response body of type string. */ patch( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; }, ): Observable<HttpResponse<string>>; /** * Constructs a `PATCH` request that interprets the body as JSON * and returns the full `HttpResponse`. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse` for the request, * with a response body in the requested type. */ patch( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }, ): Observable<HttpResponse<Object>>; /** * Constructs a `PATCH` request that interprets the body as JSON * and returns the full `HttpResponse`. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse` for the request, * with a response body in the given type. */ patch<T>( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }, ): Observable<HttpResponse<T>>; /** * Constructs a `PATCH` request that interprets the body as JSON and * returns the response body as an object parsed from JSON. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of the response, with the response body as an object parsed from JSON. */ patch( url: string, body: any | null, options?: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }, ): Observable<Object>; /** * Constructs a `PATCH` request that interprets the body as JSON * and returns the response in a given type. * * @param url The endpoint URL. * @param body The resources to edit. * @param options HTTP options. * * @return An `Observable` of the `HttpResponse` for the request, * with a response body in the given type. */ patch<T>( url: string, body: any | null, options?: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }, ): Observable<T>; /** * Constructs an observable that, when subscribed, causes the configured * `PATCH` request to execute on the server. See the individual overloads for * details on the return type. */ patch( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body' | 'events' | 'response'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'; withCredentials?: boolean; } = {}, ): Observable<any> { return this.request<any>('PATCH', url, addBody(options, body)); } /** * Constructs a `POST` request that interprets the body as an `ArrayBuffer` and returns * an `ArrayBuffer`. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options. * * @return An `Observable` of the response, with the response body as an `ArrayBuffer`. */ post( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<ArrayBuffer>; /** * Constructs a `POST` request that interprets the body as a `Blob` and returns the * response as a `Blob`. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of the response, with the response body as a `Blob`. */ post( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<Blob>; /** * Constructs a `POST` request that interprets the body as a text string and * returns the response as a string value. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of the response, with a response body of type string. */
{ "end_byte": 94388, "start_byte": 86217, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/client.ts" }
angular/packages/common/http/src/client.ts_94391_102328
post( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<string>; /** * Constructs a `POST` request that interprets the body as an `ArrayBuffer` and * returns the full event stream. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of all `HttpEvent`s for the request, * with the response body as an `ArrayBuffer`. */ post( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpEvent<ArrayBuffer>>; /** * Constructs a `POST` request that interprets the body as a `Blob` * and returns the response in an observable of the full event stream. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of all `HttpEvent`s for the request, with the response body as `Blob`. */ post( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpEvent<Blob>>; /** * Constructs a `POST` request that interprets the body as a text string and returns the full * event stream. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of all `HttpEvent`s for the request, * with a response body of type string. */ post( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpEvent<string>>; /** * Constructs a POST request that interprets the body as JSON and returns the full * event stream. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of all `HttpEvent`s for the request, * with a response body of type `Object`. */ post( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpEvent<Object>>; /** * Constructs a POST request that interprets the body as JSON and returns the full * event stream. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of all `HttpEvent`s for the request, * with a response body in the requested type. */ post<T>( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpEvent<T>>; /** * Constructs a POST request that interprets the body as an `ArrayBuffer` * and returns the full `HttpResponse`. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of the `HttpResponse` for the request, with the response body as an * `ArrayBuffer`. */ post( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpResponse<ArrayBuffer>>; /** * Constructs a `POST` request that interprets the body as a `Blob` and returns the full * `HttpResponse`. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of the `HttpResponse` for the request, * with the response body as a `Blob`. */ post( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpResponse<Blob>>; /** * Constructs a `POST` request that interprets the body as a text stream and returns * the full `HttpResponse`. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of the `HttpResponse` for the request, * with a response body of type string. */ post( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpResponse<string>>; /** * Constructs a `POST` request that interprets the body as JSON * and returns the full `HttpResponse`. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of the `HttpResponse` for the request, with a response body of type * `Object`. */
{ "end_byte": 102328, "start_byte": 94391, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/client.ts" }
angular/packages/common/http/src/client.ts_102331_110398
post( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpResponse<Object>>; /** * Constructs a `POST` request that interprets the body as JSON and returns the * full `HttpResponse`. * * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of the `HttpResponse` for the request, with a response body in the * requested type. */ post<T>( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<HttpResponse<T>>; /** * Constructs a `POST` request that interprets the body as JSON * and returns the response body as an object parsed from JSON. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of the response, with the response body as an object parsed from JSON. */ post( url: string, body: any | null, options?: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<Object>; /** * Constructs a `POST` request that interprets the body as JSON * and returns an observable of the response. * * @param url The endpoint URL. * @param body The content to replace with. * @param options HTTP options * * @return An `Observable` of the `HttpResponse` for the request, with a response body in the * requested type. */ post<T>( url: string, body: any | null, options?: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; }, ): Observable<T>; /** * Constructs an observable that, when subscribed, causes the configured * `POST` request to execute on the server. The server responds with the location of * the replaced resource. See the individual overloads for * details on the return type. */ post( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body' | 'events' | 'response'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'; withCredentials?: boolean; transferCache?: {includeHeaders?: string[]} | boolean; } = {}, ): Observable<any> { return this.request<any>('POST', url, addBody(options, body)); } /** * Constructs a `PUT` request that interprets the body as an `ArrayBuffer` and returns the * response as an `ArrayBuffer`. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of the response, with the response body as an `ArrayBuffer`. */ put( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; }, ): Observable<ArrayBuffer>; /** * Constructs a `PUT` request that interprets the body as a `Blob` and returns * the response as a `Blob`. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of the response, with the response body as a `Blob`. */ put( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; }, ): Observable<Blob>; /** * Constructs a `PUT` request that interprets the body as a text string and * returns the response as a string value. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of the response, with a response body of type string. */ put( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; }, ): Observable<string>; /** * Constructs a `PUT` request that interprets the body as an `ArrayBuffer` and * returns the full event stream. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of all `HttpEvent`s for the request, * with the response body as an `ArrayBuffer`. */ put( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; }, ): Observable<HttpEvent<ArrayBuffer>>; /** * Constructs a `PUT` request that interprets the body as a `Blob` and returns the full event * stream. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of all `HttpEvent`s for the request, * with the response body as a `Blob`. */ put( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; }, ): Observable<HttpEvent<Blob>>;
{ "end_byte": 110398, "start_byte": 102331, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/client.ts" }
angular/packages/common/http/src/client.ts_110402_118531
/** * Constructs a `PUT` request that interprets the body as a text string and returns the full event * stream. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of all `HttpEvent`s for the request, with a response body * of type string. */ put( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; }, ): Observable<HttpEvent<string>>; /** * Constructs a `PUT` request that interprets the body as JSON and returns the full * event stream. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of all `HttpEvent`s for the request, with a response body of * type `Object`. */ put( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }, ): Observable<HttpEvent<Object>>; /** * Constructs a `PUT` request that interprets the body as JSON and returns the * full event stream. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of all `HttpEvent`s for the request, * with a response body in the requested type. */ put<T>( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'events'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }, ): Observable<HttpEvent<T>>; /** * Constructs a `PUT` request that interprets the body as an * `ArrayBuffer` and returns an observable of the full HTTP response. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of the `HttpResponse` for the request, with the response body as an * `ArrayBuffer`. */ put( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'arraybuffer'; withCredentials?: boolean; }, ): Observable<HttpResponse<ArrayBuffer>>; /** * Constructs a `PUT` request that interprets the body as a `Blob` and returns the * full HTTP response. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of the `HttpResponse` for the request, * with the response body as a `Blob`. */ put( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'blob'; withCredentials?: boolean; }, ): Observable<HttpResponse<Blob>>; /** * Constructs a `PUT` request that interprets the body as a text stream and returns the * full HTTP response. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of the `HttpResponse` for the request, with a response body of type * string. */ put( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType: 'text'; withCredentials?: boolean; }, ): Observable<HttpResponse<string>>; /** * Constructs a `PUT` request that interprets the body as JSON and returns the full * HTTP response. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of the `HttpResponse` for the request, with a response body * of type 'Object`. */ put( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }, ): Observable<HttpResponse<Object>>; /** * Constructs a `PUT` request that interprets the body as an instance of the requested type and * returns the full HTTP response. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of the `HttpResponse` for the request, * with a response body in the requested type. */ put<T>( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; observe: 'response'; context?: HttpContext; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }, ): Observable<HttpResponse<T>>; /** * Constructs a `PUT` request that interprets the body as JSON * and returns an observable of JavaScript object. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of the response as a JavaScript object. */ put( url: string, body: any | null, options?: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }, ): Observable<Object>; /** * Constructs a `PUT` request that interprets the body as an instance of the requested type * and returns an observable of the requested type. * * @param url The endpoint URL. * @param body The resources to add/update. * @param options HTTP options * * @return An `Observable` of the requested type. */ put<T>( url: string, body: any | null, options?: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'json'; withCredentials?: boolean; }, ): Observable<T>;
{ "end_byte": 118531, "start_byte": 110402, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/client.ts" }
angular/packages/common/http/src/client.ts_118535_119385
/** * Constructs an observable that, when subscribed, causes the configured * `PUT` request to execute on the server. The `PUT` method replaces an existing resource * with a new set of values. * See the individual overloads for details on the return type. */ put( url: string, body: any | null, options: { headers?: HttpHeaders | {[header: string]: string | string[]}; context?: HttpContext; observe?: 'body' | 'events' | 'response'; params?: | HttpParams | {[param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>}; reportProgress?: boolean; responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'; withCredentials?: boolean; } = {}, ): Observable<any> { return this.request<any>('PUT', url, addBody(options, body)); } }
{ "end_byte": 119385, "start_byte": 118535, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/client.ts" }
angular/packages/common/http/src/xsrf.ts_0_3800
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {DOCUMENT, ɵparseCookieValue as parseCookieValue} from '@angular/common'; import { EnvironmentInjector, Inject, inject, Injectable, InjectionToken, PLATFORM_ID, runInInjectionContext, } from '@angular/core'; import {Observable} from 'rxjs'; import {HttpHandler} from './backend'; import {HttpHandlerFn, HttpInterceptor} from './interceptor'; import {HttpRequest} from './request'; import {HttpEvent} from './response'; export const XSRF_ENABLED = new InjectionToken<boolean>(ngDevMode ? 'XSRF_ENABLED' : ''); export const XSRF_DEFAULT_COOKIE_NAME = 'XSRF-TOKEN'; export const XSRF_COOKIE_NAME = new InjectionToken<string>(ngDevMode ? 'XSRF_COOKIE_NAME' : '', { providedIn: 'root', factory: () => XSRF_DEFAULT_COOKIE_NAME, }); export const XSRF_DEFAULT_HEADER_NAME = 'X-XSRF-TOKEN'; export const XSRF_HEADER_NAME = new InjectionToken<string>(ngDevMode ? 'XSRF_HEADER_NAME' : '', { providedIn: 'root', factory: () => XSRF_DEFAULT_HEADER_NAME, }); /** * Retrieves the current XSRF token to use with the next outgoing request. * * @publicApi */ export abstract class HttpXsrfTokenExtractor { /** * Get the XSRF token to use with an outgoing request. * * Will be called for every request, so the token may change between requests. */ abstract getToken(): string | null; } /** * `HttpXsrfTokenExtractor` which retrieves the token from a cookie. */ @Injectable() export class HttpXsrfCookieExtractor implements HttpXsrfTokenExtractor { private lastCookieString: string = ''; private lastToken: string | null = null; /** * @internal for testing */ parseCount: number = 0; constructor( @Inject(DOCUMENT) private doc: any, @Inject(PLATFORM_ID) private platform: string, @Inject(XSRF_COOKIE_NAME) private cookieName: string, ) {} getToken(): string | null { if (this.platform === 'server') { return null; } const cookieString = this.doc.cookie || ''; if (cookieString !== this.lastCookieString) { this.parseCount++; this.lastToken = parseCookieValue(cookieString, this.cookieName); this.lastCookieString = cookieString; } return this.lastToken; } } export function xsrfInterceptorFn( req: HttpRequest<unknown>, next: HttpHandlerFn, ): Observable<HttpEvent<unknown>> { const lcUrl = req.url.toLowerCase(); // Skip both non-mutating requests and absolute URLs. // Non-mutating requests don't require a token, and absolute URLs require special handling // anyway as the cookie set // on our origin is not the same as the token expected by another origin. if ( !inject(XSRF_ENABLED) || req.method === 'GET' || req.method === 'HEAD' || lcUrl.startsWith('http://') || lcUrl.startsWith('https://') ) { return next(req); } const token = inject(HttpXsrfTokenExtractor).getToken(); const headerName = inject(XSRF_HEADER_NAME); // Be careful not to overwrite an existing header of the same name. if (token != null && !req.headers.has(headerName)) { req = req.clone({headers: req.headers.set(headerName, token)}); } return next(req); } /** * `HttpInterceptor` which adds an XSRF token to eligible outgoing requests. */ @Injectable() export class HttpXsrfInterceptor implements HttpInterceptor { constructor(private injector: EnvironmentInjector) {} intercept(initialRequest: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return runInInjectionContext(this.injector, () => xsrfInterceptorFn(initialRequest, (downstreamRequest) => next.handle(downstreamRequest)), ); } }
{ "end_byte": 3800, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/xsrf.ts" }
angular/packages/common/http/src/provider.ts_0_7344
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { EnvironmentProviders, inject, InjectionToken, makeEnvironmentProviders, Provider, } from '@angular/core'; import {HttpBackend, HttpHandler} from './backend'; import {HttpClient} from './client'; import {FetchBackend} from './fetch'; import { HTTP_INTERCEPTOR_FNS, HttpInterceptorFn, HttpInterceptorHandler, legacyInterceptorFnFactory, } from './interceptor'; import { jsonpCallbackContext, JsonpCallbackContext, JsonpClientBackend, jsonpInterceptorFn, } from './jsonp'; import {HttpXhrBackend} from './xhr'; import { HttpXsrfCookieExtractor, HttpXsrfTokenExtractor, XSRF_COOKIE_NAME, XSRF_ENABLED, XSRF_HEADER_NAME, xsrfInterceptorFn, } from './xsrf'; /** * Identifies a particular kind of `HttpFeature`. * * @publicApi */ export enum HttpFeatureKind { Interceptors, LegacyInterceptors, CustomXsrfConfiguration, NoXsrfProtection, JsonpSupport, RequestsMadeViaParent, Fetch, } /** * A feature for use when configuring `provideHttpClient`. * * @publicApi */ export interface HttpFeature<KindT extends HttpFeatureKind> { ɵkind: KindT; ɵproviders: Provider[]; } function makeHttpFeature<KindT extends HttpFeatureKind>( kind: KindT, providers: Provider[], ): HttpFeature<KindT> { return { ɵkind: kind, ɵproviders: providers, }; } /** * Configures Angular's `HttpClient` service to be available for injection. * * By default, `HttpClient` will be configured for injection with its default options for XSRF * protection of outgoing requests. Additional configuration options can be provided by passing * feature functions to `provideHttpClient`. For example, HTTP interceptors can be added using the * `withInterceptors(...)` feature. * * <div class="alert is-helpful"> * * It's strongly recommended to enable * [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) for applications that use * Server-Side Rendering for better performance and compatibility. To enable `fetch`, add * `withFetch()` feature to the `provideHttpClient()` call at the root of the application: * * ``` * provideHttpClient(withFetch()); * ``` * * </div> * * @see {@link withInterceptors} * @see {@link withInterceptorsFromDi} * @see {@link withXsrfConfiguration} * @see {@link withNoXsrfProtection} * @see {@link withJsonpSupport} * @see {@link withRequestsMadeViaParent} * @see {@link withFetch} */ export function provideHttpClient( ...features: HttpFeature<HttpFeatureKind>[] ): EnvironmentProviders { if (ngDevMode) { const featureKinds = new Set(features.map((f) => f.ɵkind)); if ( featureKinds.has(HttpFeatureKind.NoXsrfProtection) && featureKinds.has(HttpFeatureKind.CustomXsrfConfiguration) ) { throw new Error( ngDevMode ? `Configuration error: found both withXsrfConfiguration() and withNoXsrfProtection() in the same call to provideHttpClient(), which is a contradiction.` : '', ); } } const providers: Provider[] = [ HttpClient, HttpXhrBackend, HttpInterceptorHandler, {provide: HttpHandler, useExisting: HttpInterceptorHandler}, { provide: HttpBackend, useFactory: () => { return inject(FetchBackend, {optional: true}) ?? inject(HttpXhrBackend); }, }, { provide: HTTP_INTERCEPTOR_FNS, useValue: xsrfInterceptorFn, multi: true, }, {provide: XSRF_ENABLED, useValue: true}, {provide: HttpXsrfTokenExtractor, useClass: HttpXsrfCookieExtractor}, ]; for (const feature of features) { providers.push(...feature.ɵproviders); } return makeEnvironmentProviders(providers); } /** * Adds one or more functional-style HTTP interceptors to the configuration of the `HttpClient` * instance. * * @see {@link HttpInterceptorFn} * @see {@link provideHttpClient} * @publicApi */ export function withInterceptors( interceptorFns: HttpInterceptorFn[], ): HttpFeature<HttpFeatureKind.Interceptors> { return makeHttpFeature( HttpFeatureKind.Interceptors, interceptorFns.map((interceptorFn) => { return { provide: HTTP_INTERCEPTOR_FNS, useValue: interceptorFn, multi: true, }; }), ); } const LEGACY_INTERCEPTOR_FN = new InjectionToken<HttpInterceptorFn>( ngDevMode ? 'LEGACY_INTERCEPTOR_FN' : '', ); /** * Includes class-based interceptors configured using a multi-provider in the current injector into * the configured `HttpClient` instance. * * Prefer `withInterceptors` and functional interceptors instead, as support for DI-provided * interceptors may be phased out in a later release. * * @see {@link HttpInterceptor} * @see {@link HTTP_INTERCEPTORS} * @see {@link provideHttpClient} */ export function withInterceptorsFromDi(): HttpFeature<HttpFeatureKind.LegacyInterceptors> { // Note: the legacy interceptor function is provided here via an intermediate token // (`LEGACY_INTERCEPTOR_FN`), using a pattern which guarantees that if these providers are // included multiple times, all of the multi-provider entries will have the same instance of the // interceptor function. That way, the `HttpINterceptorHandler` will dedup them and legacy // interceptors will not run multiple times. return makeHttpFeature(HttpFeatureKind.LegacyInterceptors, [ { provide: LEGACY_INTERCEPTOR_FN, useFactory: legacyInterceptorFnFactory, }, { provide: HTTP_INTERCEPTOR_FNS, useExisting: LEGACY_INTERCEPTOR_FN, multi: true, }, ]); } /** * Customizes the XSRF protection for the configuration of the current `HttpClient` instance. * * This feature is incompatible with the `withNoXsrfProtection` feature. * * @see {@link provideHttpClient} */ export function withXsrfConfiguration({ cookieName, headerName, }: { cookieName?: string; headerName?: string; }): HttpFeature<HttpFeatureKind.CustomXsrfConfiguration> { const providers: Provider[] = []; if (cookieName !== undefined) { providers.push({provide: XSRF_COOKIE_NAME, useValue: cookieName}); } if (headerName !== undefined) { providers.push({provide: XSRF_HEADER_NAME, useValue: headerName}); } return makeHttpFeature(HttpFeatureKind.CustomXsrfConfiguration, providers); } /** * Disables XSRF protection in the configuration of the current `HttpClient` instance. * * This feature is incompatible with the `withXsrfConfiguration` feature. * * @see {@link provideHttpClient} */ export function withNoXsrfProtection(): HttpFeature<HttpFeatureKind.NoXsrfProtection> { return makeHttpFeature(HttpFeatureKind.NoXsrfProtection, [ { provide: XSRF_ENABLED, useValue: false, }, ]); } /** * Add JSONP support to the configuration of the current `HttpClient` instance. * * @see {@link provideHttpClient} */ export function withJsonpSupport(): HttpFeature<HttpFeatureKind.JsonpSupport> { return makeHttpFeature(HttpFeatureKind.JsonpSupport, [ JsonpClientBackend, {provide: JsonpCallbackContext, useFactory: jsonpCallbackContext}, {provide: HTTP_INTERCEPTOR_FNS, useValue: jsonpInterceptorFn, multi: true}, ]); } /**
{ "end_byte": 7344, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/provider.ts" }
angular/packages/common/http/src/provider.ts_7346_9364
Configures the current `HttpClient` instance to make requests via the parent injector's * `HttpClient` instead of directly. * * By default, `provideHttpClient` configures `HttpClient` in its injector to be an independent * instance. For example, even if `HttpClient` is configured in the parent injector with * one or more interceptors, they will not intercept requests made via this instance. * * With this option enabled, once the request has passed through the current injector's * interceptors, it will be delegated to the parent injector's `HttpClient` chain instead of * dispatched directly, and interceptors in the parent configuration will be applied to the request. * * If there are several `HttpClient` instances in the injector hierarchy, it's possible for * `withRequestsMadeViaParent` to be used at multiple levels, which will cause the request to * "bubble up" until either reaching the root level or an `HttpClient` which was not configured with * this option. * * @see {@link provideHttpClient} * @publicApi */ export function withRequestsMadeViaParent(): HttpFeature<HttpFeatureKind.RequestsMadeViaParent> { return makeHttpFeature(HttpFeatureKind.RequestsMadeViaParent, [ { provide: HttpBackend, useFactory: () => { const handlerFromParent = inject(HttpHandler, {skipSelf: true, optional: true}); if (ngDevMode && handlerFromParent === null) { throw new Error( 'withRequestsMadeViaParent() can only be used when the parent injector also configures HttpClient', ); } return handlerFromParent; }, }, ]); } /** * Configures the current `HttpClient` instance to make requests using the fetch API. * * Note: The Fetch API doesn't support progress report on uploads. * * @publicApi */ export function withFetch(): HttpFeature<HttpFeatureKind.Fetch> { return makeHttpFeature(HttpFeatureKind.Fetch, [ FetchBackend, {provide: HttpBackend, useExisting: FetchBackend}, ]); }
{ "end_byte": 9364, "start_byte": 7346, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/provider.ts" }
angular/packages/common/http/src/backend.ts_0_1328
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Observable} from 'rxjs'; import {HttpRequest} from './request'; import {HttpEvent} from './response'; /** * Transforms an `HttpRequest` into a stream of `HttpEvent`s, one of which will likely be a * `HttpResponse`. * * `HttpHandler` is injectable. When injected, the handler instance dispatches requests to the * first interceptor in the chain, which dispatches to the second, etc, eventually reaching the * `HttpBackend`. * * In an `HttpInterceptor`, the `HttpHandler` parameter is the next interceptor in the chain. * * @publicApi */ export abstract class HttpHandler { abstract handle(req: HttpRequest<any>): Observable<HttpEvent<any>>; } /** * A final `HttpHandler` which will dispatch the request via browser HTTP APIs to a backend. * * Interceptors sit between the `HttpClient` interface and the `HttpBackend`. * * When injected, `HttpBackend` dispatches requests directly to the backend, without going * through the interceptor chain. * * @publicApi */ export abstract class HttpBackend implements HttpHandler { abstract handle(req: HttpRequest<any>): Observable<HttpEvent<any>>; }
{ "end_byte": 1328, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/backend.ts" }
angular/packages/common/http/src/params.ts_0_4138
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * A codec for encoding and decoding parameters in URLs. * * Used by `HttpParams`. * * @publicApi **/ export interface HttpParameterCodec { encodeKey(key: string): string; encodeValue(value: string): string; decodeKey(key: string): string; decodeValue(value: string): string; } /** * Provides encoding and decoding of URL parameter and query-string values. * * Serializes and parses URL parameter keys and values to encode and decode them. * If you pass URL query parameters without encoding, * the query parameters can be misinterpreted at the receiving end. * * * @publicApi */ export class HttpUrlEncodingCodec implements HttpParameterCodec { /** * Encodes a key name for a URL parameter or query-string. * @param key The key name. * @returns The encoded key name. */ encodeKey(key: string): string { return standardEncoding(key); } /** * Encodes the value of a URL parameter or query-string. * @param value The value. * @returns The encoded value. */ encodeValue(value: string): string { return standardEncoding(value); } /** * Decodes an encoded URL parameter or query-string key. * @param key The encoded key name. * @returns The decoded key name. */ decodeKey(key: string): string { return decodeURIComponent(key); } /** * Decodes an encoded URL parameter or query-string value. * @param value The encoded value. * @returns The decoded value. */ decodeValue(value: string) { return decodeURIComponent(value); } } function paramParser(rawParams: string, codec: HttpParameterCodec): Map<string, string[]> { const map = new Map<string, string[]>(); if (rawParams.length > 0) { // The `window.location.search` can be used while creating an instance of the `HttpParams` class // (e.g. `new HttpParams({ fromString: window.location.search })`). The `window.location.search` // may start with the `?` char, so we strip it if it's present. const params: string[] = rawParams.replace(/^\?/, '').split('&'); params.forEach((param: string) => { const eqIdx = param.indexOf('='); const [key, val]: string[] = eqIdx == -1 ? [codec.decodeKey(param), ''] : [codec.decodeKey(param.slice(0, eqIdx)), codec.decodeValue(param.slice(eqIdx + 1))]; const list = map.get(key) || []; list.push(val); map.set(key, list); }); } return map; } /** * Encode input string with standard encodeURIComponent and then un-encode specific characters. */ const STANDARD_ENCODING_REGEX = /%(\d[a-f0-9])/gi; const STANDARD_ENCODING_REPLACEMENTS: {[x: string]: string} = { '40': '@', '3A': ':', '24': '$', '2C': ',', '3B': ';', '3D': '=', '3F': '?', '2F': '/', }; function standardEncoding(v: string): string { return encodeURIComponent(v).replace( STANDARD_ENCODING_REGEX, (s, t) => STANDARD_ENCODING_REPLACEMENTS[t] ?? s, ); } function valueToString(value: string | number | boolean): string { return `${value}`; } interface Update { param: string; value?: string | number | boolean; op: 'a' | 'd' | 's'; } /** * Options used to construct an `HttpParams` instance. * * @publicApi */ export interface HttpParamsOptions { /** * String representation of the HTTP parameters in URL-query-string format. * Mutually exclusive with `fromObject`. */ fromString?: string; /** Object map of the HTTP parameters. Mutually exclusive with `fromString`. */ fromObject?: { [param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>; }; /** Encoding codec used to parse and serialize the parameters. */ encoder?: HttpParameterCodec; } /** * An HTTP request/response body that represents serialized parameters, * per the MIME type `application/x-www-form-urlencoded`. * * This class is immutable; all mutation operations return a new instance. * * @publicApi */
{ "end_byte": 4138, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/params.ts" }
angular/packages/common/http/src/params.ts_4139_10234
export class HttpParams { private map: Map<string, string[]> | null; private encoder: HttpParameterCodec; private updates: Update[] | null = null; private cloneFrom: HttpParams | null = null; constructor(options: HttpParamsOptions = {} as HttpParamsOptions) { this.encoder = options.encoder || new HttpUrlEncodingCodec(); if (!!options.fromString) { if (!!options.fromObject) { throw new Error(`Cannot specify both fromString and fromObject.`); } this.map = paramParser(options.fromString, this.encoder); } else if (!!options.fromObject) { this.map = new Map<string, string[]>(); Object.keys(options.fromObject).forEach((key) => { const value = (options.fromObject as any)[key]; // convert the values to strings const values = Array.isArray(value) ? value.map(valueToString) : [valueToString(value)]; this.map!.set(key, values); }); } else { this.map = null; } } /** * Reports whether the body includes one or more values for a given parameter. * @param param The parameter name. * @returns True if the parameter has one or more values, * false if it has no value or is not present. */ has(param: string): boolean { this.init(); return this.map!.has(param); } /** * Retrieves the first value for a parameter. * @param param The parameter name. * @returns The first value of the given parameter, * or `null` if the parameter is not present. */ get(param: string): string | null { this.init(); const res = this.map!.get(param); return !!res ? res[0] : null; } /** * Retrieves all values for a parameter. * @param param The parameter name. * @returns All values in a string array, * or `null` if the parameter not present. */ getAll(param: string): string[] | null { this.init(); return this.map!.get(param) || null; } /** * Retrieves all the parameters for this body. * @returns The parameter names in a string array. */ keys(): string[] { this.init(); return Array.from(this.map!.keys()); } /** * Appends a new value to existing values for a parameter. * @param param The parameter name. * @param value The new value to add. * @return A new body with the appended value. */ append(param: string, value: string | number | boolean): HttpParams { return this.clone({param, value, op: 'a'}); } /** * Constructs a new body with appended values for the given parameter name. * @param params parameters and values * @return A new body with the new value. */ appendAll(params: { [param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>; }): HttpParams { const updates: Update[] = []; Object.keys(params).forEach((param) => { const value = params[param]; if (Array.isArray(value)) { value.forEach((_value) => { updates.push({param, value: _value, op: 'a'}); }); } else { updates.push({param, value: value as string | number | boolean, op: 'a'}); } }); return this.clone(updates); } /** * Replaces the value for a parameter. * @param param The parameter name. * @param value The new value. * @return A new body with the new value. */ set(param: string, value: string | number | boolean): HttpParams { return this.clone({param, value, op: 's'}); } /** * Removes a given value or all values from a parameter. * @param param The parameter name. * @param value The value to remove, if provided. * @return A new body with the given value removed, or with all values * removed if no value is specified. */ delete(param: string, value?: string | number | boolean): HttpParams { return this.clone({param, value, op: 'd'}); } /** * Serializes the body to an encoded string, where key-value pairs (separated by `=`) are * separated by `&`s. */ toString(): string { this.init(); return ( this.keys() .map((key) => { const eKey = this.encoder.encodeKey(key); // `a: ['1']` produces `'a=1'` // `b: []` produces `''` // `c: ['1', '2']` produces `'c=1&c=2'` return this.map!.get(key)! .map((value) => eKey + '=' + this.encoder.encodeValue(value)) .join('&'); }) // filter out empty values because `b: []` produces `''` // which results in `a=1&&c=1&c=2` instead of `a=1&c=1&c=2` if we don't .filter((param) => param !== '') .join('&') ); } private clone(update: Update | Update[]): HttpParams { const clone = new HttpParams({encoder: this.encoder} as HttpParamsOptions); clone.cloneFrom = this.cloneFrom || this; clone.updates = (this.updates || []).concat(update); return clone; } private init() { if (this.map === null) { this.map = new Map<string, string[]>(); } if (this.cloneFrom !== null) { this.cloneFrom.init(); this.cloneFrom.keys().forEach((key) => this.map!.set(key, this.cloneFrom!.map!.get(key)!)); this.updates!.forEach((update) => { switch (update.op) { case 'a': case 's': const base = (update.op === 'a' ? this.map!.get(update.param) : undefined) || []; base.push(valueToString(update.value!)); this.map!.set(update.param, base); break; case 'd': if (update.value !== undefined) { let base = this.map!.get(update.param) || []; const idx = base.indexOf(valueToString(update.value)); if (idx !== -1) { base.splice(idx, 1); } if (base.length > 0) { this.map!.set(update.param, base); } else { this.map!.delete(update.param); } } else { this.map!.delete(update.param); break; } } }); this.cloneFrom = this.updates = null; } } }
{ "end_byte": 10234, "start_byte": 4139, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/params.ts" }
angular/packages/common/http/src/fetch.ts_0_9211
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {inject, Injectable, NgZone} from '@angular/core'; import {Observable, Observer} from 'rxjs'; import {HttpBackend} from './backend'; import {HttpHeaders} from './headers'; import {HttpRequest} from './request'; import { HTTP_STATUS_CODE_OK, HttpDownloadProgressEvent, HttpErrorResponse, HttpEvent, HttpEventType, HttpHeaderResponse, HttpResponse, } from './response'; const XSSI_PREFIX = /^\)\]\}',?\n/; const REQUEST_URL_HEADER = `X-Request-URL`; /** * Determine an appropriate URL for the response, by checking either * response url or the X-Request-URL header. */ function getResponseUrl(response: Response): string | null { if (response.url) { return response.url; } // stored as lowercase in the map const xRequestUrl = REQUEST_URL_HEADER.toLocaleLowerCase(); return response.headers.get(xRequestUrl); } /** * Uses `fetch` to send requests to a backend server. * * This `FetchBackend` requires the support of the * [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) which is available on all * supported browsers and on Node.js v18 or later. * * @see {@link HttpHandler} * * @publicApi */ @Injectable() export class FetchBackend implements HttpBackend { // We use an arrow function to always reference the current global implementation of `fetch`. // This is helpful for cases when the global `fetch` implementation is modified by external code, // see https://github.com/angular/angular/issues/57527. private readonly fetchImpl = inject(FetchFactory, {optional: true})?.fetch ?? ((...args) => globalThis.fetch(...args)); private readonly ngZone = inject(NgZone); handle(request: HttpRequest<any>): Observable<HttpEvent<any>> { return new Observable((observer) => { const aborter = new AbortController(); this.doRequest(request, aborter.signal, observer).then(noop, (error) => observer.error(new HttpErrorResponse({error})), ); return () => aborter.abort(); }); } private async doRequest( request: HttpRequest<any>, signal: AbortSignal, observer: Observer<HttpEvent<any>>, ): Promise<void> { const init = this.createRequestInit(request); let response; try { // Run fetch outside of Angular zone. // This is due to Node.js fetch implementation (Undici) which uses a number of setTimeouts to check if // the response should eventually timeout which causes extra CD cycles every 500ms const fetchPromise = this.ngZone.runOutsideAngular(() => this.fetchImpl(request.urlWithParams, {signal, ...init}), ); // Make sure Zone.js doesn't trigger false-positive unhandled promise // error in case the Promise is rejected synchronously. See function // description for additional information. silenceSuperfluousUnhandledPromiseRejection(fetchPromise); // Send the `Sent` event before awaiting the response. observer.next({type: HttpEventType.Sent}); response = await fetchPromise; } catch (error: any) { observer.error( new HttpErrorResponse({ error, status: error.status ?? 0, statusText: error.statusText, url: request.urlWithParams, headers: error.headers, }), ); return; } const headers = new HttpHeaders(response.headers); const statusText = response.statusText; const url = getResponseUrl(response) ?? request.urlWithParams; let status = response.status; let body: string | ArrayBuffer | Blob | object | null = null; if (request.reportProgress) { observer.next(new HttpHeaderResponse({headers, status, statusText, url})); } if (response.body) { // Read Progress const contentLength = response.headers.get('content-length'); const chunks: Uint8Array[] = []; const reader = response.body.getReader(); let receivedLength = 0; let decoder: TextDecoder; let partialText: string | undefined; // We have to check whether the Zone is defined in the global scope because this may be called // when the zone is nooped. const reqZone = typeof Zone !== 'undefined' && Zone.current; // Perform response processing outside of Angular zone to // ensure no excessive change detection runs are executed // Here calling the async ReadableStreamDefaultReader.read() is responsible for triggering CD await this.ngZone.runOutsideAngular(async () => { while (true) { const {done, value} = await reader.read(); if (done) { break; } chunks.push(value); receivedLength += value.length; if (request.reportProgress) { partialText = request.responseType === 'text' ? (partialText ?? '') + (decoder ??= new TextDecoder()).decode(value, {stream: true}) : undefined; const reportProgress = () => observer.next({ type: HttpEventType.DownloadProgress, total: contentLength ? +contentLength : undefined, loaded: receivedLength, partialText, } as HttpDownloadProgressEvent); reqZone ? reqZone.run(reportProgress) : reportProgress(); } } }); // Combine all chunks. const chunksAll = this.concatChunks(chunks, receivedLength); try { const contentType = response.headers.get('Content-Type') ?? ''; body = this.parseBody(request, chunksAll, contentType); } catch (error) { // Body loading or parsing failed observer.error( new HttpErrorResponse({ error, headers: new HttpHeaders(response.headers), status: response.status, statusText: response.statusText, url: getResponseUrl(response) ?? request.urlWithParams, }), ); return; } } // Same behavior as the XhrBackend if (status === 0) { status = body ? HTTP_STATUS_CODE_OK : 0; } // ok determines whether the response will be transmitted on the event or // error channel. Unsuccessful status codes (not 2xx) will always be errors, // but a successful status code can still result in an error if the user // asked for JSON data and the body cannot be parsed as such. const ok = status >= 200 && status < 300; if (ok) { observer.next( new HttpResponse({ body, headers, status, statusText, url, }), ); // The full body has been received and delivered, no further events // are possible. This request is complete. observer.complete(); } else { observer.error( new HttpErrorResponse({ error: body, headers, status, statusText, url, }), ); } } private parseBody( request: HttpRequest<any>, binContent: Uint8Array, contentType: string, ): string | ArrayBuffer | Blob | object | null { switch (request.responseType) { case 'json': // stripping the XSSI when present const text = new TextDecoder().decode(binContent).replace(XSSI_PREFIX, ''); return text === '' ? null : (JSON.parse(text) as object); case 'text': return new TextDecoder().decode(binContent); case 'blob': return new Blob([binContent], {type: contentType}); case 'arraybuffer': return binContent.buffer; } } private createRequestInit(req: HttpRequest<any>): RequestInit { // We could share some of this logic with the XhrBackend const headers: Record<string, string> = {}; const credentials: RequestCredentials | undefined = req.withCredentials ? 'include' : undefined; // Setting all the requested headers. req.headers.forEach((name, values) => (headers[name] = values.join(','))); // Add an Accept header if one isn't present already. if (!req.headers.has('Accept')) { headers['Accept'] = 'application/json, text/plain, */*'; } // Auto-detect the Content-Type header if one isn't present already. if (!req.headers.has('Content-Type')) { const detectedType = req.detectContentTypeHeader(); // Sometimes Content-Type detection fails. if (detectedType !== null) { headers['Content-Type'] = detectedType; } } return { body: req.serializeBody(), method: req.method, headers, credentials, }; } private concatChunks(chunks: Uint8Array[], totalLength: number): Uint8Array { const chunksAll = new Uint8Array(totalLength); let position = 0; for (const chunk of chunks) { chunksAll.set(chunk, position); position += chunk.length; } return chunksAll; } } /** * Abstract class to provide a mocked implementation of `fetch()` */
{ "end_byte": 9211, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/fetch.ts" }
angular/packages/common/http/src/fetch.ts_9212_9653
export abstract class FetchFactory { abstract fetch: typeof fetch; } function noop(): void {} /** * Zone.js treats a rejected promise that has not yet been awaited * as an unhandled error. This function adds a noop `.then` to make * sure that Zone.js doesn't throw an error if the Promise is rejected * synchronously. */ function silenceSuperfluousUnhandledPromiseRejection(promise: Promise<unknown>) { promise.then(noop, noop); }
{ "end_byte": 9653, "start_byte": 9212, "url": "https://github.com/angular/angular/blob/main/packages/common/http/src/fetch.ts" }
angular/packages/common/src/dom_tokens.ts_0_561
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {InjectionToken} from '@angular/core'; /** * A DI Token representing the main rendering context. * In a browser and SSR this is the DOM Document. * When using SSR, that document is created by [Domino](https://github.com/angular/domino). * * @publicApi */ export const DOCUMENT = new InjectionToken<Document>(ngDevMode ? 'DocumentToken' : '');
{ "end_byte": 561, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/dom_tokens.ts" }
angular/packages/common/src/errors.ts_0_1236
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * The list of error codes used in runtime code of the `common` package. * Reserved error code range: 2000-2999. */ export const enum RuntimeErrorCode { // NgSwitch errors PARENT_NG_SWITCH_NOT_FOUND = 2000, EQUALITY_NG_SWITCH_DIFFERENCE = 2001, // Pipe errors INVALID_PIPE_ARGUMENT = 2100, // NgForOf errors NG_FOR_MISSING_DIFFER = -2200, // Keep 2800 - 2900 for Http Errors. // Image directive errors UNEXPECTED_SRC_ATTR = 2950, UNEXPECTED_SRCSET_ATTR = 2951, INVALID_INPUT = 2952, UNEXPECTED_INPUT_CHANGE = 2953, REQUIRED_INPUT_MISSING = 2954, LCP_IMG_MISSING_PRIORITY = 2955, PRIORITY_IMG_MISSING_PRECONNECT_TAG = 2956, UNEXPECTED_DEV_MODE_CHECK_IN_PROD_MODE = 2958, INVALID_LOADER_ARGUMENTS = 2959, OVERSIZED_IMAGE = 2960, TOO_MANY_PRELOADED_IMAGES = 2961, MISSING_BUILTIN_LOADER = 2962, MISSING_NECESSARY_LOADER = 2963, LCP_IMG_NGSRC_MODIFIED = 2964, OVERSIZED_PLACEHOLDER = 2965, TOO_MANY_PRIORITY_ATTRIBUTES = 2966, PLACEHOLDER_DIMENSION_LIMIT_EXCEEDED = 2967, }
{ "end_byte": 1236, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/errors.ts" }
angular/packages/common/src/xhr.ts_0_356
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * A wrapper around the `XMLHttpRequest` constructor. * * @publicApi */ export abstract class XhrFactory { abstract build(): XMLHttpRequest; }
{ "end_byte": 356, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/xhr.ts" }
angular/packages/common/src/common.ts_0_2751
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * @module * @description * Entry point for all public APIs of the common package. */ export * from './private_export'; export * from './location/index'; export {formatDate} from './i18n/format_date'; export {formatCurrency, formatNumber, formatPercent} from './i18n/format_number'; export {NgLocaleLocalization, NgLocalization} from './i18n/localization'; export {registerLocaleData} from './i18n/locale_data'; export { Plural, NumberFormatStyle, FormStyle, Time, TranslationWidth, FormatWidth, NumberSymbol, WeekDay, getNumberOfCurrencyDigits, getCurrencySymbol, getLocaleDayPeriods, getLocaleDayNames, getLocaleMonthNames, getLocaleId, getLocaleEraNames, getLocaleWeekEndRange, getLocaleFirstDayOfWeek, getLocaleDateFormat, getLocaleDateTimeFormat, getLocaleExtraDayPeriodRules, getLocaleExtraDayPeriods, getLocalePluralCase, getLocaleTimeFormat, getLocaleNumberSymbol, getLocaleNumberFormat, getLocaleCurrencyCode, getLocaleCurrencyName, getLocaleCurrencySymbol, getLocaleDirection, } from './i18n/locale_data_api'; export {parseCookieValue as ɵparseCookieValue} from './cookie'; export {CommonModule} from './common_module'; export { NgClass, NgFor, NgForOf, NgForOfContext, NgIf, NgIfContext, NgPlural, NgPluralCase, NgStyle, NgSwitch, NgSwitchCase, NgSwitchDefault, NgTemplateOutlet, NgComponentOutlet, } from './directives/index'; export {DOCUMENT} from './dom_tokens'; export { AsyncPipe, DatePipe, DatePipeConfig, DATE_PIPE_DEFAULT_TIMEZONE, DATE_PIPE_DEFAULT_OPTIONS, I18nPluralPipe, I18nSelectPipe, JsonPipe, LowerCasePipe, CurrencyPipe, DecimalPipe, PercentPipe, SlicePipe, UpperCasePipe, TitleCasePipe, KeyValuePipe, KeyValue, } from './pipes/index'; export { PLATFORM_BROWSER_ID as ɵPLATFORM_BROWSER_ID, PLATFORM_SERVER_ID as ɵPLATFORM_SERVER_ID, isPlatformBrowser, isPlatformServer, } from './platform_id'; export {VERSION} from './version'; export {ViewportScroller, NullViewportScroller as ɵNullViewportScroller} from './viewport_scroller'; export {XhrFactory} from './xhr'; export { IMAGE_CONFIG, ImageConfig, IMAGE_LOADER, ImageLoader, ImageLoaderConfig, NgOptimizedImage, ImagePlaceholderConfig, PRECONNECT_CHECK_BLOCKLIST, provideCloudflareLoader, provideCloudinaryLoader, provideImageKitLoader, provideImgixLoader, provideNetlifyLoader, } from './directives/ng_optimized_image'; export {normalizeQueryParams as ɵnormalizeQueryParams} from './location/util';
{ "end_byte": 2751, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/common.ts" }
angular/packages/common/src/private_export.ts_0_426
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export { DomAdapter as ɵDomAdapter, getDOM as ɵgetDOM, setRootDomAdapter as ɵsetRootDomAdapter, } from './dom_adapter'; export {PlatformNavigation as ɵPlatformNavigation} from './navigation/platform_navigation';
{ "end_byte": 426, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/private_export.ts" }
angular/packages/common/src/platform_id.ts_0_689
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export const PLATFORM_BROWSER_ID = 'browser'; export const PLATFORM_SERVER_ID = 'server'; /** * Returns whether a platform id represents a browser platform. * @publicApi */ export function isPlatformBrowser(platformId: Object): boolean { return platformId === PLATFORM_BROWSER_ID; } /** * Returns whether a platform id represents a server platform. * @publicApi */ export function isPlatformServer(platformId: Object): boolean { return platformId === PLATFORM_SERVER_ID; }
{ "end_byte": 689, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/platform_id.ts" }
angular/packages/common/src/cookie.ts_0_661
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export function parseCookieValue(cookieStr: string, name: string): string | null { name = encodeURIComponent(name); for (const cookie of cookieStr.split(';')) { const eqIndex = cookie.indexOf('='); const [cookieName, cookieValue]: string[] = eqIndex == -1 ? [cookie, ''] : [cookie.slice(0, eqIndex), cookie.slice(eqIndex + 1)]; if (cookieName.trim() === name) { return decodeURIComponent(cookieValue); } } return null; }
{ "end_byte": 661, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/cookie.ts" }
angular/packages/common/src/viewport_scroller.ts_0_6865
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {inject, PLATFORM_ID, ɵɵdefineInjectable} from '@angular/core'; import {DOCUMENT} from './dom_tokens'; import {isPlatformBrowser} from './platform_id'; /** * Defines a scroll position manager. Implemented by `BrowserViewportScroller`. * * @publicApi */ export abstract class ViewportScroller { // De-sugared tree-shakable injection // See #23917 /** @nocollapse */ static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({ token: ViewportScroller, providedIn: 'root', factory: () => isPlatformBrowser(inject(PLATFORM_ID)) ? new BrowserViewportScroller(inject(DOCUMENT), window) : new NullViewportScroller(), }); /** * Configures the top offset used when scrolling to an anchor. * @param offset A position in screen coordinates (a tuple with x and y values) * or a function that returns the top offset position. * */ abstract setOffset(offset: [number, number] | (() => [number, number])): void; /** * Retrieves the current scroll position. * @returns A position in screen coordinates (a tuple with x and y values). */ abstract getScrollPosition(): [number, number]; /** * Scrolls to a specified position. * @param position A position in screen coordinates (a tuple with x and y values). */ abstract scrollToPosition(position: [number, number]): void; /** * Scrolls to an anchor element. * @param anchor The ID of the anchor element. */ abstract scrollToAnchor(anchor: string): void; /** * Disables automatic scroll restoration provided by the browser. * See also [window.history.scrollRestoration * info](https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration). */ abstract setHistoryScrollRestoration(scrollRestoration: 'auto' | 'manual'): void; } /** * Manages the scroll position for a browser window. */ export class BrowserViewportScroller implements ViewportScroller { private offset: () => [number, number] = () => [0, 0]; constructor( private document: Document, private window: Window, ) {} /** * Configures the top offset used when scrolling to an anchor. * @param offset A position in screen coordinates (a tuple with x and y values) * or a function that returns the top offset position. * */ setOffset(offset: [number, number] | (() => [number, number])): void { if (Array.isArray(offset)) { this.offset = () => offset; } else { this.offset = offset; } } /** * Retrieves the current scroll position. * @returns The position in screen coordinates. */ getScrollPosition(): [number, number] { return [this.window.scrollX, this.window.scrollY]; } /** * Sets the scroll position. * @param position The new position in screen coordinates. */ scrollToPosition(position: [number, number]): void { this.window.scrollTo(position[0], position[1]); } /** * Scrolls to an element and attempts to focus the element. * * Note that the function name here is misleading in that the target string may be an ID for a * non-anchor element. * * @param target The ID of an element or name of the anchor. * * @see https://html.spec.whatwg.org/#the-indicated-part-of-the-document * @see https://html.spec.whatwg.org/#scroll-to-fragid */ scrollToAnchor(target: string): void { const elSelected = findAnchorFromDocument(this.document, target); if (elSelected) { this.scrollToElement(elSelected); // After scrolling to the element, the spec dictates that we follow the focus steps for the // target. Rather than following the robust steps, simply attempt focus. // // @see https://html.spec.whatwg.org/#get-the-focusable-area // @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/focus // @see https://html.spec.whatwg.org/#focusable-area elSelected.focus(); } } /** * Disables automatic scroll restoration provided by the browser. */ setHistoryScrollRestoration(scrollRestoration: 'auto' | 'manual'): void { this.window.history.scrollRestoration = scrollRestoration; } /** * Scrolls to an element using the native offset and the specified offset set on this scroller. * * The offset can be used when we know that there is a floating header and scrolling naively to an * element (ex: `scrollIntoView`) leaves the element hidden behind the floating header. */ private scrollToElement(el: HTMLElement): void { const rect = el.getBoundingClientRect(); const left = rect.left + this.window.pageXOffset; const top = rect.top + this.window.pageYOffset; const offset = this.offset(); this.window.scrollTo(left - offset[0], top - offset[1]); } } function findAnchorFromDocument(document: Document, target: string): HTMLElement | null { const documentResult = document.getElementById(target) || document.getElementsByName(target)[0]; if (documentResult) { return documentResult; } // `getElementById` and `getElementsByName` won't pierce through the shadow DOM so we // have to traverse the DOM manually and do the lookup through the shadow roots. if ( typeof document.createTreeWalker === 'function' && document.body && typeof document.body.attachShadow === 'function' ) { const treeWalker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT); let currentNode = treeWalker.currentNode as HTMLElement | null; while (currentNode) { const shadowRoot = currentNode.shadowRoot; if (shadowRoot) { // Note that `ShadowRoot` doesn't support `getElementsByName` // so we have to fall back to `querySelector`. const result = shadowRoot.getElementById(target) || shadowRoot.querySelector(`[name="${target}"]`); if (result) { return result; } } currentNode = treeWalker.nextNode() as HTMLElement | null; } } return null; } /** * Provides an empty implementation of the viewport scroller. */ export class NullViewportScroller implements ViewportScroller { /** * Empty implementation */ setOffset(offset: [number, number] | (() => [number, number])): void {} /** * Empty implementation */ getScrollPosition(): [number, number] { return [0, 0]; } /** * Empty implementation */ scrollToPosition(position: [number, number]): void {} /** * Empty implementation */ scrollToAnchor(anchor: string): void {} /** * Empty implementation */ setHistoryScrollRestoration(scrollRestoration: 'auto' | 'manual'): void {} }
{ "end_byte": 6865, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/viewport_scroller.ts" }
angular/packages/common/src/dom_adapter.ts_0_1673
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ let _DOM: DomAdapter = null!; export function getDOM(): DomAdapter { return _DOM; } export function setRootDomAdapter(adapter: DomAdapter) { _DOM ??= adapter; } /* tslint:disable:requireParameterType */ /** * Provides DOM operations in an environment-agnostic way. * * @security Tread carefully! Interacting with the DOM directly is dangerous and * can introduce XSS risks. */ export abstract class DomAdapter { // Needs Domino-friendly test utility abstract dispatchEvent(el: any, evt: any): any; abstract readonly supportsDOMEvents: boolean; // Used by Meta abstract remove(el: any): void; abstract createElement(tagName: any, doc?: any): HTMLElement; abstract createHtmlDocument(): Document; abstract getDefaultDocument(): Document; // Used by By.css abstract isElementNode(node: any): boolean; // Used by Testability abstract isShadowRoot(node: any): boolean; // Used by KeyEventsPlugin abstract onAndCancel(el: any, evt: any, listener: any): Function; // Used by PlatformLocation and ServerEventManagerPlugin abstract getGlobalEventTarget(doc: Document, target: string): any; // Used by PlatformLocation abstract getBaseHref(doc: Document): string | null; abstract resetBaseElement(): void; // TODO: remove dependency in DefaultValueAccessor abstract getUserAgent(): string; // Used in the legacy @angular/http package which has some usage in g3. abstract getCookie(name: string): string | null; }
{ "end_byte": 1673, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/dom_adapter.ts" }
angular/packages/common/src/version.ts_0_417
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * @module * @description * Entry point for all public APIs of the common package. */ import {Version} from '@angular/core'; /** * @publicApi */ export const VERSION = new Version('0.0.0-PLACEHOLDER');
{ "end_byte": 417, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/version.ts" }
angular/packages/common/src/common_module.ts_0_883
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {NgModule} from '@angular/core'; import {COMMON_DIRECTIVES} from './directives/index'; import {COMMON_PIPES} from './pipes/index'; // Note: This does not contain the location providers, // as they need some platform specific implementations to work. /** * Exports all the basic Angular directives and pipes, * such as `NgIf`, `NgForOf`, `DecimalPipe`, and so on. * Re-exported by `BrowserModule`, which is included automatically in the root * `AppModule` when you create a new app with the CLI `new` command. * * @publicApi */ @NgModule({ imports: [COMMON_DIRECTIVES, COMMON_PIPES], exports: [COMMON_DIRECTIVES, COMMON_PIPES], }) export class CommonModule {}
{ "end_byte": 883, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/common_module.ts" }
angular/packages/common/src/directives/ng_style.ts_0_3099
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Directive, DoCheck, ElementRef, Input, KeyValueChanges, KeyValueDiffer, KeyValueDiffers, Renderer2, RendererStyleFlags2, } from '@angular/core'; /** * @ngModule CommonModule * * @usageNotes * * Set the font of the containing element to the result of an expression. * * ``` * <some-element [ngStyle]="{'font-style': styleExp}">...</some-element> * ``` * * Set the width of the containing element to a pixel value returned by an expression. * * ``` * <some-element [ngStyle]="{'max-width.px': widthExp}">...</some-element> * ``` * * Set a collection of style values using an expression that returns key-value pairs. * * ``` * <some-element [ngStyle]="objExp">...</some-element> * ``` * * @description * * An attribute directive that updates styles for the containing HTML element. * Sets one or more style properties, specified as colon-separated key-value pairs. * The key is a style name, with an optional `.<unit>` suffix * (such as 'top.px', 'font-style.em'). * The value is an expression to be evaluated. * The resulting non-null value, expressed in the given unit, * is assigned to the given style property. * If the result of evaluation is null, the corresponding style is removed. * * @publicApi */ @Directive({ selector: '[ngStyle]', standalone: true, }) export class NgStyle implements DoCheck { private _ngStyle: {[key: string]: string} | null | undefined = null; private _differ: KeyValueDiffer<string, string | number> | null = null; constructor( private _ngEl: ElementRef, private _differs: KeyValueDiffers, private _renderer: Renderer2, ) {} @Input('ngStyle') set ngStyle(values: {[klass: string]: any} | null | undefined) { this._ngStyle = values; if (!this._differ && values) { this._differ = this._differs.find(values).create(); } } ngDoCheck() { if (this._differ) { const changes = this._differ.diff(this._ngStyle!); if (changes) { this._applyChanges(changes); } } } private _setStyle(nameAndUnit: string, value: string | number | null | undefined): void { const [name, unit] = nameAndUnit.split('.'); const flags = name.indexOf('-') === -1 ? undefined : (RendererStyleFlags2.DashCase as number); if (value != null) { this._renderer.setStyle( this._ngEl.nativeElement, name, unit ? `${value}${unit}` : value, flags, ); } else { this._renderer.removeStyle(this._ngEl.nativeElement, name, flags); } } private _applyChanges(changes: KeyValueChanges<string, string | number>): void { changes.forEachRemovedItem((record) => this._setStyle(record.key, null)); changes.forEachAddedItem((record) => this._setStyle(record.key, record.currentValue)); changes.forEachChangedItem((record) => this._setStyle(record.key, record.currentValue)); } }
{ "end_byte": 3099, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_style.ts" }
angular/packages/common/src/directives/ng_plural.ts_0_3425
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Attribute, Directive, Host, Input, TemplateRef, ViewContainerRef} from '@angular/core'; import {getPluralCategory, NgLocalization} from '../i18n/localization'; import {SwitchView} from './ng_switch'; /** * @ngModule CommonModule * * @usageNotes * ``` * <some-element [ngPlural]="value"> * <ng-template ngPluralCase="=0">there is nothing</ng-template> * <ng-template ngPluralCase="=1">there is one</ng-template> * <ng-template ngPluralCase="few">there are a few</ng-template> * </some-element> * ``` * * @description * * Adds / removes DOM sub-trees based on a numeric value. Tailored for pluralization. * * Displays DOM sub-trees that match the switch expression value, or failing that, DOM sub-trees * that match the switch expression's pluralization category. * * To use this directive you must provide a container element that sets the `[ngPlural]` attribute * to a switch expression. Inner elements with a `[ngPluralCase]` will display based on their * expression: * - if `[ngPluralCase]` is set to a value starting with `=`, it will only display if the value * matches the switch expression exactly, * - otherwise, the view will be treated as a "category match", and will only display if exact * value matches aren't found and the value maps to its category for the defined locale. * * See http://cldr.unicode.org/index/cldr-spec/plural-rules * * @publicApi */ @Directive({ selector: '[ngPlural]', standalone: true, }) export class NgPlural { private _activeView?: SwitchView; private _caseViews: {[k: string]: SwitchView} = {}; constructor(private _localization: NgLocalization) {} @Input() set ngPlural(value: number) { this._updateView(value); } addCase(value: string, switchView: SwitchView): void { this._caseViews[value] = switchView; } private _updateView(switchValue: number): void { this._clearViews(); const cases = Object.keys(this._caseViews); const key = getPluralCategory(switchValue, cases, this._localization); this._activateView(this._caseViews[key]); } private _clearViews() { if (this._activeView) this._activeView.destroy(); } private _activateView(view: SwitchView) { if (view) { this._activeView = view; this._activeView.create(); } } } /** * @ngModule CommonModule * * @description * * Creates a view that will be added/removed from the parent {@link NgPlural} when the * given expression matches the plural expression according to CLDR rules. * * @usageNotes * ``` * <some-element [ngPlural]="value"> * <ng-template ngPluralCase="=0">...</ng-template> * <ng-template ngPluralCase="other">...</ng-template> * </some-element> *``` * * See {@link NgPlural} for more details and example. * * @publicApi */ @Directive({ selector: '[ngPluralCase]', standalone: true, }) export class NgPluralCase { constructor( @Attribute('ngPluralCase') public value: string, template: TemplateRef<Object>, viewContainer: ViewContainerRef, @Host() ngPlural: NgPlural, ) { const isANumber: boolean = !isNaN(Number(value)); ngPlural.addCase(isANumber ? `=${value}` : value, new SwitchView(viewContainer, template)); } }
{ "end_byte": 3425, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_plural.ts" }
angular/packages/common/src/directives/ng_component_outlet.ts_0_7183
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { ComponentRef, createNgModule, Directive, DoCheck, Injector, Input, NgModuleFactory, NgModuleRef, OnChanges, OnDestroy, SimpleChanges, Type, ViewContainerRef, } from '@angular/core'; /** * Instantiates a {@link Component} type and inserts its Host View into the current View. * `NgComponentOutlet` provides a declarative approach for dynamic component creation. * * `NgComponentOutlet` requires a component type, if a falsy value is set the view will clear and * any existing component will be destroyed. * * @usageNotes * * ### Fine tune control * * You can control the component creation process by using the following optional attributes: * * * `ngComponentOutletInputs`: Optional component inputs object, which will be bind to the * component. * * * `ngComponentOutletInjector`: Optional custom {@link Injector} that will be used as parent for * the Component. Defaults to the injector of the current view container. * * * `ngComponentOutletContent`: Optional list of projectable nodes to insert into the content * section of the component, if it exists. * * * `ngComponentOutletNgModule`: Optional NgModule class reference to allow loading another * module dynamically, then loading a component from that module. * * * `ngComponentOutletNgModuleFactory`: Deprecated config option that allows providing optional * NgModule factory to allow loading another module dynamically, then loading a component from that * module. Use `ngComponentOutletNgModule` instead. * * ### Syntax * * Simple * ``` * <ng-container *ngComponentOutlet="componentTypeExpression"></ng-container> * ``` * * With inputs * ``` * <ng-container *ngComponentOutlet="componentTypeExpression; * inputs: inputsExpression;"> * </ng-container> * ``` * * Customized injector/content * ``` * <ng-container *ngComponentOutlet="componentTypeExpression; * injector: injectorExpression; * content: contentNodesExpression;"> * </ng-container> * ``` * * Customized NgModule reference * ``` * <ng-container *ngComponentOutlet="componentTypeExpression; * ngModule: ngModuleClass;"> * </ng-container> * ``` * * ### A simple example * * {@example common/ngComponentOutlet/ts/module.ts region='SimpleExample'} * * A more complete example with additional options: * * {@example common/ngComponentOutlet/ts/module.ts region='CompleteExample'} * * @publicApi * @ngModule CommonModule */ @Directive({ selector: '[ngComponentOutlet]', standalone: true, }) export class NgComponentOutlet implements OnChanges, DoCheck, OnDestroy { @Input() ngComponentOutlet: Type<any> | null = null; @Input() ngComponentOutletInputs?: Record<string, unknown>; @Input() ngComponentOutletInjector?: Injector; @Input() ngComponentOutletContent?: any[][]; @Input() ngComponentOutletNgModule?: Type<any>; /** * @deprecated This input is deprecated, use `ngComponentOutletNgModule` instead. */ @Input() ngComponentOutletNgModuleFactory?: NgModuleFactory<any>; private _componentRef: ComponentRef<any> | undefined; private _moduleRef: NgModuleRef<any> | undefined; /** * A helper data structure that allows us to track inputs that were part of the * ngComponentOutletInputs expression. Tracking inputs is necessary for proper removal of ones * that are no longer referenced. */ private _inputsUsed = new Map<string, boolean>(); constructor(private _viewContainerRef: ViewContainerRef) {} private _needToReCreateNgModuleInstance(changes: SimpleChanges): boolean { // Note: square brackets property accessor is safe for Closure compiler optimizations (the // `changes` argument of the `ngOnChanges` lifecycle hook retains the names of the fields that // were changed). return ( changes['ngComponentOutletNgModule'] !== undefined || changes['ngComponentOutletNgModuleFactory'] !== undefined ); } private _needToReCreateComponentInstance(changes: SimpleChanges): boolean { // Note: square brackets property accessor is safe for Closure compiler optimizations (the // `changes` argument of the `ngOnChanges` lifecycle hook retains the names of the fields that // were changed). return ( changes['ngComponentOutlet'] !== undefined || changes['ngComponentOutletContent'] !== undefined || changes['ngComponentOutletInjector'] !== undefined || this._needToReCreateNgModuleInstance(changes) ); } /** @nodoc */ ngOnChanges(changes: SimpleChanges) { if (this._needToReCreateComponentInstance(changes)) { this._viewContainerRef.clear(); this._inputsUsed.clear(); this._componentRef = undefined; if (this.ngComponentOutlet) { const injector = this.ngComponentOutletInjector || this._viewContainerRef.parentInjector; if (this._needToReCreateNgModuleInstance(changes)) { this._moduleRef?.destroy(); if (this.ngComponentOutletNgModule) { this._moduleRef = createNgModule( this.ngComponentOutletNgModule, getParentInjector(injector), ); } else if (this.ngComponentOutletNgModuleFactory) { this._moduleRef = this.ngComponentOutletNgModuleFactory.create( getParentInjector(injector), ); } else { this._moduleRef = undefined; } } this._componentRef = this._viewContainerRef.createComponent(this.ngComponentOutlet, { injector, ngModuleRef: this._moduleRef, projectableNodes: this.ngComponentOutletContent, }); } } } /** @nodoc */ ngDoCheck() { if (this._componentRef) { if (this.ngComponentOutletInputs) { for (const inputName of Object.keys(this.ngComponentOutletInputs)) { this._inputsUsed.set(inputName, true); } } this._applyInputStateDiff(this._componentRef); } } /** @nodoc */ ngOnDestroy() { this._moduleRef?.destroy(); } private _applyInputStateDiff(componentRef: ComponentRef<unknown>) { for (const [inputName, touched] of this._inputsUsed) { if (!touched) { // The input that was previously active no longer exists and needs to be set to undefined. componentRef.setInput(inputName, undefined); this._inputsUsed.delete(inputName); } else { // Since touched is true, it can be asserted that the inputs object is not empty. componentRef.setInput(inputName, this.ngComponentOutletInputs![inputName]); this._inputsUsed.set(inputName, false); } } } } // Helper function that returns an Injector instance of a parent NgModule. function getParentInjector(injector: Injector): Injector { const parentNgModule = injector.get(NgModuleRef); return parentNgModule.injector; }
{ "end_byte": 7183, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_component_outlet.ts" }
angular/packages/common/src/directives/ng_switch.ts_0_8075
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Directive, DoCheck, Host, Input, Optional, TemplateRef, ViewContainerRef, ɵRuntimeError as RuntimeError, } from '@angular/core'; import {RuntimeErrorCode} from '../errors'; export class SwitchView { private _created = false; constructor( private _viewContainerRef: ViewContainerRef, private _templateRef: TemplateRef<Object>, ) {} create(): void { this._created = true; this._viewContainerRef.createEmbeddedView(this._templateRef); } destroy(): void { this._created = false; this._viewContainerRef.clear(); } enforceState(created: boolean) { if (created && !this._created) { this.create(); } else if (!created && this._created) { this.destroy(); } } } /** * @ngModule CommonModule * * @description * The `[ngSwitch]` directive on a container specifies an expression to match against. * The expressions to match are provided by `ngSwitchCase` directives on views within the container. * - Every view that matches is rendered. * - If there are no matches, a view with the `ngSwitchDefault` directive is rendered. * - Elements within the `[NgSwitch]` statement but outside of any `NgSwitchCase` * or `ngSwitchDefault` directive are preserved at the location. * * @usageNotes * Define a container element for the directive, and specify the switch expression * to match against as an attribute: * * ``` * <container-element [ngSwitch]="switch_expression"> * ``` * * Within the container, `*ngSwitchCase` statements specify the match expressions * as attributes. Include `*ngSwitchDefault` as the final case. * * ``` * <container-element [ngSwitch]="switch_expression"> * <some-element *ngSwitchCase="match_expression_1">...</some-element> * ... * <some-element *ngSwitchDefault>...</some-element> * </container-element> * ``` * * ### Usage Examples * * The following example shows how to use more than one case to display the same view: * * ``` * <container-element [ngSwitch]="switch_expression"> * <!-- the same view can be shown in more than one case --> * <some-element *ngSwitchCase="match_expression_1">...</some-element> * <some-element *ngSwitchCase="match_expression_2">...</some-element> * <some-other-element *ngSwitchCase="match_expression_3">...</some-other-element> * <!--default case when there are no matches --> * <some-element *ngSwitchDefault>...</some-element> * </container-element> * ``` * * The following example shows how cases can be nested: * ``` * <container-element [ngSwitch]="switch_expression"> * <some-element *ngSwitchCase="match_expression_1">...</some-element> * <some-element *ngSwitchCase="match_expression_2">...</some-element> * <some-other-element *ngSwitchCase="match_expression_3">...</some-other-element> * <ng-container *ngSwitchCase="match_expression_3"> * <!-- use a ng-container to group multiple root nodes --> * <inner-element></inner-element> * <inner-other-element></inner-other-element> * </ng-container> * <some-element *ngSwitchDefault>...</some-element> * </container-element> * ``` * * @publicApi * @see {@link NgSwitchCase} * @see {@link NgSwitchDefault} * @see [Structural Directives](guide/directives/structural-directives) * */ @Directive({ selector: '[ngSwitch]', standalone: true, }) export class NgSwitch { private _defaultViews: SwitchView[] = []; private _defaultUsed = false; private _caseCount = 0; private _lastCaseCheckIndex = 0; private _lastCasesMatched = false; private _ngSwitch: any; @Input() set ngSwitch(newValue: any) { this._ngSwitch = newValue; if (this._caseCount === 0) { this._updateDefaultCases(true); } } /** @internal */ _addCase(): number { return this._caseCount++; } /** @internal */ _addDefault(view: SwitchView) { this._defaultViews.push(view); } /** @internal */ _matchCase(value: any): boolean { const matched = value === this._ngSwitch; this._lastCasesMatched ||= matched; this._lastCaseCheckIndex++; if (this._lastCaseCheckIndex === this._caseCount) { this._updateDefaultCases(!this._lastCasesMatched); this._lastCaseCheckIndex = 0; this._lastCasesMatched = false; } return matched; } private _updateDefaultCases(useDefault: boolean) { if (this._defaultViews.length > 0 && useDefault !== this._defaultUsed) { this._defaultUsed = useDefault; for (const defaultView of this._defaultViews) { defaultView.enforceState(useDefault); } } } } /** * @ngModule CommonModule * * @description * Provides a switch case expression to match against an enclosing `ngSwitch` expression. * When the expressions match, the given `NgSwitchCase` template is rendered. * If multiple match expressions match the switch expression value, all of them are displayed. * * @usageNotes * * Within a switch container, `*ngSwitchCase` statements specify the match expressions * as attributes. Include `*ngSwitchDefault` as the final case. * * ``` * <container-element [ngSwitch]="switch_expression"> * <some-element *ngSwitchCase="match_expression_1">...</some-element> * ... * <some-element *ngSwitchDefault>...</some-element> * </container-element> * ``` * * Each switch-case statement contains an in-line HTML template or template reference * that defines the subtree to be selected if the value of the match expression * matches the value of the switch expression. * * As of Angular v17 the NgSwitch directive uses strict equality comparison (`===`) instead of * loose equality (`==`) to match different cases. * * @publicApi * @see {@link NgSwitch} * @see {@link NgSwitchDefault} * */ @Directive({ selector: '[ngSwitchCase]', standalone: true, }) export class NgSwitchCase implements DoCheck { private _view: SwitchView; /** * Stores the HTML template to be selected on match. */ @Input() ngSwitchCase: any; constructor( viewContainer: ViewContainerRef, templateRef: TemplateRef<Object>, @Optional() @Host() private ngSwitch: NgSwitch, ) { if ((typeof ngDevMode === 'undefined' || ngDevMode) && !ngSwitch) { throwNgSwitchProviderNotFoundError('ngSwitchCase', 'NgSwitchCase'); } ngSwitch._addCase(); this._view = new SwitchView(viewContainer, templateRef); } /** * Performs case matching. For internal use only. * @nodoc */ ngDoCheck() { this._view.enforceState(this.ngSwitch._matchCase(this.ngSwitchCase)); } } /** * @ngModule CommonModule * * @description * * Creates a view that is rendered when no `NgSwitchCase` expressions * match the `NgSwitch` expression. * This statement should be the final case in an `NgSwitch`. * * @publicApi * @see {@link NgSwitch} * @see {@link NgSwitchCase} * */ @Directive({ selector: '[ngSwitchDefault]', standalone: true, }) export class NgSwitchDefault { constructor( viewContainer: ViewContainerRef, templateRef: TemplateRef<Object>, @Optional() @Host() ngSwitch: NgSwitch, ) { if ((typeof ngDevMode === 'undefined' || ngDevMode) && !ngSwitch) { throwNgSwitchProviderNotFoundError('ngSwitchDefault', 'NgSwitchDefault'); } ngSwitch._addDefault(new SwitchView(viewContainer, templateRef)); } } function throwNgSwitchProviderNotFoundError(attrName: string, directiveName: string): never { throw new RuntimeError( RuntimeErrorCode.PARENT_NG_SWITCH_NOT_FOUND, `An element with the "${attrName}" attribute ` + `(matching the "${directiveName}" directive) must be located inside an element with the "ngSwitch" attribute ` + `(matching "NgSwitch" directive)`, ); } function stringifyValue(value: unknown): string { return typeof value === 'string' ? `'${value}'` : String(value); }
{ "end_byte": 8075, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_switch.ts" }
angular/packages/common/src/directives/ng_if.ts_0_5553
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Directive, EmbeddedViewRef, Input, TemplateRef, ViewContainerRef, ɵstringify as stringify, } from '@angular/core'; /** * A structural directive that conditionally includes a template based on the value of * an expression coerced to Boolean. * When the expression evaluates to true, Angular renders the template * provided in a `then` clause, and when false or null, * Angular renders the template provided in an optional `else` clause. The default * template for the `else` clause is blank. * * A [shorthand form](guide/directives/structural-directives#asterisk) of the directive, * `*ngIf="condition"`, is generally used, provided * as an attribute of the anchor element for the inserted template. * Angular expands this into a more explicit version, in which the anchor element * is contained in an `<ng-template>` element. * * Simple form with shorthand syntax: * * ``` * <div *ngIf="condition">Content to render when condition is true.</div> * ``` * * Simple form with expanded syntax: * * ``` * <ng-template [ngIf]="condition"><div>Content to render when condition is * true.</div></ng-template> * ``` * * Form with an "else" block: * * ``` * <div *ngIf="condition; else elseBlock">Content to render when condition is true.</div> * <ng-template #elseBlock>Content to render when condition is false.</ng-template> * ``` * * Shorthand form with "then" and "else" blocks: * * ``` * <div *ngIf="condition; then thenBlock else elseBlock"></div> * <ng-template #thenBlock>Content to render when condition is true.</ng-template> * <ng-template #elseBlock>Content to render when condition is false.</ng-template> * ``` * * Form with storing the value locally: * * ``` * <div *ngIf="condition as value; else elseBlock">{{value}}</div> * <ng-template #elseBlock>Content to render when value is null.</ng-template> * ``` * * @usageNotes * * The `*ngIf` directive is most commonly used to conditionally show an inline template, * as seen in the following example. * The default `else` template is blank. * * {@example common/ngIf/ts/module.ts region='NgIfSimple'} * * ### Showing an alternative template using `else` * * To display a template when `expression` evaluates to false, use an `else` template * binding as shown in the following example. * The `else` binding points to an `<ng-template>` element labeled `#elseBlock`. * The template can be defined anywhere in the component view, but is typically placed right after * `ngIf` for readability. * * {@example common/ngIf/ts/module.ts region='NgIfElse'} * * ### Using an external `then` template * * In the previous example, the then-clause template is specified inline, as the content of the * tag that contains the `ngIf` directive. You can also specify a template that is defined * externally, by referencing a labeled `<ng-template>` element. When you do this, you can * change which template to use at runtime, as shown in the following example. * * {@example common/ngIf/ts/module.ts region='NgIfThenElse'} * * ### Storing a conditional result in a variable * * You might want to show a set of properties from the same object. If you are waiting * for asynchronous data, the object can be undefined. * In this case, you can use `ngIf` and store the result of the condition in a local * variable as shown in the following example. * * {@example common/ngIf/ts/module.ts region='NgIfAs'} * * This code uses only one `AsyncPipe`, so only one subscription is created. * The conditional statement stores the result of `userStream|async` in the local variable `user`. * You can then bind the local `user` repeatedly. * * The conditional displays the data only if `userStream` returns a value, * so you don't need to use the * safe-navigation-operator (`?.`) * to guard against null values when accessing properties. * You can display an alternative template while waiting for the data. * * ### Shorthand syntax * * The shorthand syntax `*ngIf` expands into two separate template specifications * for the "then" and "else" clauses. For example, consider the following shorthand statement, * that is meant to show a loading page while waiting for data to be loaded. * * ``` * <div class="hero-list" *ngIf="heroes else loading"> * ... * </div> * * <ng-template #loading> * <div>Loading...</div> * </ng-template> * ``` * * You can see that the "else" clause references the `<ng-template>` * with the `#loading` label, and the template for the "then" clause * is provided as the content of the anchor element. * * However, when Angular expands the shorthand syntax, it creates * another `<ng-template>` tag, with `ngIf` and `ngIfElse` directives. * The anchor element containing the template for the "then" clause becomes * the content of this unlabeled `<ng-template>` tag. * * ``` * <ng-template [ngIf]="heroes" [ngIfElse]="loading"> * <div class="hero-list"> * ... * </div> * </ng-template> * * <ng-template #loading> * <div>Loading...</div> * </ng-template> * ``` * * The presence of the implicit template object has implications for the nesting of * structural directives. For more on this subject, see * [Structural Directives](guide/directives/structural-directives#one-per-element). * * @ngModule CommonModule * @publicApi */
{ "end_byte": 5553, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_if.ts" }
angular/packages/common/src/directives/ng_if.ts_5554_9217
Directive({ selector: '[ngIf]', standalone: true, }) export class NgIf<T = unknown> { private _context: NgIfContext<T> = new NgIfContext<T>(); private _thenTemplateRef: TemplateRef<NgIfContext<T>> | null = null; private _elseTemplateRef: TemplateRef<NgIfContext<T>> | null = null; private _thenViewRef: EmbeddedViewRef<NgIfContext<T>> | null = null; private _elseViewRef: EmbeddedViewRef<NgIfContext<T>> | null = null; constructor( private _viewContainer: ViewContainerRef, templateRef: TemplateRef<NgIfContext<T>>, ) { this._thenTemplateRef = templateRef; } /** * The Boolean expression to evaluate as the condition for showing a template. */ @Input() set ngIf(condition: T) { this._context.$implicit = this._context.ngIf = condition; this._updateView(); } /** * A template to show if the condition expression evaluates to true. */ @Input() set ngIfThen(templateRef: TemplateRef<NgIfContext<T>> | null) { assertTemplate('ngIfThen', templateRef); this._thenTemplateRef = templateRef; this._thenViewRef = null; // clear previous view if any. this._updateView(); } /** * A template to show if the condition expression evaluates to false. */ @Input() set ngIfElse(templateRef: TemplateRef<NgIfContext<T>> | null) { assertTemplate('ngIfElse', templateRef); this._elseTemplateRef = templateRef; this._elseViewRef = null; // clear previous view if any. this._updateView(); } private _updateView() { if (this._context.$implicit) { if (!this._thenViewRef) { this._viewContainer.clear(); this._elseViewRef = null; if (this._thenTemplateRef) { this._thenViewRef = this._viewContainer.createEmbeddedView( this._thenTemplateRef, this._context, ); } } } else { if (!this._elseViewRef) { this._viewContainer.clear(); this._thenViewRef = null; if (this._elseTemplateRef) { this._elseViewRef = this._viewContainer.createEmbeddedView( this._elseTemplateRef, this._context, ); } } } } /** @internal */ public static ngIfUseIfTypeGuard: void; /** * Assert the correct type of the expression bound to the `ngIf` input within the template. * * The presence of this static field is a signal to the Ivy template type check compiler that * when the `NgIf` structural directive renders its template, the type of the expression bound * to `ngIf` should be narrowed in some way. For `NgIf`, the binding expression itself is used to * narrow its type, which allows the strictNullChecks feature of TypeScript to work with `NgIf`. */ static ngTemplateGuard_ngIf: 'binding'; /** * Asserts the correct type of the context for the template that `NgIf` will render. * * The presence of this method is a signal to the Ivy template type-check compiler that the * `NgIf` structural directive renders its template with a specific context type. */ static ngTemplateContextGuard<T>( dir: NgIf<T>, ctx: any, ): ctx is NgIfContext<Exclude<T, false | 0 | '' | null | undefined>> { return true; } } /** * @publicApi */ export class NgIfContext<T = unknown> { public $implicit: T = null!; public ngIf: T = null!; } function assertTemplate(property: string, templateRef: TemplateRef<any> | null): void { const isTemplateRefOrNull = !!(!templateRef || templateRef.createEmbeddedView); if (!isTemplateRefOrNull) { throw new Error(`${property} must be a TemplateRef, but received '${stringify(templateRef)}'.`); } }
{ "end_byte": 9217, "start_byte": 5554, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_if.ts" }
angular/packages/common/src/directives/ng_for_of.ts_0_6222
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Directive, DoCheck, EmbeddedViewRef, Input, IterableChangeRecord, IterableChanges, IterableDiffer, IterableDiffers, NgIterable, TemplateRef, TrackByFunction, ViewContainerRef, ɵRuntimeError as RuntimeError, } from '@angular/core'; import {RuntimeErrorCode} from '../errors'; /** * @publicApi */ export class NgForOfContext<T, U extends NgIterable<T> = NgIterable<T>> { constructor( /** Reference to the current item from the collection. */ public $implicit: T, /** * The value of the iterable expression. Useful when the expression is * more complex then a property access, for example when using the async pipe * (`userStreams | async`). */ public ngForOf: U, /** Returns an index of the current item in the collection. */ public index: number, /** Returns total amount of items in the collection. */ public count: number, ) {} // Indicates whether this is the first item in the collection. get first(): boolean { return this.index === 0; } // Indicates whether this is the last item in the collection. get last(): boolean { return this.index === this.count - 1; } // Indicates whether an index of this item in the collection is even. get even(): boolean { return this.index % 2 === 0; } // Indicates whether an index of this item in the collection is odd. get odd(): boolean { return !this.even; } } /** * A [structural directive](guide/directives/structural-directives) that renders * a template for each item in a collection. * The directive is placed on an element, which becomes the parent * of the cloned templates. * * The `ngForOf` directive is generally used in the * [shorthand form](guide/directives/structural-directives#asterisk) `*ngFor`. * In this form, the template to be rendered for each iteration is the content * of an anchor element containing the directive. * * The following example shows the shorthand syntax with some options, * contained in an `<li>` element. * * ``` * <li *ngFor="let item of items; index as i; trackBy: trackByFn">...</li> * ``` * * The shorthand form expands into a long form that uses the `ngForOf` selector * on an `<ng-template>` element. * The content of the `<ng-template>` element is the `<li>` element that held the * short-form directive. * * Here is the expanded version of the short-form example. * * ``` * <ng-template ngFor let-item [ngForOf]="items" let-i="index" [ngForTrackBy]="trackByFn"> * <li>...</li> * </ng-template> * ``` * * Angular automatically expands the shorthand syntax as it compiles the template. * The context for each embedded view is logically merged to the current component * context according to its lexical position. * * When using the shorthand syntax, Angular allows only [one structural directive * on an element](guide/directives/structural-directives#one-per-element). * If you want to iterate conditionally, for example, * put the `*ngIf` on a container element that wraps the `*ngFor` element. * For further discussion, see * [Structural Directives](guide/directives/structural-directives#one-per-element). * * @usageNotes * * ### Local variables * * `NgForOf` provides exported values that can be aliased to local variables. * For example: * * ``` * <li *ngFor="let user of users; index as i; first as isFirst"> * {{i}}/{{users.length}}. {{user}} <span *ngIf="isFirst">default</span> * </li> * ``` * * The following exported values can be aliased to local variables: * * - `$implicit: T`: The value of the individual items in the iterable (`ngForOf`). * - `ngForOf: NgIterable<T>`: The value of the iterable expression. Useful when the expression is * more complex then a property access, for example when using the async pipe (`userStreams | * async`). * - `index: number`: The index of the current item in the iterable. * - `count: number`: The length of the iterable. * - `first: boolean`: True when the item is the first item in the iterable. * - `last: boolean`: True when the item is the last item in the iterable. * - `even: boolean`: True when the item has an even index in the iterable. * - `odd: boolean`: True when the item has an odd index in the iterable. * * ### Change propagation * * When the contents of the iterator changes, `NgForOf` makes the corresponding changes to the DOM: * * * When an item is added, a new instance of the template is added to the DOM. * * When an item is removed, its template instance is removed from the DOM. * * When items are reordered, their respective templates are reordered in the DOM. * * Angular uses object identity to track insertions and deletions within the iterator and reproduce * those changes in the DOM. This has important implications for animations and any stateful * controls that are present, such as `<input>` elements that accept user input. Inserted rows can * be animated in, deleted rows can be animated out, and unchanged rows retain any unsaved state * such as user input. * For more on animations, see [Transitions and Triggers](guide/animations/transition-and-triggers). * * The identities of elements in the iterator can change while the data does not. * This can happen, for example, if the iterator is produced from an RPC to the server, and that * RPC is re-run. Even if the data hasn't changed, the second response produces objects with * different identities, and Angular must tear down the entire DOM and rebuild it (as if all old * elements were deleted and all new elements inserted). * * To avoid this expensive operation, you can customize the default tracking algorithm. * by supplying the `trackBy` option to `NgForOf`. * `trackBy` takes a function that has two arguments: `index` and `item`. * If `trackBy` is given, Angular tracks changes by the return value of the function. * * @see [Structural Directives](guide/directives/structural-directives) * @ngModule CommonModule * @publicApi */
{ "end_byte": 6222, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_for_of.ts" }
angular/packages/common/src/directives/ng_for_of.ts_6223_13179
Directive({ selector: '[ngFor][ngForOf]', standalone: true, }) export class NgForOf<T, U extends NgIterable<T> = NgIterable<T>> implements DoCheck { /** * The value of the iterable expression, which can be used as a * [template input variable](guide/directives/structural-directives#shorthand). */ @Input() set ngForOf(ngForOf: (U & NgIterable<T>) | undefined | null) { this._ngForOf = ngForOf; this._ngForOfDirty = true; } /** * Specifies a custom `TrackByFunction` to compute the identity of items in an iterable. * * If a custom `TrackByFunction` is not provided, `NgForOf` will use the item's [object * identity](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) * as the key. * * `NgForOf` uses the computed key to associate items in an iterable with DOM elements * it produces for these items. * * A custom `TrackByFunction` is useful to provide good user experience in cases when items in an * iterable rendered using `NgForOf` have a natural identifier (for example, custom ID or a * primary key), and this iterable could be updated with new object instances that still * represent the same underlying entity (for example, when data is re-fetched from the server, * and the iterable is recreated and re-rendered, but most of the data is still the same). * * @see {@link TrackByFunction} */ @Input() set ngForTrackBy(fn: TrackByFunction<T>) { if ((typeof ngDevMode === 'undefined' || ngDevMode) && fn != null && typeof fn !== 'function') { console.warn( `trackBy must be a function, but received ${JSON.stringify(fn)}. ` + `See https://angular.io/api/common/NgForOf#change-propagation for more information.`, ); } this._trackByFn = fn; } get ngForTrackBy(): TrackByFunction<T> { return this._trackByFn; } private _ngForOf: U | undefined | null = null; private _ngForOfDirty: boolean = true; private _differ: IterableDiffer<T> | null = null; // TODO(issue/24571): remove '!' // waiting for microsoft/typescript#43662 to allow the return type `TrackByFunction|undefined` for // the getter private _trackByFn!: TrackByFunction<T>; constructor( private _viewContainer: ViewContainerRef, private _template: TemplateRef<NgForOfContext<T, U>>, private _differs: IterableDiffers, ) {} /** * A reference to the template that is stamped out for each item in the iterable. * @see [template reference variable](guide/templates/variables#template-reference-variables) */ @Input() set ngForTemplate(value: TemplateRef<NgForOfContext<T, U>>) { // TODO(TS2.1): make TemplateRef<Partial<NgForRowOf<T>>> once we move to TS v2.1 // The current type is too restrictive; a template that just uses index, for example, // should be acceptable. if (value) { this._template = value; } } /** * Applies the changes when needed. * @nodoc */ ngDoCheck(): void { if (this._ngForOfDirty) { this._ngForOfDirty = false; // React on ngForOf changes only once all inputs have been initialized const value = this._ngForOf; if (!this._differ && value) { if (typeof ngDevMode === 'undefined' || ngDevMode) { try { // CAUTION: this logic is duplicated for production mode below, as the try-catch // is only present in development builds. this._differ = this._differs.find(value).create(this.ngForTrackBy); } catch { let errorMessage = `Cannot find a differ supporting object '${value}' of type '` + `${getTypeName(value)}'. NgFor only supports binding to Iterables, such as Arrays.`; if (typeof value === 'object') { errorMessage += ' Did you mean to use the keyvalue pipe?'; } throw new RuntimeError(RuntimeErrorCode.NG_FOR_MISSING_DIFFER, errorMessage); } } else { // CAUTION: this logic is duplicated for development mode above, as the try-catch // is only present in development builds. this._differ = this._differs.find(value).create(this.ngForTrackBy); } } } if (this._differ) { const changes = this._differ.diff(this._ngForOf); if (changes) this._applyChanges(changes); } } private _applyChanges(changes: IterableChanges<T>) { const viewContainer = this._viewContainer; changes.forEachOperation( ( item: IterableChangeRecord<T>, adjustedPreviousIndex: number | null, currentIndex: number | null, ) => { if (item.previousIndex == null) { // NgForOf is never "null" or "undefined" here because the differ detected // that a new item needs to be inserted from the iterable. This implies that // there is an iterable value for "_ngForOf". viewContainer.createEmbeddedView( this._template, new NgForOfContext<T, U>(item.item, this._ngForOf!, -1, -1), currentIndex === null ? undefined : currentIndex, ); } else if (currentIndex == null) { viewContainer.remove(adjustedPreviousIndex === null ? undefined : adjustedPreviousIndex); } else if (adjustedPreviousIndex !== null) { const view = viewContainer.get(adjustedPreviousIndex)!; viewContainer.move(view, currentIndex); applyViewChange(view as EmbeddedViewRef<NgForOfContext<T, U>>, item); } }, ); for (let i = 0, ilen = viewContainer.length; i < ilen; i++) { const viewRef = <EmbeddedViewRef<NgForOfContext<T, U>>>viewContainer.get(i); const context = viewRef.context; context.index = i; context.count = ilen; context.ngForOf = this._ngForOf!; } changes.forEachIdentityChange((record: any) => { const viewRef = <EmbeddedViewRef<NgForOfContext<T, U>>>viewContainer.get(record.currentIndex); applyViewChange(viewRef, record); }); } /** * Asserts the correct type of the context for the template that `NgForOf` will render. * * The presence of this method is a signal to the Ivy template type-check compiler that the * `NgForOf` structural directive renders its template with a specific context type. */ static ngTemplateContextGuard<T, U extends NgIterable<T>>( dir: NgForOf<T, U>, ctx: any, ): ctx is NgForOfContext<T, U> { return true; } } // Also export the `NgForOf` class as `NgFor` to improve the DX for // cases when the directive is used as standalone, so the class name // matches the CSS selector (*ngFor). export {NgForOf as NgFor}; function applyViewChange<T>( view: EmbeddedViewRef<NgForOfContext<T>>, record: IterableChangeRecord<T>, ) { view.context.$implicit = record.item; } function getTypeName(type: any): string { return type['name'] || typeof type; }
{ "end_byte": 13179, "start_byte": 6223, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_for_of.ts" }
angular/packages/common/src/directives/ng_class.ts_0_6664
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Directive, DoCheck, ElementRef, Input, IterableDiffers, KeyValueDiffers, Renderer2, ɵstringify as stringify, } from '@angular/core'; type NgClassSupportedTypes = string[] | Set<string> | {[klass: string]: any} | null | undefined; const WS_REGEXP = /\s+/; const EMPTY_ARRAY: string[] = []; /** * Represents internal object used to track state of each CSS class. There are 3 different (boolean) * flags that, combined together, indicate state of a given CSS class: * - enabled: indicates if a class should be present in the DOM (true) or not (false); * - changed: tracks if a class was toggled (added or removed) during the custom dirty-checking * process; changed classes must be synchronized with the DOM; * - touched: tracks if a class is present in the current object bound to the class / ngClass input; * classes that are not present any more can be removed from the internal data structures; */ interface CssClassState { // PERF: could use a bit mask to represent state as all fields are boolean flags enabled: boolean; changed: boolean; touched: boolean; } /** * @ngModule CommonModule * * @usageNotes * ``` * <some-element [ngClass]="'first second'">...</some-element> * * <some-element [ngClass]="['first', 'second']">...</some-element> * * <some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element> * * <some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element> * * <some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element> * ``` * * @description * * Adds and removes CSS classes on an HTML element. * * The CSS classes are updated as follows, depending on the type of the expression evaluation: * - `string` - the CSS classes listed in the string (space delimited) are added, * - `Array` - the CSS classes declared as Array elements are added, * - `Object` - keys are CSS classes that get added when the expression given in the value * evaluates to a truthy value, otherwise they are removed. * * @publicApi */ @Directive({ selector: '[ngClass]', standalone: true, }) export class NgClass implements DoCheck { private initialClasses = EMPTY_ARRAY; private rawClass: NgClassSupportedTypes; private stateMap = new Map<string, CssClassState>(); constructor( private _ngEl: ElementRef, private _renderer: Renderer2, ) {} @Input('class') set klass(value: string) { this.initialClasses = value != null ? value.trim().split(WS_REGEXP) : EMPTY_ARRAY; } @Input('ngClass') set ngClass(value: string | string[] | Set<string> | {[klass: string]: any} | null | undefined) { this.rawClass = typeof value === 'string' ? value.trim().split(WS_REGEXP) : value; } /* The NgClass directive uses the custom change detection algorithm for its inputs. The custom algorithm is necessary since inputs are represented as complex object or arrays that need to be deeply-compared. This algorithm is perf-sensitive since NgClass is used very frequently and its poor performance might negatively impact runtime performance of the entire change detection cycle. The design of this algorithm is making sure that: - there is no unnecessary DOM manipulation (CSS classes are added / removed from the DOM only when needed), even if references to bound objects change; - there is no memory allocation if nothing changes (even relatively modest memory allocation during the change detection cycle can result in GC pauses for some of the CD cycles). The algorithm works by iterating over the set of bound classes, staring with [class] binding and then going over [ngClass] binding. For each CSS class name: - check if it was seen before (this information is tracked in the state map) and if its value changed; - mark it as "touched" - names that are not marked are not present in the latest set of binding and we can remove such class name from the internal data structures; After iteration over all the CSS class names we've got data structure with all the information necessary to synchronize changes to the DOM - it is enough to iterate over the state map, flush changes to the DOM and reset internal data structures so those are ready for the next change detection cycle. */ ngDoCheck(): void { // classes from the [class] binding for (const klass of this.initialClasses) { this._updateState(klass, true); } // classes from the [ngClass] binding const rawClass = this.rawClass; if (Array.isArray(rawClass) || rawClass instanceof Set) { for (const klass of rawClass) { this._updateState(klass, true); } } else if (rawClass != null) { for (const klass of Object.keys(rawClass)) { this._updateState(klass, Boolean(rawClass[klass])); } } this._applyStateDiff(); } private _updateState(klass: string, nextEnabled: boolean) { const state = this.stateMap.get(klass); if (state !== undefined) { if (state.enabled !== nextEnabled) { state.changed = true; state.enabled = nextEnabled; } state.touched = true; } else { this.stateMap.set(klass, {enabled: nextEnabled, changed: true, touched: true}); } } private _applyStateDiff() { for (const stateEntry of this.stateMap) { const klass = stateEntry[0]; const state = stateEntry[1]; if (state.changed) { this._toggleClass(klass, state.enabled); state.changed = false; } else if (!state.touched) { // A class that was previously active got removed from the new collection of classes - // remove from the DOM as well. if (state.enabled) { this._toggleClass(klass, false); } this.stateMap.delete(klass); } state.touched = false; } } private _toggleClass(klass: string, enabled: boolean): void { if (ngDevMode) { if (typeof klass !== 'string') { throw new Error( `NgClass can only toggle CSS classes expressed as strings, got ${stringify(klass)}`, ); } } klass = klass.trim(); if (klass.length > 0) { klass.split(WS_REGEXP).forEach((klass) => { if (enabled) { this._renderer.addClass(this._ngEl.nativeElement, klass); } else { this._renderer.removeClass(this._ngEl.nativeElement, klass); } }); } } }
{ "end_byte": 6664, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_class.ts" }
angular/packages/common/src/directives/index.ts_0_1188
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Provider} from '@angular/core'; import {NgClass} from './ng_class'; import {NgComponentOutlet} from './ng_component_outlet'; import {NgFor, NgForOf, NgForOfContext} from './ng_for_of'; import {NgIf, NgIfContext} from './ng_if'; import {NgPlural, NgPluralCase} from './ng_plural'; import {NgStyle} from './ng_style'; import {NgSwitch, NgSwitchCase, NgSwitchDefault} from './ng_switch'; import {NgTemplateOutlet} from './ng_template_outlet'; export { NgClass, NgComponentOutlet, NgFor, NgForOf, NgForOfContext, NgIf, NgIfContext, NgPlural, NgPluralCase, NgStyle, NgSwitch, NgSwitchCase, NgSwitchDefault, NgTemplateOutlet, }; /** * A collection of Angular directives that are likely to be used in each and every Angular * application. */ export const COMMON_DIRECTIVES: Provider[] = [ NgClass, NgComponentOutlet, NgForOf, NgIf, NgTemplateOutlet, NgStyle, NgSwitch, NgSwitchCase, NgSwitchDefault, NgPlural, NgPluralCase, ];
{ "end_byte": 1188, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/index.ts" }
angular/packages/common/src/directives/ng_template_outlet.ts_0_3857
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Directive, EmbeddedViewRef, Injector, Input, OnChanges, SimpleChange, SimpleChanges, TemplateRef, ViewContainerRef, } from '@angular/core'; /** * @ngModule CommonModule * * @description * * Inserts an embedded view from a prepared `TemplateRef`. * * You can attach a context object to the `EmbeddedViewRef` by setting `[ngTemplateOutletContext]`. * `[ngTemplateOutletContext]` should be an object, the object's keys will be available for binding * by the local template `let` declarations. * * @usageNotes * ``` * <ng-container *ngTemplateOutlet="templateRefExp; context: contextExp"></ng-container> * ``` * * Using the key `$implicit` in the context object will set its value as default. * * ### Example * * {@example common/ngTemplateOutlet/ts/module.ts region='NgTemplateOutlet'} * * @publicApi */ @Directive({ selector: '[ngTemplateOutlet]', standalone: true, }) export class NgTemplateOutlet<C = unknown> implements OnChanges { private _viewRef: EmbeddedViewRef<C> | null = null; /** * A context object to attach to the {@link EmbeddedViewRef}. This should be an * object, the object's keys will be available for binding by the local template `let` * declarations. * Using the key `$implicit` in the context object will set its value as default. */ @Input() public ngTemplateOutletContext: C | null = null; /** * A string defining the template reference and optionally the context object for the template. */ @Input() public ngTemplateOutlet: TemplateRef<C> | null = null; /** Injector to be used within the embedded view. */ @Input() public ngTemplateOutletInjector: Injector | null = null; constructor(private _viewContainerRef: ViewContainerRef) {} ngOnChanges(changes: SimpleChanges) { if (this._shouldRecreateView(changes)) { const viewContainerRef = this._viewContainerRef; if (this._viewRef) { viewContainerRef.remove(viewContainerRef.indexOf(this._viewRef)); } // If there is no outlet, clear the destroyed view ref. if (!this.ngTemplateOutlet) { this._viewRef = null; return; } // Create a context forward `Proxy` that will always bind to the user-specified context, // without having to destroy and re-create views whenever the context changes. const viewContext = this._createContextForwardProxy(); this._viewRef = viewContainerRef.createEmbeddedView(this.ngTemplateOutlet, viewContext, { injector: this.ngTemplateOutletInjector ?? undefined, }); } } /** * We need to re-create existing embedded view if either is true: * - the outlet changed. * - the injector changed. */ private _shouldRecreateView(changes: SimpleChanges): boolean { return !!changes['ngTemplateOutlet'] || !!changes['ngTemplateOutletInjector']; } /** * For a given outlet instance, we create a proxy object that delegates * to the user-specified context. This allows changing, or swapping out * the context object completely without having to destroy/re-create the view. */ private _createContextForwardProxy(): C { return <C>new Proxy( {}, { set: (_target, prop, newValue) => { if (!this.ngTemplateOutletContext) { return false; } return Reflect.set(this.ngTemplateOutletContext, prop, newValue); }, get: (_target, prop, receiver) => { if (!this.ngTemplateOutletContext) { return undefined; } return Reflect.get(this.ngTemplateOutletContext, prop, receiver); }, }, ); } }
{ "end_byte": 3857, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_template_outlet.ts" }
angular/packages/common/src/directives/ng_optimized_image/preconnect_link_checker.ts_0_5293
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { inject, Injectable, InjectionToken, ɵformatRuntimeError as formatRuntimeError, PLATFORM_ID, } from '@angular/core'; import {DOCUMENT} from '../../dom_tokens'; import {RuntimeErrorCode} from '../../errors'; import {assertDevMode} from './asserts'; import {imgDirectiveDetails} from './error_helper'; import {extractHostname, getUrl} from './url'; import {isPlatformServer} from '../../platform_id'; // Set of origins that are always excluded from the preconnect checks. const INTERNAL_PRECONNECT_CHECK_BLOCKLIST = new Set(['localhost', '127.0.0.1', '0.0.0.0']); /** * Injection token to configure which origins should be excluded * from the preconnect checks. It can either be a single string or an array of strings * to represent a group of origins, for example: * * ```typescript * {provide: PRECONNECT_CHECK_BLOCKLIST, useValue: 'https://your-domain.com'} * ``` * * or: * * ```typescript * {provide: PRECONNECT_CHECK_BLOCKLIST, * useValue: ['https://your-domain-1.com', 'https://your-domain-2.com']} * ``` * * @publicApi */ export const PRECONNECT_CHECK_BLOCKLIST = new InjectionToken<Array<string | string[]>>( ngDevMode ? 'PRECONNECT_CHECK_BLOCKLIST' : '', ); /** * Contains the logic to detect whether an image, marked with the "priority" attribute * has a corresponding `<link rel="preconnect">` tag in the `document.head`. * * Note: this is a dev-mode only class, which should not appear in prod bundles, * thus there is no `ngDevMode` use in the code. */ @Injectable({providedIn: 'root'}) export class PreconnectLinkChecker { private document = inject(DOCUMENT); private readonly isServer = isPlatformServer(inject(PLATFORM_ID)); /** * Set of <link rel="preconnect"> tags found on this page. * The `null` value indicates that there was no DOM query operation performed. */ private preconnectLinks: Set<string> | null = null; /* * Keep track of all already seen origin URLs to avoid repeating the same check. */ private alreadySeen = new Set<string>(); private window: Window | null = null; private blocklist = new Set<string>(INTERNAL_PRECONNECT_CHECK_BLOCKLIST); constructor() { assertDevMode('preconnect link checker'); const win = this.document.defaultView; if (typeof win !== 'undefined') { this.window = win; } const blocklist = inject(PRECONNECT_CHECK_BLOCKLIST, {optional: true}); if (blocklist) { this.populateBlocklist(blocklist); } } private populateBlocklist(origins: Array<string | string[]> | string) { if (Array.isArray(origins)) { deepForEach(origins, (origin) => { this.blocklist.add(extractHostname(origin)); }); } else { this.blocklist.add(extractHostname(origins)); } } /** * Checks that a preconnect resource hint exists in the head for the * given src. * * @param rewrittenSrc src formatted with loader * @param originalNgSrc ngSrc value */ assertPreconnect(rewrittenSrc: string, originalNgSrc: string): void { if (this.isServer) return; const imgUrl = getUrl(rewrittenSrc, this.window!); if (this.blocklist.has(imgUrl.hostname) || this.alreadySeen.has(imgUrl.origin)) return; // Register this origin as seen, so we don't check it again later. this.alreadySeen.add(imgUrl.origin); // Note: we query for preconnect links only *once* and cache the results // for the entire lifespan of an application, since it's unlikely that the // list would change frequently. This allows to make sure there are no // performance implications of making extra DOM lookups for each image. this.preconnectLinks ??= this.queryPreconnectLinks(); if (!this.preconnectLinks.has(imgUrl.origin)) { console.warn( formatRuntimeError( RuntimeErrorCode.PRIORITY_IMG_MISSING_PRECONNECT_TAG, `${imgDirectiveDetails(originalNgSrc)} there is no preconnect tag present for this ` + `image. Preconnecting to the origin(s) that serve priority images ensures that these ` + `images are delivered as soon as possible. To fix this, please add the following ` + `element into the <head> of the document:\n` + ` <link rel="preconnect" href="${imgUrl.origin}">`, ), ); } } private queryPreconnectLinks(): Set<string> { const preconnectUrls = new Set<string>(); const selector = 'link[rel=preconnect]'; const links: HTMLLinkElement[] = Array.from(this.document.querySelectorAll(selector)); for (let link of links) { const url = getUrl(link.href, this.window!); preconnectUrls.add(url.origin); } return preconnectUrls; } ngOnDestroy() { this.preconnectLinks?.clear(); this.alreadySeen.clear(); } } /** * Invokes a callback for each element in the array. Also invokes a callback * recursively for each nested array. */ function deepForEach<T>(input: (T | any[])[], fn: (value: T) => void): void { for (let value of input) { Array.isArray(value) ? deepForEach(value, fn) : fn(value); } }
{ "end_byte": 5293, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_optimized_image/preconnect_link_checker.ts" }
angular/packages/common/src/directives/ng_optimized_image/asserts.ts_0_877
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {ɵRuntimeError as RuntimeError} from '@angular/core'; import {RuntimeErrorCode} from '../../errors'; /** * Asserts that the application is in development mode. Throws an error if the application is in * production mode. This assert can be used to make sure that there is no dev-mode code invoked in * the prod mode accidentally. */ export function assertDevMode(checkName: string) { if (!ngDevMode) { throw new RuntimeError( RuntimeErrorCode.UNEXPECTED_DEV_MODE_CHECK_IN_PROD_MODE, `Unexpected invocation of the ${checkName} in the prod mode. ` + `Please make sure that the prod mode is enabled for production builds.`, ); } }
{ "end_byte": 877, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_optimized_image/asserts.ts" }
angular/packages/common/src/directives/ng_optimized_image/error_helper.ts_0_533
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // Assembles directive details string, useful for error messages. export function imgDirectiveDetails(ngSrc: string, includeNgSrc = true) { const ngSrcInfo = includeNgSrc ? `(activated on an <img> element with the \`ngSrc="${ngSrc}"\`) ` : ''; return `The NgOptimizedImage directive ${ngSrcInfo}has detected that`; }
{ "end_byte": 533, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_optimized_image/error_helper.ts" }
angular/packages/common/src/directives/ng_optimized_image/url.ts_0_1393
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // Converts a string that represents a URL into a URL class instance. export function getUrl(src: string, win: Window): URL { // Don't use a base URL is the URL is absolute. return isAbsoluteUrl(src) ? new URL(src) : new URL(src, win.location.href); } // Checks whether a URL is absolute (i.e. starts with `http://` or `https://`). export function isAbsoluteUrl(src: string): boolean { return /^https?:\/\//.test(src); } // Given a URL, extract the hostname part. // If a URL is a relative one - the URL is returned as is. export function extractHostname(url: string): string { return isAbsoluteUrl(url) ? new URL(url).hostname : url; } export function isValidPath(path: unknown): boolean { const isString = typeof path === 'string'; if (!isString || path.trim() === '') { return false; } // Calling new URL() will throw if the path string is malformed try { const url = new URL(path); return true; } catch { return false; } } export function normalizePath(path: string): string { return path.endsWith('/') ? path.slice(0, -1) : path; } export function normalizeSrc(src: string): string { return src.startsWith('/') ? src.slice(1) : src; }
{ "end_byte": 1393, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_optimized_image/url.ts" }
angular/packages/common/src/directives/ng_optimized_image/tokens.ts_0_1090
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {InjectionToken} from '@angular/core'; /** * In SSR scenarios, a preload `<link>` element is generated for priority images. * Having a large number of preload tags may negatively affect the performance, * so we warn developers (by throwing an error) if the number of preloaded images * is above a certain threshold. This const specifies this threshold. */ export const DEFAULT_PRELOADED_IMAGES_LIMIT = 5; /** * Helps to keep track of priority images that already have a corresponding * preload tag (to avoid generating multiple preload tags with the same URL). * * This Set tracks the original src passed into the `ngSrc` input not the src after it has been * run through the specified `IMAGE_LOADER`. */ export const PRELOADED_IMAGES = new InjectionToken<Set<string>>('NG_OPTIMIZED_PRELOADED_IMAGES', { providedIn: 'root', factory: () => new Set<string>(), });
{ "end_byte": 1090, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_optimized_image/tokens.ts" }
angular/packages/common/src/directives/ng_optimized_image/preload-link-creator.ts_0_3237
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {inject, Injectable, Renderer2, ɵRuntimeError as RuntimeError} from '@angular/core'; import {DOCUMENT} from '../../dom_tokens'; import {RuntimeErrorCode} from '../../errors'; import {DEFAULT_PRELOADED_IMAGES_LIMIT, PRELOADED_IMAGES} from './tokens'; /** * @description Contains the logic needed to track and add preload link tags to the `<head>` tag. It * will also track what images have already had preload link tags added so as to not duplicate link * tags. * * In dev mode this service will validate that the number of preloaded images does not exceed the * configured default preloaded images limit: {@link DEFAULT_PRELOADED_IMAGES_LIMIT}. */ @Injectable({providedIn: 'root'}) export class PreloadLinkCreator { private readonly preloadedImages = inject(PRELOADED_IMAGES); private readonly document = inject(DOCUMENT); /** * @description Add a preload `<link>` to the `<head>` of the `index.html` that is served from the * server while using Angular Universal and SSR to kick off image loads for high priority images. * * The `sizes` (passed in from the user) and `srcset` (parsed and formatted from `ngSrcset`) * properties used to set the corresponding attributes, `imagesizes` and `imagesrcset` * respectively, on the preload `<link>` tag so that the correctly sized image is preloaded from * the CDN. * * {@link https://web.dev/preload-responsive-images/#imagesrcset-and-imagesizes} * * @param renderer The `Renderer2` passed in from the directive * @param src The original src of the image that is set on the `ngSrc` input. * @param srcset The parsed and formatted srcset created from the `ngSrcset` input * @param sizes The value of the `sizes` attribute passed in to the `<img>` tag */ createPreloadLinkTag(renderer: Renderer2, src: string, srcset?: string, sizes?: string): void { if (ngDevMode) { if (this.preloadedImages.size >= DEFAULT_PRELOADED_IMAGES_LIMIT) { throw new RuntimeError( RuntimeErrorCode.TOO_MANY_PRELOADED_IMAGES, ngDevMode && `The \`NgOptimizedImage\` directive has detected that more than ` + `${DEFAULT_PRELOADED_IMAGES_LIMIT} images were marked as priority. ` + `This might negatively affect an overall performance of the page. ` + `To fix this, remove the "priority" attribute from images with less priority.`, ); } } if (this.preloadedImages.has(src)) { return; } this.preloadedImages.add(src); const preload = renderer.createElement('link'); renderer.setAttribute(preload, 'as', 'image'); renderer.setAttribute(preload, 'href', src); renderer.setAttribute(preload, 'rel', 'preload'); renderer.setAttribute(preload, 'fetchpriority', 'high'); if (sizes) { renderer.setAttribute(preload, 'imageSizes', sizes); } if (srcset) { renderer.setAttribute(preload, 'imageSrcset', srcset); } renderer.appendChild(this.document.head, preload); } }
{ "end_byte": 3237, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_optimized_image/preload-link-creator.ts" }
angular/packages/common/src/directives/ng_optimized_image/index.ts_0_962
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export {ɵIMAGE_CONFIG as IMAGE_CONFIG, ɵImageConfig as ImageConfig} from '@angular/core'; // These exports represent the set of symbols exposed as a public API. export {provideCloudflareLoader} from './image_loaders/cloudflare_loader'; export {provideCloudinaryLoader} from './image_loaders/cloudinary_loader'; export {IMAGE_LOADER, ImageLoader, ImageLoaderConfig} from './image_loaders/image_loader'; export {provideImageKitLoader} from './image_loaders/imagekit_loader'; export {provideImgixLoader} from './image_loaders/imgix_loader'; export {provideNetlifyLoader} from './image_loaders/netlify_loader'; export {ImagePlaceholderConfig, NgOptimizedImage} from './ng_optimized_image'; export {PRECONNECT_CHECK_BLOCKLIST} from './preconnect_link_checker';
{ "end_byte": 962, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_optimized_image/index.ts" }
angular/packages/common/src/directives/ng_optimized_image/lcp_image_observer.ts_0_5386
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { inject, Injectable, OnDestroy, ɵformatRuntimeError as formatRuntimeError, PLATFORM_ID, } from '@angular/core'; import {DOCUMENT} from '../../dom_tokens'; import {RuntimeErrorCode} from '../../errors'; import {assertDevMode} from './asserts'; import {imgDirectiveDetails} from './error_helper'; import {getUrl} from './url'; import {isPlatformBrowser} from '../../platform_id'; interface ObservedImageState { priority: boolean; modified: boolean; alreadyWarnedPriority: boolean; alreadyWarnedModified: boolean; } /** * Observer that detects whether an image with `NgOptimizedImage` * is treated as a Largest Contentful Paint (LCP) element. If so, * asserts that the image has the `priority` attribute. * * Note: this is a dev-mode only class and it does not appear in prod bundles, * thus there is no `ngDevMode` use in the code. * * Based on https://web.dev/lcp/#measure-lcp-in-javascript. */ @Injectable({providedIn: 'root'}) export class LCPImageObserver implements OnDestroy { // Map of full image URLs -> original `ngSrc` values. private images = new Map<string, ObservedImageState>(); private window: Window | null = null; private observer: PerformanceObserver | null = null; constructor() { const isBrowser = isPlatformBrowser(inject(PLATFORM_ID)); assertDevMode('LCP checker'); const win = inject(DOCUMENT).defaultView; if (isBrowser && typeof PerformanceObserver !== 'undefined') { this.window = win; this.observer = this.initPerformanceObserver(); } } /** * Inits PerformanceObserver and subscribes to LCP events. * Based on https://web.dev/lcp/#measure-lcp-in-javascript */ private initPerformanceObserver(): PerformanceObserver { const observer = new PerformanceObserver((entryList) => { const entries = entryList.getEntries(); if (entries.length === 0) return; // We use the latest entry produced by the `PerformanceObserver` as the best // signal on which element is actually an LCP one. As an example, the first image to load on // a page, by virtue of being the only thing on the page so far, is often a LCP candidate // and gets reported by PerformanceObserver, but isn't necessarily the LCP element. const lcpElement = entries[entries.length - 1]; // Cast to `any` due to missing `element` on the `LargestContentfulPaint` type of entry. // See https://developer.mozilla.org/en-US/docs/Web/API/LargestContentfulPaint const imgSrc = (lcpElement as any).element?.src ?? ''; // Exclude `data:` and `blob:` URLs, since they are not supported by the directive. if (imgSrc.startsWith('data:') || imgSrc.startsWith('blob:')) return; const img = this.images.get(imgSrc); if (!img) return; if (!img.priority && !img.alreadyWarnedPriority) { img.alreadyWarnedPriority = true; logMissingPriorityError(imgSrc); } if (img.modified && !img.alreadyWarnedModified) { img.alreadyWarnedModified = true; logModifiedWarning(imgSrc); } }); observer.observe({type: 'largest-contentful-paint', buffered: true}); return observer; } registerImage(rewrittenSrc: string, originalNgSrc: string, isPriority: boolean) { if (!this.observer) return; const newObservedImageState: ObservedImageState = { priority: isPriority, modified: false, alreadyWarnedModified: false, alreadyWarnedPriority: false, }; this.images.set(getUrl(rewrittenSrc, this.window!).href, newObservedImageState); } unregisterImage(rewrittenSrc: string) { if (!this.observer) return; this.images.delete(getUrl(rewrittenSrc, this.window!).href); } updateImage(originalSrc: string, newSrc: string) { if (!this.observer) return; const originalUrl = getUrl(originalSrc, this.window!).href; const img = this.images.get(originalUrl); if (img) { img.modified = true; this.images.set(getUrl(newSrc, this.window!).href, img); this.images.delete(originalUrl); } } ngOnDestroy() { if (!this.observer) return; this.observer.disconnect(); this.images.clear(); } } function logMissingPriorityError(ngSrc: string) { const directiveDetails = imgDirectiveDetails(ngSrc); console.error( formatRuntimeError( RuntimeErrorCode.LCP_IMG_MISSING_PRIORITY, `${directiveDetails} this image is the Largest Contentful Paint (LCP) ` + `element but was not marked "priority". This image should be marked ` + `"priority" in order to prioritize its loading. ` + `To fix this, add the "priority" attribute.`, ), ); } function logModifiedWarning(ngSrc: string) { const directiveDetails = imgDirectiveDetails(ngSrc); console.warn( formatRuntimeError( RuntimeErrorCode.LCP_IMG_NGSRC_MODIFIED, `${directiveDetails} this image is the Largest Contentful Paint (LCP) ` + `element and has had its "ngSrc" attribute modified. This can cause ` + `slower loading performance. It is recommended not to modify the "ngSrc" ` + `property on any image which could be the LCP element.`, ), ); }
{ "end_byte": 5386, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_optimized_image/lcp_image_observer.ts" }
angular/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts_0_5363
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { booleanAttribute, Directive, ElementRef, inject, Injector, Input, NgZone, numberAttribute, OnChanges, OnDestroy, OnInit, PLATFORM_ID, Renderer2, SimpleChanges, ɵformatRuntimeError as formatRuntimeError, ɵIMAGE_CONFIG as IMAGE_CONFIG, ɵIMAGE_CONFIG_DEFAULTS as IMAGE_CONFIG_DEFAULTS, ɵImageConfig as ImageConfig, ɵperformanceMarkFeature as performanceMarkFeature, ɵRuntimeError as RuntimeError, ɵSafeValue as SafeValue, ɵunwrapSafeValue as unwrapSafeValue, ChangeDetectorRef, ApplicationRef, ɵwhenStable as whenStable, } from '@angular/core'; import {RuntimeErrorCode} from '../../errors'; import {isPlatformServer} from '../../platform_id'; import {imgDirectiveDetails} from './error_helper'; import {cloudinaryLoaderInfo} from './image_loaders/cloudinary_loader'; import { IMAGE_LOADER, ImageLoader, ImageLoaderConfig, noopImageLoader, } from './image_loaders/image_loader'; import {imageKitLoaderInfo} from './image_loaders/imagekit_loader'; import {imgixLoaderInfo} from './image_loaders/imgix_loader'; import {netlifyLoaderInfo} from './image_loaders/netlify_loader'; import {LCPImageObserver} from './lcp_image_observer'; import {PreconnectLinkChecker} from './preconnect_link_checker'; import {PreloadLinkCreator} from './preload-link-creator'; /** * When a Base64-encoded image is passed as an input to the `NgOptimizedImage` directive, * an error is thrown. The image content (as a string) might be very long, thus making * it hard to read an error message if the entire string is included. This const defines * the number of characters that should be included into the error message. The rest * of the content is truncated. */ const BASE64_IMG_MAX_LENGTH_IN_ERROR = 50; /** * RegExpr to determine whether a src in a srcset is using width descriptors. * Should match something like: "100w, 200w". */ const VALID_WIDTH_DESCRIPTOR_SRCSET = /^((\s*\d+w\s*(,|$)){1,})$/; /** * RegExpr to determine whether a src in a srcset is using density descriptors. * Should match something like: "1x, 2x, 50x". Also supports decimals like "1.5x, 1.50x". */ const VALID_DENSITY_DESCRIPTOR_SRCSET = /^((\s*\d+(\.\d+)?x\s*(,|$)){1,})$/; /** * Srcset values with a density descriptor higher than this value will actively * throw an error. Such densities are not permitted as they cause image sizes * to be unreasonably large and slow down LCP. */ export const ABSOLUTE_SRCSET_DENSITY_CAP = 3; /** * Used only in error message text to communicate best practices, as we will * only throw based on the slightly more conservative ABSOLUTE_SRCSET_DENSITY_CAP. */ export const RECOMMENDED_SRCSET_DENSITY_CAP = 2; /** * Used in generating automatic density-based srcsets */ const DENSITY_SRCSET_MULTIPLIERS = [1, 2]; /** * Used to determine which breakpoints to use on full-width images */ const VIEWPORT_BREAKPOINT_CUTOFF = 640; /** * Used to determine whether two aspect ratios are similar in value. */ const ASPECT_RATIO_TOLERANCE = 0.1; /** * Used to determine whether the image has been requested at an overly * large size compared to the actual rendered image size (after taking * into account a typical device pixel ratio). In pixels. */ const OVERSIZED_IMAGE_TOLERANCE = 1000; /** * Used to limit automatic srcset generation of very large sources for * fixed-size images. In pixels. */ const FIXED_SRCSET_WIDTH_LIMIT = 1920; const FIXED_SRCSET_HEIGHT_LIMIT = 1080; /** * Default blur radius of the CSS filter used on placeholder images, in pixels */ export const PLACEHOLDER_BLUR_AMOUNT = 15; /** * Placeholder dimension (height or width) limit in pixels. Angular produces a warning * when this limit is crossed. */ const PLACEHOLDER_DIMENSION_LIMIT = 1000; /** * Used to warn or error when the user provides an overly large dataURL for the placeholder * attribute. * Character count of Base64 images is 1 character per byte, and base64 encoding is approximately * 33% larger than base images, so 4000 characters is around 3KB on disk and 10000 characters is * around 7.7KB. Experimentally, 4000 characters is about 20x20px in PNG or medium-quality JPEG * format, and 10,000 is around 50x50px, but there's quite a bit of variation depending on how the * image is saved. */ export const DATA_URL_WARN_LIMIT = 4000; export const DATA_URL_ERROR_LIMIT = 10000; /** Info about built-in loaders we can test for. */ export const BUILT_IN_LOADERS = [ imgixLoaderInfo, imageKitLoaderInfo, cloudinaryLoaderInfo, netlifyLoaderInfo, ]; /** * Threshold for the PRIORITY_TRUE_COUNT */ const PRIORITY_COUNT_THRESHOLD = 10; /** * This count is used to log a devMode warning * when the count of directive instances with priority=true * exceeds the threshold PRIORITY_COUNT_THRESHOLD */ let IMGS_WITH_PRIORITY_ATTR_COUNT = 0; /** * This function is for testing purpose. */ export function resetImagePriorityCount() { IMGS_WITH_PRIORITY_ATTR_COUNT = 0; } /** * Config options used in rendering placeholder images. * * @see {@link NgOptimizedImage} * @publicApi */ export interface ImagePlaceholderConfig { blur?: boolean; } /** *
{ "end_byte": 5363, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts" }
angular/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts_5365_9449
rective that improves image loading performance by enforcing best practices. * * `NgOptimizedImage` ensures that the loading of the Largest Contentful Paint (LCP) image is * prioritized by: * - Automatically setting the `fetchpriority` attribute on the `<img>` tag * - Lazy loading non-priority images by default * - Automatically generating a preconnect link tag in the document head * * In addition, the directive: * - Generates appropriate asset URLs if a corresponding `ImageLoader` function is provided * - Automatically generates a srcset * - Requires that `width` and `height` are set * - Warns if `width` or `height` have been set incorrectly * - Warns if the image will be visually distorted when rendered * * @usageNotes * The `NgOptimizedImage` directive is marked as [standalone](guide/components/importing) and can * be imported directly. * * Follow the steps below to enable and use the directive: * 1. Import it into the necessary NgModule or a standalone Component. * 2. Optionally provide an `ImageLoader` if you use an image hosting service. * 3. Update the necessary `<img>` tags in templates and replace `src` attributes with `ngSrc`. * Using a `ngSrc` allows the directive to control when the `src` gets set, which triggers an image * download. * * Step 1: import the `NgOptimizedImage` directive. * * ```typescript * import { NgOptimizedImage } from '@angular/common'; * * // Include it into the necessary NgModule * @NgModule({ * imports: [NgOptimizedImage], * }) * class AppModule {} * * // ... or a standalone Component * @Component({ * standalone: true * imports: [NgOptimizedImage], * }) * class MyStandaloneComponent {} * ``` * * Step 2: configure a loader. * * To use the **default loader**: no additional code changes are necessary. The URL returned by the * generic loader will always match the value of "src". In other words, this loader applies no * transformations to the resource URL and the value of the `ngSrc` attribute will be used as is. * * To use an existing loader for a **third-party image service**: add the provider factory for your * chosen service to the `providers` array. In the example below, the Imgix loader is used: * * ```typescript * import {provideImgixLoader} from '@angular/common'; * * // Call the function and add the result to the `providers` array: * providers: [ * provideImgixLoader("https://my.base.url/"), * ], * ``` * * The `NgOptimizedImage` directive provides the following functions: * - `provideCloudflareLoader` * - `provideCloudinaryLoader` * - `provideImageKitLoader` * - `provideImgixLoader` * * If you use a different image provider, you can create a custom loader function as described * below. * * To use a **custom loader**: provide your loader function as a value for the `IMAGE_LOADER` DI * token. * * ```typescript * import {IMAGE_LOADER, ImageLoaderConfig} from '@angular/common'; * * // Configure the loader using the `IMAGE_LOADER` token. * providers: [ * { * provide: IMAGE_LOADER, * useValue: (config: ImageLoaderConfig) => { * return `https://example.com/${config.src}-${config.width}.jpg`; * } * }, * ], * ``` * * Step 3: update `<img>` tags in templates to use `ngSrc` instead of `src`. * * ``` * <img ngSrc="logo.png" width="200" height="100"> * ``` * * @publicApi */ @Directive({ standalone: true, selector: 'img[ngSrc]', host: { '[style.position]': 'fill ? "absolute" : null', '[style.width]': 'fill ? "100%" : null', '[style.height]': 'fill ? "100%" : null', '[style.inset]': 'fill ? "0" : null', '[style.background-size]': 'placeholder ? "cover" : null', '[style.background-position]': 'placeholder ? "50% 50%" : null', '[style.background-repeat]': 'placeholder ? "no-repeat" : null', '[style.background-image]': 'placeholder ? generatePlaceholder(placeholder) : null', '[style.filter]': `placeholder && shouldBlurPlaceholder(placeholderConfig) ? "blur(${PLACEHOLDER_BLUR_AMOUNT}px)" : null`, }, }) export class Ng
{ "end_byte": 9449, "start_byte": 5365, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts" }
angular/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts_9450_17733
ptimizedImage implements OnInit, OnChanges, OnDestroy { private imageLoader = inject(IMAGE_LOADER); private config: ImageConfig = processConfig(inject(IMAGE_CONFIG)); private renderer = inject(Renderer2); private imgElement: HTMLImageElement = inject(ElementRef).nativeElement; private injector = inject(Injector); private readonly isServer = isPlatformServer(inject(PLATFORM_ID)); private readonly preloadLinkCreator = inject(PreloadLinkCreator); // a LCP image observer - should be injected only in the dev mode private lcpObserver = ngDevMode ? this.injector.get(LCPImageObserver) : null; /** * Calculate the rewritten `src` once and store it. * This is needed to avoid repetitive calculations and make sure the directive cleanup in the * `ngOnDestroy` does not rely on the `IMAGE_LOADER` logic (which in turn can rely on some other * instance that might be already destroyed). */ private _renderedSrc: string | null = null; /** * Name of the source image. * Image name will be processed by the image loader and the final URL will be applied as the `src` * property of the image. */ @Input({required: true, transform: unwrapSafeUrl}) ngSrc!: string; /** * A comma separated list of width or density descriptors. * The image name will be taken from `ngSrc` and combined with the list of width or density * descriptors to generate the final `srcset` property of the image. * * Example: * ``` * <img ngSrc="hello.jpg" ngSrcset="100w, 200w" /> => * <img src="path/hello.jpg" srcset="path/hello.jpg?w=100 100w, path/hello.jpg?w=200 200w" /> * ``` */ @Input() ngSrcset!: string; /** * The base `sizes` attribute passed through to the `<img>` element. * Providing sizes causes the image to create an automatic responsive srcset. */ @Input() sizes?: string; /** * For responsive images: the intrinsic width of the image in pixels. * For fixed size images: the desired rendered width of the image in pixels. */ @Input({transform: numberAttribute}) width: number | undefined; /** * For responsive images: the intrinsic height of the image in pixels. * For fixed size images: the desired rendered height of the image in pixels. */ @Input({transform: numberAttribute}) height: number | undefined; /** * The desired loading behavior (lazy, eager, or auto). Defaults to `lazy`, * which is recommended for most images. * * Warning: Setting images as loading="eager" or loading="auto" marks them * as non-priority images and can hurt loading performance. For images which * may be the LCP element, use the `priority` attribute instead of `loading`. */ @Input() loading?: 'lazy' | 'eager' | 'auto'; /** * Indicates whether this image should have a high priority. */ @Input({transform: booleanAttribute}) priority = false; /** * Data to pass through to custom loaders. */ @Input() loaderParams?: {[key: string]: any}; /** * Disables automatic srcset generation for this image. */ @Input({transform: booleanAttribute}) disableOptimizedSrcset = false; /** * Sets the image to "fill mode", which eliminates the height/width requirement and adds * styles such that the image fills its containing element. */ @Input({transform: booleanAttribute}) fill = false; /** * A URL or data URL for an image to be used as a placeholder while this image loads. */ @Input({transform: booleanOrUrlAttribute}) placeholder?: string | boolean; /** * Configuration object for placeholder settings. Options: * * blur: Setting this to false disables the automatic CSS blur. */ @Input() placeholderConfig?: ImagePlaceholderConfig; /** * Value of the `src` attribute if set on the host `<img>` element. * This input is exclusively read to assert that `src` is not set in conflict * with `ngSrc` and that images don't start to load until a lazy loading strategy is set. * @internal */ @Input() src?: string; /** * Value of the `srcset` attribute if set on the host `<img>` element. * This input is exclusively read to assert that `srcset` is not set in conflict * with `ngSrcset` and that images don't start to load until a lazy loading strategy is set. * @internal */ @Input() srcset?: string; /** @nodoc */ ngOnInit() { performanceMarkFeature('NgOptimizedImage'); if (ngDevMode) { const ngZone = this.injector.get(NgZone); assertNonEmptyInput(this, 'ngSrc', this.ngSrc); assertValidNgSrcset(this, this.ngSrcset); assertNoConflictingSrc(this); if (this.ngSrcset) { assertNoConflictingSrcset(this); } assertNotBase64Image(this); assertNotBlobUrl(this); if (this.fill) { assertEmptyWidthAndHeight(this); // This leaves the Angular zone to avoid triggering unnecessary change detection cycles when // `load` tasks are invoked on images. ngZone.runOutsideAngular(() => assertNonZeroRenderedHeight(this, this.imgElement, this.renderer), ); } else { assertNonEmptyWidthAndHeight(this); if (this.height !== undefined) { assertGreaterThanZero(this, this.height, 'height'); } if (this.width !== undefined) { assertGreaterThanZero(this, this.width, 'width'); } // Only check for distorted images when not in fill mode, where // images may be intentionally stretched, cropped or letterboxed. ngZone.runOutsideAngular(() => assertNoImageDistortion(this, this.imgElement, this.renderer), ); } assertValidLoadingInput(this); if (!this.ngSrcset) { assertNoComplexSizes(this); } assertValidPlaceholder(this, this.imageLoader); assertNotMissingBuiltInLoader(this.ngSrc, this.imageLoader); assertNoNgSrcsetWithoutLoader(this, this.imageLoader); assertNoLoaderParamsWithoutLoader(this, this.imageLoader); if (this.lcpObserver !== null) { const ngZone = this.injector.get(NgZone); ngZone.runOutsideAngular(() => { this.lcpObserver!.registerImage(this.getRewrittenSrc(), this.ngSrc, this.priority); }); } if (this.priority) { const checker = this.injector.get(PreconnectLinkChecker); checker.assertPreconnect(this.getRewrittenSrc(), this.ngSrc); if (!this.isServer) { const applicationRef = this.injector.get(ApplicationRef); assetPriorityCountBelowThreshold(applicationRef); } } } if (this.placeholder) { this.removePlaceholderOnLoad(this.imgElement); } this.setHostAttributes(); } private setHostAttributes() { // Must set width/height explicitly in case they are bound (in which case they will // only be reflected and not found by the browser) if (this.fill) { this.sizes ||= '100vw'; } else { this.setHostAttribute('width', this.width!.toString()); this.setHostAttribute('height', this.height!.toString()); } this.setHostAttribute('loading', this.getLoadingBehavior()); this.setHostAttribute('fetchpriority', this.getFetchPriority()); // The `data-ng-img` attribute flags an image as using the directive, to allow // for analysis of the directive's performance. this.setHostAttribute('ng-img', 'true'); // The `src` and `srcset` attributes should be set last since other attributes // could affect the image's loading behavior. const rewrittenSrcset = this.updateSrcAndSrcset(); if (this.sizes) { if (this.getLoadingBehavior() === 'lazy') { this.setHostAttribute('sizes', 'auto, ' + this.sizes); } else { this.setHostAttribute('sizes', this.sizes); } } else { if ( this.ngSrcset && VALID_WIDTH_DESCRIPTOR_SRCSET.test(this.ngSrcset) && this.getLoadingBehavior() === 'lazy' ) { this.setHostAttribute('sizes', 'auto, 100vw'); } } if (this.isServer && this.priority) { this.preloadLinkCreator.createPreloadLinkTag( this.renderer, this.getRewrittenSrc(), rewrittenSrcset, this.sizes, ); } } /** @nodoc */ ngOnCh
{ "end_byte": 17733, "start_byte": 9450, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts" }
angular/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts_17736_25908
es(changes: SimpleChanges) { if (ngDevMode) { assertNoPostInitInputChange(this, changes, [ 'ngSrcset', 'width', 'height', 'priority', 'fill', 'loading', 'sizes', 'loaderParams', 'disableOptimizedSrcset', ]); } if (changes['ngSrc'] && !changes['ngSrc'].isFirstChange()) { const oldSrc = this._renderedSrc; this.updateSrcAndSrcset(true); const newSrc = this._renderedSrc; if (this.lcpObserver !== null && oldSrc && newSrc && oldSrc !== newSrc) { const ngZone = this.injector.get(NgZone); ngZone.runOutsideAngular(() => { this.lcpObserver?.updateImage(oldSrc, newSrc); }); } } if (ngDevMode && changes['placeholder']?.currentValue && !this.isServer) { assertPlaceholderDimensions(this, this.imgElement); } } private callImageLoader( configWithoutCustomParams: Omit<ImageLoaderConfig, 'loaderParams'>, ): string { let augmentedConfig: ImageLoaderConfig = configWithoutCustomParams; if (this.loaderParams) { augmentedConfig.loaderParams = this.loaderParams; } return this.imageLoader(augmentedConfig); } private getLoadingBehavior(): string { if (!this.priority && this.loading !== undefined) { return this.loading; } return this.priority ? 'eager' : 'lazy'; } private getFetchPriority(): string { return this.priority ? 'high' : 'auto'; } private getRewrittenSrc(): string { // ImageLoaderConfig supports setting a width property. However, we're not setting width here // because if the developer uses rendered width instead of intrinsic width in the HTML width // attribute, the image requested may be too small for 2x+ screens. if (!this._renderedSrc) { const imgConfig = {src: this.ngSrc}; // Cache calculated image src to reuse it later in the code. this._renderedSrc = this.callImageLoader(imgConfig); } return this._renderedSrc; } private getRewrittenSrcset(): string { const widthSrcSet = VALID_WIDTH_DESCRIPTOR_SRCSET.test(this.ngSrcset); const finalSrcs = this.ngSrcset .split(',') .filter((src) => src !== '') .map((srcStr) => { srcStr = srcStr.trim(); const width = widthSrcSet ? parseFloat(srcStr) : parseFloat(srcStr) * this.width!; return `${this.callImageLoader({src: this.ngSrc, width})} ${srcStr}`; }); return finalSrcs.join(', '); } private getAutomaticSrcset(): string { if (this.sizes) { return this.getResponsiveSrcset(); } else { return this.getFixedSrcset(); } } private getResponsiveSrcset(): string { const {breakpoints} = this.config; let filteredBreakpoints = breakpoints!; if (this.sizes?.trim() === '100vw') { // Since this is a full-screen-width image, our srcset only needs to include // breakpoints with full viewport widths. filteredBreakpoints = breakpoints!.filter((bp) => bp >= VIEWPORT_BREAKPOINT_CUTOFF); } const finalSrcs = filteredBreakpoints.map( (bp) => `${this.callImageLoader({src: this.ngSrc, width: bp})} ${bp}w`, ); return finalSrcs.join(', '); } private updateSrcAndSrcset(forceSrcRecalc = false): string | undefined { if (forceSrcRecalc) { // Reset cached value, so that the followup `getRewrittenSrc()` call // will recalculate it and update the cache. this._renderedSrc = null; } const rewrittenSrc = this.getRewrittenSrc(); this.setHostAttribute('src', rewrittenSrc); let rewrittenSrcset: string | undefined = undefined; if (this.ngSrcset) { rewrittenSrcset = this.getRewrittenSrcset(); } else if (this.shouldGenerateAutomaticSrcset()) { rewrittenSrcset = this.getAutomaticSrcset(); } if (rewrittenSrcset) { this.setHostAttribute('srcset', rewrittenSrcset); } return rewrittenSrcset; } private getFixedSrcset(): string { const finalSrcs = DENSITY_SRCSET_MULTIPLIERS.map( (multiplier) => `${this.callImageLoader({ src: this.ngSrc, width: this.width! * multiplier, })} ${multiplier}x`, ); return finalSrcs.join(', '); } private shouldGenerateAutomaticSrcset(): boolean { let oversizedImage = false; if (!this.sizes) { oversizedImage = this.width! > FIXED_SRCSET_WIDTH_LIMIT || this.height! > FIXED_SRCSET_HEIGHT_LIMIT; } return ( !this.disableOptimizedSrcset && !this.srcset && this.imageLoader !== noopImageLoader && !oversizedImage ); } /** * Returns an image url formatted for use with the CSS background-image property. Expects one of: * * A base64 encoded image, which is wrapped and passed through. * * A boolean. If true, calls the image loader to generate a small placeholder url. */ private generatePlaceholder(placeholderInput: string | boolean): string | boolean | null { const {placeholderResolution} = this.config; if (placeholderInput === true) { return `url(${this.callImageLoader({ src: this.ngSrc, width: placeholderResolution, isPlaceholder: true, })})`; } else if (typeof placeholderInput === 'string') { return `url(${placeholderInput})`; } return null; } /** * Determines if blur should be applied, based on an optional boolean * property `blur` within the optional configuration object `placeholderConfig`. */ private shouldBlurPlaceholder(placeholderConfig?: ImagePlaceholderConfig): boolean { if (!placeholderConfig || !placeholderConfig.hasOwnProperty('blur')) { return true; } return Boolean(placeholderConfig.blur); } private removePlaceholderOnLoad(img: HTMLImageElement): void { const callback = () => { const changeDetectorRef = this.injector.get(ChangeDetectorRef); removeLoadListenerFn(); removeErrorListenerFn(); this.placeholder = false; changeDetectorRef.markForCheck(); }; const removeLoadListenerFn = this.renderer.listen(img, 'load', callback); const removeErrorListenerFn = this.renderer.listen(img, 'error', callback); callOnLoadIfImageIsLoaded(img, callback); } /** @nodoc */ ngOnDestroy() { if (ngDevMode) { if (!this.priority && this._renderedSrc !== null && this.lcpObserver !== null) { this.lcpObserver.unregisterImage(this._renderedSrc); } } } private setHostAttribute(name: string, value: string): void { this.renderer.setAttribute(this.imgElement, name, value); } } /***** Helpers *****/ /** * Sorts provided config breakpoints and uses defaults. */ function processConfig(config: ImageConfig): ImageConfig { let sortedBreakpoints: {breakpoints?: number[]} = {}; if (config.breakpoints) { sortedBreakpoints.breakpoints = config.breakpoints.sort((a, b) => a - b); } return Object.assign({}, IMAGE_CONFIG_DEFAULTS, config, sortedBreakpoints); } /***** Assert functions *****/ /** * Verifies that there is no `src` set on a host element. */ function assertNoConflictingSrc(dir: NgOptimizedImage) { if (dir.src) { throw new RuntimeError( RuntimeErrorCode.UNEXPECTED_SRC_ATTR, `${imgDirectiveDetails(dir.ngSrc)} both \`src\` and \`ngSrc\` have been set. ` + `Supplying both of these attributes breaks lazy loading. ` + `The NgOptimizedImage directive sets \`src\` itself based on the value of \`ngSrc\`. ` + `To fix this, please remove the \`src\` attribute.`, ); } } /** * Verifies that there is no `srcset` set on a host element. */ function assertNoConflictingSrcset(dir: NgOptimizedImage) { if (dir.srcset) { throw new RuntimeError( RuntimeErrorCode.UNEXPECTED_SRCSET_ATTR, `${imgDirectiveDetails(dir.ngSrc)} both \`srcset\` and \`ngSrcset\` have been set. ` + `Supplying both of these attributes breaks lazy loading. ` + `The NgOptimizedImage directive sets \`srcset\` itself based on the value of ` + `\`ngSrcset\`. To fix this, please remove the \`srcset\` attribute.`, ); } } /** *
{ "end_byte": 25908, "start_byte": 17736, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts" }
angular/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts_25910_33462
rifies that the `ngSrc` is not a Base64-encoded image. */ function assertNotBase64Image(dir: NgOptimizedImage) { let ngSrc = dir.ngSrc.trim(); if (ngSrc.startsWith('data:')) { if (ngSrc.length > BASE64_IMG_MAX_LENGTH_IN_ERROR) { ngSrc = ngSrc.substring(0, BASE64_IMG_MAX_LENGTH_IN_ERROR) + '...'; } throw new RuntimeError( RuntimeErrorCode.INVALID_INPUT, `${imgDirectiveDetails(dir.ngSrc, false)} \`ngSrc\` is a Base64-encoded string ` + `(${ngSrc}). NgOptimizedImage does not support Base64-encoded strings. ` + `To fix this, disable the NgOptimizedImage directive for this element ` + `by removing \`ngSrc\` and using a standard \`src\` attribute instead.`, ); } } /** * Verifies that the 'sizes' only includes responsive values. */ function assertNoComplexSizes(dir: NgOptimizedImage) { let sizes = dir.sizes; if (sizes?.match(/((\)|,)\s|^)\d+px/)) { throw new RuntimeError( RuntimeErrorCode.INVALID_INPUT, `${imgDirectiveDetails(dir.ngSrc, false)} \`sizes\` was set to a string including ` + `pixel values. For automatic \`srcset\` generation, \`sizes\` must only include responsive ` + `values, such as \`sizes="50vw"\` or \`sizes="(min-width: 768px) 50vw, 100vw"\`. ` + `To fix this, modify the \`sizes\` attribute, or provide your own \`ngSrcset\` value directly.`, ); } } function assertValidPlaceholder(dir: NgOptimizedImage, imageLoader: ImageLoader) { assertNoPlaceholderConfigWithoutPlaceholder(dir); assertNoRelativePlaceholderWithoutLoader(dir, imageLoader); assertNoOversizedDataUrl(dir); } /** * Verifies that placeholderConfig isn't being used without placeholder */ function assertNoPlaceholderConfigWithoutPlaceholder(dir: NgOptimizedImage) { if (dir.placeholderConfig && !dir.placeholder) { throw new RuntimeError( RuntimeErrorCode.INVALID_INPUT, `${imgDirectiveDetails( dir.ngSrc, false, )} \`placeholderConfig\` options were provided for an ` + `image that does not use the \`placeholder\` attribute, and will have no effect.`, ); } } /** * Warns if a relative URL placeholder is specified, but no loader is present to provide the small * image. */ function assertNoRelativePlaceholderWithoutLoader(dir: NgOptimizedImage, imageLoader: ImageLoader) { if (dir.placeholder === true && imageLoader === noopImageLoader) { throw new RuntimeError( RuntimeErrorCode.MISSING_NECESSARY_LOADER, `${imgDirectiveDetails(dir.ngSrc)} the \`placeholder\` attribute is set to true but ` + `no image loader is configured (i.e. the default one is being used), ` + `which would result in the same image being used for the primary image and its placeholder. ` + `To fix this, provide a loader or remove the \`placeholder\` attribute from the image.`, ); } } /** * Warns or throws an error if an oversized dataURL placeholder is provided. */ function assertNoOversizedDataUrl(dir: NgOptimizedImage) { if ( dir.placeholder && typeof dir.placeholder === 'string' && dir.placeholder.startsWith('data:') ) { if (dir.placeholder.length > DATA_URL_ERROR_LIMIT) { throw new RuntimeError( RuntimeErrorCode.OVERSIZED_PLACEHOLDER, `${imgDirectiveDetails( dir.ngSrc, )} the \`placeholder\` attribute is set to a data URL which is longer ` + `than ${DATA_URL_ERROR_LIMIT} characters. This is strongly discouraged, as large inline placeholders ` + `directly increase the bundle size of Angular and hurt page load performance. To fix this, generate ` + `a smaller data URL placeholder.`, ); } if (dir.placeholder.length > DATA_URL_WARN_LIMIT) { console.warn( formatRuntimeError( RuntimeErrorCode.OVERSIZED_PLACEHOLDER, `${imgDirectiveDetails( dir.ngSrc, )} the \`placeholder\` attribute is set to a data URL which is longer ` + `than ${DATA_URL_WARN_LIMIT} characters. This is discouraged, as large inline placeholders ` + `directly increase the bundle size of Angular and hurt page load performance. For better loading performance, ` + `generate a smaller data URL placeholder.`, ), ); } } } /** * Verifies that the `ngSrc` is not a Blob URL. */ function assertNotBlobUrl(dir: NgOptimizedImage) { const ngSrc = dir.ngSrc.trim(); if (ngSrc.startsWith('blob:')) { throw new RuntimeError( RuntimeErrorCode.INVALID_INPUT, `${imgDirectiveDetails(dir.ngSrc)} \`ngSrc\` was set to a blob URL (${ngSrc}). ` + `Blob URLs are not supported by the NgOptimizedImage directive. ` + `To fix this, disable the NgOptimizedImage directive for this element ` + `by removing \`ngSrc\` and using a regular \`src\` attribute instead.`, ); } } /** * Verifies that the input is set to a non-empty string. */ function assertNonEmptyInput(dir: NgOptimizedImage, name: string, value: unknown) { const isString = typeof value === 'string'; const isEmptyString = isString && value.trim() === ''; if (!isString || isEmptyString) { throw new RuntimeError( RuntimeErrorCode.INVALID_INPUT, `${imgDirectiveDetails(dir.ngSrc)} \`${name}\` has an invalid value ` + `(\`${value}\`). To fix this, change the value to a non-empty string.`, ); } } /** * Verifies that the `ngSrcset` is in a valid format, e.g. "100w, 200w" or "1x, 2x". */ export function assertValidNgSrcset(dir: NgOptimizedImage, value: unknown) { if (value == null) return; assertNonEmptyInput(dir, 'ngSrcset', value); const stringVal = value as string; const isValidWidthDescriptor = VALID_WIDTH_DESCRIPTOR_SRCSET.test(stringVal); const isValidDensityDescriptor = VALID_DENSITY_DESCRIPTOR_SRCSET.test(stringVal); if (isValidDensityDescriptor) { assertUnderDensityCap(dir, stringVal); } const isValidSrcset = isValidWidthDescriptor || isValidDensityDescriptor; if (!isValidSrcset) { throw new RuntimeError( RuntimeErrorCode.INVALID_INPUT, `${imgDirectiveDetails(dir.ngSrc)} \`ngSrcset\` has an invalid value (\`${value}\`). ` + `To fix this, supply \`ngSrcset\` using a comma-separated list of one or more width ` + `descriptors (e.g. "100w, 200w") or density descriptors (e.g. "1x, 2x").`, ); } } function assertUnderDensityCap(dir: NgOptimizedImage, value: string) { const underDensityCap = value .split(',') .every((num) => num === '' || parseFloat(num) <= ABSOLUTE_SRCSET_DENSITY_CAP); if (!underDensityCap) { throw new RuntimeError( RuntimeErrorCode.INVALID_INPUT, `${imgDirectiveDetails(dir.ngSrc)} the \`ngSrcset\` contains an unsupported image density:` + `\`${value}\`. NgOptimizedImage generally recommends a max image density of ` + `${RECOMMENDED_SRCSET_DENSITY_CAP}x but supports image densities up to ` + `${ABSOLUTE_SRCSET_DENSITY_CAP}x. The human eye cannot distinguish between image densities ` + `greater than ${RECOMMENDED_SRCSET_DENSITY_CAP}x - which makes them unnecessary for ` + `most use cases. Images that will be pinch-zoomed are typically the primary use case for ` + `${ABSOLUTE_SRCSET_DENSITY_CAP}x images. Please remove the high density descriptor and try again.`, ); } } /** * Creates a `RuntimeError` instance to represent a situation when an input is set after * the directive has initialized. */ function
{ "end_byte": 33462, "start_byte": 25910, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts" }
angular/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts_33463_41788
postInitInputChangeError(dir: NgOptimizedImage, inputName: string): {} { let reason!: string; if (inputName === 'width' || inputName === 'height') { reason = `Changing \`${inputName}\` may result in different attribute value ` + `applied to the underlying image element and cause layout shifts on a page.`; } else { reason = `Changing the \`${inputName}\` would have no effect on the underlying ` + `image element, because the resource loading has already occurred.`; } return new RuntimeError( RuntimeErrorCode.UNEXPECTED_INPUT_CHANGE, `${imgDirectiveDetails(dir.ngSrc)} \`${inputName}\` was updated after initialization. ` + `The NgOptimizedImage directive will not react to this input change. ${reason} ` + `To fix this, either switch \`${inputName}\` to a static value ` + `or wrap the image element in an *ngIf that is gated on the necessary value.`, ); } /** * Verify that none of the listed inputs has changed. */ function assertNoPostInitInputChange( dir: NgOptimizedImage, changes: SimpleChanges, inputs: string[], ) { inputs.forEach((input) => { const isUpdated = changes.hasOwnProperty(input); if (isUpdated && !changes[input].isFirstChange()) { if (input === 'ngSrc') { // When the `ngSrc` input changes, we detect that only in the // `ngOnChanges` hook, thus the `ngSrc` is already set. We use // `ngSrc` in the error message, so we use a previous value, but // not the updated one in it. dir = {ngSrc: changes[input].previousValue} as NgOptimizedImage; } throw postInitInputChangeError(dir, input); } }); } /** * Verifies that a specified input is a number greater than 0. */ function assertGreaterThanZero(dir: NgOptimizedImage, inputValue: unknown, inputName: string) { const validNumber = typeof inputValue === 'number' && inputValue > 0; const validString = typeof inputValue === 'string' && /^\d+$/.test(inputValue.trim()) && parseInt(inputValue) > 0; if (!validNumber && !validString) { throw new RuntimeError( RuntimeErrorCode.INVALID_INPUT, `${imgDirectiveDetails(dir.ngSrc)} \`${inputName}\` has an invalid value. ` + `To fix this, provide \`${inputName}\` as a number greater than 0.`, ); } } /** * Verifies that the rendered image is not visually distorted. Effectively this is checking: * - Whether the "width" and "height" attributes reflect the actual dimensions of the image. * - Whether image styling is "correct" (see below for a longer explanation). */ function assertNoImageDistortion( dir: NgOptimizedImage, img: HTMLImageElement, renderer: Renderer2, ) { const callback = () => { removeLoadListenerFn(); removeErrorListenerFn(); const computedStyle = window.getComputedStyle(img); let renderedWidth = parseFloat(computedStyle.getPropertyValue('width')); let renderedHeight = parseFloat(computedStyle.getPropertyValue('height')); const boxSizing = computedStyle.getPropertyValue('box-sizing'); if (boxSizing === 'border-box') { const paddingTop = computedStyle.getPropertyValue('padding-top'); const paddingRight = computedStyle.getPropertyValue('padding-right'); const paddingBottom = computedStyle.getPropertyValue('padding-bottom'); const paddingLeft = computedStyle.getPropertyValue('padding-left'); renderedWidth -= parseFloat(paddingRight) + parseFloat(paddingLeft); renderedHeight -= parseFloat(paddingTop) + parseFloat(paddingBottom); } const renderedAspectRatio = renderedWidth / renderedHeight; const nonZeroRenderedDimensions = renderedWidth !== 0 && renderedHeight !== 0; const intrinsicWidth = img.naturalWidth; const intrinsicHeight = img.naturalHeight; const intrinsicAspectRatio = intrinsicWidth / intrinsicHeight; const suppliedWidth = dir.width!; const suppliedHeight = dir.height!; const suppliedAspectRatio = suppliedWidth / suppliedHeight; // Tolerance is used to account for the impact of subpixel rendering. // Due to subpixel rendering, the rendered, intrinsic, and supplied // aspect ratios of a correctly configured image may not exactly match. // For example, a `width=4030 height=3020` image might have a rendered // size of "1062w, 796.48h". (An aspect ratio of 1.334... vs. 1.333...) const inaccurateDimensions = Math.abs(suppliedAspectRatio - intrinsicAspectRatio) > ASPECT_RATIO_TOLERANCE; const stylingDistortion = nonZeroRenderedDimensions && Math.abs(intrinsicAspectRatio - renderedAspectRatio) > ASPECT_RATIO_TOLERANCE; if (inaccurateDimensions) { console.warn( formatRuntimeError( RuntimeErrorCode.INVALID_INPUT, `${imgDirectiveDetails(dir.ngSrc)} the aspect ratio of the image does not match ` + `the aspect ratio indicated by the width and height attributes. ` + `\nIntrinsic image size: ${intrinsicWidth}w x ${intrinsicHeight}h ` + `(aspect-ratio: ${round( intrinsicAspectRatio, )}). \nSupplied width and height attributes: ` + `${suppliedWidth}w x ${suppliedHeight}h (aspect-ratio: ${round( suppliedAspectRatio, )}). ` + `\nTo fix this, update the width and height attributes.`, ), ); } else if (stylingDistortion) { console.warn( formatRuntimeError( RuntimeErrorCode.INVALID_INPUT, `${imgDirectiveDetails(dir.ngSrc)} the aspect ratio of the rendered image ` + `does not match the image's intrinsic aspect ratio. ` + `\nIntrinsic image size: ${intrinsicWidth}w x ${intrinsicHeight}h ` + `(aspect-ratio: ${round(intrinsicAspectRatio)}). \nRendered image size: ` + `${renderedWidth}w x ${renderedHeight}h (aspect-ratio: ` + `${round(renderedAspectRatio)}). \nThis issue can occur if "width" and "height" ` + `attributes are added to an image without updating the corresponding ` + `image styling. To fix this, adjust image styling. In most cases, ` + `adding "height: auto" or "width: auto" to the image styling will fix ` + `this issue.`, ), ); } else if (!dir.ngSrcset && nonZeroRenderedDimensions) { // If `ngSrcset` hasn't been set, sanity check the intrinsic size. const recommendedWidth = RECOMMENDED_SRCSET_DENSITY_CAP * renderedWidth; const recommendedHeight = RECOMMENDED_SRCSET_DENSITY_CAP * renderedHeight; const oversizedWidth = intrinsicWidth - recommendedWidth >= OVERSIZED_IMAGE_TOLERANCE; const oversizedHeight = intrinsicHeight - recommendedHeight >= OVERSIZED_IMAGE_TOLERANCE; if (oversizedWidth || oversizedHeight) { console.warn( formatRuntimeError( RuntimeErrorCode.OVERSIZED_IMAGE, `${imgDirectiveDetails(dir.ngSrc)} the intrinsic image is significantly ` + `larger than necessary. ` + `\nRendered image size: ${renderedWidth}w x ${renderedHeight}h. ` + `\nIntrinsic image size: ${intrinsicWidth}w x ${intrinsicHeight}h. ` + `\nRecommended intrinsic image size: ${recommendedWidth}w x ${recommendedHeight}h. ` + `\nNote: Recommended intrinsic image size is calculated assuming a maximum DPR of ` + `${RECOMMENDED_SRCSET_DENSITY_CAP}. To improve loading time, resize the image ` + `or consider using the "ngSrcset" and "sizes" attributes.`, ), ); } } }; const removeLoadListenerFn = renderer.listen(img, 'load', callback); // We only listen to the `error` event to remove the `load` event listener because it will not be // fired if the image fails to load. This is done to prevent memory leaks in development mode // because image elements aren't garbage-collected properly. It happens because zone.js stores the // event listener directly on the element and closures capture `dir`. const removeErrorListenerFn = renderer.listen(img, 'error', () => { removeLoadListenerFn(); removeErrorListenerFn(); }); callOnLoadIfImageIsLoaded(img, callback); } /** * Verifies that a specified input is set. */ function
{ "end_byte": 41788, "start_byte": 33463, "url": "https://github.com/angular/angular/blob/main/packages/common/src/directives/ng_optimized_image/ng_optimized_image.ts" }