-
Notifications
You must be signed in to change notification settings - Fork 0
/
browser.js
2774 lines (2355 loc) · 79.2 KB
/
browser.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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
module.exports={
"arenaToken": "95daa05f0f6a1a1094dea33f976e662f09fcc0b7d875df4a4799e06be7dbaa12",
"arenaUserId": "13854",
"appId": "8099a6cc5da0c7c39c37aea6694ca758e7205f209665db7c6318a4e0fd7cb377",
"appSecret": "344972781d97936239f3457b97201f0c58f61261959ce58a26388588b27dca45",
"localCallback": "urn:ietf:wg:oauth:2.0:oob"
}
},{}],2:[function(require,module,exports){
const Arena = require('are.na');
const fetch = require('node-fetch');
const config = require('./config.json');
const options = {
mode: 'no-cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}
document.addEventListener('DOMContentLoaded', () => {
console.log('Document loaded!')
document.getElementById('archivePage').addEventListener('click', requestAuth)
authenticateUser();
})
function authenticateUser(){
token = getToken()
if (token) {
requestAccess(token)
}
}
function getToken() {
//substring(1) to remove the '#'
hash = parseParms(document.location.hash.substring(1));
return hash.access_token;
}
function requestAuth(){
const {appId, localCallback} = config;
window.location = `http://dev.are.na/oauth/authorize?client_id=${appId}&redirect_uri=${localCallback}&response_type=code`
}
function requestAccess(token){
const {appId, appSecret, localCallback} = config;
const url = `https://dev.are.na/oauth/token?client_id=${appId}&client_secret=${appSecret}&code=${token}&grant_type=authorization_code&redirect_uri=${localCallback}`
fetch(url, {method: 'POST'})
}
function parseParms(str) {
var pieces = str.split("&"), data = {}, i, parts;
// process each query pair
for (i = 0; i < pieces.length; i++) {
parts = pieces[i].split("=");
if (parts.length < 2) {
parts.push("");
}
data[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
}
return data;
}
async function archiveLinks(){
// const accessToken = document.forms['archiveNow']['code'].value
const {arenaUserId, arenaToken} = config;
const results = await fetchChans(arenaUserId, arenaToken).catch(err => { console.error(err)});
displayResults(results)
}
async function fetchChans(id, accessToken){
const arena = new Arena({accessToken});
let chans = await arena.user(id).channels()
chans = chans.map(chan => {
const {id, title, contents} = chan;
return ({id, title, contents});
})
let linkBlocks = chans.map(chan => findLinks(chan)).filter(arr => arr.length > 0);
let sources = linkBlocks.map(chan => extractSources(chan)).filter(arr => arr.length > 0);
let classification = await Promise.all(sources.map(chan => checkArchive(chan)));
return classification;
}
function findLinks(chan){
const { title } = chan;
return chan.contents.map(resource => {
if (resource.class = 'Link') return {title, resource}
})
}
function extractSources(chan) {
const { title } = chan[0];
let sources = chan.map(block => {
if (block["resource"].source) {
return {title, "resource": block["resource"].source.url};
}
})
return sources.filter(Boolean)
}
async function checkArchive(chan) {
const { title } = chan[0];
let results = await Promise.all(chan.map(async source => {
let resource = await singleCheck(source["resource"]);
return ({ title, resource})
}))
return results
}
async function singleCheck(url) {
if (url.includes('web.archive.org')) {
createObject(true, url, false)
}
let json; let tries=0;
let object = await async function (){
try {
// Try fetch up to 12 times to sidestep 503 issue
while(!json && tries < 12){
let res = await fetch(`http://archive.org/wayback/available?url=${url}`, options)
.catch(err => { console.log(err) });
try {
json = await res.json()
} catch {
tries++
}
}
const arxLink = await json.archived_snapshots.closest.url;
return createObject(true, arxLink, url)
} catch {
let result = await savePage(url)
return result;
}
}()
return object;
}
async function savePage(url) {
let res;
let object = await async function (){
try {
// console.log(`Saving ${url} now.`)
res = await fetch(`https://web.archive.org/save/${url}`, options);
json = await res.json();
const arxLink = json.archived_snapshots.closest.url;
return createObject(true, arxLink, url)
}
catch {
// console.log(`The page at ${url} can't be archived. \n`)
return createObject(false, '', url)
}
}()
return object;
}
function createObject(preserved, arxLink, liveLink){
return ({preserved, arxLink, liveLink})
}
function displayResults(results) {
for(let i=0; i<results.length; i++){
for(let j=0; j<results[i].length; j++){
const { resource, title } = results[i][j];
if(resource.preserved === false){
const { liveLink } = resource;
console.log(`The resource ${liveLink} from the channel "${title}" cannot be backed up. \n`)
}
}
}
console.log("Consider backing these resources up manually and uploading them to the channel.")
}
function appendToPage(obj) {
let graf = document.createElement('p');
graf.innerText = `Preserved: ${obj.preserved}
Archival link: ${obj.arxLink}
Live link: ${obj.liveLink}`
document.querySelector('archiveNow').append(graf);
}
},{"./config.json":1,"are.na":3,"node-fetch":30}],3:[function(require,module,exports){
const axios = require('axios');
const qs = require('qs');
// Helper to deal with pulling an inner object out of returned data
// and then assigning other data as "attrs"
const pullObject = key => object => {
let newObj = object[key];
delete object[key];
Object.defineProperty(newObj, 'attrs', {
value: object
});
return newObj;
};
// Helper to accept an array or multiple arguments
// and convert to array
const arrayOrList = list => {
if (typeof list[0] === 'object' || typeof list[0] === 'array') {
return list[0];
}
return list;
};
class Arena {
constructor(opts) {
opts = opts || {};
let headers = {
"Content-Type": "application/x-www-form-urlencoded",
};
if (opts.accessToken) {
headers.Authorization = 'Bearer ' + opts.accessToken;
}
this.axios = axios.create({
baseURL: opts.baseURL || 'https://api.are.na/v2/',
headers
});
this.requestHandler = opts.requestHandler || (
(method, url, data) => this.axios.request({ method, url, data })
.then(({data}) => data)
);
}
_req(method, url, ...data) {
return this.requestHandler(method.toLowerCase(), url,
qs.stringify(Object.assign({}, ...data), {indices:false}));
}
channel(slug, data) {
slug = slug || '';
return {
get: (opts) => this._req('GET', 'channels/' + slug, data, opts),
thumb: (opts) => this._req('GET', 'channels/' + slug + '/thumb',
data, opts),
connections: (opts) => this._req('GET',
'channels/' + slug + '/connections', data, opts)
.then(pullObject('channels')),
channels: (opts) => this._req('GET', 'channels/' + slug + '/channels',
data, opts)
.then(pullObject('channels')),
contents: (opts) => this._req('GET', 'channels/' + slug + '/contents',
data, opts)
.then(pullObject('contents')),
collaborators: (opts) => this._req('GET',
'channels/' + slug + '/collaborators', data, opts)
.then(pullObject('users')),
create: (title, status) => this._req('POST', 'channels', {
// Allow it to be called as .channel(title).create(status) or
// .channel().create(title, status)
title: slug || title, status: slug ? title : status
}),
delete: (deleteSlug) => this._req('DELETE',
'channels/' + (slug || deleteSlug)),
update: (opts) => this._req('PUT', 'channels/' + slug, opts),
addCollaborators: (...ids) => this._req('POST',
'channels/' + slug + '/collaborators', {'ids[]': arrayOrList(ids)})
.then(pullObject('users')),
deleteCollaborators: (...ids) => this._req('DELETE',
'channels/' + slug + '/collaborators', {'ids[]': arrayOrList(ids)})
.then(pullObject('users')),
createBlock: (content) => {
let block = { content };
if (content.match(/^https?:\/\//)) {
block = { source: content };
}
return this._req('POST', 'channels/' + slug + '/blocks', block);
},
deleteBlock: (id) => this._req('DELETE',
'channels/' + slug + '/blocks/' + id)
}
}
block(id, data) {
return {
get: (opts) => this._req('GET', 'blocks/' + id, data, opts),
channels: (opts) => this._req('GET',
'blocks/' + id + '/channels', data, opts)
.then(pullObject('channels')),
create: (channel, content) => this.channel(channel).createBlock(content),
update: (opts) => this._req('PUT', 'blocks/' + id, data, opts)
}
}
user(id, data) {
return {
get: (opts) => this._req('GET', 'users/' + id, data, opts),
channels: (opts) => this._req('GET', 'users/' + id + '/channels',
data, opts)
.then(pullObject('channels')),
following: (opts) => this._req('GET', 'users/' + id + '/following',
data, opts)
.then(pullObject('following')),
followers: (opts) => this._req('GET', 'users/' + id + '/followers',
data, opts)
.then(pullObject('users')),
}
}
search(q, data) {
return {
all: (opts) => this._req('GET', 'search', {q}, data, opts),
users: (opts) => this._req('GET', 'search/users', {q}, data, opts)
.then(pullObject('users')),
channels: (opts) => this._req('GET', 'search/channels', {q}, data, opts)
.then(pullObject('channels')),
blocks: (opts) => this._req('GET', 'search/blocks', {q}, data, opts)
.then(pullObject('blocks')),
};
}
}
module.exports = Arena;
},{"axios":4,"qs":32}],4:[function(require,module,exports){
module.exports = require('./lib/axios');
},{"./lib/axios":6}],5:[function(require,module,exports){
(function (process){
'use strict';
var utils = require('./../utils');
var settle = require('./../core/settle');
var buildURL = require('./../helpers/buildURL');
var parseHeaders = require('./../helpers/parseHeaders');
var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
var createError = require('../core/createError');
var btoa = (typeof window !== 'undefined' && window.btoa && window.btoa.bind(window)) || require('./../helpers/btoa');
module.exports = function xhrAdapter(config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
var requestData = config.data;
var requestHeaders = config.headers;
if (utils.isFormData(requestData)) {
delete requestHeaders['Content-Type']; // Let the browser set it
}
var request = new XMLHttpRequest();
var loadEvent = 'onreadystatechange';
var xDomain = false;
// For IE 8/9 CORS support
// Only supports POST and GET calls and doesn't returns the response headers.
// DON'T do this for testing b/c XMLHttpRequest is mocked, not XDomainRequest.
if (process.env.NODE_ENV !== 'test' &&
typeof window !== 'undefined' &&
window.XDomainRequest && !('withCredentials' in request) &&
!isURLSameOrigin(config.url)) {
request = new window.XDomainRequest();
loadEvent = 'onload';
xDomain = true;
request.onprogress = function handleProgress() {};
request.ontimeout = function handleTimeout() {};
}
// HTTP basic authentication
if (config.auth) {
var username = config.auth.username || '';
var password = config.auth.password || '';
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
}
request.open(config.method.toUpperCase(), buildURL(config.url, config.params, config.paramsSerializer), true);
// Set the request timeout in MS
request.timeout = config.timeout;
// Listen for ready state
request[loadEvent] = function handleLoad() {
if (!request || (request.readyState !== 4 && !xDomain)) {
return;
}
// The request errored out and we didn't get a response, this will be
// handled by onerror instead
// With one exception: request that using file: protocol, most browsers
// will return status as 0 even though it's a successful request
if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
return;
}
// Prepare the response
var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
var response = {
data: responseData,
// IE sends 1223 instead of 204 (https://github.com/axios/axios/issues/201)
status: request.status === 1223 ? 204 : request.status,
statusText: request.status === 1223 ? 'No Content' : request.statusText,
headers: responseHeaders,
config: config,
request: request
};
settle(resolve, reject, response);
// Clean up request
request = null;
};
// Handle low level network errors
request.onerror = function handleError() {
// Real errors are hidden from us by the browser
// onerror should only fire if it's a network error
reject(createError('Network Error', config, null, request));
// Clean up request
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED',
request));
// Clean up request
request = null;
};
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (utils.isStandardBrowserEnv()) {
var cookies = require('./../helpers/cookies');
// Add xsrf header
var xsrfValue = (config.withCredentials || isURLSameOrigin(config.url)) && config.xsrfCookieName ?
cookies.read(config.xsrfCookieName) :
undefined;
if (xsrfValue) {
requestHeaders[config.xsrfHeaderName] = xsrfValue;
}
}
// Add headers to the request
if ('setRequestHeader' in request) {
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
// Remove Content-Type if data is undefined
delete requestHeaders[key];
} else {
// Otherwise add header to the request
request.setRequestHeader(key, val);
}
});
}
// Add withCredentials to request if needed
if (config.withCredentials) {
request.withCredentials = true;
}
// Add responseType to request if needed
if (config.responseType) {
try {
request.responseType = config.responseType;
} catch (e) {
// Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2.
// But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function.
if (config.responseType !== 'json') {
throw e;
}
}
}
// Handle progress if needed
if (typeof config.onDownloadProgress === 'function') {
request.addEventListener('progress', config.onDownloadProgress);
}
// Not all browsers support upload events
if (typeof config.onUploadProgress === 'function' && request.upload) {
request.upload.addEventListener('progress', config.onUploadProgress);
}
if (config.cancelToken) {
// Handle cancellation
config.cancelToken.promise.then(function onCanceled(cancel) {
if (!request) {
return;
}
request.abort();
reject(cancel);
// Clean up request
request = null;
});
}
if (requestData === undefined) {
requestData = null;
}
// Send the request
request.send(requestData);
});
};
}).call(this,require('_process'))
},{"../core/createError":12,"./../core/settle":15,"./../helpers/btoa":19,"./../helpers/buildURL":20,"./../helpers/cookies":22,"./../helpers/isURLSameOrigin":24,"./../helpers/parseHeaders":26,"./../utils":28,"_process":36}],6:[function(require,module,exports){
'use strict';
var utils = require('./utils');
var bind = require('./helpers/bind');
var Axios = require('./core/Axios');
var defaults = require('./defaults');
/**
* Create an instance of Axios
*
* @param {Object} defaultConfig The default config for the instance
* @return {Axios} A new instance of Axios
*/
function createInstance(defaultConfig) {
var context = new Axios(defaultConfig);
var instance = bind(Axios.prototype.request, context);
// Copy axios.prototype to instance
utils.extend(instance, Axios.prototype, context);
// Copy context to instance
utils.extend(instance, context);
return instance;
}
// Create the default instance to be exported
var axios = createInstance(defaults);
// Expose Axios class to allow class inheritance
axios.Axios = Axios;
// Factory for creating new instances
axios.create = function create(instanceConfig) {
return createInstance(utils.merge(defaults, instanceConfig));
};
// Expose Cancel & CancelToken
axios.Cancel = require('./cancel/Cancel');
axios.CancelToken = require('./cancel/CancelToken');
axios.isCancel = require('./cancel/isCancel');
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = require('./helpers/spread');
module.exports = axios;
// Allow use of default import syntax in TypeScript
module.exports.default = axios;
},{"./cancel/Cancel":7,"./cancel/CancelToken":8,"./cancel/isCancel":9,"./core/Axios":10,"./defaults":17,"./helpers/bind":18,"./helpers/spread":27,"./utils":28}],7:[function(require,module,exports){
'use strict';
/**
* A `Cancel` is an object that is thrown when an operation is canceled.
*
* @class
* @param {string=} message The message.
*/
function Cancel(message) {
this.message = message;
}
Cancel.prototype.toString = function toString() {
return 'Cancel' + (this.message ? ': ' + this.message : '');
};
Cancel.prototype.__CANCEL__ = true;
module.exports = Cancel;
},{}],8:[function(require,module,exports){
'use strict';
var Cancel = require('./Cancel');
/**
* A `CancelToken` is an object that can be used to request cancellation of an operation.
*
* @class
* @param {Function} executor The executor function.
*/
function CancelToken(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
var resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
var token = this;
executor(function cancel(message) {
if (token.reason) {
// Cancellation has already been requested
return;
}
token.reason = new Cancel(message);
resolvePromise(token.reason);
});
}
/**
* Throws a `Cancel` if cancellation has been requested.
*/
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
if (this.reason) {
throw this.reason;
}
};
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
CancelToken.source = function source() {
var cancel;
var token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token: token,
cancel: cancel
};
};
module.exports = CancelToken;
},{"./Cancel":7}],9:[function(require,module,exports){
'use strict';
module.exports = function isCancel(value) {
return !!(value && value.__CANCEL__);
};
},{}],10:[function(require,module,exports){
'use strict';
var defaults = require('./../defaults');
var utils = require('./../utils');
var InterceptorManager = require('./InterceptorManager');
var dispatchRequest = require('./dispatchRequest');
/**
* Create a new instance of Axios
*
* @param {Object} instanceConfig The default config for the instance
*/
function Axios(instanceConfig) {
this.defaults = instanceConfig;
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
}
/**
* Dispatch a request
*
* @param {Object} config The config specific for this request (merged with this.defaults)
*/
Axios.prototype.request = function request(config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof config === 'string') {
config = utils.merge({
url: arguments[0]
}, arguments[1]);
}
config = utils.merge(defaults, this.defaults, { method: 'get' }, config);
config.method = config.method.toLowerCase();
// Hook up interceptors middleware
var chain = [dispatchRequest, undefined];
var promise = Promise.resolve(config);
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
chain.unshift(interceptor.fulfilled, interceptor.rejected);
});
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
chain.push(interceptor.fulfilled, interceptor.rejected);
});
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}
return promise;
};
// Provide aliases for supported request methods
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, config) {
return this.request(utils.merge(config || {}, {
method: method,
url: url
}));
};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, data, config) {
return this.request(utils.merge(config || {}, {
method: method,
url: url,
data: data
}));
};
});
module.exports = Axios;
},{"./../defaults":17,"./../utils":28,"./InterceptorManager":11,"./dispatchRequest":13}],11:[function(require,module,exports){
'use strict';
var utils = require('./../utils');
function InterceptorManager() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
InterceptorManager.prototype.use = function use(fulfilled, rejected) {
this.handlers.push({
fulfilled: fulfilled,
rejected: rejected
});
return this.handlers.length - 1;
};
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*/
InterceptorManager.prototype.eject = function eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
};
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*/
InterceptorManager.prototype.forEach = function forEach(fn) {
utils.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
};
module.exports = InterceptorManager;
},{"./../utils":28}],12:[function(require,module,exports){
'use strict';
var enhanceError = require('./enhanceError');
/**
* Create an Error with the specified message, config, error code, request and response.
*
* @param {string} message The error message.
* @param {Object} config The config.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The created error.
*/
module.exports = function createError(message, config, code, request, response) {
var error = new Error(message);
return enhanceError(error, config, code, request, response);
};
},{"./enhanceError":14}],13:[function(require,module,exports){
'use strict';
var utils = require('./../utils');
var transformData = require('./transformData');
var isCancel = require('../cancel/isCancel');
var defaults = require('../defaults');
var isAbsoluteURL = require('./../helpers/isAbsoluteURL');
var combineURLs = require('./../helpers/combineURLs');
/**
* Throws a `Cancel` if cancellation has been requested.
*/
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
}
/**
* Dispatch a request to the server using the configured adapter.
*
* @param {object} config The config that is to be used for the request
* @returns {Promise} The Promise to be fulfilled
*/
module.exports = function dispatchRequest(config) {
throwIfCancellationRequested(config);
// Support baseURL config
if (config.baseURL && !isAbsoluteURL(config.url)) {
config.url = combineURLs(config.baseURL, config.url);
}
// Ensure headers exist
config.headers = config.headers || {};
// Transform request data
config.data = transformData(
config.data,
config.headers,
config.transformRequest
);
// Flatten headers
config.headers = utils.merge(
config.headers.common || {},
config.headers[config.method] || {},
config.headers || {}
);
utils.forEach(
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
function cleanHeaderConfig(method) {
delete config.headers[method];
}
);
var adapter = config.adapter || defaults.adapter;
return adapter(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
// Transform response data
response.data = transformData(
response.data,
response.headers,
config.transformResponse
);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel(reason)) {
throwIfCancellationRequested(config);
// Transform response data
if (reason && reason.response) {
reason.response.data = transformData(
reason.response.data,
reason.response.headers,
config.transformResponse
);
}
}
return Promise.reject(reason);
});
};
},{"../cancel/isCancel":9,"../defaults":17,"./../helpers/combineURLs":21,"./../helpers/isAbsoluteURL":23,"./../utils":28,"./transformData":16}],14:[function(require,module,exports){
'use strict';
/**
* Update an Error with the specified config, error code, and response.
*
* @param {Error} error The error to update.
* @param {Object} config The config.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The error.
*/
module.exports = function enhanceError(error, config, code, request, response) {
error.config = config;
if (code) {
error.code = code;
}
error.request = request;
error.response = response;
return error;
};
},{}],15:[function(require,module,exports){
'use strict';
var createError = require('./createError');
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*/
module.exports = function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus;
// Note: status is not exposed by XDomainRequest
if (!response.status || !validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(createError(
'Request failed with status code ' + response.status,
response.config,
null,
response.request,
response
));
}
};
},{"./createError":12}],16:[function(require,module,exports){
'use strict';
var utils = require('./../utils');
/**
* Transform the data for a request or a response
*
* @param {Object|String} data The data to be transformed
* @param {Array} headers The headers for the request or response
* @param {Array|Function} fns A single function or Array of functions
* @returns {*} The resulting transformed data
*/
module.exports = function transformData(data, headers, fns) {
/*eslint no-param-reassign:0*/
utils.forEach(fns, function transform(fn) {
data = fn(data, headers);
});
return data;
};
},{"./../utils":28}],17:[function(require,module,exports){
(function (process){
'use strict';
var utils = require('./utils');
var normalizeHeaderName = require('./helpers/normalizeHeaderName');
var DEFAULT_CONTENT_TYPE = {
'Content-Type': 'application/x-www-form-urlencoded'
};
function setContentTypeIfUnset(headers, value) {
if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
headers['Content-Type'] = value;
}
}
function getDefaultAdapter() {
var adapter;