-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
ajax.js
189 lines (171 loc) · 6.8 KB
/
ajax.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
// @flow
import window from './window';
import { extend } from './util';
import type { Callback } from '../types/callback';
import type { Cancelable } from '../types/cancelable';
/**
* The type of a resource.
* @private
* @readonly
* @enum {string}
*/
const ResourceType = {
Unknown: 'Unknown',
Style: 'Style',
Source: 'Source',
Tile: 'Tile',
Glyphs: 'Glyphs',
SpriteImage: 'SpriteImage',
SpriteJSON: 'SpriteJSON',
Image: 'Image'
};
export { ResourceType };
if (typeof Object.freeze == 'function') {
Object.freeze(ResourceType);
}
/**
* A `RequestParameters` object to be returned from Map.options.transformRequest callbacks.
* @typedef {Object} RequestParameters
* @property {string} url The URL to be requested.
* @property {Object} headers The headers to be sent with the request.
* @property {string} credentials `'same-origin'|'include'` Use 'include' to send cookies with cross-origin requests.
*/
export type RequestParameters = {
url: string,
headers?: Object,
method?: 'GET' | 'POST' | 'PUT',
credentials?: 'same-origin' | 'include',
collectResourceTiming?: boolean
};
class AJAXError extends Error {
status: number;
url: string;
constructor(message: string, status: number, url: string) {
super(message);
this.status = status;
this.url = url;
// work around for https://github.com/Rich-Harris/buble/issues/40
this.name = this.constructor.name;
this.message = message;
}
toString() {
return `${this.name}: ${this.message} (${this.status}): ${this.url}`;
}
}
function makeRequest(requestParameters: RequestParameters): XMLHttpRequest {
const xhr: XMLHttpRequest = new window.XMLHttpRequest();
xhr.open(requestParameters.method || 'GET', requestParameters.url, true);
for (const k in requestParameters.headers) {
xhr.setRequestHeader(k, requestParameters.headers[k]);
}
xhr.withCredentials = requestParameters.credentials === 'include';
return xhr;
}
export const getJSON = function(requestParameters: RequestParameters, callback: Callback<mixed>): Cancelable {
const xhr = makeRequest(requestParameters);
xhr.setRequestHeader('Accept', 'application/json');
xhr.onerror = function() {
callback(new Error(xhr.statusText));
};
xhr.onload = function() {
if (((xhr.status >= 200 && xhr.status < 300) || xhr.status === 0) && xhr.response) {
let data;
try {
data = JSON.parse(xhr.response);
} catch (err) {
return callback(err);
}
callback(null, data);
} else {
if (xhr.status === 401 && requestParameters.url.match(/mapbox.com/)) {
callback(new AJAXError(`${xhr.statusText}: you may have provided an invalid Mapbox access token. See https://www.mapbox.com/api-documentation/#access-tokens`, xhr.status, requestParameters.url));
} else {
callback(new AJAXError(xhr.statusText, xhr.status, requestParameters.url));
}
}
};
xhr.send();
return { cancel: () => xhr.abort() };
};
export const getArrayBuffer = function(requestParameters: RequestParameters, callback: Callback<{data: ArrayBuffer, cacheControl: ?string, expires: ?string}>): Cancelable {
const xhr = makeRequest(requestParameters);
xhr.responseType = 'arraybuffer';
xhr.onerror = function() {
callback(new Error(xhr.statusText));
};
xhr.onload = function() {
const response: ArrayBuffer = xhr.response;
if (response.byteLength === 0 && xhr.status === 200) {
return callback(new Error('http status 200 returned without content.'));
}
if (((xhr.status >= 200 && xhr.status < 300) || xhr.status === 0) && xhr.response) {
callback(null, {
data: response,
cacheControl: xhr.getResponseHeader('Cache-Control'),
expires: xhr.getResponseHeader('Expires')
});
} else {
callback(new AJAXError(xhr.statusText, xhr.status, requestParameters.url));
}
};
xhr.send();
return { cancel: () => xhr.abort() };
};
export const postData = function(requestParameters: RequestParameters, payload: string, callback: Callback<mixed>): Cancelable {
const xhr = makeRequest(extend(requestParameters, {method: 'POST'}));
xhr.onerror = function() {
callback(new Error(xhr.statusText));
};
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
callback(null, xhr.response);
} else {
callback(new AJAXError(xhr.statusText, xhr.status, requestParameters.url));
}
};
xhr.send(payload);
return { cancel: () => xhr.abort() };
};
function sameOrigin(url) {
const a: HTMLAnchorElement = window.document.createElement('a');
a.href = url;
return a.protocol === window.document.location.protocol && a.host === window.document.location.host;
}
const transparentPngUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=';
export const getImage = function(requestParameters: RequestParameters, callback: Callback<HTMLImageElement>): Cancelable {
// request the image with XHR to work around caching issues
// see https://github.com/mapbox/mapbox-gl-js/issues/1470
return getArrayBuffer(requestParameters, (err, imgData) => {
if (err) {
callback(err);
} else if (imgData) {
const img: HTMLImageElement = new window.Image();
const URL = window.URL || window.webkitURL;
img.onload = () => {
callback(null, img);
URL.revokeObjectURL(img.src);
};
img.onerror = () => callback(new Error('Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.'));
const blob: Blob = new window.Blob([new Uint8Array(imgData.data)], { type: 'image/png' });
(img: any).cacheControl = imgData.cacheControl;
(img: any).expires = imgData.expires;
img.src = imgData.data.byteLength ? URL.createObjectURL(blob) : transparentPngUrl;
}
});
};
export const getVideo = function(urls: Array<string>, callback: Callback<HTMLVideoElement>): Cancelable {
const video: HTMLVideoElement = window.document.createElement('video');
video.muted = true;
video.onloadstart = function() {
callback(null, video);
};
for (let i = 0; i < urls.length; i++) {
const s: HTMLSourceElement = window.document.createElement('source');
if (!sameOrigin(urls[i])) {
video.crossOrigin = 'Anonymous';
}
s.src = urls[i];
video.appendChild(s);
}
return { cancel: () => {} };
};