-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
ajax.js
388 lines (345 loc) · 15.3 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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
// @flow
import window from './window.js';
import {extend, warnOnce, isWorker} from './util.js';
import {isMapboxHTTPURL, hasCacheDefeatingSku} from './mapbox.js';
import config from './config.js';
import assert from 'assert';
import {cacheGet, cachePut} from './tile_request_cache.js';
import webpSupported from './webp_supported.js';
import type {Callback} from '../types/callback.js';
import type {Cancelable} from '../types/cancelable.js';
/**
* 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} method Request method `'GET' | 'POST' | 'PUT'`.
* @property {string} body Request body.
* @property {string} type Response body type to be returned `'string' | 'json' | 'arrayBuffer'`.
* @property {string} credentials `'same-origin'|'include'` Use 'include' to send cookies with cross-origin requests.
* @property {boolean} collectResourceTiming If true, Resource Timing API information will be collected for these transformed requests and returned in a resourceTiming property of relevant data events.
* @example
* // use transformRequest to modify requests that begin with `http://myHost`
* const map = new Map({
* container: 'map',
* style: 'mapbox://styles/mapbox/streets-v11',
* transformRequest: (url, resourceType) => {
* if (resourceType === 'Source' && url.indexOf('http://myHost') > -1) {
* return {
* url: url.replace('http', 'https'),
* headers: {'my-custom-header': true},
* credentials: 'include' // Include cookies for cross-origin requests
* };
* }
* }
* });
*
*/
export type RequestParameters = {
url: string,
headers?: Object,
method?: 'GET' | 'POST' | 'PUT',
body?: string,
type?: 'string' | 'json' | 'arrayBuffer',
credentials?: 'same-origin' | 'include',
collectResourceTiming?: boolean
};
export type ResponseCallback<T> = (error: ?Error, data: ?T, cacheControl: ?string, expires: ?string) => void;
class AJAXError extends Error {
status: number;
url: string;
constructor(message: string, status: number, url: string) {
if (status === 401 && isMapboxHTTPURL(url)) {
message += ': you may have provided an invalid Mapbox access token. See https://www.mapbox.com/api-documentation/#access-tokens-and-token-scopes';
}
super(message);
this.status = status;
this.url = url;
}
toString() {
return `${this.name}: ${this.message} (${this.status}): ${this.url}`;
}
}
// Ensure that we're sending the correct referrer from blob URL worker bundles.
// For files loaded from the local file system, `location.origin` will be set
// to the string(!) "null" (Firefox), or "file://" (Chrome, Safari, Edge, IE),
// and we will set an empty referrer. Otherwise, we're using the document's URL.
/* global self */
export const getReferrer: (() => string) = isWorker() ?
() => self.worker && self.worker.referrer :
() => (window.location.protocol === 'blob:' ? window.parent : window).location.href;
// Determines whether a URL is a file:// URL. This is obviously the case if it begins
// with file://. Relative URLs are also file:// URLs iff the original document was loaded
// via a file:// URL.
const isFileURL = url => /^file:/.test(url) || (/^file:/.test(getReferrer()) && !/^\w+:/.test(url));
function makeFetchRequest(requestParameters: RequestParameters, callback: ResponseCallback<any>): Cancelable {
const controller = new window.AbortController();
const request = new window.Request(requestParameters.url, {
method: requestParameters.method || 'GET',
body: requestParameters.body,
credentials: requestParameters.credentials,
headers: requestParameters.headers,
referrer: getReferrer(),
signal: controller.signal
});
let complete = false;
let aborted = false;
const cacheIgnoringSearch = hasCacheDefeatingSku(request.url);
if (requestParameters.type === 'json') {
request.headers.set('Accept', 'application/json');
}
const validateOrFetch = (err, cachedResponse, responseIsFresh) => {
if (aborted) return;
if (err) {
// Do fetch in case of cache error.
// HTTP pages in Edge trigger a security error that can be ignored.
if (err.message !== 'SecurityError') {
warnOnce(err);
}
}
if (cachedResponse && responseIsFresh) {
return finishRequest(cachedResponse);
}
if (cachedResponse) {
// We can't do revalidation with 'If-None-Match' because then the
// request doesn't have simple cors headers.
}
const requestTime = Date.now();
window.fetch(request).then(response => {
if (response.ok) {
const cacheableResponse = cacheIgnoringSearch ? response.clone() : null;
return finishRequest(response, cacheableResponse, requestTime);
} else {
return callback(new AJAXError(response.statusText, response.status, requestParameters.url));
}
}).catch(error => {
if (error.code === 20) {
// silence expected AbortError
return;
}
callback(new Error(error.message));
});
};
const finishRequest = (response, cacheableResponse, requestTime) => {
(
requestParameters.type === 'arrayBuffer' ? response.arrayBuffer() :
requestParameters.type === 'json' ? response.json() :
response.text()
).then(result => {
if (aborted) return;
if (cacheableResponse && requestTime) {
// The response needs to be inserted into the cache after it has completely loaded.
// Until it is fully loaded there is a chance it will be aborted. Aborting while
// reading the body can cause the cache insertion to error. We could catch this error
// in most browsers but in Firefox it seems to sometimes crash the tab. Adding
// it to the cache here avoids that error.
cachePut(request, cacheableResponse, requestTime);
}
complete = true;
callback(null, result, response.headers.get('Cache-Control'), response.headers.get('Expires'));
}).catch(err => {
if (!aborted) callback(new Error(err.message));
});
};
if (cacheIgnoringSearch) {
cacheGet(request, validateOrFetch);
} else {
validateOrFetch(null, null);
}
return {cancel: () => {
aborted = true;
if (!complete) controller.abort();
}};
}
function makeXMLHttpRequest(requestParameters: RequestParameters, callback: ResponseCallback<any>): Cancelable {
const xhr: XMLHttpRequest = new window.XMLHttpRequest();
xhr.open(requestParameters.method || 'GET', requestParameters.url, true);
if (requestParameters.type === 'arrayBuffer') {
xhr.responseType = 'arraybuffer';
}
for (const k in requestParameters.headers) {
xhr.setRequestHeader(k, requestParameters.headers[k]);
}
if (requestParameters.type === 'json') {
xhr.responseType = 'text';
xhr.setRequestHeader('Accept', 'application/json');
}
xhr.withCredentials = requestParameters.credentials === 'include';
xhr.onerror = () => {
callback(new Error(xhr.statusText));
};
xhr.onload = () => {
if (((xhr.status >= 200 && xhr.status < 300) || xhr.status === 0) && xhr.response !== null) {
let data: mixed = xhr.response;
if (requestParameters.type === 'json') {
// We're manually parsing JSON here to get better error messages.
try {
data = JSON.parse(xhr.response);
} catch (err) {
return callback(err);
}
}
callback(null, data, xhr.getResponseHeader('Cache-Control'), xhr.getResponseHeader('Expires'));
} else {
callback(new AJAXError(xhr.statusText, xhr.status, requestParameters.url));
}
};
xhr.send(requestParameters.body);
return {cancel: () => xhr.abort()};
}
export const makeRequest = function(requestParameters: RequestParameters, callback: ResponseCallback<any>): Cancelable {
// We're trying to use the Fetch API if possible. However, in some situations we can't use it:
// - Safari exposes window.AbortController, but it doesn't work actually abort any requests in
// older versions (see https://bugs.webkit.org/show_bug.cgi?id=174980#c2). In this case,
// we dispatch the request to the main thread so that we can get an accurate referrer header.
// - Requests for resources with the file:// URI scheme don't work with the Fetch API either. In
// this case we unconditionally use XHR on the current thread since referrers don't matter.
if (!isFileURL(requestParameters.url)) {
if (window.fetch && window.Request && window.AbortController && window.Request.prototype.hasOwnProperty('signal')) {
return makeFetchRequest(requestParameters, callback);
}
if (isWorker() && self.worker && self.worker.actor) {
const queueOnMainThread = true;
return self.worker.actor.send('getResource', requestParameters, callback, undefined, queueOnMainThread);
}
}
return makeXMLHttpRequest(requestParameters, callback);
};
export const getJSON = function(requestParameters: RequestParameters, callback: ResponseCallback<Object>): Cancelable {
return makeRequest(extend(requestParameters, {type: 'json'}), callback);
};
export const getArrayBuffer = function(requestParameters: RequestParameters, callback: ResponseCallback<ArrayBuffer>): Cancelable {
return makeRequest(extend(requestParameters, {type: 'arrayBuffer'}), callback);
};
export const postData = function(requestParameters: RequestParameters, callback: ResponseCallback<string>): Cancelable {
return makeRequest(extend(requestParameters, {method: 'POST'}), callback);
};
export const getData = function(requestParameters: RequestParameters, callback: ResponseCallback<string>): Cancelable {
return makeRequest(extend(requestParameters, {method: 'GET'}), callback);
};
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=';
function arrayBufferToImage(data: ArrayBuffer, callback: Callback<HTMLImageElement>) {
const img: HTMLImageElement = new window.Image();
const URL = window.URL;
img.onload = () => {
callback(null, img);
URL.revokeObjectURL(img.src);
// prevent image dataURI memory leak in Safari;
// but don't free the image immediately because it might be uploaded in the next frame
// https://github.com/mapbox/mapbox-gl-js/issues/10226
img.onload = null;
window.requestAnimationFrame(() => { img.src = transparentPngUrl; });
};
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(data)], {type: 'image/png'});
img.src = data.byteLength ? URL.createObjectURL(blob) : transparentPngUrl;
}
function arrayBufferToImageBitmap(data: ArrayBuffer, callback: Callback<ImageBitmap>) {
const blob: Blob = new window.Blob([new Uint8Array(data)], {type: 'image/png'});
window.createImageBitmap(blob).then((imgBitmap) => {
callback(null, imgBitmap);
}).catch((e) => {
callback(new Error(`Could not load image because of ${e.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`));
});
}
let imageQueue, numImageRequests;
export const resetImageRequestQueue = () => {
imageQueue = [];
numImageRequests = 0;
};
resetImageRequestQueue();
export const getImage = function(requestParameters: RequestParameters, callback: ResponseCallback<HTMLImageElement | ImageBitmap>): Cancelable {
if (webpSupported.supported) {
if (!requestParameters.headers) {
requestParameters.headers = {};
}
requestParameters.headers.accept = 'image/webp,*/*';
}
// limit concurrent image loads to help with raster sources performance on big screens
if (numImageRequests >= config.MAX_PARALLEL_IMAGE_REQUESTS) {
const queued = {
requestParameters,
callback,
cancelled: false,
cancel() { this.cancelled = true; }
};
imageQueue.push(queued);
return queued;
}
numImageRequests++;
let advanced = false;
const advanceImageRequestQueue = () => {
if (advanced) return;
advanced = true;
numImageRequests--;
assert(numImageRequests >= 0);
while (imageQueue.length && numImageRequests < config.MAX_PARALLEL_IMAGE_REQUESTS) { // eslint-disable-line
const request = imageQueue.shift();
const {requestParameters, callback, cancelled} = request;
if (!cancelled) {
request.cancel = getImage(requestParameters, callback).cancel;
}
}
};
// request the image with XHR to work around caching issues
// see https://github.com/mapbox/mapbox-gl-js/issues/1470
const request = getArrayBuffer(requestParameters, (err: ?Error, data: ?ArrayBuffer, cacheControl: ?string, expires: ?string) => {
advanceImageRequestQueue();
if (err) {
callback(err);
} else if (data) {
if (window.createImageBitmap) {
arrayBufferToImageBitmap(data, (err, imgBitmap) => callback(err, imgBitmap, cacheControl, expires));
} else {
arrayBufferToImage(data, (err, img) => callback(err, img, cacheControl, expires));
}
}
});
return {
cancel: () => {
request.cancel();
advanceImageRequestQueue();
}
};
};
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: () => {}};
};