refactor: move angular source to /packages rather than modules/@angular

This commit is contained in:
Jason Aden
2017-03-02 10:48:42 -08:00
parent 5ad5301a3e
commit 3e51a19983
1051 changed files with 18 additions and 18 deletions

View File

@ -0,0 +1,56 @@
/**
* @license
* Copyright Google Inc. 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.io/license
*/
import {Injectable} from '@angular/core';
let _nextRequestId = 0;
export const JSONP_HOME = '__ng_jsonp__';
let _jsonpConnections: {[key: string]: any} = null;
function _getJsonpConnections(): {[key: string]: any} {
const w: {[key: string]: any} = typeof window == 'object' ? window : {};
if (_jsonpConnections === null) {
_jsonpConnections = w[JSONP_HOME] = {};
}
return _jsonpConnections;
}
// Make sure not to evaluate this in a non-browser environment!
@Injectable()
export class BrowserJsonp {
// Construct a <script> element with the specified URL
build(url: string): any {
const node = document.createElement('script');
node.src = url;
return node;
}
nextRequestID(): string { return `__req${_nextRequestId++}`; }
requestCallback(id: string): string { return `${JSONP_HOME}.${id}.finished`; }
exposeConnection(id: string, connection: any) {
const connections = _getJsonpConnections();
connections[id] = connection;
}
removeConnection(id: string) {
const connections = _getJsonpConnections();
connections[id] = null;
}
// Attach the <script> element to the DOM
send(node: any) { document.body.appendChild(<Node>(node)); }
// Remove <script> element from the DOM
cleanup(node: any) {
if (node.parentNode) {
node.parentNode.removeChild(<Node>(node));
}
}
}

View File

@ -0,0 +1,22 @@
/**
* @license
* Copyright Google Inc. 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.io/license
*/
import {Injectable} from '@angular/core';
/**
* A backend for http that uses the `XMLHttpRequest` browser API.
*
* Take care not to evaluate this in non-browser contexts.
*
* @experimental
*/
@Injectable()
export class BrowserXhr {
constructor() {}
build(): any { return <any>(new XMLHttpRequest()); }
}

View File

@ -0,0 +1,157 @@
/**
* @license
* Copyright Google Inc. 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.io/license
*/
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {Observer} from 'rxjs/Observer';
import {ResponseOptions} from '../base_response_options';
import {ReadyState, RequestMethod, ResponseType} from '../enums';
import {Connection, ConnectionBackend} from '../interfaces';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {BrowserJsonp} from './browser_jsonp';
const JSONP_ERR_NO_CALLBACK = 'JSONP injected script did not invoke callback.';
const JSONP_ERR_WRONG_METHOD = 'JSONP requests must use GET request method.';
/**
* Abstract base class for an in-flight JSONP request.
*
* @experimental
*/
export abstract class JSONPConnection implements Connection {
/**
* The {@link ReadyState} of this request.
*/
readyState: ReadyState;
/**
* The outgoing HTTP request.
*/
request: Request;
/**
* An observable that completes with the response, when the request is finished.
*/
response: Observable<Response>;
/**
* Callback called when the JSONP request completes, to notify the application
* of the new data.
*/
abstract finished(data?: any): void;
}
export class JSONPConnection_ extends JSONPConnection {
private _id: string;
private _script: Element;
private _responseData: any;
private _finished: boolean = false;
constructor(
req: Request, private _dom: BrowserJsonp, private baseResponseOptions?: ResponseOptions) {
super();
if (req.method !== RequestMethod.Get) {
throw new TypeError(JSONP_ERR_WRONG_METHOD);
}
this.request = req;
this.response = new Observable<Response>((responseObserver: Observer<Response>) => {
this.readyState = ReadyState.Loading;
const id = this._id = _dom.nextRequestID();
_dom.exposeConnection(id, this);
// Workaround Dart
// url = url.replace(/=JSONP_CALLBACK(&|$)/, `generated method`);
const callback = _dom.requestCallback(this._id);
let url: string = req.url;
if (url.indexOf('=JSONP_CALLBACK&') > -1) {
url = url.replace('=JSONP_CALLBACK&', `=${callback}&`);
} else if (url.lastIndexOf('=JSONP_CALLBACK') === url.length - '=JSONP_CALLBACK'.length) {
url = url.substring(0, url.length - '=JSONP_CALLBACK'.length) + `=${callback}`;
}
const script = this._script = _dom.build(url);
const onLoad = (event: Event) => {
if (this.readyState === ReadyState.Cancelled) return;
this.readyState = ReadyState.Done;
_dom.cleanup(script);
if (!this._finished) {
let responseOptions =
new ResponseOptions({body: JSONP_ERR_NO_CALLBACK, type: ResponseType.Error, url});
if (baseResponseOptions) {
responseOptions = baseResponseOptions.merge(responseOptions);
}
responseObserver.error(new Response(responseOptions));
return;
}
let responseOptions = new ResponseOptions({body: this._responseData, url});
if (this.baseResponseOptions) {
responseOptions = this.baseResponseOptions.merge(responseOptions);
}
responseObserver.next(new Response(responseOptions));
responseObserver.complete();
};
const onError = (error: Error) => {
if (this.readyState === ReadyState.Cancelled) return;
this.readyState = ReadyState.Done;
_dom.cleanup(script);
let responseOptions = new ResponseOptions({body: error.message, type: ResponseType.Error});
if (baseResponseOptions) {
responseOptions = baseResponseOptions.merge(responseOptions);
}
responseObserver.error(new Response(responseOptions));
};
script.addEventListener('load', onLoad);
script.addEventListener('error', onError);
_dom.send(script);
return () => {
this.readyState = ReadyState.Cancelled;
script.removeEventListener('load', onLoad);
script.removeEventListener('error', onError);
this._dom.cleanup(script);
};
});
}
finished(data?: any) {
// Don't leak connections
this._finished = true;
this._dom.removeConnection(this._id);
if (this.readyState === ReadyState.Cancelled) return;
this._responseData = data;
}
}
/**
* A {@link ConnectionBackend} that uses the JSONP strategy of making requests.
*
* @experimental
*/
export abstract class JSONPBackend extends ConnectionBackend {}
@Injectable()
export class JSONPBackend_ extends JSONPBackend {
constructor(private _browserJSONP: BrowserJsonp, private _baseResponseOptions: ResponseOptions) {
super();
}
createConnection(request: Request): JSONPConnection {
return new JSONPConnection_(request, this._browserJSONP, this._baseResponseOptions);
}
}

View File

@ -0,0 +1,241 @@
/**
* @license
* Copyright Google Inc. 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.io/license
*/
import {Injectable} from '@angular/core';
import {ɵgetDOM as getDOM} from '@angular/platform-browser';
import {Observable} from 'rxjs/Observable';
import {Observer} from 'rxjs/Observer';
import {ResponseOptions} from '../base_response_options';
import {ContentType, ReadyState, RequestMethod, ResponseContentType, ResponseType} from '../enums';
import {Headers} from '../headers';
import {getResponseURL, isSuccess} from '../http_utils';
import {Connection, ConnectionBackend, XSRFStrategy} from '../interfaces';
import {Request} from '../static_request';
import {Response} from '../static_response';
import {BrowserXhr} from './browser_xhr';
const XSSI_PREFIX = /^\)\]\}',?\n/;
/**
* Creates connections using `XMLHttpRequest`. Given a fully-qualified
* request, an `XHRConnection` will immediately create an `XMLHttpRequest` object and send the
* request.
*
* This class would typically not be created or interacted with directly inside applications, though
* the {@link MockConnection} may be interacted with in tests.
*
* @experimental
*/
export class XHRConnection implements Connection {
request: Request;
/**
* Response {@link EventEmitter} which emits a single {@link Response} value on load event of
* `XMLHttpRequest`.
*/
response: Observable<Response>;
readyState: ReadyState;
constructor(req: Request, browserXHR: BrowserXhr, baseResponseOptions?: ResponseOptions) {
this.request = req;
this.response = new Observable<Response>((responseObserver: Observer<Response>) => {
const _xhr: XMLHttpRequest = browserXHR.build();
_xhr.open(RequestMethod[req.method].toUpperCase(), req.url);
if (req.withCredentials != null) {
_xhr.withCredentials = req.withCredentials;
}
// load event handler
const onLoad = () => {
// normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
let status: number = _xhr.status === 1223 ? 204 : _xhr.status;
let body: any = null;
// HTTP 204 means no content
if (status !== 204) {
// responseText is the old-school way of retrieving response (supported by IE8 & 9)
// response/responseType properties were introduced in ResourceLoader Level2 spec
// (supported by IE10)
body = (typeof _xhr.response === 'undefined') ? _xhr.responseText : _xhr.response;
// Implicitly strip a potential XSSI prefix.
if (typeof body === 'string') {
body = body.replace(XSSI_PREFIX, '');
}
}
// fix status code when it is 0 (0 status is undocumented).
// Occurs when accessing file resources or on Android 4.1 stock browser
// while retrieving files from application cache.
if (status === 0) {
status = body ? 200 : 0;
}
const headers: Headers = Headers.fromResponseHeaderString(_xhr.getAllResponseHeaders());
// IE 9 does not provide the way to get URL of response
const url = getResponseURL(_xhr) || req.url;
const statusText: string = _xhr.statusText || 'OK';
let responseOptions = new ResponseOptions({body, status, headers, statusText, url});
if (baseResponseOptions != null) {
responseOptions = baseResponseOptions.merge(responseOptions);
}
const response = new Response(responseOptions);
response.ok = isSuccess(status);
if (response.ok) {
responseObserver.next(response);
// TODO(gdi2290): defer complete if array buffer until done
responseObserver.complete();
return;
}
responseObserver.error(response);
};
// error event handler
const onError = (err: ErrorEvent) => {
let responseOptions = new ResponseOptions({
body: err,
type: ResponseType.Error,
status: _xhr.status,
statusText: _xhr.statusText,
});
if (baseResponseOptions != null) {
responseOptions = baseResponseOptions.merge(responseOptions);
}
responseObserver.error(new Response(responseOptions));
};
this.setDetectedContentType(req, _xhr);
if (req.headers == null) {
req.headers = new Headers();
}
if (!req.headers.has('Accept')) {
req.headers.append('Accept', 'application/json, text/plain, */*');
}
req.headers.forEach((values, name) => _xhr.setRequestHeader(name, values.join(',')));
// Select the correct buffer type to store the response
if (req.responseType != null && _xhr.responseType != null) {
switch (req.responseType) {
case ResponseContentType.ArrayBuffer:
_xhr.responseType = 'arraybuffer';
break;
case ResponseContentType.Json:
_xhr.responseType = 'json';
break;
case ResponseContentType.Text:
_xhr.responseType = 'text';
break;
case ResponseContentType.Blob:
_xhr.responseType = 'blob';
break;
default:
throw new Error('The selected responseType is not supported');
}
}
_xhr.addEventListener('load', onLoad);
_xhr.addEventListener('error', onError);
_xhr.send(this.request.getBody());
return () => {
_xhr.removeEventListener('load', onLoad);
_xhr.removeEventListener('error', onError);
_xhr.abort();
};
});
}
setDetectedContentType(req: any /** TODO Request */, _xhr: any /** XMLHttpRequest */) {
// Skip if a custom Content-Type header is provided
if (req.headers != null && req.headers.get('Content-Type') != null) {
return;
}
// Set the detected content type
switch (req.contentType) {
case ContentType.NONE:
break;
case ContentType.JSON:
_xhr.setRequestHeader('content-type', 'application/json');
break;
case ContentType.FORM:
_xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
break;
case ContentType.TEXT:
_xhr.setRequestHeader('content-type', 'text/plain');
break;
case ContentType.BLOB:
const blob = req.blob();
if (blob.type) {
_xhr.setRequestHeader('content-type', blob.type);
}
break;
}
}
}
/**
* `XSRFConfiguration` sets up Cross Site Request Forgery (XSRF) protection for the application
* using a cookie. See https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)
* for more information on XSRF.
*
* Applications can configure custom cookie and header names by binding an instance of this class
* with different `cookieName` and `headerName` values. See the main HTTP documentation for more
* details.
*
* @experimental
*/
export class CookieXSRFStrategy implements XSRFStrategy {
constructor(
private _cookieName: string = 'XSRF-TOKEN', private _headerName: string = 'X-XSRF-TOKEN') {}
configureRequest(req: Request): void {
const xsrfToken = getDOM().getCookie(this._cookieName);
if (xsrfToken) {
req.headers.set(this._headerName, xsrfToken);
}
}
}
/**
* Creates {@link XHRConnection} instances.
*
* This class would typically not be used by end users, but could be
* overridden if a different backend implementation should be used,
* such as in a node backend.
*
* ### Example
*
* ```
* import {Http, MyNodeBackend, HTTP_PROVIDERS, BaseRequestOptions} from '@angular/http';
* @Component({
* viewProviders: [
* HTTP_PROVIDERS,
* {provide: Http, useFactory: (backend, options) => {
* return new Http(backend, options);
* }, deps: [MyNodeBackend, BaseRequestOptions]}]
* })
* class MyComponent {
* constructor(http:Http) {
* http.request('people.json').subscribe(res => this.people = res.json());
* }
* }
* ```
* @experimental
*/
@Injectable()
export class XHRBackend implements ConnectionBackend {
constructor(
private _browserXHR: BrowserXhr, private _baseResponseOptions: ResponseOptions,
private _xsrfStrategy: XSRFStrategy) {}
createConnection(request: Request): XHRConnection {
this._xsrfStrategy.configureRequest(request);
return new XHRConnection(request, this._browserXHR, this._baseResponseOptions);
}
}

View File

@ -0,0 +1,220 @@
/**
* @license
* Copyright Google Inc. 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.io/license
*/
import {Injectable} from '@angular/core';
import {RequestMethod, ResponseContentType} from './enums';
import {Headers} from './headers';
import {normalizeMethodName} from './http_utils';
import {RequestOptionsArgs} from './interfaces';
import {URLSearchParams} from './url_search_params';
/**
* Creates a request options object to be optionally provided when instantiating a
* {@link Request}.
*
* This class is based on the `RequestInit` description in the [Fetch
* Spec](https://fetch.spec.whatwg.org/#requestinit).
*
* All values are null by default. Typical defaults can be found in the {@link BaseRequestOptions}
* class, which sub-classes `RequestOptions`.
*
* ### Example ([live demo](http://plnkr.co/edit/7Wvi3lfLq41aQPKlxB4O?p=preview))
*
* ```typescript
* import {RequestOptions, Request, RequestMethod} from '@angular/http';
*
* var options = new RequestOptions({
* method: RequestMethod.Post,
* url: 'https://google.com'
* });
* var req = new Request(options);
* console.log('req.method:', RequestMethod[req.method]); // Post
* console.log('options.url:', options.url); // https://google.com
* ```
*
* @experimental
*/
export class RequestOptions {
/**
* Http method with which to execute a {@link Request}.
* Acceptable methods are defined in the {@link RequestMethod} enum.
*/
method: RequestMethod|string;
/**
* {@link Headers} to be attached to a {@link Request}.
*/
headers: Headers;
/**
* Body to be used when creating a {@link Request}.
*/
body: any;
/**
* Url with which to perform a {@link Request}.
*/
url: string;
/**
* Search parameters to be included in a {@link Request}.
*/
params: URLSearchParams;
/**
* @deprecated from 4.0.0. Use params instead.
*/
get search(): URLSearchParams { return this.params; }
/**
* @deprecated from 4.0.0. Use params instead.
*/
set search(params: URLSearchParams) { this.params = params; }
/**
* Enable use credentials for a {@link Request}.
*/
withCredentials: boolean;
/*
* Select a buffer to store the response, such as ArrayBuffer, Blob, Json (or Document)
*/
responseType: ResponseContentType;
// TODO(Dzmitry): remove search when this.search is removed
constructor(
{method, headers, body, url, search, params, withCredentials,
responseType}: RequestOptionsArgs = {}) {
this.method = method != null ? normalizeMethodName(method) : null;
this.headers = headers != null ? headers : null;
this.body = body != null ? body : null;
this.url = url != null ? url : null;
this.params = this._mergeSearchParams(params || search);
this.withCredentials = withCredentials != null ? withCredentials : null;
this.responseType = responseType != null ? responseType : null;
}
/**
* Creates a copy of the `RequestOptions` instance, using the optional input as values to override
* existing values. This method will not change the values of the instance on which it is being
* called.
*
* Note that `headers` and `search` will override existing values completely if present in
* the `options` object. If these values should be merged, it should be done prior to calling
* `merge` on the `RequestOptions` instance.
*
* ### Example ([live demo](http://plnkr.co/edit/6w8XA8YTkDRcPYpdB9dk?p=preview))
*
* ```typescript
* import {RequestOptions, Request, RequestMethod} from '@angular/http';
*
* var options = new RequestOptions({
* method: RequestMethod.Post
* });
* var req = new Request(options.merge({
* url: 'https://google.com'
* }));
* console.log('req.method:', RequestMethod[req.method]); // Post
* console.log('options.url:', options.url); // null
* console.log('req.url:', req.url); // https://google.com
* ```
*/
merge(options?: RequestOptionsArgs): RequestOptions {
return new RequestOptions({
method: options && options.method != null ? options.method : this.method,
headers: options && options.headers != null ? options.headers : new Headers(this.headers),
body: options && options.body != null ? options.body : this.body,
url: options && options.url != null ? options.url : this.url,
params: options && this._mergeSearchParams(options.params || options.search),
withCredentials: options && options.withCredentials != null ? options.withCredentials :
this.withCredentials,
responseType: options && options.responseType != null ? options.responseType :
this.responseType
});
}
private _mergeSearchParams(params: string|URLSearchParams|
{[key: string]: any | any[]}): URLSearchParams {
if (!params) return this.params;
if (params instanceof URLSearchParams) {
return params.clone();
}
if (typeof params === 'string') {
return new URLSearchParams(params);
}
return this._parseParams(params);
}
private _parseParams(objParams: {[key: string]: any | any[]} = {}): URLSearchParams {
const params = new URLSearchParams();
Object.keys(objParams).forEach((key: string) => {
const value: any|any[] = objParams[key];
if (Array.isArray(value)) {
value.forEach((item: any) => this._appendParam(key, item, params));
} else {
this._appendParam(key, value, params);
}
});
return params;
}
private _appendParam(key: string, value: any, params: URLSearchParams): void {
if (typeof value !== 'string') {
value = JSON.stringify(value);
}
params.append(key, value);
}
}
/**
* Subclass of {@link RequestOptions}, with default values.
*
* Default values:
* * method: {@link RequestMethod RequestMethod.Get}
* * headers: empty {@link Headers} object
*
* This class could be extended and bound to the {@link RequestOptions} class
* when configuring an {@link Injector}, in order to override the default options
* used by {@link Http} to create and send {@link Request Requests}.
*
* ### Example ([live demo](http://plnkr.co/edit/LEKVSx?p=preview))
*
* ```typescript
* import {provide} from '@angular/core';
* import {bootstrap} from '@angular/platform-browser/browser';
* import {HTTP_PROVIDERS, Http, BaseRequestOptions, RequestOptions} from '@angular/http';
* import {App} from './myapp';
*
* class MyOptions extends BaseRequestOptions {
* search: string = 'coreTeam=true';
* }
*
* bootstrap(App, [HTTP_PROVIDERS, {provide: RequestOptions, useClass: MyOptions}]);
* ```
*
* The options could also be extended when manually creating a {@link Request}
* object.
*
* ### Example ([live demo](http://plnkr.co/edit/oyBoEvNtDhOSfi9YxaVb?p=preview))
*
* ```
* import {BaseRequestOptions, Request, RequestMethod} from '@angular/http';
*
* var options = new BaseRequestOptions();
* var req = new Request(options.merge({
* method: RequestMethod.Post,
* url: 'https://google.com'
* }));
* console.log('req.method:', RequestMethod[req.method]); // Post
* console.log('options.url:', options.url); // null
* console.log('req.url:', req.url); // https://google.com
* ```
*
* @experimental
*/
@Injectable()
export class BaseRequestOptions extends RequestOptions {
constructor() { super({method: RequestMethod.Get, headers: new Headers()}); }
}

View File

@ -0,0 +1,165 @@
/**
* @license
* Copyright Google Inc. 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.io/license
*/
import {Injectable} from '@angular/core';
import {ResponseType} from './enums';
import {Headers} from './headers';
import {ResponseOptionsArgs} from './interfaces';
/**
* Creates a response options object to be optionally provided when instantiating a
* {@link Response}.
*
* This class is based on the `ResponseInit` description in the [Fetch
* Spec](https://fetch.spec.whatwg.org/#responseinit).
*
* All values are null by default. Typical defaults can be found in the
* {@link BaseResponseOptions} class, which sub-classes `ResponseOptions`.
*
* This class may be used in tests to build {@link Response Responses} for
* mock responses (see {@link MockBackend}).
*
* ### Example ([live demo](http://plnkr.co/edit/P9Jkk8e8cz6NVzbcxEsD?p=preview))
*
* ```typescript
* import {ResponseOptions, Response} from '@angular/http';
*
* var options = new ResponseOptions({
* body: '{"name":"Jeff"}'
* });
* var res = new Response(options);
*
* console.log('res.json():', res.json()); // Object {name: "Jeff"}
* ```
*
* @experimental
*/
export class ResponseOptions {
// TODO: FormData | Blob
/**
* String, Object, ArrayBuffer or Blob representing the body of the {@link Response}.
*/
body: string|Object|ArrayBuffer|Blob;
/**
* Http {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html status code}
* associated with the response.
*/
status: number;
/**
* Response {@link Headers headers}
*/
headers: Headers;
/**
* @internal
*/
statusText: string;
/**
* @internal
*/
type: ResponseType;
url: string;
constructor({body, status, headers, statusText, type, url}: ResponseOptionsArgs = {}) {
this.body = body != null ? body : null;
this.status = status != null ? status : null;
this.headers = headers != null ? headers : null;
this.statusText = statusText != null ? statusText : null;
this.type = type != null ? type : null;
this.url = url != null ? url : null;
}
/**
* Creates a copy of the `ResponseOptions` instance, using the optional input as values to
* override
* existing values. This method will not change the values of the instance on which it is being
* called.
*
* This may be useful when sharing a base `ResponseOptions` object inside tests,
* where certain properties may change from test to test.
*
* ### Example ([live demo](http://plnkr.co/edit/1lXquqFfgduTFBWjNoRE?p=preview))
*
* ```typescript
* import {ResponseOptions, Response} from '@angular/http';
*
* var options = new ResponseOptions({
* body: {name: 'Jeff'}
* });
* var res = new Response(options.merge({
* url: 'https://google.com'
* }));
* console.log('options.url:', options.url); // null
* console.log('res.json():', res.json()); // Object {name: "Jeff"}
* console.log('res.url:', res.url); // https://google.com
* ```
*/
merge(options?: ResponseOptionsArgs): ResponseOptions {
return new ResponseOptions({
body: options && options.body != null ? options.body : this.body,
status: options && options.status != null ? options.status : this.status,
headers: options && options.headers != null ? options.headers : this.headers,
statusText: options && options.statusText != null ? options.statusText : this.statusText,
type: options && options.type != null ? options.type : this.type,
url: options && options.url != null ? options.url : this.url,
});
}
}
/**
* Subclass of {@link ResponseOptions}, with default values.
*
* Default values:
* * status: 200
* * headers: empty {@link Headers} object
*
* This class could be extended and bound to the {@link ResponseOptions} class
* when configuring an {@link Injector}, in order to override the default options
* used by {@link Http} to create {@link Response Responses}.
*
* ### Example ([live demo](http://plnkr.co/edit/qv8DLT?p=preview))
*
* ```typescript
* import {provide} from '@angular/core';
* import {bootstrap} from '@angular/platform-browser/browser';
* import {HTTP_PROVIDERS, Headers, Http, BaseResponseOptions, ResponseOptions} from
* '@angular/http';
* import {App} from './myapp';
*
* class MyOptions extends BaseResponseOptions {
* headers:Headers = new Headers({network: 'github'});
* }
*
* bootstrap(App, [HTTP_PROVIDERS, {provide: ResponseOptions, useClass: MyOptions}]);
* ```
*
* The options could also be extended when manually creating a {@link Response}
* object.
*
* ### Example ([live demo](http://plnkr.co/edit/VngosOWiaExEtbstDoix?p=preview))
*
* ```
* import {BaseResponseOptions, Response} from '@angular/http';
*
* var options = new BaseResponseOptions();
* var res = new Response(options.merge({
* body: 'Angular',
* headers: new Headers({framework: 'angular'})
* }));
* console.log('res.headers.get("framework"):', res.headers.get('framework')); // angular
* console.log('res.text():', res.text()); // Angular;
* ```
*
* @experimental
*/
@Injectable()
export class BaseResponseOptions extends ResponseOptions {
constructor() {
super({status: 200, statusText: 'Ok', type: ResponseType.Default, headers: new Headers()});
}
}

86
packages/http/src/body.ts Normal file
View File

@ -0,0 +1,86 @@
/**
* @license
* Copyright Google Inc. 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.io/license
*/
import {stringToArrayBuffer} from './http_utils';
import {URLSearchParams} from './url_search_params';
/**
* HTTP request body used by both {@link Request} and {@link Response}
* https://fetch.spec.whatwg.org/#body
*/
export abstract class Body {
/**
* @internal
*/
protected _body: any;
/**
* Attempts to return body as parsed `JSON` object, or raises an exception.
*/
json(): any {
if (typeof this._body === 'string') {
return JSON.parse(<string>this._body);
}
if (this._body instanceof ArrayBuffer) {
return JSON.parse(this.text());
}
return this._body;
}
/**
* Returns the body as a string, presuming `toString()` can be called on the response body.
*/
text(): string {
if (this._body instanceof URLSearchParams) {
return this._body.toString();
}
if (this._body instanceof ArrayBuffer) {
return String.fromCharCode.apply(null, new Uint16Array(<ArrayBuffer>this._body));
}
if (this._body == null) {
return '';
}
if (typeof this._body === 'object') {
return JSON.stringify(this._body, null, 2);
}
return this._body.toString();
}
/**
* Return the body as an ArrayBuffer
*/
arrayBuffer(): ArrayBuffer {
if (this._body instanceof ArrayBuffer) {
return <ArrayBuffer>this._body;
}
return stringToArrayBuffer(this.text());
}
/**
* Returns the request's body as a Blob, assuming that body exists.
*/
blob(): Blob {
if (this._body instanceof Blob) {
return <Blob>this._body;
}
if (this._body instanceof ArrayBuffer) {
return new Blob([this._body]);
}
throw new Error('The request body isn\'t either a blob or an array buffer');
}
}

View File

@ -0,0 +1,74 @@
/**
* @license
* Copyright Google Inc. 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.io/license
*/
/**
* Supported http methods.
* @experimental
*/
export enum RequestMethod {
Get,
Post,
Put,
Delete,
Options,
Head,
Patch
}
/**
* All possible states in which a connection can be, based on
* [States](http://www.w3.org/TR/XMLHttpRequest/#states) from the `XMLHttpRequest` spec, but with an
* additional "CANCELLED" state.
* @experimental
*/
export enum ReadyState {
Unsent,
Open,
HeadersReceived,
Loading,
Done,
Cancelled
}
/**
* Acceptable response types to be associated with a {@link Response}, based on
* [ResponseType](https://fetch.spec.whatwg.org/#responsetype) from the Fetch spec.
* @experimental
*/
export enum ResponseType {
Basic,
Cors,
Default,
Error,
Opaque
}
/**
* Supported content type to be automatically associated with a {@link Request}.
* @experimental
*/
export enum ContentType {
NONE,
JSON,
FORM,
FORM_DATA,
TEXT,
BLOB,
ARRAY_BUFFER
}
/**
* Define which buffer to use to store the response
* @experimental
*/
export enum ResponseContentType {
Text,
Json,
ArrayBuffer,
Blob
}

View File

@ -0,0 +1,185 @@
/**
* @license
* Copyright Google Inc. 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.io/license
*/
/**
* Polyfill for [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers/Headers), as
* specified in the [Fetch Spec](https://fetch.spec.whatwg.org/#headers-class).
*
* The only known difference between this `Headers` implementation and the spec is the
* lack of an `entries` method.
*
* ### Example
*
* ```
* import {Headers} from '@angular/http';
*
* var firstHeaders = new Headers();
* firstHeaders.append('Content-Type', 'image/jpeg');
* console.log(firstHeaders.get('Content-Type')) //'image/jpeg'
*
* // Create headers from Plain Old JavaScript Object
* var secondHeaders = new Headers({
* 'X-My-Custom-Header': 'Angular'
* });
* console.log(secondHeaders.get('X-My-Custom-Header')); //'Angular'
*
* var thirdHeaders = new Headers(secondHeaders);
* console.log(thirdHeaders.get('X-My-Custom-Header')); //'Angular'
* ```
*
* @experimental
*/
export class Headers {
/** @internal header names are lower case */
_headers: Map<string, string[]> = new Map();
/** @internal map lower case names to actual names */
_normalizedNames: Map<string, string> = new Map();
// TODO(vicb): any -> string|string[]
constructor(headers?: Headers|{[name: string]: any}) {
if (!headers) {
return;
}
if (headers instanceof Headers) {
headers.forEach((values: string[], name: string) => {
values.forEach(value => this.append(name, value));
});
return;
}
Object.keys(headers).forEach((name: string) => {
const values: string[] = Array.isArray(headers[name]) ? headers[name] : [headers[name]];
this.delete(name);
values.forEach(value => this.append(name, value));
});
}
/**
* Returns a new Headers instance from the given DOMString of Response Headers
*/
static fromResponseHeaderString(headersString: string): Headers {
const headers = new Headers();
headersString.split('\n').forEach(line => {
const index = line.indexOf(':');
if (index > 0) {
const name = line.slice(0, index);
const value = line.slice(index + 1).trim();
headers.set(name, value);
}
});
return headers;
}
/**
* Appends a header to existing list of header values for a given header name.
*/
append(name: string, value: string): void {
const values = this.getAll(name);
if (values === null) {
this.set(name, value);
} else {
values.push(value);
}
}
/**
* Deletes all header values for the given name.
*/
delete (name: string): void {
const lcName = name.toLowerCase();
this._normalizedNames.delete(lcName);
this._headers.delete(lcName);
}
forEach(fn: (values: string[], name: string, headers: Map<string, string[]>) => void): void {
this._headers.forEach(
(values, lcName) => fn(values, this._normalizedNames.get(lcName), this._headers));
}
/**
* Returns first header that matches given name.
*/
get(name: string): string {
const values = this.getAll(name);
if (values === null) {
return null;
}
return values.length > 0 ? values[0] : null;
}
/**
* Checks for existence of header by given name.
*/
has(name: string): boolean { return this._headers.has(name.toLowerCase()); }
/**
* Returns the names of the headers
*/
keys(): string[] { return Array.from(this._normalizedNames.values()); }
/**
* Sets or overrides header value for given name.
*/
set(name: string, value: string|string[]): void {
if (Array.isArray(value)) {
if (value.length) {
this._headers.set(name.toLowerCase(), [value.join(',')]);
}
} else {
this._headers.set(name.toLowerCase(), [value]);
}
this.mayBeSetNormalizedName(name);
}
/**
* Returns values of all headers.
*/
values(): string[][] { return Array.from(this._headers.values()); }
/**
* Returns string of all headers.
*/
// TODO(vicb): returns {[name: string]: string[]}
toJSON(): {[name: string]: any} {
const serialized: {[name: string]: string[]} = {};
this._headers.forEach((values: string[], name: string) => {
const split: string[] = [];
values.forEach(v => split.push(...v.split(',')));
serialized[this._normalizedNames.get(name)] = split;
});
return serialized;
}
/**
* Returns list of header values for a given name.
*/
getAll(name: string): string[] {
return this.has(name) ? this._headers.get(name.toLowerCase()) : null;
}
/**
* This method is not implemented.
*/
entries() { throw new Error('"entries" method is not implemented on Headers class'); }
private mayBeSetNormalizedName(name: string): void {
const lcName = name.toLowerCase();
if (!this._normalizedNames.has(lcName)) {
this._normalizedNames.set(lcName, name);
}
}
}

226
packages/http/src/http.ts Normal file
View File

@ -0,0 +1,226 @@
/**
* @license
* Copyright Google Inc. 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.io/license
*/
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {BaseRequestOptions, RequestOptions} from './base_request_options';
import {RequestMethod} from './enums';
import {ConnectionBackend, RequestOptionsArgs} from './interfaces';
import {Request} from './static_request';
import {Response} from './static_response';
function httpRequest(backend: ConnectionBackend, request: Request): Observable<Response> {
return backend.createConnection(request).response;
}
function mergeOptions(
defaultOpts: BaseRequestOptions, providedOpts: RequestOptionsArgs, method: RequestMethod,
url: string): RequestOptions {
const newOptions = defaultOpts;
if (providedOpts) {
// Hack so Dart can used named parameters
return newOptions.merge(new RequestOptions({
method: providedOpts.method || method,
url: providedOpts.url || url,
search: providedOpts.search,
params: providedOpts.params,
headers: providedOpts.headers,
body: providedOpts.body,
withCredentials: providedOpts.withCredentials,
responseType: providedOpts.responseType
}));
}
return newOptions.merge(new RequestOptions({method, url}));
}
/**
* Performs http requests using `XMLHttpRequest` as the default backend.
*
* `Http` is available as an injectable class, with methods to perform http requests. Calling
* `request` returns an `Observable` which will emit a single {@link Response} when a
* response is received.
*
* ### Example
*
* ```typescript
* import {Http, HTTP_PROVIDERS} from '@angular/http';
* import 'rxjs/add/operator/map'
* @Component({
* selector: 'http-app',
* viewProviders: [HTTP_PROVIDERS],
* templateUrl: 'people.html'
* })
* class PeopleComponent {
* constructor(http: Http) {
* http.get('people.json')
* // Call map on the response observable to get the parsed people object
* .map(res => res.json())
* // Subscribe to the observable to get the parsed people object and attach it to the
* // component
* .subscribe(people => this.people = people);
* }
* }
* ```
*
*
* ### Example
*
* ```
* http.get('people.json').subscribe((res:Response) => this.people = res.json());
* ```
*
* The default construct used to perform requests, `XMLHttpRequest`, is abstracted as a "Backend" (
* {@link XHRBackend} in this case), which could be mocked with dependency injection by replacing
* the {@link XHRBackend} provider, as in the following example:
*
* ### Example
*
* ```typescript
* import {BaseRequestOptions, Http} from '@angular/http';
* import {MockBackend} from '@angular/http/testing';
* var injector = Injector.resolveAndCreate([
* BaseRequestOptions,
* MockBackend,
* {provide: Http, useFactory:
* function(backend, defaultOptions) {
* return new Http(backend, defaultOptions);
* },
* deps: [MockBackend, BaseRequestOptions]}
* ]);
* var http = injector.get(Http);
* http.get('request-from-mock-backend.json').subscribe((res:Response) => doSomething(res));
* ```
*
* @experimental
*/
@Injectable()
export class Http {
constructor(protected _backend: ConnectionBackend, protected _defaultOptions: RequestOptions) {}
/**
* Performs any type of http request. First argument is required, and can either be a url or
* a {@link Request} instance. If the first argument is a url, an optional {@link RequestOptions}
* object can be provided as the 2nd argument. The options object will be merged with the values
* of {@link BaseRequestOptions} before performing the request.
*/
request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
let responseObservable: any;
if (typeof url === 'string') {
responseObservable = httpRequest(
this._backend,
new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Get, <string>url)));
} else if (url instanceof Request) {
responseObservable = httpRequest(this._backend, url);
} else {
throw new Error('First argument must be a url string or Request instance.');
}
return responseObservable;
}
/**
* Performs a request with `get` http method.
*/
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
return this.request(
new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Get, url)));
}
/**
* Performs a request with `post` http method.
*/
post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
return this.request(new Request(mergeOptions(
this._defaultOptions.merge(new RequestOptions({body: body})), options, RequestMethod.Post,
url)));
}
/**
* Performs a request with `put` http method.
*/
put(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
return this.request(new Request(mergeOptions(
this._defaultOptions.merge(new RequestOptions({body: body})), options, RequestMethod.Put,
url)));
}
/**
* Performs a request with `delete` http method.
*/
delete (url: string, options?: RequestOptionsArgs): Observable<Response> {
return this.request(
new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Delete, url)));
}
/**
* Performs a request with `patch` http method.
*/
patch(url: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
return this.request(new Request(mergeOptions(
this._defaultOptions.merge(new RequestOptions({body: body})), options, RequestMethod.Patch,
url)));
}
/**
* Performs a request with `head` http method.
*/
head(url: string, options?: RequestOptionsArgs): Observable<Response> {
return this.request(
new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Head, url)));
}
/**
* Performs a request with `options` http method.
*/
options(url: string, options?: RequestOptionsArgs): Observable<Response> {
return this.request(
new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Options, url)));
}
}
/**
* @experimental
*/
@Injectable()
export class Jsonp extends Http {
constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
super(backend, defaultOptions);
}
/**
* Performs any type of http request. First argument is required, and can either be a url or
* a {@link Request} instance. If the first argument is a url, an optional {@link RequestOptions}
* object can be provided as the 2nd argument. The options object will be merged with the values
* of {@link BaseRequestOptions} before performing the request.
*
* @security Regular XHR is the safest alternative to JSONP for most applications, and is
* supported by all current browsers. Because JSONP creates a `<script>` element with
* contents retrieved from a remote source, attacker-controlled data introduced by an untrusted
* source could expose your application to XSS risks. Data exposed by JSONP may also be
* readable by malicious third-party websites. In addition, JSONP introduces potential risk for
* future security issues (e.g. content sniffing). For more detail, see the
* [Security Guide](http://g.co/ng/security).
*/
request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
let responseObservable: any;
if (typeof url === 'string') {
url =
new Request(mergeOptions(this._defaultOptions, options, RequestMethod.Get, <string>url));
}
if (url instanceof Request) {
if (url.method !== RequestMethod.Get) {
throw new Error('JSONP requests must use GET request method.');
}
responseObservable = httpRequest(this._backend, url);
} else {
throw new Error('First argument must be a url string or Request instance.');
}
return responseObservable;
}
}

View File

@ -0,0 +1,77 @@
/**
* @license
* Copyright Google Inc. 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.io/license
*/
/**
* @module
* @description
* The http module provides services to perform http requests. To get started, see the {@link Http}
* class.
*/
import {NgModule} from '@angular/core';
import {BrowserJsonp} from './backends/browser_jsonp';
import {BrowserXhr} from './backends/browser_xhr';
import {JSONPBackend, JSONPBackend_} from './backends/jsonp_backend';
import {CookieXSRFStrategy, XHRBackend} from './backends/xhr_backend';
import {BaseRequestOptions, RequestOptions} from './base_request_options';
import {BaseResponseOptions, ResponseOptions} from './base_response_options';
import {Http, Jsonp} from './http';
import {XSRFStrategy} from './interfaces';
export function _createDefaultCookieXSRFStrategy() {
return new CookieXSRFStrategy();
}
export function httpFactory(xhrBackend: XHRBackend, requestOptions: RequestOptions): Http {
return new Http(xhrBackend, requestOptions);
}
export function jsonpFactory(jsonpBackend: JSONPBackend, requestOptions: RequestOptions): Jsonp {
return new Jsonp(jsonpBackend, requestOptions);
}
/**
* The module that includes http's providers
*
* @experimental
*/
@NgModule({
providers: [
// TODO(pascal): use factory type annotations once supported in DI
// issue: https://github.com/angular/angular/issues/3183
{provide: Http, useFactory: httpFactory, deps: [XHRBackend, RequestOptions]},
BrowserXhr,
{provide: RequestOptions, useClass: BaseRequestOptions},
{provide: ResponseOptions, useClass: BaseResponseOptions},
XHRBackend,
{provide: XSRFStrategy, useFactory: _createDefaultCookieXSRFStrategy},
],
})
export class HttpModule {
}
/**
* The module that includes jsonp's providers
*
* @experimental
*/
@NgModule({
providers: [
// TODO(pascal): use factory type annotations once supported in DI
// issue: https://github.com/angular/angular/issues/3183
{provide: Jsonp, useFactory: jsonpFactory, deps: [JSONPBackend, RequestOptions]},
BrowserJsonp,
{provide: RequestOptions, useClass: BaseRequestOptions},
{provide: ResponseOptions, useClass: BaseResponseOptions},
{provide: JSONPBackend, useClass: JSONPBackend_},
],
})
export class JsonpModule {
}

View File

@ -0,0 +1,51 @@
/**
* @license
* Copyright Google Inc. 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.io/license
*/
import {RequestMethod} from './enums';
export function normalizeMethodName(method: string | RequestMethod): RequestMethod {
if (typeof method !== 'string') return method;
switch (method.toUpperCase()) {
case 'GET':
return RequestMethod.Get;
case 'POST':
return RequestMethod.Post;
case 'PUT':
return RequestMethod.Put;
case 'DELETE':
return RequestMethod.Delete;
case 'OPTIONS':
return RequestMethod.Options;
case 'HEAD':
return RequestMethod.Head;
case 'PATCH':
return RequestMethod.Patch;
}
throw new Error(`Invalid request method. The method "${method}" is not supported.`);
}
export const isSuccess = (status: number): boolean => (status >= 200 && status < 300);
export function getResponseURL(xhr: any): string {
if ('responseURL' in xhr) {
return xhr.responseURL;
}
if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
return xhr.getResponseHeader('X-Request-URL');
}
return;
}
export function stringToArrayBuffer(input: String): ArrayBuffer {
const view = new Uint16Array(input.length);
for (let i = 0, strLen = input.length; i < strLen; i++) {
view[i] = input.charCodeAt(i);
}
return view.buffer;
}

View File

@ -0,0 +1,22 @@
/**
* @license
* Copyright Google Inc. 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.io/license
*/
export {BrowserXhr} from './backends/browser_xhr';
export {JSONPBackend, JSONPConnection} from './backends/jsonp_backend';
export {CookieXSRFStrategy, XHRBackend, XHRConnection} from './backends/xhr_backend';
export {BaseRequestOptions, RequestOptions} from './base_request_options';
export {BaseResponseOptions, ResponseOptions} from './base_response_options';
export {ReadyState, RequestMethod, ResponseContentType, ResponseType} from './enums';
export {Headers} from './headers';
export {Http, Jsonp} from './http';
export {HttpModule, JsonpModule} from './http_module';
export {Connection, ConnectionBackend, RequestOptionsArgs, ResponseOptionsArgs, XSRFStrategy} from './interfaces';
export {Request} from './static_request';
export {Response} from './static_response';
export {QueryEncoder, URLSearchParams} from './url_search_params';
export {VERSION} from './version';

View File

@ -0,0 +1,76 @@
/**
* @license
* Copyright Google Inc. 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.io/license
*/
import {ReadyState, RequestMethod, ResponseContentType, ResponseType} from './enums';
import {Headers} from './headers';
import {Request} from './static_request';
import {URLSearchParams} from './url_search_params';
/**
* Abstract class from which real backends are derived.
*
* The primary purpose of a `ConnectionBackend` is to create new connections to fulfill a given
* {@link Request}.
*
* @experimental
*/
export abstract class ConnectionBackend { abstract createConnection(request: any): Connection; }
/**
* Abstract class from which real connections are derived.
*
* @experimental
*/
export abstract class Connection {
readyState: ReadyState;
request: Request;
response: any; // TODO: generic of <Response>;
}
/**
* An XSRFStrategy configures XSRF protection (e.g. via headers) on an HTTP request.
*
* @experimental
*/
export abstract class XSRFStrategy { abstract configureRequest(req: Request): void; }
/**
* Interface for options to construct a RequestOptions, based on
* [RequestInit](https://fetch.spec.whatwg.org/#requestinit) from the Fetch spec.
*
* @experimental
*/
export interface RequestOptionsArgs {
url?: string;
method?: string|RequestMethod;
/** @deprecated from 4.0.0. Use params instead. */
search?: string|URLSearchParams|{[key: string]: any | any[]};
params?: string|URLSearchParams|{[key: string]: any | any[]};
headers?: Headers;
body?: any;
withCredentials?: boolean;
responseType?: ResponseContentType;
}
/**
* Required structure when constructing new Request();
*/
export interface RequestArgs extends RequestOptionsArgs { url: string; }
/**
* Interface for options to construct a Response, based on
* [ResponseInit](https://fetch.spec.whatwg.org/#responseinit) from the Fetch spec.
*
* @experimental
*/
export type ResponseOptionsArgs = {
body?: string | Object | FormData | ArrayBuffer | Blob; status?: number; statusText?: string;
headers?: Headers;
type?: ResponseType;
url?: string;
};

View File

@ -0,0 +1,170 @@
/**
* @license
* Copyright Google Inc. 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.io/license
*/
import {Body} from './body';
import {ContentType, RequestMethod, ResponseContentType} from './enums';
import {Headers} from './headers';
import {normalizeMethodName} from './http_utils';
import {RequestArgs} from './interfaces';
import {URLSearchParams} from './url_search_params';
// TODO(jeffbcross): properly implement body accessors
/**
* Creates `Request` instances from provided values.
*
* The Request's interface is inspired by the Request constructor defined in the [Fetch
* Spec](https://fetch.spec.whatwg.org/#request-class),
* but is considered a static value whose body can be accessed many times. There are other
* differences in the implementation, but this is the most significant.
*
* `Request` instances are typically created by higher-level classes, like {@link Http} and
* {@link Jsonp}, but it may occasionally be useful to explicitly create `Request` instances.
* One such example is when creating services that wrap higher-level services, like {@link Http},
* where it may be useful to generate a `Request` with arbitrary headers and search params.
*
* ```typescript
* import {Injectable, Injector} from '@angular/core';
* import {HTTP_PROVIDERS, Http, Request, RequestMethod} from '@angular/http';
*
* @Injectable()
* class AutoAuthenticator {
* constructor(public http:Http) {}
* request(url:string) {
* return this.http.request(new Request({
* method: RequestMethod.Get,
* url: url,
* search: 'password=123'
* }));
* }
* }
*
* var injector = Injector.resolveAndCreate([HTTP_PROVIDERS, AutoAuthenticator]);
* var authenticator = injector.get(AutoAuthenticator);
* authenticator.request('people.json').subscribe(res => {
* //URL should have included '?password=123'
* console.log('people', res.json());
* });
* ```
*
* @experimental
*/
export class Request extends Body {
/**
* Http method with which to perform the request.
*/
method: RequestMethod;
/**
* {@link Headers} instance
*/
headers: Headers;
/** Url of the remote resource */
url: string;
/** Type of the request body **/
private contentType: ContentType;
/** Enable use credentials */
withCredentials: boolean;
/** Buffer to store the response */
responseType: ResponseContentType;
constructor(requestOptions: RequestArgs) {
super();
// TODO: assert that url is present
const url = requestOptions.url;
this.url = requestOptions.url;
if (requestOptions.params) {
const params = requestOptions.params.toString();
if (params.length > 0) {
let prefix = '?';
if (this.url.indexOf('?') != -1) {
prefix = (this.url[this.url.length - 1] == '&') ? '' : '&';
}
// TODO: just delete search-query-looking string in url?
this.url = url + prefix + params;
}
}
this._body = requestOptions.body;
this.method = normalizeMethodName(requestOptions.method);
// TODO(jeffbcross): implement behavior
// Defaults to 'omit', consistent with browser
this.headers = new Headers(requestOptions.headers);
this.contentType = this.detectContentType();
this.withCredentials = requestOptions.withCredentials;
this.responseType = requestOptions.responseType;
}
/**
* Returns the content type enum based on header options.
*/
detectContentType(): ContentType {
switch (this.headers.get('content-type')) {
case 'application/json':
return ContentType.JSON;
case 'application/x-www-form-urlencoded':
return ContentType.FORM;
case 'multipart/form-data':
return ContentType.FORM_DATA;
case 'text/plain':
case 'text/html':
return ContentType.TEXT;
case 'application/octet-stream':
return this._body instanceof ArrayBuffer ? ContentType.ARRAY_BUFFER : ContentType.BLOB;
default:
return this.detectContentTypeFromBody();
}
}
/**
* Returns the content type of request's body based on its type.
*/
detectContentTypeFromBody(): ContentType {
if (this._body == null) {
return ContentType.NONE;
} else if (this._body instanceof URLSearchParams) {
return ContentType.FORM;
} else if (this._body instanceof FormData) {
return ContentType.FORM_DATA;
} else if (this._body instanceof Blob) {
return ContentType.BLOB;
} else if (this._body instanceof ArrayBuffer) {
return ContentType.ARRAY_BUFFER;
} else if (this._body && typeof this._body === 'object') {
return ContentType.JSON;
} else {
return ContentType.TEXT;
}
}
/**
* Returns the request's body according to its type. If body is undefined, return
* null.
*/
getBody(): any {
switch (this.contentType) {
case ContentType.JSON:
return this.text();
case ContentType.FORM:
return this.text();
case ContentType.FORM_DATA:
return this._body;
case ContentType.TEXT:
return this.text();
case ContentType.BLOB:
return this.blob();
case ContentType.ARRAY_BUFFER:
return this.arrayBuffer();
default:
return null;
}
}
}
const noop = function() {};
const w = typeof window == 'object' ? window : noop;
const FormData = (w as any /** TODO #9100 */)['FormData'] || noop;
const Blob = (w as any /** TODO #9100 */)['Blob'] || noop;
export const ArrayBuffer = (w as any /** TODO #9100 */)['ArrayBuffer'] || noop;

View File

@ -0,0 +1,100 @@
/**
* @license
* Copyright Google Inc. 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.io/license
*/
import {ResponseOptions} from './base_response_options';
import {Body} from './body';
import {ResponseType} from './enums';
import {Headers} from './headers';
/**
* Creates `Response` instances from provided values.
*
* Though this object isn't
* usually instantiated by end-users, it is the primary object interacted with when it comes time to
* add data to a view.
*
* ### Example
*
* ```
* http.request('my-friends.txt').subscribe(response => this.friends = response.text());
* ```
*
* The Response's interface is inspired by the Response constructor defined in the [Fetch
* Spec](https://fetch.spec.whatwg.org/#response-class), but is considered a static value whose body
* can be accessed many times. There are other differences in the implementation, but this is the
* most significant.
*
* @experimental
*/
export class Response extends Body {
/**
* One of "basic", "cors", "default", "error", or "opaque".
*
* Defaults to "default".
*/
type: ResponseType;
/**
* True if the response's status is within 200-299
*/
ok: boolean;
/**
* URL of response.
*
* Defaults to empty string.
*/
url: string;
/**
* Status code returned by server.
*
* Defaults to 200.
*/
status: number;
/**
* Text representing the corresponding reason phrase to the `status`, as defined in [ietf rfc 2616
* section 6.1.1](https://tools.ietf.org/html/rfc2616#section-6.1.1)
*
* Defaults to "OK"
*/
statusText: string;
/**
* Non-standard property
*
* Denotes how many of the response body's bytes have been loaded, for example if the response is
* the result of a progress event.
*/
bytesLoaded: number;
/**
* Non-standard property
*
* Denotes how many bytes are expected in the final response body.
*/
totalBytes: number;
/**
* Headers object based on the `Headers` class in the [Fetch
* Spec](https://fetch.spec.whatwg.org/#headers-class).
*/
headers: Headers;
constructor(responseOptions: ResponseOptions) {
super();
this._body = responseOptions.body;
this.status = responseOptions.status;
this.ok = (this.status >= 200 && this.status <= 299);
this.statusText = responseOptions.statusText;
this.headers = responseOptions.headers;
this.type = responseOptions.type;
this.url = responseOptions.url;
}
toString(): string {
return `Response with status: ${this.status} ${this.statusText} for URL: ${this.url}`;
}
}

View File

@ -0,0 +1,184 @@
/**
* @license
* Copyright Google Inc. 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.io/license
*/
function paramParser(rawParams: string = ''): Map<string, string[]> {
const map = new Map<string, string[]>();
if (rawParams.length > 0) {
const params: string[] = rawParams.split('&');
params.forEach((param: string) => {
const eqIdx = param.indexOf('=');
const [key, val]: string[] =
eqIdx == -1 ? [param, ''] : [param.slice(0, eqIdx), param.slice(eqIdx + 1)];
const list = map.get(key) || [];
list.push(val);
map.set(key, list);
});
}
return map;
}
/**
* @experimental
**/
export class QueryEncoder {
encodeKey(k: string): string { return standardEncoding(k); }
encodeValue(v: string): string { return standardEncoding(v); }
}
function standardEncoding(v: string): string {
return encodeURIComponent(v)
.replace(/%40/gi, '@')
.replace(/%3A/gi, ':')
.replace(/%24/gi, '$')
.replace(/%2C/gi, ',')
.replace(/%3B/gi, ';')
.replace(/%2B/gi, '+')
.replace(/%3D/gi, '=')
.replace(/%3F/gi, '?')
.replace(/%2F/gi, '/');
}
/**
* Map-like representation of url search parameters, based on
* [URLSearchParams](https://url.spec.whatwg.org/#urlsearchparams) in the url living standard,
* with several extensions for merging URLSearchParams objects:
* - setAll()
* - appendAll()
* - replaceAll()
*
* This class accepts an optional second parameter of ${@link QueryEncoder},
* which is used to serialize parameters before making a request. By default,
* `QueryEncoder` encodes keys and values of parameters using `encodeURIComponent`,
* and then un-encodes certain characters that are allowed to be part of the query
* according to IETF RFC 3986: https://tools.ietf.org/html/rfc3986.
*
* These are the characters that are not encoded: `! $ \' ( ) * + , ; A 9 - . _ ~ ? /`
*
* If the set of allowed query characters is not acceptable for a particular backend,
* `QueryEncoder` can be subclassed and provided as the 2nd argument to URLSearchParams.
*
* ```
* import {URLSearchParams, QueryEncoder} from '@angular/http';
* class MyQueryEncoder extends QueryEncoder {
* encodeKey(k: string): string {
* return myEncodingFunction(k);
* }
*
* encodeValue(v: string): string {
* return myEncodingFunction(v);
* }
* }
*
* let params = new URLSearchParams('', new MyQueryEncoder());
* ```
* @experimental
*/
export class URLSearchParams {
paramsMap: Map<string, string[]>;
constructor(
public rawParams: string = '', private queryEncoder: QueryEncoder = new QueryEncoder()) {
this.paramsMap = paramParser(rawParams);
}
clone(): URLSearchParams {
const clone = new URLSearchParams('', this.queryEncoder);
clone.appendAll(this);
return clone;
}
has(param: string): boolean { return this.paramsMap.has(param); }
get(param: string): string {
const storedParam = this.paramsMap.get(param);
return Array.isArray(storedParam) ? storedParam[0] : null;
}
getAll(param: string): string[] { return this.paramsMap.get(param) || []; }
set(param: string, val: string) {
if (val === void 0 || val === null) {
this.delete(param);
return;
}
const list = this.paramsMap.get(param) || [];
list.length = 0;
list.push(val);
this.paramsMap.set(param, list);
}
// A merge operation
// For each name-values pair in `searchParams`, perform `set(name, values[0])`
//
// E.g: "a=[1,2,3], c=[8]" + "a=[4,5,6], b=[7]" = "a=[4], c=[8], b=[7]"
//
// TODO(@caitp): document this better
setAll(searchParams: URLSearchParams) {
searchParams.paramsMap.forEach((value, param) => {
const list = this.paramsMap.get(param) || [];
list.length = 0;
list.push(value[0]);
this.paramsMap.set(param, list);
});
}
append(param: string, val: string): void {
if (val === void 0 || val === null) return;
const list = this.paramsMap.get(param) || [];
list.push(val);
this.paramsMap.set(param, list);
}
// A merge operation
// For each name-values pair in `searchParams`, perform `append(name, value)`
// for each value in `values`.
//
// E.g: "a=[1,2], c=[8]" + "a=[3,4], b=[7]" = "a=[1,2,3,4], c=[8], b=[7]"
//
// TODO(@caitp): document this better
appendAll(searchParams: URLSearchParams) {
searchParams.paramsMap.forEach((value, param) => {
const list = this.paramsMap.get(param) || [];
for (let i = 0; i < value.length; ++i) {
list.push(value[i]);
}
this.paramsMap.set(param, list);
});
}
// A merge operation
// For each name-values pair in `searchParams`, perform `delete(name)`,
// followed by `set(name, values)`
//
// E.g: "a=[1,2,3], c=[8]" + "a=[4,5,6], b=[7]" = "a=[4,5,6], c=[8], b=[7]"
//
// TODO(@caitp): document this better
replaceAll(searchParams: URLSearchParams) {
searchParams.paramsMap.forEach((value, param) => {
const list = this.paramsMap.get(param) || [];
list.length = 0;
for (let i = 0; i < value.length; ++i) {
list.push(value[i]);
}
this.paramsMap.set(param, list);
});
}
toString(): string {
const paramsList: string[] = [];
this.paramsMap.forEach((values, k) => {
values.forEach(
v => paramsList.push(
this.queryEncoder.encodeKey(k) + '=' + this.queryEncoder.encodeValue(v)));
});
return paramsList.join('&');
}
delete (param: string): void { this.paramsMap.delete(param); }
}

View File

@ -0,0 +1,19 @@
/**
* @license
* Copyright Google Inc. 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.io/license
*/
/**
* @module
* @description
* Entry point for all public APIs of the common package.
*/
import {Version} from '@angular/core';
/**
* @stable
*/
export const VERSION = new Version('0.0.0-PLACEHOLDER');