· 9 years ago · Jan 12, 2017, 12:52 PM
1(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
2window['APIGatewayClient'] = require('aws-api-gateway-client');
3
4},{"aws-api-gateway-client":2}],2:[function(require,module,exports){
5/*
6 * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
7 *
8 * Licensed under the Apache License, Version 2.0 (the "License").
9 * You may not use this file except in compliance with the License.
10 * A copy of the License is located at
11 *
12 * http://aws.amazon.com/apache2.0
13 *
14 * or in the "license" file accompanying this file. This file is distributed
15 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
16 * express or implied. See the License for the specific language governing
17 * permissions and limitations under the License.
18 */
19
20var apigClientFactory = {};
21var apiGateway = require('./lib/apiGatewayCore/apiGatewayClient.js');
22var uritemplate = require('url-template');
23
24apigClientFactory.newClient = function (config) {
25 var apigClient = { };
26 if(config === undefined) {
27 config = {
28 accessKey: '',
29 secretKey: '',
30 sessionToken: '',
31 region: '',
32 apiKey: undefined,
33 invokeUrl: '',
34 defaultContentType: 'application/json',
35 defaultAcceptType: 'application/json'
36 };
37 }
38 if(config.accessKey === undefined) {
39 config.accessKey = '';
40 }
41 if(config.secretKey === undefined) {
42 config.secretKey = '';
43 }
44 if(config.apiKey === undefined) {
45 config.apiKey = '';
46 }
47 if(config.sessionToken === undefined) {
48 config.sessionToken = '';
49 }
50 if(config.region === undefined) {
51 config.region = 'us-east-1';
52 }
53 //If defaultContentType is not defined then default to application/json
54 if(config.defaultContentType === undefined) {
55 config.defaultContentType = 'application/json';
56 }
57 //If defaultAcceptType is not defined then default to application/json
58 if(config.defaultAcceptType === undefined) {
59 config.defaultAcceptType = 'application/json';
60 }
61
62 // extract endpoint and path from url
63 var invokeUrl = config.invokeUrl;
64 var endpoint = /(^https?:\/\/[^\/]+)/g.exec(invokeUrl)[1];
65 var pathComponent = invokeUrl.substring(endpoint.length);
66
67 var sigV4ClientConfig = {
68 accessKey: config.accessKey,
69 secretKey: config.secretKey,
70 sessionToken: config.sessionToken,
71 serviceName: 'execute-api',
72 region: config.region,
73 endpoint: endpoint,
74 defaultContentType: config.defaultContentType,
75 defaultAcceptType: config.defaultAcceptType
76 };
77
78 var authType = 'NONE';
79 if (sigV4ClientConfig.accessKey !== undefined && sigV4ClientConfig.accessKey !== '' && sigV4ClientConfig.secretKey !== undefined && sigV4ClientConfig.secretKey !== '') {
80 authType = 'AWS_IAM';
81 }
82
83 var simpleHttpClientConfig = {
84 endpoint: endpoint,
85 defaultContentType: config.defaultContentType,
86 defaultAcceptType: config.defaultAcceptType
87 };
88
89 var apiGatewayClient = apiGateway.core.apiGatewayClientFactory.newClient(simpleHttpClientConfig, sigV4ClientConfig);
90
91
92
93 apigClient.invokeApi = function (params, pathTemplate, method, additionalParams, body) {
94 if (additionalParams===undefined) additionalParams={};
95 if (body===undefined) body='';
96
97 var request = {
98 verb: method.toUpperCase(),
99 path: pathComponent + uritemplate.parse(pathTemplate).expand(params),
100 headers: additionalParams.headers,
101 queryParams: additionalParams.queryParams,
102 body: body
103 };
104
105 return apiGatewayClient.makeRequest(request, authType, additionalParams, config.apiKey);
106 };
107
108
109 return apigClient;
110};
111
112module.exports = apigClientFactory;
113
114},{"./lib/apiGatewayCore/apiGatewayClient.js":3,"url-template":37}],3:[function(require,module,exports){
115/*
116 * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
117 *
118 * Licensed under the Apache License, Version 2.0 (the "License").
119 * You may not use this file except in compliance with the License.
120 * A copy of the License is located at
121 *
122 * http://aws.amazon.com/apache2.0
123 *
124 * or in the "license" file accompanying this file. This file is distributed
125 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
126 * express or implied. See the License for the specific language governing
127 * permissions and limitations under the License.
128 */
129
130var apiGateway = apiGateway || {};
131apiGateway.core = apiGateway.core || {};
132apiGateway.core.utils = require('./utils');
133apiGateway.core.sigV4ClientFactory = require('./sigV4Client');
134apiGateway.core.simpleHttpClientFactory = require('./simpleHttpClient');
135
136apiGateway.core.apiGatewayClientFactory = {};
137apiGateway.core.apiGatewayClientFactory.newClient = function (simpleHttpClientConfig, sigV4ClientConfig) {
138 var apiGatewayClient = { };
139 //Spin up 2 httpClients, one for simple requests, one for SigV4
140 var sigV4Client = apiGateway.core.sigV4ClientFactory.newClient(sigV4ClientConfig);
141 var simpleHttpClient = apiGateway.core.simpleHttpClientFactory.newClient(simpleHttpClientConfig);
142
143 apiGatewayClient.makeRequest = function (request, authType, additionalParams, apiKey) {
144 //Default the request to use the simple http client
145 var clientToUse = simpleHttpClient;
146
147 //Attach the apiKey to the headers request if one was provided
148 if (apiKey !== undefined && apiKey !== '' && apiKey !== null) {
149 request.headers['x-api-key'] = apiKey;
150 }
151
152 if (request.body === undefined || request.body === '' || request.body === null || Object.keys(request.body).length === 0) {
153 request.body = undefined;
154 }
155
156 // If the user specified any additional headers or query params that may not have been modeled
157 // merge them into the appropriate request properties
158 request.headers = apiGateway.core.utils.mergeInto(request.headers, additionalParams.headers);
159 request.queryParams = apiGateway.core.utils.mergeInto(request.queryParams, additionalParams.queryParams);
160
161 //If an auth type was specified inject the appropriate auth client
162 if (authType === 'AWS_IAM') {
163 clientToUse = sigV4Client;
164 }
165
166 //Call the selected http client to make the request, returning a promise once the request is sent
167 return clientToUse.makeRequest(request);
168 };
169 return apiGatewayClient;
170};
171
172module.exports = apiGateway;
173
174},{"./sigV4Client":4,"./simpleHttpClient":5,"./utils":6}],4:[function(require,module,exports){
175/*
176 * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
177 *
178 * Licensed under the Apache License, Version 2.0 (the "License").
179 * You may not use this file except in compliance with the License.
180 * A copy of the License is located at
181 *
182 * http://aws.amazon.com/apache2.0
183 *
184 * or in the "license" file accompanying this file. This file is distributed
185 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
186 * express or implied. See the License for the specific language governing
187 * permissions and limitations under the License.
188 */
189
190var apiGateway = apiGateway || {};
191apiGateway.core = apiGateway.core || {};
192apiGateway.core.utils = require('./utils');
193var axios = require('axios');
194var SHA256 = require('crypto-js/sha256');
195var encHex = require('crypto-js/enc-hex');
196var HmacSHA256 = require('crypto-js/hmac-sha256');
197var urlParser = require('url');
198
199apiGateway.core.sigV4ClientFactory = {};
200apiGateway.core.sigV4ClientFactory.newClient = function (config) {
201 var AWS_SHA_256 = 'AWS4-HMAC-SHA256';
202 var AWS4_REQUEST = 'aws4_request';
203 var AWS4 = 'AWS4';
204 var X_AMZ_DATE = 'x-amz-date';
205 var X_AMZ_SECURITY_TOKEN = 'x-amz-security-token';
206 var HOST = 'host';
207 var AUTHORIZATION = 'Authorization';
208
209 function hash(value) {
210 return SHA256(value);
211 }
212
213 function hexEncode(value) {
214 return value.toString(encHex);
215 }
216
217 function hmac(secret, value) {
218 return HmacSHA256(value, secret, {asBytes: true});
219 }
220
221 function buildCanonicalRequest(method, path, queryParams, headers, payload) {
222 return method + '\n' +
223 buildCanonicalUri(path) + '\n' +
224 buildCanonicalQueryString(queryParams) + '\n' +
225 buildCanonicalHeaders(headers) + '\n' +
226 buildCanonicalSignedHeaders(headers) + '\n' +
227 hexEncode(hash(payload));
228 }
229
230 function hashCanonicalRequest(request) {
231 return hexEncode(hash(request));
232 }
233
234 function buildCanonicalUri(uri) {
235 return encodeURI(uri);
236 }
237
238 function buildCanonicalQueryString(queryParams) {
239 if (Object.keys(queryParams).length < 1) {
240 return '';
241 }
242
243 var sortedQueryParams = [];
244 for (var property in queryParams) {
245 if (queryParams.hasOwnProperty(property)) {
246 sortedQueryParams.push(property);
247 }
248 }
249 sortedQueryParams.sort();
250
251 var canonicalQueryString = '';
252 for (var i = 0; i < sortedQueryParams.length; i++) {
253 canonicalQueryString += sortedQueryParams[i] + '=' + encodeURIComponent(queryParams[sortedQueryParams[i]]) + '&';
254 }
255 return canonicalQueryString.substr(0, canonicalQueryString.length - 1);
256 }
257
258 function buildCanonicalHeaders(headers) {
259 var canonicalHeaders = '';
260 var sortedKeys = [];
261 for (var property in headers) {
262 if (headers.hasOwnProperty(property)) {
263 sortedKeys.push(property);
264 }
265 }
266 sortedKeys.sort();
267
268 for (var i = 0; i < sortedKeys.length; i++) {
269 canonicalHeaders += sortedKeys[i].toLowerCase() + ':' + headers[sortedKeys[i]] + '\n';
270 }
271 return canonicalHeaders;
272 }
273
274 function buildCanonicalSignedHeaders(headers) {
275 var sortedKeys = [];
276 for (var property in headers) {
277 if (headers.hasOwnProperty(property)) {
278 sortedKeys.push(property.toLowerCase());
279 }
280 }
281 sortedKeys.sort();
282
283 return sortedKeys.join(';');
284 }
285
286 function buildStringToSign(datetime, credentialScope, hashedCanonicalRequest) {
287 return AWS_SHA_256 + '\n' +
288 datetime + '\n' +
289 credentialScope + '\n' +
290 hashedCanonicalRequest;
291 }
292
293 function buildCredentialScope(datetime, region, service) {
294 return datetime.substr(0, 8) + '/' + region + '/' + service + '/' + AWS4_REQUEST
295 }
296
297 function calculateSigningKey(secretKey, datetime, region, service) {
298 return hmac(hmac(hmac(hmac(AWS4 + secretKey, datetime.substr(0, 8)), region), service), AWS4_REQUEST);
299 }
300
301 function calculateSignature(key, stringToSign) {
302 return hexEncode(hmac(key, stringToSign));
303 }
304
305 function buildAuthorizationHeader(accessKey, credentialScope, headers, signature) {
306 return AWS_SHA_256 + ' Credential=' + accessKey + '/' + credentialScope + ', SignedHeaders=' + buildCanonicalSignedHeaders(headers) + ', Signature=' + signature;
307 }
308
309 var awsSigV4Client = { };
310 if(config.accessKey === undefined || config.secretKey === undefined) {
311 return awsSigV4Client;
312 }
313 awsSigV4Client.accessKey = apiGateway.core.utils.assertDefined(config.accessKey, 'accessKey');
314 awsSigV4Client.secretKey = apiGateway.core.utils.assertDefined(config.secretKey, 'secretKey');
315 awsSigV4Client.sessionToken = config.sessionToken;
316 awsSigV4Client.serviceName = apiGateway.core.utils.assertDefined(config.serviceName, 'serviceName');
317 awsSigV4Client.region = apiGateway.core.utils.assertDefined(config.region, 'region');
318 awsSigV4Client.endpoint = apiGateway.core.utils.assertDefined(config.endpoint, 'endpoint');
319
320 awsSigV4Client.makeRequest = function (request) {
321 var verb = apiGateway.core.utils.assertDefined(request.verb, 'verb');
322 var path = apiGateway.core.utils.assertDefined(request.path, 'path');
323 var queryParams = apiGateway.core.utils.copy(request.queryParams);
324 if (queryParams === undefined) {
325 queryParams = {};
326 }
327 var headers = apiGateway.core.utils.copy(request.headers);
328 if (headers === undefined) {
329 headers = {};
330 }
331
332 //If the user has not specified an override for Content type the use default
333 if(headers['Content-Type'] === undefined) {
334 headers['Content-Type'] = config.defaultContentType;
335 }
336
337 //If the user has not specified an override for Accept type the use default
338 if(headers['Accept'] === undefined) {
339 headers['Accept'] = config.defaultAcceptType;
340 }
341
342 var body = apiGateway.core.utils.copy(request.body);
343 if (body === undefined || verb === 'GET') { // override request body and set to empty when signing GET requests
344 body = '';
345 } else {
346 body = JSON.stringify(body);
347 }
348
349 //If there is no body remove the content-type header so it is not included in SigV4 calculation
350 if(body === '' || body === undefined || body === null) {
351 delete headers['Content-Type'];
352 }
353
354 var datetime = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z').replace(/[:\-]|\.\d{3}/g, '');
355 headers[X_AMZ_DATE] = datetime;
356 var parser = urlParser.parse(awsSigV4Client.endpoint);
357 headers[HOST] = parser.hostname;
358
359 var canonicalRequest = buildCanonicalRequest(verb, path, queryParams, headers, body);
360 var hashedCanonicalRequest = hashCanonicalRequest(canonicalRequest);
361 var credentialScope = buildCredentialScope(datetime, awsSigV4Client.region, awsSigV4Client.serviceName);
362 var stringToSign = buildStringToSign(datetime, credentialScope, hashedCanonicalRequest);
363 var signingKey = calculateSigningKey(awsSigV4Client.secretKey, datetime, awsSigV4Client.region, awsSigV4Client.serviceName);
364 var signature = calculateSignature(signingKey, stringToSign);
365 headers[AUTHORIZATION] = buildAuthorizationHeader(awsSigV4Client.accessKey, credentialScope, headers, signature);
366 if(awsSigV4Client.sessionToken !== undefined && awsSigV4Client.sessionToken !== '') {
367 headers[X_AMZ_SECURITY_TOKEN] = awsSigV4Client.sessionToken;
368 }
369 delete headers[HOST];
370
371 var url = config.endpoint + path;
372 var queryString = buildCanonicalQueryString(queryParams);
373 if (queryString != '') {
374 url += '?' + queryString;
375 }
376
377 //Need to re-attach Content-Type if it is not specified at this point
378 if(headers['Content-Type'] === undefined) {
379 headers['Content-Type'] = config.defaultContentType;
380 }
381
382 var signedRequest = {
383 method: verb,
384 url: url,
385 headers: headers,
386 data: body
387 };
388 return axios(signedRequest);
389 };
390
391 return awsSigV4Client;
392};
393
394module.exports = apiGateway.core.sigV4ClientFactory;
395
396},{"./utils":6,"axios":7,"crypto-js/enc-hex":33,"crypto-js/hmac-sha256":34,"crypto-js/sha256":36,"url":43}],5:[function(require,module,exports){
397/*
398 * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
399 *
400 * Licensed under the Apache License, Version 2.0 (the "License").
401 * You may not use this file except in compliance with the License.
402 * A copy of the License is located at
403 *
404 * http://aws.amazon.com/apache2.0
405 *
406 * or in the "license" file accompanying this file. This file is distributed
407 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
408 * express or implied. See the License for the specific language governing
409 * permissions and limitations under the License.
410 */
411
412var apiGateway = apiGateway || {};
413apiGateway.core = apiGateway.core || {};
414apiGateway.core.utils = require('./utils');
415var axios = require('axios');
416
417apiGateway.core.simpleHttpClientFactory = {};
418apiGateway.core.simpleHttpClientFactory.newClient = function (config) {
419 function buildCanonicalQueryString(queryParams) {
420 //Build a properly encoded query string from a QueryParam object
421 if (Object.keys(queryParams).length < 1) {
422 return '';
423 }
424
425 var canonicalQueryString = '';
426 for (var property in queryParams) {
427 if (queryParams.hasOwnProperty(property)) {
428 canonicalQueryString += encodeURIComponent(property) + '=' + encodeURIComponent(queryParams[property]) + '&';
429 }
430 }
431
432 return canonicalQueryString.substr(0, canonicalQueryString.length - 1);
433 }
434
435 var simpleHttpClient = { };
436 simpleHttpClient.endpoint = apiGateway.core.utils.assertDefined(config.endpoint, 'endpoint');
437
438 simpleHttpClient.makeRequest = function (request) {
439 var verb = apiGateway.core.utils.assertDefined(request.verb, 'verb');
440 var path = apiGateway.core.utils.assertDefined(request.path, 'path');
441 var queryParams = apiGateway.core.utils.copy(request.queryParams);
442 if (queryParams === undefined) {
443 queryParams = {};
444 }
445 var headers = apiGateway.core.utils.copy(request.headers);
446 if (headers === undefined) {
447 headers = {};
448 }
449
450 //If the user has not specified an override for Content type the use default
451 if(headers['Content-Type'] === undefined) {
452 headers['Content-Type'] = config.defaultContentType;
453 }
454
455 //If the user has not specified an override for Accept type the use default
456 if(headers['Accept'] === undefined) {
457 headers['Accept'] = config.defaultAcceptType;
458 }
459
460 var body = apiGateway.core.utils.copy(request.body);
461 if (body === undefined) {
462 body = '';
463 }
464
465 var url = config.endpoint + path;
466 var queryString = buildCanonicalQueryString(queryParams);
467 if (queryString != '') {
468 url += '?' + queryString;
469 }
470 var simpleHttpRequest = {
471 method: verb,
472 url: url,
473 headers: headers,
474 data: body
475 };
476 return axios(simpleHttpRequest);
477 };
478 return simpleHttpClient;
479};
480
481module.exports = apiGateway.core.simpleHttpClientFactory;
482
483},{"./utils":6,"axios":7}],6:[function(require,module,exports){
484/*
485 * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
486 *
487 * Licensed under the Apache License, Version 2.0 (the "License").
488 * You may not use this file except in compliance with the License.
489 * A copy of the License is located at
490 *
491 * http://aws.amazon.com/apache2.0
492 *
493 * or in the "license" file accompanying this file. This file is distributed
494 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
495 * express or implied. See the License for the specific language governing
496 * permissions and limitations under the License.
497 */
498
499var apiGateway = apiGateway || {};
500apiGateway.core = apiGateway.core || {};
501
502apiGateway.core.utils = {
503 assertDefined: function (object, name) {
504 if (object === undefined) {
505 throw name + ' must be defined';
506 } else {
507 return object;
508 }
509 },
510 assertParametersDefined: function (params, keys, ignore) {
511 if (keys === undefined) {
512 return;
513 }
514 if (keys.length > 0 && params === undefined) {
515 params = {};
516 }
517 for (var i = 0; i < keys.length; i++) {
518 if(!apiGateway.core.utils.contains(ignore, keys[i])) {
519 apiGateway.core.utils.assertDefined(params[keys[i]], keys[i]);
520 }
521 }
522 },
523 parseParametersToObject: function (params, keys) {
524 if (params === undefined) {
525 return {};
526 }
527 var object = { };
528 for (var i = 0; i < keys.length; i++) {
529 object[keys[i]] = params[keys[i]];
530 }
531 return object;
532 },
533 contains: function(a, obj) {
534 if(a === undefined) { return false;}
535 var i = a.length;
536 while (i--) {
537 if (a[i] === obj) {
538 return true;
539 }
540 }
541 return false;
542 },
543 copy: function (obj) {
544 if (null == obj || "object" != typeof obj) return obj;
545 var copy = obj.constructor();
546 for (var attr in obj) {
547 if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
548 }
549 return copy;
550 },
551 mergeInto: function (baseObj, additionalProps) {
552 if (null == baseObj || "object" != typeof baseObj) return baseObj;
553 var merged = baseObj.constructor();
554 for (var attr in baseObj) {
555 if (baseObj.hasOwnProperty(attr)) merged[attr] = baseObj[attr];
556 }
557 if (null == additionalProps || "object" != typeof additionalProps) return baseObj;
558 for (attr in additionalProps) {
559 if (additionalProps.hasOwnProperty(attr)) merged[attr] = additionalProps[attr];
560 }
561 return merged;
562 }
563};
564
565module.exports = apiGateway.core.utils;
566
567},{}],7:[function(require,module,exports){
568module.exports = require('./lib/axios');
569},{"./lib/axios":9}],8:[function(require,module,exports){
570(function (process){
571'use strict';
572
573var utils = require('./../utils');
574var settle = require('./../core/settle');
575var buildURL = require('./../helpers/buildURL');
576var parseHeaders = require('./../helpers/parseHeaders');
577var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
578var createError = require('../core/createError');
579var btoa = (typeof window !== 'undefined' && window.btoa && window.btoa.bind(window)) || require('./../helpers/btoa');
580
581module.exports = function xhrAdapter(config) {
582 return new Promise(function dispatchXhrRequest(resolve, reject) {
583 var requestData = config.data;
584 var requestHeaders = config.headers;
585
586 if (utils.isFormData(requestData)) {
587 delete requestHeaders['Content-Type']; // Let the browser set it
588 }
589
590 var request = new XMLHttpRequest();
591 var loadEvent = 'onreadystatechange';
592 var xDomain = false;
593
594 // For IE 8/9 CORS support
595 // Only supports POST and GET calls and doesn't returns the response headers.
596 // DON'T do this for testing b/c XMLHttpRequest is mocked, not XDomainRequest.
597 if (process.env.NODE_ENV !== 'test' &&
598 typeof window !== 'undefined' &&
599 window.XDomainRequest && !('withCredentials' in request) &&
600 !isURLSameOrigin(config.url)) {
601 request = new window.XDomainRequest();
602 loadEvent = 'onload';
603 xDomain = true;
604 request.onprogress = function handleProgress() {};
605 request.ontimeout = function handleTimeout() {};
606 }
607
608 // HTTP basic authentication
609 if (config.auth) {
610 var username = config.auth.username || '';
611 var password = config.auth.password || '';
612 requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
613 }
614
615 request.open(config.method.toUpperCase(), buildURL(config.url, config.params, config.paramsSerializer), true);
616
617 // Set the request timeout in MS
618 request.timeout = config.timeout;
619
620 // Listen for ready state
621 request[loadEvent] = function handleLoad() {
622 if (!request || (request.readyState !== 4 && !xDomain)) {
623 return;
624 }
625
626 // The request errored out and we didn't get a response, this will be
627 // handled by onerror instead
628 // With one exception: request that using file: protocol, most browsers
629 // will return status as 0 even though it's a successful request
630 if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
631 return;
632 }
633
634 // Prepare the response
635 var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
636 var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
637 var response = {
638 data: responseData,
639 // IE sends 1223 instead of 204 (https://github.com/mzabriskie/axios/issues/201)
640 status: request.status === 1223 ? 204 : request.status,
641 statusText: request.status === 1223 ? 'No Content' : request.statusText,
642 headers: responseHeaders,
643 config: config,
644 request: request
645 };
646
647 settle(resolve, reject, response);
648
649 // Clean up request
650 request = null;
651 };
652
653 // Handle low level network errors
654 request.onerror = function handleError() {
655 // Real errors are hidden from us by the browser
656 // onerror should only fire if it's a network error
657 reject(createError('Network Error', config));
658
659 // Clean up request
660 request = null;
661 };
662
663 // Handle timeout
664 request.ontimeout = function handleTimeout() {
665 reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED'));
666
667 // Clean up request
668 request = null;
669 };
670
671 // Add xsrf header
672 // This is only done if running in a standard browser environment.
673 // Specifically not if we're in a web worker, or react-native.
674 if (utils.isStandardBrowserEnv()) {
675 var cookies = require('./../helpers/cookies');
676
677 // Add xsrf header
678 var xsrfValue = (config.withCredentials || isURLSameOrigin(config.url)) && config.xsrfCookieName ?
679 cookies.read(config.xsrfCookieName) :
680 undefined;
681
682 if (xsrfValue) {
683 requestHeaders[config.xsrfHeaderName] = xsrfValue;
684 }
685 }
686
687 // Add headers to the request
688 if ('setRequestHeader' in request) {
689 utils.forEach(requestHeaders, function setRequestHeader(val, key) {
690 if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
691 // Remove Content-Type if data is undefined
692 delete requestHeaders[key];
693 } else {
694 // Otherwise add header to the request
695 request.setRequestHeader(key, val);
696 }
697 });
698 }
699
700 // Add withCredentials to request if needed
701 if (config.withCredentials) {
702 request.withCredentials = true;
703 }
704
705 // Add responseType to request if needed
706 if (config.responseType) {
707 try {
708 request.responseType = config.responseType;
709 } catch (e) {
710 if (request.responseType !== 'json') {
711 throw e;
712 }
713 }
714 }
715
716 // Handle progress if needed
717 if (typeof config.onDownloadProgress === 'function') {
718 request.addEventListener('progress', config.onDownloadProgress);
719 }
720
721 // Not all browsers support upload events
722 if (typeof config.onUploadProgress === 'function' && request.upload) {
723 request.upload.addEventListener('progress', config.onUploadProgress);
724 }
725
726 if (config.cancelToken) {
727 // Handle cancellation
728 config.cancelToken.promise.then(function onCanceled(cancel) {
729 if (!request) {
730 return;
731 }
732
733 request.abort();
734 reject(cancel);
735 // Clean up request
736 request = null;
737 });
738 }
739
740 if (requestData === undefined) {
741 requestData = null;
742 }
743
744 // Send the request
745 request.send(requestData);
746 });
747};
748
749}).call(this,require('_process'))
750},{"../core/createError":15,"./../core/settle":18,"./../helpers/btoa":22,"./../helpers/buildURL":23,"./../helpers/cookies":25,"./../helpers/isURLSameOrigin":27,"./../helpers/parseHeaders":29,"./../utils":31,"_process":38}],9:[function(require,module,exports){
751'use strict';
752
753var utils = require('./utils');
754var bind = require('./helpers/bind');
755var Axios = require('./core/Axios');
756var defaults = require('./defaults');
757
758/**
759 * Create an instance of Axios
760 *
761 * @param {Object} defaultConfig The default config for the instance
762 * @return {Axios} A new instance of Axios
763 */
764function createInstance(defaultConfig) {
765 var context = new Axios(defaultConfig);
766 var instance = bind(Axios.prototype.request, context);
767
768 // Copy axios.prototype to instance
769 utils.extend(instance, Axios.prototype, context);
770
771 // Copy context to instance
772 utils.extend(instance, context);
773
774 return instance;
775}
776
777// Create the default instance to be exported
778var axios = createInstance(defaults);
779
780// Expose Axios class to allow class inheritance
781axios.Axios = Axios;
782
783// Factory for creating new instances
784axios.create = function create(instanceConfig) {
785 return createInstance(utils.merge(defaults, instanceConfig));
786};
787
788// Expose Cancel & CancelToken
789axios.Cancel = require('./cancel/Cancel');
790axios.CancelToken = require('./cancel/CancelToken');
791axios.isCancel = require('./cancel/isCancel');
792
793// Expose all/spread
794axios.all = function all(promises) {
795 return Promise.all(promises);
796};
797axios.spread = require('./helpers/spread');
798
799module.exports = axios;
800
801// Allow use of default import syntax in TypeScript
802module.exports.default = axios;
803
804},{"./cancel/Cancel":10,"./cancel/CancelToken":11,"./cancel/isCancel":12,"./core/Axios":13,"./defaults":20,"./helpers/bind":21,"./helpers/spread":30,"./utils":31}],10:[function(require,module,exports){
805'use strict';
806
807/**
808 * A `Cancel` is an object that is thrown when an operation is canceled.
809 *
810 * @class
811 * @param {string=} message The message.
812 */
813function Cancel(message) {
814 this.message = message;
815}
816
817Cancel.prototype.toString = function toString() {
818 return 'Cancel' + (this.message ? ': ' + this.message : '');
819};
820
821Cancel.prototype.__CANCEL__ = true;
822
823module.exports = Cancel;
824
825},{}],11:[function(require,module,exports){
826'use strict';
827
828var Cancel = require('./Cancel');
829
830/**
831 * A `CancelToken` is an object that can be used to request cancellation of an operation.
832 *
833 * @class
834 * @param {Function} executor The executor function.
835 */
836function CancelToken(executor) {
837 if (typeof executor !== 'function') {
838 throw new TypeError('executor must be a function.');
839 }
840
841 var resolvePromise;
842 this.promise = new Promise(function promiseExecutor(resolve) {
843 resolvePromise = resolve;
844 });
845
846 var token = this;
847 executor(function cancel(message) {
848 if (token.reason) {
849 // Cancellation has already been requested
850 return;
851 }
852
853 token.reason = new Cancel(message);
854 resolvePromise(token.reason);
855 });
856}
857
858/**
859 * Throws a `Cancel` if cancellation has been requested.
860 */
861CancelToken.prototype.throwIfRequested = function throwIfRequested() {
862 if (this.reason) {
863 throw this.reason;
864 }
865};
866
867/**
868 * Returns an object that contains a new `CancelToken` and a function that, when called,
869 * cancels the `CancelToken`.
870 */
871CancelToken.source = function source() {
872 var cancel;
873 var token = new CancelToken(function executor(c) {
874 cancel = c;
875 });
876 return {
877 token: token,
878 cancel: cancel
879 };
880};
881
882module.exports = CancelToken;
883
884},{"./Cancel":10}],12:[function(require,module,exports){
885'use strict';
886
887module.exports = function isCancel(value) {
888 return !!(value && value.__CANCEL__);
889};
890
891},{}],13:[function(require,module,exports){
892'use strict';
893
894var defaults = require('./../defaults');
895var utils = require('./../utils');
896var InterceptorManager = require('./InterceptorManager');
897var dispatchRequest = require('./dispatchRequest');
898var isAbsoluteURL = require('./../helpers/isAbsoluteURL');
899var combineURLs = require('./../helpers/combineURLs');
900
901/**
902 * Create a new instance of Axios
903 *
904 * @param {Object} instanceConfig The default config for the instance
905 */
906function Axios(instanceConfig) {
907 this.defaults = instanceConfig;
908 this.interceptors = {
909 request: new InterceptorManager(),
910 response: new InterceptorManager()
911 };
912}
913
914/**
915 * Dispatch a request
916 *
917 * @param {Object} config The config specific for this request (merged with this.defaults)
918 */
919Axios.prototype.request = function request(config) {
920 /*eslint no-param-reassign:0*/
921 // Allow for axios('example/url'[, config]) a la fetch API
922 if (typeof config === 'string') {
923 config = utils.merge({
924 url: arguments[0]
925 }, arguments[1]);
926 }
927
928 config = utils.merge(defaults, this.defaults, { method: 'get' }, config);
929
930 // Support baseURL config
931 if (config.baseURL && !isAbsoluteURL(config.url)) {
932 config.url = combineURLs(config.baseURL, config.url);
933 }
934
935 // Hook up interceptors middleware
936 var chain = [dispatchRequest, undefined];
937 var promise = Promise.resolve(config);
938
939 this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
940 chain.unshift(interceptor.fulfilled, interceptor.rejected);
941 });
942
943 this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
944 chain.push(interceptor.fulfilled, interceptor.rejected);
945 });
946
947 while (chain.length) {
948 promise = promise.then(chain.shift(), chain.shift());
949 }
950
951 return promise;
952};
953
954// Provide aliases for supported request methods
955utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
956 /*eslint func-names:0*/
957 Axios.prototype[method] = function(url, config) {
958 return this.request(utils.merge(config || {}, {
959 method: method,
960 url: url
961 }));
962 };
963});
964
965utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
966 /*eslint func-names:0*/
967 Axios.prototype[method] = function(url, data, config) {
968 return this.request(utils.merge(config || {}, {
969 method: method,
970 url: url,
971 data: data
972 }));
973 };
974});
975
976module.exports = Axios;
977
978},{"./../defaults":20,"./../helpers/combineURLs":24,"./../helpers/isAbsoluteURL":26,"./../utils":31,"./InterceptorManager":14,"./dispatchRequest":16}],14:[function(require,module,exports){
979'use strict';
980
981var utils = require('./../utils');
982
983function InterceptorManager() {
984 this.handlers = [];
985}
986
987/**
988 * Add a new interceptor to the stack
989 *
990 * @param {Function} fulfilled The function to handle `then` for a `Promise`
991 * @param {Function} rejected The function to handle `reject` for a `Promise`
992 *
993 * @return {Number} An ID used to remove interceptor later
994 */
995InterceptorManager.prototype.use = function use(fulfilled, rejected) {
996 this.handlers.push({
997 fulfilled: fulfilled,
998 rejected: rejected
999 });
1000 return this.handlers.length - 1;
1001};
1002
1003/**
1004 * Remove an interceptor from the stack
1005 *
1006 * @param {Number} id The ID that was returned by `use`
1007 */
1008InterceptorManager.prototype.eject = function eject(id) {
1009 if (this.handlers[id]) {
1010 this.handlers[id] = null;
1011 }
1012};
1013
1014/**
1015 * Iterate over all the registered interceptors
1016 *
1017 * This method is particularly useful for skipping over any
1018 * interceptors that may have become `null` calling `eject`.
1019 *
1020 * @param {Function} fn The function to call for each interceptor
1021 */
1022InterceptorManager.prototype.forEach = function forEach(fn) {
1023 utils.forEach(this.handlers, function forEachHandler(h) {
1024 if (h !== null) {
1025 fn(h);
1026 }
1027 });
1028};
1029
1030module.exports = InterceptorManager;
1031
1032},{"./../utils":31}],15:[function(require,module,exports){
1033'use strict';
1034
1035var enhanceError = require('./enhanceError');
1036
1037/**
1038 * Create an Error with the specified message, config, error code, and response.
1039 *
1040 * @param {string} message The error message.
1041 * @param {Object} config The config.
1042 * @param {string} [code] The error code (for example, 'ECONNABORTED').
1043 @ @param {Object} [response] The response.
1044 * @returns {Error} The created error.
1045 */
1046module.exports = function createError(message, config, code, response) {
1047 var error = new Error(message);
1048 return enhanceError(error, config, code, response);
1049};
1050
1051},{"./enhanceError":17}],16:[function(require,module,exports){
1052'use strict';
1053
1054var utils = require('./../utils');
1055var transformData = require('./transformData');
1056var isCancel = require('../cancel/isCancel');
1057var defaults = require('../defaults');
1058
1059/**
1060 * Throws a `Cancel` if cancellation has been requested.
1061 */
1062function throwIfCancellationRequested(config) {
1063 if (config.cancelToken) {
1064 config.cancelToken.throwIfRequested();
1065 }
1066}
1067
1068/**
1069 * Dispatch a request to the server using the configured adapter.
1070 *
1071 * @param {object} config The config that is to be used for the request
1072 * @returns {Promise} The Promise to be fulfilled
1073 */
1074module.exports = function dispatchRequest(config) {
1075 throwIfCancellationRequested(config);
1076
1077 // Ensure headers exist
1078 config.headers = config.headers || {};
1079
1080 // Transform request data
1081 config.data = transformData(
1082 config.data,
1083 config.headers,
1084 config.transformRequest
1085 );
1086
1087 // Flatten headers
1088 config.headers = utils.merge(
1089 config.headers.common || {},
1090 config.headers[config.method] || {},
1091 config.headers || {}
1092 );
1093
1094 utils.forEach(
1095 ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
1096 function cleanHeaderConfig(method) {
1097 delete config.headers[method];
1098 }
1099 );
1100
1101 var adapter = config.adapter || defaults.adapter;
1102
1103 return adapter(config).then(function onAdapterResolution(response) {
1104 throwIfCancellationRequested(config);
1105
1106 // Transform response data
1107 response.data = transformData(
1108 response.data,
1109 response.headers,
1110 config.transformResponse
1111 );
1112
1113 return response;
1114 }, function onAdapterRejection(reason) {
1115 if (!isCancel(reason)) {
1116 throwIfCancellationRequested(config);
1117
1118 // Transform response data
1119 if (reason && reason.response) {
1120 reason.response.data = transformData(
1121 reason.response.data,
1122 reason.response.headers,
1123 config.transformResponse
1124 );
1125 }
1126 }
1127
1128 return Promise.reject(reason);
1129 });
1130};
1131
1132},{"../cancel/isCancel":12,"../defaults":20,"./../utils":31,"./transformData":19}],17:[function(require,module,exports){
1133'use strict';
1134
1135/**
1136 * Update an Error with the specified config, error code, and response.
1137 *
1138 * @param {Error} error The error to update.
1139 * @param {Object} config The config.
1140 * @param {string} [code] The error code (for example, 'ECONNABORTED').
1141 @ @param {Object} [response] The response.
1142 * @returns {Error} The error.
1143 */
1144module.exports = function enhanceError(error, config, code, response) {
1145 error.config = config;
1146 if (code) {
1147 error.code = code;
1148 }
1149 error.response = response;
1150 return error;
1151};
1152
1153},{}],18:[function(require,module,exports){
1154'use strict';
1155
1156var createError = require('./createError');
1157
1158/**
1159 * Resolve or reject a Promise based on response status.
1160 *
1161 * @param {Function} resolve A function that resolves the promise.
1162 * @param {Function} reject A function that rejects the promise.
1163 * @param {object} response The response.
1164 */
1165module.exports = function settle(resolve, reject, response) {
1166 var validateStatus = response.config.validateStatus;
1167 // Note: status is not exposed by XDomainRequest
1168 if (!response.status || !validateStatus || validateStatus(response.status)) {
1169 resolve(response);
1170 } else {
1171 reject(createError(
1172 'Request failed with status code ' + response.status,
1173 response.config,
1174 null,
1175 response
1176 ));
1177 }
1178};
1179
1180},{"./createError":15}],19:[function(require,module,exports){
1181'use strict';
1182
1183var utils = require('./../utils');
1184
1185/**
1186 * Transform the data for a request or a response
1187 *
1188 * @param {Object|String} data The data to be transformed
1189 * @param {Array} headers The headers for the request or response
1190 * @param {Array|Function} fns A single function or Array of functions
1191 * @returns {*} The resulting transformed data
1192 */
1193module.exports = function transformData(data, headers, fns) {
1194 /*eslint no-param-reassign:0*/
1195 utils.forEach(fns, function transform(fn) {
1196 data = fn(data, headers);
1197 });
1198
1199 return data;
1200};
1201
1202},{"./../utils":31}],20:[function(require,module,exports){
1203(function (process){
1204'use strict';
1205
1206var utils = require('./utils');
1207var normalizeHeaderName = require('./helpers/normalizeHeaderName');
1208
1209var PROTECTION_PREFIX = /^\)\]\}',?\n/;
1210var DEFAULT_CONTENT_TYPE = {
1211 'Content-Type': 'application/x-www-form-urlencoded'
1212};
1213
1214function setContentTypeIfUnset(headers, value) {
1215 if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
1216 headers['Content-Type'] = value;
1217 }
1218}
1219
1220function getDefaultAdapter() {
1221 var adapter;
1222 if (typeof XMLHttpRequest !== 'undefined') {
1223 // For browsers use XHR adapter
1224 adapter = require('./adapters/xhr');
1225 } else if (typeof process !== 'undefined') {
1226 // For node use HTTP adapter
1227 adapter = require('./adapters/http');
1228 }
1229 return adapter;
1230}
1231
1232var defaults = {
1233 adapter: getDefaultAdapter(),
1234
1235 transformRequest: [function transformRequest(data, headers) {
1236 normalizeHeaderName(headers, 'Content-Type');
1237 if (utils.isFormData(data) ||
1238 utils.isArrayBuffer(data) ||
1239 utils.isStream(data) ||
1240 utils.isFile(data) ||
1241 utils.isBlob(data)
1242 ) {
1243 return data;
1244 }
1245 if (utils.isArrayBufferView(data)) {
1246 return data.buffer;
1247 }
1248 if (utils.isURLSearchParams(data)) {
1249 setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
1250 return data.toString();
1251 }
1252 if (utils.isObject(data)) {
1253 setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
1254 return JSON.stringify(data);
1255 }
1256 return data;
1257 }],
1258
1259 transformResponse: [function transformResponse(data) {
1260 /*eslint no-param-reassign:0*/
1261 if (typeof data === 'string') {
1262 data = data.replace(PROTECTION_PREFIX, '');
1263 try {
1264 data = JSON.parse(data);
1265 } catch (e) { /* Ignore */ }
1266 }
1267 return data;
1268 }],
1269
1270 timeout: 0,
1271
1272 xsrfCookieName: 'XSRF-TOKEN',
1273 xsrfHeaderName: 'X-XSRF-TOKEN',
1274
1275 maxContentLength: -1,
1276
1277 validateStatus: function validateStatus(status) {
1278 return status >= 200 && status < 300;
1279 }
1280};
1281
1282defaults.headers = {
1283 common: {
1284 'Accept': 'application/json, text/plain, */*'
1285 }
1286};
1287
1288utils.forEach(['delete', 'get', 'head'], function forEachMehtodNoData(method) {
1289 defaults.headers[method] = {};
1290});
1291
1292utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
1293 defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
1294});
1295
1296module.exports = defaults;
1297
1298}).call(this,require('_process'))
1299},{"./adapters/http":8,"./adapters/xhr":8,"./helpers/normalizeHeaderName":28,"./utils":31,"_process":38}],21:[function(require,module,exports){
1300'use strict';
1301
1302module.exports = function bind(fn, thisArg) {
1303 return function wrap() {
1304 var args = new Array(arguments.length);
1305 for (var i = 0; i < args.length; i++) {
1306 args[i] = arguments[i];
1307 }
1308 return fn.apply(thisArg, args);
1309 };
1310};
1311
1312},{}],22:[function(require,module,exports){
1313'use strict';
1314
1315// btoa polyfill for IE<10 courtesy https://github.com/davidchambers/Base64.js
1316
1317var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
1318
1319function E() {
1320 this.message = 'String contains an invalid character';
1321}
1322E.prototype = new Error;
1323E.prototype.code = 5;
1324E.prototype.name = 'InvalidCharacterError';
1325
1326function btoa(input) {
1327 var str = String(input);
1328 var output = '';
1329 for (
1330 // initialize result and counter
1331 var block, charCode, idx = 0, map = chars;
1332 // if the next str index does not exist:
1333 // change the mapping table to "="
1334 // check if d has no fractional digits
1335 str.charAt(idx | 0) || (map = '=', idx % 1);
1336 // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
1337 output += map.charAt(63 & block >> 8 - idx % 1 * 8)
1338 ) {
1339 charCode = str.charCodeAt(idx += 3 / 4);
1340 if (charCode > 0xFF) {
1341 throw new E();
1342 }
1343 block = block << 8 | charCode;
1344 }
1345 return output;
1346}
1347
1348module.exports = btoa;
1349
1350},{}],23:[function(require,module,exports){
1351'use strict';
1352
1353var utils = require('./../utils');
1354
1355function encode(val) {
1356 return encodeURIComponent(val).
1357 replace(/%40/gi, '@').
1358 replace(/%3A/gi, ':').
1359 replace(/%24/g, '$').
1360 replace(/%2C/gi, ',').
1361 replace(/%20/g, '+').
1362 replace(/%5B/gi, '[').
1363 replace(/%5D/gi, ']');
1364}
1365
1366/**
1367 * Build a URL by appending params to the end
1368 *
1369 * @param {string} url The base of the url (e.g., http://www.google.com)
1370 * @param {object} [params] The params to be appended
1371 * @returns {string} The formatted url
1372 */
1373module.exports = function buildURL(url, params, paramsSerializer) {
1374 /*eslint no-param-reassign:0*/
1375 if (!params) {
1376 return url;
1377 }
1378
1379 var serializedParams;
1380 if (paramsSerializer) {
1381 serializedParams = paramsSerializer(params);
1382 } else if (utils.isURLSearchParams(params)) {
1383 serializedParams = params.toString();
1384 } else {
1385 var parts = [];
1386
1387 utils.forEach(params, function serialize(val, key) {
1388 if (val === null || typeof val === 'undefined') {
1389 return;
1390 }
1391
1392 if (utils.isArray(val)) {
1393 key = key + '[]';
1394 }
1395
1396 if (!utils.isArray(val)) {
1397 val = [val];
1398 }
1399
1400 utils.forEach(val, function parseValue(v) {
1401 if (utils.isDate(v)) {
1402 v = v.toISOString();
1403 } else if (utils.isObject(v)) {
1404 v = JSON.stringify(v);
1405 }
1406 parts.push(encode(key) + '=' + encode(v));
1407 });
1408 });
1409
1410 serializedParams = parts.join('&');
1411 }
1412
1413 if (serializedParams) {
1414 url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
1415 }
1416
1417 return url;
1418};
1419
1420},{"./../utils":31}],24:[function(require,module,exports){
1421'use strict';
1422
1423/**
1424 * Creates a new URL by combining the specified URLs
1425 *
1426 * @param {string} baseURL The base URL
1427 * @param {string} relativeURL The relative URL
1428 * @returns {string} The combined URL
1429 */
1430module.exports = function combineURLs(baseURL, relativeURL) {
1431 return baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '');
1432};
1433
1434},{}],25:[function(require,module,exports){
1435'use strict';
1436
1437var utils = require('./../utils');
1438
1439module.exports = (
1440 utils.isStandardBrowserEnv() ?
1441
1442 // Standard browser envs support document.cookie
1443 (function standardBrowserEnv() {
1444 return {
1445 write: function write(name, value, expires, path, domain, secure) {
1446 var cookie = [];
1447 cookie.push(name + '=' + encodeURIComponent(value));
1448
1449 if (utils.isNumber(expires)) {
1450 cookie.push('expires=' + new Date(expires).toGMTString());
1451 }
1452
1453 if (utils.isString(path)) {
1454 cookie.push('path=' + path);
1455 }
1456
1457 if (utils.isString(domain)) {
1458 cookie.push('domain=' + domain);
1459 }
1460
1461 if (secure === true) {
1462 cookie.push('secure');
1463 }
1464
1465 document.cookie = cookie.join('; ');
1466 },
1467
1468 read: function read(name) {
1469 var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
1470 return (match ? decodeURIComponent(match[3]) : null);
1471 },
1472
1473 remove: function remove(name) {
1474 this.write(name, '', Date.now() - 86400000);
1475 }
1476 };
1477 })() :
1478
1479 // Non standard browser env (web workers, react-native) lack needed support.
1480 (function nonStandardBrowserEnv() {
1481 return {
1482 write: function write() {},
1483 read: function read() { return null; },
1484 remove: function remove() {}
1485 };
1486 })()
1487);
1488
1489},{"./../utils":31}],26:[function(require,module,exports){
1490'use strict';
1491
1492/**
1493 * Determines whether the specified URL is absolute
1494 *
1495 * @param {string} url The URL to test
1496 * @returns {boolean} True if the specified URL is absolute, otherwise false
1497 */
1498module.exports = function isAbsoluteURL(url) {
1499 // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
1500 // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
1501 // by any combination of letters, digits, plus, period, or hyphen.
1502 return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
1503};
1504
1505},{}],27:[function(require,module,exports){
1506'use strict';
1507
1508var utils = require('./../utils');
1509
1510module.exports = (
1511 utils.isStandardBrowserEnv() ?
1512
1513 // Standard browser envs have full support of the APIs needed to test
1514 // whether the request URL is of the same origin as current location.
1515 (function standardBrowserEnv() {
1516 var msie = /(msie|trident)/i.test(navigator.userAgent);
1517 var urlParsingNode = document.createElement('a');
1518 var originURL;
1519
1520 /**
1521 * Parse a URL to discover it's components
1522 *
1523 * @param {String} url The URL to be parsed
1524 * @returns {Object}
1525 */
1526 function resolveURL(url) {
1527 var href = url;
1528
1529 if (msie) {
1530 // IE needs attribute set twice to normalize properties
1531 urlParsingNode.setAttribute('href', href);
1532 href = urlParsingNode.href;
1533 }
1534
1535 urlParsingNode.setAttribute('href', href);
1536
1537 // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
1538 return {
1539 href: urlParsingNode.href,
1540 protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
1541 host: urlParsingNode.host,
1542 search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
1543 hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
1544 hostname: urlParsingNode.hostname,
1545 port: urlParsingNode.port,
1546 pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
1547 urlParsingNode.pathname :
1548 '/' + urlParsingNode.pathname
1549 };
1550 }
1551
1552 originURL = resolveURL(window.location.href);
1553
1554 /**
1555 * Determine if a URL shares the same origin as the current location
1556 *
1557 * @param {String} requestURL The URL to test
1558 * @returns {boolean} True if URL shares the same origin, otherwise false
1559 */
1560 return function isURLSameOrigin(requestURL) {
1561 var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
1562 return (parsed.protocol === originURL.protocol &&
1563 parsed.host === originURL.host);
1564 };
1565 })() :
1566
1567 // Non standard browser envs (web workers, react-native) lack needed support.
1568 (function nonStandardBrowserEnv() {
1569 return function isURLSameOrigin() {
1570 return true;
1571 };
1572 })()
1573);
1574
1575},{"./../utils":31}],28:[function(require,module,exports){
1576'use strict';
1577
1578var utils = require('../utils');
1579
1580module.exports = function normalizeHeaderName(headers, normalizedName) {
1581 utils.forEach(headers, function processHeader(value, name) {
1582 if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
1583 headers[normalizedName] = value;
1584 delete headers[name];
1585 }
1586 });
1587};
1588
1589},{"../utils":31}],29:[function(require,module,exports){
1590'use strict';
1591
1592var utils = require('./../utils');
1593
1594/**
1595 * Parse headers into an object
1596 *
1597 * ```
1598 * Date: Wed, 27 Aug 2014 08:58:49 GMT
1599 * Content-Type: application/json
1600 * Connection: keep-alive
1601 * Transfer-Encoding: chunked
1602 * ```
1603 *
1604 * @param {String} headers Headers needing to be parsed
1605 * @returns {Object} Headers parsed into an object
1606 */
1607module.exports = function parseHeaders(headers) {
1608 var parsed = {};
1609 var key;
1610 var val;
1611 var i;
1612
1613 if (!headers) { return parsed; }
1614
1615 utils.forEach(headers.split('\n'), function parser(line) {
1616 i = line.indexOf(':');
1617 key = utils.trim(line.substr(0, i)).toLowerCase();
1618 val = utils.trim(line.substr(i + 1));
1619
1620 if (key) {
1621 parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
1622 }
1623 });
1624
1625 return parsed;
1626};
1627
1628},{"./../utils":31}],30:[function(require,module,exports){
1629'use strict';
1630
1631/**
1632 * Syntactic sugar for invoking a function and expanding an array for arguments.
1633 *
1634 * Common use case would be to use `Function.prototype.apply`.
1635 *
1636 * ```js
1637 * function f(x, y, z) {}
1638 * var args = [1, 2, 3];
1639 * f.apply(null, args);
1640 * ```
1641 *
1642 * With `spread` this example can be re-written.
1643 *
1644 * ```js
1645 * spread(function(x, y, z) {})([1, 2, 3]);
1646 * ```
1647 *
1648 * @param {Function} callback
1649 * @returns {Function}
1650 */
1651module.exports = function spread(callback) {
1652 return function wrap(arr) {
1653 return callback.apply(null, arr);
1654 };
1655};
1656
1657},{}],31:[function(require,module,exports){
1658'use strict';
1659
1660var bind = require('./helpers/bind');
1661
1662/*global toString:true*/
1663
1664// utils is a library of generic helper functions non-specific to axios
1665
1666var toString = Object.prototype.toString;
1667
1668/**
1669 * Determine if a value is an Array
1670 *
1671 * @param {Object} val The value to test
1672 * @returns {boolean} True if value is an Array, otherwise false
1673 */
1674function isArray(val) {
1675 return toString.call(val) === '[object Array]';
1676}
1677
1678/**
1679 * Determine if a value is an ArrayBuffer
1680 *
1681 * @param {Object} val The value to test
1682 * @returns {boolean} True if value is an ArrayBuffer, otherwise false
1683 */
1684function isArrayBuffer(val) {
1685 return toString.call(val) === '[object ArrayBuffer]';
1686}
1687
1688/**
1689 * Determine if a value is a FormData
1690 *
1691 * @param {Object} val The value to test
1692 * @returns {boolean} True if value is an FormData, otherwise false
1693 */
1694function isFormData(val) {
1695 return (typeof FormData !== 'undefined') && (val instanceof FormData);
1696}
1697
1698/**
1699 * Determine if a value is a view on an ArrayBuffer
1700 *
1701 * @param {Object} val The value to test
1702 * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
1703 */
1704function isArrayBufferView(val) {
1705 var result;
1706 if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
1707 result = ArrayBuffer.isView(val);
1708 } else {
1709 result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
1710 }
1711 return result;
1712}
1713
1714/**
1715 * Determine if a value is a String
1716 *
1717 * @param {Object} val The value to test
1718 * @returns {boolean} True if value is a String, otherwise false
1719 */
1720function isString(val) {
1721 return typeof val === 'string';
1722}
1723
1724/**
1725 * Determine if a value is a Number
1726 *
1727 * @param {Object} val The value to test
1728 * @returns {boolean} True if value is a Number, otherwise false
1729 */
1730function isNumber(val) {
1731 return typeof val === 'number';
1732}
1733
1734/**
1735 * Determine if a value is undefined
1736 *
1737 * @param {Object} val The value to test
1738 * @returns {boolean} True if the value is undefined, otherwise false
1739 */
1740function isUndefined(val) {
1741 return typeof val === 'undefined';
1742}
1743
1744/**
1745 * Determine if a value is an Object
1746 *
1747 * @param {Object} val The value to test
1748 * @returns {boolean} True if value is an Object, otherwise false
1749 */
1750function isObject(val) {
1751 return val !== null && typeof val === 'object';
1752}
1753
1754/**
1755 * Determine if a value is a Date
1756 *
1757 * @param {Object} val The value to test
1758 * @returns {boolean} True if value is a Date, otherwise false
1759 */
1760function isDate(val) {
1761 return toString.call(val) === '[object Date]';
1762}
1763
1764/**
1765 * Determine if a value is a File
1766 *
1767 * @param {Object} val The value to test
1768 * @returns {boolean} True if value is a File, otherwise false
1769 */
1770function isFile(val) {
1771 return toString.call(val) === '[object File]';
1772}
1773
1774/**
1775 * Determine if a value is a Blob
1776 *
1777 * @param {Object} val The value to test
1778 * @returns {boolean} True if value is a Blob, otherwise false
1779 */
1780function isBlob(val) {
1781 return toString.call(val) === '[object Blob]';
1782}
1783
1784/**
1785 * Determine if a value is a Function
1786 *
1787 * @param {Object} val The value to test
1788 * @returns {boolean} True if value is a Function, otherwise false
1789 */
1790function isFunction(val) {
1791 return toString.call(val) === '[object Function]';
1792}
1793
1794/**
1795 * Determine if a value is a Stream
1796 *
1797 * @param {Object} val The value to test
1798 * @returns {boolean} True if value is a Stream, otherwise false
1799 */
1800function isStream(val) {
1801 return isObject(val) && isFunction(val.pipe);
1802}
1803
1804/**
1805 * Determine if a value is a URLSearchParams object
1806 *
1807 * @param {Object} val The value to test
1808 * @returns {boolean} True if value is a URLSearchParams object, otherwise false
1809 */
1810function isURLSearchParams(val) {
1811 return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;
1812}
1813
1814/**
1815 * Trim excess whitespace off the beginning and end of a string
1816 *
1817 * @param {String} str The String to trim
1818 * @returns {String} The String freed of excess whitespace
1819 */
1820function trim(str) {
1821 return str.replace(/^\s*/, '').replace(/\s*$/, '');
1822}
1823
1824/**
1825 * Determine if we're running in a standard browser environment
1826 *
1827 * This allows axios to run in a web worker, and react-native.
1828 * Both environments support XMLHttpRequest, but not fully standard globals.
1829 *
1830 * web workers:
1831 * typeof window -> undefined
1832 * typeof document -> undefined
1833 *
1834 * react-native:
1835 * typeof document.createElement -> undefined
1836 */
1837function isStandardBrowserEnv() {
1838 return (
1839 typeof window !== 'undefined' &&
1840 typeof document !== 'undefined' &&
1841 typeof document.createElement === 'function'
1842 );
1843}
1844
1845/**
1846 * Iterate over an Array or an Object invoking a function for each item.
1847 *
1848 * If `obj` is an Array callback will be called passing
1849 * the value, index, and complete array for each item.
1850 *
1851 * If 'obj' is an Object callback will be called passing
1852 * the value, key, and complete object for each property.
1853 *
1854 * @param {Object|Array} obj The object to iterate
1855 * @param {Function} fn The callback to invoke for each item
1856 */
1857function forEach(obj, fn) {
1858 // Don't bother if no value provided
1859 if (obj === null || typeof obj === 'undefined') {
1860 return;
1861 }
1862
1863 // Force an array if not already something iterable
1864 if (typeof obj !== 'object' && !isArray(obj)) {
1865 /*eslint no-param-reassign:0*/
1866 obj = [obj];
1867 }
1868
1869 if (isArray(obj)) {
1870 // Iterate over array values
1871 for (var i = 0, l = obj.length; i < l; i++) {
1872 fn.call(null, obj[i], i, obj);
1873 }
1874 } else {
1875 // Iterate over object keys
1876 for (var key in obj) {
1877 if (Object.prototype.hasOwnProperty.call(obj, key)) {
1878 fn.call(null, obj[key], key, obj);
1879 }
1880 }
1881 }
1882}
1883
1884/**
1885 * Accepts varargs expecting each argument to be an object, then
1886 * immutably merges the properties of each object and returns result.
1887 *
1888 * When multiple objects contain the same key the later object in
1889 * the arguments list will take precedence.
1890 *
1891 * Example:
1892 *
1893 * ```js
1894 * var result = merge({foo: 123}, {foo: 456});
1895 * console.log(result.foo); // outputs 456
1896 * ```
1897 *
1898 * @param {Object} obj1 Object to merge
1899 * @returns {Object} Result of all merge properties
1900 */
1901function merge(/* obj1, obj2, obj3, ... */) {
1902 var result = {};
1903 function assignValue(val, key) {
1904 if (typeof result[key] === 'object' && typeof val === 'object') {
1905 result[key] = merge(result[key], val);
1906 } else {
1907 result[key] = val;
1908 }
1909 }
1910
1911 for (var i = 0, l = arguments.length; i < l; i++) {
1912 forEach(arguments[i], assignValue);
1913 }
1914 return result;
1915}
1916
1917/**
1918 * Extends object a by mutably adding to it the properties of object b.
1919 *
1920 * @param {Object} a The object to be extended
1921 * @param {Object} b The object to copy properties from
1922 * @param {Object} thisArg The object to bind function to
1923 * @return {Object} The resulting value of object a
1924 */
1925function extend(a, b, thisArg) {
1926 forEach(b, function assignValue(val, key) {
1927 if (thisArg && typeof val === 'function') {
1928 a[key] = bind(val, thisArg);
1929 } else {
1930 a[key] = val;
1931 }
1932 });
1933 return a;
1934}
1935
1936module.exports = {
1937 isArray: isArray,
1938 isArrayBuffer: isArrayBuffer,
1939 isFormData: isFormData,
1940 isArrayBufferView: isArrayBufferView,
1941 isString: isString,
1942 isNumber: isNumber,
1943 isObject: isObject,
1944 isUndefined: isUndefined,
1945 isDate: isDate,
1946 isFile: isFile,
1947 isBlob: isBlob,
1948 isFunction: isFunction,
1949 isStream: isStream,
1950 isURLSearchParams: isURLSearchParams,
1951 isStandardBrowserEnv: isStandardBrowserEnv,
1952 forEach: forEach,
1953 merge: merge,
1954 extend: extend,
1955 trim: trim
1956};
1957
1958},{"./helpers/bind":21}],32:[function(require,module,exports){
1959;(function (root, factory) {
1960 if (typeof exports === "object") {
1961 // CommonJS
1962 module.exports = exports = factory();
1963 }
1964 else if (typeof define === "function" && define.amd) {
1965 // AMD
1966 define([], factory);
1967 }
1968 else {
1969 // Global (browser)
1970 root.CryptoJS = factory();
1971 }
1972}(this, function () {
1973
1974 /**
1975 * CryptoJS core components.
1976 */
1977 var CryptoJS = CryptoJS || (function (Math, undefined) {
1978 /*
1979 * Local polyfil of Object.create
1980 */
1981 var create = Object.create || (function () {
1982 function F() {};
1983
1984 return function (obj) {
1985 var subtype;
1986
1987 F.prototype = obj;
1988
1989 subtype = new F();
1990
1991 F.prototype = null;
1992
1993 return subtype;
1994 };
1995 }())
1996
1997 /**
1998 * CryptoJS namespace.
1999 */
2000 var C = {};
2001
2002 /**
2003 * Library namespace.
2004 */
2005 var C_lib = C.lib = {};
2006
2007 /**
2008 * Base object for prototypal inheritance.
2009 */
2010 var Base = C_lib.Base = (function () {
2011
2012
2013 return {
2014 /**
2015 * Creates a new object that inherits from this object.
2016 *
2017 * @param {Object} overrides Properties to copy into the new object.
2018 *
2019 * @return {Object} The new object.
2020 *
2021 * @static
2022 *
2023 * @example
2024 *
2025 * var MyType = CryptoJS.lib.Base.extend({
2026 * field: 'value',
2027 *
2028 * method: function () {
2029 * }
2030 * });
2031 */
2032 extend: function (overrides) {
2033 // Spawn
2034 var subtype = create(this);
2035
2036 // Augment
2037 if (overrides) {
2038 subtype.mixIn(overrides);
2039 }
2040
2041 // Create default initializer
2042 if (!subtype.hasOwnProperty('init') || this.init === subtype.init) {
2043 subtype.init = function () {
2044 subtype.$super.init.apply(this, arguments);
2045 };
2046 }
2047
2048 // Initializer's prototype is the subtype object
2049 subtype.init.prototype = subtype;
2050
2051 // Reference supertype
2052 subtype.$super = this;
2053
2054 return subtype;
2055 },
2056
2057 /**
2058 * Extends this object and runs the init method.
2059 * Arguments to create() will be passed to init().
2060 *
2061 * @return {Object} The new object.
2062 *
2063 * @static
2064 *
2065 * @example
2066 *
2067 * var instance = MyType.create();
2068 */
2069 create: function () {
2070 var instance = this.extend();
2071 instance.init.apply(instance, arguments);
2072
2073 return instance;
2074 },
2075
2076 /**
2077 * Initializes a newly created object.
2078 * Override this method to add some logic when your objects are created.
2079 *
2080 * @example
2081 *
2082 * var MyType = CryptoJS.lib.Base.extend({
2083 * init: function () {
2084 * // ...
2085 * }
2086 * });
2087 */
2088 init: function () {
2089 },
2090
2091 /**
2092 * Copies properties into this object.
2093 *
2094 * @param {Object} properties The properties to mix in.
2095 *
2096 * @example
2097 *
2098 * MyType.mixIn({
2099 * field: 'value'
2100 * });
2101 */
2102 mixIn: function (properties) {
2103 for (var propertyName in properties) {
2104 if (properties.hasOwnProperty(propertyName)) {
2105 this[propertyName] = properties[propertyName];
2106 }
2107 }
2108
2109 // IE won't copy toString using the loop above
2110 if (properties.hasOwnProperty('toString')) {
2111 this.toString = properties.toString;
2112 }
2113 },
2114
2115 /**
2116 * Creates a copy of this object.
2117 *
2118 * @return {Object} The clone.
2119 *
2120 * @example
2121 *
2122 * var clone = instance.clone();
2123 */
2124 clone: function () {
2125 return this.init.prototype.extend(this);
2126 }
2127 };
2128 }());
2129
2130 /**
2131 * An array of 32-bit words.
2132 *
2133 * @property {Array} words The array of 32-bit words.
2134 * @property {number} sigBytes The number of significant bytes in this word array.
2135 */
2136 var WordArray = C_lib.WordArray = Base.extend({
2137 /**
2138 * Initializes a newly created word array.
2139 *
2140 * @param {Array} words (Optional) An array of 32-bit words.
2141 * @param {number} sigBytes (Optional) The number of significant bytes in the words.
2142 *
2143 * @example
2144 *
2145 * var wordArray = CryptoJS.lib.WordArray.create();
2146 * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
2147 * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
2148 */
2149 init: function (words, sigBytes) {
2150 words = this.words = words || [];
2151
2152 if (sigBytes != undefined) {
2153 this.sigBytes = sigBytes;
2154 } else {
2155 this.sigBytes = words.length * 4;
2156 }
2157 },
2158
2159 /**
2160 * Converts this word array to a string.
2161 *
2162 * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
2163 *
2164 * @return {string} The stringified word array.
2165 *
2166 * @example
2167 *
2168 * var string = wordArray + '';
2169 * var string = wordArray.toString();
2170 * var string = wordArray.toString(CryptoJS.enc.Utf8);
2171 */
2172 toString: function (encoder) {
2173 return (encoder || Hex).stringify(this);
2174 },
2175
2176 /**
2177 * Concatenates a word array to this word array.
2178 *
2179 * @param {WordArray} wordArray The word array to append.
2180 *
2181 * @return {WordArray} This word array.
2182 *
2183 * @example
2184 *
2185 * wordArray1.concat(wordArray2);
2186 */
2187 concat: function (wordArray) {
2188 // Shortcuts
2189 var thisWords = this.words;
2190 var thatWords = wordArray.words;
2191 var thisSigBytes = this.sigBytes;
2192 var thatSigBytes = wordArray.sigBytes;
2193
2194 // Clamp excess bits
2195 this.clamp();
2196
2197 // Concat
2198 if (thisSigBytes % 4) {
2199 // Copy one byte at a time
2200 for (var i = 0; i < thatSigBytes; i++) {
2201 var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
2202 thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
2203 }
2204 } else {
2205 // Copy one word at a time
2206 for (var i = 0; i < thatSigBytes; i += 4) {
2207 thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
2208 }
2209 }
2210 this.sigBytes += thatSigBytes;
2211
2212 // Chainable
2213 return this;
2214 },
2215
2216 /**
2217 * Removes insignificant bits.
2218 *
2219 * @example
2220 *
2221 * wordArray.clamp();
2222 */
2223 clamp: function () {
2224 // Shortcuts
2225 var words = this.words;
2226 var sigBytes = this.sigBytes;
2227
2228 // Clamp
2229 words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
2230 words.length = Math.ceil(sigBytes / 4);
2231 },
2232
2233 /**
2234 * Creates a copy of this word array.
2235 *
2236 * @return {WordArray} The clone.
2237 *
2238 * @example
2239 *
2240 * var clone = wordArray.clone();
2241 */
2242 clone: function () {
2243 var clone = Base.clone.call(this);
2244 clone.words = this.words.slice(0);
2245
2246 return clone;
2247 },
2248
2249 /**
2250 * Creates a word array filled with random bytes.
2251 *
2252 * @param {number} nBytes The number of random bytes to generate.
2253 *
2254 * @return {WordArray} The random word array.
2255 *
2256 * @static
2257 *
2258 * @example
2259 *
2260 * var wordArray = CryptoJS.lib.WordArray.random(16);
2261 */
2262 random: function (nBytes) {
2263 var words = [];
2264
2265 var r = (function (m_w) {
2266 var m_w = m_w;
2267 var m_z = 0x3ade68b1;
2268 var mask = 0xffffffff;
2269
2270 return function () {
2271 m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
2272 m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
2273 var result = ((m_z << 0x10) + m_w) & mask;
2274 result /= 0x100000000;
2275 result += 0.5;
2276 return result * (Math.random() > .5 ? 1 : -1);
2277 }
2278 });
2279
2280 for (var i = 0, rcache; i < nBytes; i += 4) {
2281 var _r = r((rcache || Math.random()) * 0x100000000);
2282
2283 rcache = _r() * 0x3ade67b7;
2284 words.push((_r() * 0x100000000) | 0);
2285 }
2286
2287 return new WordArray.init(words, nBytes);
2288 }
2289 });
2290
2291 /**
2292 * Encoder namespace.
2293 */
2294 var C_enc = C.enc = {};
2295
2296 /**
2297 * Hex encoding strategy.
2298 */
2299 var Hex = C_enc.Hex = {
2300 /**
2301 * Converts a word array to a hex string.
2302 *
2303 * @param {WordArray} wordArray The word array.
2304 *
2305 * @return {string} The hex string.
2306 *
2307 * @static
2308 *
2309 * @example
2310 *
2311 * var hexString = CryptoJS.enc.Hex.stringify(wordArray);
2312 */
2313 stringify: function (wordArray) {
2314 // Shortcuts
2315 var words = wordArray.words;
2316 var sigBytes = wordArray.sigBytes;
2317
2318 // Convert
2319 var hexChars = [];
2320 for (var i = 0; i < sigBytes; i++) {
2321 var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
2322 hexChars.push((bite >>> 4).toString(16));
2323 hexChars.push((bite & 0x0f).toString(16));
2324 }
2325
2326 return hexChars.join('');
2327 },
2328
2329 /**
2330 * Converts a hex string to a word array.
2331 *
2332 * @param {string} hexStr The hex string.
2333 *
2334 * @return {WordArray} The word array.
2335 *
2336 * @static
2337 *
2338 * @example
2339 *
2340 * var wordArray = CryptoJS.enc.Hex.parse(hexString);
2341 */
2342 parse: function (hexStr) {
2343 // Shortcut
2344 var hexStrLength = hexStr.length;
2345
2346 // Convert
2347 var words = [];
2348 for (var i = 0; i < hexStrLength; i += 2) {
2349 words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
2350 }
2351
2352 return new WordArray.init(words, hexStrLength / 2);
2353 }
2354 };
2355
2356 /**
2357 * Latin1 encoding strategy.
2358 */
2359 var Latin1 = C_enc.Latin1 = {
2360 /**
2361 * Converts a word array to a Latin1 string.
2362 *
2363 * @param {WordArray} wordArray The word array.
2364 *
2365 * @return {string} The Latin1 string.
2366 *
2367 * @static
2368 *
2369 * @example
2370 *
2371 * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
2372 */
2373 stringify: function (wordArray) {
2374 // Shortcuts
2375 var words = wordArray.words;
2376 var sigBytes = wordArray.sigBytes;
2377
2378 // Convert
2379 var latin1Chars = [];
2380 for (var i = 0; i < sigBytes; i++) {
2381 var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
2382 latin1Chars.push(String.fromCharCode(bite));
2383 }
2384
2385 return latin1Chars.join('');
2386 },
2387
2388 /**
2389 * Converts a Latin1 string to a word array.
2390 *
2391 * @param {string} latin1Str The Latin1 string.
2392 *
2393 * @return {WordArray} The word array.
2394 *
2395 * @static
2396 *
2397 * @example
2398 *
2399 * var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
2400 */
2401 parse: function (latin1Str) {
2402 // Shortcut
2403 var latin1StrLength = latin1Str.length;
2404
2405 // Convert
2406 var words = [];
2407 for (var i = 0; i < latin1StrLength; i++) {
2408 words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
2409 }
2410
2411 return new WordArray.init(words, latin1StrLength);
2412 }
2413 };
2414
2415 /**
2416 * UTF-8 encoding strategy.
2417 */
2418 var Utf8 = C_enc.Utf8 = {
2419 /**
2420 * Converts a word array to a UTF-8 string.
2421 *
2422 * @param {WordArray} wordArray The word array.
2423 *
2424 * @return {string} The UTF-8 string.
2425 *
2426 * @static
2427 *
2428 * @example
2429 *
2430 * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
2431 */
2432 stringify: function (wordArray) {
2433 try {
2434 return decodeURIComponent(escape(Latin1.stringify(wordArray)));
2435 } catch (e) {
2436 throw new Error('Malformed UTF-8 data');
2437 }
2438 },
2439
2440 /**
2441 * Converts a UTF-8 string to a word array.
2442 *
2443 * @param {string} utf8Str The UTF-8 string.
2444 *
2445 * @return {WordArray} The word array.
2446 *
2447 * @static
2448 *
2449 * @example
2450 *
2451 * var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
2452 */
2453 parse: function (utf8Str) {
2454 return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
2455 }
2456 };
2457
2458 /**
2459 * Abstract buffered block algorithm template.
2460 *
2461 * The property blockSize must be implemented in a concrete subtype.
2462 *
2463 * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
2464 */
2465 var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
2466 /**
2467 * Resets this block algorithm's data buffer to its initial state.
2468 *
2469 * @example
2470 *
2471 * bufferedBlockAlgorithm.reset();
2472 */
2473 reset: function () {
2474 // Initial values
2475 this._data = new WordArray.init();
2476 this._nDataBytes = 0;
2477 },
2478
2479 /**
2480 * Adds new data to this block algorithm's buffer.
2481 *
2482 * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
2483 *
2484 * @example
2485 *
2486 * bufferedBlockAlgorithm._append('data');
2487 * bufferedBlockAlgorithm._append(wordArray);
2488 */
2489 _append: function (data) {
2490 // Convert string to WordArray, else assume WordArray already
2491 if (typeof data == 'string') {
2492 data = Utf8.parse(data);
2493 }
2494
2495 // Append
2496 this._data.concat(data);
2497 this._nDataBytes += data.sigBytes;
2498 },
2499
2500 /**
2501 * Processes available data blocks.
2502 *
2503 * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
2504 *
2505 * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
2506 *
2507 * @return {WordArray} The processed data.
2508 *
2509 * @example
2510 *
2511 * var processedData = bufferedBlockAlgorithm._process();
2512 * var processedData = bufferedBlockAlgorithm._process(!!'flush');
2513 */
2514 _process: function (doFlush) {
2515 // Shortcuts
2516 var data = this._data;
2517 var dataWords = data.words;
2518 var dataSigBytes = data.sigBytes;
2519 var blockSize = this.blockSize;
2520 var blockSizeBytes = blockSize * 4;
2521
2522 // Count blocks ready
2523 var nBlocksReady = dataSigBytes / blockSizeBytes;
2524 if (doFlush) {
2525 // Round up to include partial blocks
2526 nBlocksReady = Math.ceil(nBlocksReady);
2527 } else {
2528 // Round down to include only full blocks,
2529 // less the number of blocks that must remain in the buffer
2530 nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
2531 }
2532
2533 // Count words ready
2534 var nWordsReady = nBlocksReady * blockSize;
2535
2536 // Count bytes ready
2537 var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
2538
2539 // Process blocks
2540 if (nWordsReady) {
2541 for (var offset = 0; offset < nWordsReady; offset += blockSize) {
2542 // Perform concrete-algorithm logic
2543 this._doProcessBlock(dataWords, offset);
2544 }
2545
2546 // Remove processed words
2547 var processedWords = dataWords.splice(0, nWordsReady);
2548 data.sigBytes -= nBytesReady;
2549 }
2550
2551 // Return processed words
2552 return new WordArray.init(processedWords, nBytesReady);
2553 },
2554
2555 /**
2556 * Creates a copy of this object.
2557 *
2558 * @return {Object} The clone.
2559 *
2560 * @example
2561 *
2562 * var clone = bufferedBlockAlgorithm.clone();
2563 */
2564 clone: function () {
2565 var clone = Base.clone.call(this);
2566 clone._data = this._data.clone();
2567
2568 return clone;
2569 },
2570
2571 _minBufferSize: 0
2572 });
2573
2574 /**
2575 * Abstract hasher template.
2576 *
2577 * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
2578 */
2579 var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
2580 /**
2581 * Configuration options.
2582 */
2583 cfg: Base.extend(),
2584
2585 /**
2586 * Initializes a newly created hasher.
2587 *
2588 * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
2589 *
2590 * @example
2591 *
2592 * var hasher = CryptoJS.algo.SHA256.create();
2593 */
2594 init: function (cfg) {
2595 // Apply config defaults
2596 this.cfg = this.cfg.extend(cfg);
2597
2598 // Set initial values
2599 this.reset();
2600 },
2601
2602 /**
2603 * Resets this hasher to its initial state.
2604 *
2605 * @example
2606 *
2607 * hasher.reset();
2608 */
2609 reset: function () {
2610 // Reset data buffer
2611 BufferedBlockAlgorithm.reset.call(this);
2612
2613 // Perform concrete-hasher logic
2614 this._doReset();
2615 },
2616
2617 /**
2618 * Updates this hasher with a message.
2619 *
2620 * @param {WordArray|string} messageUpdate The message to append.
2621 *
2622 * @return {Hasher} This hasher.
2623 *
2624 * @example
2625 *
2626 * hasher.update('message');
2627 * hasher.update(wordArray);
2628 */
2629 update: function (messageUpdate) {
2630 // Append
2631 this._append(messageUpdate);
2632
2633 // Update the hash
2634 this._process();
2635
2636 // Chainable
2637 return this;
2638 },
2639
2640 /**
2641 * Finalizes the hash computation.
2642 * Note that the finalize operation is effectively a destructive, read-once operation.
2643 *
2644 * @param {WordArray|string} messageUpdate (Optional) A final message update.
2645 *
2646 * @return {WordArray} The hash.
2647 *
2648 * @example
2649 *
2650 * var hash = hasher.finalize();
2651 * var hash = hasher.finalize('message');
2652 * var hash = hasher.finalize(wordArray);
2653 */
2654 finalize: function (messageUpdate) {
2655 // Final message update
2656 if (messageUpdate) {
2657 this._append(messageUpdate);
2658 }
2659
2660 // Perform concrete-hasher logic
2661 var hash = this._doFinalize();
2662
2663 return hash;
2664 },
2665
2666 blockSize: 512/32,
2667
2668 /**
2669 * Creates a shortcut function to a hasher's object interface.
2670 *
2671 * @param {Hasher} hasher The hasher to create a helper for.
2672 *
2673 * @return {Function} The shortcut function.
2674 *
2675 * @static
2676 *
2677 * @example
2678 *
2679 * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
2680 */
2681 _createHelper: function (hasher) {
2682 return function (message, cfg) {
2683 return new hasher.init(cfg).finalize(message);
2684 };
2685 },
2686
2687 /**
2688 * Creates a shortcut function to the HMAC's object interface.
2689 *
2690 * @param {Hasher} hasher The hasher to use in this HMAC helper.
2691 *
2692 * @return {Function} The shortcut function.
2693 *
2694 * @static
2695 *
2696 * @example
2697 *
2698 * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
2699 */
2700 _createHmacHelper: function (hasher) {
2701 return function (message, key) {
2702 return new C_algo.HMAC.init(hasher, key).finalize(message);
2703 };
2704 }
2705 });
2706
2707 /**
2708 * Algorithm namespace.
2709 */
2710 var C_algo = C.algo = {};
2711
2712 return C;
2713 }(Math));
2714
2715
2716 return CryptoJS;
2717
2718}));
2719},{}],33:[function(require,module,exports){
2720;(function (root, factory) {
2721 if (typeof exports === "object") {
2722 // CommonJS
2723 module.exports = exports = factory(require("./core"));
2724 }
2725 else if (typeof define === "function" && define.amd) {
2726 // AMD
2727 define(["./core"], factory);
2728 }
2729 else {
2730 // Global (browser)
2731 factory(root.CryptoJS);
2732 }
2733}(this, function (CryptoJS) {
2734
2735 return CryptoJS.enc.Hex;
2736
2737}));
2738},{"./core":32}],34:[function(require,module,exports){
2739;(function (root, factory, undef) {
2740 if (typeof exports === "object") {
2741 // CommonJS
2742 module.exports = exports = factory(require("./core"), require("./sha256"), require("./hmac"));
2743 }
2744 else if (typeof define === "function" && define.amd) {
2745 // AMD
2746 define(["./core", "./sha256", "./hmac"], factory);
2747 }
2748 else {
2749 // Global (browser)
2750 factory(root.CryptoJS);
2751 }
2752}(this, function (CryptoJS) {
2753
2754 return CryptoJS.HmacSHA256;
2755
2756}));
2757},{"./core":32,"./hmac":35,"./sha256":36}],35:[function(require,module,exports){
2758;(function (root, factory) {
2759 if (typeof exports === "object") {
2760 // CommonJS
2761 module.exports = exports = factory(require("./core"));
2762 }
2763 else if (typeof define === "function" && define.amd) {
2764 // AMD
2765 define(["./core"], factory);
2766 }
2767 else {
2768 // Global (browser)
2769 factory(root.CryptoJS);
2770 }
2771}(this, function (CryptoJS) {
2772
2773 (function () {
2774 // Shortcuts
2775 var C = CryptoJS;
2776 var C_lib = C.lib;
2777 var Base = C_lib.Base;
2778 var C_enc = C.enc;
2779 var Utf8 = C_enc.Utf8;
2780 var C_algo = C.algo;
2781
2782 /**
2783 * HMAC algorithm.
2784 */
2785 var HMAC = C_algo.HMAC = Base.extend({
2786 /**
2787 * Initializes a newly created HMAC.
2788 *
2789 * @param {Hasher} hasher The hash algorithm to use.
2790 * @param {WordArray|string} key The secret key.
2791 *
2792 * @example
2793 *
2794 * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
2795 */
2796 init: function (hasher, key) {
2797 // Init hasher
2798 hasher = this._hasher = new hasher.init();
2799
2800 // Convert string to WordArray, else assume WordArray already
2801 if (typeof key == 'string') {
2802 key = Utf8.parse(key);
2803 }
2804
2805 // Shortcuts
2806 var hasherBlockSize = hasher.blockSize;
2807 var hasherBlockSizeBytes = hasherBlockSize * 4;
2808
2809 // Allow arbitrary length keys
2810 if (key.sigBytes > hasherBlockSizeBytes) {
2811 key = hasher.finalize(key);
2812 }
2813
2814 // Clamp excess bits
2815 key.clamp();
2816
2817 // Clone key for inner and outer pads
2818 var oKey = this._oKey = key.clone();
2819 var iKey = this._iKey = key.clone();
2820
2821 // Shortcuts
2822 var oKeyWords = oKey.words;
2823 var iKeyWords = iKey.words;
2824
2825 // XOR keys with pad constants
2826 for (var i = 0; i < hasherBlockSize; i++) {
2827 oKeyWords[i] ^= 0x5c5c5c5c;
2828 iKeyWords[i] ^= 0x36363636;
2829 }
2830 oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
2831
2832 // Set initial values
2833 this.reset();
2834 },
2835
2836 /**
2837 * Resets this HMAC to its initial state.
2838 *
2839 * @example
2840 *
2841 * hmacHasher.reset();
2842 */
2843 reset: function () {
2844 // Shortcut
2845 var hasher = this._hasher;
2846
2847 // Reset
2848 hasher.reset();
2849 hasher.update(this._iKey);
2850 },
2851
2852 /**
2853 * Updates this HMAC with a message.
2854 *
2855 * @param {WordArray|string} messageUpdate The message to append.
2856 *
2857 * @return {HMAC} This HMAC instance.
2858 *
2859 * @example
2860 *
2861 * hmacHasher.update('message');
2862 * hmacHasher.update(wordArray);
2863 */
2864 update: function (messageUpdate) {
2865 this._hasher.update(messageUpdate);
2866
2867 // Chainable
2868 return this;
2869 },
2870
2871 /**
2872 * Finalizes the HMAC computation.
2873 * Note that the finalize operation is effectively a destructive, read-once operation.
2874 *
2875 * @param {WordArray|string} messageUpdate (Optional) A final message update.
2876 *
2877 * @return {WordArray} The HMAC.
2878 *
2879 * @example
2880 *
2881 * var hmac = hmacHasher.finalize();
2882 * var hmac = hmacHasher.finalize('message');
2883 * var hmac = hmacHasher.finalize(wordArray);
2884 */
2885 finalize: function (messageUpdate) {
2886 // Shortcut
2887 var hasher = this._hasher;
2888
2889 // Compute HMAC
2890 var innerHash = hasher.finalize(messageUpdate);
2891 hasher.reset();
2892 var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
2893
2894 return hmac;
2895 }
2896 });
2897 }());
2898
2899
2900}));
2901},{"./core":32}],36:[function(require,module,exports){
2902;(function (root, factory) {
2903 if (typeof exports === "object") {
2904 // CommonJS
2905 module.exports = exports = factory(require("./core"));
2906 }
2907 else if (typeof define === "function" && define.amd) {
2908 // AMD
2909 define(["./core"], factory);
2910 }
2911 else {
2912 // Global (browser)
2913 factory(root.CryptoJS);
2914 }
2915}(this, function (CryptoJS) {
2916
2917 (function (Math) {
2918 // Shortcuts
2919 var C = CryptoJS;
2920 var C_lib = C.lib;
2921 var WordArray = C_lib.WordArray;
2922 var Hasher = C_lib.Hasher;
2923 var C_algo = C.algo;
2924
2925 // Initialization and round constants tables
2926 var H = [];
2927 var K = [];
2928
2929 // Compute constants
2930 (function () {
2931 function isPrime(n) {
2932 var sqrtN = Math.sqrt(n);
2933 for (var factor = 2; factor <= sqrtN; factor++) {
2934 if (!(n % factor)) {
2935 return false;
2936 }
2937 }
2938
2939 return true;
2940 }
2941
2942 function getFractionalBits(n) {
2943 return ((n - (n | 0)) * 0x100000000) | 0;
2944 }
2945
2946 var n = 2;
2947 var nPrime = 0;
2948 while (nPrime < 64) {
2949 if (isPrime(n)) {
2950 if (nPrime < 8) {
2951 H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
2952 }
2953 K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
2954
2955 nPrime++;
2956 }
2957
2958 n++;
2959 }
2960 }());
2961
2962 // Reusable object
2963 var W = [];
2964
2965 /**
2966 * SHA-256 hash algorithm.
2967 */
2968 var SHA256 = C_algo.SHA256 = Hasher.extend({
2969 _doReset: function () {
2970 this._hash = new WordArray.init(H.slice(0));
2971 },
2972
2973 _doProcessBlock: function (M, offset) {
2974 // Shortcut
2975 var H = this._hash.words;
2976
2977 // Working variables
2978 var a = H[0];
2979 var b = H[1];
2980 var c = H[2];
2981 var d = H[3];
2982 var e = H[4];
2983 var f = H[5];
2984 var g = H[6];
2985 var h = H[7];
2986
2987 // Computation
2988 for (var i = 0; i < 64; i++) {
2989 if (i < 16) {
2990 W[i] = M[offset + i] | 0;
2991 } else {
2992 var gamma0x = W[i - 15];
2993 var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
2994 ((gamma0x << 14) | (gamma0x >>> 18)) ^
2995 (gamma0x >>> 3);
2996
2997 var gamma1x = W[i - 2];
2998 var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
2999 ((gamma1x << 13) | (gamma1x >>> 19)) ^
3000 (gamma1x >>> 10);
3001
3002 W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
3003 }
3004
3005 var ch = (e & f) ^ (~e & g);
3006 var maj = (a & b) ^ (a & c) ^ (b & c);
3007
3008 var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
3009 var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
3010
3011 var t1 = h + sigma1 + ch + K[i] + W[i];
3012 var t2 = sigma0 + maj;
3013
3014 h = g;
3015 g = f;
3016 f = e;
3017 e = (d + t1) | 0;
3018 d = c;
3019 c = b;
3020 b = a;
3021 a = (t1 + t2) | 0;
3022 }
3023
3024 // Intermediate hash value
3025 H[0] = (H[0] + a) | 0;
3026 H[1] = (H[1] + b) | 0;
3027 H[2] = (H[2] + c) | 0;
3028 H[3] = (H[3] + d) | 0;
3029 H[4] = (H[4] + e) | 0;
3030 H[5] = (H[5] + f) | 0;
3031 H[6] = (H[6] + g) | 0;
3032 H[7] = (H[7] + h) | 0;
3033 },
3034
3035 _doFinalize: function () {
3036 // Shortcuts
3037 var data = this._data;
3038 var dataWords = data.words;
3039
3040 var nBitsTotal = this._nDataBytes * 8;
3041 var nBitsLeft = data.sigBytes * 8;
3042
3043 // Add padding
3044 dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
3045 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
3046 dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
3047 data.sigBytes = dataWords.length * 4;
3048
3049 // Hash final blocks
3050 this._process();
3051
3052 // Return final computed hash
3053 return this._hash;
3054 },
3055
3056 clone: function () {
3057 var clone = Hasher.clone.call(this);
3058 clone._hash = this._hash.clone();
3059
3060 return clone;
3061 }
3062 });
3063
3064 /**
3065 * Shortcut function to the hasher's object interface.
3066 *
3067 * @param {WordArray|string} message The message to hash.
3068 *
3069 * @return {WordArray} The hash.
3070 *
3071 * @static
3072 *
3073 * @example
3074 *
3075 * var hash = CryptoJS.SHA256('message');
3076 * var hash = CryptoJS.SHA256(wordArray);
3077 */
3078 C.SHA256 = Hasher._createHelper(SHA256);
3079
3080 /**
3081 * Shortcut function to the HMAC's object interface.
3082 *
3083 * @param {WordArray|string} message The message to hash.
3084 * @param {WordArray|string} key The secret key.
3085 *
3086 * @return {WordArray} The HMAC.
3087 *
3088 * @static
3089 *
3090 * @example
3091 *
3092 * var hmac = CryptoJS.HmacSHA256(message, key);
3093 */
3094 C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
3095 }(Math));
3096
3097
3098 return CryptoJS.SHA256;
3099
3100}));
3101},{"./core":32}],37:[function(require,module,exports){
3102(function (root, factory) {
3103 if (typeof exports === 'object') {
3104 module.exports = factory();
3105 } else if (typeof define === 'function' && define.amd) {
3106 define([], factory);
3107 } else {
3108 root.urltemplate = factory();
3109 }
3110}(this, function () {
3111 /**
3112 * @constructor
3113 */
3114 function UrlTemplate() {
3115 }
3116
3117 /**
3118 * @private
3119 * @param {string} str
3120 * @return {string}
3121 */
3122 UrlTemplate.prototype.encodeReserved = function (str) {
3123 return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) {
3124 if (!/%[0-9A-Fa-f]/.test(part)) {
3125 part = encodeURI(part).replace(/%5B/g, '[').replace(/%5D/g, ']');
3126 }
3127 return part;
3128 }).join('');
3129 };
3130
3131 /**
3132 * @private
3133 * @param {string} str
3134 * @return {string}
3135 */
3136 UrlTemplate.prototype.encodeUnreserved = function (str) {
3137 return encodeURIComponent(str).replace(/[!'()*]/g, function (c) {
3138 return '%' + c.charCodeAt(0).toString(16).toUpperCase();
3139 });
3140 }
3141
3142 /**
3143 * @private
3144 * @param {string} operator
3145 * @param {string} value
3146 * @param {string} key
3147 * @return {string}
3148 */
3149 UrlTemplate.prototype.encodeValue = function (operator, value, key) {
3150 value = (operator === '+' || operator === '#') ? this.encodeReserved(value) : this.encodeUnreserved(value);
3151
3152 if (key) {
3153 return this.encodeUnreserved(key) + '=' + value;
3154 } else {
3155 return value;
3156 }
3157 };
3158
3159 /**
3160 * @private
3161 * @param {*} value
3162 * @return {boolean}
3163 */
3164 UrlTemplate.prototype.isDefined = function (value) {
3165 return value !== undefined && value !== null;
3166 };
3167
3168 /**
3169 * @private
3170 * @param {string}
3171 * @return {boolean}
3172 */
3173 UrlTemplate.prototype.isKeyOperator = function (operator) {
3174 return operator === ';' || operator === '&' || operator === '?';
3175 };
3176
3177 /**
3178 * @private
3179 * @param {Object} context
3180 * @param {string} operator
3181 * @param {string} key
3182 * @param {string} modifier
3183 */
3184 UrlTemplate.prototype.getValues = function (context, operator, key, modifier) {
3185 var value = context[key],
3186 result = [];
3187
3188 if (this.isDefined(value) && value !== '') {
3189 if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
3190 value = value.toString();
3191
3192 if (modifier && modifier !== '*') {
3193 value = value.substring(0, parseInt(modifier, 10));
3194 }
3195
3196 result.push(this.encodeValue(operator, value, this.isKeyOperator(operator) ? key : null));
3197 } else {
3198 if (modifier === '*') {
3199 if (Array.isArray(value)) {
3200 value.filter(this.isDefined).forEach(function (value) {
3201 result.push(this.encodeValue(operator, value, this.isKeyOperator(operator) ? key : null));
3202 }, this);
3203 } else {
3204 Object.keys(value).forEach(function (k) {
3205 if (this.isDefined(value[k])) {
3206 result.push(this.encodeValue(operator, value[k], k));
3207 }
3208 }, this);
3209 }
3210 } else {
3211 var tmp = [];
3212
3213 if (Array.isArray(value)) {
3214 value.filter(this.isDefined).forEach(function (value) {
3215 tmp.push(this.encodeValue(operator, value));
3216 }, this);
3217 } else {
3218 Object.keys(value).forEach(function (k) {
3219 if (this.isDefined(value[k])) {
3220 tmp.push(this.encodeUnreserved(k));
3221 tmp.push(this.encodeValue(operator, value[k].toString()));
3222 }
3223 }, this);
3224 }
3225
3226 if (this.isKeyOperator(operator)) {
3227 result.push(this.encodeUnreserved(key) + '=' + tmp.join(','));
3228 } else if (tmp.length !== 0) {
3229 result.push(tmp.join(','));
3230 }
3231 }
3232 }
3233 } else {
3234 if (operator === ';') {
3235 if (this.isDefined(value)) {
3236 result.push(this.encodeUnreserved(key));
3237 }
3238 } else if (value === '' && (operator === '&' || operator === '?')) {
3239 result.push(this.encodeUnreserved(key) + '=');
3240 } else if (value === '') {
3241 result.push('');
3242 }
3243 }
3244 return result;
3245 };
3246
3247 /**
3248 * @param {string} template
3249 * @return {function(Object):string}
3250 */
3251 UrlTemplate.prototype.parse = function (template) {
3252 var that = this;
3253 var operators = ['+', '#', '.', '/', ';', '?', '&'];
3254
3255 return {
3256 expand: function (context) {
3257 return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) {
3258 if (expression) {
3259 var operator = null,
3260 values = [];
3261
3262 if (operators.indexOf(expression.charAt(0)) !== -1) {
3263 operator = expression.charAt(0);
3264 expression = expression.substr(1);
3265 }
3266
3267 expression.split(/,/g).forEach(function (variable) {
3268 var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable);
3269 values.push.apply(values, that.getValues(context, operator, tmp[1], tmp[2] || tmp[3]));
3270 });
3271
3272 if (operator && operator !== '+') {
3273 var separator = ',';
3274
3275 if (operator === '?') {
3276 separator = '&';
3277 } else if (operator !== '#') {
3278 separator = operator;
3279 }
3280 return (values.length !== 0 ? operator : '') + values.join(separator);
3281 } else {
3282 return values.join(',');
3283 }
3284 } else {
3285 return that.encodeReserved(literal);
3286 }
3287 });
3288 }
3289 };
3290 };
3291
3292 return new UrlTemplate();
3293}));
3294
3295},{}],38:[function(require,module,exports){
3296// shim for using process in browser
3297var process = module.exports = {};
3298
3299// cached from whatever global is present so that test runners that stub it
3300// don't break things. But we need to wrap it in a try catch in case it is
3301// wrapped in strict mode code which doesn't define any globals. It's inside a
3302// function because try/catches deoptimize in certain engines.
3303
3304var cachedSetTimeout;
3305var cachedClearTimeout;
3306
3307function defaultSetTimout() {
3308 throw new Error('setTimeout has not been defined');
3309}
3310function defaultClearTimeout () {
3311 throw new Error('clearTimeout has not been defined');
3312}
3313(function () {
3314 try {
3315 if (typeof setTimeout === 'function') {
3316 cachedSetTimeout = setTimeout;
3317 } else {
3318 cachedSetTimeout = defaultSetTimout;
3319 }
3320 } catch (e) {
3321 cachedSetTimeout = defaultSetTimout;
3322 }
3323 try {
3324 if (typeof clearTimeout === 'function') {
3325 cachedClearTimeout = clearTimeout;
3326 } else {
3327 cachedClearTimeout = defaultClearTimeout;
3328 }
3329 } catch (e) {
3330 cachedClearTimeout = defaultClearTimeout;
3331 }
3332} ())
3333function runTimeout(fun) {
3334 if (cachedSetTimeout === setTimeout) {
3335 //normal enviroments in sane situations
3336 return setTimeout(fun, 0);
3337 }
3338 // if setTimeout wasn't available but was latter defined
3339 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
3340 cachedSetTimeout = setTimeout;
3341 return setTimeout(fun, 0);
3342 }
3343 try {
3344 // when when somebody has screwed with setTimeout but no I.E. maddness
3345 return cachedSetTimeout(fun, 0);
3346 } catch(e){
3347 try {
3348 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
3349 return cachedSetTimeout.call(null, fun, 0);
3350 } catch(e){
3351 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
3352 return cachedSetTimeout.call(this, fun, 0);
3353 }
3354 }
3355
3356
3357}
3358function runClearTimeout(marker) {
3359 if (cachedClearTimeout === clearTimeout) {
3360 //normal enviroments in sane situations
3361 return clearTimeout(marker);
3362 }
3363 // if clearTimeout wasn't available but was latter defined
3364 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
3365 cachedClearTimeout = clearTimeout;
3366 return clearTimeout(marker);
3367 }
3368 try {
3369 // when when somebody has screwed with setTimeout but no I.E. maddness
3370 return cachedClearTimeout(marker);
3371 } catch (e){
3372 try {
3373 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
3374 return cachedClearTimeout.call(null, marker);
3375 } catch (e){
3376 // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
3377 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
3378 return cachedClearTimeout.call(this, marker);
3379 }
3380 }
3381
3382
3383
3384}
3385var queue = [];
3386var draining = false;
3387var currentQueue;
3388var queueIndex = -1;
3389
3390function cleanUpNextTick() {
3391 if (!draining || !currentQueue) {
3392 return;
3393 }
3394 draining = false;
3395 if (currentQueue.length) {
3396 queue = currentQueue.concat(queue);
3397 } else {
3398 queueIndex = -1;
3399 }
3400 if (queue.length) {
3401 drainQueue();
3402 }
3403}
3404
3405function drainQueue() {
3406 if (draining) {
3407 return;
3408 }
3409 var timeout = runTimeout(cleanUpNextTick);
3410 draining = true;
3411
3412 var len = queue.length;
3413 while(len) {
3414 currentQueue = queue;
3415 queue = [];
3416 while (++queueIndex < len) {
3417 if (currentQueue) {
3418 currentQueue[queueIndex].run();
3419 }
3420 }
3421 queueIndex = -1;
3422 len = queue.length;
3423 }
3424 currentQueue = null;
3425 draining = false;
3426 runClearTimeout(timeout);
3427}
3428
3429process.nextTick = function (fun) {
3430 var args = new Array(arguments.length - 1);
3431 if (arguments.length > 1) {
3432 for (var i = 1; i < arguments.length; i++) {
3433 args[i - 1] = arguments[i];
3434 }
3435 }
3436 queue.push(new Item(fun, args));
3437 if (queue.length === 1 && !draining) {
3438 runTimeout(drainQueue);
3439 }
3440};
3441
3442// v8 likes predictible objects
3443function Item(fun, array) {
3444 this.fun = fun;
3445 this.array = array;
3446}
3447Item.prototype.run = function () {
3448 this.fun.apply(null, this.array);
3449};
3450process.title = 'browser';
3451process.browser = true;
3452process.env = {};
3453process.argv = [];
3454process.version = ''; // empty string to avoid regexp issues
3455process.versions = {};
3456
3457function noop() {}
3458
3459process.on = noop;
3460process.addListener = noop;
3461process.once = noop;
3462process.off = noop;
3463process.removeListener = noop;
3464process.removeAllListeners = noop;
3465process.emit = noop;
3466
3467process.binding = function (name) {
3468 throw new Error('process.binding is not supported');
3469};
3470
3471process.cwd = function () { return '/' };
3472process.chdir = function (dir) {
3473 throw new Error('process.chdir is not supported');
3474};
3475process.umask = function() { return 0; };
3476
3477},{}],39:[function(require,module,exports){
3478(function (global){
3479/*! https://mths.be/punycode v1.4.1 by @mathias */
3480;(function(root) {
3481
3482 /** Detect free variables */
3483 var freeExports = typeof exports == 'object' && exports &&
3484 !exports.nodeType && exports;
3485 var freeModule = typeof module == 'object' && module &&
3486 !module.nodeType && module;
3487 var freeGlobal = typeof global == 'object' && global;
3488 if (
3489 freeGlobal.global === freeGlobal ||
3490 freeGlobal.window === freeGlobal ||
3491 freeGlobal.self === freeGlobal
3492 ) {
3493 root = freeGlobal;
3494 }
3495
3496 /**
3497 * The `punycode` object.
3498 * @name punycode
3499 * @type Object
3500 */
3501 var punycode,
3502
3503 /** Highest positive signed 32-bit float value */
3504 maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
3505
3506 /** Bootstring parameters */
3507 base = 36,
3508 tMin = 1,
3509 tMax = 26,
3510 skew = 38,
3511 damp = 700,
3512 initialBias = 72,
3513 initialN = 128, // 0x80
3514 delimiter = '-', // '\x2D'
3515
3516 /** Regular expressions */
3517 regexPunycode = /^xn--/,
3518 regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
3519 regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
3520
3521 /** Error messages */
3522 errors = {
3523 'overflow': 'Overflow: input needs wider integers to process',
3524 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
3525 'invalid-input': 'Invalid input'
3526 },
3527
3528 /** Convenience shortcuts */
3529 baseMinusTMin = base - tMin,
3530 floor = Math.floor,
3531 stringFromCharCode = String.fromCharCode,
3532
3533 /** Temporary variable */
3534 key;
3535
3536 /*--------------------------------------------------------------------------*/
3537
3538 /**
3539 * A generic error utility function.
3540 * @private
3541 * @param {String} type The error type.
3542 * @returns {Error} Throws a `RangeError` with the applicable error message.
3543 */
3544 function error(type) {
3545 throw new RangeError(errors[type]);
3546 }
3547
3548 /**
3549 * A generic `Array#map` utility function.
3550 * @private
3551 * @param {Array} array The array to iterate over.
3552 * @param {Function} callback The function that gets called for every array
3553 * item.
3554 * @returns {Array} A new array of values returned by the callback function.
3555 */
3556 function map(array, fn) {
3557 var length = array.length;
3558 var result = [];
3559 while (length--) {
3560 result[length] = fn(array[length]);
3561 }
3562 return result;
3563 }
3564
3565 /**
3566 * A simple `Array#map`-like wrapper to work with domain name strings or email
3567 * addresses.
3568 * @private
3569 * @param {String} domain The domain name or email address.
3570 * @param {Function} callback The function that gets called for every
3571 * character.
3572 * @returns {Array} A new string of characters returned by the callback
3573 * function.
3574 */
3575 function mapDomain(string, fn) {
3576 var parts = string.split('@');
3577 var result = '';
3578 if (parts.length > 1) {
3579 // In email addresses, only the domain name should be punycoded. Leave
3580 // the local part (i.e. everything up to `@`) intact.
3581 result = parts[0] + '@';
3582 string = parts[1];
3583 }
3584 // Avoid `split(regex)` for IE8 compatibility. See #17.
3585 string = string.replace(regexSeparators, '\x2E');
3586 var labels = string.split('.');
3587 var encoded = map(labels, fn).join('.');
3588 return result + encoded;
3589 }
3590
3591 /**
3592 * Creates an array containing the numeric code points of each Unicode
3593 * character in the string. While JavaScript uses UCS-2 internally,
3594 * this function will convert a pair of surrogate halves (each of which
3595 * UCS-2 exposes as separate characters) into a single code point,
3596 * matching UTF-16.
3597 * @see `punycode.ucs2.encode`
3598 * @see <https://mathiasbynens.be/notes/javascript-encoding>
3599 * @memberOf punycode.ucs2
3600 * @name decode
3601 * @param {String} string The Unicode input string (UCS-2).
3602 * @returns {Array} The new array of code points.
3603 */
3604 function ucs2decode(string) {
3605 var output = [],
3606 counter = 0,
3607 length = string.length,
3608 value,
3609 extra;
3610 while (counter < length) {
3611 value = string.charCodeAt(counter++);
3612 if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
3613 // high surrogate, and there is a next character
3614 extra = string.charCodeAt(counter++);
3615 if ((extra & 0xFC00) == 0xDC00) { // low surrogate
3616 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
3617 } else {
3618 // unmatched surrogate; only append this code unit, in case the next
3619 // code unit is the high surrogate of a surrogate pair
3620 output.push(value);
3621 counter--;
3622 }
3623 } else {
3624 output.push(value);
3625 }
3626 }
3627 return output;
3628 }
3629
3630 /**
3631 * Creates a string based on an array of numeric code points.
3632 * @see `punycode.ucs2.decode`
3633 * @memberOf punycode.ucs2
3634 * @name encode
3635 * @param {Array} codePoints The array of numeric code points.
3636 * @returns {String} The new Unicode string (UCS-2).
3637 */
3638 function ucs2encode(array) {
3639 return map(array, function(value) {
3640 var output = '';
3641 if (value > 0xFFFF) {
3642 value -= 0x10000;
3643 output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
3644 value = 0xDC00 | value & 0x3FF;
3645 }
3646 output += stringFromCharCode(value);
3647 return output;
3648 }).join('');
3649 }
3650
3651 /**
3652 * Converts a basic code point into a digit/integer.
3653 * @see `digitToBasic()`
3654 * @private
3655 * @param {Number} codePoint The basic numeric code point value.
3656 * @returns {Number} The numeric value of a basic code point (for use in
3657 * representing integers) in the range `0` to `base - 1`, or `base` if
3658 * the code point does not represent a value.
3659 */
3660 function basicToDigit(codePoint) {
3661 if (codePoint - 48 < 10) {
3662 return codePoint - 22;
3663 }
3664 if (codePoint - 65 < 26) {
3665 return codePoint - 65;
3666 }
3667 if (codePoint - 97 < 26) {
3668 return codePoint - 97;
3669 }
3670 return base;
3671 }
3672
3673 /**
3674 * Converts a digit/integer into a basic code point.
3675 * @see `basicToDigit()`
3676 * @private
3677 * @param {Number} digit The numeric value of a basic code point.
3678 * @returns {Number} The basic code point whose value (when used for
3679 * representing integers) is `digit`, which needs to be in the range
3680 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
3681 * used; else, the lowercase form is used. The behavior is undefined
3682 * if `flag` is non-zero and `digit` has no uppercase form.
3683 */
3684 function digitToBasic(digit, flag) {
3685 // 0..25 map to ASCII a..z or A..Z
3686 // 26..35 map to ASCII 0..9
3687 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
3688 }
3689
3690 /**
3691 * Bias adaptation function as per section 3.4 of RFC 3492.
3692 * https://tools.ietf.org/html/rfc3492#section-3.4
3693 * @private
3694 */
3695 function adapt(delta, numPoints, firstTime) {
3696 var k = 0;
3697 delta = firstTime ? floor(delta / damp) : delta >> 1;
3698 delta += floor(delta / numPoints);
3699 for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
3700 delta = floor(delta / baseMinusTMin);
3701 }
3702 return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
3703 }
3704
3705 /**
3706 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
3707 * symbols.
3708 * @memberOf punycode
3709 * @param {String} input The Punycode string of ASCII-only symbols.
3710 * @returns {String} The resulting string of Unicode symbols.
3711 */
3712 function decode(input) {
3713 // Don't use UCS-2
3714 var output = [],
3715 inputLength = input.length,
3716 out,
3717 i = 0,
3718 n = initialN,
3719 bias = initialBias,
3720 basic,
3721 j,
3722 index,
3723 oldi,
3724 w,
3725 k,
3726 digit,
3727 t,
3728 /** Cached calculation results */
3729 baseMinusT;
3730
3731 // Handle the basic code points: let `basic` be the number of input code
3732 // points before the last delimiter, or `0` if there is none, then copy
3733 // the first basic code points to the output.
3734
3735 basic = input.lastIndexOf(delimiter);
3736 if (basic < 0) {
3737 basic = 0;
3738 }
3739
3740 for (j = 0; j < basic; ++j) {
3741 // if it's not a basic code point
3742 if (input.charCodeAt(j) >= 0x80) {
3743 error('not-basic');
3744 }
3745 output.push(input.charCodeAt(j));
3746 }
3747
3748 // Main decoding loop: start just after the last delimiter if any basic code
3749 // points were copied; start at the beginning otherwise.
3750
3751 for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
3752
3753 // `index` is the index of the next character to be consumed.
3754 // Decode a generalized variable-length integer into `delta`,
3755 // which gets added to `i`. The overflow checking is easier
3756 // if we increase `i` as we go, then subtract off its starting
3757 // value at the end to obtain `delta`.
3758 for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
3759
3760 if (index >= inputLength) {
3761 error('invalid-input');
3762 }
3763
3764 digit = basicToDigit(input.charCodeAt(index++));
3765
3766 if (digit >= base || digit > floor((maxInt - i) / w)) {
3767 error('overflow');
3768 }
3769
3770 i += digit * w;
3771 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
3772
3773 if (digit < t) {
3774 break;
3775 }
3776
3777 baseMinusT = base - t;
3778 if (w > floor(maxInt / baseMinusT)) {
3779 error('overflow');
3780 }
3781
3782 w *= baseMinusT;
3783
3784 }
3785
3786 out = output.length + 1;
3787 bias = adapt(i - oldi, out, oldi == 0);
3788
3789 // `i` was supposed to wrap around from `out` to `0`,
3790 // incrementing `n` each time, so we'll fix that now:
3791 if (floor(i / out) > maxInt - n) {
3792 error('overflow');
3793 }
3794
3795 n += floor(i / out);
3796 i %= out;
3797
3798 // Insert `n` at position `i` of the output
3799 output.splice(i++, 0, n);
3800
3801 }
3802
3803 return ucs2encode(output);
3804 }
3805
3806 /**
3807 * Converts a string of Unicode symbols (e.g. a domain name label) to a
3808 * Punycode string of ASCII-only symbols.
3809 * @memberOf punycode
3810 * @param {String} input The string of Unicode symbols.
3811 * @returns {String} The resulting Punycode string of ASCII-only symbols.
3812 */
3813 function encode(input) {
3814 var n,
3815 delta,
3816 handledCPCount,
3817 basicLength,
3818 bias,
3819 j,
3820 m,
3821 q,
3822 k,
3823 t,
3824 currentValue,
3825 output = [],
3826 /** `inputLength` will hold the number of code points in `input`. */
3827 inputLength,
3828 /** Cached calculation results */
3829 handledCPCountPlusOne,
3830 baseMinusT,
3831 qMinusT;
3832
3833 // Convert the input in UCS-2 to Unicode
3834 input = ucs2decode(input);
3835
3836 // Cache the length
3837 inputLength = input.length;
3838
3839 // Initialize the state
3840 n = initialN;
3841 delta = 0;
3842 bias = initialBias;
3843
3844 // Handle the basic code points
3845 for (j = 0; j < inputLength; ++j) {
3846 currentValue = input[j];
3847 if (currentValue < 0x80) {
3848 output.push(stringFromCharCode(currentValue));
3849 }
3850 }
3851
3852 handledCPCount = basicLength = output.length;
3853
3854 // `handledCPCount` is the number of code points that have been handled;
3855 // `basicLength` is the number of basic code points.
3856
3857 // Finish the basic string - if it is not empty - with a delimiter
3858 if (basicLength) {
3859 output.push(delimiter);
3860 }
3861
3862 // Main encoding loop:
3863 while (handledCPCount < inputLength) {
3864
3865 // All non-basic code points < n have been handled already. Find the next
3866 // larger one:
3867 for (m = maxInt, j = 0; j < inputLength; ++j) {
3868 currentValue = input[j];
3869 if (currentValue >= n && currentValue < m) {
3870 m = currentValue;
3871 }
3872 }
3873
3874 // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
3875 // but guard against overflow
3876 handledCPCountPlusOne = handledCPCount + 1;
3877 if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
3878 error('overflow');
3879 }
3880
3881 delta += (m - n) * handledCPCountPlusOne;
3882 n = m;
3883
3884 for (j = 0; j < inputLength; ++j) {
3885 currentValue = input[j];
3886
3887 if (currentValue < n && ++delta > maxInt) {
3888 error('overflow');
3889 }
3890
3891 if (currentValue == n) {
3892 // Represent delta as a generalized variable-length integer
3893 for (q = delta, k = base; /* no condition */; k += base) {
3894 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
3895 if (q < t) {
3896 break;
3897 }
3898 qMinusT = q - t;
3899 baseMinusT = base - t;
3900 output.push(
3901 stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
3902 );
3903 q = floor(qMinusT / baseMinusT);
3904 }
3905
3906 output.push(stringFromCharCode(digitToBasic(q, 0)));
3907 bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
3908 delta = 0;
3909 ++handledCPCount;
3910 }
3911 }
3912
3913 ++delta;
3914 ++n;
3915
3916 }
3917 return output.join('');
3918 }
3919
3920 /**
3921 * Converts a Punycode string representing a domain name or an email address
3922 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
3923 * it doesn't matter if you call it on a string that has already been
3924 * converted to Unicode.
3925 * @memberOf punycode
3926 * @param {String} input The Punycoded domain name or email address to
3927 * convert to Unicode.
3928 * @returns {String} The Unicode representation of the given Punycode
3929 * string.
3930 */
3931 function toUnicode(input) {
3932 return mapDomain(input, function(string) {
3933 return regexPunycode.test(string)
3934 ? decode(string.slice(4).toLowerCase())
3935 : string;
3936 });
3937 }
3938
3939 /**
3940 * Converts a Unicode string representing a domain name or an email address to
3941 * Punycode. Only the non-ASCII parts of the domain name will be converted,
3942 * i.e. it doesn't matter if you call it with a domain that's already in
3943 * ASCII.
3944 * @memberOf punycode
3945 * @param {String} input The domain name or email address to convert, as a
3946 * Unicode string.
3947 * @returns {String} The Punycode representation of the given domain name or
3948 * email address.
3949 */
3950 function toASCII(input) {
3951 return mapDomain(input, function(string) {
3952 return regexNonASCII.test(string)
3953 ? 'xn--' + encode(string)
3954 : string;
3955 });
3956 }
3957
3958 /*--------------------------------------------------------------------------*/
3959
3960 /** Define the public API */
3961 punycode = {
3962 /**
3963 * A string representing the current Punycode.js version number.
3964 * @memberOf punycode
3965 * @type String
3966 */
3967 'version': '1.4.1',
3968 /**
3969 * An object of methods to convert from JavaScript's internal character
3970 * representation (UCS-2) to Unicode code points, and back.
3971 * @see <https://mathiasbynens.be/notes/javascript-encoding>
3972 * @memberOf punycode
3973 * @type Object
3974 */
3975 'ucs2': {
3976 'decode': ucs2decode,
3977 'encode': ucs2encode
3978 },
3979 'decode': decode,
3980 'encode': encode,
3981 'toASCII': toASCII,
3982 'toUnicode': toUnicode
3983 };
3984
3985 /** Expose `punycode` */
3986 // Some AMD build optimizers, like r.js, check for specific condition patterns
3987 // like the following:
3988 if (
3989 typeof define == 'function' &&
3990 typeof define.amd == 'object' &&
3991 define.amd
3992 ) {
3993 define('punycode', function() {
3994 return punycode;
3995 });
3996 } else if (freeExports && freeModule) {
3997 if (module.exports == freeExports) {
3998 // in Node.js, io.js, or RingoJS v0.8.0+
3999 freeModule.exports = punycode;
4000 } else {
4001 // in Narwhal or RingoJS v0.7.0-
4002 for (key in punycode) {
4003 punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
4004 }
4005 }
4006 } else {
4007 // in Rhino or a web browser
4008 root.punycode = punycode;
4009 }
4010
4011}(this));
4012
4013}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
4014},{}],40:[function(require,module,exports){
4015// Copyright Joyent, Inc. and other Node contributors.
4016//
4017// Permission is hereby granted, free of charge, to any person obtaining a
4018// copy of this software and associated documentation files (the
4019// "Software"), to deal in the Software without restriction, including
4020// without limitation the rights to use, copy, modify, merge, publish,
4021// distribute, sublicense, and/or sell copies of the Software, and to permit
4022// persons to whom the Software is furnished to do so, subject to the
4023// following conditions:
4024//
4025// The above copyright notice and this permission notice shall be included
4026// in all copies or substantial portions of the Software.
4027//
4028// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4029// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4030// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4031// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4032// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4033// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4034// USE OR OTHER DEALINGS IN THE SOFTWARE.
4035
4036'use strict';
4037
4038// If obj.hasOwnProperty has been overridden, then calling
4039// obj.hasOwnProperty(prop) will break.
4040// See: https://github.com/joyent/node/issues/1707
4041function hasOwnProperty(obj, prop) {
4042 return Object.prototype.hasOwnProperty.call(obj, prop);
4043}
4044
4045module.exports = function(qs, sep, eq, options) {
4046 sep = sep || '&';
4047 eq = eq || '=';
4048 var obj = {};
4049
4050 if (typeof qs !== 'string' || qs.length === 0) {
4051 return obj;
4052 }
4053
4054 var regexp = /\+/g;
4055 qs = qs.split(sep);
4056
4057 var maxKeys = 1000;
4058 if (options && typeof options.maxKeys === 'number') {
4059 maxKeys = options.maxKeys;
4060 }
4061
4062 var len = qs.length;
4063 // maxKeys <= 0 means that we should not limit keys count
4064 if (maxKeys > 0 && len > maxKeys) {
4065 len = maxKeys;
4066 }
4067
4068 for (var i = 0; i < len; ++i) {
4069 var x = qs[i].replace(regexp, '%20'),
4070 idx = x.indexOf(eq),
4071 kstr, vstr, k, v;
4072
4073 if (idx >= 0) {
4074 kstr = x.substr(0, idx);
4075 vstr = x.substr(idx + 1);
4076 } else {
4077 kstr = x;
4078 vstr = '';
4079 }
4080
4081 k = decodeURIComponent(kstr);
4082 v = decodeURIComponent(vstr);
4083
4084 if (!hasOwnProperty(obj, k)) {
4085 obj[k] = v;
4086 } else if (isArray(obj[k])) {
4087 obj[k].push(v);
4088 } else {
4089 obj[k] = [obj[k], v];
4090 }
4091 }
4092
4093 return obj;
4094};
4095
4096var isArray = Array.isArray || function (xs) {
4097 return Object.prototype.toString.call(xs) === '[object Array]';
4098};
4099
4100},{}],41:[function(require,module,exports){
4101// Copyright Joyent, Inc. and other Node contributors.
4102//
4103// Permission is hereby granted, free of charge, to any person obtaining a
4104// copy of this software and associated documentation files (the
4105// "Software"), to deal in the Software without restriction, including
4106// without limitation the rights to use, copy, modify, merge, publish,
4107// distribute, sublicense, and/or sell copies of the Software, and to permit
4108// persons to whom the Software is furnished to do so, subject to the
4109// following conditions:
4110//
4111// The above copyright notice and this permission notice shall be included
4112// in all copies or substantial portions of the Software.
4113//
4114// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4115// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4116// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4117// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4118// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4119// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4120// USE OR OTHER DEALINGS IN THE SOFTWARE.
4121
4122'use strict';
4123
4124var stringifyPrimitive = function(v) {
4125 switch (typeof v) {
4126 case 'string':
4127 return v;
4128
4129 case 'boolean':
4130 return v ? 'true' : 'false';
4131
4132 case 'number':
4133 return isFinite(v) ? v : '';
4134
4135 default:
4136 return '';
4137 }
4138};
4139
4140module.exports = function(obj, sep, eq, name) {
4141 sep = sep || '&';
4142 eq = eq || '=';
4143 if (obj === null) {
4144 obj = undefined;
4145 }
4146
4147 if (typeof obj === 'object') {
4148 return map(objectKeys(obj), function(k) {
4149 var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
4150 if (isArray(obj[k])) {
4151 return map(obj[k], function(v) {
4152 return ks + encodeURIComponent(stringifyPrimitive(v));
4153 }).join(sep);
4154 } else {
4155 return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
4156 }
4157 }).join(sep);
4158
4159 }
4160
4161 if (!name) return '';
4162 return encodeURIComponent(stringifyPrimitive(name)) + eq +
4163 encodeURIComponent(stringifyPrimitive(obj));
4164};
4165
4166var isArray = Array.isArray || function (xs) {
4167 return Object.prototype.toString.call(xs) === '[object Array]';
4168};
4169
4170function map (xs, f) {
4171 if (xs.map) return xs.map(f);
4172 var res = [];
4173 for (var i = 0; i < xs.length; i++) {
4174 res.push(f(xs[i], i));
4175 }
4176 return res;
4177}
4178
4179var objectKeys = Object.keys || function (obj) {
4180 var res = [];
4181 for (var key in obj) {
4182 if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
4183 }
4184 return res;
4185};
4186
4187},{}],42:[function(require,module,exports){
4188'use strict';
4189
4190exports.decode = exports.parse = require('./decode');
4191exports.encode = exports.stringify = require('./encode');
4192
4193},{"./decode":40,"./encode":41}],43:[function(require,module,exports){
4194// Copyright Joyent, Inc. and other Node contributors.
4195//
4196// Permission is hereby granted, free of charge, to any person obtaining a
4197// copy of this software and associated documentation files (the
4198// "Software"), to deal in the Software without restriction, including
4199// without limitation the rights to use, copy, modify, merge, publish,
4200// distribute, sublicense, and/or sell copies of the Software, and to permit
4201// persons to whom the Software is furnished to do so, subject to the
4202// following conditions:
4203//
4204// The above copyright notice and this permission notice shall be included
4205// in all copies or substantial portions of the Software.
4206//
4207// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
4208// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
4209// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
4210// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
4211// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
4212// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
4213// USE OR OTHER DEALINGS IN THE SOFTWARE.
4214
4215'use strict';
4216
4217var punycode = require('punycode');
4218var util = require('./util');
4219
4220exports.parse = urlParse;
4221exports.resolve = urlResolve;
4222exports.resolveObject = urlResolveObject;
4223exports.format = urlFormat;
4224
4225exports.Url = Url;
4226
4227function Url() {
4228 this.protocol = null;
4229 this.slashes = null;
4230 this.auth = null;
4231 this.host = null;
4232 this.port = null;
4233 this.hostname = null;
4234 this.hash = null;
4235 this.search = null;
4236 this.query = null;
4237 this.pathname = null;
4238 this.path = null;
4239 this.href = null;
4240}
4241
4242// Reference: RFC 3986, RFC 1808, RFC 2396
4243
4244// define these here so at least they only have to be
4245// compiled once on the first module load.
4246var protocolPattern = /^([a-z0-9.+-]+:)/i,
4247 portPattern = /:[0-9]*$/,
4248
4249 // Special case for a simple path URL
4250 simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
4251
4252 // RFC 2396: characters reserved for delimiting URLs.
4253 // We actually just auto-escape these.
4254 delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
4255
4256 // RFC 2396: characters not allowed for various reasons.
4257 unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
4258
4259 // Allowed by RFCs, but cause of XSS attacks. Always escape these.
4260 autoEscape = ['\''].concat(unwise),
4261 // Characters that are never ever allowed in a hostname.
4262 // Note that any invalid chars are also handled, but these
4263 // are the ones that are *expected* to be seen, so we fast-path
4264 // them.
4265 nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
4266 hostEndingChars = ['/', '?', '#'],
4267 hostnameMaxLen = 255,
4268 hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
4269 hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
4270 // protocols that can allow "unsafe" and "unwise" chars.
4271 unsafeProtocol = {
4272 'javascript': true,
4273 'javascript:': true
4274 },
4275 // protocols that never have a hostname.
4276 hostlessProtocol = {
4277 'javascript': true,
4278 'javascript:': true
4279 },
4280 // protocols that always contain a // bit.
4281 slashedProtocol = {
4282 'http': true,
4283 'https': true,
4284 'ftp': true,
4285 'gopher': true,
4286 'file': true,
4287 'http:': true,
4288 'https:': true,
4289 'ftp:': true,
4290 'gopher:': true,
4291 'file:': true
4292 },
4293 querystring = require('querystring');
4294
4295function urlParse(url, parseQueryString, slashesDenoteHost) {
4296 if (url && util.isObject(url) && url instanceof Url) return url;
4297
4298 var u = new Url;
4299 u.parse(url, parseQueryString, slashesDenoteHost);
4300 return u;
4301}
4302
4303Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
4304 if (!util.isString(url)) {
4305 throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
4306 }
4307
4308 // Copy chrome, IE, opera backslash-handling behavior.
4309 // Back slashes before the query string get converted to forward slashes
4310 // See: https://code.google.com/p/chromium/issues/detail?id=25916
4311 var queryIndex = url.indexOf('?'),
4312 splitter =
4313 (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
4314 uSplit = url.split(splitter),
4315 slashRegex = /\\/g;
4316 uSplit[0] = uSplit[0].replace(slashRegex, '/');
4317 url = uSplit.join(splitter);
4318
4319 var rest = url;
4320
4321 // trim before proceeding.
4322 // This is to support parse stuff like " http://foo.com \n"
4323 rest = rest.trim();
4324
4325 if (!slashesDenoteHost && url.split('#').length === 1) {
4326 // Try fast path regexp
4327 var simplePath = simplePathPattern.exec(rest);
4328 if (simplePath) {
4329 this.path = rest;
4330 this.href = rest;
4331 this.pathname = simplePath[1];
4332 if (simplePath[2]) {
4333 this.search = simplePath[2];
4334 if (parseQueryString) {
4335 this.query = querystring.parse(this.search.substr(1));
4336 } else {
4337 this.query = this.search.substr(1);
4338 }
4339 } else if (parseQueryString) {
4340 this.search = '';
4341 this.query = {};
4342 }
4343 return this;
4344 }
4345 }
4346
4347 var proto = protocolPattern.exec(rest);
4348 if (proto) {
4349 proto = proto[0];
4350 var lowerProto = proto.toLowerCase();
4351 this.protocol = lowerProto;
4352 rest = rest.substr(proto.length);
4353 }
4354
4355 // figure out if it's got a host
4356 // user@server is *always* interpreted as a hostname, and url
4357 // resolution will treat //foo/bar as host=foo,path=bar because that's
4358 // how the browser resolves relative URLs.
4359 if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
4360 var slashes = rest.substr(0, 2) === '//';
4361 if (slashes && !(proto && hostlessProtocol[proto])) {
4362 rest = rest.substr(2);
4363 this.slashes = true;
4364 }
4365 }
4366
4367 if (!hostlessProtocol[proto] &&
4368 (slashes || (proto && !slashedProtocol[proto]))) {
4369
4370 // there's a hostname.
4371 // the first instance of /, ?, ;, or # ends the host.
4372 //
4373 // If there is an @ in the hostname, then non-host chars *are* allowed
4374 // to the left of the last @ sign, unless some host-ending character
4375 // comes *before* the @-sign.
4376 // URLs are obnoxious.
4377 //
4378 // ex:
4379 // http://a@b@c/ => user:a@b host:c
4380 // http://a@b?@c => user:a host:c path:/?@c
4381
4382 // v0.12 TODO(isaacs): This is not quite how Chrome does things.
4383 // Review our test case against browsers more comprehensively.
4384
4385 // find the first instance of any hostEndingChars
4386 var hostEnd = -1;
4387 for (var i = 0; i < hostEndingChars.length; i++) {
4388 var hec = rest.indexOf(hostEndingChars[i]);
4389 if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
4390 hostEnd = hec;
4391 }
4392
4393 // at this point, either we have an explicit point where the
4394 // auth portion cannot go past, or the last @ char is the decider.
4395 var auth, atSign;
4396 if (hostEnd === -1) {
4397 // atSign can be anywhere.
4398 atSign = rest.lastIndexOf('@');
4399 } else {
4400 // atSign must be in auth portion.
4401 // http://a@b/c@d => host:b auth:a path:/c@d
4402 atSign = rest.lastIndexOf('@', hostEnd);
4403 }
4404
4405 // Now we have a portion which is definitely the auth.
4406 // Pull that off.
4407 if (atSign !== -1) {
4408 auth = rest.slice(0, atSign);
4409 rest = rest.slice(atSign + 1);
4410 this.auth = decodeURIComponent(auth);
4411 }
4412
4413 // the host is the remaining to the left of the first non-host char
4414 hostEnd = -1;
4415 for (var i = 0; i < nonHostChars.length; i++) {
4416 var hec = rest.indexOf(nonHostChars[i]);
4417 if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
4418 hostEnd = hec;
4419 }
4420 // if we still have not hit it, then the entire thing is a host.
4421 if (hostEnd === -1)
4422 hostEnd = rest.length;
4423
4424 this.host = rest.slice(0, hostEnd);
4425 rest = rest.slice(hostEnd);
4426
4427 // pull out port.
4428 this.parseHost();
4429
4430 // we've indicated that there is a hostname,
4431 // so even if it's empty, it has to be present.
4432 this.hostname = this.hostname || '';
4433
4434 // if hostname begins with [ and ends with ]
4435 // assume that it's an IPv6 address.
4436 var ipv6Hostname = this.hostname[0] === '[' &&
4437 this.hostname[this.hostname.length - 1] === ']';
4438
4439 // validate a little.
4440 if (!ipv6Hostname) {
4441 var hostparts = this.hostname.split(/\./);
4442 for (var i = 0, l = hostparts.length; i < l; i++) {
4443 var part = hostparts[i];
4444 if (!part) continue;
4445 if (!part.match(hostnamePartPattern)) {
4446 var newpart = '';
4447 for (var j = 0, k = part.length; j < k; j++) {
4448 if (part.charCodeAt(j) > 127) {
4449 // we replace non-ASCII char with a temporary placeholder
4450 // we need this to make sure size of hostname is not
4451 // broken by replacing non-ASCII by nothing
4452 newpart += 'x';
4453 } else {
4454 newpart += part[j];
4455 }
4456 }
4457 // we test again with ASCII char only
4458 if (!newpart.match(hostnamePartPattern)) {
4459 var validParts = hostparts.slice(0, i);
4460 var notHost = hostparts.slice(i + 1);
4461 var bit = part.match(hostnamePartStart);
4462 if (bit) {
4463 validParts.push(bit[1]);
4464 notHost.unshift(bit[2]);
4465 }
4466 if (notHost.length) {
4467 rest = '/' + notHost.join('.') + rest;
4468 }
4469 this.hostname = validParts.join('.');
4470 break;
4471 }
4472 }
4473 }
4474 }
4475
4476 if (this.hostname.length > hostnameMaxLen) {
4477 this.hostname = '';
4478 } else {
4479 // hostnames are always lower case.
4480 this.hostname = this.hostname.toLowerCase();
4481 }
4482
4483 if (!ipv6Hostname) {
4484 // IDNA Support: Returns a punycoded representation of "domain".
4485 // It only converts parts of the domain name that
4486 // have non-ASCII characters, i.e. it doesn't matter if
4487 // you call it with a domain that already is ASCII-only.
4488 this.hostname = punycode.toASCII(this.hostname);
4489 }
4490
4491 var p = this.port ? ':' + this.port : '';
4492 var h = this.hostname || '';
4493 this.host = h + p;
4494 this.href += this.host;
4495
4496 // strip [ and ] from the hostname
4497 // the host field still retains them, though
4498 if (ipv6Hostname) {
4499 this.hostname = this.hostname.substr(1, this.hostname.length - 2);
4500 if (rest[0] !== '/') {
4501 rest = '/' + rest;
4502 }
4503 }
4504 }
4505
4506 // now rest is set to the post-host stuff.
4507 // chop off any delim chars.
4508 if (!unsafeProtocol[lowerProto]) {
4509
4510 // First, make 100% sure that any "autoEscape" chars get
4511 // escaped, even if encodeURIComponent doesn't think they
4512 // need to be.
4513 for (var i = 0, l = autoEscape.length; i < l; i++) {
4514 var ae = autoEscape[i];
4515 if (rest.indexOf(ae) === -1)
4516 continue;
4517 var esc = encodeURIComponent(ae);
4518 if (esc === ae) {
4519 esc = escape(ae);
4520 }
4521 rest = rest.split(ae).join(esc);
4522 }
4523 }
4524
4525
4526 // chop off from the tail first.
4527 var hash = rest.indexOf('#');
4528 if (hash !== -1) {
4529 // got a fragment string.
4530 this.hash = rest.substr(hash);
4531 rest = rest.slice(0, hash);
4532 }
4533 var qm = rest.indexOf('?');
4534 if (qm !== -1) {
4535 this.search = rest.substr(qm);
4536 this.query = rest.substr(qm + 1);
4537 if (parseQueryString) {
4538 this.query = querystring.parse(this.query);
4539 }
4540 rest = rest.slice(0, qm);
4541 } else if (parseQueryString) {
4542 // no query string, but parseQueryString still requested
4543 this.search = '';
4544 this.query = {};
4545 }
4546 if (rest) this.pathname = rest;
4547 if (slashedProtocol[lowerProto] &&
4548 this.hostname && !this.pathname) {
4549 this.pathname = '/';
4550 }
4551
4552 //to support http.request
4553 if (this.pathname || this.search) {
4554 var p = this.pathname || '';
4555 var s = this.search || '';
4556 this.path = p + s;
4557 }
4558
4559 // finally, reconstruct the href based on what has been validated.
4560 this.href = this.format();
4561 return this;
4562};
4563
4564// format a parsed object into a url string
4565function urlFormat(obj) {
4566 // ensure it's an object, and not a string url.
4567 // If it's an obj, this is a no-op.
4568 // this way, you can call url_format() on strings
4569 // to clean up potentially wonky urls.
4570 if (util.isString(obj)) obj = urlParse(obj);
4571 if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
4572 return obj.format();
4573}
4574
4575Url.prototype.format = function() {
4576 var auth = this.auth || '';
4577 if (auth) {
4578 auth = encodeURIComponent(auth);
4579 auth = auth.replace(/%3A/i, ':');
4580 auth += '@';
4581 }
4582
4583 var protocol = this.protocol || '',
4584 pathname = this.pathname || '',
4585 hash = this.hash || '',
4586 host = false,
4587 query = '';
4588
4589 if (this.host) {
4590 host = auth + this.host;
4591 } else if (this.hostname) {
4592 host = auth + (this.hostname.indexOf(':') === -1 ?
4593 this.hostname :
4594 '[' + this.hostname + ']');
4595 if (this.port) {
4596 host += ':' + this.port;
4597 }
4598 }
4599
4600 if (this.query &&
4601 util.isObject(this.query) &&
4602 Object.keys(this.query).length) {
4603 query = querystring.stringify(this.query);
4604 }
4605
4606 var search = this.search || (query && ('?' + query)) || '';
4607
4608 if (protocol && protocol.substr(-1) !== ':') protocol += ':';
4609
4610 // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
4611 // unless they had them to begin with.
4612 if (this.slashes ||
4613 (!protocol || slashedProtocol[protocol]) && host !== false) {
4614 host = '//' + (host || '');
4615 if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
4616 } else if (!host) {
4617 host = '';
4618 }
4619
4620 if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
4621 if (search && search.charAt(0) !== '?') search = '?' + search;
4622
4623 pathname = pathname.replace(/[?#]/g, function(match) {
4624 return encodeURIComponent(match);
4625 });
4626 search = search.replace('#', '%23');
4627
4628 return protocol + host + pathname + search + hash;
4629};
4630
4631function urlResolve(source, relative) {
4632 return urlParse(source, false, true).resolve(relative);
4633}
4634
4635Url.prototype.resolve = function(relative) {
4636 return this.resolveObject(urlParse(relative, false, true)).format();
4637};
4638
4639function urlResolveObject(source, relative) {
4640 if (!source) return relative;
4641 return urlParse(source, false, true).resolveObject(relative);
4642}
4643
4644Url.prototype.resolveObject = function(relative) {
4645 if (util.isString(relative)) {
4646 var rel = new Url();
4647 rel.parse(relative, false, true);
4648 relative = rel;
4649 }
4650
4651 var result = new Url();
4652 var tkeys = Object.keys(this);
4653 for (var tk = 0; tk < tkeys.length; tk++) {
4654 var tkey = tkeys[tk];
4655 result[tkey] = this[tkey];
4656 }
4657
4658 // hash is always overridden, no matter what.
4659 // even href="" will remove it.
4660 result.hash = relative.hash;
4661
4662 // if the relative url is empty, then there's nothing left to do here.
4663 if (relative.href === '') {
4664 result.href = result.format();
4665 return result;
4666 }
4667
4668 // hrefs like //foo/bar always cut to the protocol.
4669 if (relative.slashes && !relative.protocol) {
4670 // take everything except the protocol from relative
4671 var rkeys = Object.keys(relative);
4672 for (var rk = 0; rk < rkeys.length; rk++) {
4673 var rkey = rkeys[rk];
4674 if (rkey !== 'protocol')
4675 result[rkey] = relative[rkey];
4676 }
4677
4678 //urlParse appends trailing / to urls like http://www.example.com
4679 if (slashedProtocol[result.protocol] &&
4680 result.hostname && !result.pathname) {
4681 result.path = result.pathname = '/';
4682 }
4683
4684 result.href = result.format();
4685 return result;
4686 }
4687
4688 if (relative.protocol && relative.protocol !== result.protocol) {
4689 // if it's a known url protocol, then changing
4690 // the protocol does weird things
4691 // first, if it's not file:, then we MUST have a host,
4692 // and if there was a path
4693 // to begin with, then we MUST have a path.
4694 // if it is file:, then the host is dropped,
4695 // because that's known to be hostless.
4696 // anything else is assumed to be absolute.
4697 if (!slashedProtocol[relative.protocol]) {
4698 var keys = Object.keys(relative);
4699 for (var v = 0; v < keys.length; v++) {
4700 var k = keys[v];
4701 result[k] = relative[k];
4702 }
4703 result.href = result.format();
4704 return result;
4705 }
4706
4707 result.protocol = relative.protocol;
4708 if (!relative.host && !hostlessProtocol[relative.protocol]) {
4709 var relPath = (relative.pathname || '').split('/');
4710 while (relPath.length && !(relative.host = relPath.shift()));
4711 if (!relative.host) relative.host = '';
4712 if (!relative.hostname) relative.hostname = '';
4713 if (relPath[0] !== '') relPath.unshift('');
4714 if (relPath.length < 2) relPath.unshift('');
4715 result.pathname = relPath.join('/');
4716 } else {
4717 result.pathname = relative.pathname;
4718 }
4719 result.search = relative.search;
4720 result.query = relative.query;
4721 result.host = relative.host || '';
4722 result.auth = relative.auth;
4723 result.hostname = relative.hostname || relative.host;
4724 result.port = relative.port;
4725 // to support http.request
4726 if (result.pathname || result.search) {
4727 var p = result.pathname || '';
4728 var s = result.search || '';
4729 result.path = p + s;
4730 }
4731 result.slashes = result.slashes || relative.slashes;
4732 result.href = result.format();
4733 return result;
4734 }
4735
4736 var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
4737 isRelAbs = (
4738 relative.host ||
4739 relative.pathname && relative.pathname.charAt(0) === '/'
4740 ),
4741 mustEndAbs = (isRelAbs || isSourceAbs ||
4742 (result.host && relative.pathname)),
4743 removeAllDots = mustEndAbs,
4744 srcPath = result.pathname && result.pathname.split('/') || [],
4745 relPath = relative.pathname && relative.pathname.split('/') || [],
4746 psychotic = result.protocol && !slashedProtocol[result.protocol];
4747
4748 // if the url is a non-slashed url, then relative
4749 // links like ../.. should be able
4750 // to crawl up to the hostname, as well. This is strange.
4751 // result.protocol has already been set by now.
4752 // Later on, put the first path part into the host field.
4753 if (psychotic) {
4754 result.hostname = '';
4755 result.port = null;
4756 if (result.host) {
4757 if (srcPath[0] === '') srcPath[0] = result.host;
4758 else srcPath.unshift(result.host);
4759 }
4760 result.host = '';
4761 if (relative.protocol) {
4762 relative.hostname = null;
4763 relative.port = null;
4764 if (relative.host) {
4765 if (relPath[0] === '') relPath[0] = relative.host;
4766 else relPath.unshift(relative.host);
4767 }
4768 relative.host = null;
4769 }
4770 mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
4771 }
4772
4773 if (isRelAbs) {
4774 // it's absolute.
4775 result.host = (relative.host || relative.host === '') ?
4776 relative.host : result.host;
4777 result.hostname = (relative.hostname || relative.hostname === '') ?
4778 relative.hostname : result.hostname;
4779 result.search = relative.search;
4780 result.query = relative.query;
4781 srcPath = relPath;
4782 // fall through to the dot-handling below.
4783 } else if (relPath.length) {
4784 // it's relative
4785 // throw away the existing file, and take the new path instead.
4786 if (!srcPath) srcPath = [];
4787 srcPath.pop();
4788 srcPath = srcPath.concat(relPath);
4789 result.search = relative.search;
4790 result.query = relative.query;
4791 } else if (!util.isNullOrUndefined(relative.search)) {
4792 // just pull out the search.
4793 // like href='?foo'.
4794 // Put this after the other two cases because it simplifies the booleans
4795 if (psychotic) {
4796 result.hostname = result.host = srcPath.shift();
4797 //occationaly the auth can get stuck only in host
4798 //this especially happens in cases like
4799 //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
4800 var authInHost = result.host && result.host.indexOf('@') > 0 ?
4801 result.host.split('@') : false;
4802 if (authInHost) {
4803 result.auth = authInHost.shift();
4804 result.host = result.hostname = authInHost.shift();
4805 }
4806 }
4807 result.search = relative.search;
4808 result.query = relative.query;
4809 //to support http.request
4810 if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
4811 result.path = (result.pathname ? result.pathname : '') +
4812 (result.search ? result.search : '');
4813 }
4814 result.href = result.format();
4815 return result;
4816 }
4817
4818 if (!srcPath.length) {
4819 // no path at all. easy.
4820 // we've already handled the other stuff above.
4821 result.pathname = null;
4822 //to support http.request
4823 if (result.search) {
4824 result.path = '/' + result.search;
4825 } else {
4826 result.path = null;
4827 }
4828 result.href = result.format();
4829 return result;
4830 }
4831
4832 // if a url ENDs in . or .., then it must get a trailing slash.
4833 // however, if it ends in anything else non-slashy,
4834 // then it must NOT get a trailing slash.
4835 var last = srcPath.slice(-1)[0];
4836 var hasTrailingSlash = (
4837 (result.host || relative.host || srcPath.length > 1) &&
4838 (last === '.' || last === '..') || last === '');
4839
4840 // strip single dots, resolve double dots to parent dir
4841 // if the path tries to go above the root, `up` ends up > 0
4842 var up = 0;
4843 for (var i = srcPath.length; i >= 0; i--) {
4844 last = srcPath[i];
4845 if (last === '.') {
4846 srcPath.splice(i, 1);
4847 } else if (last === '..') {
4848 srcPath.splice(i, 1);
4849 up++;
4850 } else if (up) {
4851 srcPath.splice(i, 1);
4852 up--;
4853 }
4854 }
4855
4856 // if the path is allowed to go above the root, restore leading ..s
4857 if (!mustEndAbs && !removeAllDots) {
4858 for (; up--; up) {
4859 srcPath.unshift('..');
4860 }
4861 }
4862
4863 if (mustEndAbs && srcPath[0] !== '' &&
4864 (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
4865 srcPath.unshift('');
4866 }
4867
4868 if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
4869 srcPath.push('');
4870 }
4871
4872 var isAbsolute = srcPath[0] === '' ||
4873 (srcPath[0] && srcPath[0].charAt(0) === '/');
4874
4875 // put the host back
4876 if (psychotic) {
4877 result.hostname = result.host = isAbsolute ? '' :
4878 srcPath.length ? srcPath.shift() : '';
4879 //occationaly the auth can get stuck only in host
4880 //this especially happens in cases like
4881 //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
4882 var authInHost = result.host && result.host.indexOf('@') > 0 ?
4883 result.host.split('@') : false;
4884 if (authInHost) {
4885 result.auth = authInHost.shift();
4886 result.host = result.hostname = authInHost.shift();
4887 }
4888 }
4889
4890 mustEndAbs = mustEndAbs || (result.host && srcPath.length);
4891
4892 if (mustEndAbs && !isAbsolute) {
4893 srcPath.unshift('');
4894 }
4895
4896 if (!srcPath.length) {
4897 result.pathname = null;
4898 result.path = null;
4899 } else {
4900 result.pathname = srcPath.join('/');
4901 }
4902
4903 //to support request.http
4904 if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
4905 result.path = (result.pathname ? result.pathname : '') +
4906 (result.search ? result.search : '');
4907 }
4908 result.auth = relative.auth || result.auth;
4909 result.slashes = result.slashes || relative.slashes;
4910 result.href = result.format();
4911 return result;
4912};
4913
4914Url.prototype.parseHost = function() {
4915 var host = this.host;
4916 var port = portPattern.exec(host);
4917 if (port) {
4918 port = port[0];
4919 if (port !== ':') {
4920 this.port = port.substr(1);
4921 }
4922 host = host.substr(0, host.length - port.length);
4923 }
4924 if (host) this.hostname = host;
4925};
4926
4927},{"./util":44,"punycode":39,"querystring":42}],44:[function(require,module,exports){
4928'use strict';
4929
4930module.exports = {
4931 isString: function(arg) {
4932 return typeof(arg) === 'string';
4933 },
4934 isObject: function(arg) {
4935 return typeof(arg) === 'object' && arg !== null;
4936 },
4937 isNull: function(arg) {
4938 return arg === null;
4939 },
4940 isNullOrUndefined: function(arg) {
4941 return arg == null;
4942 }
4943};
4944
4945},{}]},{},[1]);